Compare commits

..
1 Commits
Author SHA1 Message Date
Lago 9faba3f107 Add Repo Forker mirror config 2026-10-19 23:06:40 +02:00
632 changed files with 18 additions and 353442 deletions

No files matched your search

-7
View File
@@ -1,7 +0,0 @@
# The image is normally built from `git archive` (docker/build.sh), which carries none of these;
# this keeps a `docker build .` from a working tree just as clean.
build*
.git
.claude
**/*.rad
compile_commands.json
+18
View File
@@ -0,0 +1,18 @@
# .forker.yaml — per-mirror configuration for Repo Forker.
#
# The upstream URL, its token, and the Gitea REMOTE/TOKEN are NOT set
# here: they live in the container (environment or the UI's mirror
# registry). Everything below is non-secret per-mirror behavior.
#
# Flat `key: value` only (the parser is a grep) — no nesting.
enabled: true
mirror_tags: true
mirror_prune: true
mirror_branches: "*"
on_new_tag: true
mirror_upstream_releases: true
sync_interval: 0
build_cmd: ""
build_script: ""
artifacts: ""
-7
View File
@@ -1,7 +0,0 @@
/build*/
compile_commands.json
*.o
*.so
*.rad
/sync-jarvis.sh
__pycache__/
-448
View File
@@ -1,448 +0,0 @@
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.0.13 LANGUAGES C CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_C_STANDARD 11)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
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.
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 and video parts with libavformat/libavcodec/libswscale")
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)
# ---------------------------------------------------------------- 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.
#
# 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.
#
# 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.
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)
if(RAD_HIPCC)
execute_process(COMMAND ${RAD_HIPCC} --version OUTPUT_VARIABLE RAD_HIPCC_VER ERROR_QUIET)
set(RAD_HIP_FOUND ON)
elseif(RAD_WITH_HIP STREQUAL "ON")
message(FATAL_ERROR "RAD_WITH_HIP=ON but hipcc was not found.")
endif()
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.
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)
execute_process(COMMAND ${RAD_ARCH_TOOL} OUTPUT_VARIABLE RAD_ARCH_OUT
RESULT_VARIABLE RAD_ARCH_RC ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE)
if(RAD_ARCH_RC EQUAL 0)
string(REPLACE "\n" ";" RAD_ARCH_OUT "${RAD_ARCH_OUT}")
list(FILTER RAD_ARCH_OUT INCLUDE REGEX "^gfx")
list(REMOVE_DUPLICATES RAD_ARCH_OUT)
set(RAD_GPU_TARGETS ${RAD_ARCH_OUT})
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.
set(RAD_HIP_FOUND OFF)
message(WARNING
"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()
endif()
if(RAD_HIP_FOUND)
message(STATUS "radiance: HIP backend ON, targets ${RAD_GPU_TARGETS}")
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 \.")
endif()
# HOST CODE ONLY, AND THAT IS NOT A COMPROMISE -- IT IS THE WHOLE AVAILABLE SURFACE.
#
# 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.
if(RAD_ASAN)
add_compile_options($<$<COMPILE_LANGUAGE:CXX>:-fsanitize=address,undefined>
$<$<COMPILE_LANGUAGE:CXX>:-fno-omit-frame-pointer>
$<$<COMPILE_LANGUAGE:CXX>:-fno-sanitize-recover=all>)
add_link_options(-fsanitize=address,undefined)
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.
include(GNUInstallDirs)
# ---------------------------------------------------------------- the ABI
# Header-only. 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.
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 <prefix>/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.
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.
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/abi>
$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}/radiance>)
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.
#
# 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.
#
# 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).
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")
set(RAD_ROCM_INCLUDE "${RAD_ROCM_ROOT}/include")
elseif(EXISTS "/opt/rocm/include/hip/hip_runtime.h")
set(RAD_ROCM_INCLUDE "/opt/rocm/include")
endif()
if(RAD_ROCM_INCLUDE)
target_include_directories(rad_abi SYSTEM INTERFACE $<BUILD_INTERFACE:${RAD_ROCM_INCLUDE}>)
else()
message(FATAL_ERROR
"hipcc is at ${RAD_HIPCC} but hip/hip_runtime.h is not under ${RAD_ROCM_ROOT}/include "
"or /opt/rocm/include. Set ROCM_PATH.")
endif()
target_compile_definitions(rad_abi INTERFACE __HIP_PLATFORM_AMD__=1)
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
#
# rad-kbench -m <model.rad> --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)
install(FILES ${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
#
# rad-kbench -m <model.rad> --max-cases 1 --record data/kernels_moe.rkb
#
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/data/kernels_moe.rkb)
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/data/kernels_moe.rkb
${RAD_PLUGIN_OUT}/kernels_moe.rkb COPYONLY)
install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/data/kernels_moe.rkb
DESTINATION ${CMAKE_INSTALL_DATADIR}/radiance)
endif()
# 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.
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.
enable_language(HIP)
# 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.
#
# `CMAKE_DEPFILE_FLAGS_<LANG>` 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 <DEP_TARGET> -MF <DEP_FILE>")
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_<LANG>`
# 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_<CONFIG>` 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_<CONFIG>. 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.
foreach(cfg DEBUG RELEASE RELWITHDEBINFO MINSIZEREL)
if(cfg STREQUAL "DEBUG")
set(lvl "-O0 -g")
elseif(cfg STREQUAL "MINSIZEREL")
set(lvl "-Os -DNDEBUG")
else()
set(lvl "-O3 -DNDEBUG")
endif()
if(RAD_HIP_FLAGS_${cfg})
set(lvl "${RAD_HIP_FLAGS_${cfg}}")
message(STATUS "radiance: HIP ${cfg} flags overridden by RAD_HIP_FLAGS_${cfg}: '${lvl}'")
endif()
set(CMAKE_HIP_FLAGS_${cfg} "${lvl}" CACHE STRING "HIP flags for ${cfg}" FORCE)
endforeach()
message(STATUS "radiance: HIP ${CMAKE_BUILD_TYPE} flags '${CMAKE_HIP_FLAGS_${RAD_CFG_UPPER}}'")
find_library(RAD_HIP_RUNTIME amdhip64 HINTS /opt/rocm/lib ENV ROCM_PATH)
# The AQL backend writes packets into HSA queues itself (core/device/aql.cpp).
find_library(RAD_HSA_RUNTIME hsa-runtime64 HINTS /opt/rocm/lib ENV ROCM_PATH)
endif()
find_package(Threads REQUIRED)
# ---------------------------------------------------------------- media decoding
# An image or video part of a chat request is decoded by libavformat/libavcodec and converted by
# libswscale (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.
set(RAD_FFMPEG_FOUND OFF)
if(NOT RAD_WITH_FFMPEG STREQUAL "OFF")
find_package(PkgConfig QUIET)
if(PkgConfig_FOUND)
pkg_check_modules(RAD_FFMPEG QUIET IMPORTED_TARGET libavformat libavcodec libavutil libswscale)
endif()
if(RAD_FFMPEG_FOUND)
message(STATUS "radiance: media decoding via libavformat ${RAD_FFMPEG_libavformat_VERSION}")
elseif(RAD_WITH_FFMPEG STREQUAL "ON")
message(FATAL_ERROR "RAD_WITH_FFMPEG=ON but libavformat/libavcodec/libavutil/libswscale were not found.")
else()
message(STATUS "radiance: no libavformat -- image and video input will be refused")
endif()
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.
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.
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.
if(CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64|amd64)$")
add_subdirectory(libavx)
endif()
add_subdirectory(arch)
add_subdirectory(tools)
if(RAD_BUILD_TESTS)
enable_testing()
add_subdirectory(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.
#
# (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.
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.
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.
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.")
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.
set(RAD_HOME_RELDIR "${CMAKE_INSTALL_DATADIR}/radiance")
set(RAD_INCLUDE_RELDIR "${CMAKE_INSTALL_INCLUDEDIR}/radiance")
configure_package_config_file(
${CMAKE_CURRENT_SOURCE_DIR}/cmake/radiance-config.cmake.in
${CMAKE_CURRENT_BINARY_DIR}/radiance-config.cmake
INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/radiance
PATH_VARS RAD_INCLUDE_RELDIR RAD_HOME_RELDIR)
write_basic_package_version_file(
${CMAKE_CURRENT_BINARY_DIR}/radiance-config-version.cmake
VERSION ${RAD_ABI_VERSION}.0.0
COMPATIBILITY SameMajorVersion)
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.
${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.
install(FILES LICENSE NOTICE DESTINATION ${CMAKE_INSTALL_DOCDIR})
install(FILES vendor/llama/LICENSE
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME llama.cpp.LICENSE)
install(FILES vendor/nlohmann/LICENSE.MIT
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME nlohmann-json.LICENSE)
install(FILES vendor/cpp-httplib/LICENSE
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME cpp-httplib.LICENSE)
-190
View File
@@ -1,190 +0,0 @@
# 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.
#
# 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; the distribution's build brings ~200 packages of encoders, filters and
# display libraries the engine never calls
# build ROCm dev image + cmake/ninja/g++-14; configures, builds, installs to /stage
# test `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
#
# Device code is NOT built with --offload-compress: the engine's 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:
# 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.
ARG ROCM_VERSION=7.2.4
ARG UBUNTU_VERSION=24.04
ARG FFMPEG_VERSION=8.1.3
ARG FFMPEG_SHA256=7138d28c96d9d3e3af4ee3d8cad72741f8ffb40da90c1112235dea3ecd3178a3
# ----------------------------------------------------------------------------------------- ffmpeg
FROM ubuntu:${UBUNTU_VERSION} AS ffmpeg
ARG FFMPEG_VERSION
ARG FFMPEG_SHA256
ARG JOBS=
RUN apt-get update \
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
build-essential nasm pkg-config ca-certificates curl xz-utils zlib1g-dev libdav1d-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. 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 - \
&& tar -xJf ffmpeg.tar.xz && cd "ffmpeg-${FFMPEG_VERSION}" \
&& ./configure --prefix=/opt/ffmpeg --enable-shared --disable-static --disable-debug \
--disable-programs --disable-doc --disable-network --disable-autodetect --disable-everything \
--disable-avdevice --disable-avfilter --disable-swresample \
--enable-zlib --enable-libdav1d \
--enable-demuxer=mov,matroska,avi,mpegts,flv,ogg,gif,apng,image2pipe,image_png_pipe,image_jpeg_pipe,image_jpegls_pipe,image_jpegxl_pipe,image_webp_pipe,image_bmp_pipe,image_tiff_pipe,image_qoi_pipe,image_pgm_pipe,image_ppm_pipe,image_pbm_pipe,image_pam_pipe,image_gif_pipe \
--enable-decoder=h264,hevc,vp8,vp9,libdav1d,mpeg4,mpeg1video,mpeg2video,mjpeg,jpegls,png,apng,gif,webp,bmp,tiff,qoi,pgm,ppm,pbm,pam,pgmyuv,theora,vp3,flv,h263 \
--enable-parser=h264,hevc,vp8,vp9,av1,mpeg4video,mpegvideo,mjpeg,png,gif,bmp,webp,vp3,qoi,pnm,h263,jpegxl \
&& make -j"${JOBS:-$(nproc)}" \
&& make install \
&& mkdir -p /opt/ffmpeg/share/doc/ffmpeg \
&& cp LICENSE.md COPYING.LGPLv2.1 /opt/ffmpeg/share/doc/ffmpeg/ \
&& sed -n 's/^#define FFMPEG_CONFIGURATION "\(.*\)"$/\1/p' config.h \
> /opt/ffmpeg/share/doc/ffmpeg/CONFIGURATION \
&& echo "https://ffmpeg.org/releases/ffmpeg-${FFMPEG_VERSION}.tar.xz, sha256 ${FFMPEG_SHA256}" \
> /opt/ffmpeg/share/doc/ffmpeg/SOURCE
# ------------------------------------------------------------------------------------------ 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.
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 is the runtime half of the AV1 decoder the ffmpeg stage linked; 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 busybox-static \
&& rm -rf /var/lib/apt/lists/*
COPY --from=ffmpeg /opt/ffmpeg /opt/ffmpeg
RUN echo /opt/ffmpeg/lib > /etc/ld.so.conf.d/ffmpeg.conf && ldconfig
ENV ROCM_PATH=/opt/rocm HIP_PATH=/opt/rocm CC=gcc-14 CXX=g++-14 \
PKG_CONFIG_PATH=/opt/ffmpeg/lib/pkgconfig
WORKDIR /src
COPY . .
# The install prefix is fixed at configure time because the default $RADIANCE_HOME is compiled in
# as <prefix>/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.
RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
cmake -S . -B /build -G Ninja \
-DCMAKE_INSTALL_PREFIX=/opt/radiance \
-DRAD_WITH_HIP=ON -DRAD_WITH_FFMPEG=ON \
"-DRAD_GPU_TARGETS=${GPU_TARGETS}" \
&& cmake --build /build ${JOBS:+-j${JOBS}} \
&& DESTDIR=/stage cmake --install /build \
&& mkdir -p /stage/opt/radiance/share/radiance/recipes \
&& cp data/recipes/*.recipe /stage/opt/radiance/share/radiance/recipes/
# ------------------------------------------------------------------------------------------- test
FROM build AS test
# Host-only: a build container has no /dev/kfd. The `gpu`-labelled suites (mem_test,
# 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.
RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
ctest --test-dir /build -LE 'gpu|oot' --output-on-failure \
&& touch /build/host-tests-passed
# ----------------------------------------------------------------------------------------- rootfs
FROM build AS rootfs
# 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. libdrm_amdgpu names the card from amdgpu.ids. A
# static busybox provides the health check's wget and a shell for `docker exec`. 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.
RUN set -e; R=/rootfs; L=$R/usr/lib/x86_64-linux-gnu; \
mkdir -p $L $R/lib64 $R/usr/bin $R/bin $R/usr/share/libdrm $R/data $R/tmp; \
chmod 1777 $R/tmp; \
cp -a /stage/opt/radiance $R/opt/; \
elves=$(find $R/opt/radiance -type f -exec sh -c 'head -c4 "$1" | grep -q ELF' _ {} \; -print); \
strip --strip-unneeded $elves; \
libs=$(for f in $elves /opt/rocm/lib/libamd_comgr.so.3; do ldd "$f"; done \
| awk '/=> \//{print $3} /^\t\/lib64\//{print $1}' | sort -u); \
for lib in $libs; do \
case "$lib" in */ld-linux-x86-64.so.2) cp -L "$lib" $R/lib64/ ;; *) cp -L "$lib" $L/ ;; esac; \
done; \
cp -L /opt/rocm/lib/libamd_comgr.so.3 $L/; \
cp /usr/share/libdrm/amdgpu.ids $R/usr/share/libdrm/; \
cp /bin/busybox $R/usr/bin/busybox; ln -s /usr/bin/busybox $R/bin/sh; \
sh /src/docker/licenses.sh $R $libs /opt/rocm/lib/libamd_comgr.so.3 \
/usr/share/libdrm/amdgpu.ids /bin/busybox; \
for f in $(cd $R && find opt/radiance usr/lib -type f -exec sh -c 'head -c4 "$1" | grep -q ELF' _ {} \; -print); do \
out=$(chroot $R /lib64/ld-linux-x86-64.so.2 --list "/$f" 2>&1) || { echo "$f: $out" >&2; exit 1; }; \
if echo "$out" | grep -q 'not found'; then echo "$f: $out" >&2; exit 1; fi; \
done; \
chroot $R /opt/radiance/bin/radiance --help > /dev/null; \
du -sh $R $L $R/opt/radiance
# ---------------------------------------------------------------------------------------- runtime
FROM scratch AS runtime
ARG GPU_TARGETS=gfx1201
ARG VERSION=dev
ARG REVISION=unknown
LABEL org.opencontainers.image.title="radiance" \
org.opencontainers.image.description="LLM inference engine for AMD GPUs" \
org.opencontainers.image.version="${VERSION}" \
org.opencontainers.image.revision="${REVISION}" \
org.opencontainers.image.licenses="Apache-2.0" \
radiance.gpu-targets="${GPU_TARGETS}"
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.
ENV PATH=/opt/radiance/bin:/usr/bin:/bin \
GPU_MAX_ALLOC_PERCENT=100 \
GPU_MAX_HEAP_SIZE=100
WORKDIR /data
EXPOSE 8000
ENTRYPOINT ["radiance"]
CMD ["--help"]
-202
View File
@@ -1,202 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-20
View File
@@ -1,20 +0,0 @@
radiance
Copyright 2026 Deadcode and the radiance contributors
Written by Deadcode, with contributions from tcclaviger (the N-rank all-reduce kernels), ggz14
(the MXFP4 GEMM and the GDN kernels' overflow guards), 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 and the Grafana dashboard),
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) and baKon (three-rank tensor parallelism and the request
log).
This product includes software from the following projects, each under the MIT License. The
license text is in the file named beside each.
llama.cpp Copyright (c) 2023-2026 The ggml authors vendor/llama/LICENSE
vendor/llama/, and the code lifted or ported from it: core/sample/gbnf.*, the
host samplers in core/sample/host_ref.*, the tokenisers in core/text/, and
libquant/lq_ggml_*
nlohmann/json Copyright (c) 2013-2025 Niels Lohmann vendor/nlohmann/LICENSE.MIT
cpp-httplib Copyright (c) 2017 yhirose vendor/cpp-httplib/LICENSE
-169
View File
@@ -1,169 +0,0 @@
# radiance
An LLM inference server for AMD GPUs, in C++ and HIP, with an OpenAI-compatible HTTP API. 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.
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)
## Models
| model | container | get it | compose file |
|---|---|---|---|
| Qwen3.8-Flash-Next: 4-bit experts, int8 trunk, MTP, vision | `qwen3.8-next-flash-fp8-iq4r-moe.rad` (114 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-next-flash-fp8-iq4r-moe) | `flashnext.yaml` |
| Qwen3.8-27B FP8, DFlash2 drafter, vision | `qwen3.8-27b-fp8.rad` (29 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-27b-fp8) | `qwen3.8-27b-fp8.yaml` |
| Qwen3.6-35B-A3B FP8, MTP | `qwen3.6-35b-a3b-fp8.rad` (35 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.6-35b-a3b-fp8) | `qwen3.6-35b-a3b.yaml` |
| MiniCPM5-2B FP8, DSpark drafter | `minicpm5-2b-fp8.rad` (3 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-fp8) | `minicpm5-2b.yaml` |
| MiniCPM5-2B bf16, DSpark drafter | `minicpm5-2b-bf16.rad` (5 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-bf16) | `minicpm5-2b-bf16.yaml` |
| 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` |
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
file. Download one into your models directory (the transfer resumes if interrupted):
```sh
mkdir -p /srv/models/rad && cd /srv/models/rad
curl -LC - -O https://huggingface.co/StillDeadcode/minicpm5-2b-fp8/resolve/main/minicpm5-2b-fp8.rad
```
## Run with Docker
The host needs Docker and an `amdgpu` driver that supports ROCm 7.2; it does not need ROCm. 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
git clone https://codeberg.org/StillDeadcode/radiance.git
cp -r radiance/deploy/compose ~/radiance-compose && cd ~/radiance-compose
cp .env.example .env # set RADIANCE_MODELS, RADIANCE_STATE, RADIANCE_API_KEY, the GIDs
docker compose -f minicpm5-2b.yaml up -d # or any file from the table
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).
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
`RADIANCE_IMAGE=radiance:latest` in `.env`.
## Build from source
You need Linux, git, a C++20 compiler, CMake 3.21+ and Ninja. For the device kernels you also need
ROCm 7.2 (`hipcc`; set `ROCM_PATH` if it is not `/opt/rocm`). Clone the repository and 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 --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/
```
## Run without Docker
```sh
export RADIANCE_HOME=$PWD/build/radiance_home # the plugins; an installed prefix finds its own
build/bin/radiance --model /srv/models/rad/minicpm5-2b-fp8.rad --port 8000 <flags>
```
These are the flags each model is served with. They match its compose file, minus Flash-Next's
prefix-cache tiers:
| 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 --expert-vs-cache-ratio 0.82 --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 --expert-vs-cache-ratio 0.82 --kv-cache-dtype fp8 --num-speculative-tokens 3 --max-num-batched-tokens 2048` |
| Qwen3.8-Flash-Next, three ranks (the checkpoint padded first, [`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 --expert-vs-cache-ratio 0.82 --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 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` |
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 leave the attention cache short of one
200K-token request: Flash-Next at ratio 0.82 (`--max-num-seqs 32 --expert-vs-cache-ratio 0.78`
keeps the 200K request and costs single-stream decode about 15%) and the 27B in bf16. 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 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 `--expert-vs-cache-ratio` and
`--host-pool-mib` before trusting them. **`--host-pool-mib` is pinned on every card**, so the row
above pins 4 × 12 GiB = 48 GiB, and the amdgpu driver caps pinned memory at `ttm.pages_limit`, half
of RAM by default: that row needs 96 GiB of RAM or a raised limit
([`docs/GUIDE.md`](docs/GUIDE.md) §7).
Add `--api-key KEY` to require `Authorization: Bearer KEY`. Add `--debug-graph` to print every op
and the kernel it resolved to, then exit without serving. 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}'
```
`http://localhost:8000/` is the dashboard. [`docs/GUIDE.md`](docs/GUIDE.md) covers the API, memory
budgets, long context, speculative decoding and operating a server.
## Convert a checkpoint
`rad-convert` turns a Hugging Face checkpoint into a container, quantising what a recipe in
`data/recipes/` names. Download checkpoints with `scripts/hfget.sh <org/repo> <dir>`.
```sh
build/bin/rad-convert ~/models/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
```
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`.
## 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
```
## Documentation
| | |
|---|---|
| [`docs/GUIDE.md`](docs/GUIDE.md) | installing, converting, serving, the HTTP API, operating a server |
| [`docs/TOOLS.md`](docs/TOOLS.md) | every flag of every tool, and the recipe syntax |
| [`docs/DOCKER.md`](docs/DOCKER.md) | the image and the compose files |
| [`docs/PLUGIN.md`](docs/PLUGIN.md) | writing a kernel library, architecture or quantiser plugin, including one for another AMD card |
| [`docs/ARCHITECTURES.md`](docs/ARCHITECTURES.md) | the supported model families and their geometry |
| [`docs/TP3.md`](docs/TP3.md) | padding a checkpoint, exactly, to a world its head counts do not divide; three ranks |
| [`docs/OPS.md`](docs/OPS.md), [`docs/KERNELS.md`](docs/KERNELS.md) | the op vocabulary, and what `rad-kbench` last measured |
| [`spec.md`](spec.md) | the design |
## License
[Apache-2.0](LICENSE), copyright Deadcode and the radiance contributors. Keep [`NOTICE`](NOTICE)
with any copy or derivative. It credits the authors and lists the MIT-licensed code the tree
includes. The model weights are not covered: each keeps the license of the model it was converted
from. The Docker image also holds third-party libraries under their own licenses, GPL and LGPL
among them; `/usr/share/doc/THIRD-PARTY` in the image lists each one with its version and source.
-616
View File
@@ -1,616 +0,0 @@
/* 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.
*/
#ifndef RAD_ABI_H
#define RAD_ABI_H
#include "rad_types.h"
#include "rad_encoding.h"
#ifdef __cplusplus
extern "C" {
#endif
/* 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 15u
/* ================================================================== plugin identity */
/* 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 */
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. */
const char* build_target;
} RadPluginInfo;
/* Every plugin exports these two. */
uint32_t rad_plugin_abi_version(void);
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. */
enum { RAD_DOMAIN_DEVICE = 0, RAD_DOMAIN_HOST = 1, RAD_N_DOMAINS = 2 };
/* ================================================================== kernel arguments */
typedef struct RadArgs {
const RadTensor* t; /* operands, positional, in the op schema's order */
int n_t;
const RadParam* p; /* the resolved geometry: every param, ranges collapsed */
int n_p;
void* scratch; /* device (or host) scratch, >= the scratch hook's answer */
int64_t scratch_bytes;
void* instance; /* whatever init() returned for this resolved instance */
int rank; /* tensor-parallel rank and world size, for collectives */
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. */
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)
if (a->p[i].kind == RAD_P_INT && strcmp(a->p[i].key, key) == 0) {
if (out) *out = a->p[i].ival;
return 1;
}
return 0;
}
/* Null if absent. */
static inline const char* rad_args_gets(const RadArgs* a, const char* key) {
if (!a || !key) return 0;
for (int i = 0; i < a->n_p; ++i)
if (a->p[i].kind == RAD_P_STR && strcmp(a->p[i].key, key) == 0) return a->p[i].sval;
return 0;
}
/* ================================================================== 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 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. */
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. */
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.
*
* 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. */
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 align; /* byte alignment the stored base must satisfy */
int64_t bytes; /* total, including any padding the layout implies */
} 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`.
*
* 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. */
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. */
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
* 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. */
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.
*
* 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.
*
* 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. */
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. */
RAD_FILL_UNIT_ROW = 5,
};
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. */
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. */
RAD_OPD_F_IDX_UNIQUE = 1u << 1,
/* CUMULATIVE SEQUENCE LENGTHS, [0, ..., T]. Not a draw: it is the batch's shape. */
RAD_OPD_F_IDX_CU = 1u << 2,
};
typedef struct RadOpdDesc {
uint32_t dtype;
uint32_t rank;
int64_t shape[RAD_MAX_RANK];
uint32_t fill; /* RAD_FILL_* */
int64_t fill_chunk; /* the reset width for GATE_CUMSUM and TRI_LOWER */
/* 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. */
int64_t idx_max;
int64_t idx_const; /* -1 to draw */
uint32_t flags; /* RAD_OPD_F_* */
} 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.
*
* 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.
*
* 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. */
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. */
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.
*
* `p` is the resolved geometry, `choice` the candidate as key/value parameters. Pure host code,
* called before anything is allocated, once per candidate.
*
* 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. */
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).
*
* 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.
*
* 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. */
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. */
enum { RAD_PROLE_NONE = 0, RAD_PROLE_SEQ_CHUNK = 1, RAD_PROLE_CAPACITY = 2 };
typedef struct RadParamSpec {
const char* key;
int type; /* RAD_P_INT | RAD_P_STR */
int required;
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. */
enum { RAD_OPD_IN = 0, RAD_OPD_OUT = 1, RAD_OPD_INOUT = 2, RAD_OPD_WEIGHT = 3,
RAD_OPD_WTAB = 4 };
typedef struct RadOperandSpec {
const char* name; /* for diagnostics: "x", "w_gate", "out" */
int role;
int optional; /* an absent optional operand is a null RadTensor.data */
} RadOperandSpec;
typedef struct RadOpSchema {
const char* op;
const RadParamSpec* params; int n_params;
const RadOperandSpec* operands; int n_operands;
const char* doc;
} RadOpSchema;
/* ================================================================== declared fusions
*
* WHAT CHAIN OF CONVENTIONAL OPS DOES THIS KERNEL COMPUTE?
*
* 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.
* "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.
*
* 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:
*
* 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.
*
* 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. */
enum {
RAD_FUSE_NONE = -1, /* this step does not pass that optional operand */
};
/* Temporary `t`, for t in [0, RAD_MAX_FUSE_TMP). Encoded so that a non-negative value is always an
* operand of the fused kernel and needs no tagging. */
#define RAD_FUSE_TMP(t) ((int16_t)(-2 - (t)))
#define RAD_FUSE_IS_TMP(v) ((v) <= -2)
#define RAD_FUSE_TMP_INDEX(v) ((int)(-2 - (v)))
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 */
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. */
int16_t from[RAD_MAX_FUSE_OPD];
int n_from;
} 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.
*
* 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.
*
* 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. */
#define RAD_FUSE_PRESENT_ALL ((uint64_t)~0ull)
#define RAD_FUSE_HAS(mask, i) (((mask) >> (i)) & 1ull)
typedef int (*RadFuseFn)(const RadParam* p, int n_p, uint64_t present, int step,
RadFuseStep* out);
/* ================================================================== kernel rows */
typedef struct RadKernelInfo {
const char* name; /* entry point, unique within the plugin */
const char* op; /* the op it implements -- the key callers select on */
const char* family; /* attn | gdn | ar | gemm | norm | sample | ... , for grouping only */
const char* computes; /* prose, for a human */
const char* shape; /* the geometry it is compiled for, prose */
const char* dtypes;
int domain; /* RAD_DOMAIN_DEVICE | RAD_DOMAIN_HOST */
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. */
const RadTunable* tunables; int n_tunables;
RadTuneValidFn tune_valid;
RadInitFn init;
RadFiniFn fini;
RadLaunchFn launch;
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. */
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. */
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.
*
* 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;
} 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). */
int rad_kernel_schema_count(void);
const RadOpSchema* rad_kernel_schema_at(int i);
int rad_kernel_count(void);
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.
*
* `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. */
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`. */
typedef int (*RadKernelConcurrentFn)(int i);
/* 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:
* - 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);
* - the engine refuses to serve a model with an op only a reference library implements, unless
* told to with --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`. */
typedef int (*RadPluginReferenceFn)(void);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* RAD_ABI_H */
-690
View File
@@ -1,690 +0,0 @@
/* 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.
*
* 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.
*/
#ifndef RAD_BUILDER_H
#define RAD_BUILDER_H
#include "rad_abi.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct RadBuilder RadBuilder;
/* ================================================================== model metadata */
/* What the loader read out of the container's header before any plugin ran. Dimensions come from
* here, so one plugin covers every size in a family: qwen3_dense_bf16.so serves 2B, 9B and 27B. */
typedef struct RadModelMeta {
const char* arch_id; /* the string that selected this plugin */
const char* name;
const char* quant; /* the quantisation descriptor, e.g. "w4a8_symz_g128" */
int64_t n_layers;
int64_t n_embd;
int64_t n_head;
int64_t n_head_kv;
int64_t head_dim;
int64_t n_ff;
int64_t n_vocab;
int64_t n_ctx_train;
int64_t n_expert; /* 0 for a dense model */
int64_t n_expert_used;
int64_t n_expert_shared;
float rms_eps;
float rope_theta;
float rope_scale;
/* Free-form key/value from the container header, for anything the struct above does not
* name. A plugin reads what it needs; the core never interprets these. */
int n_kv;
const char* const* kv_key;
const char* const* kv_val;
} RadModelMeta;
long long rad_meta_geti(const RadModelMeta* m, const char* key, long long dflt);
double rad_meta_getf(const RadModelMeta* m, const char* key, double dflt);
const char* rad_meta_gets(const RadModelMeta* m, const char* key, const char* dflt);
/* ================================================================== 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) */
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. */
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. */
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.
*
* 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.
*
* 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. */
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.
*
* 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.
*
* 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. */
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.
*
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
int64_t max_out_rows;
} 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). */
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). */
};
/* How a weight is split across tensor-parallel ranks. The plugin says; the core does not infer. */
enum {
RAD_SHARD_NONE = 0, /* replicated on every rank */
RAD_SHARD_ROW = 1, /* split along dim 0 -- column-parallel in the usual naming */
RAD_SHARD_COL = 2 /* split along dim 1 -- row-parallel, needs a following all-reduce */
};
/* 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. */
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 `<arch/rad_arch.h>` instead: the installed spelling, which the plugins in
* radiance's own tree use as well. Same values, no extension. */
#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. */
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) */
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.
*
* 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. */
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.
*
* 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.
*
* 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. */
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.
*
* 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. */
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). */
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 */
RAD_BUF_DERIVED = 2 /* computed once per step by the core from the batch (spec §8) */
};
typedef struct RadBufDecl {
uint32_t dtype;
uint32_t rank;
int64_t shape[RAD_MAX_RANK]; /* sized at max_tok, which is the worst step */
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".
*
* `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.
*
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
rad_kvgroup kv;
} 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). */
enum {
RAD_KV_FULL = 0, /* paged, per-token, growing -- full attention */
RAD_KV_WINDOW = 1, /* paged, per-token, bounded by the window */
RAD_KV_LINEAR = 2, /* per-sequence, fixed size -- GDN recurrent state */
RAD_KV_CONV = 3 /* per-sequence, a rolling window of width-1 + num_spec entries */
};
typedef struct RadKVGroupDecl {
int kind; /* RAD_KV_* */
uint32_t dtype;
int64_t window; /* RAD_KV_WINDOW: the window; 0 otherwise */
int64_t n_head_kv;
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. */
} RadKVGroupDecl;
/* `rad_kvgroup` is in rad_types.h with the other handles -- RadBufDecl above carries one. */
rad_kvgroup rad_decl_kv_group(RadBuilder* b, const char* name, const RadKVGroupDecl* d);
/* Valid only after the op that reads this group has been declared. 0 before that. */
int64_t rad_kv_block_size(RadBuilder* b, rad_kvgroup g);
/* Bind a layer to a group, so the block manager knows how many state instances a sequence owns. */
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. */
rad_op rad_decl_op(RadBuilder* b, const char* op,
const RadParam* params, int n_params,
const rad_weight* weights, int n_weights);
/* Convenience wrappers so a declare function reads like a list of what the model does.
* rad_op h = RAD_OP(b, "gemm_w4a8_nt",
* RAD_PARAMS(RAD_RANGE("M",1,max_tok), RAD_INT("N",8192), RAD_INT("K",5120)),
* RAD_WEIGHTS(w));
*/
#define RAD_PARAMS(...) ((const RadParam[]){ __VA_ARGS__ }), \
(int)(sizeof((const RadParam[]){ __VA_ARGS__ }) / sizeof(RadParam))
#define RAD_NOPARAMS ((const RadParam*)0), 0
#define RAD_WEIGHTS(...) ((const rad_weight[]){ __VA_ARGS__ }), \
(int)(sizeof((const rad_weight[]){ __VA_ARGS__ }) / sizeof(rad_weight))
#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. */
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.
*
* 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.
*
* 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.
*
* Calling it for a PERSIST or DERIVED buffer is a no-op: those are 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).
*
* 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. */
int rad_weight_shard_span(RadBuilder* b, rad_weight w, int64_t lo, int64_t hi);
#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. */
int rad_op_resolved(RadBuilder* b, rad_op h);
/* ================================================================== 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). */
enum { RAD_MAP_COPY = 0, RAD_MAP_CONCAT = 1 };
typedef struct RadNameMap {
const char* declared; /* the name given to rad_decl_weight */
int mode; /* RAD_MAP_COPY | RAD_MAP_CONCAT */
int n_src;
const char* src[8]; /* checkpoint tensor names */
int concat_dim;
/* 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. */
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. */
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.
*
* 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: 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. */
int rad_declare_logits(RadBuilder* b, rad_buf logits);
/* ================================================================== 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.
*
* 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.
*
* 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, 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. */
typedef enum {
RAD_DRAFT_NONE = 0,
RAD_DRAFT_SERIAL = 1, /* `depth` dependent passes, one proposal each */
RAD_DRAFT_BLOCK = 2, /* a context pass, then one pass that fills the whole block */
} RadDraftKind;
typedef struct RadDrafterDecl {
const char* name; /* "mtp", "dflash2" -- for messages and the graph dump */
int kind; /* RAD_DRAFT_* */
int depth; /* tokens proposed a step; must equal RadBuildCtx::max_spec */
/* Where a pass leaves its proposal. 0 = the sampler's token buffer. */
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. */
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`.
*
* 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:
*
* 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.
*
* 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. */
int64_t block;
} RadDrafterDecl;
int rad_declare_drafter(RadBuilder* b, const RadDrafterDecl* d);
/* ================================================================== 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.
*
* 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. */
enum {
RAD_MM_IMAGE = 1u << 0,
RAD_MM_VIDEO = 1u << 1,
};
typedef struct RadEncoderDecl {
const char* name; /* "vision" -- for messages */
uint32_t modalities; /* RAD_MM_* this encoder serves */
int64_t patch_dim; /* elements in one input patch row */
int64_t merge; /* input patches per output row */
int64_t max_patches; /* must equal RadBuildCtx::max_enc_patches */
int64_t n_embd; /* the width of an output row, the model's embedding width */
/* [max_patches / merge, n_embd] bf16: where a pass leaves its rows. The core reads it after
* the pass and before any other pass runs, so the planner may share its bytes with buffers
* no encoder pass touches. */
rad_buf out;
} RadEncoderDecl;
int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d);
/* ================================================================== diagnostics */
/* A plugin may annotate the graph dump. Free-form, printed under --debug-graph. */
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.
*
* 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.
*
* 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)". */
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.
*
* 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.
*
* 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. */
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.
*
* `--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. */
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. */
int shape_probe_ok;
} 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.
*
* 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:
*
* [reasoning_open] reasoning [reasoning_close] content
* [call_open] name_prefix NAME name_suffix
* arg_prefix ARG arg_name_suffix arg_value_prefix VALUE arg_value_suffix ...
* call_end [call_close]
*
* Qwen3.8, for example, is "<think>\n" / "\n</think>\n\n", calls "<tool_call>\n" / "</tool_call>",
* "<function=" / ">\n" / "</function>\n", arguments "<parameter=" / ">\n" / "" / "</parameter>\n".
* Whitespace at the ends of a tag is optional when matching. Every string is NUL-terminated
* UTF-8; NULL reads as "". The engine copies what it needs while loading, so static storage in
* the plugin is enough.
*
* 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. */
enum {
RAD_CHAT_VALUE_RAW = 0, /* the text between the delimiters, verbatim */
RAD_CHAT_VALUE_CDATA = 1, /* verbatim, unless wrapped in <![CDATA[ ... ]]>, which is removed */
RAD_CHAT_VALUE_JSON = 2 /* a JSON value; text that does not parse as JSON is taken raw */
};
enum {
/* The generation prompt shows whether the reply starts inside a reasoning block: whatever
* follows the first `reasoning_open` in it is the start of the reply's own text. */
RAD_CHAT_THINK_FROM_PROMPT = 0,
RAD_CHAT_THINK_ALWAYS = 1, /* the reply is inside a reasoning block from its first byte */
RAD_CHAT_THINK_NEVER = 2 /* the model opens its own block, if any */
};
typedef struct RadChatFormat {
uint32_t struct_size;
const char* name; /* for the startup log; NULL is the plugin's name */
const char* reasoning_open; /* "" when the model does not reason */
const char* reasoning_close;
/* Literals that end a reasoning block the model forgot to close, when a call starts there.
* Each must be the call opener: `call_open`, or `name_prefix` when there is no call_open. */
const char* const* reasoning_breaks;
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. */
const char* section_open;
const char* section_close;
const char* call_separator;
const char* call_open; /* around each call; "" when calls are not wrapped */
const char* call_close;
const char* name_prefix; /* "" when the model has no tool calls */
const char* name_suffix;
const char* call_end;
const char* arg_prefix;
const char* arg_name_suffix; /* "" when arg_value_prefix alone ends the name */
const char* arg_value_prefix;
const char* arg_value_suffix;
uint32_t string_value; /* RAD_CHAT_VALUE_RAW or _CDATA: a string-typed argument */
uint32_t other_value; /* RAD_CHAT_VALUE_JSON: any other type (or _RAW, as text) */
/* Non-zero: one newline at each end of a value is punctuation, not part of the value. */
uint32_t value_newlines;
/* The literal words that start constrained decoding of a call. None: no grammar, and the
* reply is read unconstrained. */
const char* const* triggers;
uint32_t n_triggers;
} 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);
int rad_arch_declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx);
/* Forward declaration; the signature is in rad_runtime.h. */
struct RadCtx;
struct RadBatch;
void rad_arch_step(struct RadCtx* c, const struct RadBatch* batch);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* RAD_BUILDER_H */
-79
View File
@@ -1,79 +0,0 @@
/* 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.
*
* 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).
*/
#ifndef RAD_DEVICE_H
#define RAD_DEVICE_H
#include "rad_types.h"
#ifdef __cplusplus
extern "C" {
#endif
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.
*
* Every field carries whatever 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
* suffixes cut -- "gfx1201", "sm_90". This is what a kernel
* plugin's build_target is compared against. */
int device_id;
int n_cu; /* independent compute units, however the backend counts them */
int warp_size; /* lanes executed in lockstep; 1 on a scalar backend */
int64_t vram_bytes; /* device-local memory, total and unclaimed */
int64_t vram_free;
int64_t lds_bytes; /* per-workgroup scratch, for occupancy arithmetic only */
int supports_p2p;
int is_host_backend; /* 1 when there is no accelerator behind this device */
} RadDeviceProps;
int rad_dev_count(void);
int rad_dev_set(int device);
int rad_dev_props(int device, RadDeviceProps* out);
int rad_dev_enable_peer(int self, int peer);
void* rad_dev_alloc(int64_t bytes, int kind);
void rad_dev_free(void* p, int kind);
/* Host-visible pointer for a RAD_MEM_HOST_MAPPED allocation, so the zero-copy execution site can
* hand the same allocation to both sides (spec §5.1). Null if the kind has no such view. */
void* rad_dev_host_ptr(void* p);
void* rad_dev_device_ptr(void* p);
int rad_stream_create(RadStream* out, int high_priority);
void rad_stream_destroy(RadStream s);
int rad_stream_sync(RadStream s);
int rad_event_create(RadEvent* out);
void rad_event_destroy(RadEvent e);
int rad_event_record(RadEvent e, RadStream s);
int rad_event_wait(RadStream s, RadEvent e); /* stream waits; no host sync */
int rad_event_query(RadEvent e); /* 1 = complete, 0 = pending, <0 = error */
int rad_event_sync(RadEvent e);
int rad_event_elapsed_ms(RadEvent a, RadEvent b, float* out);
int rad_memcpy_async(void* dst, const void* src, int64_t bytes, RadStream s);
int rad_memcpy_2d_async(void* dst, int64_t dpitch, const void* src, int64_t spitch,
int64_t width, int64_t height, RadStream s);
int rad_memset_async(void* dst, int value, int64_t bytes, RadStream s);
/* The last device error, cleared by reading it. A device fault is not recoverable in-process;
* the engine exits non-zero rather than serving from a wedged queue (spec §17). */
const char* rad_dev_last_error(void);
#ifdef __cplusplus
}
#endif
#endif /* RAD_DEVICE_H */
-421
View File
@@ -1,421 +0,0 @@
/* rad_encoding.h -- what a stored weight's numbers ARE, independently 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 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.
*
* ===================================================================== PLANES
*
* 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]
* with rows = d0 * ... * d(n-1) and cols = dn (a rank-1 weight is one row); a TILED
* plane whose block is [br, bc] has ceil(rows/br) x ceil(cols/bc) elements, element
* (i, j) covering logical rows [i*br, (i+1)*br) and columns [j*bc, (j+1)*bc). A block
* extent of 0 is the whole extent, so a per-tensor scale is one element and a
* per-column scale is a block of [0 x 1].
* 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.
*
* ===================================================================== THE AFFINE SCHEME
*
* 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
* lattices); value k of the code's V-vector
* 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
* 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
* 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
* codes, a u6 scale and u6 min per [1 x 32] each times an f16 per [1 x 256]; IQ2_XXS is u8 codes
* per [1 x 8] into a 256 x 8 grid with a sign bit a value and two scale levels. Any other scheme
* is a quantiser's own, and that quantiser decodes it (rad_quant.h).
*
* ===================================================================== TRANSFORMS
*
* `transform` names what was done to each row before it was quantised: the stored row is v = w . T,
* so a kernel computes <w, x> = <v, x . T^-T> and transforms its ACTIVATION, never the weight.
*
* "" none.
* "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 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.
* "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.
*
* Pure C, header-only, like the rest of abi/.
*/
#ifndef RAD_ENCODING_H
#define RAD_ENCODING_H
#include "rad_types.h"
#include <stdio.h>
#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif
enum { RAD_ENC_MAX_PLANES = 8, RAD_ENC_STR = 24 };
enum { RAD_PLANE_TILED = 0, RAD_PLANE_TABLE = 1 };
typedef struct RadEncPlane {
char role[RAD_ENC_STR]; /* "codes", "scale", "scale.1", "zero", "min", "grid", "t.perm" */
uint32_t dtype; /* a core dtype -- never a plugin-private one */
uint32_t kind; /* RAD_PLANE_TILED | RAD_PLANE_TABLE */
int64_t block[2]; /* TILED: logical rows x cols one element covers; 0 = whole */
int64_t extent[2]; /* TABLE: the plane's own rows x cols */
} RadEncPlane;
typedef struct RadEncoding {
char scheme[RAD_ENC_STR]; /* "plain" | "affine" | a quantiser's own */
char transform[RAD_ENC_STR]; /* "" | "fwhtN" | "perm" | "givens" */
int32_t n_planes;
int32_t reserved;
RadEncPlane plane[RAD_ENC_MAX_PLANES];
} RadEncoding;
/* ================================================================== building one */
static inline void rad_enc_copy_str(char* dst, const char* src) {
size_t n = src ? strlen(src) : 0;
if (n >= RAD_ENC_STR) n = RAD_ENC_STR - 1;
memset(dst, 0, RAD_ENC_STR);
if (n) memcpy(dst, src, n);
}
static inline void rad_enc_clear(RadEncoding* e) { memset(e, 0, sizeof *e); }
/* Append a TILED plane. Returns its index, or -1 when the encoding is full. */
static inline int rad_enc_add_plane(RadEncoding* e, const char* role, uint32_t dtype,
int64_t block_rows, int64_t block_cols) {
RadEncPlane* p;
if (e->n_planes >= RAD_ENC_MAX_PLANES) return -1;
p = &e->plane[e->n_planes];
memset(p, 0, sizeof *p);
rad_enc_copy_str(p->role, role);
p->dtype = dtype;
p->kind = RAD_PLANE_TILED;
p->block[0] = block_rows;
p->block[1] = block_cols;
return e->n_planes++;
}
/* Append a TABLE plane of its own [rows x cols]. */
static inline int rad_enc_add_table(RadEncoding* e, const char* role, uint32_t dtype,
int64_t rows, int64_t cols) {
const int i = rad_enc_add_plane(e, role, dtype, 0, 0);
if (i < 0) return i;
e->plane[i].kind = RAD_PLANE_TABLE;
e->plane[i].extent[0] = rows;
e->plane[i].extent[1] = cols;
return i;
}
/* A weight stored as it is: one plane of `dtype`, one element a value. */
static inline RadEncoding rad_enc_plain(uint32_t dtype) {
RadEncoding e;
rad_enc_clear(&e);
rad_enc_copy_str(e.scheme, "plain");
rad_enc_add_plane(&e, "codes", dtype, 1, 1);
return e;
}
/* value = code * scale, one scale per [block_rows x block_cols]. Further planes go on with
* rad_enc_add_plane / rad_enc_add_table, and a transform with
* rad_enc_copy_str(e.transform, ...). */
static inline RadEncoding rad_enc_affine(uint32_t codes, uint32_t scale, int64_t block_rows,
int64_t block_cols) {
RadEncoding e;
rad_enc_clear(&e);
rad_enc_copy_str(e.scheme, "affine");
rad_enc_add_plane(&e, "codes", codes, 1, 1);
rad_enc_add_plane(&e, "scale", scale, block_rows, block_cols);
return e;
}
/* ================================================================== reading one */
static inline int rad_enc_is(const RadEncoding* e, const char* scheme) {
return e && strncmp(e->scheme, scheme, RAD_ENC_STR) == 0;
}
/* The index of the plane with this role, or -1. */
static inline int rad_enc_find(const RadEncoding* e, const char* role) {
int i;
if (!e || !role) return -1;
for (i = 0; i < e->n_planes; ++i)
if (strncmp(e->plane[i].role, role, RAD_ENC_STR) == 0) return i;
return -1;
}
/* The plane with this role, or null. */
static inline const RadEncPlane* rad_enc_plane(const RadEncoding* e, const char* role) {
const int i = rad_enc_find(e, role);
return i < 0 ? 0 : &e->plane[i];
}
/* The index of level `level` of a multiplied chain -- "scale", "scale.1", "scale.2" -- or -1. */
static inline int rad_enc_find_level(const RadEncoding* e, const char* base, int level) {
char r[RAD_ENC_STR];
if (level == 0) return rad_enc_find(e, base);
snprintf(r, sizeof r, "%s.%d", base, level);
return rad_enc_find(e, r);
}
/* Does `role` belong to the chain `base` ("scale" -> scale, scale.1, ...)? */
static inline int rad_enc_role_in_chain(const char* role, const char* base) {
const size_t n = strlen(base);
int lv = 0;
if (strncmp(role, base, n) != 0) return 0;
if (role[n] == 0) return 1;
return role[n] == '.' && sscanf(role + n + 1, "%d", &lv) == 1 && lv > 0;
}
/* The order N of an "fwhtN" transform, 0 when the transform is not one, -1 when it is malformed. */
static inline int64_t rad_enc_fwht(const RadEncoding* e) {
long long n = 0;
if (!e || strncmp(e->transform, "fwht", 4) != 0) return 0;
if (sscanf(e->transform + 4, "%lld", &n) != 1 || n < 2 || (n & (n - 1)) != 0) return -1;
return (int64_t)n;
}
/* 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. */
static inline int rad_enc_equal(const RadEncoding* a, const RadEncoding* b) {
return a && b && memcmp(a, b, sizeof *a) == 0;
}
/* ================================================================== geometry */
/* The [rows, cols] a logical shape is seen as. */
static inline void rad_enc_view(uint32_t rank, const int64_t* shape, int64_t* rows,
int64_t* cols) {
uint32_t i;
int64_t r = 1;
if (rank == 0) { *rows = 1; *cols = 1; return; }
for (i = 0; i + 1 < rank; ++i) r *= shape[i];
*rows = r;
*cols = shape[rank - 1];
}
/* A plane's element extents over a [rows, cols] weight. */
static inline void rad_enc_plane_dims(const RadEncPlane* p, int64_t rows, int64_t cols,
int64_t* prows, int64_t* pcols) {
if (p->kind == RAD_PLANE_TABLE) {
*prows = p->extent[0];
*pcols = p->extent[1];
return;
}
*prows = p->block[0] > 0 ? (rows + p->block[0] - 1) / p->block[0] : 1;
*pcols = p->block[1] > 0 ? (cols + p->block[1] - 1) / p->block[1] : 1;
}
/* Bytes of one row of `n` elements: every row starts on a byte. 0 for a dtype the core does not
* size, which an encoding may never hold. */
static inline int64_t rad_enc_row_bytes(uint32_t dtype, int64_t n) {
return rad_dtype_bytes(dtype, n);
}
static inline int64_t rad_enc_plane_bytes(const RadEncPlane* p, int64_t rows, int64_t cols) {
int64_t pr, pc;
rad_enc_plane_dims(p, rows, cols, &pr, &pc);
return pr * rad_enc_row_bytes(p->dtype, pc);
}
/* How many values one code stands for: 1, or V for a vector code into a grid. */
static inline int64_t rad_enc_code_width(const RadEncoding* e) {
return (e && e->n_planes > 0 && e->plane[0].block[1] > 1) ? e->plane[0].block[1] : 1;
}
/* Is the encoding well formed? 1 if so.
*
* Every plane has a role and a core dtype, the "codes" plane comes first, is TILED and covers one
* row of one value -- or of V values when a grid of width V is there to expand it -- and the
* planes the affine scheme reads have the kinds it reads them as. A scheme the core does not
* define is checked for the first two only: its planes are its quantiser's business. */
static inline int rad_enc_valid(const RadEncoding* e) {
int i, g;
int64_t v;
const char* t;
if (!e || e->n_planes < 1 || e->n_planes > RAD_ENC_MAX_PLANES || !e->scheme[0]) return 0;
for (i = 0; i < e->n_planes; ++i) {
const RadEncPlane* p = &e->plane[i];
if (!p->role[0] || rad_dtype_bits(p->dtype) == 0) return 0;
if (p->kind == RAD_PLANE_TILED && (p->block[0] < 0 || p->block[1] < 0)) return 0;
if (p->kind == RAD_PLANE_TABLE && (p->extent[0] < 1 || p->extent[1] < 1)) return 0;
if (p->kind != RAD_PLANE_TILED && p->kind != RAD_PLANE_TABLE) return 0;
if (rad_enc_find(e, p->role) != i) return 0; /* roles are unique */
}
if (strncmp(e->plane[0].role, "codes", RAD_ENC_STR) != 0) return 0;
if (e->plane[0].kind != RAD_PLANE_TILED || e->plane[0].block[0] != 1) return 0;
if (rad_enc_is(e, "plain"))
return e->n_planes == 1 && !e->transform[0] && e->plane[0].block[1] == 1;
if (!rad_enc_is(e, "affine")) return e->plane[0].block[1] >= 1;
/* nothing beyond the codes is "plain", and one weight has one spelling */
if (e->n_planes == 1 && !e->transform[0]) return 0;
v = e->plane[0].block[1];
g = rad_enc_find(e, "grid");
if (v < 1) return 0;
if (g >= 0) {
if (e->plane[g].kind != RAD_PLANE_TABLE || e->plane[g].extent[1] != v) return 0;
} else if (v != 1) {
return 0;
}
if (rad_enc_find(e, "table") >= 0 && (g >= 0 || e->plane[rad_enc_find(e, "table")].kind
!= RAD_PLANE_TABLE)) return 0;
for (i = 1; i < e->n_planes; ++i) {
const RadEncPlane* p = &e->plane[i];
const int tiled = rad_enc_role_in_chain(p->role, "scale") ||
rad_enc_role_in_chain(p->role, "min") ||
!strncmp(p->role, "zero", RAD_ENC_STR) ||
!strncmp(p->role, "signs", RAD_ENC_STR);
const int table = !strncmp(p->role, "grid", RAD_ENC_STR) ||
!strncmp(p->role, "table", RAD_ENC_STR) || !strncmp(p->role, "t.", 2);
if (!tiled && !table) return 0; /* a role nothing reads */
if (tiled && p->kind != RAD_PLANE_TILED) return 0;
if (table && p->kind != RAD_PLANE_TABLE) return 0;
}
/* a chain level exists only above the one before it */
for (i = 1; i < e->n_planes; ++i) {
int lv = 0;
const char* r = e->plane[i].role;
const char* base = rad_enc_role_in_chain(r, "scale") ? "scale"
: rad_enc_role_in_chain(r, "min") ? "min" : 0;
if (!base || !strchr(r, '.')) continue;
sscanf(strchr(r, '.') + 1, "%d", &lv);
if (rad_enc_find_level(e, base, lv - 1) < 0) return 0;
}
if (rad_enc_find(e, "signs") >= 0 &&
(e->plane[rad_enc_find(e, "signs")].dtype != RAD_U1 ||
e->plane[rad_enc_find(e, "signs")].block[0] != 1 ||
e->plane[rad_enc_find(e, "signs")].block[1] != 1)) return 0;
t = e->transform;
if (!t[0]) return 1;
if (!strncmp(t, "fwht", 4)) return rad_enc_fwht(e) > 0;
if (!strcmp(t, "perm")) return rad_enc_find(e, "t.perm") > 0;
if (!strcmp(t, "givens"))
return rad_enc_find(e, "t.pairs") > 0 && rad_enc_find(e, "t.angle") > 0;
return 0;
}
/* ================================================================== the canonical spelling
*
* What a person, a log line and rad-info read. Kernels read the struct.
*
* plain <dtype> bf16
* affine, codes and scales <codes>*<scale>[RxC]*<scale.1>[RxC] fp4_e2m1*fp8_e4m3[1x16]*f32[*x*]
* with an integer zero ...-<zero>[RxC] u2*f16[1x128]-u8[1x128]
* anything else <scheme>:<role>=<dtype><shape>,... affine:codes=u4[1x1],...
* and a transform .../<transform> i4*bf16[1x128]/fwht128
*
* A block extent of 0 -- the whole extent -- is written `*`, and a TABLE plane's shape is written
* `{RxC}`. Returns the length written, like snprintf; the output is always terminated. */
static inline int rad_enc_shape_str(const RadEncPlane* p, char* buf, size_t n) {
char r[24], c[24];
if (p->kind == RAD_PLANE_TABLE)
return snprintf(buf, n, "{%lldx%lld}", (long long)p->extent[0], (long long)p->extent[1]);
if (p->block[0] > 0) snprintf(r, sizeof r, "%lld", (long long)p->block[0]);
else snprintf(r, sizeof r, "*");
if (p->block[1] > 0) snprintf(c, sizeof c, "%lld", (long long)p->block[1]);
else snprintf(c, sizeof c, "*");
return snprintf(buf, n, "[%sx%s]", r, c);
}
/* Codes, a scale chain and at most an integer zero: the shape that has a short spelling. */
static inline int rad_enc_is_simple_affine(const RadEncoding* e) {
int i, lv;
if (!rad_enc_is(e, "affine") || e->plane[0].block[1] != 1) return 0;
for (i = 1; i < e->n_planes; ++i) {
const char* r = e->plane[i].role;
if (!rad_enc_role_in_chain(r, "scale") && strncmp(r, "zero", RAD_ENC_STR) != 0 &&
strncmp(r, "t.", 2) != 0) return 0;
}
/* and the scales in level order, so the spelling is read the way it is multiplied */
for (i = 1, lv = 0; i < e->n_planes; ++i) {
if (!rad_enc_role_in_chain(e->plane[i].role, "scale")) continue;
if (rad_enc_find_level(e, "scale", lv++) != i) return 0;
}
return lv > 0;
}
static inline int rad_enc_format(const RadEncoding* e, char* buf, size_t n) {
char shp[64];
size_t at = 0;
int i;
#define RAD_ENC_PUT(...) \
do { \
int w_ = snprintf(buf + (at < n ? at : n), at < n ? n - at : 0, __VA_ARGS__); \
if (w_ > 0) at += (size_t)w_; \
} while (0)
if (!buf || n == 0) return 0;
buf[0] = 0;
if (!e || e->n_planes < 1) {
RAD_ENC_PUT("(none)");
} else if (rad_enc_is(e, "plain") && e->n_planes == 1) {
RAD_ENC_PUT("%s", rad_dtype_name(e->plane[0].dtype));
} else if (rad_enc_is_simple_affine(e)) {
RAD_ENC_PUT("%s", rad_dtype_name(e->plane[0].dtype));
for (i = 1; i < e->n_planes; ++i) {
if (!rad_enc_role_in_chain(e->plane[i].role, "scale")) continue;
rad_enc_shape_str(&e->plane[i], shp, sizeof shp);
RAD_ENC_PUT("*%s%s", rad_dtype_name(e->plane[i].dtype), shp);
}
i = rad_enc_find(e, "zero");
if (i > 0) {
rad_enc_shape_str(&e->plane[i], shp, sizeof shp);
RAD_ENC_PUT("-%s%s", rad_dtype_name(e->plane[i].dtype), shp);
}
} else {
RAD_ENC_PUT("%s:", e->scheme);
for (i = 0; i < e->n_planes; ++i) {
rad_enc_shape_str(&e->plane[i], shp, sizeof shp);
RAD_ENC_PUT("%s%s=%s%s", i ? "," : "", e->plane[i].role,
rad_dtype_name(e->plane[i].dtype), shp);
}
}
if (e && e->transform[0]) RAD_ENC_PUT("/%s", e->transform);
#undef RAD_ENC_PUT
return (int)at;
}
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* RAD_ENCODING_H */
-164
View File
@@ -1,164 +0,0 @@
/* 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
* 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)
* grouped by movement unit -- an expert's entries are adjacent, and addressing within a
* layer is base + id*stride
* aligned -- pool 2 MiB, movement unit 4 KiB, plane 256 B
* self-describing -- each entry carries its encoding, its logical shape and the
* quantiser and options that made it
*
* 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. */
#ifndef RAD_FORMAT_H
#define RAD_FORMAT_H
#include "rad_types.h"
#include "rad_encoding.h"
#ifdef __cplusplus
extern "C" {
#endif
#define RAD_MAGIC 0x31444152u /* "RAD1" little-endian: the family; the version follows */
#define RAD_FORMAT_VER 2u
#define RAD_ALIGN_POOL (2u * 1024u * 1024u)
#define RAD_ALIGN_UNIT 4096u
#define RAD_ALIGN_SUB 256u
typedef uint64_t rad_stroff; /* offset into the string blob; 0 is the empty string */
/* ------------------------------------------------------------------ header */
typedef struct RadFileHeader {
uint32_t magic;
uint32_t version;
uint64_t file_bytes;
rad_stroff arch_id;
rad_stroff model_name;
rad_stroff quant; /* the source checkpoint's quantisation descriptor, "" for none:
* with arch_id, what selects the architecture plugin (spec §2.4) */
rad_stroff recipe; /* the recipe it was converted with, as text; "" for none */
rad_stroff created_by; /* rad-convert version + the source checkpoint's identity */
uint64_t str_off, str_bytes;
uint64_t meta_off, meta_count; /* RadFileKV[] */
uint64_t dir_off, dir_count; /* RadFileEntry[] */
uint64_t plane_off, plane_count; /* RadFilePlane[] */
uint64_t enc_off, enc_count; /* RadEncoding[], each distinct one once */
uint64_t vocab_off, vocab_bytes; /* RadVocabHeader + its payload */
uint64_t prof_off, prof_count; /* RadFileProfile[] -- expert popularity */
uint64_t data_off, data_bytes; /* the blob; RAD_ALIGN_POOL-aligned */
uint64_t reserved[8];
} RadFileHeader;
/* ------------------------------------------------------------------ metadata */
typedef struct RadFileKV {
rad_stroff key;
uint32_t type; /* RAD_P_INT | RAD_P_STR, or RAD_KV_F64 */
uint32_t pad;
union {
int64_t i;
double f;
rad_stroff s;
} v;
} RadFileKV;
enum { RAD_KV_F64 = 100 };
/* ------------------------------------------------------------------ weight directory */
/* 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 {
rad_stroff name; /* the logical weight's name */
rad_stroff quantizer; /* the quantiser that wrote the planes; "" for the checkpoint's own */
rad_stroff options; /* the options it ran with, "k=v,k=v" sorted by key */
uint32_t enc; /* index into the encoding table */
uint32_t rank;
int64_t shape[RAD_MAX_RANK]; /* the LOGICAL shape */
int32_t layer; /* RadWeightGroup, flattened: the movement unit */
int32_t expert;
int32_t slot;
uint32_t n_planes; /* the encoding's, in its order */
uint64_t plane_first; /* index into the plane table */
uint64_t offset; /* the entry's first byte, from file start, RAD_ALIGN_UNIT-aligned */
uint64_t bytes; /* to the end of its last plane */
uint64_t reserved[2];
} RadFileEntry;
/* One plane of an entry: dense, row-major, every row starting on a byte, exactly
* rad_enc_plane_bytes() long for the entry's logical shape. */
typedef struct RadFilePlane {
uint64_t offset; /* from file start, RAD_ALIGN_SUB-aligned */
uint64_t bytes;
} 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. */
typedef struct RadFileProfile {
int32_t layer;
int32_t expert;
float share; /* fraction of tokens routed here in the calibration set */
float reserved;
} 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). */
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. */
enum {
RAD_NORM_NFC = 1, RAD_NORM_NFKC = 2, RAD_NORM_NFD = 3, RAD_NORM_NFKD = 4,
RAD_NORM_LOWERCASE = 5, RAD_NORM_STRIP = 6, RAD_NORM_REPLACE = 7, RAD_NORM_PREPEND = 8,
RAD_PRE_BYTELEVEL = 32, RAD_PRE_SPLIT = 33, RAD_PRE_METASPACE = 34,
RAD_PRE_WHITESPACE = 35, RAD_PRE_PUNCTUATION = 36, RAD_PRE_DIGITS = 37,
RAD_PRE_BYTE_FALLBACK = 38,
RAD_DEC_BYTELEVEL = 64, RAD_DEC_METASPACE = 65, RAD_DEC_REPLACE = 66,
RAD_DEC_STRIP = 67, RAD_DEC_FUSE = 68, RAD_DEC_BYTE_FALLBACK = 69
};
typedef struct RadVocabStep {
uint32_t kind; /* RAD_NORM_* | RAD_PRE_* | RAD_DEC_* */
uint32_t flags; /* step-specific: invert, add_prefix_space, use_regex, ... */
rad_stroff arg0; /* a pattern, a replacement, a prepend string */
rad_stroff arg1;
int64_t iarg;
} RadVocabStep;
typedef struct RadVocabHeader {
uint32_t kind; /* RAD_TOK_* */
uint32_t n_tokens;
uint32_t n_merges;
uint32_t n_steps;
uint64_t tok_text_off; /* rad_stroff[n_tokens] */
uint64_t tok_score_off; /* float[n_tokens], unigram only */
uint64_t tok_type_off; /* uint8[n_tokens]: normal/unknown/control/user/byte */
uint64_t merge_off; /* uint32[n_merges][2] */
uint64_t step_off; /* RadVocabStep[n_steps] */
int32_t bos, eos, eot, pad_id, unk, sep;
uint32_t add_bos, add_eos;
rad_stroff chat_template;
uint64_t reserved[4];
} RadVocabHeader;
enum { RAD_TT_NORMAL = 1, RAD_TT_UNKNOWN = 2, RAD_TT_CONTROL = 3,
RAD_TT_USER_DEFINED = 4, RAD_TT_BYTE = 6 };
#ifdef __cplusplus
}
#endif
#endif /* RAD_FORMAT_H */
-520
View File
@@ -1,520 +0,0 @@
/* rad_plugin.h -- everything a kernel or architecture plugin needs and cannot link.
*
* ===================================================================== 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.
*
* 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.
*
* ===================================================================== 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.
*
* 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.
*
* 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.
*
* Pure C, like the rest of abi/. See spec.md 2.
*/
#ifndef RAD_PLUGIN_H
#define RAD_PLUGIN_H
#include "rad_abi.h"
#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif
/* ================================================================== 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. */
static inline const RadParam* rad_param_find(const RadParam* p, int n_p, const char* key) {
if (!p || !key) return 0;
for (int i = 0; i < n_p; ++i)
if (p[i].key && strcmp(p[i].key, key) == 0) return &p[i];
return 0;
}
/* An int parameter, or `dflt` if the key is absent or is 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. */
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. */
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);
if (!f) return dflt;
if (f->kind == RAD_P_INT) return f->ival;
if (f->kind == RAD_P_RANGE) return f->ihi;
return dflt;
}
static inline const char* rad_param_gets(const RadParam* p, int n_p, const char* key,
const char* dflt) {
const RadParam* f = rad_param_find(p, n_p, key);
return (f && f->kind == RAD_P_STR && f->sval) ? f->sval : dflt;
}
static inline double rad_param_getf(const RadParam* p, int n_p, const char* key, double dflt) {
const RadParam* f = rad_param_find(p, n_p, 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. */
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));
}
/* The RadArgs forms. rad_args_geti/gets are in rad_abi.h and return presence; these return the
* value with a default, which is what a launch almost always wants. */
static inline long long rad_args_geti_or(const RadArgs* a, const char* key, long long dflt) {
long long v = 0;
return (a && rad_args_geti(a, key, &v)) ? v : dflt;
}
static inline const char* rad_args_gets_or(const RadArgs* a, const char* key, const char* dflt) {
const char* s = a ? rad_args_gets(a, key) : 0;
return s ? s : dflt;
}
static inline double rad_args_getf_or(const RadArgs* a, const char* key, double dflt) {
return a ? rad_param_getf(a->p, a->n_p, key, dflt) : dflt;
}
/* ================================================================== operands
*
* THE ABSENT-OPERAND RULE, WHICH IS THE EASIEST THING IN THIS ABI TO GET WRONG.
*
* 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. */
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. */
/* Are the first `n` operands all present? The usual opening line of a launch, where the required
* ones 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;
}
/* ================================================================== 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. */
static inline int64_t rad_tensor_rows(const RadTensor* t) {
if (!t || t->rank == 0) return 0;
int64_t m = 1;
for (uint32_t i = 0; i + 1 < t->rank; ++i) m *= t->shape[i];
return m;
}
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). */
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). */
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.
*
* 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.
*
* 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. */
static inline float rad_bf16_to_f32(uint16_t h) {
uint32_t u = (uint32_t)h << 16;
float f;
memcpy(&f, &u, 4);
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. */
static inline uint16_t rad_f32_to_bf16(float f) {
uint32_t u;
memcpy(&u, &f, 4);
if ((u & 0x7fffffffu) > 0x7f800000u) return (uint16_t)((u >> 16) | 0x0040u);
return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16);
}
static inline float rad_f16_to_f32(uint16_t h) {
uint32_t s = (uint32_t)(h >> 15) << 31;
uint32_t e = (uint32_t)(h >> 10) & 0x1fu;
uint32_t m = (uint32_t)h & 0x3ffu;
uint32_t u;
if (e == 0u) {
if (m == 0u) {
u = s;
} else {
int sh = 0; /* subnormal: renormalise into f32's range */
while (!(m & 0x400u)) { m <<= 1; ++sh; }
m &= 0x3ffu;
u = s | ((uint32_t)(127 - 15 - sh + 1) << 23) | (m << 13);
}
} else if (e == 0x1fu) {
u = s | 0x7f800000u | (m << 13);
} else {
u = s | ((e - 15u + 127u) << 23) | (m << 13);
}
float f;
memcpy(&f, &u, 4);
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. */
static inline uint16_t rad_f32_to_f16(float f) {
uint32_t u;
memcpy(&u, &f, 4);
uint32_t s = (u >> 16) & 0x8000u;
uint32_t a = u & 0x7fffffffu;
if (a >= 0x7f800000u) /* inf or nan */
return (uint16_t)(s | 0x7c00u | (a > 0x7f800000u ? ((a >> 13) & 0x3ffu) | 0x200u : 0u));
if (a >= 0x47800000u) return (uint16_t)(s | 0x7c00u); /* overflow -> inf */
if (a < 0x33000000u) return (uint16_t)s; /* underflow -> zero */
{
int e = (int)(a >> 23) - 127;
uint32_t m = a & 0x7fffffu;
if (e < -14) { /* subnormal half */
int sh = -14 - e + 13;
uint32_t lo, q, half;
m |= 0x800000u;
lo = m & ((1u << sh) - 1u);
q = m >> sh;
half = 1u << (sh - 1);
if (lo > half || (lo == half && (q & 1u))) ++q;
return (uint16_t)(s | q);
}
{
uint32_t q = m >> 13;
uint32_t lo = m & 0x1fffu;
uint32_t he;
if (lo > 0x1000u || (lo == 0x1000u && (q & 1u))) ++q;
he = (uint32_t)(e + 15);
if (q == 0x400u) { q = 0; ++he; } /* rounding carried into the exp */
if (he >= 0x1fu) return (uint16_t)(s | 0x7c00u);
return (uint16_t)(s | (he << 10) | q);
}
}
}
/* 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. */
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;
uint32_t m = (uint32_t)b & 0x7u;
uint32_t u;
if (e == 0u) {
if (m == 0u) {
u = s;
} else {
int sh = 0;
while (!(m & 0x8u)) { m <<= 1; ++sh; }
m &= 0x7u;
u = s | ((uint32_t)(127 - 6 - sh) << 23) | (m << 20);
}
} else if (e == 0xfu && m == 0x7u) {
u = s | 0x7fc00000u; /* the single NaN encoding */
} else {
u = s | ((e - 7u + 127u) << 23) | (m << 20);
}
float f;
memcpy(&f, &u, 4);
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. */
static inline uint8_t rad_f32_to_fp8e4m3(float f) {
uint32_t u;
memcpy(&u, &f, 4);
{
uint8_t s = (uint8_t)((u >> 24) & 0x80u);
uint32_t a = u & 0x7fffffffu;
int e;
uint32_t m;
if (a > 0x7f800000u) return (uint8_t)(s | 0x7fu); /* nan */
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. */
if (e < -10) return s;
if (e < -6) { /* subnormal fp8 */
int sh = -6 - e + 20;
uint32_t lo, q, half;
m |= 0x800000u;
lo = m & ((1u << sh) - 1u);
q = m >> sh;
half = 1u << (sh - 1);
if (lo > half || (lo == half && (q & 1u))) ++q;
return (uint8_t)(s | q);
}
{
uint32_t q = m >> 20;
uint32_t lo = m & 0xfffffu;
int ee;
if (lo > 0x80000u || (lo == 0x80000u && (q & 1u))) ++q;
ee = e + 7;
if (q == 0x8u) { q = 0; ++ee; }
if (ee > 15 || (ee == 15 && q >= 7u)) return (uint8_t)(s | 0x7eu);
return (uint8_t)(s | ((uint32_t)ee << 3) | q);
}
}
}
/* 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. */
static inline float rad_fp8e5m2_to_f32(uint8_t b) {
return rad_f16_to_f32((uint16_t)((uint16_t)b << 8));
}
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);
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. */
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. */
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);
const float frac = (float)m / (float)(1 << mbits);
const float pow2 = e >= bias ? (float)(1 << (e - bias)) : 1.0f / (float)(1 << (bias - e));
const float mag = e == 0 ? frac / (float)(1 << (bias - 1)) : (1.0f + frac) * pow2;
return (c & 0x20) ? -mag : mag;
}
/* 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
* 16 bits. rad_encoding.h is where the order is defined. */
static inline uint32_t rad_load_bits(const void* base, int bits, int64_t i) {
const uint8_t* b8 = (const uint8_t*)base;
const int64_t o = i * (int64_t)bits;
const int64_t byte = o >> 3;
const int sh = (int)(o & 7);
uint32_t w = b8[byte];
if (sh + bits > 8) w |= (uint32_t)b8[byte + 1] << 8;
if (sh + bits > 16) w |= (uint32_t)b8[byte + 2] << 16;
return (w >> sh) & ((1u << bits) - 1u);
}
static inline void rad_store_bits(void* base, int bits, int64_t i, uint32_t code) {
uint8_t* b8 = (uint8_t*)base;
const int64_t o = i * (int64_t)bits;
int64_t byte = o >> 3;
int sh = (int)(o & 7), left = bits;
code &= (1u << bits) - 1u;
while (left > 0) {
const int take = 8 - sh < left ? 8 - sh : left;
const uint8_t m = (uint8_t)(((1u << take) - 1u) << sh);
b8[byte] = (uint8_t)((b8[byte] & ~m) | ((code << sh) & m));
code >>= take;
left -= take;
sh = 0;
++byte;
}
}
/* Signed widths from the table, sign-extended from the stream; 0 for a dtype that is not a
* packed integer. */
static inline int rad_dtype_packed_int(uint32_t dt, int* is_signed) {
switch (dt) {
case RAD_I2: case RAD_I3: case RAD_I4: case RAD_I5: case RAD_I6: case RAD_I7:
*is_signed = 1; return rad_dtype_bits(dt);
case RAD_U1: case RAD_U2: case RAD_U3: case RAD_U4: case RAD_U5: case RAD_U6:
case RAD_U7: case RAD_U9: case RAD_U10: case RAD_U11: case RAD_U12:
*is_signed = 0; return rad_dtype_bits(dt);
default:
*is_signed = 0; return 0;
}
}
/* OCP E8M0: a bare biased exponent, 2^(e-127), with 0xFF the NaN. Exact in f32 except at the two
* ends, where 2^-127 is subnormal and still exact and 2^128 does not exist. */
static inline float rad_e8m0_to_f32(uint8_t e) {
uint32_t u;
float f;
if (e == 0xffu) u = 0x7fc00000u;
else if (e == 0u) u = 0x00400000u; /* 2^-127, the one subnormal */
else u = (uint32_t)e << 23;
memcpy(&f, &u, 4);
return f;
}
/* ================================================================== 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.
*
* 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. */
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;
const int pb = rad_dtype_packed_int(dtype, &sgn);
if (pb) {
const uint32_t c = rad_load_bits(base, pb, i);
return sgn ? (float)((int32_t)(c ^ (1u << (pb - 1))) - (int32_t)(1u << (pb - 1)))
: (float)c;
}
switch (dtype) {
case RAD_FP4E2M1: return rad_fp4e2m1_to_f32((uint8_t)rad_load_bits(base, 4, i));
case RAD_FP6E2M3: return rad_fp6_to_f32((uint8_t)rad_load_bits(base, 6, i), 2);
case RAD_FP6E3M2: return rad_fp6_to_f32((uint8_t)rad_load_bits(base, 6, i), 3);
case RAD_E8M0: return rad_e8m0_to_f32(b8[i]);
case RAD_U16: return (float)((const uint16_t*)base)[i];
case RAD_F32: return ((const float*)base)[i];
case RAD_F16: return rad_f16_to_f32(((const uint16_t*)base)[i]);
case RAD_BF16: return rad_bf16_to_f32(((const uint16_t*)base)[i]);
case RAD_F8E4M3: return rad_fp8e4m3_to_f32(((const uint8_t*)base)[i]);
case RAD_F8E5M2: return rad_fp8e5m2_to_f32(((const uint8_t*)base)[i]);
case RAD_I8: return (float)((const int8_t*)base)[i];
case RAD_U8: return (float)((const uint8_t*)base)[i];
case RAD_I16: return (float)((const int16_t*)base)[i];
case RAD_I32: return (float)((const int32_t*)base)[i];
case RAD_U32: return (float)((const uint32_t*)base)[i];
case RAD_I64: return (float)((const int64_t*)base)[i];
case RAD_BOOL: return ((const uint8_t*)base)[i] ? 1.0f : 0.0f;
default: return 0.0f;
}
}
/* 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. */
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;
if (bits == 16) { ((uint16_t*)base)[i] = (uint16_t)code; return 1; }
if (bits == 8) { ((uint8_t*)base)[i] = (uint8_t)code; return 1; }
rad_store_bits(base, bits, i, (uint32_t)code);
return 1;
}
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;
case RAD_F16: ((uint16_t*)base)[i] = rad_f32_to_f16(v); break;
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_BOOL: ((uint8_t*)base)[i] = v != 0.0f ? 1u : 0u; break;
default: break;
}
}
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* RAD_PLUGIN_H */
-116
View File
@@ -1,116 +0,0 @@
/* 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).
* 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.
*
* 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.
*
* 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.
*
* 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.
*
* Pure C, like the rest of abi/.
*/
#ifndef RAD_QUANT_H
#define RAD_QUANT_H
#include "rad_abi.h"
#include "rad_encoding.h"
#ifdef __cplusplus
extern "C" {
#endif
/* What a quantiser is told about the weight it is quantising. */
typedef struct RadQuantWeight {
const char* name; /* the logical (declared) name: "blk.7.ffn_down_exps.3.weight" */
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. */
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. */
const float* importance;
} RadQuantWeight;
/* One option a quantiser takes, for `rad-convert --list-quantizers` and for typing a recipe's
* `key=value` text before the quantiser sees it: an option declared RAD_P_INT arrives as an int,
* RAD_P_F64 as a double, RAD_P_STR as the text. An option a recipe gives and the table does not
* name is refused by the converter, by name, before anything is quantised. */
typedef struct RadQuantOption {
const char* key;
int type; /* RAD_P_INT | RAD_P_F64 | RAD_P_STR */
const char* deflt; /* the default, as text; null for none */
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. */
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. */
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.
* 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);
/* Decode rows [row0, row0 + rows) back to f32 [rows, cols], for an encoding whose scheme the core
* 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
* 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. */
typedef int (*RadQuantDecodeFn)(const RadEncoding* e, const RadQuantWeight* w,
const void* const* planes, int64_t row0, int64_t rows,
float* out);
typedef struct RadQuantizerInfo {
const char* name; /* what a recipe names: "fp8-block", "int", "gptq" */
const char* doc;
const RadQuantOption* options;
int n_options;
RadQuantEncodingFn encoding;
RadQuantRowBlockFn row_block;
RadQuantizeFn quantize;
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. */
int rad_quant_count(void);
const RadQuantizerInfo* rad_quant_at(int i);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* RAD_QUANT_H */
-382
View File
@@ -1,382 +0,0 @@
/* 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.
*/
#ifndef RAD_RUNTIME_H
#define RAD_RUNTIME_H
#include "rad_builder.h"
#ifdef __cplusplus
extern "C" {
#endif
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.
*
* 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. */
enum { RAD_PHASE_PREFILL = 0, RAD_PHASE_DECODE = 1, RAD_PHASE_MIXED = 2 };
typedef struct RadKVGroupBatch {
rad_kvgroup group;
int32_t* slot_mapping; /* [n_tok] flat slot index per token, device */
int32_t* block_table; /* [n_seq, max_blocks] device */
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. */
int64_t state_index_pitch;
int64_t block_size;
int64_t max_blocks;
} RadKVGroupBatch;
typedef struct RadBatch {
int phase; /* RAD_PHASE_* -- the run phase uses it to index bucket tables */
int step; /* monotonic, for the heat engine and for logs */
int64_t n_tok; /* total tokens across all sequences in this step */
int64_t n_seq;
const int32_t* token_ids; /* [n_tok] device */
const int32_t* positions; /* [n_tok] device */
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].
*
* 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").
*
* 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. */
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 */
int32_t max_q_len; /* host-side bounds -- these select kernel bands */
int32_t max_ctx_len;
int n_kv_groups;
const RadKVGroupBatch* kv; /* [n_kv_groups] */
/* 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* 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:
*
* 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.
*
* 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. */
int32_t draft_pass;
/* Linear-state checkpointing (spec §7.3): tokens at which the scheduler wants a checkpoint
* written, already aligned to the checkpoint interval by the chunk split. */
int n_checkpoints;
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.
*
* 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.
*
* 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.
*
* 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. */
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. */
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.
*
* 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. */
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.
*
* 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.
*
* 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).
*
* 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`). */
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.
*
* [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.
*
* Null when the program declares no encoder: nothing can move a rotary position away from
* the index then, and `positions` is 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. */
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]`.
*
* 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.
*
* 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. */
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 the plugin's declared encoder (rad_declare_encoder)
* and nothing else: no token rows, no KV, no logits. 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.
*
* 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. */
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
* 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;
const int32_t* enc_cu; /* [enc_n_seg + 1] device: segment boundaries in patches */
int32_t enc_max_seg; /* host: the longest segment, which bands the attention */
} RadBatch;
/* ================================================================== 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. */
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 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. */
} RadOperand;
#define RAD_B(h) ((RadOperand){ RAD_OPK_BUF, RAD_DT_INVALID, (h), 0, 0, 0, 0 })
#define RAD_B_AT(h, o) ((RadOperand){ RAD_OPK_BUF, RAD_DT_INVALID, (h), 0, (o), 0, 0 })
#define RAD_B_N(h, o, n) ((RadOperand){ RAD_OPK_BUF, RAD_DT_INVALID, (h), 0, (o), (n), 0 })
/* A column slice: `w` columns starting at column `c`, keeping the buffer's declared width as the
* 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.
*
* 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 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. */
#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. */
#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 })
#define RAD_OPD(...) ((const RadOperand[]){ __VA_ARGS__ }), \
(int)(sizeof((const RadOperand[]){ __VA_ARGS__ }) / sizeof(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.
*
* `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.
*
* 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). */
#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.
*
* 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. */
int rad_lane(RadCtx* c, int lane);
int rad_lane_join(RadCtx* c, int from, int to);
/* Same, with the ranged value taken from the batch. */
#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. */
int rad_step_fail(RadCtx* c, const char* what);
/* ================================================================== run-phase queries */
const RadBatch* rad_batch(RadCtx* c);
int rad_rank(RadCtx* c);
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. */
typedef struct RadRouting {
const int32_t* expert_ids; /* [n_tok, top_k] device */
const float* expert_w; /* [n_tok, top_k] device */
const int32_t* expert_count; /* [n_expert] device: tokens routed to each */
const int32_t* sorted_tok; /* [n_tok * top_k] device: tokens grouped by expert */
const int32_t* expert_offset; /* [n_expert+1] device */
int64_t top_k;
int64_t n_expert;
} RadRouting;
/* Record that this layer's routing lives in these buffers, so the heat engine can read the
* histogram back and the mover can be told what was wanted. The plugin computed them with
* 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. */
int32_t* rad_route_counts(RadCtx* c, int layer, int64_t n_expert);
/* 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. */
void* rad_weight_ptr(RadCtx* c, rad_weight w);
void* rad_buf_ptr(RadCtx* c, rad_buf b);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* RAD_RUNTIME_H */
-135
View File
@@ -1,135 +0,0 @@
/* rad_sample.h -- the per-sequence sampling row, and why it is part of the ABI.
*
* 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.
*
* ============================== 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.
*
* core/sample/sampler.h carries the full schema table this implies; libref implements it.
*/
#ifndef RAD_SAMPLE_H
#define RAD_SAMPLE_H
#include "rad_types.h"
#ifdef __cplusplus
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.
*
* 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. */
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 */
RAD_SP_MASK = 1 << 2, /* a grammar is constraining this sequence this step */
RAD_SP_XTC = 1 << 3,
RAD_SP_DRY = 1 << 4
};
/* 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
* 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`.
*
* `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
* and repeats are not limited. The breakers themselves are resolved against the vocabulary on the
* host, which is also where that limit is found; see `sample_dry`'s optional `breakers` operand
* for the other half. */
typedef struct RadSampleParams {
uint64_t seed; /* the request's seed */
uint64_t pos; /* output position: the RNG's second coordinate */
float temp;
float top_p;
float min_p;
float typical_p;
float rep_penalty;
float freq_penalty;
float pres_penalty;
float xtc_probability;
float xtc_threshold;
float dry_multiplier;
float dry_base;
int32_t top_k;
int32_t penalty_last_n;
int32_t dry_allowed_length;
int32_t dry_penalty_last_n;
int32_t hist_off; /* start of the window within this row's own history row */
int32_t hist_len;
int32_t mask_row; /* row into the bitmask plane, or -1 when unconstrained */
int32_t flags; /* RAD_SP_* */
int32_t dry_rep_limit; /* the breaker-imposed repeat limit, 0 when there is none */
} RadSampleParams;
/* The row is uploaded as an array and addressed as 24 words by every plugin, so its size is fixed
* and every byte of it is a named field. */
#ifdef __cplusplus
static_assert(sizeof(RadSampleParams) == 96, "RadSampleParams is 96 bytes on the wire");
static_assert(offsetof(RadSampleParams, dry_rep_limit) + sizeof(int32_t) == sizeof(RadSampleParams),
"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.
*
* 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
* theirs. Every implementation of a stage takes its key from here. */
#define RAD_SAMPLE_KEY_PICK 0x0ull
#define RAD_SAMPLE_KEY_XTC 0x58544311ull
#define RAD_SAMPLE_KEY_ACCEPT 0x41435054ull
#define RAD_SAMPLE_KEY_RESID 0x52534944ull
static inline uint64_t rad_sample_splitmix64(uint64_t z) {
z += 0x9E3779B97F4A7C15ull;
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull;
z = (z ^ (z >> 27)) * 0x94D049BB133111EBull;
return z ^ (z >> 31);
}
static inline float rad_sample_uniform01(uint64_t seed, uint64_t pos) {
const uint64_t z = rad_sample_splitmix64(seed * 0x9E3779B97F4A7C15ull + pos);
return (float)(uint32_t)(z >> 40) * (1.0f / 16777216.0f);
}
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* RAD_SAMPLE_H */
-376
View File
@@ -1,376 +0,0 @@
/* rad_types.h -- the primitive vocabulary shared by the core, the plugins and the tools.
*
* Pure C. Everything here crosses an .so boundary, so nothing in this file may be a C++ type,
* have a non-trivial layout, or depend on a compiler flag. See spec.md §2.
*/
#ifndef RAD_TYPES_H
#define RAD_TYPES_H
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#ifdef __cplusplus
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. */
enum {
RAD_OK = 0,
RAD_E_SHAPE = -1, /* geometry this instantiation does not serve */
RAD_E_DTYPE = -2,
RAD_E_ALIGN = -3, /* pointer or stride alignment the kernel requires */
RAD_E_STRIDE = -4, /* non-contiguous where contiguity is required */
RAD_E_SCRATCH = -5, /* scratch buffer absent or too small */
RAD_E_NOMEM = -6,
RAD_E_NOKERNEL = -7, /* nothing in the hierarchy resolved */
RAD_E_NOSCHEMA = -8, /* op name has no declared schema */
RAD_E_SCHEMA = -9, /* params do not satisfy the op's schema */
RAD_E_ABI = -10, /* plugin ABI version mismatch */
RAD_E_DUPLICATE = -11, /* two plugins claim the same architecture id / op schema */
RAD_E_INVAL = -12,
RAD_E_IO = -13,
RAD_E_FORMAT = -14, /* container is not a .rad, or is a version we do not read */
RAD_E_DEVICE = -15, /* the device layer refused or faulted */
RAD_E_STATE = -16, /* called in the wrong phase */
RAD_E_NOTFOUND = -17,
RAD_E_UNSUPPORTED = -18,
RAD_E_FULL = -19, /* a pool, arena or table is exhausted */
RAD_E_CANCELLED = -20
};
/* ------------------------------------------------------------------ the helpers, INLINE
*
* WHY EVERY FREE FUNCTION IN THIS HEADER IS A DEFINITION AND NOT A DECLARATION.
*
* 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.
*
* 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. */
static inline const char* rad_strerror(int status) {
switch (status) {
case RAD_OK: return "ok";
case RAD_E_SHAPE: return "shape this kernel does not serve";
case RAD_E_DTYPE: return "dtype this kernel does not serve";
case RAD_E_ALIGN: return "alignment the kernel requires was not met";
case RAD_E_STRIDE: return "non-contiguous operand where contiguity is required";
case RAD_E_SCRATCH: return "scratch buffer absent or too small";
case RAD_E_NOMEM: return "out of memory";
case RAD_E_NOKERNEL: return "no kernel resolved";
case RAD_E_NOSCHEMA: return "op has no declared schema";
case RAD_E_SCHEMA: return "parameters do not satisfy the op schema";
case RAD_E_ABI: return "plugin ABI version mismatch";
case RAD_E_DUPLICATE: return "duplicate registration";
case RAD_E_INVAL: return "invalid argument";
case RAD_E_IO: return "io error";
case RAD_E_FORMAT: return "container format error";
case RAD_E_DEVICE: return "device error";
case RAD_E_STATE: return "called in the wrong phase";
case RAD_E_NOTFOUND: return "not found";
case RAD_E_UNSUPPORTED: return "unsupported";
case RAD_E_FULL: return "pool or table exhausted";
case RAD_E_CANCELLED: return "cancelled";
default: return "unknown error";
}
}
/* ------------------------------------------------------------------ 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 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. */
enum {
RAD_DT_INVALID = 0,
/* float */
RAD_F32 = 1,
RAD_F16 = 2,
RAD_BF16 = 3,
RAD_F8E4M3 = 4,
RAD_F8E5M2 = 5,
/* integer */
RAD_I8 = 8,
RAD_U8 = 9,
RAD_I16 = 10,
RAD_I32 = 11,
RAD_I64 = 12,
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. */
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 */
RAD_U4 = 19, /* 0..15 */
RAD_U2 = 20, /* 0..3 */
RAD_E8M0 = 21, /* OCP E8M0: 2^(e-127), 0xFF is nan -- an MX block's shared scale */
RAD_U1 = 22, /* a bit: a sign plane, a binary code */
RAD_I3 = 23,
RAD_U3 = 24,
RAD_I5 = 25,
RAD_U5 = 26,
RAD_I6 = 27, /* also the K-quants' 6-bit scale with its offset removed */
RAD_U6 = 28,
RAD_I7 = 29,
RAD_U7 = 30,
RAD_U9 = 31, /* 9- to 12-bit unsigned: lattice grid indices (IQ3_S, IQ2_S, IQ1_S) */
RAD_U10 = 32,
RAD_U11 = 33,
RAD_U12 = 34,
RAD_FP6E2M3 = 35, /* OCP FP6: 1-2-3, bias 1, no inf or nan, max 7.5 */
RAD_FP6E3M2 = 36, /* OCP FP6: 1-3-2, bias 3, no inf or nan, max 28 */
RAD_U16 = 37,
RAD_DT_PLUGIN_BASE = 256
};
/* THE DTYPE TABLE, and it lives in the header for the reason the block above rad_strerror gives.
*
* 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. */
typedef struct RadDtRow { uint32_t dt; const char* name; int bits; } RadDtRow;
static const RadDtRow rad_dt_table[] = {
{ RAD_F32, "f32", 32 },
{ RAD_F16, "f16", 16 },
{ RAD_BF16, "bf16", 16 },
{ RAD_F8E4M3, "fp8_e4m3", 8 },
{ RAD_F8E5M2, "fp8_e5m2", 8 },
{ RAD_I8, "i8", 8 },
{ RAD_U8, "u8", 8 },
{ RAD_I16, "i16", 16 },
{ RAD_I32, "i32", 32 },
{ RAD_I64, "i64", 64 },
{ RAD_U32, "u32", 32 },
{ RAD_BOOL, "bool", 8 },
{ RAD_I4, "i4", 4 },
{ RAD_I2, "i2", 2 },
{ RAD_FP4E2M1, "fp4_e2m1", 4 },
{ RAD_U4, "u4", 4 },
{ RAD_U2, "u2", 2 },
{ RAD_E8M0, "e8m0", 8 },
{ RAD_U1, "u1", 1 },
{ RAD_I3, "i3", 3 },
{ RAD_U3, "u3", 3 },
{ RAD_I5, "i5", 5 },
{ RAD_U5, "u5", 5 },
{ RAD_I6, "i6", 6 },
{ RAD_U6, "u6", 6 },
{ RAD_I7, "i7", 7 },
{ RAD_U7, "u7", 7 },
{ RAD_U9, "u9", 9 },
{ RAD_U10, "u10", 10 },
{ RAD_U11, "u11", 11 },
{ RAD_U12, "u12", 12 },
{ RAD_FP6E2M3, "fp6_e2m3", 6 },
{ RAD_FP6E3M2, "fp6_e3m2", 6 },
{ RAD_U16, "u16", 16 },
};
enum { RAD_DT_TABLE_N = (int)(sizeof(rad_dt_table) / sizeof(rad_dt_table[0])) };
/* Bits per logical element. Returns 0 for a plugin-private dtype -- the plugin sizes those. */
static inline int rad_dtype_bits(uint32_t dtype) {
for (int i = 0; i < RAD_DT_TABLE_N; ++i)
if (rad_dt_table[i].dt == dtype) return rad_dt_table[i].bits;
return 0;
}
static inline const char* rad_dtype_name(uint32_t dtype) {
for (int i = 0; i < RAD_DT_TABLE_N; ++i)
if (rad_dt_table[i].dt == dtype) return rad_dt_table[i].name;
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. */
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)
if (strcmp(rad_dt_table[i].name, name) == 0) return rad_dt_table[i].dt;
if (!strcmp(name, "float32") || !strcmp(name, "fp32")) return RAD_F32;
if (!strcmp(name, "float16") || !strcmp(name, "fp16") || !strcmp(name, "half")) return RAD_F16;
if (!strcmp(name, "bfloat16")) return RAD_BF16;
if (!strcmp(name, "e4m3") || !strcmp(name, "fp8")) return RAD_F8E4M3;
if (!strcmp(name, "e5m2")) return RAD_F8E5M2;
if (!strcmp(name, "int8")) return RAD_I8;
if (!strcmp(name, "int32")) return RAD_I32;
return RAD_DT_INVALID;
}
/* Byte size of n elements, rounding up. 0 if the dtype is plugin-private. */
static inline int64_t rad_dtype_bytes(uint32_t dtype, int64_t n) {
const int bits = rad_dtype_bits(dtype);
if (bits == 0) return 0;
return ((int64_t)bits * n + 7) / 8;
}
/* ------------------------------------------------------------------ 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. */
typedef struct RadTensor {
void* data;
uint32_t dtype;
uint32_t rank;
int64_t shape [RAD_MAX_RANK];
int64_t stride[RAD_MAX_RANK];
} RadTensor;
static inline int64_t rad_tensor_numel(const RadTensor* t) {
if (!t || t->rank == 0) return 0;
int64_t n = 1;
for (uint32_t i = 0; i < t->rank; ++i) n *= t->shape[i];
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. */
static inline int rad_tensor_is_contiguous(const RadTensor* t) {
if (!t || t->rank == 0) return 1;
int64_t acc = 1;
for (int i = (int)t->rank - 1; i >= 0; --i) {
if (t->shape[i] != 1 && t->stride[i] != acc) return 0;
acc *= t->shape[i];
}
return 1;
}
/* Fill strides for a dense row-major tensor whose shape and rank are already set. */
static inline void rad_tensor_pack(RadTensor* t) {
if (!t || t->rank == 0) return;
int64_t acc = 1;
for (int i = (int)t->rank - 1; i >= 0; --i) { t->stride[i] = acc; acc *= t->shape[i]; }
}
/* ------------------------------------------------------------------ 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. */
enum { RAD_P_INT = 1, RAD_P_STR = 2, RAD_P_RANGE = 3, RAD_P_F64 = 4 };
typedef struct RadParam {
const char* key;
int kind; /* RAD_P_INT | RAD_P_STR | RAD_P_RANGE | RAD_P_F64 */
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. */
} RadParam;
/* Builders. RAD_PARAMS below wraps these into a positional list. */
#define RAD_INT(k, v) ((RadParam){ (k), RAD_P_INT, (long long)(v), 0, 0, 0.0 })
#define RAD_STR(k, v) ((RadParam){ (k), RAD_P_STR, 0, 0, (v), 0.0 })
#define RAD_F64(k, v) ((RadParam){ (k), RAD_P_F64, 0, 0, 0, (double)(v) })
#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. */
enum { RAD_C_EQ = 0, RAD_C_LE = 1, RAD_C_GE = 2, RAD_C_DIV = 3, RAD_C_IN = 4 };
typedef struct RadConstraint {
const char* key;
int op;
long long ival; /* EQ / LE / GE / DIV */
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.
*
* 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. */
#define RAD_DEVICE_FACT_PREFIX "device."
#define RAD_FACT_P2P "device.p2p"
#define RAD_C(k, o, v) { (k), (o), (long long)(v), 0 }
#define RAD_CEQ(k, v) { (k), RAD_C_EQ, (long long)(v), 0 }
#define RAD_CLE(k, v) { (k), RAD_C_LE, (long long)(v), 0 }
#define RAD_CGE(k, v) { (k), RAD_C_GE, (long long)(v), 0 }
#define RAD_CDIV(k, v) { (k), RAD_C_DIV, (long long)(v), 0 }
#define RAD_CIN(k, s) { (k), RAD_C_IN, 0, (s) }
/* ------------------------------------------------------------------ handles */
/* Opaque, dense, small. A handle is an index into a core-owned table; zero is never a valid
* handle, so a zeroed struct is an unset one and a failed decl_* is falsy. */
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. */
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. */
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
#endif /* RAD_TYPES_H */
-72
View File
@@ -1,72 +0,0 @@
# Architecture plugins. One directory each, one .so each, linking only rad_abi -- an architecture
# plugin does not link 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.
#
# 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.
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 <include>/radiance/arch/, so a
# plugin built against an installed radiance writes `#include <arch/rad_arch.h>`; 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.
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)
file(CREATE_LINK ${CMAKE_CURRENT_SOURCE_DIR}/common ${RAD_ARCH_INCLUDE_ROOT}/arch SYMBOLIC)
endif()
target_include_directories(rad_abi INTERFACE $<BUILD_INTERFACE:${RAD_ARCH_INCLUDE_ROOT}>)
foreach(d ${RAD_ARCH_DIRS})
if(NOT IS_DIRECTORY ${d})
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.
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.
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.
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.
#
# 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 <arch/rad_arch.h>` -- see RAD_ARCH_INCLUDE_ROOT above for how that resolves
# here.
install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/common/
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/radiance/arch
FILES_MATCHING PATTERN "*.h")
File diff suppressed because it is too large. Load diff
-236
View File
@@ -1,236 +0,0 @@
/* rad_block_attn_fp8.h -- the PLAIN GQA attention block 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:
*
* - 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.
*
* 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.
*
* 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.
*
* 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.
*/
#ifndef RAD_BLOCK_ATTN_FP8_H
#define RAD_BLOCK_ATTN_FP8_H
#include "rad_fp8.h"
#include <cstdlib>
#include <cstring>
namespace rad {
namespace arch {
struct AttnFP8 {
struct Wire {
rad_buf x = 0; /* [max_tok, n_embd] the residual stream */
ActFP8 h{}; /* [max_tok, n_embd] normed input, then the o output */
rad_buf qkv = 0; /* [max_tok, q_dim + 2*kv_dim] the fused projection */
rad_buf q = 0; /* [max_tok, q_dim] the query, CONTIGUOUS */
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. */
struct Src {
const char* norm = nullptr;
const char* q = nullptr;
const char* k = nullptr;
const char* v = nullptr;
const char* o = nullptr;
};
Geom g{};
Wire w{};
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. */
const char* mode = "neox";
rad_weight w_norm = 0;
LinearFP8 qkv{}, o{};
NormQuantFP8 nq_h{};
QuantFP8 q_attn{};
rad_op op_rope = 0, op_qlift = 0, op_attn = 0, op_kv_store = 0;
rad_op op_ar = 0, op_add = 0;
bool ar_out = false;
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;
};
inline int AttnFP8::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, bool add_out, int ar_in, bool ar_out_) {
g = geom; w = wire; layer = l;
ar_out = ar_out_; kv = group; n_rot = rotary_dim;
const int64_t q_dim = g.q_dim();
const int64_t kv_dim = g.kv_dim();
if (n_rot <= 0 || n_rot > g.head_dim || (n_rot & 1)) {
fprintf(stderr, "radiance: rotary_dim %lld is not an even width inside head_dim %lld\n",
(long long)n_rot, (long long)g.head_dim);
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. */
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;
}
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l), src.norm));
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. */
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, RAD_OP(b, "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),
{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. */
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. */
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.x});
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.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. */
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));
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.x}, {w.h.x});
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),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.x, w.h.x}, {w.x});
return RAD_OK;
}
inline void AttnFP8::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 int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim();
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));
/* k and v are COLUMN SLICES of the same 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));
RAD_ISSUE(c, op_qlift, bcol(w.qkv, 0, q_dim, T), brows(w.q, T));
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.x, T));
q_attn.step(c, T);
o.step(c, w.attn, w.h.x, T);
if (op_ar && !(ar_out && ar_fused_ok(g, T)))
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));
}
} /* namespace arch */
} /* namespace rad */
#endif /* RAD_BLOCK_ATTN_FP8_H */
-384
View File
@@ -1,384 +0,0 @@
/* rad_block_attn_gated.h -- one GATED grouped-query attention block, 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
*
* This is Qwen3.5's attention and not Qwen3's, and the difference is not a flag:
*
* * `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.
*
* 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.
*/
#ifndef RAD_BLOCK_ATTN_GATED_H
#define RAD_BLOCK_ATTN_GATED_H
#include "rad_arch.h"
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. */
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 qg = 0; /* [max_tok, n_head, 2*head_dim] query and gate, interleaved */
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 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. */
struct Src {
const char* norm = nullptr; /* input_layernorm.weight */
const char* qg = nullptr; /* self_attn.q_proj.weight -- query AND gate */
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;
int64_t n_rot = 0; /* partial rotary: the leading n_rot of head_dim */
const char* mode = "mrope";
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_attn = 0, op_kv_store = 0, op_sigmoid = 0, op_gate = 0;
rad_op op_o = 0, op_ar = 0, op_add = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup group,
int64_t rotary_dim, const Wire& wire, const Src& src);
void step(RadCtx* c, const RadBatch* batch) const;
};
inline int AttnGatedBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
rad_kvgroup group, int64_t rotary_dim, const Wire& wire,
const Src& src) {
g = geom; w = wire; layer = l; kv = group; n_rot = rotary_dim;
const int64_t q_dim = g.q_dim();
const int64_t kv_dim = g.kv_dim();
const int64_t qg_dim = 2 * q_dim; /* query and gate, one per head, interleaved */
if (n_rot <= 0 || n_rot > g.head_dim || (n_rot & 1)) {
fprintf(stderr, "radiance: rotary_dim %lld is not an even width inside head_dim %lld\n",
(long long)n_rot, (long long)g.head_dim);
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. */
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 "
"span passed to its k/v weights.\n", __func__, g.world,
(long long)g.n_head_kv_all);
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.
*
* 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. */
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));
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_qg = decl_w(b, nm.f("blk.%d.attn_qg.weight", l), RAD_BF16, {qg_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 vector shared by every head, so it is replicated across ranks even 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));
/* ---- 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. */
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_qg = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", qg_dim),
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_qg)),
{w.h}, {w.qg});
op_kp = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", kv_dim),
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_k)),
{w.h}, {w.k});
op_vp = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", kv_dim),
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
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 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.
*
* 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 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.
*
* 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. */
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. */
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. */
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}, {});
/* 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. */
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});
op_gate = 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, w.gate}, {w.attn});
op_o = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", g.n_embd),
RAD_INT("K", q_dim), RAD_STR("dtype", g.dtype)),
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. */
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 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. */
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;
RAD_ISSUE(c, op_norm, brows(w.x, T), RAD_W(w_norm), brows(w.h, T));
RAD_ISSUE(c, op_qg, brows(w.h, T), RAD_W(w_qg), brows(w.qg, T));
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));
}
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. */
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. */
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));
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));
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_GATED_H */
-568
View File
@@ -1,568 +0,0 @@
/* rad_block_attn_gated_fp8.h -- the gated GQA block 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.
*
* What differs:
*
* - 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.
*/
#ifndef RAD_BLOCK_ATTN_GATED_FP8_H
#define RAD_BLOCK_ATTN_GATED_FP8_H
#include "rad_fp8.h"
#include <cstdlib>
#include <cstring>
namespace rad {
namespace arch {
struct AttnGatedFP8 {
struct Wire {
rad_buf x = 0; /* [max_tok, n_embd] the residual stream */
ActFP8 h{}; /* [max_tok, n_embd] normed input, then the o output */
rad_buf qg = 0; /* [max_tok, n_head, 2*head_dim] query and gate, interleaved */
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. */
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. */
rad_buf gate = 0;
};
struct Src {
const char* norm = nullptr;
const char* qg = nullptr; /* self_attn.q_proj.weight -- query AND gate */
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;
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. */
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. */
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. */
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. */
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. */
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. */
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 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. */
const char* mode = "mrope";
rad_weight w_norm = 0, w_q_norm = 0, w_k_norm = 0;
/* The input was normed and quantised by the caller; this block declares no norm. */
bool ext_in = false;
LinearFP8 qg{}, kp{}, vp{}, o{};
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_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 */
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. */
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). */
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. */
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;
};
inline int AttnGatedFP8::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, bool add_out,
int ar_in, bool ar_out_) {
g = geom; w = wire; layer = l;
ar_out = ar_out_; kv = group; n_rot = rotary_dim;
const int64_t q_dim = g.q_dim();
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. */
const bool kv_spanned = g.world > g.n_head_kv_all;
const int64_t kv_span_lo = kv_spanned ? g.kv_off : 0;
const int64_t kv_span_hi = kv_spanned ? g.kv_off + kv_dim : 0;
if (n_rot <= 0 || n_rot > g.head_dim || (n_rot & 1)) {
fprintf(stderr, "radiance: rotary_dim %lld is not an even width inside head_dim %lld\n",
(long long)n_rot, (long long)g.head_dim);
return RAD_E_INVAL;
}
/* 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`). */
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;
if (g.w_bf16 && !w.gate) return RAD_E_INVAL;
} else {
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l), src.norm));
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));
}
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));
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));
/* One norm, one quantise, three consumers -- and one op, see rad_fp8.h's 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));
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));
RAD_ARCH_TRY(kp.declare(b, nm, g, nm.f("blk.%d.attn_k", l), kv_dim, g.n_embd,
RAD_SHARD_ROW, grp_layer(l), { src.k }, w.h, w.k,
0, {}, kv_span_lo, kv_span_hi));
RAD_ARCH_TRY(vp.declare(b, nm, g, nm.f("blk.%d.attn_v", l), kv_dim, g.n_embd,
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.
*
* 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.
*
* 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.
*
* 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. */
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)
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),
RAD_INT("n_head_kv", g.n_head_kv), RAD_INT("rot", n_rot),
RAD_STR("q_dtype", g.dtype), RAD_F64("eps", g.eps),
RAD_F64("wadd", g.wadd_qk), RAD_INT("cs_f32", 1)),
RAD_WEIGHTS(w_q_norm, w_k_norm)),
{w.qg, w.k, w.cos_sin}, {w.q, w.k});
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});
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});
/* 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. */
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. */
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. */
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);
rad_op_writes(b, op_attn, &w.attn.x, 1);
}
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}, {});
/* 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)
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),
RAD_INT("n_head_kv", g.n_head_kv), RAD_INT("rot", n_rot),
RAD_STR("q_dtype", g.dtype), RAD_F64("eps", g.eps),
RAD_F64("wadd", g.wadd_qk), RAD_INT("cs_f32", 1),
RAD_INT("block_size", rad_kv_block_size(b, kv)),
RAD_STR("kv_dtype", g.kv_dtype)),
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.
*
* 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) {
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});
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});
/* 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) {
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),
RAD_INT("window", 0), RAD_INT("n_head", g.n_head),
RAD_INT("block_size", rad_kv_block_size(b, kv)),
RAD_INT("max_seqs", qsa_gq_rows()),
RAD_INT("max_ctx", g.max_ctx),
RAD_STR("q_dtype", g.dtype),
RAD_STR("kv_dtype", g.kv_dtype),
RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("act", "sigmoid")),
RAD_NOWEIGHTS);
if (op_attn_gq) {
const rad_buf rd[4] = { w.q, qsa_sel, qsa_sequ, w.qg };
const rad_buf wr[3] = { w.attn.x, w.attn.cq(), w.attn.cs() };
RAD_ARCH_TRY(rad_op_reads (b, op_attn_gq, rd, 4));
RAD_ARCH_TRY(rad_op_writes(b, op_attn_gq, wr, 3));
}
}
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));
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.x}, {w.h.x});
/* Only where the NEXT block's norm will not do it; see rad_fp8.h's 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),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.x, w.h.x}, {w.x});
return RAD_OK;
}
inline void AttnGatedFP8::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;
if (!ext_in) nq_h.step(c, T);
qg.step(c, w.h, w.qg, T);
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. */
const bool fuse_ok = T <= fused_rows && !rope_mixed(batch);
const bool fused_kv = op_fused_kv && fuse_ok;
if (fused_kv) {
RAD_ISSUE_N(c, op_fused_kv, T,
brows(w.qg, T), brows(w.k, T), RAD_B(w.cos_sin), rope_pos1(batch, T),
RAD_W(w_q_norm), RAD_W(w_k_norm),
brows(w.q, T), brows(w.k, T), RAD_NONE,
brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer));
} else if (op_fused && fuse_ok) {
RAD_ISSUE_N(c, op_fused, T,
brows(w.qg, T), brows(w.k, T), RAD_B(w.cos_sin), rope_pos1(batch, T),
RAD_W(w_q_norm), RAD_W(w_k_norm),
brows(w.q, T), brows(w.k, T), RAD_NONE);
} else {
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));
}
if (!fused_kv)
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.
*
* 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.
*
* 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. */
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;
if (gated) {
const int64_t chunk = qsa_gq_rows();
const int64_t qw = g.q_dim(), hd = g.head_dim;
for (int64_t off = 0; off < T; off += chunk) {
const int64_t rows = (T - off) < chunk ? (T - 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)));
}
} else if (sparse) {
const int64_t chunk = qsa_rows();
const int64_t qw = g.q_dim();
for (int64_t off = 0; off < T; off += chunk) {
const int64_t rows = (T - off) < chunk ? (T - off) : chunk;
RAD_ISSUE_N(c, op_attn, 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));
}
} else {
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. */
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
brows(w.attn.x, T));
}
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)
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))
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));
}
} /* namespace arch */
} /* namespace rad */
#endif /* RAD_BLOCK_ATTN_GATED_FP8_H */
-999
View File
@@ -1,999 +0,0 @@
/* rad_block_dflash2.h -- the DFlash2 block-diffusion drafter, bf16.
*
* ============================== WHAT IT IS ==============================
*
* 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 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.
*
* 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.
*
* ============================== 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:
*
* 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 QUERY PASS, one row a draft position, `block` = 1 + n_spec of them a sequence:
*
* x = embed(anchor, mask, mask, ...)
* for each layer:
* h = attn_norm(x); coef = attn_conv_proj(h)
* h = dflash_conv(h, coef[0:taps*NG], attn_conv_base[0]) <- prepare
* h = o_proj(attention(q_proj(h), kv_proj(h))) <- non-causal, windowed
* h = dflash_conv(h, coef[taps*NG:], attn_conv_base[1]); x += h <- finish
* h = ffn_norm(x); coef = ffn_conv_proj(h)
* h = dflash_conv(h, coef[0:taps*NG], ffn_conv_base[0])
* h = down(silu_mul(gate_up(h)))
* 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:
*
* cand, unary = top_k(draft_head(x)) the candidates and their logits
* hp = hidden_projection(x) the selector's query, rank 256
* tokens = dflash_select(cand, unary, hp, anchor, predecessor, successor)
*
* ============================== 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 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. Here it 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 NORMS ARE PLAIN ==============================
*
* `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.
*
* ============================== 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.
*
* THREE THINGS ARE REPLICATED AND EACH IS A DECISION:
*
* 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.
*
* ============================== 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.
*/
#ifndef RAD_BLOCK_DFLASH2_H
#define RAD_BLOCK_DFLASH2_H
#include "rad_arch.h"
#include "rad_fp8.h"
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. */
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;
o.rows = n;
return o;
}
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. */
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 */
int64_t taps = 2; /* the convolution's */
int64_t group = 16;
int64_t sel_rank = 256; /* the codebooks' width */
int64_t sel_topk = 16; /* candidates kept per position */
int64_t window = 0; /* sliding attention width, 0 for none */
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. */
int64_t coef_dim(int64_t n_embd) const { return 2 * taps * ng(n_embd); }
};
struct Wire {
/* 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. */
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 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 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. */
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) */
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 */
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, 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. */
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 */
};
/* 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. */
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. */
static int64_t head_rows(const Geom& g) { return vocab_head_rows(g); }
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 */
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 AND THE CHECKPOINT IS BF16. rad_fp8.h's DenseFP8 declares each as
* block fp8 and the recipe makes it so -- 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.
* 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. */
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 */
/* 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. */
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]{};
rad_weight w_acp[MAX_LAYERS] = {}, w_acb[MAX_LAYERS] = {};
rad_weight w_fcp[MAX_LAYERS] = {}, w_fcb[MAX_LAYERS] = {};
/* context-pass ops */
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 */
/* 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. */
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] = {};
rad_op op_qp[MAX_LAYERS] = {}, op_kp[MAX_LAYERS] = {}, op_vp[MAX_LAYERS] = {};
rad_op op_op[MAX_LAYERS] = {};
rad_op op_qn[MAX_LAYERS] = {}, op_kn[MAX_LAYERS] = {};
rad_op op_gu[MAX_LAYERS] = {}, op_dn[MAX_LAYERS] = {};
rad_op op_gug[MAX_LAYERS] = {}; /* the gate_up|silu|quant fold; 0 when nothing serves it */
rad_op op_aconv[MAX_LAYERS] = {}, op_fconv[MAX_LAYERS] = {};
rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn = 0;
rad_op op_act = 0, op_ar = 0, op_add = 0, op_final = 0;
/* head and selector */
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_hp = 0, op_sel = 0;
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. */
void context(RadCtx* c, const RadBatch* batch) const;
/* The query pass and the selector, one call, `block` rows a sequence. */
void step(RadCtx* c, const RadBatch* batch) const;
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; }
};
/* ------------------------------------------------------------------------------ declare */
inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c,
int base_layer, rad_kvgroup group, rad_weight tok_embd,
const char* ck, const char* ck_lm, const Wire& wire) {
g = geom; cfg = c; w = wire; first_layer = base_layer; kv = group; w_tok = tok_embd;
if (!ck || !ck_lm || !w_tok) return RAD_E_INVAL;
if (g.n_layer <= 0 || g.n_layer > MAX_LAYERS) {
fprintf(stderr, "radiance: dflash2 has %lld layers; this block carries at most %d\n",
(long long)g.n_layer, MAX_LAYERS);
return RAD_E_UNSUPPORTED;
}
if (cfg.block < 2 || cfg.n_taps <= 0 || cfg.sel_rank <= 0 || cfg.sel_topk <= 0)
return RAD_E_INVAL;
const int64_t NG = cfg.ng(g.n_embd);
const int64_t CD = cfg.coef_dim(g.n_embd);
const int64_t qd = q_dim(), kvd = kv_dim();
crows = g.max_tok;
qrows = g.max_seqs * cfg.block;
if (qrows > g.max_tok) qrows = g.max_tok;
srows = g.max_seqs * cfg.steps();
if (qrows <= 0 || srows <= 0) return RAD_E_INVAL;
/* ---------------------------------------------------------------- model-scope weights */
RAD_ARCH_TRY(w_fc.declare(b, nm, nm.f("dflash.fc"), g.n_embd, cfg.n_taps * g.n_embd,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model(),
{ nm.ckpt("%s.fc.weight", ck) }));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.hidden_norm.weight"), nm.ckpt("%s.hidden_norm.weight", ck)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.norm.weight"), nm.ckpt("%s.norm.weight", ck)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.sel_proj.weight"),
nm.ckpt("%s.candidate_selector.hidden_projection.weight", ck)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.sel_pred"),
nm.ckpt("%s.candidate_selector.predecessor_codebook", ck)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.sel_succ"),
nm.ckpt("%s.candidate_selector.successor_codebook", ck)));
w_hnorm = decl_w(b, nm.f("dflash.hidden_norm.weight"), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
w_norm = decl_w(b, nm.f("dflash.norm.weight"), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
w_selp = decl_w(b, nm.f("dflash.sel_proj.weight"), RAD_BF16, {cfg.sel_rank, g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
w_pred = decl_w(b, nm.f("dflash.sel_pred"), RAD_BF16, {g.n_vocab_all, cfg.sel_rank},
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
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.
*
* 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. */
enum { DF_W2_GROUP = 128 };
const bool dh_shard = head_sharded(g);
const int dh_split = dh_shard ? RAD_SHARD_ROW : RAD_SHARD_NONE;
const char* dhn = nm.f("dflash.draft_head.weight");
RAD_ARCH_TRY(map_copy(b, dhn, ck_lm));
w_dh = decl_view(b, dhn, nullptr, "codes", RAD_U2, {head_rows(g), g.n_embd},
RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
w_dhs = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale,zero", RAD_F16,
{head_rows(g), g.n_embd}, RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
if (!w_dh || !w_dhs) return RAD_E_INVAL;
/* ---------------------------------------------------------------- per-layer weights */
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_norm.weight", i),
nm.ckpt("%s.layers.%d.input_layernorm.weight", ck, i)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.ffn_norm.weight", i),
nm.ckpt("%s.layers.%d.post_attention_layernorm.weight", ck, i)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_q_norm.weight", i),
nm.ckpt("%s.layers.%d.self_attn.q_norm.weight", ck, i)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_k_norm.weight", i),
nm.ckpt("%s.layers.%d.self_attn.k_norm.weight", ck, i)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_conv_proj.weight", i),
nm.ckpt("%s.layers.%d.attention_conv.kernel_projection.weight", ck, i)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_conv_base", i),
nm.ckpt("%s.layers.%d.attention_conv.base_kernel", ck, i)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.ffn_conv_proj.weight", i),
nm.ckpt("%s.layers.%d.mlp_conv.kernel_projection.weight", ck, i)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.ffn_conv_base", i),
nm.ckpt("%s.layers.%d.mlp_conv.base_kernel", ck, i)));
w_anorm[i] = decl_w(b, nm.f("dflash.blk.%d.attn_norm.weight", i), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(first_layer + i));
w_fnorm[i] = decl_w(b, nm.f("dflash.blk.%d.ffn_norm.weight", i), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(first_layer + i));
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. */
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) }));
RAD_ARCH_TRY(w_v[i].declare(b, nm, nm.f("dflash.blk.%d.attn_v", i), kvd, g.n_embd,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(first_layer + i),
{ nm.ckpt("%s.layers.%d.self_attn.v_proj.weight", ck, i) }));
w_qn[i] = decl_w(b, nm.f("dflash.blk.%d.attn_q_norm.weight", i), RAD_F32, {g.head_dim},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(first_layer + i));
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, grp_layer(first_layer + i));
RAD_ARCH_TRY(w_o[i].declare(b, nm, nm.f("dflash.blk.%d.attn_output", i), g.n_embd, qd,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, grp_layer(first_layer + i),
{ nm.ckpt("%s.layers.%d.self_attn.o_proj.weight", ck, i) }));
RAD_ARCH_TRY(w_gu[i].declare(b, nm, nm.f("dflash.blk.%d.ffn_gate_up", i),
2 * g.n_ff, g.n_embd,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(first_layer + i),
{ nm.ckpt("%s.layers.%d.mlp.gate_proj.weight", ck, i),
nm.ckpt("%s.layers.%d.mlp.up_proj.weight", ck, i) },
{ g.n_ff, g.n_ff }));
RAD_ARCH_TRY(w_dn[i].declare(b, nm, nm.f("dflash.blk.%d.ffn_down", i), g.n_embd, g.n_ff,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, grp_layer(first_layer + i),
{ nm.ckpt("%s.layers.%d.mlp.down_proj.weight", ck, i) }));
w_acp[i] = decl_w(b, nm.f("dflash.blk.%d.attn_conv_proj.weight", i), RAD_BF16,
{CD, g.n_embd}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(first_layer + i));
w_acb[i] = decl_w(b, nm.f("dflash.blk.%d.attn_conv_base", i), RAD_BF16,
{2, cfg.taps, g.n_embd}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(first_layer + i));
w_fcp[i] = decl_w(b, nm.f("dflash.blk.%d.ffn_conv_proj.weight", i), RAD_BF16,
{CD, g.n_embd}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(first_layer + i));
w_fcb[i] = decl_w(b, nm.f("dflash.blk.%d.ffn_conv_base", i), RAD_BF16,
{2, cfg.taps, g.n_embd}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(first_layer + i));
}
/* 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.
*
* 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. */
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),
RAD_INT("window", cfg.window), 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});
/* ---------------------------------------------------------------- the context pass */
/* EVERY LINEAR HERE IS `fp8a8`, and every activation that feeds one gets a `quant_act_fp8` in
* front of it. The 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.
*
* 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. */
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 = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("N", g.n_embd),
RAD_INT("K", cfg.n_taps * g.n_embd),
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. */
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. */
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)),
RAD_NOWEIGHTS),
{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. */
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),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_k[i].w, w_k[i].s)),
{w.cq, w.cs}, {w.ck});
op_cv[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),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_v[i].w, w_v[i].s)),
{w.cq, w.cs}, {w.cv});
op_cknorm[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, crows * 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_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, RAD_OP(b, "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});
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),
RAD_INT("block_size", rad_kv_block_size(b, kv)),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{w.ck, w.cv}, {});
/* ---------------------------------------------------------------- the query pass */
op_embed = rw(b, RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), 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(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. */
if (g.world > 1)
op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", g.n_embd, qrows * g.n_embd),
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. */
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)),
RAD_NOWEIGHTS),
{w.h2}, {w.h2q, w.h2s});
op_qat = rw(b, RAD_OP(b, "quant_act_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", qd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.attn}, {w.atq, w.ats});
op_qff = rw(b, RAD_OP(b, "quant_act_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.ffn}, {w.ffq, w.ffs});
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
op_anorm[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_anorm[i])),
{w.x}, {w.h});
op_acoef[i] = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", CD),
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_acp[i])),
{w.h}, {w.coef});
op_qp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", qd),
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_q[i].w, w_q[i].s)),
{w.h2q, w.h2s}, {w.q});
op_kp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", kvd),
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_k[i].w, w_k[i].s)),
{w.h2q, w.h2s}, {w.k});
op_vp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", kvd),
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_v[i].w, w_v[i].s)),
{w.h2q, w.h2s}, {w.v});
op_qn[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows * 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_qn[i])),
{w.q}, {w.q});
op_kn[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows * 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_kn[i])),
{w.k}, {w.k});
op_op[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", qd), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_o[i].w, w_o[i].s)),
{w.atq, w.ats}, {w.h});
op_fnorm[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_fnorm[i])),
{w.x}, {w.h});
op_fcoef[i] = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", CD),
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_fcp[i])),
{w.h}, {w.coef});
op_gu[i] = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", 2 * g.n_ff),
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_gu[i].w, w_gu[i].s)),
{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) {
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;
}
}
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),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_dn[i].w, w_dn[i].s)),
{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.
*
* 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. */
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",
RAD_PARAMS(RAD_RANGE("T", 1, qrows), RAD_INT("hidden_size", g.n_embd),
RAD_INT("taps", cfg.taps), RAD_INT("group_size", cfg.group),
RAD_INT("NG", NG), RAD_INT("block_size", cfg.block),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_acb[i])),
{w.h, w.coef}, {w.h2});
op_fconv[i] = rw(b, RAD_OP(b, "dflash_conv",
RAD_PARAMS(RAD_RANGE("T", 1, qrows), RAD_INT("hidden_size", g.n_embd),
RAD_INT("taps", cfg.taps), RAD_INT("group_size", cfg.group),
RAD_INT("NG", NG), RAD_INT("block_size", cfg.block),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_fcb[i])),
{w.h, w.coef}, {w.h2});
}
op_qrope = rw(b, RAD_OP(b, "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, RAD_OP(b, "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});
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),
RAD_INT("block_size", rad_kv_block_size(b, kv)),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{w.k, w.v}, {});
op_act = rw(b, RAD_OP(b, "silu_mul",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.gate_up}, {w.ffn});
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, qrows * 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, qrows), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.x, w.h2}, {w.x});
op_final = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), 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});
/* ---------------------------------------------------------------- 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 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. */
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});
op_dquant = rw(b, RAD_OP(b, "quant_act_i8",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd),
RAD_INT("group", DF_W2_GROUP), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.sel_h}, {w.dq, w.ds, w.dsum});
op_dlogits = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)),
RAD_INT("K", g.n_embd), RAD_INT("group", DF_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, 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. */
op_dtopk = dh_shard
? rw(b, RAD_OP(b, "row_topk",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)),
RAD_INT("R", cfg.sel_topk), RAD_INT("vocab_off", g.vocab_off),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.dlog}, {w.cand, w.unary, w.dpair})
: rw(b, RAD_OP(b, "row_topk",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)),
RAD_INT("R", cfg.sel_topk), RAD_STR("dtype", g.dtype)),
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 same reason the sampler's own
* candidate gather carries `row`. */
op_dgather = rw(b, RAD_OP(b, "all_gather",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_INT("numel", srows * cfg.sel_topk * 2),
RAD_STR("dtype", "f32"),
RAD_INT("row", cfg.sel_topk * 2)),
RAD_NOWEIGHTS),
{w.dpair}, {w.dgath});
op_dmerge = rw(b, RAD_OP(b, "row_topk_merge",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("R", cfg.sel_topk),
RAD_INT("world_size", g.world),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.dgath}, {w.cand, w.unary});
}
op_hp = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", cfg.sel_rank),
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. */
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),
RAD_INT("n_vocab", g.n_vocab_all),
RAD_INT("anchor_stride", cfg.block), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_pred, w_succ)),
{w.cand, w.unary, w.hp}, {w.tokens});
return RAD_OK;
}
/* ------------------------------------------------------------------------------ the context pass */
inline void Dflash2::context(RadCtx* c, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
if (T <= 0) return;
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. */
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, RAD_NONE);
RAD_ISSUE_N(c, op_cnorm, T, brows(w.c, T), RAD_W(w_hnorm), brows(w.c, T));
RAD_ISSUE_N(c, op_qc, T, brows(w.c, T), brows(w.cq, T), brows(w.cs, T));
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
RAD_ISSUE_N(c, op_ck[i], T, brows(w.cq, T), brows(w.cs, T),
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.ck, T), RAD_NONE, RAD_NONE);
RAD_ISSUE_N(c, op_cv[i], T, brows(w.cq, T), brows(w.cs, T),
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.cv, T), RAD_NONE, RAD_NONE);
RAD_ISSUE_N(c, op_cknorm[i], T * g.n_head_kv,
brows(w.ck, T), RAD_W(w_kn[i]), brows(w.ck, T));
RAD_ISSUE_N(c, op_crope, T, brows(w.ck, T), praw(batch->positions, RAD_I32, T));
RAD_ISSUE_N(c, op_cstore, T, brows(w.ck, T), brows(w.cv, T),
praw(slot, RAD_I32, T), kv_cache(kv, first_layer + i));
}
}
/* ------------------------------------------------------------------------------ the query pass */
inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
if (T <= 0) return;
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 NG = cfg.ng(g.n_embd);
const int64_t half = cfg.taps * NG; /* prepare's coefficients, then finish's */
RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w_tok), brows(w.x, T));
if (op_embed_ar)
RAD_ISSUE_N(c, op_embed_ar, (int64_t)T * g.n_embd, brows(w.x, T), RAD_NONE);
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
/* ---- attention, wrapped in the two halves of one convolution */
RAD_ISSUE_N(c, op_anorm[i], T, brows(w.x, T), RAD_W(w_anorm[i]), brows(w.h, T));
RAD_ISSUE_N(c, op_acoef[i], T, brows(w.h, T), RAD_W(w_acp[i]), brows(w.coef, T));
RAD_ISSUE_N(c, op_aconv[i], T, brows(w.h, T), bcol(w.coef, 0, half, T),
wrow_slice(w_acb[i], 0, 1, cfg.taps * g.n_embd), brows(w.h2, T));
RAD_ISSUE_N(c, op_qh2, T, brows(w.h2, T), brows(w.h2q, T), brows(w.h2s, T));
RAD_ISSUE_N(c, op_qp[i], T, brows(w.h2q, T), brows(w.h2s, T),
RAD_W(w_q[i].w), RAD_W(w_q[i].s), brows(w.q, T), RAD_NONE, RAD_NONE);
RAD_ISSUE_N(c, op_kp[i], T, brows(w.h2q, T), brows(w.h2s, T),
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.k, T), RAD_NONE, RAD_NONE);
RAD_ISSUE_N(c, op_vp[i], T, brows(w.h2q, T), brows(w.h2s, T),
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.v, T), RAD_NONE, RAD_NONE);
RAD_ISSUE_N(c, op_qn[i], T * g.n_head, brows(w.q, T), RAD_W(w_qn[i]), brows(w.q, T));
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));
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,
brows(w.q, T), kv_cache(kv, first_layer + i),
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_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, RAD_NONE);
/* 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. */
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));
RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h2, T), brows(w.x, T));
/* ---- the feed-forward, wrapped in the other convolution */
RAD_ISSUE_N(c, op_fnorm[i], T, brows(w.x, T), RAD_W(w_fnorm[i]), brows(w.h, T));
RAD_ISSUE_N(c, op_fcoef[i], T, brows(w.h, T), RAD_W(w_fcp[i]), brows(w.coef, T));
RAD_ISSUE_N(c, op_fconv[i], T, brows(w.h, T), bcol(w.coef, 0, half, T),
wrow_slice(w_fcb[i], 0, 1, cfg.taps * g.n_embd), brows(w.h2, T));
RAD_ISSUE_N(c, op_qh2, T, brows(w.h2, T), brows(w.h2q, T), brows(w.h2s, T));
if (op_gug[i] && T <= gated_rows) {
RAD_ISSUE_N(c, op_gug[i], T, brows(w.h2q, T), brows(w.h2s, T),
RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.ffq, T), brows(w.ffs, T),
RAD_NONE);
} else {
RAD_ISSUE_N(c, op_gu[i], T, brows(w.h2q, T), brows(w.h2s, T),
RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.gate_up, T), RAD_NONE,
RAD_NONE);
RAD_ISSUE_N(c, op_act, T, brows(w.gate_up, T), brows(w.ffn, T));
RAD_ISSUE_N(c, op_qff, T, brows(w.ffn, T), brows(w.ffq, T), brows(w.ffs, T));
}
RAD_ISSUE_N(c, op_dn[i], T, brows(w.ffq, T), brows(w.ffs, T),
RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h, T), RAD_NONE, RAD_NONE);
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
RAD_ISSUE_N(c, op_fconv[i], T, brows(w.h, T), bcol(w.coef, half, half, T),
wrow_slice(w_fcb[i], 1, 1, cfg.taps * g.n_embd), brows(w.h2, T));
RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h2, T), brows(w.x, T));
}
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. */
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. */
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. */
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. */
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));
RAD_ISSUE(c, op_dgather, brows(w.dpair, S), brows(w.dgath, S));
RAD_ISSUE_N(c, op_dmerge, S, brows(w.dgath, S), brows(w.cand, S), brows(w.unary, S));
} else {
RAD_ISSUE_N(c, op_dtopk, S, brows(w.dlog, S), brows(w.cand, S), brows(w.unary, S),
RAD_NONE);
}
RAD_ISSUE_N(c, op_hp, S, brows(w.sel_h, S), RAD_W(w_selp), brows(w.hp, S));
RAD_ISSUE_N(c, op_sel, batch->n_seq, brows(w.cand, S), brows(w.unary, S), brows(w.hp, S),
praw(batch->token_ids, RAD_I32, T), RAD_W(w_pred), RAD_W(w_succ),
brows(w.tokens, batch->n_seq));
}
} /* namespace arch */
} /* namespace rad */
#endif /* RAD_BLOCK_DFLASH2_H */
-938
View File
@@ -1,938 +0,0 @@
/* rad_block_dspark.h -- the DSpark block-diffusion drafter, fp8 weights over a bf16 checkpoint.
*
* ============================== 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
* 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.
*
* 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.
*
* ============================== THE FORWARD PASS, PINNED ==============================
*
* 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:
*
* 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
* 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
* 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.
*
* ============================== THE DUAL-SOURCE K/V IS AN ORDINARY KV 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.
*
* So the split is the same two passes Dflash2 has, for the same reason:
*
* 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.
*
* THE QUERY PASS, `block` rows a sequence, over the drafter's five layers, attending to the
* context rows AND to each other.
*
* 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.
*
* `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.
*
* ============================== 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 ==============================
*
* 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
*
* 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
* `<pred[prev], succ[cand]>`; 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.
*
* 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.
*
* 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 NORMS ARE PLAIN ==============================
*
* `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.
*
* ============================== WHAT IS FP8 AND WHAT IS NOT ==============================
*
* 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
*
* 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 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.
*
* ============================== WHAT IS LEFT ON THE TABLE ==============================
*
* Two things this block does not do, and what each would be worth:
*
* 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.
*/
#ifndef RAD_BLOCK_DSPARK_H
#define RAD_BLOCK_DSPARK_H
#include "rad_arch.h"
#include "rad_fp8.h"
namespace rad {
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. */
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. */
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 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. */
int64_t steps() const { return block; }
};
struct Wire {
/* ---- the context pass, one row a 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] */
rad_buf cq = 0, cs = 0;
/* ---- the query pass, `block` rows a 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. */
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 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 */
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 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. */
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_arch.h's, asked through the block so whoever sizes `dlog` and the pair planes does not
* re-derive the rule. */
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 */
Config cfg{};
Wire w{};
int first_layer = 0; /* absolute, so the KV group's layer_slot lookup finds these five */
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 */
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 */
/* ---- 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. */
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] = {};
DenseFP8 w_gu[MAX_LAYERS]{}, w_dn[MAX_LAYERS]{};
/* ---- context-pass ops */
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. */
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. */
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] = {};
rad_op op_op[MAX_LAYERS] = {};
rad_op op_qn[MAX_LAYERS] = {}, op_kn[MAX_LAYERS] = {};
rad_op op_gu[MAX_LAYERS] = {}, op_dn[MAX_LAYERS] = {};
rad_op op_gug[MAX_LAYERS] = {}; /* the gate_up|silu|quant fold; 0 when nothing serves it */
rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn = 0;
rad_op op_act = 0, op_qff = 0, op_ar = 0;
/* ---- the head and the Markov walk */
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_sel = 0;
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. */
void context(RadCtx* c, const RadBatch* batch) const;
/* The query pass, the head and the Markov walk: one call, `block` rows a sequence. */
void step(RadCtx* c, const RadBatch* batch) const;
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; }
};
/* ------------------------------------------------------------------------------ declare */
inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c,
int base_layer, rad_kvgroup group, rad_weight tok_embd,
const char* ck, const char* ck_lm, const char* ck_lm_alt,
const Wire& wire) {
g = geom; cfg = c; w = wire; first_layer = base_layer; kv = group; w_tok = tok_embd;
if (!ck || !ck_lm || !w_tok) return RAD_E_INVAL;
if (g.n_layer <= 0 || g.n_layer > MAX_LAYERS) {
fprintf(stderr, "radiance: dspark has %lld layers; this block carries at most %d\n",
(long long)g.n_layer, MAX_LAYERS);
return RAD_E_UNSUPPORTED;
}
if (cfg.block < 2 || cfg.n_taps <= 0 || cfg.rank <= 0 || cfg.top_k <= 0) return RAD_E_INVAL;
const int64_t qd = q_dim(), kvd = kv_dim();
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. */
srows = g.max_seqs * cfg.steps();
if (qrows <= 0 || srows <= 0) return RAD_E_INVAL;
/* ---------------------------------------------------------------- model-scope weights */
RAD_ARCH_TRY(w_fc.declare(b, nm, nm.f("dspark.fc"), g.n_embd, cfg.n_taps * g.n_embd,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model(),
{ nm.ckpt("%s.fc.weight", ck) }));
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.hidden_norm.weight"),
nm.ckpt("%s.hidden_norm.weight", ck)));
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.norm.weight"), nm.ckpt("%s.norm.weight", ck)));
w_hnorm = decl_w(b, nm.f("dspark.hidden_norm.weight"), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
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 `<w1[prev], w2[cand]>` 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. */
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"),
nm.ckpt("%s.markov_head.markov_w2.weight", ck)));
w_mk1 = decl_w(b, nm.f("dspark.markov_w1"), RAD_BF16, {g.n_vocab_all, cfg.rank},
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
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.
*
* 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. */
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");
if (ck_lm_alt && *ck_lm_alt) RAD_ARCH_TRY(map_copy_alt(b, dhn, ck_lm, ck_lm_alt));
else RAD_ARCH_TRY(map_copy(b, dhn, ck_lm));
w_dh = decl_view(b, dhn, nullptr, "codes", RAD_U2, {head_rows(g), g.n_embd},
RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
w_dhs = decl_view(b, nm.f("dspark.draft_head.scale"), dhn, "scale,zero", RAD_F16,
{head_rows(g), g.n_embd}, RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
if (!w_dh || !w_dhs) return RAD_E_INVAL;
/* ---------------------------------------------------------------- per-layer weights */
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
const RadWeightGroup grp = grp_layer(first_layer + i);
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.blk.%d.attn_norm.weight", i),
nm.ckpt("%s.layers.%d.input_layernorm.weight", ck, i)));
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.blk.%d.ffn_norm.weight", i),
nm.ckpt("%s.layers.%d.post_attention_layernorm.weight", ck, i)));
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.blk.%d.attn_q_norm.weight", i),
nm.ckpt("%s.layers.%d.self_attn.q_norm.weight", ck, i)));
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.blk.%d.attn_k_norm.weight", i),
nm.ckpt("%s.layers.%d.self_attn.k_norm.weight", ck, i)));
w_anorm[i] = decl_w(b, nm.f("dspark.blk.%d.attn_norm.weight", i), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp);
w_fnorm[i] = decl_w(b, nm.f("dspark.blk.%d.ffn_norm.weight", i), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp);
RAD_ARCH_TRY(w_q[i].declare(b, nm, nm.f("dspark.blk.%d.attn_q", i), qd, g.n_embd,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp,
{ nm.ckpt("%s.layers.%d.self_attn.q_proj.weight", ck, i) }));
RAD_ARCH_TRY(w_k[i].declare(b, nm, nm.f("dspark.blk.%d.attn_k", i), kvd, g.n_embd,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp,
{ nm.ckpt("%s.layers.%d.self_attn.k_proj.weight", ck, i) }));
RAD_ARCH_TRY(w_v[i].declare(b, nm, nm.f("dspark.blk.%d.attn_v", i), kvd, g.n_embd,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp,
{ nm.ckpt("%s.layers.%d.self_attn.v_proj.weight", ck, i) }));
w_qn[i] = decl_w(b, nm.f("dspark.blk.%d.attn_q_norm.weight", i), RAD_F32, {g.head_dim},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp);
w_kn[i] = decl_w(b, nm.f("dspark.blk.%d.attn_k_norm.weight", i), RAD_F32, {g.head_dim},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp);
RAD_ARCH_TRY(w_o[i].declare(b, nm, nm.f("dspark.blk.%d.attn_output", i), g.n_embd, qd,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, grp,
{ nm.ckpt("%s.layers.%d.self_attn.o_proj.weight", ck, i) }));
RAD_ARCH_TRY(w_gu[i].declare(b, nm, nm.f("dspark.blk.%d.ffn_gate_up", i),
2 * g.n_ff, g.n_embd,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp,
{ nm.ckpt("%s.layers.%d.mlp.gate_proj.weight", ck, i),
nm.ckpt("%s.layers.%d.mlp.up_proj.weight", ck, i) },
{ g.n_ff, g.n_ff }));
RAD_ARCH_TRY(w_dn[i].declare(b, nm, nm.f("dspark.blk.%d.ffn_down", i), g.n_embd, g.n_ff,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, grp,
{ 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.
*
* 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. */
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),
RAD_INT("window", cfg.window), 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.x});
/* ---------------------------------------------------------------- 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. */
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 = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("N", g.n_embd),
RAD_INT("K", cfg.n_taps * g.n_embd),
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. */
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. */
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)),
RAD_NOWEIGHTS),
{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. */
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),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_k[i].w, w_k[i].s)),
{w.cq, w.cs}, {w.ck});
op_cv[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),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_v[i].w, w_v[i].s)),
{w.cq, w.cs}, {w.cv});
op_cknorm[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, crows * 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_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.
*
* 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. */
op_crope = rw(b, RAD_OP(b, "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});
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),
RAD_INT("block_size", rad_kv_block_size(b, kv)),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{w.ck, w.cv}, {});
/* ---------------------------------------------------------------- the query pass */
op_embed = rw(b, RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), 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(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. */
if (g.world > 1)
op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", g.n_embd, qrows * g.n_embd),
RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)),
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.
*
* `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. */
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),
RAD_F64("eps", g.eps), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd)),
RAD_WEIGHTS(gain));
if (!h) return 0;
rad_buf rd[2] = { fold ? w.h.x : w.x, w.x };
rad_buf wr[4] = { w.h.q, w.h.s, w.h.x, w.x };
rad_op_reads (b, h, rd, fold ? 2 : 1);
rad_op_writes(b, h, wr, fold ? 4 : 3);
return h;
};
op_qat = rw(b, RAD_OP(b, "quant_act_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", qd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{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. */
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);
if (!op_anorm[i]) return RAD_E_INVAL;
op_qp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", qd),
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_q[i].w, w_q[i].s)),
{w.h.q, w.h.s}, {w.q});
op_kp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", kvd),
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_k[i].w, w_k[i].s)),
{w.h.q, w.h.s}, {w.k});
op_vp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", kvd),
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_v[i].w, w_v[i].s)),
{w.h.q, w.h.s}, {w.v});
op_qn[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows * 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_qn[i])),
{w.q}, {w.q});
op_kn[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows * 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_kn[i])),
{w.k}, {w.k});
op_op[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", qd), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_o[i].w, w_o[i].s)),
{w.attn.q, w.attn.s}, {w.h.x});
op_fnorm[i] = decl_norm(w_fnorm[i], true);
if (!op_fnorm[i]) return RAD_E_INVAL;
op_gu[i] = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", 2 * g.n_ff),
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
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_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),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_dn[i].w, w_dn[i].s)),
{w.ffn.q, w.ffn.s}, {w.h.x});
}
op_qrope = rw(b, RAD_OP(b, "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, RAD_OP(b, "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});
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),
RAD_INT("block_size", rad_kv_block_size(b, kv)),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{w.k, w.v}, {});
op_act = rw(b, RAD_OP(b, "silu_mul",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.gate_up}, {w.ffn.x});
op_qff = rw(b, RAD_OP(b, "quant_act_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff),
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. */
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, qrows * 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.x}, {w.h.x});
op_outnorm = decl_norm(w_norm, true);
if (!op_outnorm) return RAD_E_INVAL;
/* ---------------------------------------------------------------- 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. */
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.x}, {w.sel_h});
op_dquant = rw(b, RAD_OP(b, "quant_act_i8",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd),
RAD_INT("group", DS_W2_GROUP), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.sel_h}, {w.dq, w.ds, w.dsum});
op_dlogits = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)),
RAD_INT("K", g.n_embd), RAD_INT("group", DS_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. */
op_dtopk = dh_shard
? rw(b, RAD_OP(b, "row_topk",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)),
RAD_INT("R", cfg.top_k), RAD_INT("vocab_off", g.vocab_off),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.dlog}, {w.cand, w.unary, w.dpair})
: rw(b, RAD_OP(b, "row_topk",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)),
RAD_INT("R", cfg.top_k), RAD_STR("dtype", g.dtype)),
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. */
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),
RAD_STR("dtype", "f32"),
RAD_INT("row", cfg.top_k * 2)),
RAD_NOWEIGHTS),
{w.dpair}, {w.dgath});
op_dmerge = rw(b, RAD_OP(b, "row_topk_merge",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("R", cfg.top_k),
RAD_INT("world_size", g.world),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.dgath}, {w.cand, w.unary});
}
/* THE MARKOV WALK. `dflash_select` with the hidden projection ABSENT is the plain bigram
* `unary + <markov_w1[prev], markov_w2[cand]>`, 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.
*
* `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. */
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),
RAD_INT("n_vocab", g.n_vocab_all),
RAD_INT("anchor_stride", cfg.block), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_mk1, w_mk2)),
{w.cand, w.unary}, {w.tokens});
return RAD_OK;
}
/* ------------------------------------------------------------------------------ the context pass */
inline void Dspark::context(RadCtx* c, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
if (T <= 0) return;
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
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, RAD_NONE);
RAD_ISSUE_N(c, op_cnorm, T, brows(w.c, T), RAD_W(w_hnorm), brows(w.c, T));
RAD_ISSUE_N(c, op_qc, T, brows(w.c, T), brows(w.cq, T), brows(w.cs, T));
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
RAD_ISSUE_N(c, op_ck[i], T, brows(w.cq, T), brows(w.cs, T),
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.ck, T), RAD_NONE, RAD_NONE);
RAD_ISSUE_N(c, op_cv[i], T, brows(w.cq, T), brows(w.cs, T),
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.cv, T), RAD_NONE, RAD_NONE);
RAD_ISSUE_N(c, op_cknorm[i], T * g.n_head_kv,
brows(w.ck, T), RAD_W(w_kn[i]), brows(w.ck, T));
RAD_ISSUE_N(c, op_crope, T, brows(w.ck, T), praw(batch->positions, RAD_I32, T));
RAD_ISSUE_N(c, op_cstore, T, brows(w.ck, T), brows(w.cv, T),
praw(slot, RAD_I32, T), kv_cache(kv, first_layer + i));
}
}
/* ------------------------------------------------------------------------------ the query pass */
inline void Dspark::step(RadCtx* c, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
if (T <= 0) return;
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;
/* 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. */
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),
brows(w.h.q, rows), brows(w.h.s, rows), brows(w.h.x, rows));
};
RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w_tok),
brows(w.x, T));
if (op_embed_ar)
RAD_ISSUE_N(c, op_embed_ar, (int64_t)T * g.n_embd, brows(w.x, T), RAD_NONE);
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. */
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);
RAD_ISSUE_N(c, op_kp[i], T, brows(w.h.q, T), brows(w.h.s, T),
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.k, T), RAD_NONE, RAD_NONE);
RAD_ISSUE_N(c, op_vp[i], T, brows(w.h.q, T), brows(w.h.s, T),
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.v, T), RAD_NONE, RAD_NONE);
RAD_ISSUE_N(c, op_qn[i], T * g.n_head, brows(w.q, T), RAD_W(w_qn[i]), brows(w.q, T));
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. */
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,
brows(w.q, T), kv_cache(kv, first_layer + i),
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.x, T));
RAD_ISSUE_N(c, op_qat, T, brows(w.attn.x, T), brows(w.attn.q, T), brows(w.attn.s, T));
RAD_ISSUE_N(c, op_op[i], T, brows(w.attn.q, T), brows(w.attn.s, T),
RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h.x, T), RAD_NONE, RAD_NONE);
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h.x, T), RAD_NONE);
/* ---- the feed-forward, behind the same fused norm-add-quantise */
issue_norm(op_fnorm[i], true, w_fnorm[i], T);
if (op_gug[i] && T <= gated_rows) {
RAD_ISSUE_N(c, op_gug[i], T, brows(w.h.q, T), brows(w.h.s, T),
RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.ffn.q, T), brows(w.ffn.s, T),
RAD_NONE);
} else {
RAD_ISSUE_N(c, op_gu[i], T, brows(w.h.q, T), brows(w.h.s, T),
RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.gate_up, T), RAD_NONE,
RAD_NONE);
RAD_ISSUE_N(c, op_act, T, brows(w.gate_up, T), brows(w.ffn.x, T));
RAD_ISSUE_N(c, op_qff, T, brows(w.ffn.x, T), brows(w.ffn.q, T), brows(w.ffn.s, T));
}
RAD_ISSUE_N(c, op_dn[i], T, brows(w.ffn.q, T), brows(w.ffn.s, T),
RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h.x, T), RAD_NONE, RAD_NONE);
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. */
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. */
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. */
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. */
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. */
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));
RAD_ISSUE_N(c, op_dmerge, S, brows(w.dgath, S), brows(w.cand, S), brows(w.unary, S));
} else {
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_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));
}
} /* namespace arch */
} /* namespace rad */
#endif /* RAD_BLOCK_DSPARK_H */
-398
View File
@@ -1,398 +0,0 @@
/* 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.
*
* 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.
*
* 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).
*
* ============================== TWO CONVENTIONS TO GET RIGHT ==============================
*
* `A_log` IS A LOG AND THE EXPONENT HAS NOT BEEN TAKEN. 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.
*
* 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.
*
* ============================== 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.
*/
#ifndef RAD_BLOCK_GDN_H
#define RAD_BLOCK_GDN_H
#include "rad_arch.h"
#include <cmath>
namespace rad {
namespace arch {
struct GdnBF16 {
struct Config {
int64_t n_head_k = 0; /* per rank -- q and k share these */
int64_t head_k = 0; /* the recurrent state's key width */
int64_t n_head_v = 0; /* per rank; a multiple of n_head_k, 3x it on this model */
int64_t head_v = 0;
int64_t conv_width = 4;
int64_t chunk = 64; /* the chunked-scan interval, and the checkpoint interval */
int64_t k_dim() const { return n_head_k * head_k; }
int64_t v_dim() const { return n_head_v * head_v; }
int64_t conv_dim() const { return 2 * k_dim() + v_dim(); }
int64_t in_dim() const { return conv_dim() + 2 * n_head_v; } /* ... + a + b */
};
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 out projection */
rad_buf in = 0; /* [max_tok, in_dim] [q|k|v|a|b], pre-convolution */
rad_buf z = 0; /* [max_tok, v_dim] the output gate */
rad_buf q = 0; /* [max_tok, n_head_k, head_k] post-convolution, l2-normed */
rad_buf k = 0; /* [max_tok, n_head_k, head_k] */
rad_buf v = 0; /* [max_tok, n_head_v, head_v] */
rad_buf gdec = 0; /* [max_tok, n_head_v] the resolved decay, per-chunk cumsum */
rad_buf beta = 0; /* [max_tok, n_head_v] */
rad_buf kkt = 0; /* [max_tok, n_head_v, chunk] the within-chunk inverse */
rad_buf o = 0; /* [max_tok, n_head_v, head_v] */
};
/* 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* in_qkv = nullptr; /* linear_attn.in_proj_qkv.weight */
const char* in_a = nullptr; /* linear_attn.in_proj_a.weight */
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* 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 */
};
Geom g{};
Config cfg{};
Wire w{};
Src src{};
int layer = 0;
rad_kvgroup kv_state = 0, kv_conv = 0;
rad_weight w_norm = 0, w_in = 0, w_z = 0, w_conv = 0;
rad_weight w_a_log = 0, w_dt_bias = 0, w_out_norm = 0, w_out = 0;
rad_op op_norm = 0, op_in = 0, op_z = 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 */
rad_op op_out = 0, op_ar = 0, op_add = 0;
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);
void step(RadCtx* c, const RadBatch* batch) const;
};
inline int GdnBF16::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) {
g = geom; cfg = c; w = wire; src = s; layer = l; kv_state = state; kv_conv = conv;
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. */
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.
*
* 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. */
const double q_scale = 1.0 / std::sqrt((double)cfg.head_k);
const int64_t v_dim = cfg.v_dim();
const int64_t conv_dim = cfg.conv_dim();
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. */
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));
RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ssm_conv1d.weight", l), src.conv1d));
RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ssm_a_log", l), src.a_log));
RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ssm_dt.bias", l), src.dt_bias));
RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ssm_norm.weight", l), src.out_norm));
RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ssm_out.weight", l), src.out));
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_in = decl_w(b, nm.f("blk.%d.ssm_in.weight", l), RAD_BF16, {in_dim, g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l), 0,
{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. */
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,
{cfg.k_dim(), cfg.k_dim(), cfg.v_dim()});
w_a_log = decl_w(b, nm.f("blk.%d.ssm_a_log", l), RAD_F32, {cfg.n_head_v},
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. */
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},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, grp_layer(l));
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_in = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", in_dim),
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_in)), {w.h}, {w.in});
op_z = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", v_dim),
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. */
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),
RAD_INT("conv_width", cfg.conv_width)),
RAD_WEIGHTS(w_conv, w_a_log, w_dt_bias)),
{w.in}, {w.q, w.k, w.v, w.gdec, w.beta});
op_kkt = rw(b, RAD_OP(b, "gdn_kkt_solve",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_k", cfg.head_k)),
RAD_NOWEIGHTS),
{w.k, w.beta, w.gdec}, {w.kkt});
op_scan = rw(b, RAD_OP(b, "gdn_chunk_scan",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_k", cfg.head_k),
RAD_INT("head_v", cfg.head_v), RAD_F64("scale", q_scale)),
RAD_NOWEIGHTS),
{w.q, w.k, w.v, w.kkt, w.gdec, w.beta}, {w.o});
op_gnorm = rw(b, RAD_OP(b, "gdn_gated_rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("channels", cfg.head_v),
RAD_F64("eps", g.eps), RAD_STR("act", "silu")),
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. */
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),
RAD_INT("head_v", cfg.head_v),
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. */
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),
RAD_INT("n_head_v", cfg.n_head_v),
RAD_F64("scale", q_scale),
RAD_F64("eps", g.eps), RAD_STR("act", "silu"),
RAD_STR("state_form",
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.in, w.z}, {w.o});
op_out = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", g.n_embd),
RAD_INT("K", v_dim), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_out)),
{w.o}, {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 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. */
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 conv_dim = cfg.conv_dim();
const int64_t H = cfg.n_head_v;
RAD_ISSUE(c, op_norm, brows(w.x, T), RAD_W(w_norm), brows(w.h, T));
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. */
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. */
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;
const int64_t v_dim = cfg.v_dim();
if (D > 0) {
RAD_ISSUE_N(c, op_conv_update, qd,
brows(w.in, DT), RAD_W(w_conv), RAD_NONE, kv_cache(kv_conv, layer),
praw(cv_idx, RAD_I32, D), praw(batch->num_accepted, RAD_I32, D),
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. */
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),
RAD_W(w_a_log), RAD_W(w_dt_bias), kv_cache(kv_state, layer),
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). */
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.
*
* `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. */
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),
bcol(w.in, conv_dim, H, T), bcol(w.in, conv_dim + H, H, T),
praw(cv_idx ? cv_idx + D : nullptr, RAD_I32, P),
praw(batch->ctx_lens + D, RAD_I32, P),
brows(w.q, T), brows(w.k, T), brows(w.v, T),
brows(w.gdec, T), brows(w.beta, T));
RAD_ISSUE(c, op_kkt,
brows(w.k, T), brows(w.beta, T), brows(w.gdec, T),
praw(batch->cu_seqlens + D, RAD_I32, P + 1), brows(w.kkt, T));
RAD_ISSUE(c, op_scan,
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(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. */
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));
}
RAD_ISSUE(c, op_out, brows(w.o, T), RAD_W(w_out), 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_GDN_H */
-519
View File
@@ -1,519 +0,0 @@
/* 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.
*
* ============================== a AND b SPLIT OUT; z DOES NOT ==============================
*
* 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:
*
* 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 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 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.
*/
#ifndef RAD_BLOCK_GDN_FP8_H
#define RAD_BLOCK_GDN_FP8_H
#include "rad_fp8.h"
#include <cmath>
#include <cstdlib>
#include <cstring>
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. */
struct Config {
int64_t n_head_k = 0;
int64_t head_k = 0;
int64_t n_head_v = 0;
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. */
const char* act = "silu";
int64_t k_dim() const { return n_head_k * head_k; }
int64_t v_dim() const { return n_head_v * head_v; }
int64_t conv_dim() const { return 2 * k_dim() + v_dim(); }
int64_t ab_dim() const { return 2 * n_head_v; }
};
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. */
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 */
rad_buf k = 0; /* [max_tok, n_head_k, head_k] */
rad_buf v = 0; /* [max_tok, n_head_v, head_v] */
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 */
};
struct Src {
const char* norm = nullptr;
const char* in_qkv = nullptr; /* fp8 */
const char* in_a = nullptr; /* bf16 */
const char* in_b = nullptr; /* bf16 */
const char* in_z = nullptr; /* fp8 */
const char* conv1d = nullptr;
const char* a_log = nullptr;
const char* dt_bias = nullptr;
const char* out_norm = nullptr;
const char* out = nullptr; /* fp8 */
};
Geom g{};
Config cfg{};
Wire w{};
int layer = 0;
rad_kvgroup kv_state = 0, kv_conv = 0;
rad_weight w_norm = 0, w_ab = 0, w_conv = 0;
/* The input was normed and quantised by the caller; this block declares no norm. */
bool ext_in = false;
rad_weight w_a_log = 0, w_dt_bias = 0, w_out_norm = 0;
LinearFP8 in{}, out{};
NormQuantFP8 nq_h{};
QuantFP8 q_o{};
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. */
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. */
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). */
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. */
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;
};
inline int GdnFP8::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, bool add_out,
int ar_in, bool ar_out_) {
g = geom;
ar_out = ar_out_; cfg = c; w = wire; layer = l; kv_state = state; kv_conv = conv;
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;
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.
*
* 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. */
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)) {
fprintf(stderr, "radiance: the delta net's output gate is '%s'; libr4d's gated norm "
"implements silu and sigmoid and nothing else\n", cfg.act ? cfg.act : "(null)");
return RAD_E_INVAL;
}
const int64_t v_dim = cfg.v_dim();
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`). */
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;
} else {
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l), s.norm));
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. */
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. */
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. */
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,
{cfg.k_dim(), cfg.k_dim(), cfg.v_dim()});
w_a_log = decl_w(b, nm.f("blk.%d.ssm_a_log", l), RAD_F32, {cfg.n_head_v},
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));
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. */
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.
*
* 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. */
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() }));
/* 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.
*
* 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. */
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. */
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),
RAD_INT("conv_width", cfg.conv_width)),
RAD_WEIGHTS(w_conv, w_a_log, w_dt_bias)),
{w.in.x, w.ab}, {w.q, w.k, w.v, w.gdec, w.beta});
op_kkt = rw(b, RAD_OP(b, "gdn_kkt_solve",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_k", cfg.head_k)),
RAD_NOWEIGHTS),
{w.k, w.beta, w.gdec}, {w.kkt});
op_scan = rw(b, RAD_OP(b, "gdn_chunk_scan",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_k", cfg.head_k),
RAD_INT("head_v", cfg.head_v), RAD_F64("scale", q_scale)),
RAD_NOWEIGHTS),
{w.q, w.k, w.v, w.kkt, w.gdec, w.beta}, {w.o.x});
op_gnorm = rw(b, RAD_OP(b, "gdn_gated_rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("channels", cfg.head_v),
RAD_F64("eps", g.eps), RAD_STR("act", cfg.act)),
RAD_WEIGHTS(w_out_norm)),
{w.o.x, w.in.x}, {w.o.x});
/* ---- the recurrent path. */
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),
RAD_INT("head_v", cfg.head_v),
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. */
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),
RAD_INT("n_head_v", cfg.n_head_v),
RAD_F64("scale", q_scale),
RAD_F64("eps", g.eps), RAD_STR("act", cfg.act),
RAD_STR("state_form",
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. */
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. */
{
const int64_t hi = g.max_tok < 8 ? g.max_tok : 8;
op_cr = rw(b, RAD_OP(b, "gdn_conv_recurrent_update",
RAD_PARAMS(RAD_RANGE("q_len", 1, hi), RAD_INT("head_k", cfg.head_k),
RAD_INT("head_v", cfg.head_v),
RAD_INT("conv_width", cfg.conv_width),
RAD_INT("n_head_v", cfg.n_head_v), RAD_F64("scale", q_scale),
RAD_F64("eps", g.eps), RAD_STR("act", cfg.act),
RAD_STR("state_form",
g.max_spec > 0 ? "anchor" : "per_candidate")),
RAD_WEIGHTS(w_conv, w_a_log, w_dt_bias, w_out_norm)),
{w.in.x, w.ab}, {w.o.x});
if (op_cr && w.o.cq()) {
const rad_buf oq[2] = { w.o.cq(), w.o.cs() };
RAD_ARCH_TRY(rad_op_writes(b, op_cr, oq, 2));
}
if (op_cr) cr_rows = hi;
}
RAD_ARCH_TRY(q_o.declare(b, g, w.o, v_dim));
RAD_ARCH_TRY(out.declare(b, nm, g, nm.f("blk.%d.ssm_out", l), g.n_embd, v_dim,
RAD_SHARD_COL, grp_layer(l), { s.out }, w.o, w.h.x));
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.x}, {w.h.x});
/* Only where the NEXT block's norm will not do it; see rad_fp8.h's 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),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.x, w.h.x}, {w.x});
return RAD_OK;
}
inline void GdnFP8::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. */
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. */
const int64_t conv_dim = cfg.conv_dim();
const int64_t v_dim = cfg.v_dim();
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.
*
* 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.
*
* 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. */
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. */
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;
const int64_t in_w = conv_dim + v_dim; /* w.in.x's declared row width */
if (D > 0 && op_cr && qd <= cr_rows) {
RAD_ISSUE_N(c, op_cr, qd,
bcol(w.in.x, 0, conv_dim, DT), RAD_W(w_conv), RAD_NONE, kv_cache(kv_conv, layer),
praw(cv_idx, RAD_I32, D),
bcol(w.ab, 0, H, DT), bcol(w.ab, H, H, DT),
RAD_W(w_a_log), RAD_W(w_dt_bias), kv_cache(kv_state, layer),
praw2(st_idx, RAD_I32, D, st_w), praw(batch->num_accepted, RAD_I32, D),
praw(batch->cu_seqlens, RAD_I32, D + 1),
bcol(w.in.x, conv_dim, v_dim, DT), RAD_W(w_out_norm), brows(w.o.x, DT),
w.o.cq() ? brows(w.o.cq(), DT) : RAD_NONE,
w.o.cq() ? brows(w.o.cs(), DT) : RAD_NONE);
} else if (D > 0) {
RAD_ISSUE_N(c, op_conv_update, qd,
bcol(w.in.x, 0, conv_dim, DT), RAD_W(w_conv), RAD_NONE, kv_cache(kv_conv, layer),
praw(cv_idx, RAD_I32, D), praw(batch->num_accepted, RAD_I32, D),
praw(batch->cu_seqlens, RAD_I32, D + 1),
brows(w.q, DT), brows(w.k, DT), brows(w.v, DT));
RAD_ISSUE_N(c, op_recur, qd,
brows(w.q, DT), brows(w.k, DT), brows(w.v, DT),
bcol(w.ab, 0, H, DT), bcol(w.ab, H, H, DT),
RAD_W(w_a_log), RAD_W(w_dt_bias), kv_cache(kv_state, layer),
praw2(st_idx, RAD_I32, D, st_w), praw(batch->num_accepted, RAD_I32, D),
praw(batch->cu_seqlens, RAD_I32, D + 1),
bcol(w.in.x, conv_dim, v_dim, DT), RAD_W(w_out_norm), brows(w.o.x, DT),
w.o.cq() ? brows(w.o.cq(), DT) : RAD_NONE,
w.o.cq() ? brows(w.o.cs(), DT) : RAD_NONE);
}
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),
kv_cache(kv_conv, layer), praw(batch->cu_seqlens + D, RAD_I32, P + 1),
bcol(w.ab, 0, H, T), bcol(w.ab, H, H, T),
praw(cv_idx ? cv_idx + D : nullptr, RAD_I32, P),
praw(batch->ctx_lens + D, RAD_I32, P),
brows(w.q, T), brows(w.k, T), brows(w.v, T),
brows(w.gdec, T), brows(w.beta, T));
RAD_ISSUE(c, op_kkt,
brows(w.k, T), brows(w.beta, T), brows(w.gdec, T),
praw(batch->cu_seqlens + D, RAD_I32, P + 1), brows(w.kkt, T));
RAD_ISSUE(c, op_scan,
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(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. */
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. */
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))
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));
}
} /* namespace arch */
} /* namespace rad */
#endif /* RAD_BLOCK_GDN_FP8_H */
-420
View File
@@ -1,420 +0,0 @@
/* rad_block_hc.h -- the GATED RESIDUAL, which is what Qwen4-Exp has 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:
*
* read N = grouped_rmsnorm(h) one rsqrt per 2560 stream, one 10240 gain, `1 + w`
* g = sigmoid(mix_up @ silu(mix_down @ N / hc))
* x = mean over the four streams of g * N -> the block's input
* 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).
*
* ============================== WHY IT IS A BLOCK AND NOT TWO CALLS ==============================
*
* 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.
*
* ============================== 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.
*/
#ifndef RAD_BLOCK_HC_H
#define RAD_BLOCK_HC_H
#include "rad_fp8.h"
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. */
struct HcEnter {
Geom g{};
int64_t hc = 0;
rad_buf x = 0, h = 0;
rad_op op = 0;
int declare(RadBuilder* b, const Geom& geom, int64_t hc_, rad_buf x_, rad_buf h_) {
g = geom; hc = hc_; x = x_; h = h_;
if (hc <= 1 || !x || !h) return RAD_E_INVAL;
op = rw(b, RAD_OP(b, "hc_enter",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_INT("hc", hc), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{x}, {h});
return op ? RAD_OK : RAD_E_INVAL;
}
void step(RadCtx* c_, int64_t T) const {
RAD_ISSUE_N(c_, op, T, brows(x, T), brows(h, T));
}
};
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. */
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. */
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. */
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. */
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. */
int codes_i8 = 0;
};
struct Wire {
rad_buf h = 0; /* [max_tok, hc * n_embd] THE WIDE STREAM, 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` */
rad_buf rs = 0; /* [max_tok, n_embd/128] and their scales */
};
struct Src {
const char* norm = nullptr; /* hc_norm.weight, [hc*n_embd] */
const char* mix_down = nullptr; /* input_mix_weight_down.weight, [lowrank, hc*n_embd] */
const char* mix_up = nullptr; /* input_mix_weight_up.weight, [hc*n_embd, lowrank] */
const char* inject_w = nullptr; /* block_inject_weight.weight, [hc, hc*n_embd] */
};
Geom g{};
Config c{};
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. */
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. */
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). */
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;
int64_t rows = 0; /* one pass of the block, at most */
};
GatherSrc gsrc{};
rad_op op_ar_gather_write = 0, op_ar_gather_write6 = 0;
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. */
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. */
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. */
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);
}
/* `name` is the declared prefix -- "blk.7.attn_hc" -- and `src` the checkpoint side. */
int declare(RadBuilder* b, Names& nm, const Geom& geom, const char* name,
const Config& cfg, const Wire& wire, const Src& src);
int declare_gather(RadBuilder* b, const GatherSrc& src);
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;
};
inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const char* name,
const Config& cfg, const Wire& wire, const Src& src) {
g = geom; c = cfg; w = wire;
if (c.hc <= 1 || c.lowrank <= 0 || g.n_embd <= 0) {
fprintf(stderr, "radiance: %s: hc = %lld, lowrank = %lld -- a gated residual needs hc > 1 "
"and a positive waist\n",
name, (long long)c.hc, (long long)c.lowrank);
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. */
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");
return RAD_E_INVAL;
}
if (!c.inject && (src.inject_w || w.inj)) {
fprintf(stderr, "radiance: %s: inject is off, so neither block_inject_weight nor an inj "
"buffer may be passed\n", name);
return RAD_E_INVAL;
}
if (c.quant && (c.codes_i8 ? (!w.x.q8 || !w.x.s8) : (!w.x.q || !w.x.s))) return RAD_E_INVAL;
if (c.rotate && (!c.quant || !w.rq || !w.rs)) {
fprintf(stderr, "radiance: %s: the rotated codes need the plain ones (quant) and the "
"rq/rs pair on the wire\n", name);
return RAD_E_INVAL;
}
if (!w.h || !w.x.x) return RAD_E_INVAL;
const int64_t HN = hn();
/* The name maps first: they are how the model is asked what each weight is. */
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);
const char* in = nm.f("%s_inject.weight", name);
RAD_ARCH_TRY(map_copy(b, nn, src.norm));
RAD_ARCH_TRY(map_copy(b, dn, src.mix_down));
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. */
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 "
"as bf16 or both as E4M3 rows\n", name,
rad_dtype_name(mdt), rad_dtype_name(weight_codes_dtype(b, un, RAD_BF16)));
return RAD_E_DTYPE;
}
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. */
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());
w_up = decl_w(b, un, mdt, {HN, c.lowrank}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_model());
if (c.inject)
w_inj = decl_w(b, in, RAD_BF16, {c.hc, HN}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
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. */
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. */
rad_buf wr[6] = { w.x.x, 0, 0, 0, 0, 0 };
int n_wr = 1;
if (c.inject) wr[n_wr++] = w.inj;
if (c.quant) { wr[n_wr++] = c.codes_i8 ? w.x.q8 : w.x.q; wr[n_wr++] = c.codes_i8 ? w.x.s8 : w.x.s; }
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_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),
RAD_INT("group", c.quant ? RAD_FP8_BLOCK : 0),
RAD_INT("rotate", c.rotate ? 1 : 0),
RAD_STR("mix", mix_e4m3 ? "e4m3" : "bf16")),
wts, n_wts);
if (!op_read) return RAD_E_INVAL;
{
const rad_buf rd[1] = { w.h };
rad_op_reads (b, op_read, rd, 1);
rad_op_writes(b, op_read, wr, n_wr);
}
if (c.inject) {
op_write = rw(b, RAD_OP(b, "hc_write",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_INT("hc", c.hc), RAD_STR("dtype", g.dtype)),
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. */
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",
RAD_PARAMS(RAD_RANGE("M", 1, ar_rows), RAD_INT("n", g.n_embd),
RAD_INT("hc", c.hc), RAD_INT("world_size", g.world),
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. */
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),
RAD_INT("hc", c.hc), RAD_INT("world_size", g.world),
RAD_STR("dtype", g.dtype), RAD_INT("wire", 6)),
RAD_NOWEIGHTS),
{w.x.x, w.inj, w.h}, {w.x.x, w.h});
}
return RAD_OK;
}
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. */
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. */
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. */
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),
RAD_INT("world_size", g.world),
RAD_STR("dtype", g.dtype),
RAD_STR("act", shared ? "sigmoid" : "none"),
RAD_INT("wire", 0)),
RAD_NOWEIGHTS);
if (op_ar_gather_write) {
RAD_ARCH_TRY(rad_op_reads (b, op_ar_gather_write, rd, shared ? 8 : 6));
RAD_ARCH_TRY(rad_op_writes(b, op_ar_gather_write, wr, 2));
gather_rows = rows;
}
if (op_ar_write6) {
op_ar_gather_write6 = 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),
RAD_INT("world_size", g.world),
RAD_STR("dtype", g.dtype),
RAD_STR("act", shared ? "sigmoid" : "none"),
RAD_INT("wire", 6)),
RAD_NOWEIGHTS);
if (op_ar_gather_write6) {
RAD_ARCH_TRY(rad_op_reads (b, op_ar_gather_write6, rd, shared ? 8 : 6));
RAD_ARCH_TRY(rad_op_writes(b, op_ar_gather_write6, wr, 2));
gather_rows6 = rows;
}
}
return RAD_OK;
}
inline void HyperConn::read(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const {
(void)T;
const int64_t HN = hn();
RAD_ISSUE_N(c_, op_read, rows,
brow_slice(w.h, r0, rows, HN), RAD_W(w_norm), RAD_W(w_down), RAD_W(w_up),
c.inject ? RAD_W(w_inj) : RAD_NONE,
brow_slice(w.x.x, r0, rows, g.n_embd),
c.inject ? brow_slice(w.inj, r0, rows, c.hc) : RAD_NONE,
c.quant ? brow_slice(c.codes_i8 ? w.x.q8 : w.x.q, r0, rows, g.n_embd) : RAD_NONE,
c.quant ? brow_slice(c.codes_i8 ? w.x.s8 : w.x.s, r0, rows,
fp8_blocks(g.n_embd)) : RAD_NONE,
c.rotate ? brow_slice(w.rq, r0, rows, g.n_embd) : RAD_NONE,
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. */
inline void HyperConn::write(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const {
if (!op_write) return;
if (takes_gather(T)) {
const int64_t k = gsrc.top_k;
const bool shared = gsrc.sh && gsrc.sg;
const rad_op op = ar_exact_write_takes(g, T) ? op_ar_gather_write : op_ar_gather_write6;
RAD_ISSUE_N(c_, op, rows,
brows(gsrc.ye, rows * k), brow_slice(gsrc.ew, r0, rows, k),
brows(gsrc.sorted, rows * k),
shared ? brow_slice(gsrc.sh, r0, rows, g.n_embd) : RAD_NONE,
shared ? brow_slice(gsrc.sg, r0, rows, 1) : RAD_NONE,
brow_slice(w.x.x, r0, rows, g.n_embd),
brow_slice(w.inj, r0, rows, c.hc),
brow_slice(w.h, r0, rows, hn()));
return;
}
RAD_ISSUE_N(c_, takes_ar(T) ? ar_write(T) : op_write, rows,
brow_slice(w.x.x, r0, rows, g.n_embd),
brow_slice(w.inj, r0, rows, c.hc),
brow_slice(w.h, r0, rows, hn()));
}
} /* namespace arch */
} /* namespace rad */
#endif /* RAD_BLOCK_HC_H */
-123
View File
@@ -1,123 +0,0 @@
/* rad_block_mlp.h -- one SwiGLU feed-forward block, bf16 operands.
*
* 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.
*/
#ifndef RAD_BLOCK_MLP_H
#define RAD_BLOCK_MLP_H
#include "rad_arch.h"
namespace rad {
namespace arch {
struct MlpBF16 {
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 down-projection output */
rad_buf gate_up = 0; /* [max_tok, 2 * n_ff] */
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_*`. */
struct Src {
const char* norm = nullptr; /* post_attention_layernorm.weight */
const char* gate = nullptr;
const char* up = nullptr;
const char* down = nullptr;
};
Geom g{};
Wire w{};
int layer = 0;
rad_weight w_norm = 0, w_gate_up = 0, w_down = 0;
rad_op op_norm = 0, op_gate_up = 0, op_act = 0, op_down = 0, op_ar = 0, op_add = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
const Src& src);
void step(RadCtx* c, const RadBatch* batch) const;
};
inline int MlpBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
const Src& src) {
g = geom; w = wire; layer = l;
RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ffn_norm.weight", l), src.norm));
RAD_ARCH_TRY(map_concat(b, nm.f("blk.%d.ffn_gate_up.weight", l), { src.gate, src.up }, 0));
RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ffn_down.weight", l), src.down));
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));
w_gate_up = decl_w(b, nm.f("blk.%d.ffn_gate_up.weight", l), RAD_BF16, {2 * g.n_ff, g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l), 0, {g.n_ff, g.n_ff});
w_down = decl_w(b, nm.f("blk.%d.ffn_down.weight", l), RAD_BF16, {g.n_embd, g.n_ff},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, grp_layer(l));
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_gate_up = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", 2 * g.n_ff),
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_gate_up)),
{w.h}, {w.gate_up});
op_act = rw(b, RAD_OP(b, "silu_mul",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_ff),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.gate_up}, {w.ffn});
op_down = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", g.n_embd),
RAD_INT("K", g.n_ff), RAD_STR("dtype", g.dtype)),
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). */
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 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). */
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));
RAD_ISSUE(c, op_act, brows(w.gate_up, T), brows(w.ffn, T));
RAD_ISSUE(c, op_down, brows(w.ffn, T), RAD_W(w_down), 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_MLP_H */
-203
View File
@@ -1,203 +0,0 @@
/* rad_block_mlp_fp8.h -- the SwiGLU feed-forward block with block-scaled FP8 linears.
*
* 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.
*
* What differs, and only this:
*
* - 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.
*/
#ifndef RAD_BLOCK_MLP_FP8_H
#define RAD_BLOCK_MLP_FP8_H
#include "rad_fp8.h"
namespace rad {
namespace arch {
struct MlpFP8 {
struct Wire {
rad_buf x = 0; /* [max_tok, n_embd] the residual stream */
ActFP8 h{}; /* [max_tok, n_embd] normed input, then the down-projection output */
rad_buf gate_up = 0; /* [max_tok, 2 * n_ff] */
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. */
struct Src {
const char* norm = nullptr;
const char* gate = nullptr;
const char* up = nullptr;
const char* down = nullptr;
};
Geom g{};
Wire w{};
int layer = 0;
rad_weight w_norm = 0;
LinearFP8 gate_up{}, down{};
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. */
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. */
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. */
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;
/* 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;
};
inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
const Src& src, bool fold, bool add_out,
int ar_in, bool ar_out_) {
g = geom; w = wire; layer = l;
ar_out = ar_out_;
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ffn_norm.weight", l), src.norm));
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. */
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. */
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. */
{
const int64_t hi = g.max_tok < 64 ? g.max_tok : 64;
if (hi > 0 && !gate_up.bf16) {
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<rad_buf>{ w.ffn.q, w.ffn.s, w.ffn.x }
: std::initializer_list<rad_buf>{ w.ffn.q, w.ffn.s });
if (op_gated) gated_rows = hi;
}
}
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));
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.x}, {w.h.x});
/* Only where the NEXT block's norm will not do it; see rad_fp8.h's 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),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.x, w.h.x}, {w.x});
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. */
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);
if (op_gated && rows <= gated_rows) {
RAD_ISSUE_N(c, op_gated, rows, brow_slice(w.h.q, r0, rows, g.n_embd),
brow_slice(w.h.s, r0, rows, g.n_embd / RAD_FP8_BLOCK), RAD_W(gate_up.w),
RAD_W(gate_up.ws), brow_slice(w.ffn.q, r0, rows, g.n_ff),
brow_slice(w.ffn.s, r0, rows, g.n_ff / RAD_FP8_BLOCK),
gq_ffn.want_x ? brow_slice(w.ffn.x, r0, rows, g.n_ff) : RAD_NONE);
} else {
gate_up.step(c, w.h, w.gate_up, T, r0, rows);
gq_ffn.step(c, w.gate_up, T, r0, rows);
}
down.step(c, w.ffn, w.h.x, T, r0, rows);
if (op_ar && !(ar_out && ar_fused_ok(g, rows)))
RAD_ISSUE_N(c, op_ar, rows * g.n_embd, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_NONE);
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));
}
inline void MlpFP8::step(RadCtx* c, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
slice(c, T, 0, T);
}
} /* namespace arch */
} /* namespace rad */
#endif /* RAD_BLOCK_MLP_FP8_H */
File diff suppressed because it is too large. Load diff
-484
View File
@@ -1,484 +0,0 @@
/* rad_block_mtp_fp8.h -- the multi-token-prediction head, with block-scaled FP8 projections.
*
* ============================== 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).
*
* THE INDEXING IS THE WHOLE THING, so it is stated once here and everything else follows:
*
* 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.
*
* The forward is short and every piece of it already exists in this library:
*
* 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'
*
* 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.
*
* ============================== THE TWO KINDS OF PASS ==============================
*
* RadBatch::draft_pass says which, and the sign is the whole distinction:
*
* < 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.
*
* 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.
*
* > 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.
*
* ============================== WHAT IS AND IS NOT FP8 ==============================
*
* Read off mtp.safetensors rather than assumed, exactly as qwen35_fp8.cpp reads the trunk:
*
* 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.
*
* ============================== 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.
*
* ============================== 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.
*
* ============================== 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 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.
*
* 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.
*/
#ifndef RAD_BLOCK_MTP_FP8_H
#define RAD_BLOCK_MTP_FP8_H
#include "rad_block_attn_gated_fp8.h"
#include "rad_block_mlp_fp8.h"
#include "rad_block_vit.h"
#include <cstdlib>
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.
*
* 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. */
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;
RadEncoding e{};
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. */
template <class Ffn>
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. */
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. */
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. */
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 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. */
AttnGatedFP8::Wire attn{};
typename Ffn::Wire mlp{};
};
struct Src {
const char* fc = nullptr;
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. */
const char* lm = nullptr;
AttnGatedFP8::Src attn{};
typename Ffn::Src mlp{};
};
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 */
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 */
bool q2 = false; /* is the draft round reading it? */
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. */
bool media = false;
MediaRows mrows{};
rad_op op_norm = 0, op_dsel = 0, op_dback = 0, op_logits = 0;
rad_op op_dquant = 0, op_dlogits = 0, op_dtopk = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup kv,
int64_t rotary_dim, rad_weight tok_embd, rad_weight lm_head, float out_wadd,
const Wire& wire, const Src& src);
void step(RadCtx* c, const RadBatch* batch) const;
};
template <class Ffn>
inline int MtpBlockFP8<Ffn>::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
rad_kvgroup kv, int64_t rotary_dim, rad_weight tok_embd,
rad_weight lm_head, float out_wadd, const Wire& wire,
const Src& src) {
g = geom; w = wire; layer = l; w_tok = tok_embd; w_lm = lm_head;
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. */
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. */
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));
RAD_ARCH_TRY(map_copy(b, nm.f("mtp.fc.weight"), src.fc));
w_pre_h = decl_w(b, nm.f("mtp.pre_fc_norm_hidden.weight"), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
w_pre_e = decl_w(b, nm.f("mtp.pre_fc_norm_embedding.weight"), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
w_norm = decl_w(b, nm.f("mtp.norm.weight"), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
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. */
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)),
RAD_NOWEIGHTS),
{w.src}, {w.hout});
op_embed = rw(b, RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, rows), 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(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. */
if (g.world > 1)
op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", g.n_embd, rows * g.n_embd),
RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)),
RAD_NOWEIGHTS),
{w.e}, {w.e});
op_pre_h = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_pre_h)),
{w.hout}, {w.c});
op_pre_e = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_pre_e)),
{w.e}, {w.c});
op_fc = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", g.n_embd),
RAD_INT("K", 2 * g.n_embd), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_fc)),
{w.c}, {w.x});
RAD_ARCH_TRY(attn.declare(b, nm, g, l, kv, rotary_dim, w.attn, src.attn));
RAD_ARCH_TRY(mlp.declare(b, nm, g, l, w.mlp, src.mlp));
op_norm = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_F64("wadd", out_wadd),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_norm)),
{w.x}, {w.hout});
/* 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 `hout` -- where the lm_head reads a round's rows
* and round 2 reads its input. Through `x`, which is dead once the norm has read it, because a
* gather in place could overwrite a row another sequence has yet to 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)),
RAD_NOWEIGHTS),
{w.hout}, {w.x});
op_dback = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd),
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
RAD_NOWEIGHTS),
{w.x}, {w.hout});
if (!op_dsel || !op_dback) return RAD_E_INVAL;
/* 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. */
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(w_lm)),
{w.hout}, {w.logits});
/* ---- 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.
*
* 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.
*
* 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.
*/
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. */
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. */
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));
w_dhs = decl_view(b, nm.f("mtp.draft_head.scale"), dhn, "scale,zero", RAD_F16,
{g.n_vocab_all, g.n_embd}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(l));
if (!w_dh || !w_dhs) return RAD_E_INVAL;
op_dquant = rw(b, RAD_OP(b, "quant_act_i8",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
RAD_INT("n", g.n_embd), RAD_INT("group", MTP_W2_GROUP),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.hout}, {w.dq, w.ds, w.dsum});
op_dlogits = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
RAD_INT("N", g.n_vocab_all), RAD_INT("K", g.n_embd),
RAD_INT("group", MTP_W2_GROUP), RAD_STR("dtype", "w2a8")),
RAD_WEIGHTS(w_dh, w_dhs)),
{w.dq, w.ds, w.dsum}, {w.dlog});
op_dtopk = rw(b, RAD_OP(b, "row_topk",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
RAD_INT("N", g.n_vocab_all), RAD_INT("R", 1),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{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. */
{
const rad_op last = q2 ? op_dtopk : op_logits;
if (rad_op_reads(b, last, &w.hout, 1) < 0) return RAD_E_INVAL;
}
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. */
template <class Ffn>
inline void MtpBlockFP8<Ffn>::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. */
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");
return;
}
if (r < 0 && batch->n_out > 0)
RAD_ISSUE_N(c, op_gather, batch->n_out,
RAD_B(w.src), praw(batch->out_ids, RAD_I32, batch->n_out),
brows(w.hout, batch->n_out));
RAD_ISSUE(c, op_embed, praw(batch->token_ids, RAD_I32, T), RAD_W(w_tok), brows(w.e, T));
mrows.step(c, batch, w.e, T);
if (op_embed_ar)
RAD_ISSUE_N(c, op_embed_ar, (int64_t)T * g.n_embd, brows(w.e, T), RAD_NONE);
RAD_ISSUE(c, op_pre_h, brows(w.hout, T), RAD_W(w_pre_h), bcol(w.c, off_h, g.n_embd, T));
RAD_ISSUE(c, op_pre_e, brows(w.e, T), RAD_W(w_pre_e), bcol(w.c, off_e, g.n_embd, T));
RAD_ISSUE(c, op_fc, brows(w.c, T), RAD_W(w_fc), brows(w.x, T));
attn.step(c, batch);
/* A HISTORY PASS THAT DRAFTS NOTHING ENDS HERE. It exists to leave K and V behind, and the
* attention above has stored them. 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 the feed-forward would run is skipped on all of them. */
if (r < 0 && batch->n_draft_out <= 0) return;
mlp.step(c, batch);
RAD_ISSUE(c, op_norm, brows(w.x, T), RAD_W(w_norm), brows(w.hout, T));
/* A history pass that drafts brings round 1's rows to the front first. */
int64_t L = T; /* the rows the lm_head runs over */
if (r < 0) {
L = batch->n_draft_out;
RAD_ISSUE_N(c, op_dsel, L, RAD_B(w.hout), praw(batch->draft_out_ids, RAD_I32, L),
brows(w.x, L));
RAD_ISSUE_N(c, op_dback, L, brows(w.x, L), 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. */
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). */
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),
RAD_NONE); /* the `pairs` slot, absent: operands are positional */
} else {
RAD_ISSUE_N(c, op_logits, L, brows(w.hout, L), RAD_W(w_lm), brows(w.logits, L));
}
}
/* 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<MoeFP8>, 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. */
using MtpFP8 = MtpBlockFP8<MlpFP8>;
} /* namespace arch */
} /* namespace rad */
#endif /* RAD_BLOCK_MTP_FP8_H */
-595
View File
@@ -1,595 +0,0 @@
/* 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 ==============================
*
* 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:
*
* 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.
*
* ============================== THE 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
*
* 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.
*
* ============================== THE TWO KINDS OF PASS ==============================
*
* `RadBatch::draft_pass` says which and the SIGN is the whole distinction:
*
* < 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.
*
* ============================== THE CARRY, AND WHY IT IS A COPY ==============================
*
* `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.
*
* ============================== 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.
*
* ============================== WHAT IS AND IS NOT DECLARED ==============================
*
* 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.
*
* 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.
*/
#ifndef RAD_BLOCK_MTP_HC_H
#define RAD_BLOCK_MTP_HC_H
#include "rad_block_attn_gated_fp8.h"
#include "rad_block_hc.h"
#include "rad_block_moe_fp8.h"
#include "rad_block_mtp_fp8.h" /* mtp_draft_head_q2(): one reading of the 2-bit head */
#include "rad_qsa.h"
#include "rad_block_vit.h"
#include <cstdlib>
namespace rad {
namespace arch {
/* HOW MANY CANDIDATES THE COARSE HEAD PROPOSES, and it is 8 because they are RESCORED.
*
* 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. */
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. */
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 */
rad_buf e = 0; /* [max_tok, n_embd] the input token's embedding */
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. */
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. */
rad_buf dpair = 0, dgath = 0;
AttnGatedFP8::Wire attn{};
MoeFP8::Wire mlp{};
QsaIndexer::Wire qsa{};
};
struct Src {
const char* fc_hidden = nullptr;
const char* fc_embedding = nullptr;
const char* pre_norm_hidden = nullptr;
const char* pre_norm_embedding = nullptr;
HyperConn::Src hc_attn{}, hc_mlp{}, hc_mix{};
AttnGatedFP8::Src attn{};
MoeFP8::Src mlp{};
/* The indexer's names and geometry; `qk_proj` null declares no indexer at all. */
QsaIndexer::Config qsa{};
};
Geom g{};
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 */
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. */
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;
rad_weight w_dh = 0, w_dhs = 0;
HyperConn hc_attn{}, hc_mlp{}, mixer{};
AttnGatedFP8 attn{};
QsaIndexer qsa{};
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. */
bool media = false;
MediaRows mrows{};
rad_op op_dsel = 0, op_dback = 0;
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. */
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); }
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup kv,
rad_kvgroup* qsa_bk, int64_t rotary_dim, rad_weight tok_embd, rad_weight lm_head,
const HyperConn::Config& hc, int draft_depth, const Wire& wire, const Src& src);
void step(RadCtx* c, const RadBatch* batch) const;
};
inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup kv,
rad_kvgroup* qsa_bk, int64_t rotary_dim, rad_weight tok_embd,
rad_weight lm_head, const HyperConn::Config& hc, int draft_depth,
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. */
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. */
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");
const char* nfe = nm.f("mtp.fc_embedding.weight");
RAD_ARCH_TRY(map_copy(b, nph, src.pre_norm_hidden));
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. */
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 "
"reads both as bf16 or both as E4M3 rows\n", rad_dtype_name(fdt),
rad_dtype_name(weight_codes_dtype(b, nfe, RAD_BF16)));
return RAD_E_DTYPE;
}
w_pre_h = decl_w(b, nph, RAD_F32, {HN}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
w_pre_e = decl_w(b, npe, RAD_F32, {g.n_embd}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(l));
w_fc_h = decl_w(b, nfh, fdt, {g.n_embd, g.n_embd}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(l));
w_fc_e = decl_w(b, nfe, fdt, {g.n_embd, g.n_embd}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
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. */
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)),
RAD_NOWEIGHTS),
{w.src}, {w.hin});
op_embed = rw(b, RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, rows), 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(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. */
if (g.world > 1)
op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", g.n_embd, rows * g.n_embd),
RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)),
RAD_NOWEIGHTS),
{w.e}, {w.e});
op_enter = rw(b, RAD_OP(b, "mtp_enter",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", g.n_embd),
RAD_INT("hc", hc.hc), RAD_F64("eps", g.eps),
RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd),
RAD_INT("ngroup", ngroup),
RAD_STR("fc", fdt == RAD_F8E4M3 ? "e4m3" : "bf16")),
RAD_WEIGHTS(w_pre_h, w_pre_e, w_fc_h, w_fc_e)),
{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. */
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));
attn.ar_out_take = hc_attn.ar_take();
RAD_ARCH_TRY(attn.declare(b, nm, g, l, kv, rotary_dim, w.attn, src.attn,
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));
/* The rotated expert input rides in this read, as it does 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; }
RAD_ARCH_TRY(hc_mlp.declare(b, nm, g, nm.f("mtp.ffn_hc"), mcfg, mwire, src.hc_mlp));
mlp.ar_out_take = hc_mlp.ar_take();
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. */
{
HyperConn::GatherSrc gs{};
gs.ye = mlp.w.edn;
gs.ew = mlp.w.ew;
gs.sorted = mlp.w.sorted;
if (mlp.gfold) { gs.sh = mlp.w.sout; gs.sg = mlp.w.sgate; }
gs.top_k = mlp.c.top_k;
gs.rows = mlp.c.rows;
RAD_ARCH_TRY(hc_mlp.declare_gather(b, gs));
mlp.gather_out_rows = hc_mlp.gather_rows;
mlp.gather_out_rows6 = hc_mlp.gather_rows6;
}
/* ---- the carry. See the header: `mtp_enter` cannot be issued 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});
/* ---- draft round 1's rows out of a history pass (RadBatch::draft_out_ids): gathered into the
* carry, one row a drafting sequence in round order, and copied back to the front of `hw` for
* the mixer. Two ops and not one because a gather in place could overwrite a row another
* sequence has yet to read. */
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)),
RAD_NOWEIGHTS),
{w.hw}, {w.hin});
op_dback = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", HN),
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
RAD_NOWEIGHTS),
{w.hin}, {w.hw});
if (!op_dsel || !op_dback) return RAD_E_INVAL;
/* ---- 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. */
{
HyperConn::Config mc = hc;
mc.inject = 0;
mc.quant = 0;
HyperConn::Wire mixw{};
mixw.h = w.hw; mixw.x.x = w.hout; /* q/s deliberately absent */
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. */
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(w_lm)),
{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. */
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. */
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. */
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. */
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));
w_dhs = decl_view(b, nm.f("mtp.draft_head.scale"), dhn, "scale,zero", RAD_F16,
{hrows, g.n_embd}, RAD_ACCESS_PER_TOKEN, dh_split, grp_layer(l));
if (!w_dh || !w_dhs) return RAD_E_INVAL;
op_dquant = rw(b, RAD_OP(b, "quant_act_i8",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
RAD_INT("n", g.n_embd), RAD_INT("group", MTP_W2_GROUP),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.hout}, {w.dq, w.ds, w.dsum});
op_dlogits = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
RAD_INT("N", hrows), RAD_INT("K", g.n_embd),
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. */
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),
RAD_INT("R", kDraftTopR), RAD_INT("vocab_off", g.vocab_off),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.dlog}, {w.didx, w.dval, w.dpair})
: rw(b, RAD_OP(b, "row_topk",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("N", hrows),
RAD_INT("R", kDraftTopR), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.dlog}, {w.didx, w.dval});
/* ---- THE COARSE HEAD'S CANDIDATES, RESCORED EXACTLY.
*
* `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.
*
* 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.
*
* 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. */
const bool rerank = dh_shard || g.world <= 1;
if (rerank) {
op_drerank = RAD_OP(b, "logit_rerank",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
RAD_INT("R", kDraftTopR), RAD_INT("n_vocab", g.n_vocab),
RAD_INT("n_embd", g.n_embd),
RAD_INT("vocab_off", g.vocab_off),
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. */
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. */
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),
RAD_STR("dtype", "f32"),
RAD_INT("row", kDraftTopR * 2)),
RAD_NOWEIGHTS),
{w.dpair}, {w.dgath});
op_dmerge = rw(b, RAD_OP(b, "row_topk_merge",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
RAD_INT("R", kDraftTopR),
RAD_INT("world_size", g.world),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.dgath}, {w.didx, w.dval});
if (!op_dgather || !op_dmerge) return RAD_E_INVAL;
}
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. */
{
rad_op last = op_logits;
if (q2) last = op_dmerge ? op_dmerge : op_drerank ? op_drerank : op_dtopk;
if (rad_op_reads(b, last, &w.hin, 1) < 0) return RAD_E_INVAL;
}
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. */
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. */
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");
return;
}
if (r < 0 && batch->n_out > 0)
RAD_ISSUE_N(c, op_gather, batch->n_out,
RAD_B(w.src), praw(batch->out_ids, RAD_I32, batch->n_out),
brows(w.hin, batch->n_out));
RAD_ISSUE(c, op_embed, praw(batch->token_ids, RAD_I32, T), RAD_W(w_tok), brows(w.e, T));
mrows.step(c, batch, w.e, T);
if (op_embed_ar)
RAD_ISSUE_N(c, op_embed_ar, (int64_t)T * g.n_embd, brows(w.e, T), RAD_NONE);
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);
/* 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);
attn.step(c, batch);
/* A HISTORY PASS THAT DRAFTS NOTHING ENDS HERE. It exists to leave the head's state behind --
* the K and V the attention just stored and the indexer's block keys and tail -- and both are
* written above. Everything below computes the head's stream, which only a drafting row
* reads: the experts, the two connections around them and the lm_head. Every prefill chunk
* but a prompt's last is such a pass, so on those the head costs its attention alone.
* `n_draft_out` is the batch's and the same on every rank, so the collectives skipped here
* are skipped on all of them. */
if (r < 0 && batch->n_draft_out <= 0) return;
hc_attn.write(c, T, 0, T);
hc_mlp.read(c, T, 0, T);
mlp.step(c, batch);
hc_mlp.write(c, T, 0, T);
/* 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 that drafts takes round 1's rows out of its own
* -- into the carry, and back to the front of `hw` for the mixer below. */
int64_t L = T; /* the rows the lm_head runs over */
if (r < 0) {
L = batch->n_draft_out;
RAD_ISSUE_N(c, op_dsel, L, RAD_B(w.hw), praw(batch->draft_out_ids, RAD_I32, L),
brows(w.hin, L));
RAD_ISSUE_N(c, op_dback, L, brows(w.hin, L), brows(w.hw, L));
} else if (r < depth) {
RAD_ISSUE_N(c, op_carry, T, brows(w.hw, T), brows(w.hin, T));
}
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. */
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). */
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. */
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));
RAD_ISSUE(c, op_dgather, brows(w.dpair, L), brows(w.dgath, L));
RAD_ISSUE_N(c, op_dmerge, L, brows(w.dgath, L), brows(w.didx, L), brows(w.dval, L));
} else {
RAD_ISSUE_N(c, op_dtopk, L, brows(w.dlog, L), brows(w.didx, L), brows(w.dval, L),
RAD_NONE); /* the `pairs` slot, absent: operands are positional */
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), RAD_NONE);
}
} else {
RAD_ISSUE_N(c, op_logits, L, brows(w.hout, L), RAD_W(w_lm), brows(w.logits, L));
}
}
} /* namespace arch */
} /* namespace rad */
#endif /* RAD_BLOCK_MTP_HC_H */
-553
View File
@@ -1,553 +0,0 @@
/* rad_block_ple.h -- Qwen4-Exp's Per-Layer Embedding, declared and issued.
*
* ============================== 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:
*
* 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
* k = key_proj(e) [T, hc*n] v = value_proj(e) [T, n]
* gv,
* gvn = ple_gate(k, h, v, ...) the dot, the signed sqrt, the broadcast
* 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.
*
* ============================== THE TABLE DECIDES THE SHAPE OF ALL OF THIS ======================
*
* 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 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.
*
* 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.
*
* 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.
*
* ============================== TWO STATES, ONE CONTRACT ==============================
*
* 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.
*
* 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.
*/
#ifndef RAD_BLOCK_PLE_H
#define RAD_BLOCK_PLE_H
#include "rad_arch.h"
#include "rad_fp8.h"
namespace rad {
namespace arch {
struct PleLayer {
struct Config {
int64_t hc = 0; /* hyper-connection streams */
int64_t embed_dim = 0; /* ple_embed_dim: heads * head_dim */
int64_t heads = 0; /* (ngram - 1) * heads_per_ngram */
int64_t ngram = 0;
int64_t eos = -1;
int64_t rows = 0; /* the table's row count, padded */
int64_t shards = 0; /* how many checkpoint tensors it is stored as */
int64_t conv_width = 0;
int64_t dilation = 0; /* == ngram, in this model */
int64_t head_dim() const { return heads > 0 ? embed_dim / heads : 0; }
int64_t hist() const { return (conv_width - 1) * dilation; }
};
struct Wire {
rad_buf h = 0; /* [max_tok, hc * n_embd] THE WIDE STREAM, read and added into */
};
struct Src {
/* The table's shards are named `<prefix><i><suffix>`; everything else is one tensor. */
const char* shard_prefix = nullptr;
const char* shard_suffix = nullptr;
const char* mult = nullptr;
const char* vocab_sizes = nullptr;
const char* offsets = nullptr;
const char* key_proj = nullptr;
const char* value_proj = nullptr;
const char* norm_key = nullptr;
const char* norm_query = nullptr;
const char* norm_conv = nullptr;
const char* conv1d = nullptr;
};
Geom g{};
Config c{};
Wire w{};
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. */
bool table_bf16 = false;
rad_weight w_key = 0, w_value = 0, w_nk = 0, w_nq = 0, w_nc = 0, w_conv = 0;
rad_kvgroup kv_tok = 0, kv_conv = 0;
rad_buf b_ids = 0, b_emb = 0, b_embd = 0, b_k = 0, b_v = 0, b_gv = 0, b_gvn = 0, b_out = 0;
rad_op op_ids = 0, op_gather = 0, op_embd = 0, op_key = 0, op_value = 0;
rad_op op_gate = 0, op_conv = 0, op_add = 0;
int64_t hn() const { return c.hc * g.n_embd; }
/* The prompt that follows the step, bounded by what `b_ids` holds after the step's rows. */
int64_t ahead_rows(const RadBatch* batch) const {
const int64_t a = batch->n_ahead;
return a <= 0 ? 0 : (a < g.max_tok ? a : g.max_tok);
}
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(). */
void ids(RadCtx* c_, const RadBatch* batch) const;
void step(RadCtx* c_, const RadBatch* batch) const;
};
inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& cfg,
int layer, const Wire& wire, const Src& src) {
g = geom; c = cfg; w = wire;
if (c.hc <= 1 || c.heads <= 0 || c.ngram < 2 || c.eos < 0 || c.rows <= 0 ||
c.shards <= 0 || c.conv_width <= 1 || c.dilation <= 0 || c.embed_dim <= 0) {
fprintf(stderr, "radiance: ple: geometry refused -- hc %lld heads %lld ngram %lld eos "
"%lld rows %lld shards %lld width %lld dilation %lld embed %lld\n",
(long long)c.hc, (long long)c.heads, (long long)c.ngram, (long long)c.eos,
(long long)c.rows, (long long)c.shards, (long long)c.conv_width,
(long long)c.dilation, (long long)c.embed_dim);
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. */
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),
(long long)c.embed_dim);
return RAD_E_INVAL;
}
if (!w.h) return RAD_E_INVAL;
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 ==============================
*
* Replication is the RIGHT answer here, not a gap: sharding would be the mistake.
*
* 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.
*
* 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.
*/
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. */
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. */
RadEncoding te{};
table_bf16 = weight_enc(b, tn, &te) && rad_enc_is(&te, "plain") && te.n_planes == 1 &&
te.plane[0].dtype == RAD_BF16;
if (table_bf16) {
w_table = decl_w(b, tn, RAD_BF16, {c.rows, HD}, RAD_ACCESS_VOCAB, RAD_SHARD_NONE,
grp_model());
} else {
w_table = decl_view(b, tn, nullptr, "codes", RAD_F8E4M3, {c.rows, HD},
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
w_scale = decl_view(b, nm.f("blk.%d.ple_ngram.scale", layer), tn, "scale", RAD_BF16, {1},
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. */
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());
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_vocab_sizes", layer), src.vocab_sizes));
w_vsz = decl_w(b, nm.f("blk.%d.ple_vocab_sizes", layer), RAD_I64, {c.heads},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_offsets", layer), src.offsets));
w_off = decl_w(b, nm.f("blk.%d.ple_offsets", layer), RAD_I64, {c.heads},
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. */
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());
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_value.weight", layer), src.value_proj));
w_value = decl_w(b, nm.f("blk.%d.ple_value.weight", layer), RAD_BF16,
{g.n_embd, c.embed_dim}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_norm_key.weight", layer), src.norm_key));
w_nk = decl_w(b, nm.f("blk.%d.ple_norm_key.weight", layer), RAD_F32, {HN},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_norm_query.weight", layer), src.norm_query));
w_nq = decl_w(b, nm.f("blk.%d.ple_norm_query.weight", layer), RAD_F32, {HN},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_norm_conv.weight", layer), src.norm_conv));
w_nc = decl_w(b, nm.f("blk.%d.ple_norm_conv.weight", layer), RAD_F32, {HN},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
/* The checkpoint stores it [hc*n, 1, width]; the op wants [hc*n, width], which is the same
* bytes with the depthwise group axis dropped. */
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_conv.weight", layer), src.conv1d));
w_conv = decl_w(b, nm.f("blk.%d.ple_conv.weight", layer), RAD_BF16, {HN, c.conv_width},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
if (!w_table || (!table_bf16 && !w_scale) || !w_mult || !w_vsz || !w_off || !w_key || !w_value ||
!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.
*
* 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. */
{
RadKVGroupDecl td{};
td.kind = RAD_KV_CONV;
td.dtype = RAD_I32;
td.conv_width = c.ngram;
td.n_head_kv = 1;
td.head_dim = 1; /* one token id a slot */
kv_tok = rad_decl_kv_group(b, nm.f("kv_ple_tok"), &td);
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. */
cd.conv_width = c.hist() + 1;
cd.n_head_kv = 1;
cd.head_dim = HN; /* [n_states, hc*n_embd, hist + n_spec] */
kv_conv = rad_decl_kv_group(b, nm.f("kv_ple_conv"), &cd);
}
if (!kv_tok || !kv_conv) return RAD_E_INVAL;
RAD_ARCH_TRY(rad_bind_layer_kv(b, layer, kv_tok));
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.
*
* `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. */
{
/* 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. */
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. */
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. */
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});
b_gv = decl_b(b, nm.f("ple_gv"), g.act_dtype, {g.max_tok, HN});
b_gvn = decl_b(b, nm.f("ple_gvn"), g.act_dtype, {g.max_tok, HN});
b_out = decl_b(b, nm.f("ple_out"), g.act_dtype, {g.max_tok, HN});
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.
*
* ---- the ops, in the order step() issues them ------------------------------------------- */
layer_ = layer;
op_ids = rw(b, RAD_OP(b, "ngram_ids",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("heads", c.heads),
RAD_INT("ngram", c.ngram), RAD_INT("eos", c.eos)),
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)
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)),
{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),
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
RAD_NOWEIGHTS),
{b_emb}, {b_embd});
op_key = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", HN),
RAD_INT("K", c.embed_dim), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_key)),
{b_embd}, {b_k});
op_value = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", g.n_embd),
RAD_INT("K", c.embed_dim), RAD_STR("dtype", g.dtype)),
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. */
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),
RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd)),
RAD_WEIGHTS(w_nk, w_nq, w_nc)),
{b_k, w.h, b_v}, {b_gv, b_gvn});
op_conv = rw(b, RAD_OP(b, "ple_conv",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", HN),
RAD_INT("width", c.conv_width), RAD_INT("dilation", c.dilation),
RAD_STR("dtype", g.dtype)),
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. */
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)),
RAD_NOWEIGHTS),
{w.h, b_out}, {w.h});
if (!op_ids || !op_gather || !op_embd || !op_key || !op_value || !op_gate || !op_conv ||
!op_add)
return RAD_E_INVAL;
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.
*
* 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 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. */
inline void PleLayer::ids(RadCtx* c_, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
const int64_t S = batch->n_seq;
const RadKVGroupBatch* tk = kv_batch(batch, kv_tok);
const int32_t* tk_idx = tk ? tk->state_index : nullptr;
int64_t D = 0, DT = 0;
batch_split(batch, &D, &DT);
const int64_t P = S - D;
if (D > 0)
RAD_ISSUE_N(c_, op_ids, DT,
praw(batch->token_ids, RAD_I32, DT), kv_cache(kv_tok, layer_),
praw(batch->cu_seqlens, RAD_I32, D + 1),
RAD_W(w_mult), RAD_W(w_vsz), RAD_W(w_off),
praw(tk_idx, RAD_I32, D),
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. */
const int64_t A = P > 0 ? ahead_rows(batch) : 0;
if (P > 0)
RAD_ISSUE_N(c_, op_ids, T,
praw(batch->token_ids, RAD_I32, T + A), kv_cache(kv_tok, layer_),
praw(batch->cu_seqlens + D, RAD_I32, P + 1),
RAD_W(w_mult), RAD_W(w_vsz), RAD_W(w_off),
praw(tk_idx ? tk_idx + D : nullptr, RAD_I32, P),
praw(batch->ctx_lens + D, RAD_I32, P),
RAD_NONE,
brows(b_ids, T),
A > 0 ? brow_slice(b_ids, T, A, c.heads) : RAD_NONE);
}
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;
int64_t D = 0, DT = 0;
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. */
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));
RAD_ISSUE_N(c_, op_value, T, brows(b_embd, T), RAD_W(w_value), brows(b_v, T));
RAD_ISSUE_N(c_, op_gate, T,
brows(b_k, T), brows(w.h, T), brows(b_v, T),
RAD_W(w_nk), RAD_W(w_nq), RAD_W(w_nc),
brows(b_gv, T), brows(b_gvn, T));
if (D > 0)
RAD_ISSUE_N(c_, op_conv, DT,
brows(b_gvn, DT), RAD_W(w_conv), kv_cache(kv_conv, layer_),
praw(batch->cu_seqlens, RAD_I32, D + 1), brows(b_gv, DT),
praw(cv_idx, RAD_I32, D),
praw(batch->ctx_lens, RAD_I32, D),
praw(batch->num_accepted, RAD_I32, D),
brows(b_out, DT));
if (P > 0)
RAD_ISSUE_N(c_, op_conv, T,
brows(b_gvn, T), RAD_W(w_conv), kv_cache(kv_conv, layer_),
praw(batch->cu_seqlens + D, RAD_I32, P + 1), brows(b_gv, T),
praw(cv_idx ? cv_idx + D : nullptr, RAD_I32, P),
praw(batch->ctx_lens + D, RAD_I32, P),
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. */
RAD_ISSUE_N(c_, op_add, T, brows(w.h, T), brows(b_out, T), brows(w.h, T));
}
} /* namespace arch */
} /* namespace rad */
#endif /* RAD_BLOCK_PLE_H */
-345
View File
@@ -1,345 +0,0 @@
/* rad_block_vit.h -- the Qwen-VL vision tower (Qwen2.5-VL / Qwen3-VL / Qwen3.5 / Qwen3.8), and the
* scatter that puts its rows into a language model's embeddings.
*
* WHAT IT COMPUTES, per encoder pass (RadBatch::enc):
*
* x = patches @ Wp^T + bp the Conv3d patch embedding, as a linear layer:
* a patch row is (channel, frame, y, x)
* x += pos_embed resampled to each segment's grid bilinear, corners aligned (grid_embed)
* depth times:
* x += proj(attn(rope(qkv(LN1(x))))) full attention within a segment (one image, or
* one temporal group of a video), 2-D rotary over
* (row, column) -- `axial` with half the rotated
* width a side, each on its own ladder
* 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 with no deepstack taps (the checkpoints this tree
* serves list none, and one that did would be refused at declare). Every linear layer is
* `gemm_nt_bias` with its activation and residual in the epilogue, each 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
* 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).
*/
#ifndef RAD_BLOCK_VIT_H
#define RAD_BLOCK_VIT_H
#include "rad_arch.h"
#include <cmath>
#include <cstdio>
#include <cstring>
#include <vector>
namespace rad {
namespace arch {
struct VisionTower {
/* Geometry, from the container's vision_config. */
int64_t depth = 0, width = 0, heads = 0, ff = 0, patch = 0, temporal = 0, chans = 0;
int64_t merge = 0, side = 0, n_embd = 0, head_dim = 0, patch_dim = 0, P = 0;
float eps = 1e-6f, theta = 10000.0f;
bool on = false;
struct Layer {
rad_weight n1w = 0, n1b = 0, n2w = 0, n2b = 0;
rad_weight qkv_w = 0, qkv_b = 0, out_w = 0, out_b = 0;
rad_weight up_w = 0, up_b = 0, down_w = 0, down_b = 0;
rad_op ln1 = 0, qkv = 0, rope = 0, attn = 0, proj = 0, ln2 = 0, up = 0, down = 0;
};
std::vector<Layer> L;
rad_weight w_patch = 0, b_patch = 0, w_pos = 0;
rad_weight mn_w = 0, mn_b = 0, m1_w = 0, m1_b = 0, m2_w = 0, m2_b = 0;
rad_op op_patch = 0, op_pos = 0, op_mln = 0, op_m1 = 0, op_m2 = 0;
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] = {};
/* 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. */
static bool present(const RadModelMeta* m) {
return rad_meta_geti(m, "vision_config.depth", 0) > 0;
}
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
int64_t model_embd, int first_group);
void step(RadCtx* c, const RadBatch* batch) const;
};
inline int VisionTower::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;
depth = rad_meta_geti(m, "vision_config.depth", 0);
width = rad_meta_geti(m, "vision_config.hidden_size", 0);
heads = rad_meta_geti(m, "vision_config.num_heads", 0);
ff = rad_meta_geti(m, "vision_config.intermediate_size", 0);
patch = rad_meta_geti(m, "vision_config.patch_size", 0);
temporal = rad_meta_geti(m, "vision_config.temporal_patch_size", 0);
chans = rad_meta_geti(m, "vision_config.in_channels", 3);
merge = rad_meta_geti(m, "vision_config.spatial_merge_size", 0);
n_embd = rad_meta_geti(m, "vision_config.out_hidden_size", 0);
const int64_t npos = rad_meta_geti(m, "vision_config.num_position_embeddings", 0);
theta = (float)rad_meta_getf(m, "vision_config.rope_parameters.rope_theta",
rad_meta_getf(m, "vision_config.rope_theta", 10000.0));
side = (int64_t)std::llround(std::sqrt((double)npos));
if (depth <= 0 || width <= 0 || heads <= 0 || ff <= 0 || patch <= 0 || temporal <= 0 ||
merge <= 0 || n_embd <= 0 || side <= 0 || side * side != npos || width % heads) {
fprintf(stderr, "radiance: the container's vision_config is incomplete or inconsistent "
"(depth %lld, hidden %lld, heads %lld, ff %lld, patch %lld, merge %lld, "
"positions %lld)\n", (long long)depth, (long long)width, (long long)heads,
(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. */
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 this block does not carry. Refused by name rather than dropped. */
const char* ds = rad_meta_gets(m, "vision_config.deepstack_visual_indexes", "");
for (const char* q = ds; q && *q; ++q)
if (*q >= '0' && *q <= '9') {
fprintf(stderr, "radiance: this vision tower has deepstack taps (%s), which this plugin "
"does not serve\n", ds);
return RAD_E_UNSUPPORTED;
}
const char* act = rad_meta_gets(m, "vision_config.hidden_act", "gelu_pytorch_tanh");
if (std::strcmp(act, "gelu_pytorch_tanh") && std::strcmp(act, "gelu")) {
fprintf(stderr, "radiance: vision_config.hidden_act '%s' is not served\n", act);
return RAD_E_UNSUPPORTED;
}
const char* mlp_act = std::strcmp(act, "gelu") ? "gelu_tanh" : "gelu";
head_dim = width / heads;
patch_dim = chans * temporal * patch * patch;
/* The 2-D rotary: half the head a side, each on its own ladder. */
if (head_dim % 4) return RAD_E_SHAPE;
std::snprintf(sec, sizeof sec, "%lld %lld", (long long)(head_dim / 4), (long long)(head_dim / 4));
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. */
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. */
const int64_t r = std::min<int64_t>(P, ctx->max_tok);
P = std::max<int64_t>(mm, r / mm * mm);
}
if (P % mm) return RAD_E_SHAPE;
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. */
auto bw = [&](const char* dn, const char* src, uint32_t dt, std::initializer_list<int64_t> shp,
RadWeightGroup g) -> rad_weight {
/* the map first: it is how the checkpoint is asked what the weight is */
if (map_copy(b, dn, src) < 0) return 0;
return decl_w(b, dn, dt, shp, ACC, RAD_SHARD_NONE, g);
};
w_patch = bw(nm.f("v.patch.weight"), nm.ckpt("model.visual.patch_embed.proj.weight"),
RAD_BF16, { width, patch_dim }, grp_model());
b_patch = bw(nm.f("v.patch.bias"), nm.ckpt("model.visual.patch_embed.proj.bias"),
RAD_BF16, { width }, grp_model());
w_pos = bw(nm.f("v.pos.weight"), nm.ckpt("model.visual.pos_embed.weight"),
RAD_BF16, { npos, width }, grp_model());
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;
l.n1w = bw(nm.f("v.blk.%d.norm1.weight", li), nm.ckpt("model.visual.blocks.%d.norm1.weight", li), RAD_BF16, { width }, g);
l.n1b = bw(nm.f("v.blk.%d.norm1.bias", li), nm.ckpt("model.visual.blocks.%d.norm1.bias", li), RAD_BF16, { width }, g);
l.qkv_w = bw(nm.f("v.blk.%d.qkv.weight", li), nm.ckpt("model.visual.blocks.%d.attn.qkv.weight", li), RAD_BF16, { 3 * width, width }, g);
l.qkv_b = bw(nm.f("v.blk.%d.qkv.bias", li), nm.ckpt("model.visual.blocks.%d.attn.qkv.bias", li), RAD_BF16, { 3 * width }, g);
l.out_w = bw(nm.f("v.blk.%d.proj.weight", li), nm.ckpt("model.visual.blocks.%d.attn.proj.weight", li), RAD_BF16, { width, width }, g);
l.out_b = bw(nm.f("v.blk.%d.proj.bias", li), nm.ckpt("model.visual.blocks.%d.attn.proj.bias", li), RAD_BF16, { width }, g);
l.n2w = bw(nm.f("v.blk.%d.norm2.weight", li), nm.ckpt("model.visual.blocks.%d.norm2.weight", li), RAD_BF16, { width }, g);
l.n2b = bw(nm.f("v.blk.%d.norm2.bias", li), nm.ckpt("model.visual.blocks.%d.norm2.bias", li), RAD_BF16, { width }, g);
l.up_w = bw(nm.f("v.blk.%d.fc1.weight", li), nm.ckpt("model.visual.blocks.%d.mlp.linear_fc1.weight", li), RAD_BF16, { ff, width }, g);
l.up_b = bw(nm.f("v.blk.%d.fc1.bias", li), nm.ckpt("model.visual.blocks.%d.mlp.linear_fc1.bias", li), RAD_BF16, { ff }, g);
l.down_w = bw(nm.f("v.blk.%d.fc2.weight", li), nm.ckpt("model.visual.blocks.%d.mlp.linear_fc2.weight", li), RAD_BF16, { width, ff }, g);
l.down_b = bw(nm.f("v.blk.%d.fc2.bias", li), nm.ckpt("model.visual.blocks.%d.mlp.linear_fc2.bias", li), RAD_BF16, { width }, g);
}
mn_w = bw(nm.f("v.merger.norm.weight"), nm.ckpt("model.visual.merger.norm.weight"), RAD_BF16, { width }, grp_model());
mn_b = bw(nm.f("v.merger.norm.bias"), nm.ckpt("model.visual.merger.norm.bias"), RAD_BF16, { width }, grp_model());
m1_w = bw(nm.f("v.merger.fc1.weight"), nm.ckpt("model.visual.merger.linear_fc1.weight"), RAD_BF16, { mm * width, mm * width }, grp_model());
m1_b = bw(nm.f("v.merger.fc1.bias"), nm.ckpt("model.visual.merger.linear_fc1.bias"), RAD_BF16, { mm * width }, grp_model());
m2_w = bw(nm.f("v.merger.fc2.weight"), nm.ckpt("model.visual.merger.linear_fc2.weight"), RAD_BF16, { n_embd, mm * width }, grp_model());
m2_b = bw(nm.f("v.merger.fc2.bias"), nm.ckpt("model.visual.merger.linear_fc2.bias"), RAD_BF16, { n_embd }, grp_model());
if (!w_patch || !b_patch || !w_pos || !mn_w || !mn_b || !m1_w || !m1_b || !m2_w || !m2_b)
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. */
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 });
b_att = decl_b(b, nm.f("v.att"), RAD_BF16, { P, width });
b_ff = decl_b(b, nm.f("v.ff"), RAD_BF16, { P, ff });
b_mh = decl_b(b, nm.f("v.mh"), RAD_BF16, { R, mm * width });
b_mf = decl_b(b, nm.f("v.mf"), RAD_BF16, { R, mm * width });
b_out = decl_b(b, nm.f("v.out"), RAD_BF16, { R, n_embd });
if (!b_x || !b_h || !b_qkv || !b_att || !b_ff || !b_mh || !b_mf || !b_out) return RAD_E_INVAL;
auto gemm = [&](int64_t rows, int64_t N, int64_t K, const char* a, rad_weight w,
rad_weight bias) -> rad_op {
return RAD_OP(b, "gemm_nt_bias",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K),
RAD_STR("dtype", "bf16"), RAD_STR("act", a)),
RAD_WEIGHTS(w, bias));
};
auto lnorm = [&](int64_t rows, rad_weight w, rad_weight bias) -> rad_op {
return RAD_OP(b, "layernorm",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width),
RAD_F64("eps", eps), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w, bias));
};
op_patch = rw(b, gemm(P, width, patch_dim, "none", w_patch, b_patch), {}, { b_x });
op_pos = rw(b, RAD_OP(b, "grid_embed",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
RAD_INT("side", side), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_pos)),
{ b_x }, { b_x });
for (Layer& l : L) {
l.ln1 = rw(b, lnorm(P, l.n1w, l.n1b), { b_x }, { b_h });
l.qkv = rw(b, gemm(P, 3 * width, width, "none", l.qkv_w, l.qkv_b), { b_h }, { b_qkv });
l.rope = rw(b, RAD_OP(b, "rope",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", head_dim),
RAD_INT("n_head", heads), RAD_INT("n_head_kv", heads),
RAD_F64("theta", theta), RAD_F64("scale", 1.0),
RAD_STR("mode", "axial"),
RAD_INT("rotary_dim", head_dim),
RAD_STR("sections", sec)),
RAD_NOWEIGHTS),
{ b_qkv }, { b_qkv });
l.attn = rw(b, RAD_OP(b, "attn_dense",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", head_dim),
RAD_INT("gqa", 1), RAD_INT("causal", 0),
RAD_STR("dtype", "bf16"),
RAD_F64("scale", 1.0 / std::sqrt((double)head_dim)),
RAD_INT("max_seqlen", max_seg)),
RAD_NOWEIGHTS),
{ b_qkv }, { b_att });
l.proj = rw(b, gemm(P, width, width, "none", l.out_w, l.out_b), { b_att, b_x }, { b_x });
l.ln2 = rw(b, lnorm(P, l.n2w, l.n2b), { b_x }, { b_h });
l.up = rw(b, gemm(P, ff, width, mlp_act, l.up_w, l.up_b), { b_h }, { b_ff });
l.down = rw(b, gemm(P, width, ff, "none", l.down_w, l.down_b), { b_ff, b_x }, { b_x });
}
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 });
if (!ctx->shape_probe) {
RadEncoderDecl e{};
e.name = "vision";
e.modalities = RAD_MM_IMAGE | RAD_MM_VIDEO;
e.patch_dim = patch_dim;
e.merge = mm;
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 blocks of %lld (%lld heads x %lld), ff %lld, patch %lld x "
"%lld x %lld, merge %lld; %lld patches a pass -> %lld rows of %lld",
(long long)depth, (long long)width, (long long)heads, (long long)head_dim,
(long long)ff, (long long)temporal, (long long)patch, (long long)patch,
(long long)merge, (long long)P, (long long)R, (long long)n_embd);
}
on = true;
return RAD_OK;
}
inline void VisionTower::step(RadCtx* c, const RadBatch* batch) const {
const int64_t Pn = batch->enc_n_patch, S = batch->enc_n_seg;
const int64_t mm = merge * merge, Rn = Pn / mm;
if (!on || Pn <= 0 || Pn > P || Pn % mm || S <= 0) {
rad_step_fail(c, "an encoder pass this program's vision tower cannot serve: no tower, or "
"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. */
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);
const RadOperand cu = praw(batch->enc_cu, RAD_I32, S + 1);
RAD_ISSUE_N(c, op_patch, Pn, pix, RAD_W(w_patch), RAD_W(b_patch), RAD_NONE, brows(b_x, Pn));
RAD_ISSUE_N(c, op_pos, Pn, brows(b_x, Pn), RAD_W(w_pos), crd);
for (const Layer& l : L) {
RAD_ISSUE_N(c, l.ln1, Pn, brows(b_x, Pn), RAD_W(l.n1w), RAD_W(l.n1b), brows(b_h, Pn));
RAD_ISSUE_N(c, l.qkv, Pn, brows(b_h, Pn), RAD_W(l.qkv_w), RAD_W(l.qkv_b), RAD_NONE,
brows(b_qkv, Pn));
RAD_ISSUE_N(c, l.rope, Pn, brows(b_qkv, Pn), rc);
RAD_ISSUE_N(c, l.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.proj, Pn, brows(b_att, Pn), RAD_W(l.out_w), RAD_W(l.out_b),
brows(b_x, Pn), brows(b_x, Pn));
RAD_ISSUE_N(c, l.ln2, Pn, brows(b_x, Pn), RAD_W(l.n2w), RAD_W(l.n2b), brows(b_h, Pn));
RAD_ISSUE_N(c, l.up, Pn, brows(b_h, Pn), RAD_W(l.up_w), RAD_W(l.up_b), RAD_NONE,
brows(b_ff, Pn));
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 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. */
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));
RAD_ISSUE_N(c, op_m2, Rn, brows(b_mf, Rn), RAD_W(m2_w), RAD_W(m2_b), RAD_NONE,
brows(b_out, Rn));
}
/* ================================================================== 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.
*
* 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. */
struct MediaRows {
rad_op op = 0;
int64_t n_embd = 0;
int declare(RadBuilder* b, int64_t max_tok, int64_t width, rad_buf embd) {
n_embd = width;
op = rw(b, RAD_OP(b, "scatter_rows",
RAD_PARAMS(RAD_RANGE("M", 1, max_tok), RAD_INT("n", width),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ embd }, { embd });
return op ? RAD_OK : RAD_E_INVAL;
}
/* `embd` narrowed to this pass's tokens; nothing is issued on a pass with no media rows. */
void step(RadCtx* c, const RadBatch* batch, rad_buf embd, int64_t T) const {
if (!op || batch->n_mm_rows <= 0) return;
RAD_ISSUE_N(c, op, batch->n_mm_rows,
praw2(batch->mm_embd, RAD_BF16, batch->n_mm_rows, n_embd),
praw(batch->mm_rows, RAD_I32, batch->n_mm_rows), brows(embd, T));
}
};
} /* namespace arch */
} /* namespace rad */
#endif /* RAD_BLOCK_VIT_H */
File diff suppressed because it is too large. Load diff
-456
View File
@@ -1,456 +0,0 @@
/* 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.
*
* 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.
*
* 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.
*/
#ifndef RAD_QSA_H
#define RAD_QSA_H
#include "rad_arch.h"
#include "rad_fp8.h"
namespace rad {
namespace arch {
struct QsaIndexer {
struct Config {
int64_t heads = 0; /* indexer_n_heads -- 4 */
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 */
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. */
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. */
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(). */
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. */
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. */
bool emit_sel = true;
};
/* 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.
*
* 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. */
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. */
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.
*
* `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. */
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. */
rad_buf cos_sin = 0;
};
Geom g{};
Config c{};
Wire w{};
int layer = 0;
rad_weight w_qn = 0, w_kn = 0;
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. */
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. */
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;
};
inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
const Config& cfg, const Wire& wire, const ActFP8& in,
rad_kvgroup* bk) {
g = geom; c = cfg; w = wire; layer = 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. */
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 */
RAD_ARCH_TRY(proj.declare(b, nm, g, nm.f("blk.%d.qsa_qk", l), nw, g.n_embd,
RAD_SHARD_NONE, grp_layer(l), { c.qk_proj }, in, w.qk));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.qsa_q_norm.weight", l), c.q_norm));
w_qn = decl_w(b, nm.f("blk.%d.qsa_q_norm.weight", l), RAD_F32, { c.head_dim },
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.
*
* 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. */
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)
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),
RAD_INT("n_head_kv", c.heads), RAD_INT("rot", c.rot),
RAD_STR("q_dtype", g.dtype), RAD_F64("eps", g.eps),
RAD_F64("wadd", g.wadd_qk), RAD_INT("cs_f32", 1)),
RAD_WEIGHTS(w_qn)),
{w.qk, w.cos_sin}, {w.q});
op_norm = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", c.head_dim),
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_qn)),
{w.qk}, {w.q});
op_rope = rw(b, decl_rope(b, g, g.max_tok, c.head_dim, c.heads, 0, c.rot, c.mode),
{w.q}, {w.q});
/* ---- the block-key path. Nothing below reads anything above except `w.qk`'s raw-key half. */
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. */
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 },
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
if (!w_kn) return RAD_E_INVAL;
op_work = rw(b, RAD_OP(b, "qsa_work",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", c.head_dim),
RAD_INT("ratio", c.ratio), RAD_INT("ring", c.ring),
RAD_INT("seqs", g.max_seqs),
RAD_INT("work", c.max_work), RAD_STR("dtype", g.dtype)),
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. */
if (*bk == 0) {
if ((c.head_dim % (2 * c.ratio)) != 0) return RAD_E_SHAPE;
RadKVGroupDecl d{};
d.kind = RAD_KV_FULL;
d.dtype = RAD_BF16;
d.n_head_kv = 1;
d.head_dim = c.head_dim / (2 * c.ratio);
*bk = rad_decl_kv_group(b, nm.f("kv_qsa_bkey"), &d);
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
? RAD_OP(b, "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))
: RAD_OP(b, "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}, {});
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, kv_bk));
op_tail = rw(b, RAD_OP(b, "qsa_tail_store",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", c.head_dim),
RAD_INT("ratio", c.ratio), RAD_INT("ring", c.ring),
RAD_INT("seqs", g.max_seqs),
RAD_STR("dtype", g.dtype)),
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. */
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),
RAD_INT("seqs", g.max_seqs), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.q, w.nc}, {w.score});
op_select = rw(b, RAD_OP(b, "qsa_select",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
RAD_INT("blocks", c.max_blocks), RAD_INT("topk", c.topk),
RAD_INT("ratio", c.ratio), RAD_INT("seqs", g.max_seqs)),
RAD_NOWEIGHTS),
{w.score, w.nc}, {w.sel, w.nsel, w.sequ});
return RAD_OK;
}
inline void QsaIndexer::step(RadCtx* c_, const ActFP8& in, const RadBatch* batch) 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;
const int64_t koff = qw; /* the raw-key head, after the query heads */
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. */
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),
RAD_NONE, RAD_W(w_qn),
RAD_NONE, brows(w.q, T), RAD_NONE);
} else {
for (int64_t h = 0; h < c.heads; ++h)
RAD_ISSUE_N(c_, op_norm, T,
bcol_at(w.qk, 0, nw, h * c.head_dim, c.head_dim, T), RAD_W(w_qn),
bcol_at(w.q, 0, qw, h * c.head_dim, c.head_dim, T));
RAD_ISSUE_N(c_, op_rope, T, brows(w.q, T), rope_posmc(g, batch, T));
}
const RadKVGroupBatch* bkb = kv_batch(batch, kv_bk);
const RadKVGroupBatch* atb = kv_batch(batch, c.kv_attn);
const RadKVGroupBatch* tlb = kv_batch(batch, c.kv_tail);
if (!bkb || !atb || !tlb) return;
/* 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. */
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. */
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. */
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;
RAD_ISSUE_N(c_, op_work, T,
bcol_at(w.qk, 0, nw, koff, c.head_dim, T),
praw(batch->positions, RAD_I32, T),
praw(batch->cu_seqlens, RAD_I32, S + 1),
kv_cache(c.kv_tail, layer),
praw2(tlb->state_index, RAD_I32, S, tw),
praw2(bkb->block_table, RAD_I32, S, bkb->block_table_pitch),
mc ? praw2(batch->rope_pos, RAD_I32, 3, T) : RAD_NONE,
brows(w.stage, work * c.ratio), brows(w.page, work), bpos,
brows(w.nc, S));
RAD_ISSUE_N(c_, op_bkey, work,
brows(w.stage, work * c.ratio), RAD_W(w_kn),
brows(w.page, work), bpos,
kv_cache(kv_bk, layer));
RAD_ISSUE_N(c_, op_tail, T,
bcol_at(w.qk, 0, nw, koff, c.head_dim, T),
praw(batch->positions, RAD_I32, T),
praw(batch->cu_seqlens, RAD_I32, S + 1),
kv_cache(c.kv_tail, layer),
praw2(tlb->state_index, RAD_I32, S, tw));
/* 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. */
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`.
*
* 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. */
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;
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),
praw(batch->cu_seqlens, RAD_I32, S + 1), brows(w.nc, S),
bcol_at(w.score, 0, c.max_blocks, 0, live, T));
RAD_ISSUE_N(c_, op_select, T,
bcol_at(w.score, 0, c.max_blocks, 0, live, T),
praw2(atb->block_table, RAD_I32, S, atb->block_table_pitch),
brows(w.nc, S), praw(batch->positions, RAD_I32, T),
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) {
rad_stream_sync(rad_stream(c_));
std::vector<int32_t> hnc(1), hns(1), hsu(1), hsel(8);
std::vector<float> hsc(8);
rad_memcpy_async(hnc.data(), rad_buf_ptr(c_, w.nc), 4, rad_stream(c_));
rad_memcpy_async(hns.data(), rad_buf_ptr(c_, w.nsel), 4, rad_stream(c_));
rad_memcpy_async(hsu.data(), rad_buf_ptr(c_, w.sequ), 4, rad_stream(c_));
rad_memcpy_async(hsel.data(), rad_buf_ptr(c_, w.sel), 32, rad_stream(c_));
rad_memcpy_async(hsc.data(), rad_buf_ptr(c_, w.score), 32, rad_stream(c_));
rad_stream_sync(rad_stream(c_));
std::fprintf(stderr, "D qsa L%d nc=%d nsel=%d sequ=%d sel[%d %d %d %d] "
"score[%.4g %.4g %.4g %.4g]\n", layer,
hnc[0], hns[0], hsu[0], hsel[0], hsel[1], hsel[2], hsel[3],
hsc[0], hsc[1], hsc[2], hsc[3]);
}
}
}
} /* namespace arch */
} /* namespace rad */
#endif /* RAD_QSA_H */
-11
View File
@@ -1,11 +0,0 @@
# 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=<radiance prefix>`) -- the same
# rad_add_plugin either way (cmake/RadAddPlugin.cmake).
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(llama_dense_fp8 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(llama_dense_fp8 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/llama_dense_fp8.cpp)
-19
View File
@@ -1,19 +0,0 @@
/* llama_dense_fp8 -- arch/llama_fp8 over a checkpoint that was never quantised.
*
* 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.
*
* 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.
*/
#define LLAMA_DENSE_SRC 1
#define LLAMA_NS llama_dense_fp8
#define LLAMA_QUANT ""
#include "../llama_fp8/llama_fp8.cpp"
-11
View File
@@ -1,11 +0,0 @@
# 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=<radiance prefix>`) -- the same
# rad_add_plugin either way (cmake/RadAddPlugin.cmake).
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(llama_fp8 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(llama_fp8 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/llama_fp8.cpp)
-759
View File
@@ -1,759 +0,0 @@
/* llama_fp8 -- the plain LLaMA graph with block-scaled FP8 weights and FP8 activations.
*
* ============================== 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.
*
* ============================== TWO CHECKPOINT FORMATS, ONE GRAPH ==============================
*
* The selection key is the PAIR (architecture, quantisation) -- 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.
*
* 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.
*
* ============================== 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.
*/
#ifndef LLAMA_DENSE_SRC
#define LLAMA_DENSE_SRC 0
#endif
#ifndef LLAMA_NS
#define LLAMA_NS llama_fp8
#endif
#ifndef LLAMA_QUANT
#define LLAMA_QUANT "fp8_e4m3"
#endif
#include <cstdlib>
#include <cstring>
#include <vector>
#include <arch/rad_arch.h>
#include <arch/rad_block_attn_fp8.h>
#include <arch/rad_block_dspark.h>
#include <arch/rad_block_mlp_fp8.h>
namespace LLAMA_NS {
using namespace rad::arch;
struct Layer {
AttnFP8 attn;
MlpFP8 mlp;
};
struct Model {
Names nm{""};
Geom g{};
int64_t n_rot = 0;
int64_t n_main = 0;
rad_kvgroup kv_full = 0;
rad_buf b_x = 0, b_hout = 0, b_logits = 0;
ActFP8 a_h{};
rad_buf b_qkv = 0;
rad_buf b_q = 0;
ActFP8 a_attn{};
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. */
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. */
Dspark ds{};
Dspark::Wire dsw{};
rad_kvgroup kv_draft = 0;
bool have_ds = false;
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;
std::vector<Layer> 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. */
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);
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)");
return RAD_E_UNSUPPORTED;
}
#endif
if (meta->n_expert > 0) {
fprintf(stderr, "radiance: llama has no routed feed-forward and this checkpoint declares "
"%lld experts\n", (long long)meta->n_expert);
return RAD_E_UNSUPPORTED;
}
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.*`.
*
* 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).
*
* 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. */
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));
dg.rope_scale = 1.0f;
/* 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;
}
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;
}
Dspark::Config dc{};
dc.n_taps = m.n_taps;
dc.rank = rad_meta_geti(meta, "draft.markov_rank", 0);
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. */
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 "
"candidates a position\n", (long long)dc.top_k);
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.
*
* 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. */
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 "
"number of masked positions it denoises is not a number this engine may "
"choose.\n");
return RAD_E_FORMAT;
}
if ((long long)ctx->max_spec != trained) {
fprintf(stderr, "radiance: the DSpark drafter was trained at block_size %lld, which is "
"%lld draft tokens, and this serve asks for %d. A block-diffusion drafter "
"denoises a fixed number of mask positions; run it at %lld.\n",
trained, trained, ctx->max_spec, trained);
return RAD_E_UNSUPPORTED;
}
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. */
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 "
"markov_head_type '%s'. Only the rank-N 'vanilla' bigram head is "
"implemented, and it is what the published checkpoints ship.\n",
(long long)dc.rank, mh ? mh : "(none)");
return RAD_E_UNSUPPORTED;
}
if (dc.rank % 32 || dc.rank > 512) {
fprintf(stderr, "radiance: markov_rank %lld; the walk that applies the bigram bias takes "
"a multiple of 32 up to 512\n", (long long)dc.rank);
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);
/* 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. */
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;
if (qr > dg.max_tok) qr = dg.max_tok;
const int64_t sr = dg.max_seqs * dc.steps();
const int64_t spad = ((sr + 15) / 16) * 16;
Dspark::Wire& dw = m.dsw;
dw.src = m.b_dfsrc;
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. */
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)});
dw.cq = decl_b(b, nm.f("ds_cq"), RAD_F8E4M3, {dg.max_tok, dg.n_embd});
dw.cs = decl_b(b, nm.f("ds_cs"), RAD_F32, {dg.max_tok, fp8_blocks(dg.n_embd)});
dw.x = decl_b(b, nm.f("ds_x"), dg.act_dtype, {qr, dg.n_embd});
dw.h.x = decl_b(b, nm.f("ds_h"), dg.act_dtype, {qr, dg.n_embd});
dw.h.q = decl_b(b, nm.f("ds_h.q"), RAD_F8E4M3, {qr, dg.n_embd});
dw.h.s = decl_b(b, nm.f("ds_h.s"), RAD_F32, {qr, fp8_blocks(dg.n_embd)});
dw.q = decl_b(b, nm.f("ds_q"), dg.act_dtype, {qr, qd});
dw.k = decl_b(b, nm.f("ds_k"), dg.act_dtype, {qr, kvd});
dw.v = decl_b(b, nm.f("ds_v"), dg.act_dtype, {qr, kvd});
dw.attn.x = decl_b(b, nm.f("ds_attn"), dg.act_dtype, {qr, qd});
dw.attn.q = decl_b(b, nm.f("ds_attn.q"), RAD_F8E4M3, {qr, qd});
dw.attn.s = decl_b(b, nm.f("ds_attn.s"), RAD_F32, {qr, fp8_blocks(qd)});
dw.gate_up = decl_b(b, nm.f("ds_gate_up"), dg.act_dtype, {qr, 2 * dg.n_ff});
dw.ffn.x = decl_b(b, nm.f("ds_ffn"), dg.act_dtype, {qr, dg.n_ff});
dw.ffn.q = decl_b(b, nm.f("ds_ffn.q"), RAD_F8E4M3, {qr, dg.n_ff});
dw.ffn.s = decl_b(b, nm.f("ds_ffn.s"), RAD_F32, {qr, fp8_blocks(dg.n_ff)});
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. */
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. */
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});
if (Dspark::head_sharded(dg)) {
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. */
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. */
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. */
RadDrafterDecl drf{};
drf.name = "dspark";
drf.kind = RAD_DRAFT_BLOCK;
drf.depth = ctx->max_spec;
drf.block = dc.block;
drf.proposal = dw.tokens;
drf.proposal_pitch = dc.steps();
drf.window = dc.window;
drf.mask_token = (int32_t)rad_meta_geti(meta, "draft.mask_token_id", -1);
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");
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`",
(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 + <markov_w1[prev], markov_w2[cand]>` 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",
(long long)dc.rank, (long long)dc.top_k);
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;
Model& m = g_model[ctx->rank];
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. */
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". */
{
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);
m.n_rot = prf > 0.0 ? (int64_t)(g.head_dim * prf) : g.head_dim;
}
if (m.n_rot <= 0 || m.n_rot > g.head_dim || (m.n_rot & 1)) {
fprintf(stderr, "radiance: llama: rotary width %lld is not an even width inside head_dim "
"%lld\n", (long long)m.n_rot, (long long)g.head_dim);
return RAD_E_INVAL;
}
/* ---- the KV cache. One group: every layer is full attention. */
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);
g.kv_dtype = rad_dtype_name(fd.dtype);
/* ---- activations. */
const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim();
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));
m.b_qkv = decl_b(b, nm.f("attn_qkv"), g.act_dtype, {g.max_tok, q_dim + 2 * 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});
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", q_dim));
m.b_gate_up = decl_b(b, nm.f("gate_up"), g.act_dtype, {g.max_tok, 2 * g.n_ff});
m.a_ffn.x = decl_b(b, nm.f("ffn"), g.act_dtype, {g.max_tok, g.n_ff});
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.
*
* 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. */
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);
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});
m.op_tap = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
RAD_INT("n", g.n_embd),
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
RAD_NOWEIGHTS),
{m.b_x}, {m.b_dfsrc});
} else {
fprintf(stderr, "radiance: llama: the container carries a '%s' drafter but names "
"no trunk layer this model has; it is paired with a different "
"target\n", da);
return RAD_E_UNSUPPORTED;
}
}
}
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. */
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"),
nm.ckpt("model.embed_tokens.weight")));
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});
/* 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. */
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});
AttnFP8::Wire aw{};
aw.x = m.b_x; aw.h = m.a_h; aw.qkv = m.b_qkv; aw.q = m.b_q; aw.attn = m.a_attn;
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;
const char* pre = "model.layers";
AttnFP8::Src as{};
as.norm = nm.ckpt("%s.%lld.input_layernorm.weight", pre, (long long)l);
as.q = nm.ckpt("%s.%lld.self_attn.q_proj.weight", pre, (long long)l);
as.k = nm.ckpt("%s.%lld.self_attn.k_proj.weight", pre, (long long)l);
as.v = nm.ckpt("%s.%lld.self_attn.v_proj.weight", pre, (long long)l);
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));
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));
}
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.a_h.x});
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.a_h.x}, {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});
/* THE DRAFTER IS DECLARED LAST, AFTER `op_logits`, AND THE ORDER IS LOAD-BEARING.
*
* 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.
*
* 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. */
if (m.n_taps > 0)
RAD_ARCH_TRY(declare_dspark(b, meta, ctx, m, (int)m.n_main));
rad_note(b, "rank %d/%d: %lld layers, all full attention; n_head=%lld n_head_kv=%lld "
"head_dim=%lld rot=%lld n_ff=%lld vocab=[%lld,%lld)",
g.rank, g.world, (long long)m.n_main, (long long)g.n_head, (long long)g.n_head_kv,
(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_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");
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, "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",
(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. */
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");
return;
}
if (batch->draft_pass > 0) m.ds.step(c, batch);
else m.ds.context(c, batch);
return;
}
RAD_ISSUE(c, m.op_embed,
praw(batch->token_ids, RAD_I32, batch->n_tok), RAD_W(m.w_tok),
brows(m.b_x, batch->n_tok));
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);
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. */
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),
bcol(m.b_dfsrc, (int64_t)t * m.g.n_embd, m.g.n_embd, batch->n_tok));
}
}
RAD_ISSUE(c, m.op_final_norm,
brows(m.b_x, batch->n_tok), RAD_W(m.w_out_norm), brows(m.a_h.x, batch->n_tok));
if (batch->n_out > 0) {
RAD_ISSUE_N(c, m.op_gather, batch->n_out,
brows(m.a_h.x, batch->n_tok),
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));
}
}
/* 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.
*
* `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. */
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
if (!meta || !out) return RAD_E_INVAL;
out->draft_depth = 0;
const char* da = rad_meta_gets(meta, "draft.architectures", "");
if (da && (std::strstr(da, "DSpark") || std::strstr(da, "DFlash"))) {
const long long bs = rad_meta_geti(meta, "draft.block_size", 0);
if (bs > 1) {
out->draft_depth = (int)bs;
out->draft_depth_fixed = 1;
}
}
return RAD_OK;
}
} /* namespace LLAMA_NS */
#ifndef RAD_ARCH_NO_EXPORTS
/* One more level of expansion so `#NS` sees the expanded namespace; arch/qwen35_fp8 explains it. */
#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 "
"at convert time and served fp8 weights / fp8 activations")
#else
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), block-scaled fp8 weights and fp8 activations")
#endif
#endif
-11
View File
@@ -1,11 +0,0 @@
# 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=<radiance prefix>`) -- the same
# rad_add_plugin either way (cmake/RadAddPlugin.cmake).
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(qwen35_bf16 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(qwen35_bf16 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/qwen35_bf16.cpp)
-576
View File
@@ -1,576 +0,0 @@
/* 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.
*
* 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.
*
* ============================== 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 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.
* 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 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.
*/
#include <arch/rad_arch.h>
#include <arch/rad_block_attn_gated.h>
#include <arch/rad_block_gdn.h>
#include <arch/rad_block_mlp.h>
#include <arch/rad_block_vit.h>
#include <vector>
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. */
struct Layer {
int full = 0;
AttnGatedBF16 attn;
GdnBF16 gdn;
MlpBF16 mlp;
};
struct Model {
Names nm{""};
Geom g{};
GdnBF16::Config gcfg{};
int64_t n_rot = 0;
int64_t n_main = 0; /* trunk layers, excluding the MTP block */
rad_kvgroup kv_full = 0, kv_state = 0, kv_conv = 0;
/* the residual stream and the two vocabulary edges */
rad_buf b_x = 0, b_h = 0, b_hout = 0, b_logits = 0;
/* full attention */
rad_buf b_qg = 0, b_k = 0, b_v = 0, b_q = 0, b_gate = 0, b_attn = 0;
/* gated delta net */
rad_buf b_in = 0, b_z = 0, b_gq = 0, b_gk = 0, b_gv = 0;
rad_buf b_gdec = 0, b_beta = 0, b_kkt = 0, b_go = 0;
/* feed-forward */
rad_buf b_gate_up = 0, b_ffn = 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;
/* ---- media (arch/common/rad_block_vit.h): the vision tower and the scatter of its rows,
* declared only when the container carries a tower and the deployment asked for media. */
bool media = false;
VisionTower vit{};
MediaRows mrows{};
std::vector<Layer> 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(). */
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;
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));
/* A routed model is a different graph, not a flag on this one. qwen35moe_bf16 serves it. */
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);
return RAD_E_UNSUPPORTED;
}
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. */
bool have_interval = false;
const int64_t interval = meta_int2(meta, "qwen35.full_attention_interval",
"full_attention_interval", 4, &have_interval);
const int64_t nextn = meta_int2(meta, "qwen35.nextn_predict_layers",
"mtp_num_hidden_layers", 0);
if (interval <= 0 || nextn < 0 || nextn >= g.n_layer) {
fprintf(stderr, "radiance: qwen35: full_attention_interval %lld / nextn %lld out of range "
"for %lld layers\n",
(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. */
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. */
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. */
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. */
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);
}
if (m.n_rot <= 0 || m.n_rot > g.head_dim || (m.n_rot & 1)) {
fprintf(stderr, "radiance: qwen35: no usable rotary width -- give the container "
"qwen35.rope.dimension_count or partial_rotary_factor (head_dim %lld)\n",
(long long)g.head_dim);
return RAD_E_INVAL;
}
/* The linear-attention geometry. llama.cpp maps the GGUF ssm keys onto these:
* ssm.state_size -> the key AND value head width, ssm.group_count -> key heads,
* ssm.time_step_rank -> value heads, ssm.inner_size -> value heads * value width. */
GdnBF16::Config& gc = m.gcfg;
const int64_t n_head_k_all = meta_int2(meta, "qwen35.ssm.group_count",
"linear_num_key_heads", 0);
const int64_t n_head_v_all = meta_int2(meta, "qwen35.ssm.time_step_rank",
"linear_num_value_heads", 0);
gc.head_k = meta_int2(meta, "qwen35.ssm.state_size", "linear_key_head_dim", 0);
gc.head_v = meta_int2(meta, "qwen35.ssm.value_head_dim", "linear_value_head_dim", 0);
gc.conv_width = meta_int2(meta, "qwen35.ssm.conv_kernel", "linear_conv_kernel_dim", 0);
if (gc.head_v <= 0) {
const int64_t inner = meta_int2(meta, "qwen35.ssm.inner_size", "linear_inner_size", 0);
if (inner > 0 && n_head_v_all > 0) gc.head_v = inner / n_head_v_all;
}
if (n_head_k_all <= 0 || n_head_v_all <= 0 || gc.head_k <= 0 || gc.head_v <= 0 ||
gc.conv_width <= 0) {
fprintf(stderr, "radiance: qwen35: the container does not describe the linear layers "
"(key heads %lld, value heads %lld, key width %lld, value width %lld, "
"conv width %lld)\n",
(long long)n_head_k_all, (long long)n_head_v_all, (long long)gc.head_k,
(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. */
gc.chunk = 64;
int s;
if ((s = divide_or_fail(n_head_k_all, g.world, "linear_num_key_heads", &gc.n_head_k)) < 0)
return s;
if ((s = divide_or_fail(n_head_v_all, g.world, "linear_num_value_heads", &gc.n_head_v)) < 0)
return s;
const int64_t q_dim = g.q_dim();
const int64_t kv_dim = g.kv_dim();
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.
*
* 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. */
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);
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. */
RadKVGroupDecl sd{};
sd.kind = RAD_KV_LINEAR;
sd.dtype = RAD_F32;
sd.n_head_kv = gc.n_head_v;
sd.state_dim[0] = gc.head_v;
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
* so the channel split never straddles a q/k/v boundary at any tensor-parallel width. */
RadKVGroupDecl cd{};
cd.kind = RAD_KV_CONV;
cd.dtype = RAD_BF16;
cd.n_head_kv = 2 * gc.n_head_k + gc.n_head_v;
cd.head_dim = gc.head_k;
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). */
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. */
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});
m.b_q = decl_b(b, nm.f("attn_q"), g.act_dtype, {g.max_tok, q_dim});
m.b_gate = decl_b(b, nm.f("attn_gate"),g.act_dtype, {g.max_tok, q_dim});
m.b_attn = decl_b(b, nm.f("attn_out"), g.act_dtype, {g.max_tok, q_dim});
m.b_in = decl_b(b, nm.f("gdn_in"), g.act_dtype, {g.max_tok, gc.in_dim()});
m.b_z = decl_b(b, nm.f("gdn_z"), g.act_dtype, {g.max_tok, v_dim});
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. */
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. */
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. */
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. */
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. */
RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"),
nm.ckpt("model.language_model.embed_tokens.weight")));
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());
/* 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. */
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 = 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. */
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});
/* ---- the layers. This loop is the model card. */
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;
GdnBF16::Wire gw{};
gw.x = m.b_x; gw.h = m.b_h; gw.in = m.b_in; gw.z = m.b_z;
gw.q = m.b_gq; gw.k = m.b_gk; gw.v = m.b_gv;
gw.gdec = m.b_gdec; gw.beta = m.b_beta; gw.kkt = m.b_kkt; gw.o = m.b_go;
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)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;
const char* pre = "model.language_model.layers";
if (lay.full) {
AttnGatedBF16::Src as{};
as.norm = nm.ckpt("%s.%lld.input_layernorm.weight", pre, (long long)l);
as.qg = nm.ckpt("%s.%lld.self_attn.q_proj.weight", pre, (long long)l);
as.k = nm.ckpt("%s.%lld.self_attn.k_proj.weight", pre, (long long)l);
as.v = nm.ckpt("%s.%lld.self_attn.v_proj.weight", pre, (long long)l);
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);
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));
} else {
GdnBF16::Src gs{};
gs.norm = nm.ckpt("%s.%lld.input_layernorm.weight", pre, (long long)l);
gs.in_qkv = nm.ckpt("%s.%lld.linear_attn.in_proj_qkv.weight", pre, (long long)l);
gs.in_a = nm.ckpt("%s.%lld.linear_attn.in_proj_a.weight", pre, (long long)l);
gs.in_b = nm.ckpt("%s.%lld.linear_attn.in_proj_b.weight", pre, (long long)l);
gs.in_z = nm.ckpt("%s.%lld.linear_attn.in_proj_z.weight", pre, (long long)l);
gs.conv1d = nm.ckpt("%s.%lld.linear_attn.conv1d.weight", pre, (long long)l);
gs.a_log = nm.ckpt("%s.%lld.linear_attn.A_log", pre, (long long)l);
gs.dt_bias = nm.ckpt("%s.%lld.linear_attn.dt_bias", pre, (long long)l);
gs.out_norm = nm.ckpt("%s.%lld.linear_attn.norm.weight", pre, (long long)l);
gs.out = nm.ckpt("%s.%lld.linear_attn.out_proj.weight", pre, (long long)l);
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));
}
MlpBF16::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));
}
m.op_final_norm = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_F64("wadd", final_wadd), RAD_STR("dtype", g.dtype)),
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});
/* ---- what a reader of --debug-graph should be told, in the plugin's own words. */
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,
(long long)(m.n_main / interval), (long long)(m.n_main - m.n_main / interval),
(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, "gdn: %lld key heads x %lld, %lld value heads x %lld, conv width %lld, chunk %lld; "
"conv row %lld channels, projection 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.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);
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);
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);
/* 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;
}
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). */
if (batch->enc) {
m.vit.step(c, batch);
return;
}
RAD_ISSUE(c, m.op_embed,
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; declared only when world > 1, so tp1 is unchanged. */
if (m.op_embed_ar)
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);
for (const Layer& l : m.layers) {
if (l.full) l.attn.step(c, batch);
else l.gdn.step(c, batch);
l.mlp.step(c, 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. */
if (batch->n_out > 0) {
RAD_ISSUE_N(c, m.op_gather, batch->n_out,
brows(m.b_h, batch->n_tok),
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));
}
}
} /* namespace qwen35_bf16 */
#ifndef RAD_ARCH_NO_EXPORTS
RAD_ARCH_PLUGIN(qwen35_bf16, "qwen35", "", "0.1.0",
"Qwen3.5 / 3.6 / 3.8 dense (0.8B..27B), bf16 weights and activations, gated "
"attention over paged KV every fourth layer and gated delta net between")
#endif
-11
View File
@@ -1,11 +0,0 @@
# 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=<radiance prefix>`) -- the same
# rad_add_plugin either way (cmake/RadAddPlugin.cmake).
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(qwen35_fp8 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(qwen35_fp8 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/qwen35_fp8.cpp)
File diff suppressed because it is too large. Load diff
-11
View File
@@ -1,11 +0,0 @@
# 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=<radiance prefix>`) -- the same
# rad_add_plugin either way (cmake/RadAddPlugin.cmake).
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(qwen35moe_fp8 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(qwen35moe_fp8 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/qwen35moe_fp8.cpp)
-24
View File
@@ -1,24 +0,0 @@
/* 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.
*
* 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.
*/
#define QWEN35_MOE 1
#define QWEN35_NS qwen35moe_fp8
#define QWEN35_ARCH_ID "qwen35moe"
#include "../qwen35_fp8/qwen35_fp8.cpp"
-11
View File
@@ -1,11 +0,0 @@
# 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=<radiance prefix>`) -- the same
# rad_add_plugin either way (cmake/RadAddPlugin.cmake).
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(qwen4exp_fp8 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(qwen4exp_fp8 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/qwen4exp_fp8.cpp)
File diff suppressed because it is too large. Load diff
-35
View File
@@ -1,35 +0,0 @@
#!/bin/sh
# build.sh -- configure and build.
#
# 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
# built. The host backend is a real implementation, not a stub -- everything except device kernels
# is exercised through it -- so a machine with no ROCm is a supported development configuration.
#
# Pass -DRAD_GPU_TARGETS=<arch>[;<arch>...] to cmake to compile for cards this machine does not
# 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 -c wipe the build directory first
# ./build.sh --no-hip force the host backend even where hipcc exists
set -e
BUILD=build
CMAKE_ARGS=""
while [ $# -gt 0 ]; do
case "$1" in
-c|--clean) rm -rf "$BUILD" ;;
--no-hip) CMAKE_ARGS="$CMAKE_ARGS -DRAD_WITH_HIP=OFF" ;;
--asan) CMAKE_ARGS="$CMAKE_ARGS -DRAD_ASAN=ON" ;;
--debug) CMAKE_ARGS="$CMAKE_ARGS -DCMAKE_BUILD_TYPE=Debug" ;;
-b) shift; BUILD="$1" ;;
*) echo "build.sh: unknown option $1" >&2; exit 2 ;;
esac
shift
done
cmake -S . -B "$BUILD" -G Ninja $CMAKE_ARGS
cmake --build "$BUILD" -j"$(nproc)"
ctest --test-dir "$BUILD" --output-on-failure
-206
View File
@@ -1,206 +0,0 @@
# 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.
#
# 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.
#
# What an includer must set first:
# radiance::abi the ABI interface target -- an in-tree ALIAS, or the imported target
# RAD_PLUGIN_OUT the build-tree $RADIANCE_HOME; a plugin lands in ${RAD_PLUGIN_OUT}/<kind>
# RAD_HIP_FOUND whether device sources can be compiled at all
# 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.
#
# And one an includer MAY set:
# 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.
# 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 <prefix>/radiance/kernels and the loader never looks there.
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 --
#
# if(NOT COMMAND rad_add_plugin) # on its own, 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)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
endif()
if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
set(CMAKE_BUILD_TYPE RelWithDebInfo)
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.
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
NOT kind MATCHES "^(kernels|architectures|quantizers)$")
message(FATAL_ERROR
"rad_add_plugin(${name} ${kind}): the kind is the directory the engine loads the plugin "
"from, and it is one of kernels, architectures or quantizers.")
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.
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).
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.")
endif()
set_source_files_properties(${P_HIP_SOURCES} PROPERTIES LANGUAGE HIP)
list(APPEND srcs ${P_HIP_SOURCES})
endif()
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.
file(MAKE_DIRECTORY ${RAD_PLUGIN_OUT}/${kind})
set_target_properties(${name} PROPERTIES
PREFIX "" OUTPUT_NAME "${name}"
LIBRARY_OUTPUT_DIRECTORY ${RAD_PLUGIN_OUT}/${kind})
if(RAD_HIP_FOUND AND P_HIP_SOURCES)
rad_hipify(${name} ${P_GPU_TARGETS})
endif()
# ...and so is the install tree, in the same shape. RAD_DEFAULT_HOME points at
# <prefix>/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.
if(NOT DEFINED RAD_PLUGIN_INSTALL)
set(RAD_PLUGIN_INSTALL ON)
endif()
if(RAD_PLUGIN_INSTALL)
if(RAD_PLUGIN_INSTALL_HOME)
set(_rad_dest "${RAD_PLUGIN_INSTALL_HOME}/${kind}")
else()
set(_rad_dest "${CMAKE_INSTALL_DATADIR}/radiance/${kind}")
endif()
install(TARGETS ${name} LIBRARY DESTINATION "${_rad_dest}")
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.
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.
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 $<$<COMPILE_LANGUAGE:HIP>:-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_<CONFIG> 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_<CONFIG> overrides, as it does in the tree.
foreach(cfg DEBUG RELEASE RELWITHDEBINFO MINSIZEREL)
if(RAD_HIP_FLAGS_${cfg})
set(lvl "${RAD_HIP_FLAGS_${cfg}}")
elseif(cfg STREQUAL "DEBUG")
set(lvl "-O0 -g")
elseif(cfg STREQUAL "MINSIZEREL")
set(lvl "-Os -DNDEBUG -g0")
else()
set(lvl "-O3 -DNDEBUG -g0")
endif()
separate_arguments(lvl)
target_compile_options(${tgt} PRIVATE "$<$<AND:$<COMPILE_LANGUAGE:HIP>,$<CONFIG:${cfg}>>:${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.
target_compile_options(${tgt} PRIVATE $<$<COMPILE_LANGUAGE:HIP>:--no-offload-compress>)
target_link_options(${tgt} PRIVATE $<$<LINK_LANGUAGE:HIP>:--no-offload-compress>)
target_link_libraries(${tgt} PRIVATE ${RAD_HIP_RUNTIME})
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.
function(rad_plugin_gpu_targets out)
set(keep "")
foreach(t ${RAD_GPU_TARGETS})
foreach(pat ${ARGN})
if(t MATCHES "${pat}")
list(APPEND keep ${t})
break()
endif()
endforeach()
endforeach()
list(REMOVE_DUPLICATES keep)
set(${out} "${keep}" PARENT_SCOPE)
endfunction()
-104
View File
@@ -1,104 +0,0 @@
# 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.
#
# What a consumer gets:
# radiance::abi the header-only ABI target -- abi/ plus RAD_DEFAULT_HOME,
# RAD_HAVE_HIP and the ROCm include path, exactly as the engine's own
# plugins were compiled with them
# rad_add_plugin() the same function radiance builds its own plugins with
# RADIANCE_ABI_VERSION the number the loader compares against, so a consumer can refuse at
# configure time rather than at dlopen
# RADIANCE_HOME the installed $RADIANCE_HOME; `cmake --install` puts a plugin
# built with rad_add_plugin under it (RAD_PLUGIN_INSTALL_HOME)
# RADIANCE_KERNELS_DIR ${RADIANCE_HOME}/kernels
# RADIANCE_ARCHITECTURES_DIR ${RADIANCE_HOME}/architectures
# RADIANCE_QUANTIZERS_DIR ${RADIANCE_HOME}/quantizers
# RADIANCE_INCLUDE_DIR the include root, for a consumer that wants the path rather than the
# 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.
@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.
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.
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.
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.
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.
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.
set(RAD_HIP_RUNTIME "@RAD_HIP_RUNTIME@")
if(RAD_HIP_FOUND)
if(NOT EXISTS "${RAD_HIP_RUNTIME}")
find_library(RAD_HIP_RUNTIME_HERE amdhip64 HINTS ENV ROCM_PATH ENV HIP_PATH /opt/rocm
PATH_SUFFIXES lib lib64)
set(RAD_HIP_RUNTIME "${RAD_HIP_RUNTIME_HERE}")
endif()
set(_rad_rocm_inc "@RAD_ROCM_INCLUDE@")
if(NOT EXISTS "${_rad_rocm_inc}/hip/hip_runtime.h")
find_path(_rad_rocm_inc_here hip/hip_runtime.h HINTS ENV ROCM_PATH ENV HIP_PATH /opt/rocm
PATH_SUFFIXES include)
set(_rad_rocm_inc "${_rad_rocm_inc_here}")
endif()
if(_rad_rocm_inc)
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 <DEP_TARGET> -MF <DEP_FILE>")
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=<their build dir>/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.
if(NOT DEFINED RAD_PLUGIN_OUT)
set(RAD_PLUGIN_OUT ${CMAKE_BINARY_DIR}/radiance_home)
endif()
include("${CMAKE_CURRENT_LIST_DIR}/RadAddPlugin.cmake")
check_required_components(radiance)
-103
View File
@@ -1,103 +0,0 @@
# 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.
#
# 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.
set(RAD_CORE_DIRS util device plugin build runtime mem sched place sample text server format mm)
set(RAD_CORE_SRC "")
foreach(d ${RAD_CORE_DIRS})
file(GLOB_RECURSE _s CONFIGURE_DEPENDS
${CMAKE_CURRENT_SOURCE_DIR}/${d}/*.cpp
${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.
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})
add_library(rad_core STATIC ${RAD_CORE_SRC})
target_link_libraries(rad_core PUBLIC rad_abi ${CMAKE_DL_LIBS} Threads::Threads)
target_compile_definitions(rad_core PUBLIC RAD_VERSION="${PROJECT_VERSION}")
target_include_directories(rad_core PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}
${CMAKE_SOURCE_DIR}/abi
${CMAKE_SOURCE_DIR}/vendor)
if(TARGET rad_vendor)
target_link_libraries(rad_core PUBLIC rad_vendor)
endif()
if(RAD_FFMPEG_FOUND)
target_compile_definitions(rad_core PRIVATE RAD_HAVE_FFMPEG=1)
target_link_libraries(rad_core PUBLIC PkgConfig::RAD_FFMPEG)
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})
# THE AQL BACKEND'S OWN KERNELS: the copies and fills it dispatches for 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).
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).
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 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.
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}")
# 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.
foreach(sym hipLaunchKernel hipMemcpy2DAsync hipMemcpyAsync hipMemsetAsync hipMemset hipStreamSynchronize
hipEventRecord hipStreamWaitEvent hipGetLastError hipPeekAtLastError
__hipRegisterFatBinary __hipRegisterFunction __hipUnregisterFatBinary)
target_link_options(rad_core INTERFACE "LINKER:--export-dynamic-symbol=${sym}")
endforeach()
endif()
# The engine binary. core/main.cpp is owned by the engine component.
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/main.cpp)
add_executable(radiance main.cpp)
target_link_libraries(radiance PRIVATE "$<LINK_LIBRARY:WHOLE_ARCHIVE,rad_core>")
# 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.
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.
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/.)
#
# 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.
set(RAD_PLUGIN_INSTALL OFF)
add_subdirectory(plugin)
-244
View File
@@ -1,244 +0,0 @@
/* 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.
*
* 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.
*
* 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.
*/
#include "rad_build.h"
#include "rad_internal.h"
#include <algorithm>
#include <climits>
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. */
static constexpr int64_t kBufAlign = (int64_t)RAD_ALIGN_SUB;
#include <cstdlib>
namespace {
struct Item {
size_t idx; /* index into Program::buffers */
int64_t bytes; /* already rounded up to kBufAlign */
int32_t lo, hi; /* inclusive op-index lifetime */
int64_t off = -1;
};
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. */
int64_t first_fit(const Item& want, const std::vector<Item>& placed) {
std::vector<std::pair<int64_t, int64_t>> occ;
occ.reserve(placed.size());
for (const Item& p : placed)
if (p.off >= 0 && overlaps(p, want)) occ.emplace_back(p.off, p.off + p.bytes);
std::sort(occ.begin(), occ.end());
int64_t off = 0;
for (auto& [s, e] : occ) {
if (s >= off + want.bytes) break; /* the gap below this block is big enough */
off = std::max(off, align_up(e, kBufAlign));
}
return off;
}
} /* namespace */
int plan_buffers(Program& p, BufPlanReport* rep) {
BufPlanReport r;
int status = RAD_OK;
const int32_t last_op = (int32_t)p.ops.size() - 1;
std::vector<Item> transient, persist, host;
for (size_t i = 1; i < p.buffers.size(); ++i) {
BufferInfo& b = p.buffers[i];
if (b.bytes <= 0) b.bytes = buffer_bytes(b.decl);
if (b.bytes <= 0) {
RAD_ERR("buffer plan: '%s' cannot be sized (dtype %u, rank %u)", b.name.c_str(),
b.decl.dtype, b.decl.rank);
status = RAD_E_INVAL;
continue;
}
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. */
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.
* 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. */
for (int32_t t = 0; t <= std::max<int32_t>(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.
*
* 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. */
int64_t off = 0;
for (const Item& it : persist) {
p.buffers[it.idx].arena_offset = off;
off += it.bytes;
off = align_up(off, kBufAlign);
}
const int64_t fixed = align_up(off, kBufAlign);
r.persist_bytes = fixed;
std::vector<Item> 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);
}
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<Item> 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);
}
r.host_bytes = host_end;
p.host_arena_bytes = host_end;
if (rep) *rep = r;
return status;
}
/* ------------------------------------------------------------------ a smaller step's plan */
int plan_level(const Program& full, const Program& probe, int64_t rows, ArenaLevel* out,
std::string* why) {
auto refuse = [&](const std::string& w) {
if (why) *why = w;
return RAD_E_STATE;
};
if (probe.buffers.size() != full.buffers.size())
return refuse(fmt("the sizing declare named %zu buffers and the real one %zu",
probe.buffers.size() - 1, full.buffers.size() - 1));
ArenaLevel lv;
lv.rows = rows;
lv.offset.assign(full.buffers.size(), -1);
lv.decl.assign(full.buffers.size(), RadBufDecl{});
std::vector<Item> transient;
for (size_t i = 1; i < full.buffers.size(); ++i) {
const BufferInfo& fb = full.buffers[i];
const BufferInfo& pb = probe.buffers[i];
const RadBufDecl& f = fb.decl;
const RadBufDecl& q = pb.decl;
if (fb.name != pb.name || f.kind != q.kind || f.domain != q.domain ||
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. */
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",
fb.name.c_str(), d, (long long)f.shape[d], (long long)q.shape[d]));
if (f.rank > 0 && q.shape[0] > f.shape[0])
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. */
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. */
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(); }
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<Item> 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);
}
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 "
"%lld", (long long)lv.end, (long long)full.arena_bytes));
*out = std::move(lv);
return RAD_OK;
}
} /* namespace rad */
-294
View File
@@ -1,294 +0,0 @@
/* rad_build.h -- the declare phase (spec §3.1). The architecture plugin states everything it will
* ever do; this is what receives it.
*
* 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, 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. 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.
*
* 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.
*/
#pragma once
#include "plugin/registry.h"
#include <cstdio>
#include <functional>
#include <set>
#include <string>
#include <string_view>
#include <unordered_map>
#include <vector>
/* 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. */
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. */
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. */
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. */
struct BufPlanReport {
int64_t transient_bytes = 0; /* the packed, shared region */
int64_t persist_bytes = 0; /* PERSIST + DERIVED: their own non-overlapping region */
int64_t host_bytes = 0; /* domain=HOST buffers; a separate address space (see below) */
int64_t peak_live = 0; /* max over op index of the bytes live at it */
int64_t sum_bytes = 0; /* every transient, unshared */
int n_unknown_live = 0; /* transients whose liveness nothing declared */
};
/* 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.
*
* 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. */
struct ArenaLevel {
int64_t rows = 0;
int64_t end = 0;
std::vector<int64_t> offset;
std::vector<RadBufDecl> 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. */
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. */
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. */
struct WeightSource {
RadEncoding enc{};
uint32_t rank = 0;
int64_t shape[RAD_MAX_RANK] = {0};
};
using WeightSourceFn = std::function<int(const std::string& name, const Program& prog,
WeightSource* out)>;
/* ------------------------------------------------------------------ the builder */
class Builder : public RadBuilder {
public:
/* The Registry must outlive the Builder AND the Program it produces: every KernelRow the
* bands hold points into a plugin the Registry dlclose()s. */
Builder(Registry& reg, const RadModelMeta& meta, const RadBuildCtx& ctx);
/* Where rad_weight_encoding's answers come from. Unset, every source is RAD_E_NOTFOUND and a
* weight is read as plain in its declared dtype -- a test, a synthetic tool. */
void set_sources(WeightSourceFn f) { sources_ = std::move(f); }
/* The C surface, one method per rad_builder.h entry point. */
rad_weight decl_weight (const char* name, const RadWeightDecl* d);
int weight_encoding(const char* source, RadEncoding* out, int64_t* shape,
uint32_t* rank);
rad_buf decl_buffer (const char* name, const RadBufDecl* d);
rad_kvgroup decl_kv_group(const char* name, const RadKVGroupDecl* d);
int64_t kv_block_size(rad_kvgroup g);
int bind_layer_kv(int layer, rad_kvgroup g);
rad_op decl_op (const char* op, const RadParam* p, int n_p,
const rad_weight* w, int n_w);
int op_resolved (rad_op h) const;
int decl_name_map(const RadNameMap* m);
int declare_logits(rad_buf b);
int declare_drafter(const RadDrafterDecl* d);
int declare_encoder(const RadEncoderDecl* d);
void note_v (const char* f, va_list ap);
/* The buffer operands of an op.
*
* NOT in rad_builder.h, and it needs to be -- see the proposed ABI addition at the foot of this
* header. rad_decl_op names an op's WEIGHT operands but not its buffer operands, so declare
* cannot compute activation liveness from the ABI as frozen, and without liveness the arena is
* the sum of every transient rather than the peak of them. Until the two functions below are added to the frozen header (purely additive,
* no existing signature changes), a plugin cannot supply this and every transient is assumed
* live for the whole program: correct, and as wasteful as it sounds. The --debug-graph buffer
* report prints how many buffers fell into that case, so the cost is never invisible. */
int op_reads (rad_op h, const rad_buf* b, int n);
int op_writes(rad_op h, const rad_buf* b, int n);
int buf_concurrent(rad_buf b);
int weight_shard_span(rad_weight w, int64_t lo, int64_t hi);
/* Finalise: weight first/last use, KV group geometry, buffer liveness and packing. Returns
* RAD_OK, or the first structural error class. Resolution MISSES are not an error here -- an
* op that did not resolve returns a null handle and the plugin is expected to have offered a
* fallback (spec §2.3); it becomes an error when the run phase issues it. */
int finish();
/* A SIZING DECLARE (RadBuildCtx::shape_probe): every op takes the bands `ref` resolved for
* the op at the same position instead of resolving its own, and finish() initialises nothing.
* The plugin then sees exactly the answers the real declare gave -- which ops resolved, which
* block size a group has -- so it declares the same graph, and nothing is selected or set up
* a second time. An op that is not the one `ref` has at that position ends the probe with an
* error: the plugin declared a different graph at the smaller size, and its buffers cannot be
* laid over the real ones. */
void set_reference(const Program* ref) { ref_ = ref; }
/* WITHOUT INSTANCES: finish() selects every kernel and initialises none. For a caller that
* launches nothing -- rad-convert plans a container's stored form, which is the kernels'
* layouts and not their setup. A kernel's init is about the process it runs in (a ring, a
* peer's buffers) and the conversion is often not that process: libavx's n-gram gather
* refuses a process that may not make an io_uring ring, and a sandbox that forbids one still
* has to be able to convert the model. */
void set_instances(bool on) { instances_ = on; }
Program& program() { return prog_; }
const Program& program() const { return prog_; }
/* Structural failures: a bad schema, two ranged parameters, a duplicate name. Every one of
* them, not the first -- same rule as the miss list. */
const std::vector<std::string>& 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. */
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. */
void finish_instances();
int32_t find_kv_consumer(rad_kvgroup g);
void finish_layouts();
void finish_kv_groups();
void finish_weight_uses();
void finish_buffer_liveness();
Registry& reg_;
Program prog_;
const Program* ref_ = nullptr;
bool instances_ = true;
std::vector<std::string> errors_;
int status_ = RAD_OK;
bool finished_ = false;
std::string scope_;
/* Parallel to prog_.ops. Empty until the ABI carries buffer operands. */
struct OpBufUse { std::vector<rad_buf> reads, writes; };
std::vector<OpBufUse> 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. */
std::set<rad_buf> 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(). */
std::vector<int32_t> kv_decl_at_;
std::vector<int32_t> 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. */
std::unordered_map<std::string, size_t> 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. */
std::unordered_map<std::string, rad_weight> 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. */
WeightSourceFn sources_;
std::unordered_map<std::string, std::pair<int, WeightSource>> source_cache_;
int lookup_source(const std::string& name, WeightSource* out);
BufPlanReport bufrep_;
};
/* ------------------------------------------------------------------ --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. */
std::string dump_graph_str(const Program& p, const std::vector<std::string>* 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. */
std::string dump_graph_json(const Program& p);
void dump_graph (const Program& p, FILE* out,
const std::vector<std::string>* 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
File diff suppressed because it is too large. Load diff
-828
View File
@@ -1,828 +0,0 @@
/* rad_graph.cpp -- `--debug-graph` (spec §16).
*
* "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:
*
* 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.
*/
#include "rad_build.h"
#include "startup.h"
#include <nlohmann/json.hpp>
#include <algorithm>
#include <climits>
#include <unordered_map>
#include <cstring>
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. */
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. */
std::string constraint_str(const RadConstraint& c) {
switch (c.op) {
case RAD_C_EQ: return fmt("%s == %lld", c.key, c.ival);
case RAD_C_LE: return fmt("%s <= %lld", c.key, c.ival);
case RAD_C_GE: return fmt("%s >= %lld", c.key, c.ival);
case RAD_C_DIV: return fmt("%s %% %lld == 0", c.key, c.ival);
case RAD_C_IN: return fmt("%s in {%s}", c.key, c.sval ? c.sval : "");
default: return fmt("%s ?", c.key);
}
}
/* "(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). */
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. */
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. */
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());
return fmt(" %s <= %4lld -> ", o.ranged_key.c_str(), (long long)b.hi);
}
bool domain_has_any(const OpInfo& o, int d) {
for (const Band& b : o.bands) if (b.dom[d]) return true;
return false;
}
void dump_bucket_table(std::string& s, const OpInfo& o, int d) {
for (const Band& b : o.bands) {
const Resolved& r = b.dom[d];
if (r) {
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). */
s += band_prefix(o, b) + fmt("%-24s", "(nothing)")
+ "-- " + (b.miss[d].empty() ? "no kernel matched" : b.miss[d]) + "\n";
}
}
}
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. */
std::vector<const RadKernelInfo*> seen;
for (const Band& b : o.bands) {
const Resolved& r = b.dom[d];
if (!r || !r.row->info) continue;
if (std::find(seen.begin(), seen.end(), r.row->info) != seen.end()) continue;
seen.push_back(r.row->info);
std::string cs;
for (int i = 0; i < r.row->info->n_constraints; ++i) {
if (i) cs += ", ";
cs += constraint_str(r.row->info->constraints[i]);
}
if (cs.empty()) cs = "(unconstrained -- serves any geometry)";
s += fmt(" matched %s: %s\n", r.row->info->name, cs.c_str());
}
}
/* 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. */
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<std::string>& 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<std::string>* errors) {
std::string s;
s += fmt("==== declared graph: %s [%s] rank %d/%d max_tok %lld max_seqs %lld%s\n\n",
p.meta.name ? p.meta.name : "?", p.meta.arch_id ? p.meta.arch_id : "?",
p.ctx.rank, p.ctx.world_size, (long long)p.ctx.max_tok, (long long)p.ctx.max_seqs,
(p.ctx.scope && *p.ctx.scope) ? fmt(" scope '%s'", p.ctx.scope).c_str() : "");
/* ---------------------------------------------------------------- the ops */
for (size_t i = 1; i < p.ops.size(); ++i) {
const OpInfo& o = p.ops[i];
std::string params = o.base.str();
s += o.op;
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. */
bool dev = domain_has_any(o, RAD_DOMAIN_DEVICE);
bool hst = domain_has_any(o, RAD_DOMAIN_HOST);
bool printed_device = dev || !hst;
if (printed_device) dump_bucket_table(s, o, RAD_DOMAIN_DEVICE);
if (hst) {
if (printed_device) s += " host domain:\n";
dump_bucket_table(s, o, RAD_DOMAIN_HOST);
}
if (printed_device) dump_matched(s, o, RAD_DOMAIN_DEVICE);
if (hst) dump_matched(s, o, RAD_DOMAIN_HOST);
if (!o.weights.empty()) {
std::vector<std::string> names;
for (rad_weight h : o.weights)
names.push_back(h < p.weights.size() ? p.weights[h].name : fmt("<bad handle %u>", h));
s += fmt(" weights %s\n", join_names(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. */
std::vector<std::string> 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. */
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());
s += "\n";
}
/* ---------------------------------------------------------------- the weight manifest */
int64_t wtotal = 0;
for (size_t i = 1; i < p.weights.size(); ++i) wtotal += p.weights[i].stored_bytes;
s += fmt("---- weights: %zu, %s held by rank %d of %d\n",
p.weights.size() - 1, humanb(wtotal).c_str(), p.ctx.rank, p.ctx.world_size);
append_row(s, fmt(" %-40s %12s %6s %-12s %6s %7s %6s %6s %-16s %-5s %-5s",
"name", "bytes", "align", "access", "layer", "expert", "first", "last",
"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. */
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,
w.first_use_op, w.last_use_op,
w.layout_tag.empty() ? "as declared" : w.layout_tag.c_str(), "", ""));
}
s += "\n";
/* ---------------------------------------------------------------- the buffer plan */
int64_t sum = 0, peak = 0, unknown = 0, persist = 0;
const int32_t last_op = (int32_t)p.ops.size() - 1;
for (size_t i = 1; i < p.buffers.size(); ++i) {
const BufferInfo& b = p.buffers[i];
if (b.decl.domain == RAD_DOMAIN_HOST) continue;
if (b.decl.kind == RAD_BUF_TRANSIENT) {
sum += b.bytes;
if (b.first_def <= 0 && b.last_use >= last_op) ++unknown;
} else {
persist += b.bytes;
}
}
for (int32_t t = 1; t <= std::max<int32_t>(last_op, 1); ++t) {
int64_t live = 0;
for (size_t i = 1; i < p.buffers.size(); ++i) {
const BufferInfo& b = p.buffers[i];
if (b.decl.kind != RAD_BUF_TRANSIENT || b.decl.domain == RAD_DOMAIN_HOST) continue;
if (b.first_def <= t && t <= b.last_use) live += b.bytes;
}
peak = std::max(peak, live);
}
s += fmt("---- buffer plan: arena %s, scratch %s\n",
humanb(p.arena_bytes).c_str(), humanb(p.scratch_bytes).c_str());
s += fmt(" transient %12s packed from %s unshared (peak live %s, waste %s)\n",
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. */
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());
if (unknown)
s += fmt(" %lld transient buffer(s) had no declared use and are assumed live for the "
"whole program -- that is the arena's waste, and it goes away when ops name "
"their buffer operands\n", (long long)unknown);
std::vector<const BufferInfo*> big;
for (size_t i = 1; i < p.buffers.size(); ++i) big.push_back(&p.buffers[i]);
std::sort(big.begin(), big.end(),
[](const BufferInfo* a, const BufferInfo* b) { return a->bytes > b->bytes; });
for (size_t i = 0; i < big.size() && i < 5; ++i)
s += fmt(" %-32s %12s %-9s live [%d,%d] @ %lld\n", big[i]->name.c_str(),
humanb(big[i]->bytes).c_str(), bld_buf_kind_name(big[i]->decl.kind),
big[i]->first_def, big[i]->last_use, (long long)big[i]->arena_offset);
s += "\n";
/* ---------------------------------------------------------------- KV groups */
if (p.kv_groups.size() > 1) {
s += fmt("---- kv groups: %zu\n", p.kv_groups.size() - 1);
for (size_t i = 1; i < p.kv_groups.size(); ++i) {
const KVGroupInfo& g = p.kv_groups[i];
s += fmt(" %-20s %-7s block %-5lld %12s/block %12s/state %zu layer(s)\n",
g.name.c_str(), bld_kv_kind_name(g.decl.kind), (long long)g.block_size,
humanb(g.bytes_per_block).c_str(), humanb(g.bytes_per_state).c_str(),
g.layers.size());
}
s += "\n";
}
/* ---------------------------------------------------------------- the drafter (spec §10) */
if (p.drafter.kind != RAD_DRAFT_NONE) {
const bool blk = p.drafter.kind == RAD_DRAFT_BLOCK;
s += fmt("---- drafter: '%s', %s, %d token(s) a step\n",
p.drafter_name.c_str(),
blk ? "RAD_DRAFT_BLOCK -- a context pass, then one pass fills the whole block"
: "RAD_DRAFT_SERIAL -- one dependent pass a token",
p.drafter.depth);
s += fmt(" proposal %s\n",
p.drafter.proposal
? fmt("%s [%lld a row]", p.buffers[p.drafter.proposal].name.c_str(),
(long long)p.drafter.proposal_pitch).c_str()
: "the sampler's token buffer (this head's logits go through the chain)");
if (blk)
s += fmt(" block %lld row(s) a sequence, the head over the last %d, mask token "
"%d, drafter window %lld\n",
(long long)p.drafter.block, p.drafter.depth,
(int)p.drafter.mask_token, (long long)p.drafter.window);
s += "\n";
}
/* ---------------------------------------------------------------- tuning (spec §15) */
if (!p.tune_requests.empty()) {
s += fmt("---- tuning requests: %zu (rad-tune benchmarks each on this machine)\n",
p.tune_requests.size());
for (const auto& t : p.tune_requests)
s += fmt(" %-24s %-14s %2d axes %s\n", t.kernel.c_str(), t.plugin.c_str(),
t.info ? t.info->n_tunables : 0, t.geom.str().c_str());
s += "\n";
}
/* ---------------------------------------------------------------- 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. */
{
std::vector<std::string> lines;
int n_fused = 0, n_ops_replaced = 0;
for (size_t i = 1; i < p.ops.size(); ++i) {
const OpInfo& o = p.ops[i];
for (size_t b = 0; b < o.bands.size(); ++b) {
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. */
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". */
const int st = r.row->info->replaces(r.geom.params(), r.geom.n_params(),
RAD_FUSE_PRESENT_ALL,
step, &fs);
if (st != RAD_OK) break;
if (!fs.op) break;
chain += (chain.empty() ? "" : " -> ");
chain += fs.op;
++n_step;
}
if (n_step < 2) continue; /* a one-op "chain" is not a fusion */
++n_fused;
n_ops_replaced += n_step;
lines.push_back(fmt(" %-24s %-28s %s", o.op.c_str(), r.row->info->name,
chain.c_str()));
}
}
}
if (n_fused > 0) {
std::sort(lines.begin(), lines.end());
lines.erase(std::unique(lines.begin(), lines.end()), lines.end());
s += fmt("---- fusions: %d resolved kernel(s) stand in for %d op(s)\n",
n_fused, n_ops_replaced);
s += " each row is a kernel and the conventional chain it declares it computes;\n"
" rad-check runs that chain out of the same plugin and compares the bytes\n";
for (const std::string& l : lines) s += l + "\n";
s += "\n";
}
}
/* ---------------------------------------------------------------- plugin notes */
if (!p.notes.empty()) {
s += "---- notes from the architecture plugin\n";
for (const auto& n : p.notes) s += " " + n + "\n";
s += "\n";
}
/* ---------------------------------------------------------------- what did not resolve */
if (!p.misses.empty()) {
s += fmt("---- unresolved: %zu op/band/domain combination(s)\n", p.misses.size());
s += " no DEVICE kernel is fatal for that band; no HOST kernel removes host-site\n"
" placement for that op and nothing else (spec §2.1)\n";
for (const auto& m : p.misses) s += " " + m.line() + "\n";
s += "\n";
}
if (errors && !errors->empty()) {
s += fmt("---- declare errors: %zu\n", errors->size());
for (const auto& e : *errors) s += " " + e + "\n";
s += "\n";
}
return s;
}
void dump_graph(const Program& p, FILE* out, const std::vector<std::string>* errors) {
std::string s = dump_graph_str(p, errors);
fwrite(s.data(), 1, s.size(), out ? out : stderr);
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.
*
* 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.
*
* 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. */
/* 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. */
static std::string params_str(const RadParam* p, int n) {
std::string s;
for (int i = 0; i < n; ++i) {
if (!p[i].key) continue;
if (!s.empty()) s += " ";
switch (p[i].kind) {
case RAD_P_INT: s += fmt("%s=%lld", p[i].key, p[i].ival); break;
case RAD_P_STR: s += fmt("%s=%s", p[i].key, p[i].sval ? p[i].sval : ""); break;
case RAD_P_F64: s += fmt("%s=%g", p[i].key, p[i].dval); break;
case RAD_P_RANGE: s += fmt("%s=[%lld,%lld]", p[i].key, p[i].ival, p[i].ihi); break;
default: s += p[i].key; break;
}
}
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. */
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. */
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;
json j;
j["op"] = fs.op;
j["params"] = params_str(fs.p, fs.n_p);
out.push_back(std::move(j));
}
if (out.size() < 2) return json::array(); /* a one-op "chain" is not a fusion */
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. */
static json kernel_hooks(const RadKernelInfo* k) {
json h = json::array();
if (k->init) h.push_back("init");
if (k->scratch) h.push_back("scratch");
if (k->layout) h.push_back("layout");
if (k->relayout) h.push_back("relayout");
if (k->unrelayout) h.push_back("unrelayout");
if (k->opd_shape) h.push_back("opd_shape");
if (k->replaces) h.push_back("replaces");
return h;
}
static json resolved_json(const Resolved& r) {
if (!r || !r.row || !r.row->info) return nullptr;
const RadKernelInfo* k = r.row->info;
json j;
j["kernel"] = k->name ? k->name : "?";
j["plugin"] = r.row->plugin;
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. */
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;
if (k->dtypes && *k->dtypes) j["dtypes"] = k->dtypes;
if (r.scratch_bytes) j["scratch"] = r.scratch_bytes;
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. */
json ax = json::array();
int64_t space = 1;
for (int i = 0; i < k->n_tunables; ++i) {
const RadTunable& t = k->tunables[i];
json a;
a["key"] = t.key ? t.key : "?";
a["default"] = t.deflt;
if (t.doc && *t.doc) a["doc"] = t.doc;
json vals = json::array();
for (int v = 0; v < t.n_values; ++v) vals.push_back(t.values[v]);
a["values"] = std::move(vals);
ax.push_back(std::move(a));
space *= (int64_t)t.n_values;
}
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`. */
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);
j["hooks"] = kernel_hooks(k);
/* Names only, for the flow's chip and the filter's haystack; the steps carry the geometries. */
json names = json::array();
json steps = fuse_steps(r);
for (const json& st : steps) names.push_back(st["op"]);
j["replaces"] = std::move(names);
j["fuse_steps"] = std::move(steps);
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. */
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);
SelectionTrace t;
reg.select(o.op, q, dom, &t, /*record=*/false);
json out = json::array();
for (const SelectionTrace::Candidate& c : t.candidates) {
json j;
j["kernel"] = c.kernel;
j["plugin"] = c.plugin;
j["priority"] = c.priority;
j["ok"] = c.ok;
j["why"] = c.why;
out.push_back(std::move(j));
}
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. */
static json schema_json(const RadOpSchema* s) {
if (!s) return nullptr;
json j;
if (s->doc && *s->doc) j["doc"] = s->doc;
json ps = json::array();
for (int i = 0; i < s->n_params; ++i) {
json p;
p["key"] = s->params[i].key ? s->params[i].key : "?";
p["type"] = s->params[i].type == RAD_P_STR ? "str" : "int";
p["need"] = s->params[i].required == RAD_REQUIRED ? "required"
: s->params[i].required == RAD_DERIVED ? "derived" : "optional";
ps.push_back(std::move(p));
}
j["params"] = std::move(ps);
json os = json::array();
for (int i = 0; i < s->n_operands; ++i) {
const int role = s->operands[i].role;
json p;
p["name"] = s->operands[i].name ? s->operands[i].name : "?";
p["role"] = role == RAD_OPD_OUT ? "out" : role == RAD_OPD_INOUT ? "inout"
: role == RAD_OPD_WEIGHT ? "weight" : role == RAD_OPD_WTAB ? "wtab" : "in";
p["optional"] = s->operands[i].optional != 0;
os.push_back(std::move(p));
}
j["operands"] = std::move(os);
return j;
}
static std::string shape_str(const int64_t* dims, uint32_t rank) {
if (!rank) return "";
std::string s;
for (uint32_t i = 0; i < rank; ++i) s += (i ? " x " : "") + std::to_string((long long)dims[i]);
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. */
static json weight_json(const WeightInfo& w) {
json j;
j["name"] = w.name;
j["bytes"] = w.stored_bytes;
j["logical"] = w.logical_bytes;
j["dtype"] = rad_dtype_name(w.stored_dtype);
j["shape"] = shape_str(w.stored_shape, w.stored_rank);
j["layout"] = w.layout_tag.empty() ? std::string("as declared") : w.layout_tag;
j["access"] = bld_access_name(w.decl.access);
j["tier"] = tier_name(w.tier);
j["site"] = site_name(w.site);
j["layer"] = w.decl.group.layer;
if (w.decl.group.expert >= 0) j["expert"] = w.decl.group.expert;
return j;
}
std::string dump_graph_json(const Program& p) {
Registry& reg = rad_tools_registry();
json root;
json meta;
meta["arch"] = p.meta.arch_id ? p.meta.arch_id : "";
meta["name"] = p.meta.name ? p.meta.name : "";
meta["quant"] = p.meta.quant ? p.meta.quant : "";
meta["n_layers"] = p.meta.n_layers;
meta["n_embd"] = p.meta.n_embd;
meta["n_vocab"] = p.meta.n_vocab;
meta["rank"] = p.ctx.rank;
meta["world"] = p.ctx.world_size;
meta["max_tok"] = p.ctx.max_tok;
meta["max_seqs"] = p.ctx.max_seqs;
root["model"] = std::move(meta);
int64_t wtotal = 0;
for (size_t i = 1; i < p.weights.size(); ++i) wtotal += p.weights[i].stored_bytes;
json counts;
counts["ops"] = (int64_t)p.ops.size() - 1;
counts["weights"] = (int64_t)p.weights.size() - 1;
counts["buffers"] = (int64_t)p.buffers.size() - 1;
counts["kv_groups"] = (int64_t)p.kv_groups.size();
counts["weight_bytes"] = wtotal;
counts["arena_bytes"] = p.arena_bytes;
counts["host_arena_bytes"] = p.host_arena_bytes;
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. */
json plugs = json::array();
for (const Plugin& pl : reg.plugins()) {
json j;
j["name"] = pl.name;
j["order"] = pl.order;
j["version"] = pl.version;
j["kernels"] = pl.n_kernels;
j["schemas"] = pl.n_schemas;
if (!pl.description.empty()) j["description"] = pl.description;
if (!pl.build_target.empty()) j["build_target"] = pl.build_target;
if (!pl.arch_id.empty()) j["arch"] = pl.arch_id + (pl.arch_quant.empty()
? std::string() : " " + pl.arch_quant);
plugs.push_back(std::move(j));
}
root["plugins"] = std::move(plugs);
/* One entry per distinct (op, band table), with how many declarations collapsed into it. */
std::vector<std::string> order; /* unique keys, first-seen order */
std::vector<std::string> seq; /* every declared op, in order, by key */
std::unordered_map<std::string, json> group;
std::unordered_map<std::string, int64_t> tally;
const int32_t nops = (int32_t)p.ops.size() - 1;
for (size_t i = 1; i < p.ops.size(); ++i) {
const OpInfo& o = p.ops[i];
json bands = json::array();
std::string key = o.op;
for (const Band& b : o.bands) {
json jb;
jb["span"] = b.span;
jb["hi"] = b.hi; /* the page picks the widest band as the node's headline */
for (int d = 0; d < RAD_N_DOMAINS; ++d) {
json rj = resolved_json(b.dom[d]);
const char* dn = bld_domain_name(d);
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. */
key += "|" + jb.dump();
for (int d = 0; d < RAD_N_DOMAINS; ++d)
jb[std::string(bld_domain_name(d)) + "_considered"] =
considered_json(reg, o, b, d);
bands.push_back(std::move(jb));
}
seq.push_back(key);
auto it = group.find(key);
if (it != group.end()) { tally[key] += 1; continue; }
json j;
j["op"] = o.op;
j["index"] = o.index;
j["geometry"] = o.base.str();
j["ranged"] = o.ranged_key;
if (!o.ranged_key.empty()) { j["range_lo"] = o.range_lo; j["range_hi"] = o.range_hi; }
j["issued"] = o.issued;
j["schema"] = schema_json(o.schema ? o.schema : reg.schema(o.op));
json ws = json::array();
for (rad_weight w : o.weights)
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. */
json writes = json::array(), frees = json::array();
for (size_t bi = 1; bi < p.buffers.size(); ++bi) {
const BufferInfo& bf = p.buffers[bi];
if (bf.decl.kind != RAD_BUF_TRANSIENT) continue;
if (bf.first_def <= 0 && bf.last_use >= nops) continue;
if (bf.first_def != (int32_t)i && bf.last_use != (int32_t)i) continue;
json jb;
jb["name"] = bf.name;
jb["bytes"] = bf.bytes;
jb["domain"] = bld_domain_name(bf.decl.domain);
jb["live"] = fmt("[%d, %d]", bf.first_def, bf.last_use);
if (bf.first_def == (int32_t)i) writes.push_back(std::move(jb));
else frees.push_back(std::move(jb));
}
j["writes"] = std::move(writes);
j["frees"] = std::move(frees);
j["bands"] = std::move(bands);
group.emplace(key, std::move(j));
order.push_back(key);
tally[key] = 1;
}
std::unordered_map<std::string, int> index_of;
json ops = json::array();
for (const std::string& key : order) {
index_of[key] = (int)ops.size();
json j = group[key];
j["count"] = tally[key];
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. */
json ord = json::array();
std::vector<int> first_at((size_t)ops.size(), -1), last_at((size_t)ops.size(), -1);
for (size_t k = 0; k < seq.size(); ++k) {
const int gi = index_of[seq[k]];
ord.push_back(gi);
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. */
for (size_t k = 0; k < ops.size(); ++k) {
ops[k]["first_at"] = first_at[k];
ops[k]["last_at"] = last_at[k];
}
root["ops"] = std::move(ops);
root["order"] = std::move(ord);
json kvs = json::array();
for (const KVGroupInfo& g : p.kv_groups) {
if (g.name.empty() || g.layers.empty()) continue;
json j;
j["name"] = g.name;
j["kind"] = bld_kv_kind_name(g.decl.kind);
j["layers"] = (int64_t)g.layers.size();
j["block_size"] = g.block_size;
j["bytes_per_block"] = g.bytes_per_block;
j["bytes_per_state"] = g.bytes_per_state;
kvs.push_back(std::move(j));
}
root["kv_groups"] = std::move(kvs);
if (p.drafter.kind != RAD_DRAFT_NONE) {
json d;
d["name"] = p.drafter_name;
d["kind"] = p.drafter.kind == RAD_DRAFT_BLOCK ? "block" : "serial";
d["depth"] = p.drafter.depth;
if (p.drafter.kind == RAD_DRAFT_BLOCK) {
d["window"] = p.drafter.window;
d["block"] = p.drafter.block;
}
root["drafter"] = std::move(d);
}
json notes = json::array();
for (const std::string& n : p.notes) notes.push_back(n);
root["notes"] = std::move(notes);
json misses = json::array();
for (const Program::Miss& m : p.misses) {
json j;
j["op"] = m.op; j["geometry"] = m.geom; j["span"] = m.span;
j["domain"] = bld_domain_name(m.domain); j["why"] = m.why;
misses.push_back(std::move(j));
}
root["misses"] = std::move(misses);
return root.dump();
}
} /* namespace rad */
-382
View File
@@ -1,382 +0,0 @@
/* 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.
*/
#include "build/startup.h"
#include "build/rad_build.h"
#include "format/tunecache.h"
#include "plugin/registry.h"
#include <sys/stat.h>
#include <algorithm>
#include <cstdlib>
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. */
Registry& rad_tools_registry() {
static Registry r;
return r;
}
/* ------------------------------------------------------------------ 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. */
int rad_reference_ops(const Program& p, std::vector<std::string>* out) {
int n = 0;
for (size_t i = 1; i < p.ops.size(); ++i) {
const OpInfo& oi = p.ops[i];
bool real = false;
for (const Band& b : oi.bands)
for (int d = 0; d < RAD_N_DOMAINS && !real; ++d)
if (b.dom[d] && b.dom[d].row && !b.dom[d].row->reference)
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. */
if (out && std::find(out->begin(), out->end(), oi.op) == out->end())
out->push_back(oi.op);
}
return n;
}
int rad_gate_reference_kernels(const Program& p, bool allow, const char* what) {
std::vector<std::string> ops;
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. */
std::vector<std::string> refs;
for (size_t i = 1; i < p.ops.size(); ++i)
for (const Band& b : p.ops[i].bands)
for (int d = 0; d < RAD_N_DOMAINS; ++d)
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]; }
if (allow) {
RAD_WARN("%d declared op(s) resolve to a reference implementation (%s) and "
"--debug-accept-reference-kernels was passed, so %s continues. This is not a "
"production configuration: %zu distinct op(s) run the naive generic "
"implementation -- %s", n, libs.c_str(), what, ops.size(), list.c_str());
return RAD_OK;
}
RAD_ERR("%d declared op(s) resolve only to a reference implementation (%s).\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);
return RAD_E_NOKERNEL;
}
std::vector<std::string> rad_home_dirs(const std::string& home) {
std::vector<std::string> out;
size_t i = 0;
while (i <= home.size()) {
size_t e = home.find(':', i);
if (e == std::string::npos) e = home.size();
if (e > i) out.push_back(home.substr(i, e - i));
i = e + 1;
}
if (out.empty()) out.push_back(".");
return out;
}
std::string rad_home_file(const std::string& home, const std::string& rel) {
const std::vector<std::string> dirs = rad_home_dirs(home);
for (const std::string& d : dirs) {
struct stat st {};
if (stat((d + "/" + rel).c_str(), &st) == 0) return d + "/" + rel;
}
return dirs.front() + "/" + rel;
}
/* The homes on the path that have the directory `sub`. */
static std::vector<std::string> home_subdirs(const std::string& home, const char* sub) {
std::vector<std::string> out;
for (const std::string& d : rad_home_dirs(home)) {
struct stat st {};
const std::string p = d + "/" + sub;
if (stat(p.c_str(), &st) == 0 && S_ISDIR(st.st_mode)) out.push_back(p);
}
return out;
}
int rad_tools_load_plugins(const std::string& home, const std::vector<std::string>& hierarchy,
const std::string& arch_id, const std::string& quant,
LoadedPlugins* out) {
if (!out) return RAD_E_INVAL;
*out = LoadedPlugins{};
Registry& r = rad_tools_registry();
/* Kernels first and in hierarchy order, then architectures. The order matters for kernels and
* not for architectures: no two architecture plugins may claim the same id, so there is
* nothing for a hierarchy to break a tie between.
*
* A home on the path need not have every directory -- one holding a single kernel library is
* the ordinary shape of a home of one's own -- but kernels/ and architectures/ must each be
* somewhere on it, or the scan names the first home's as missing. */
const std::string first = rad_home_dirs(home).front();
std::vector<std::string> kdirs = home_subdirs(home, "kernels");
if (kdirs.empty()) kdirs.push_back(first + "/kernels");
int s = r.load_dirs(kdirs, hierarchy);
if (s < 0) return s;
std::vector<std::string> adirs = home_subdirs(home, "architectures");
if (adirs.empty()) adirs.push_back(first + "/architectures");
s = r.load_dirs(adirs, {});
if (s < 0) return s;
/* The quantisers, which rad-convert drives and the oracle decodes through for a scheme the
* core does not define. A home without the directory has none, which is not an error for an
* engine serving a container whose encodings the core decodes itself. */
const std::vector<std::string> qdirs = home_subdirs(home, "quantizers");
if (!qdirs.empty()) {
s = r.load_dirs(qdirs, {});
if (s < 0) return s;
}
RAD_TRY(r.check_complete());
/* The tuning cache, once the kernel set is known. A missing file is not an error and leaves
* every shape on its plugin's first variant; a present one moves the shapes rad-tune measured.
* Reported when it has rows, because "which variant am I running" is otherwise a question with
* no visible answer -- --debug-graph prints the per-shape source beside each kernel. */
const std::string tune = rad_home_file(home, TuneCache::rel_path(rad_machine_key()));
const std::string tune_home = tune.substr(0, tune.size() - TuneCache::rel_path(rad_machine_key()).size() - 1);
const int n_tuned = r.load_tune(tune_home);
if (n_tuned > 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. */
for (const Plugin& p : r.plugins()) {
if (p.kind == RAD_PLUGIN_KERNEL) {
out->kernels.push_back({ p.name, p.version });
} else if (p.kind == RAD_PLUGIN_ARCH && !arch_id.empty() && p.arch_id == arch_id &&
p.arch_quant == quant) {
out->arch_plugin = p.name;
out->arch_version = p.version;
out->arch_id = p.arch_id;
out->arch_quant = p.arch_quant;
}
}
if (out->kernels.empty()) {
RAD_ERR("no kernel plugin loaded from %s/kernels. Every weight's layout comes from the "
"kernel that will read it, so there is nothing to lay a container out for.",
home.c_str());
return RAD_E_NOKERNEL;
}
if (!arch_id.empty() && out->arch_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. */
std::string have, same;
for (const Plugin& p : r.plugins()) {
if (p.kind != RAD_PLUGIN_ARCH) continue;
const std::string q = p.arch_quant.empty() ? "(unquantised)" : p.arch_quant;
if (!have.empty()) have += ", ";
have += p.arch_id + " @ " + q;
if (p.arch_id == arch_id) { if (!same.empty()) same += ", "; same += q; }
}
if (!same.empty())
RAD_ERR("no architecture plugin claims '%s' at quantisation '%s'. '%s' is served at: "
"%s. Either the container's quantisation descriptor is not one this project "
"has a plugin for, or the container was written before the descriptor was "
"recorded -- rad-info prints it.",
arch_id.c_str(), quant.empty() ? "(unquantised)" : quant.c_str(),
arch_id.c_str(), same.c_str());
else
RAD_ERR("no architecture plugin claims '%s'. %s/architectures offers: %s",
arch_id.c_str(), home.c_str(), have.empty() ? "(none)" : have.c_str());
return RAD_E_NOTFOUND;
}
return RAD_OK;
}
/* WHAT THE ARCHITECTURE PLUGIN SAYS BEFORE IT DECLARES. Optional export: a plugin without one
* leaves every field zero, which the caller reads as "no opinion" and answers from its own
* defaults.
*
* Not an error path. A probe that fails is a plugin declining to answer, not a model that cannot
* be served -- the caller falls back to its own default and the plugin gets to refuse properly in
* declare, where it has the whole configuration in front of it and can say why. */
int rad_tools_probe(const LoadedPlugins& lp, const RadModelMeta& meta, RadArchProbe* out) {
if (!out) return RAD_E_INVAL;
*out = RadArchProbe{};
const Plugin* ap = rad_tools_registry().plugin(lp.arch_plugin);
if (!ap || !ap->arch_probe) return RAD_E_UNSUPPORTED;
const int s = ap->arch_probe(&meta, out);
if (s < 0) {
RAD_WARN("%s: rad_arch_probe returned %s; the core will use its own defaults",
lp.arch_plugin.c_str(), rad_strerror(s));
*out = RadArchProbe{};
return s;
}
return RAD_OK;
}
const RadChatFormat* rad_tools_chat_format(const LoadedPlugins& lp, const RadModelMeta& meta) {
const Plugin* ap = rad_tools_registry().plugin(lp.arch_plugin);
if (!ap || !ap->arch_chat_format) return nullptr;
return ap->arch_chat_format(&meta);
}
WeightSourceFn rad_container_sources(const RadFile& f) {
return [&f](const std::string& name, const Program&, WeightSource* out) {
const RadFileEntry* e = f.find(name);
if (!e) return RAD_E_NOTFOUND;
out->enc = f.encoding(*e);
out->rank = e->rank;
for (int i = 0; i < RAD_MAX_RANK; ++i) out->shape[i] = e->shape[i];
return RAD_OK;
};
}
WeightSourceFn CheckpointSources::fn() {
return [this](const std::string& name, const Program& prog, WeightSource* out) {
return answer(name, prog, out);
};
}
int CheckpointSources::answer(const std::string& name, const Program& prog, WeightSource* out) {
std::lock_guard<std::mutex> lk(mu_);
auto it = got_.find(name);
if (it == got_.end()) {
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. */
if (st == RAD_E_NOTFOUND) {
missing_[name] = why;
return st;
}
missing_.erase(name);
if (st < 0) {
refused_[name] = why;
return st;
}
it = got_.emplace(name, std::move(w)).first;
}
const CkptWeight& w = it->second;
if (!w.trivial) {
refused_[name] = w.why;
return RAD_E_UNSUPPORTED;
}
out->enc = w.enc;
out->rank = w.rank;
for (int i = 0; i < RAD_MAX_RANK; ++i) out->shape[i] = w.shape[i];
return RAD_OK;
}
const CkptWeight* CheckpointSources::find(const std::string& name) const {
std::lock_guard<std::mutex> lk(mu_);
auto it = got_.find(name);
return it == got_.end() || !it->second.trivial ? nullptr : &it->second;
}
std::string CheckpointSources::missing(const std::string& name) const {
std::lock_guard<std::mutex> lk(mu_);
auto it = missing_.find(name);
return it == missing_.end() ? std::string() : it->second;
}
std::vector<std::string> CheckpointSources::refused() const {
std::lock_guard<std::mutex> lk(mu_);
std::vector<std::string> out;
for (const auto& [n, why] : refused_) out.push_back(n + ": " + why);
return out;
}
int rad_tools_declare(const LoadedPlugins& lp, const RadModelMeta& meta, const RadBuildCtx& ctx,
Program* out, const std::function<int(RadBuilder*, int64_t)>& also,
const Program* ref, const WeightSourceFn& sources, bool instances) {
if (!out) return RAD_E_INVAL;
Registry& r = rad_tools_registry();
const Plugin* ap = r.plugin(lp.arch_plugin);
if (!ap || !ap->arch_declare) {
RAD_ERR("architecture plugin '%s' is not loaded or exports no rad_arch_declare",
lp.arch_plugin.c_str());
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);
b.set_instances(instances);
int s = ap->arch_declare(&b, &meta, &ctx);
if (s < 0) {
RAD_ERR("%s: rad_arch_declare returned %s", lp.arch_plugin.c_str(), rad_strerror(s));
for (const auto& e : b.errors()) RAD_ERR(" %s", e.c_str());
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. */
if (also) {
/* 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. */
int64_t lw = 0;
if (b.program().logits_buf != RAD_NULL_HANDLE &&
(size_t)b.program().logits_buf < b.program().buffers.size()) {
const RadBufDecl& d = b.program().buffers[b.program().logits_buf].decl;
if (d.rank > 0) lw = d.shape[d.rank - 1];
}
s = also(&b, lw);
if (s < 0) {
for (const auto& e : b.errors()) RAD_ERR(" %s", e.c_str());
return s;
}
}
s = b.finish();
/* Declare ALWAYS completes: a structural error is reported whole, not first-failure-at-the-top
* (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();
*out = std::move(b.program());
return RAD_OK;
}
} /* namespace rad */
-151
View File
@@ -1,151 +0,0 @@
/* startup.h -- steps 1 through 4 of spec §1's startup sequence, shared by the engine and by every
* tool that needs them.
*
* 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.
*/
#pragma once
#include "rad_core.h"
#include "format/radfile.h"
#include "format/checkpoint.h"
#include "plugin/registry.h"
#include "build/rad_build.h"
#include <functional>
#include <map>
#include <mutex>
#include <string>
#include <vector>
namespace rad {
/* A loaded plugin, as a tool names it. */
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. */
std::vector<PluginId> 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. */
std::string arch_quant;
/* `name@version`, space separated, in hierarchy order: what a benchmark records as the
* libraries it measured. */
std::string libraries() const {
std::string s;
for (const auto& p : kernels) {
if (!s.empty()) s += ' ';
s += p.name + "@" + (p.version.empty() ? "0" : p.version);
}
return s;
}
};
/* $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. */
std::vector<std::string> rad_home_dirs(const std::string& home);
/* `<home>/<rel>` 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. */
int rad_tools_load_plugins(const std::string& radiance_home,
const std::vector<std::string>& hierarchy,
const std::string& arch_id,
const std::string& quant,
LoadedPlugins* out);
/* `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. */
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. */
int rad_tools_declare(const LoadedPlugins& plugins, const RadModelMeta& meta,
const RadBuildCtx& ctx, Program* out,
const std::function<int(RadBuilder*, int64_t logits_width)>& also = {},
const Program* ref = nullptr, const WeightSourceFn& sources = {},
bool instances = true);
/* A container's entries as the source of every declaration's encoding. `f` must outlive the
* 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.
*
* 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. */
class CheckpointSources {
public:
explicit CheckpointSources(Checkpoint& ck) : ck_(ck) {}
WeightSourceFn fn();
/* After declare: what `name` resolved to, or null. */
const CkptWeight* find(const std::string& name) const;
/* Why `name` resolved to nothing, as the name map last answered it; empty if it did. */
std::string missing(const std::string& name) const;
/* Every weight that is not served as it stands, "name: why", sorted. */
std::vector<std::string> refused() const;
private:
int answer(const std::string& name, const Program& prog, WeightSource* out);
Checkpoint& ck_;
mutable std::mutex mu_;
std::map<std::string, CkptWeight> got_;
std::map<std::string, std::string> refused_;
std::map<std::string, std::string> 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. */
int rad_reference_ops(const Program& p, std::vector<std::string>* 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. */
int rad_gate_reference_kernels(const Program& p, bool allow, const char* what);
Registry& rad_tools_registry();
} /* namespace rad */
-754
View File
@@ -1,754 +0,0 @@
/* 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
* (spec §6).
*/
#include "rad_core.h"
#include "sample/host_ref.h"
#include "server/oai.h"
#include <nlohmann/json.hpp>
#include <algorithm>
#include <cerrno>
#include <climits>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <sstream>
namespace rad {
struct Flag {
const char* name;
const char* arg; /* null for a boolean */
const char* help;
};
static const Flag g_flags[] = {
{ "--model", "PATH", "the .rad container, or a checkpoint served as it stands" },
{ "--radiance-home", "DIRS", "where kernels/, architectures/ and quantizers/ live; several\n"
"homes separated by ':' are searched in order, the first winning" },
{ "--kernels", "LIST", "kernel plugin hierarchy, comma-separated, first wins" },
{ "--tp", "N", "tensor-parallel ranks" },
{ "--tp-wire", "MODE", "cross-rank all-reduce payload: exact (default) or wht6, a\n"
"lossy wire: rotated 6-bit at 2 ranks, tiered int8 at 4,\n"
"none at 8" },
{ "--tp-wire-min-kb", "N", "smallest all-reduce, in KiB, the lossy wire is used for" },
{ "--max-num-batched-tokens", "N", "the largest token count one step may carry" },
{ "--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" },
{ "--gpu-headroom-mib", "N", "VRAM left unclaimed on every card (default 96)" },
/* THE FLAG THAT DECIDES WHETHER MULTI-TURN WORKS, which is more than the split it names.
* The KV side is not just concurrency: prefix caching holds a finished sequence's blocks
* so the next turn can reuse them, so 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, bought back for
* a fraction of a percent of the decode step. See core/mem/prefix.h. */
{ "--expert-vs-cache-ratio", "R", "weights vs KV split of what is claimed (default "
"0.75). The KV side also holds cached prefixes, so "
"too little of it makes every agent turn re-prefill" },
{ "--vram-weights-mib", "N", "the resident weight slab; 0 derives it from the card" },
{ "--vram-kv-mib", "N", "the paged KV pool; 0 derives it from the card" },
{ "--kv-cache-dtype", "T", "bf16 | fp8 -- fp8 halves what a token of context costs" },
{ "--host-pool-mib", "N", "pinned host tier" },
{ "--embedding-placement", "WHERE", "auto (default) | vram | ram: where the token embedding lives. ram\n"
" keeps it in the pinned host pool, read over the link in place;\n"
" auto keeps it on the card unless the KV cache could then not\n"
" hold one --max-model-len sequence. disk is refused: the lookup\n"
" writes the card's activations, which no host read can reach" },
{ "--ngram-placement", "WHERE", "auto (default) | vram | ram | disk: where an n-gram\n"
" embedding table lives (Qwen3.8-Flash-Next: 47.7 GiB).\n"
" vram puts all of it on every card; ram copies it into\n"
" host memory at load, pinned for the cards to read\n"
" (locked, where only a host kernel reads it); disk reads\n"
" its rows from the container on the host. auto takes the\n"
" first of the three that holds it" },
{ "--weights-disk-tier", nullptr, "read weights that fit neither VRAM nor the host pool from the\n"
" container on disk (O_DIRECT); a routed expert is read a layer\n"
" at a time, so a step is paced by the drive" },
{ "--prefix-cache-host-mib", "N", "copy finished conversations' KV to host memory, up to N MiB,\n"
" so their VRAM can go to experts and a return restores\n"
" instead of re-prefilling. 0 is off. Part of it holds\n"
" linear-state snapshots on a hybrid model; startup says how many" },
{ "--prefix-cache-dir", "DIR", "where the disk tier keeps them. Not --weights-disk-tier, which is\n"
" about WEIGHTS" },
{ "--prefix-cache-disk-mib", "N", "and copy them on to disk under --prefix-cache-dir, up to N MiB,\n"
" so a full host tier gives slots up for nothing. Holds\n"
" conversation content unencrypted. 0 is off" },
{ "--placement", "MODE", "all_vram | layer_offload | expert_tiered | auto" },
{ "--deterministic", nullptr, "pin placement to the plan the loader made, so the resident\n"
" set cannot change under the heat engine. The sampler is\n"
" already order-independent and needs no pinning; note that\n"
" 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. `ck_free_` is one global free list of N slots handed out by
* pop_back (core/mem/kv.cpp), 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. */
{ "--checkpoint-slots", "N", "linear-state snapshots retained IN TOTAL (not "
"per sequence); compare against --max-num-seqs" },
{ "--no-prefix-cache", nullptr, "disable prefix caching" },
{ "--checkpoint-policy", "NAME", "which snapshots a session retains: geometric-backoff "
"(default), tip-only, keep-all" },
{ "--num-speculative-tokens", "N", "speculative window; 0 disables. Default `auto`: the drafter's\n"
" own operating point, which the plugin states. A container\n"
" with no draft head is unaffected -- auto resolves to 0." },
{ "--draft-model", "PATH", "NOT IMPLEMENTED -- merge the drafter at convert time" },
{ "--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" },
{ "--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 <model>.generation.json\n"
" beside the container, 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-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"
" config asked for; unset, they are resolved from it" },
{ "--reasoning-effort", "S", "default `reasoning_effort` for chat requests that do not set one.\n"
" The value goes to the model's chat template verbatim, so the legal\n"
" set is the template's: Qwen3.8 takes xhigh|medium|low and defaults\n"
" to xhigh, which on a short task can spend the whole token budget\n"
" inside <think> and answer nothing. \"none\" turns thinking off" },
{ "--thinking-token-budget", "N", "default `thinking_token_budget` for chat requests that do not set one: at\n"
" N reasoning tokens the reasoning block is closed and the answer follows,\n"
" so a client's max_tokens is not spent on reasoning alone. Unset is no\n"
" limit. Needs a reasoning block that ends in one token, as </think> is" },
{ "--typical-p", "F", "default typical_p, (0, 1]. This flag and the eleven below set the default\n"
" for requests that do not name the field; a request that names it wins" },
{ "--presence-penalty", "F", "default presence_penalty, [-2, 2]" },
{ "--frequency-penalty", "F", "default frequency_penalty, [-2, 2]" },
{ "--repetition-penalty", "F", "default repetition_penalty, > 0" },
{ "--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-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]" },
{ "--xtc-threshold", "F", "default xtc_threshold, [0, 1]" },
{ "--default-max-tokens", "N", "max_tokens for requests that do not set one: N, or `auto` (default),\n"
" whatever the context leaves after the prompt" },
{ "--max-tokens-cap", "N", "the most any request may generate. A larger max_tokens is cut to it rather\n"
" than refused, and the reply ends with finish_reason \"length\". 0 is none\n"
" (default)" },
{ "--max-n", "N", "the largest `n` a request may ask for (default: the larger of 8 and\n"
" --max-num-seqs)" },
{ "--max-queued-requests", "N", "requests admitted and unfinished at once, past which the answer is 429\n"
" (default 8 x --max-num-seqs)" },
{ "--max-stop-strings", "N", "stop strings one request may send (default 64)" },
{ "--max-stop-bytes", "N", "bytes in one stop string (default 4096)" },
{ "--chat-template-kwargs", "JSON", "variables handed to the chat template on every chat request: a JSON object,\n"
" or @FILE to read one. Repeatable, a later key replacing an earlier one.\n"
" A key the request's own chat_template_kwargs names is the request's, and a\n"
" request that says anything about thinking replaces enable_thinking and\n"
" reasoning_effort here" },
{ "--reasoning-format", "MODE", "auto (default): a reasoning block comes back as reasoning_content.\n"
" none: it stays inline in content" },
{ "--http-threads", "N", "HTTP workers kept while idle (default: one per core, at least 4)" },
{ "--read-timeout", "S", "seconds a client may go silent while sending a request (default 30)" },
{ "--write-timeout", "S", "seconds one write to a client may block (default 600)" },
{ "--keep-alive-timeout", "S", "seconds an idle connection is held open between requests (default 5)" },
{ "--max-body-mib", "N", "the largest request body; images and video arrive base64 inside it\n"
" (default 512)" },
{ "--retry-after", "S", "the Retry-After a 429 carries, in seconds (default 1)" },
{ "--no-cors", nullptr, "send no CORS headers, so a page on another origin cannot read the API" },
{ "--image-min-pixels", "N", "an image is resized to at least N pixels (default: the container's)" },
{ "--image-max-pixels", "N", "and to at most N; one encoder pass (--mm-max-patches) still bounds it" },
{ "--video-min-pixels", "N", "a video's sampled frames together resize to at least N pixels" },
{ "--video-max-pixels", "N", "and to at most N" },
{ "--video-fps", "F", "frames sampled per second of video" },
{ "--video-min-frames", "N", "the fewest frames sampled from a video" },
{ "--video-max-frames", "N", "the most frames sampled from a video" },
{ "--video-max-frame-tokens", "N", "the most prompt tokens one video frame may become; 0 is no cap" },
{ "--max-source-pixels", "N", "the largest image or video frame the decoder accepts, before any resize\n"
" (default 67108864). The media flags above default to what the container\n"
" states, and do nothing for a model that takes no media" },
{ "--kld-record", "DIR", "instead of serving, run --kld-corpus through prefill and write this\n"
" model's log-probabilities at every scored position to DIR: the\n"
" reference a quantised model is measured against" },
{ "--kld-ref", "DIR", "instead of serving, score this model against the reference in DIR:\n"
" mean, median, 99/99.9/99.99th percentile KL divergence and top-1\n"
" agreement, over the positions and tokens DIR was recorded at" },
{ "--kld-corpus", "FILE", "JSONL, one {\"prompt\", \"score_from\"?, \"source\"?} a line; --kld-record only" },
{ "--kld-out", "FILE", "the --kld-ref report as JSON, and every position's numbers in FILE.rows" },
{ "--debug-graph", nullptr, "print the entire declared graph and exit-quality detail" },
{ "--debug-selection", nullptr, "print the selection table" },
{ "--debug-placement", nullptr, "print the placement plan" },
{ "--debug-accept-reference-kernels", nullptr,
"serve even when ops resolve only to a reference library. NOT a production configuration: the reference\n"
" implementation is an oracle and a last resort, and falling back\n"
" to it is orders of magnitude of speed with nothing to say so." },
{ "--profile-ops", nullptr, "per-op device timing (see the caveat it prints)" },
{ "--live", nullptr, "the live view: cards, throughput, draft acceptance, the expert plane.\n"
" Redirected it prints one greppable key=value line instead" },
{ "-v", nullptr, "verbose" },
{ "-vv", nullptr, "very verbose" },
{ "--help", nullptr, "this" },
};
void config_usage(const char* argv0) {
fprintf(stderr, "usage: %s --model FILE [options]\n\n", argv0);
for (const Flag& f : g_flags) {
char left[64];
snprintf(left, sizeof left, "%s%s%s", f.name, f.arg ? " " : "", f.arg ? f.arg : "");
fprintf(stderr, " %-32s %s\n", left, f.help);
}
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");
}
/* 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. */
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;
else if (!std::strcmp(v, "ram")) *out = TablePlacement::Ram;
else if (!std::strcmp(v, "disk")) *out = TablePlacement::Disk;
else return false;
return true;
}
static std::vector<std::string> split_commas(const std::string& s) {
std::vector<std::string> 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. */
static bool parse_num(const char* flag, const char* v, double* out) {
char* end = nullptr;
errno = 0;
const double d = std::strtod(v, &end);
if (!*v || !end || *end || errno == ERANGE || !std::isfinite(d)) {
RAD_ERR("%s takes a number, not '%s'", flag, v);
return false;
}
*out = d;
return true;
}
static bool parse_int(const char* flag, const char* v, int64_t lo, int64_t hi, int64_t* out) {
char* end = nullptr;
errno = 0;
const long long n = std::strtoll(v, &end, 10);
if (!*v || !end || *end || errno == ERANGE) {
RAD_ERR("%s takes a whole number, not '%s'", flag, v);
return false;
}
if (n < lo || n > hi) {
if (lo > INT32_MIN && (hi == INT32_MAX || hi == INT64_MAX))
RAD_ERR("%s must be >= %lld, not %lld", flag, (long long)lo, n);
else
RAD_ERR("%s must be in [%lld, %lld], not %lld", flag, (long long)lo, (long long)hi, n);
return false;
}
*out = n;
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. */
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;
if (!server::sampler_value_ok(field, *out, &why)) {
RAD_ERR("%s %s: %s %s", flag, v, field, why.c_str());
return false;
}
return true;
}
static bool sampler_int(const char* flag, const char* field, const char* v, int* out) {
int64_t n = 0;
double d = 0;
if (!parse_int(flag, v, INT32_MIN, INT32_MAX, &n) || !sampler_num(flag, field, v, &d))
return false;
*out = (int)n;
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. */
static const char* const kTemplateOwnNames[] = {
"messages", "tools", "bos_token", "eos_token", "add_generation_prompt",
};
/* --chat-template-kwargs: a JSON object, or @FILE holding one, merged key by key into `out`. */
static bool parse_template_kwargs(const char* v, std::map<std::string, std::string>* out) {
std::string text = v;
std::string src = "--chat-template-kwargs";
if (!text.empty() && text[0] == '@') {
std::ifstream f(text.substr(1), std::ios::binary);
if (!f) {
RAD_ERR("--chat-template-kwargs %s: cannot read %s", v, text.c_str() + 1);
return false;
}
std::ostringstream ss;
ss << f.rdbuf();
src += " " + text.substr(1);
text = ss.str();
}
const nlohmann::json j = nlohmann::json::parse(text, nullptr, false);
if (j.is_discarded() || !j.is_object()) {
RAD_ERR("%s takes a JSON object, such as '{\"enable_thinking\": false}'", src.c_str());
return false;
}
for (auto it = j.begin(); it != j.end(); ++it) {
for (const char* own : kTemplateOwnNames)
if (it.key() == own) {
RAD_ERR("%s: '%s' is set by the server for every request and cannot be a template "
"variable", src.c_str(), own);
return false;
}
if (it.key() == "enable_thinking" && !it.value().is_boolean()) {
RAD_ERR("%s: enable_thinking takes true or false", src.c_str());
return false;
}
/* dump(): the template context takes JSON, so a string arrives still quoted. */
(*out)[it.key()] = it.value().dump();
}
return true;
}
/* Returns 0 on success, 1 for --help (caller exits 0), negative on a bad argument. An unknown
* flag is an error naming it, not a warning: a typo in a budget flag is the difference between
* the plan you asked for and one the planner invented. */
int config_parse(int argc, char** argv, Config* c) {
auto need = [&](int& i) -> const char* {
if (i + 1 >= argc) { RAD_ERR("%s needs an argument", argv[i]); return nullptr; }
return argv[++i];
};
for (int i = 1; i < argc; ++i) {
std::string a = argv[i];
const char* v = nullptr;
auto S = [&](const char* n) { return a == n; };
if (S("--help") || S("-h")) return 1;
else 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("--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("--tp-wire")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (!std::strcmp(v, "exact")) c->tp_wire_exact = 1;
else if (!std::strcmp(v, "wht6")) c->tp_wire_exact = 0;
else { RAD_ERR("--tp-wire takes exact or wht6, 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("--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("--vram-weights-mib")) { if (!(v = need(i))) return RAD_E_INVAL; c->vram_weights_mib = atoll(v); }
else if (S("--vram-kv-mib")) { if (!(v = need(i))) return RAD_E_INVAL; c->vram_kv_mib = atoll(v); }
/* --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. */
else if (S("--gpu-headroom-mib") || S("--gpu-headroom"))
{ if (!(v = need(i))) return RAD_E_INVAL; c->gpu_headroom_mib = atoll(v); }
else if (S("--kv-cache-dtype")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (std::strcmp(v, "bf16") && std::strcmp(v, "fp8")) {
RAD_ERR("--kv-cache-dtype takes bf16 or fp8, not '%s'", v);
return RAD_E_INVAL;
}
c->kv_cache_dtype = v;
}
else if (S("--expert-vs-cache-ratio")) {
if (!(v = need(i))) return RAD_E_INVAL;
c->expert_cache_ratio = atof(v);
if (!(c->expert_cache_ratio > 0.0 && c->expert_cache_ratio < 1.0)) {
RAD_ERR("--expert-vs-cache-ratio is the WEIGHTS share of what is claimed and must "
"be strictly between 0 and 1, not '%s'. 0.75 gives three quarters to "
"weights and a quarter to the KV cache.", v);
return RAD_E_INVAL;
}
}
else if (S("--host-pool-mib")) { if (!(v = need(i))) return RAD_E_INVAL; c->host_pool_mib = atoll(v); }
else if (S("--embedding-placement") || S("--ngram-placement")) {
const bool emb = S("--embedding-placement");
if (!(v = need(i))) return RAD_E_INVAL;
TablePlacement p;
if (!parse_table_placement(v, &p)) {
RAD_ERR("%s takes auto, vram, ram or disk, not '%s'", a.c_str(), v);
return RAD_E_INVAL;
}
(emb ? c->embedding_placement : c->ngram_placement) = p;
}
else if (S("--weights-disk-tier")) { c->weights_disk_tier = true; }
else if (S("--prefix-cache-host-mib")) { if (!(v = need(i))) return RAD_E_INVAL; c->prefix_cache_host_mib = atoll(v); }
else if (S("--prefix-cache-dir")) { if (!(v = need(i))) return RAD_E_INVAL; c->prefix_cache_dir = v; }
else if (S("--prefix-cache-disk-mib")) { if (!(v = need(i))) return RAD_E_INVAL; c->prefix_cache_disk_mib = atoll(v); }
else if (S("--placement")) { if (!(v = need(i))) 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("--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. */
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, "
"keep-all", v);
return RAD_E_INVAL;
}
c->checkpoint_policy = v;
}
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);
return RAD_E_INVAL;
}
}
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. */
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 "
"`rad-convert --draft-model DIR` and pass the container to --model. "
"An MTP head that ships inside the target checkpoint needs neither flag.");
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("--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;
if (!*v) { RAD_ERR("--served-model-name takes a non-empty name"); return RAD_E_INVAL; }
c->served_model_name = v;
}
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 (S("--reasoning-effort")) { if (!(v = need(i))) return RAD_E_INVAL;
c->reasoning_effort = v; }
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("--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. */
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";
double d = 0;
if (!sampler_num(a.c_str(), field, v, &d)) return RAD_E_INVAL;
(S("--temp") ? c->sample_temp : S("--top-p") ? c->sample_top_p : c->sample_min_p) = (float)d;
}
else if (S("--top-k")) { if (!(v = need(i))) return RAD_E_INVAL;
if (!sampler_int("--top-k", "top_k", v, &c->sample_top_k))
return RAD_E_INVAL; }
else if (S("--typical-p") || S("--presence-penalty") || S("--frequency-penalty") ||
S("--repetition-penalty") || S("--dry-multiplier") || S("--dry-base") ||
S("--xtc-probability") || S("--xtc-threshold")) {
if (!(v = need(i))) return RAD_E_INVAL;
struct F { const char* flag; const char* field; std::optional<float> Config::* m; };
static const F kF[] = {
{ "--typical-p", "typical_p", &Config::sample_typical_p },
{ "--presence-penalty", "presence_penalty", &Config::sample_pres_penalty },
{ "--frequency-penalty", "frequency_penalty", &Config::sample_freq_penalty },
{ "--repetition-penalty", "repetition_penalty", &Config::sample_rep_penalty },
{ "--dry-multiplier", "dry_multiplier", &Config::sample_dry_multiplier },
{ "--dry-base", "dry_base", &Config::sample_dry_base },
{ "--xtc-probability", "xtc_probability", &Config::sample_xtc_probability },
{ "--xtc-threshold", "xtc_threshold", &Config::sample_xtc_threshold },
};
for (const F& f : kF) {
if (!S(f.flag)) continue;
double d = 0;
if (!sampler_num(f.flag, f.field, v, &d)) return RAD_E_INVAL;
c->*f.m = (float)d;
}
}
else if (S("--repeat-last-n") || S("--dry-allowed-length") || S("--dry-penalty-last-n")) {
if (!(v = need(i))) return RAD_E_INVAL;
const char* field = S("--repeat-last-n") ? "repeat_last_n"
: S("--dry-allowed-length") ? "dry_allowed_length"
: "dry_penalty_last_n";
int n = 0;
if (!sampler_int(a.c_str(), field, v, &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;
}
else if (S("--dry-sequence-breakers")) {
if (!(v = need(i))) return RAD_E_INVAL;
const nlohmann::json j = nlohmann::json::parse(v, nullptr, false);
bool strings = j.is_array();
if (strings) for (const auto& e : j) strings = strings && e.is_string();
if (!strings) {
RAD_ERR("--dry-sequence-breakers takes a JSON array of strings, such as "
"'[\"\\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. */
if (j.size() > kDryMaxBreakers) {
RAD_ERR("--dry-sequence-breakers holds %zu strings; the sampler takes at most %zu",
j.size(), kDryMaxBreakers);
return RAD_E_INVAL;
}
c->sample_dry_seq_breakers = j.get<std::vector<std::string>>();
}
else if (S("--default-max-tokens")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (!std::strcmp(v, "auto")) c->default_max_tokens = 0;
else if (!parse_int(a.c_str(), v, 1, INT32_MAX, &c->default_max_tokens)) {
RAD_ERR("--default-max-tokens takes a token count >= 1, or auto");
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("--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. */
if (std::strcmp(v, "auto") && std::strcmp(v, "none")) {
RAD_ERR("--reasoning-format takes auto or none, not '%s'", v);
return RAD_E_INVAL;
}
c->reasoning_format = v;
}
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. */
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;
(S("--http-threads") ? c->http_threads
: S("--read-timeout") ? c->http_read_timeout_s
: S("--write-timeout") ? c->http_write_timeout_s
: 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("--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")) {
if (!(v = need(i))) return RAD_E_INVAL;
int64_t n = 0;
if (!parse_int(a.c_str(), v, 1, INT64_MAX, &n)) return RAD_E_INVAL;
(S("--image-min-pixels") ? c->image_min_pixels
: S("--image-max-pixels") ? c->image_max_pixels
: S("--video-min-pixels") ? c->video_min_pixels
: S("--video-max-pixels") ? c->video_max_pixels
: c->max_source_pixels) = n;
}
else if (S("--video-fps")) {
if (!(v = need(i))) return RAD_E_INVAL;
double d = 0;
if (!parse_num(a.c_str(), v, &d)) return RAD_E_INVAL;
if (!(d > 0.0)) { RAD_ERR("--video-fps must be > 0, not '%s'", v); return RAD_E_INVAL; }
c->video_fps = d;
}
else if (S("--video-min-frames") || S("--video-max-frames") || S("--video-max-frame-tokens")) {
if (!(v = need(i))) return RAD_E_INVAL;
int64_t n = 0;
if (!parse_int(a.c_str(), v, S("--video-max-frame-tokens") ? 0 : 1, INT32_MAX, &n))
return RAD_E_INVAL;
(S("--video-min-frames") ? c->video_min_frames
: S("--video-max-frames") ? c->video_max_frames
: c->video_max_frame_tokens) = (int32_t)n;
}
else if (S("--kld-record")) { if (!(v = need(i))) return RAD_E_INVAL; c->kld_record = v; }
else if (S("--kld-ref")) { if (!(v = need(i))) return RAD_E_INVAL; c->kld_ref = v; }
else if (S("--kld-corpus")) { if (!(v = need(i))) return RAD_E_INVAL; c->kld_corpus = v; }
else if (S("--kld-out")) { if (!(v = need(i))) return RAD_E_INVAL; c->kld_out = v; }
else if (S("--debug-graph")) { c->debug_graph = true; c->debug_selection = true; }
else if (S("--debug-selection")) c->debug_selection = true;
else if (S("--debug-placement")) c->debug_placement = true;
else if (S("--debug-accept-reference-kernels")) c->accept_reference_kernels = true;
else if (S("--profile-ops")) c->profile_ops = true;
else if (S("--live")) c->live_view = true;
else {
RAD_ERR("unknown option '%s'", a.c_str());
return RAD_E_INVAL;
}
}
if (c->radiance_home.empty()) {
const char* h = getenv("RADIANCE_HOME");
c->radiance_home = h ? h : RAD_DEFAULT_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);
}
/* 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 orders what it finds: everything named by
* --kernels or RADIANCE_KERNELS first, then every other plugin, then 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 -- and naming one ahead of another is what settles a tie between two that
* both serve an op. */
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. */
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;
}
if (!c->kld_record.empty() && c->kld_corpus.empty()) {
RAD_ERR("--kld-record needs --kld-corpus: the reference is recorded over a corpus");
return RAD_E_INVAL;
}
if (!c->kld_ref.empty() && !c->kld_corpus.empty()) {
RAD_ERR("--kld-ref reads its tokens from the reference, which recorded them; drop "
"--kld-corpus");
return RAD_E_INVAL;
}
if (!c->kld_out.empty() && c->kld_ref.empty()) {
RAD_ERR("--kld-out is the --kld-ref report");
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. */
if (!c->reasoning_effort.empty() &&
(c->chat_template_kwargs.count("reasoning_effort") ||
c->chat_template_kwargs.count("enable_thinking"))) {
RAD_ERR("--reasoning-effort and a reasoning_effort or enable_thinking key in "
"--chat-template-kwargs both set the default for thinking; give one");
return RAD_E_INVAL;
}
if (c->default_max_tokens > 0 && c->max_tokens_cap > 0 &&
c->default_max_tokens > c->max_tokens_cap) {
RAD_ERR("--default-max-tokens %lld is above --max-tokens-cap %lld, so no request could be "
"served at the default", (long long)c->default_max_tokens,
(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. */
if (c->max_n > 0 || c->max_queued_requests > 0) {
const int64_t n = c->max_n > 0 ? c->max_n : std::max<int64_t>(8, c->max_seqs);
const int64_t q = c->max_queued_requests > 0 ? c->max_queued_requests : c->max_seqs * 8;
if (n > q) {
RAD_ERR("--max-n %lld is above the %lld requests the queue admits "
"(--max-queued-requests), so a request asking for it could never be admitted",
(long long)n, (long long)q);
return RAD_E_INVAL;
}
}
if (c->image_min_pixels && c->image_max_pixels && *c->image_min_pixels > *c->image_max_pixels) {
RAD_ERR("--image-min-pixels is above --image-max-pixels"); return RAD_E_INVAL; }
if (c->video_min_pixels && c->video_max_pixels && *c->video_min_pixels > *c->video_max_pixels) {
RAD_ERR("--video-min-pixels is above --video-max-pixels"); return RAD_E_INVAL; }
if (c->video_min_frames && c->video_max_frames && *c->video_min_frames > *c->video_max_frames) {
RAD_ERR("--video-min-frames is above --video-max-frames"); return RAD_E_INVAL; }
return RAD_OK;
}
} /* namespace rad */
-2508
View File
File diff suppressed because it is too large. Load diff
-90
View File
@@ -1,90 +0,0 @@
/* aql.h -- what the AQL backend's translation units share.
*
* 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.
*/
#pragma once
#include <cstddef>
#include <cstdint>
#include <string>
#include <vector>
namespace rad {
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`. */
enum class Hidden : uint8_t {
None, /* an explicit parameter */
Pad, /* hidden_none: bytes the compiler reserved and reads nothing from */
BlockCountX, BlockCountY, BlockCountZ,
GroupSizeX, GroupSizeY, GroupSizeZ,
RemainderX, RemainderY, RemainderZ,
GlobalOffsetX, GlobalOffsetY, GlobalOffsetZ,
GridDims,
DynamicLds,
Unsupported, /* anything else: a kernel that wants it is refused by name */
};
struct KernelArg {
uint32_t offset = 0;
uint32_t size = 0;
Hidden hidden = Hidden::None;
std::string kind; /* the metadata's value_kind, for the refusal message */
};
struct KernelMeta {
std::string symbol; /* "<name>.kd" */
uint32_t kernarg_size = 0;
uint32_t group_size = 0; /* static LDS */
uint32_t private_size = 0; /* static scratch */
bool dynamic_stack = false;
std::vector<KernelArg> 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. */
bool bundle_code_object(const void* bundle, const std::vector<std::string>& isas, const void** out,
size_t* out_size, std::string* why);
/* Every kernel described in an AMDGPU code object's metadata note. */
bool code_object_kernels(const void* elf, size_t size, std::vector<KernelMeta>* out,
std::string* why);
/* ------------------------------------------------------------------ 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. */
enum : uint8_t { kFenceAcquireSystem = 1, kFenceReleaseSystem = 2 };
void set_next_fence(uint8_t f);
} // namespace aql
} // namespace rad
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. */
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. */
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. */
int rad_aql_blit_ranges(void* dst, const void* src, uint64_t prefix, const RadCopyRange* ranges,
int n, void* stream);
}
-252
View File
@@ -1,252 +0,0 @@
/* aql_blit.hip -- the copy and fill kernels the AQL backend dispatches for rad_memcpy_async,
* rad_memcpy_2d_async and rad_memset_async.
*
* 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.
*
* 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.
*/
#include <hip/hip_runtime.h>
#include <cstdint>
#include "aql.h"
#include "device.h"
namespace {
constexpr int kThreads = 256;
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. */
__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;
uint64_t i = (uint64_t)blockIdx.x * kThreads + threadIdx.x;
for (; i + 3 * stride < n; i += 4 * stride) {
const u32x4 a = src[i], b = src[i + stride], c = src[i + 2 * stride], d = src[i + 3 * stride];
dst[i] = a; dst[i + stride] = b; dst[i + 2 * stride] = c; dst[i + 3 * stride] = d;
}
for (; i < n; i += stride) dst[i] = src[i];
}
/* A COPY THAT READS OR WRITES ACROSS THE LINK 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:
*
* 16 x 256 threads, 4 loads in flight 28.9 GB/s
* 1 x 256 threads, 16 in flight 28.9
* 1 x 128 threads, 16 in flight 28.9 <- this
* 1 x 64 threads, 16 in flight 16.8
* 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.
*
* 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. */
constexpr int kLinkThreads = 128, kLinkDepth = 16;
constexpr uint64_t kLinkByteBlocks = 16;
__global__ __launch_bounds__(kLinkThreads) void aql_copy_link(const u32x4* __restrict__ src,
u32x4* __restrict__ dst, uint64_t n) {
uint64_t i = threadIdx.x;
for (; i + (uint64_t)(kLinkDepth - 1) * kLinkThreads < n; i += (uint64_t)kLinkDepth * kLinkThreads) {
u32x4 v[kLinkDepth];
#pragma unroll
for (int k = 0; k < kLinkDepth; ++k) v[k] = src[i + (uint64_t)k * kLinkThreads];
#pragma unroll
for (int k = 0; k < kLinkDepth; ++k) dst[i + (uint64_t)k * kLinkThreads] = v[k];
}
if (i >= n) return;
u32x4 v[kLinkDepth];
#pragma unroll
for (int k = 0; k < kLinkDepth; ++k) {
const uint64_t j = i + (uint64_t)k * kLinkThreads;
v[k] = src[j < n ? j : n - 1];
}
#pragma unroll
for (int k = 0; k < kLinkDepth; ++k) {
const uint64_t j = i + (uint64_t)k * kLinkThreads;
if (j < n) dst[j] = v[k];
}
}
__global__ __launch_bounds__(kThreads) void aql_copy1(const unsigned char* __restrict__ src,
unsigned char* __restrict__ dst, uint64_t n) {
const uint64_t stride = (uint64_t)gridDim.x * kThreads;
for (uint64_t i = (uint64_t)blockIdx.x * kThreads + threadIdx.x; i < n; i += stride)
dst[i] = src[i];
}
__global__ __launch_bounds__(kThreads) void aql_copy2d16(const u32x4* __restrict__ src,
u32x4* __restrict__ dst, uint64_t spitch16,
uint64_t dpitch16, uint64_t w16,
uint64_t height) {
const uint64_t cstride = (uint64_t)gridDim.x * kThreads;
for (uint64_t r = blockIdx.y; r < height; r += gridDim.y) {
const u32x4* s = src + r * spitch16;
u32x4* d = dst + r * dpitch16;
for (uint64_t c = (uint64_t)blockIdx.x * kThreads + threadIdx.x; c < w16; c += cstride)
d[c] = s[c];
}
}
__global__ __launch_bounds__(kThreads) void aql_copy2d1(const unsigned char* __restrict__ src,
unsigned char* __restrict__ dst,
uint64_t spitch, uint64_t dpitch,
uint64_t width, uint64_t height) {
const uint64_t cstride = (uint64_t)gridDim.x * kThreads;
for (uint64_t r = blockIdx.y; r < height; r += gridDim.y) {
const unsigned char* s = src + r * spitch;
unsigned char* d = dst + r * dpitch;
for (uint64_t c = (uint64_t)blockIdx.x * kThreads + threadIdx.x; c < width; c += cstride)
d[c] = s[c];
}
}
/* 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. */
constexpr int kRangeWords = 16;
__global__ __launch_bounds__(kThreads) void aql_copy_ranges(const u32x4* __restrict__ src16,
u32x4* __restrict__ dst16, uint64_t n16,
unsigned prefix_blocks,
const RadCopyRange* __restrict__ r) {
if (blockIdx.x < prefix_blocks) {
const uint64_t stride = (uint64_t)prefix_blocks * kThreads;
uint64_t i = (uint64_t)blockIdx.x * kThreads + threadIdx.x;
for (; i + 3 * stride < n16; i += 4 * stride) {
const u32x4 a = src16[i], b = src16[i + stride], c = src16[i + 2 * stride],
d = src16[i + 3 * stride];
dst16[i] = a; dst16[i + stride] = b; dst16[i + 2 * stride] = c; dst16[i + 3 * stride] = d;
}
for (; i < n16; i += stride) dst16[i] = src16[i];
return;
}
const RadCopyRange g = r[blockIdx.x - prefix_blocks];
const unsigned* s4 = (const unsigned*)((const char*)src16 + g.src);
unsigned* d4 = (unsigned*)((char*)dst16 + g.dst);
const int64_t n = g.bytes / 4;
for (int64_t base = 0; base < n; base += (int64_t)kThreads * kRangeWords) {
unsigned v[kRangeWords];
#pragma unroll
for (int k = 0; k < kRangeWords; ++k) {
const int64_t w = base + (int64_t)k * kThreads + threadIdx.x;
v[k] = s4[w < n ? w : n - 1];
}
#pragma unroll
for (int k = 0; k < kRangeWords; ++k) {
const int64_t w = base + (int64_t)k * kThreads + threadIdx.x;
if (w < n) d4[w] = v[k];
}
}
}
__global__ __launch_bounds__(kThreads) void aql_fill16(u32x4* __restrict__ dst, unsigned v,
uint64_t n) {
const uint64_t stride = (uint64_t)gridDim.x * kThreads;
const u32x4 w = { v, v, v, v };
for (uint64_t i = (uint64_t)blockIdx.x * kThreads + threadIdx.x; i < n; i += stride) dst[i] = w;
}
__global__ __launch_bounds__(kThreads) void aql_fill1(unsigned char* __restrict__ dst,
unsigned char v, uint64_t n) {
const uint64_t stride = (uint64_t)gridDim.x * kThreads;
for (uint64_t i = (uint64_t)blockIdx.x * kThreads + threadIdx.x; i < n; i += stride) dst[i] = v;
}
inline unsigned blocks_for(uint64_t n, uint64_t per_block, uint64_t cap = kMaxBlocks) {
uint64_t b = (n + per_block - 1) / per_block;
if (b < 1) b = 1;
if (b > cap) b = cap;
return (unsigned)b;
}
inline bool aligned16(uint64_t v) { return (v & 15u) == 0; }
inline int launched() { return hipGetLastError() == hipSuccess ? 0 : -1; }
} // namespace
extern "C" int rad_aql_blit_copy(void* dst, const void* src, uint64_t bytes, void* stream,
bool link) {
if (bytes == 0) return 0;
const hipStream_t s = (hipStream_t)stream;
if (aligned16((uint64_t)(uintptr_t)dst | (uint64_t)(uintptr_t)src | bytes)) {
const uint64_t n = bytes / 16;
if (link)
hipLaunchKernelGGL(aql_copy_link, dim3(1), dim3(kLinkThreads), 0, s,
(const u32x4*)src, (u32x4*)dst, n);
else
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. */
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);
}
return launched();
}
extern "C" int rad_aql_blit_copy2d(void* dst, uint64_t dpitch, const void* src, uint64_t spitch,
uint64_t width, uint64_t height, void* stream) {
if (width == 0 || height == 0) return 0;
const hipStream_t s = (hipStream_t)stream;
const unsigned by = (unsigned)(height < 65535 ? height : 65535);
if (aligned16((uint64_t)(uintptr_t)dst | (uint64_t)(uintptr_t)src | dpitch | spitch | width)) {
const uint64_t w16 = width / 16;
hipLaunchKernelGGL(aql_copy2d16, dim3(blocks_for(w16, kThreads), by), dim3(kThreads), 0, s,
(const u32x4*)src, (u32x4*)dst, spitch / 16, dpitch / 16, w16, height);
} else {
hipLaunchKernelGGL(aql_copy2d1, dim3(blocks_for(width, kThreads), by), dim3(kThreads), 0, s,
(const unsigned char*)src, (unsigned char*)dst, spitch, dpitch, width,
height);
}
return launched();
}
extern "C" int rad_aql_blit_ranges(void* dst, const void* src, uint64_t prefix,
const RadCopyRange* ranges, int n, void* stream) {
const uint64_t n16 = prefix / 16;
const unsigned pb = n16 ? blocks_for(n16, 4 * kThreads) : 0;
if (pb == 0 && n == 0) return 0;
hipLaunchKernelGGL(aql_copy_ranges, dim3(pb + (unsigned)n), dim3(kThreads), 0,
(hipStream_t)stream, (const u32x4*)src, (u32x4*)dst, n16, pb, ranges);
return launched();
}
extern "C" int rad_aql_blit_fill(void* dst, int value, uint64_t bytes, void* stream) {
if (bytes == 0) return 0;
const hipStream_t s = (hipStream_t)stream;
const unsigned char b = (unsigned char)value;
if (aligned16((uint64_t)(uintptr_t)dst | bytes)) {
const unsigned v = 0x01010101u * b;
const uint64_t n = bytes / 16;
hipLaunchKernelGGL(aql_fill16, dim3(blocks_for(n, 4 * kThreads)), dim3(kThreads), 0, s,
(u32x4*)dst, v, n);
} else {
hipLaunchKernelGGL(aql_fill1, dim3(blocks_for(bytes, 4 * kThreads)), dim3(kThreads), 0, s,
(unsigned char*)dst, b, bytes);
}
return launched();
}
-324
View File
@@ -1,324 +0,0 @@
/* 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.
*
* 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.
*
* Nothing here touches a device, so it builds and is tested without one.
*/
#include "aql.h"
#include <cstring>
namespace rad {
namespace aql {
/* ------------------------------------------------------------------ the offload bundle */
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. */
struct TargetId {
std::string proc;
std::vector<std::pair<std::string, char>> feat;
};
TargetId parse_target_id(const std::string& s) {
TargetId t;
size_t i = s.find(':');
t.proc = s.substr(0, i);
while (i != std::string::npos) {
const size_t j = s.find(':', i + 1);
const std::string f = s.substr(i + 1, j == std::string::npos ? std::string::npos : j - i - 1);
if (f.size() > 1 && (f.back() == '+' || f.back() == '-'))
t.feat.emplace_back(f.substr(0, f.size() - 1), f.back());
i = j;
}
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. */
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. */
int target_fit(const TargetId& co, const TargetId& card) {
if (co.proc != card.proc) return -1;
for (const auto& f : co.feat) {
bool ok = false;
for (const auto& g : card.feat)
if (g.first == f.first) { ok = g.second == f.second; break; }
if (!ok) return -1;
}
return (int)co.feat.size();
}
} // namespace
bool bundle_code_object(const void* bundle, const std::vector<std::string>& isas, const void** out,
size_t* out_size, std::string* why) {
static const char kMagic[] = "__CLANG_OFFLOAD_BUNDLE__";
const unsigned char* b = static_cast<const unsigned char*>(bundle);
*out = nullptr;
*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 "
"--offload-compress";
return false;
}
if (std::memcmp(b, kMagic, sizeof kMagic - 1) != 0) {
*why = "the fat binary does not start with a clang offload bundle header";
return false;
}
uint64_t n = 0;
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 "<kind>-amdgcn-amd-amdhsa--<target ID>". Both kinds HIP has used,
* "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<Entry> ents;
const unsigned char* p = b + 32;
for (uint64_t i = 0; i < n; ++i) {
uint64_t off = 0, size = 0, tl = 0;
std::memcpy(&off, p, 8);
std::memcpy(&size, p + 8, 8);
std::memcpy(&tl, p + 16, 8);
if (tl > 4096) { *why = "offload bundle entry with an implausible triple"; return false; }
const std::string triple(reinterpret_cast<const char*>(p + 24), (size_t)tl);
p += 24 + tl;
const std::string id = target_id_of(triple);
if (size == 0 || id.empty()) continue;
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. */
for (const std::string& isa : isas) {
const TargetId card = parse_target_id(target_id_of(isa).empty() ? isa : target_id_of(isa));
const Entry* best = nullptr;
int best_fit = -1;
for (const Entry& e : ents) {
const int f = target_fit(e.id, card);
if (f > best_fit) { best_fit = f; best = &e; }
}
if (best) {
*out = b + best->off;
*out_size = (size_t)best->size;
return true;
}
}
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));
*why = "the fat binary has code objects for [" + (have.empty() ? std::string("none") : have) +
"] and this card runs [" + want + "]";
return false;
}
/* ------------------------------------------------------------------ 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. */
namespace {
struct MP {
enum T : uint8_t { Nil, Bool, Int, Str, Arr, Map, Other } t = Nil;
int64_t i = 0;
const char* s = nullptr;
uint32_t n = 0;
std::vector<MP> a; /* array items, or map keys and values interleaved */
const MP* get(const char* key) const {
if (t != Map) return nullptr;
const size_t kl = std::strlen(key);
for (size_t k = 0; k + 1 < a.size(); k += 2)
if (a[k].t == Str && a[k].n == kl && std::memcmp(a[k].s, key, kl) == 0) return &a[k + 1];
return nullptr;
}
std::string str() const { return t == Str ? std::string(s, n) : std::string(); }
};
struct Reader {
const unsigned char* p;
const unsigned char* e;
bool ok = true;
uint64_t be(int nb) {
if (e - p < nb) { ok = false; return 0; }
uint64_t v = 0;
for (int k = 0; k < nb; ++k) v = (v << 8) | p[k];
p += nb;
return v;
}
void str(MP* m, uint32_t n) {
if ((uint64_t)(e - p) < n) { ok = false; return; }
m->t = MP::Str; m->s = reinterpret_cast<const char*>(p); m->n = n; p += n;
}
void items(MP* m, uint32_t n, int depth) {
m->a.resize(n);
for (uint32_t k = 0; k < n && ok; ++k) read(&m->a[k], depth + 1);
}
void read(MP* m, int depth) {
if (!ok || p >= e || depth > 64) { ok = false; return; }
const unsigned char c = *p++;
if (c <= 0x7f) { m->t = MP::Int; m->i = c; return; }
if (c >= 0xe0) { m->t = MP::Int; m->i = (int8_t)c; return; }
if ((c & 0xf0) == 0x80) { m->t = MP::Map; items(m, 2u * (c & 0x0f), depth); return; }
if ((c & 0xf0) == 0x90) { m->t = MP::Arr; items(m, c & 0x0f, depth); return; }
if ((c & 0xe0) == 0xa0) { str(m, c & 0x1f); return; }
switch (c) {
case 0xc0: m->t = MP::Nil; return;
case 0xc2: m->t = MP::Bool; m->i = 0; return;
case 0xc3: m->t = MP::Bool; m->i = 1; return;
case 0xcc: m->t = MP::Int; m->i = (int64_t)be(1); return;
case 0xcd: m->t = MP::Int; m->i = (int64_t)be(2); return;
case 0xce: m->t = MP::Int; m->i = (int64_t)be(4); return;
case 0xcf: m->t = MP::Int; m->i = (int64_t)be(8); return;
case 0xd0: m->t = MP::Int; m->i = (int8_t)be(1); return;
case 0xd1: m->t = MP::Int; m->i = (int16_t)be(2); return;
case 0xd2: m->t = MP::Int; m->i = (int32_t)be(4); return;
case 0xd3: m->t = MP::Int; m->i = (int64_t)be(8); return;
case 0xca: m->t = MP::Other; be(4); return;
case 0xcb: m->t = MP::Other; be(8); return;
case 0xd9: str(m, (uint32_t)be(1)); return;
case 0xda: str(m, (uint32_t)be(2)); return;
case 0xdb: str(m, (uint32_t)be(4)); return;
case 0xc4: case 0xc5: case 0xc6: {
const uint32_t n = (uint32_t)be(c == 0xc4 ? 1 : c == 0xc5 ? 2 : 4);
str(m, n); m->t = MP::Other; return;
}
case 0xdc: m->t = MP::Arr; items(m, (uint32_t)be(2), depth); return;
case 0xdd: m->t = MP::Arr; items(m, (uint32_t)be(4), depth); return;
case 0xde: m->t = MP::Map; items(m, 2u * (uint32_t)be(2), depth); return;
case 0xdf: m->t = MP::Map; items(m, 2u * (uint32_t)be(4), depth); return;
default: ok = false; return; /* ext types: never in code object metadata */
}
}
};
Hidden hidden_kind(const std::string& k) {
if (k.compare(0, 7, "hidden_") != 0) return Hidden::None;
static const struct { const char* n; Hidden h; } kTab[] = {
{ "hidden_none", Hidden::Pad },
{ "hidden_block_count_x", Hidden::BlockCountX },
{ "hidden_block_count_y", Hidden::BlockCountY },
{ "hidden_block_count_z", Hidden::BlockCountZ },
{ "hidden_group_size_x", Hidden::GroupSizeX },
{ "hidden_group_size_y", Hidden::GroupSizeY },
{ "hidden_group_size_z", Hidden::GroupSizeZ },
{ "hidden_remainder_x", Hidden::RemainderX },
{ "hidden_remainder_y", Hidden::RemainderY },
{ "hidden_remainder_z", Hidden::RemainderZ },
{ "hidden_global_offset_x", Hidden::GlobalOffsetX },
{ "hidden_global_offset_y", Hidden::GlobalOffsetY },
{ "hidden_global_offset_z", Hidden::GlobalOffsetZ },
{ "hidden_grid_dims", Hidden::GridDims },
{ "hidden_dynamic_lds_size", Hidden::DynamicLds },
};
for (const auto& t : kTab) if (k == t.n) return t.h;
return Hidden::Unsupported;
}
} // namespace
/* ------------------------------------------------------------------ the metadata note */
bool code_object_kernels(const void* elf, size_t size, std::vector<KernelMeta>* out,
std::string* why) {
out->clear();
const unsigned char* b = static_cast<const unsigned char*>(elf);
if (size < 64 || std::memcmp(b, "\x7f" "ELF", 4) != 0 || b[4] != 2 /* ELFCLASS64 */) {
*why = "not a 64-bit ELF code object";
return false;
}
uint64_t phoff = 0;
uint16_t phentsize = 0, phnum = 0;
std::memcpy(&phoff, b + 32, 8);
std::memcpy(&phentsize, b + 54, 2);
std::memcpy(&phnum, b + 56, 2);
if (phentsize < 56 || phoff + (uint64_t)phentsize * phnum > size) {
*why = "code object program headers run past its end";
return false;
}
for (uint16_t h = 0; h < phnum; ++h) {
const unsigned char* ph = b + phoff + (uint64_t)h * phentsize;
uint32_t type = 0;
uint64_t off = 0, fsz = 0;
std::memcpy(&type, ph, 4);
std::memcpy(&off, ph + 8, 8);
std::memcpy(&fsz, ph + 32, 8);
if (type != 4 /* PT_NOTE */ || off + fsz > size) continue;
const unsigned char* q = b + off;
const unsigned char* qe = q + fsz;
while (qe - q >= 12) {
uint32_t namesz = 0, descsz = 0, ntype = 0;
std::memcpy(&namesz, q, 4);
std::memcpy(&descsz, q + 4, 4);
std::memcpy(&ntype, q + 8, 4);
const unsigned char* name = q + 12;
const unsigned char* desc = name + ((namesz + 3u) & ~3u);
const unsigned char* next = desc + ((descsz + 3u) & ~3u);
if (next > qe) break;
q = next;
if (ntype != 32 /* NT_AMDGPU_METADATA */ || namesz != 7 ||
std::memcmp(name, "AMDGPU", 6) != 0)
continue;
Reader r{ desc, desc + descsz };
MP root;
r.read(&root, 0);
if (!r.ok || root.t != MP::Map) { *why = "malformed AMDGPU metadata"; return false; }
const MP* ks = root.get("amdhsa.kernels");
if (!ks || ks->t != MP::Arr) { *why = "metadata has no amdhsa.kernels"; return false; }
for (const MP& k : ks->a) {
KernelMeta m;
const MP* sym = k.get(".symbol");
if (!sym) continue;
m.symbol = sym->str();
if (const MP* v = k.get(".kernarg_segment_size")) m.kernarg_size = (uint32_t)v->i;
if (const MP* v = k.get(".group_segment_fixed_size")) m.group_size = (uint32_t)v->i;
if (const MP* v = k.get(".private_segment_fixed_size")) m.private_size = (uint32_t)v->i;
if (const MP* v = k.get(".uses_dynamic_stack")) m.dynamic_stack = v->i != 0;
if (const MP* as = k.get(".args"); as && as->t == MP::Arr) {
for (const MP& a : as->a) {
KernelArg ka;
if (const MP* v = a.get(".offset")) ka.offset = (uint32_t)v->i;
if (const MP* v = a.get(".size")) ka.size = (uint32_t)v->i;
if (const MP* v = a.get(".value_kind")) ka.kind = v->str();
ka.hidden = hidden_kind(ka.kind);
m.args.push_back(std::move(ka));
}
}
out->push_back(std::move(m));
}
return true;
}
}
*why = "code object has no AMDGPU metadata note";
return false;
}
} // namespace aql
} // namespace rad
-387
View File
@@ -1,387 +0,0 @@
/* device.h -- the device layer's internal face.
*
* `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.
*
* 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.
*/
#pragma once
#include "rad_abi.h"
#include "rad_device.h"
#include <cstdint>
#include <string>
#include <utility>
#include <vector>
/* 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. */
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. */
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. */
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. */
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. */
extern "C" int rad_memcpy_ranges_async(void* dst, const void* src, int64_t prefix,
const RadCopyRange* ranges, int n, 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. */
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:
*
* 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.
*
* 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.
*/
/* ------------------------------------------------------------------ the backend vtable */
/* One entry per call in rad_device.h. `name` is what device_backend_name() returns. */
struct DeviceBackend {
const char* name;
int (*count)(void);
int (*set)(int device);
int (*props)(int device, RadDeviceProps* out);
int (*enable_peer)(int self, int peer);
void* (*alloc)(int64_t bytes, int kind);
void (*free)(void* p, int kind);
void* (*host_ptr)(void* p);
void* (*device_ptr)(void* p);
int (*stream_create)(RadStream* out, int high_priority);
void (*stream_destroy)(RadStream s);
int (*stream_sync)(RadStream s);
/* `flags`: see rad_event_create_as. A backend with no scope to choose ignores RAD_EVENT_LOCAL. */
int (*event_create)(RadEvent* out, unsigned flags);
void (*event_destroy)(RadEvent e);
int (*event_record)(RadEvent e, RadStream s);
int (*event_wait)(RadStream s, RadEvent e);
int (*event_query)(RadEvent e);
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. */
void (*host_wrote)(void);
int (*memcpy_async)(void* dst, const void* src, int64_t bytes, RadStream s);
int (*memcpy_2d_async)(void* dst, int64_t dpitch, const void* src, int64_t spitch,
int64_t width, int64_t height, RadStream s);
int (*memset_async)(void* dst, int value, int64_t bytes, RadStream s);
int (*memcpy_ranges_async)(void* dst, const void* src, int64_t prefix,
const RadCopyRange* ranges, int n, 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.
*
* `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. */
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`. */
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. */
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.
*
* 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.
*
* 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.
*
* 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.
*
* `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. */
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);
int (*vmem_commit)(void* addr, int64_t bytes);
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. */
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. */
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. */
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. */
int (*peer_access)(int self, int peer);
};
const DeviceBackend* host_backend(void);
/* The current backend's recorded passes; RAD_E_UNSUPPORTED (or null) from one that has none. */
bool tape_supported();
int tape_begin();
int tape_mark();
void tape_pause(bool on);
RadTape tape_end(bool keep);
int tape_len(RadTape t);
int tape_play(RadTape t, int from, int to);
int tape_diff(RadTape a, RadTape b, std::string* why);
void tape_destroy(RadTape t);
int tape_record(RadTape t, int i, int* kind, uint32_t* queue);
int tape_set_overlap(RadTape t, int i, bool on);
/* The current backend's DeviceBackend::peer_access. */
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). */
size_t dev_code_mark();
int dev_code_runs(size_t from, size_t to, int device, std::string* why);
/* The current backend's DeviceBackend::integrated. */
bool dev_integrated(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. */
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. */
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);
/* ------------------------------------------------------------------ elastic memory
* One reserved address range and the record of 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 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.
*
* 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. */
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. */
static bool supported();
static int64_t granularity(); /* 0 when unsupported */
VMem() = default;
~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. */
VMem(VMem&& o) noexcept
: base_(o.base_), size_(o.size_), committed_(o.committed_), ext_(std::move(o.ext_)) {
o.base_ = nullptr;
o.size_ = o.committed_ = 0;
o.ext_.clear();
}
VMem& operator=(VMem&& o) noexcept {
if (this != &o) {
release();
base_ = o.base_;
size_ = o.size_;
committed_ = o.committed_;
ext_ = std::move(o.ext_);
o.base_ = nullptr;
o.size_ = o.committed_ = 0;
o.ext_.clear();
}
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. */
int reserve(int64_t bytes, int64_t align = 0);
void release(); /* decommits whatever is still backed, then frees the VA */
void* base() const { return base_; }
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. */
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. */
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. */
std::vector<std::pair<int64_t, int64_t>> ext_;
/* Adds a newly mapped piece and merges it with whatever it touches. */
void add_extent(int64_t off, int64_t bytes);
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. */
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. */
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. */
const DeviceBackend* aql_backend_if_present(void);
/* Bytes copied to or from pageable host memory so far: every such copy is a host wait. */
int64_t aql_pageable_bytes(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. */
void device_set_error(const char* fmt, ...) __attribute__((format(printf, 1, 2)));
} /* namespace rad */
-228
View File
@@ -1,228 +0,0 @@
/* directio.cpp -- see directio.h for why the page cache is not wanted here. */
#include "directio.h"
#include "../rad_internal.h"
#include <algorithm>
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
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. */
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. */
int64_t pread_some(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) break;
done += r;
}
return done;
}
int pwrite_exact(int fd, const void* src, int64_t bytes, int64_t off) {
int64_t done = 0;
while (done < bytes) {
ssize_t w = ::pwrite(fd, (const uint8_t*)src + done, (size_t)(bytes - done),
(off_t)(off + done));
if (w <= 0) {
if (w < 0 && errno == EINTR) continue;
return RAD_E_IO;
}
done += w;
}
return RAD_OK;
}
} /* namespace */
DirectFile::~DirectFile() { close(); }
int DirectFile::open(const char* path, int flags) {
if (!path || !*path) return RAD_E_INVAL;
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. */
int oflags = want_write ? O_RDWR : O_RDONLY;
if (flags & RAD_DIO_CREATE) oflags |= O_CREAT;
if (flags & RAD_DIO_TRUNC) oflags |= O_TRUNC;
fd_ = ::open(path, oflags | O_DIRECT, 0600);
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. */
if (flags & RAD_DIO_ALLOW_BUFFERED) {
fd_ = ::open(path, oflags, 0600);
direct_ = false;
if (fd_ >= 0)
RAD_WARN("directio: %s does not support O_DIRECT; opened buffered. Reads will go "
"through the page cache, which is a second copy of every byte and evicts "
"the weight pool's own pages.", path);
} else {
RAD_ERR("directio: cannot open %s with O_DIRECT: %s. The tier directory must be on a "
"filesystem that supports it.", path, std::strerror(errno));
return RAD_E_IO;
}
}
if (fd_ < 0) {
RAD_ERR("directio: cannot open %s: %s", path, std::strerror(errno));
return RAD_E_IO;
}
return RAD_OK;
}
void DirectFile::close() {
if (fd_ >= 0) ::close(fd_);
fd_ = -1;
direct_ = false;
std::free(bounce_);
bounce_ = nullptr;
bounce_bytes_ = 0;
}
int64_t DirectFile::size() const {
if (fd_ < 0) return -1;
struct stat st{};
if (::fstat(fd_, &st) != 0) return -1;
return (int64_t)st.st_size;
}
int DirectFile::bounce_ready() {
if (bounce_) return RAD_OK;
void* p = nullptr;
if (posix_memalign(&p, (size_t)alignment(), (size_t)kBounceBytes) != 0 || !p)
return RAD_E_NOMEM;
bounce_ = (uint8_t*)p;
bounce_bytes_ = kBounceBytes;
return RAD_OK;
}
/* ------------------------------------------------------------------ read */
int DirectFile::read_at(void* dst, int64_t off, int64_t bytes) {
if (fd_ < 0) return RAD_E_STATE;
if (!dst || off < 0 || bytes < 0) return RAD_E_INVAL;
if (bytes == 0) return RAD_OK;
const int64_t A = alignment();
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. */
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. */
RAD_TRY(bounce_ready());
const int64_t lo = align_down(off, A);
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);
const int64_t s = std::max(off, base);
const int64_t e = std::min(off + bytes, base + span);
if (e <= s) continue;
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). */
if (got < e - base) return RAD_E_IO;
std::memcpy((uint8_t*)dst + (s - off), bounce_ + (s - base), (size_t)(e - s));
}
return RAD_OK;
}
/* ------------------------------------------------------------------ write */
/* The store is written to as well as read: the SSD prefix-cache tier (core/mem/sstier.cpp)
* publishes blocks, and the SSD weight tier is populated once at load. Both write whole aligned
* slots, so this has the same shape as read_at -- one fast path, and a read-modify-write for
* anything that does not cover a whole block. */
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;
if (bytes == 0) return RAD_OK;
const int64_t A = alignment();
const bool aligned = (off % A) == 0 && (bytes % A) == 0 &&
((uintptr_t)src % (uintptr_t)A) == 0;
if (aligned) return pwrite_exact(fd_, src, bytes, off);
RAD_TRY(bounce_ready());
const int64_t old_size = size();
if (old_size < 0) return RAD_E_IO;
const int64_t lo = align_down(off, A);
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. */
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));
const int64_t s = std::max(off, base);
const int64_t e = std::min(off + bytes, base + span);
if (e > s)
std::memcpy(bounce_ + (s - base), (const uint8_t*)src + (s - off), (size_t)(e - s));
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. */
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;
}
} /* namespace rad */
-80
View File
@@ -1,80 +0,0 @@
/* directio.h -- the file tier's reader.
*
* 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.
*
* 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.
*/
#pragma once
#include <cstdint>
namespace rad {
enum {
RAD_DIO_READ = 1,
RAD_DIO_WRITE = 2, /* implies read: a partial block is a read-modify-write */
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 and the prefix cache are
* sized in gigabytes and read in megabyte runs; a silent buffered fallback turns both into a
* page-cache pump that is three times slower and looks like nothing at all in a profile. An
* operator who pointed --prefix-cache-dir at tmpfs wants to be told, not accommodated. The flag is
* for tests, which have to run on whatever /tmp happens to be. */
RAD_DIO_ALLOW_BUFFERED = 16,
};
class DirectFile {
public:
DirectFile() = default;
~DirectFile();
DirectFile(const DirectFile&) = delete;
DirectFile& operator=(const DirectFile&) = delete;
/* RAD_OK, or a negative RAD_E_*. `flags` is the RAD_DIO_* set above. */
int open(const char* path, int flags);
void close();
bool is_open() const { return fd_ >= 0; }
/* Whether the open actually got O_DIRECT. False only under RAD_DIO_ALLOW_BUFFERED. */
bool direct() const { return direct_; }
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. */
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. */
static constexpr int64_t alignment() { return 4096; }
private:
int bounce_ready();
int fd_ = -1;
bool direct_ = false;
uint8_t* bounce_ = nullptr;
int64_t bounce_bytes_ = 0;
};
} /* namespace rad */
-497
View File
@@ -1,497 +0,0 @@
/* 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 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.
*/
#include "device.h"
#include "../rad_internal.h"
#include <algorithm>
#include <cstdarg>
#include <cstdio>
#include <cstring>
#include <atomic>
#include <cstdlib>
#include <mutex>
#include <string>
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. */
static thread_local std::string t_last_error;
void device_set_error(const char* f, ...) {
char buf[1024];
va_list ap;
va_start(ap, 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. */
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). */
static std::string device_inventory(const DeviceBackend* b) {
std::string s;
const int n = b->count();
for (int i = 0; i < n; ++i) {
RadDeviceProps p{};
if (b->props(i, &p) < 0) continue;
s += fmt("%s%d:%s", i ? " " : "", i, p.arch);
}
return s;
}
static const DeviceBackend* select_backend() {
#if defined(RAD_HAVE_HIP) && RAD_HAVE_HIP
if (const DeviceBackend* b = aql_backend_if_present()) {
RAD_INFO("device: AQL backend, %d device(s) [%s]", b->count(),
device_inventory(b).c_str());
return b;
}
RAD_INFO("device: built with HIP but no device is visible -- using the host backend");
#endif
const DeviceBackend* b = host_backend();
RAD_INFO("device: host backend, %d device(s) [%s]", b->count(), device_inventory(b).c_str());
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. */
static const DeviceBackend* g_backend = nullptr;
static std::once_flag g_once;
static inline const DeviceBackend* dev() {
std::call_once(g_once, [] { g_backend = select_backend(); });
return g_backend;
}
bool device_is_host() { return std::strcmp(dev()->name, "host") == 0; }
const char* device_backend_name() { return dev()->name; }
} /* namespace rad */
/* ------------------------------------------------------------------ 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.
*
* 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.
*
* 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 every allocation of at least N bytes as it happens. That is the
* instrument; the counters are the summary. */
namespace rad {
namespace {
struct Ledger {
std::atomic<int64_t> bytes{0};
std::atomic<int64_t> count{0};
};
Ledger g_ledger[4]; /* indexed by RAD_MEM_*; see rad_dev_alloc below for the bound check */
/* 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. */
std::atomic<int64_t> g_live_events{0};
int64_t trace_floor() {
static const int64_t v = [] {
const char* e = std::getenv("RADIANCE_TRACE_ALLOC");
if (!e || !*e) return (int64_t)-1;
const long long x = std::atoll(e);
return x >= 0 ? (int64_t)x : (int64_t)0;
}();
return v;
}
const char* kind_name(int kind) {
switch (kind) {
case RAD_MEM_DEVICE: return "device";
case RAD_MEM_HOST: return "host";
case RAD_MEM_HOST_PINNED: return "host-pinned";
case RAD_MEM_HOST_MAPPED: return "host-mapped";
default: return "?";
}
}
} /* 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 (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); }
/* ------------------------------------------------------------------ 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. */
namespace {
std::atomic<int64_t> g_vmem_committed{0};
} /* namespace */
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. */
bool VMem::supported() { return dev()->vmem_reserve != nullptr && VMem::granularity() > 0; }
int64_t VMem::granularity() {
if (!dev()->vmem_granularity) return 0;
const int64_t g = dev()->vmem_granularity();
return g > 0 ? g : 0;
}
int VMem::reserve(int64_t bytes, int64_t align) {
release();
if (bytes <= 0) return RAD_E_INVAL;
if (!supported()) {
device_set_error("elastic memory: the %s backend has none", device_backend_name());
return RAD_E_UNSUPPORTED;
}
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. */
const int64_t want = align_up(bytes, g);
void* p = dev()->vmem_reserve(want, align);
if (!p) return RAD_E_NOMEM;
base_ = p;
size_ = want;
committed_ = 0;
ext_.clear();
return RAD_OK;
}
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. */
const int64_t g = granularity();
for (const auto& e : ext_) {
if (dev()->vmem_decommit && g > 0)
for (int64_t o = e.first; o < e.first + e.second; o += g)
(void)dev()->vmem_decommit((char*)base_ + o, g);
g_vmem_committed.fetch_sub(e.second, std::memory_order_relaxed);
}
if (dev()->vmem_release) dev()->vmem_release(base_, size_);
base_ = nullptr;
size_ = 0;
committed_ = 0;
ext_.clear();
}
bool VMem::is_committed(int64_t off, int64_t bytes) const {
if (bytes <= 0) return true;
if (off < 0 || off + bytes > size_) return false;
for (const auto& e : ext_)
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.
*
* 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. */
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. */
const int64_t lo = (off < 0 ? 0 : off / g * g);
int64_t hi = align_up(off + bytes, g);
if (hi > size_) hi = size_;
if (lo >= hi) return RAD_OK;
std::vector<int64_t> want;
want.reserve((size_t)((hi - lo) / g));
for (int64_t o = lo; o < hi; o += g)
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. */
int rc = RAD_OK;
size_t took = 0;
for (; took < want.size(); ++took) {
rc = dev()->vmem_commit((char*)base_ + want[took], g);
if (rc < 0) break;
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. */
int prc = RAD_OK;
if (took > 0 && dev()->vmem_protect) {
for (const auto& e : ext_) {
if (e.first + e.second <= lo || e.first >= hi) continue;
prc = dev()->vmem_protect((char*)base_ + e.first, e.second);
if (prc < 0) break;
}
}
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. */
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);
}
return prc;
}
return rc;
}
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. */
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. */
std::vector<int64_t> drop;
for (int64_t o = lo; o < hi; o += g)
if (is_committed(o, g)) drop.push_back(o);
for (const int64_t o : drop) {
const int rc = dev()->vmem_decommit((char*)base_ + o, g);
if (rc < 0) return rc;
drop_extent(o, g);
}
return RAD_OK;
}
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. */
size_t i = 0;
while (i < ext_.size() && ext_[i].first < off) ++i;
ext_.insert(ext_.begin() + (long)i, { off, bytes });
for (size_t j = 0; j + 1 < ext_.size();) {
if (ext_[j].first + ext_[j].second >= ext_[j + 1].first) {
const int64_t end = std::max(ext_[j].first + ext_[j].second,
ext_[j + 1].first + ext_[j + 1].second);
ext_[j].second = end - ext_[j].first;
ext_.erase(ext_.begin() + (long)j + 1);
} else {
++j;
}
}
}
/* 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. */
void VMem::drop_extent(int64_t off, int64_t bytes) {
committed_ -= bytes;
g_vmem_committed.fetch_sub(bytes, std::memory_order_relaxed);
for (size_t i = 0; i < ext_.size(); ++i) {
const int64_t es = ext_[i].first, ee = es + ext_[i].second;
if (off < es || off + bytes > ee) continue;
ext_.erase(ext_.begin() + (long)i);
if (off + bytes < ee) ext_.insert(ext_.begin() + (long)i, { off + bytes, ee - off - bytes });
if (es < off) ext_.insert(ext_.begin() + (long)i, { es, off - es });
return;
}
}
} /* namespace rad */
/* ------------------------------------------------------------------ the ABI surface */
using rad::dev;
extern "C" {
int rad_dev_count(void) { return dev()->count(); }
int rad_dev_set(int device) { return dev()->set(device); }
int rad_dev_props(int device, RadDeviceProps* o) { return dev()->props(device, o); }
int rad_dev_enable_peer(int self, int peer) { return dev()->enable_peer(self, peer); }
void* rad_dev_alloc(int64_t bytes, int kind) {
void* p = dev()->alloc(bytes, kind);
if (p && kind >= 0 && kind < 4) {
rad::g_ledger[kind].bytes.fetch_add(bytes, std::memory_order_relaxed);
rad::g_ledger[kind].count.fetch_add(1, std::memory_order_relaxed);
const int64_t floor_ = rad::trace_floor();
if (floor_ >= 0 && bytes >= floor_)
RAD_INFO("alloc %s %s (%lld live in %lld allocations)", rad::kind_name(kind),
rad::humanb(bytes).c_str(),
(long long)rad::g_ledger[kind].bytes.load(std::memory_order_relaxed),
(long long)rad::g_ledger[kind].count.load(std::memory_order_relaxed));
}
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. */
dev()->free(p, kind);
}
void* rad_dev_host_ptr(void* p) { return dev()->host_ptr(p); }
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); }
} /* extern "C" */
namespace rad {
bool tape_supported() { return dev()->tape_begin != nullptr; }
int dev_vram_used(int device, int64_t* out) {
return dev()->vram_used ? dev()->vram_used(device, out) : RAD_E_UNSUPPORTED;
}
int tape_begin() { return dev()->tape_begin ? dev()->tape_begin() : RAD_E_UNSUPPORTED; }
int tape_mark() { return dev()->tape_mark ? dev()->tape_mark() : RAD_E_UNSUPPORTED; }
void tape_pause(bool on) { if (dev()->tape_pause) dev()->tape_pause(on ? 1 : 0); }
RadTape tape_end(bool keep) { return dev()->tape_end ? dev()->tape_end(keep ? 1 : 0) : nullptr; }
int tape_len(RadTape t) { return dev()->tape_len ? dev()->tape_len(t) : RAD_E_UNSUPPORTED; }
int tape_play(RadTape t, int from, int to) {
return dev()->tape_play ? dev()->tape_play(t, from, to) : RAD_E_UNSUPPORTED;
}
int tape_diff(RadTape a, RadTape b, std::string* why) {
if (!dev()->tape_diff) return RAD_E_UNSUPPORTED;
char buf[512];
buf[0] = 0;
const int at = dev()->tape_diff(a, b, buf, (int)sizeof buf);
if (why) *why = buf;
return at;
}
void tape_destroy(RadTape t) { if (dev()->tape_destroy) dev()->tape_destroy(t); }
int tape_record(RadTape t, int i, int* kind, uint32_t* queue) {
return dev()->tape_record ? dev()->tape_record(t, i, kind, queue) : RAD_E_UNSUPPORTED;
}
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; }
int dev_peer_access(int self, int peer) {
if (self == peer) return 1;
return dev()->peer_access ? dev()->peer_access(self, peer) : 1;
}
size_t dev_code_mark() { return dev()->code_mark ? dev()->code_mark() : 0; }
int dev_code_runs(size_t from, size_t to, int device, std::string* why) {
if (!dev()->code_runs || from >= to) return 1;
char buf[1024];
buf[0] = 0;
const int r = dev()->code_runs(from, to, device, buf, (int)sizeof buf);
if (why) *why = buf;
return r;
}
} /* namespace rad */
extern "C" {
int rad_event_create_as(RadEvent* out, unsigned flags) {
const int s = dev()->event_create(out, flags);
if (s >= 0 && out && *out) rad::g_live_events.fetch_add(1, std::memory_order_relaxed);
return s;
}
int rad_event_create(RadEvent* out) { return rad_event_create_as(out, RAD_EVENT_HOST_WAIT); }
int rad_event_create_local(RadEvent* out) { return rad_event_create_as(out, RAD_EVENT_LOCAL); }
void rad_event_destroy(RadEvent e) {
if (!e) return;
rad::g_live_events.fetch_sub(1, std::memory_order_relaxed);
dev()->event_destroy(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); }
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);
}
int rad_memcpy_async(void* dst, const void* src, int64_t bytes, RadStream s) {
return dev()->memcpy_async(dst, src, bytes, s);
}
int rad_memcpy_2d_async(void* dst, int64_t dpitch, const void* src, int64_t spitch,
int64_t width, int64_t height, RadStream s) {
return dev()->memcpy_2d_async(dst, dpitch, src, spitch, width, height, s);
}
int rad_memset_async(void* dst, int value, int64_t bytes, RadStream s) {
return dev()->memset_async(dst, value, bytes, s);
}
int rad_memcpy_ranges_async(void* dst, const void* src, int64_t prefix,
const RadCopyRange* ranges, int n, RadStream s) {
return dev()->memcpy_ranges_async(dst, src, prefix, ranges, n, s);
}
/* 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. */
const char* rad_dev_last_error(void) {
static thread_local std::string drained;
drained.swap(rad::t_last_error);
rad::t_last_error.clear();
return drained.c_str();
}
} /* extern "C" */
-396
View File
@@ -1,396 +0,0 @@
/* 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.
*
* 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.
*
* 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.
*/
#include "device.h"
#if defined(RAD_HAVE_HIP) && RAD_HAVE_HIP
#include "../rad_internal.h"
#include <hip/hip_runtime.h>
#include <atomic>
#include <cstdint>
#include <cstdlib>
#include <mutex>
#include <new>
#include <vector>
#include <cstring>
#include <cstdio>
#include <strings.h>
#include <fcntl.h>
#include <unistd.h>
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(). */
int hip_fail(hipError_t e, const char* who) {
device_set_error("%s: %s (%s)", who, hipGetErrorString(e), hipGetErrorName(e));
switch (e) {
case hipErrorOutOfMemory: return RAD_E_NOMEM;
case hipErrorInvalidValue:
case hipErrorInvalidDevice:
case hipErrorInvalidHandle: return RAD_E_INVAL;
case hipErrorNotSupported: return RAD_E_UNSUPPORTED;
default: return RAD_E_DEVICE;
}
}
#define HIP_TRY(call) \
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. */
void hip_note(hipError_t e, const char* who) {
if (e != hipSuccess) RAD_WARN("device: %s: %s", who, hipGetErrorString(e));
}
#define HIP_NOTE(call) hip_note((call), #call)
/* ------------------------------------------------------------------ devices */
int d_count(void) {
int n = 0;
if (hipGetDeviceCount(&n) != hipSuccess) return 0;
return n;
}
int d_set(int device) {
HIP_TRY(hipSetDevice(device));
return RAD_OK;
}
/* ------------------------------------------------------------------ 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 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. */
constexpr int kMaxVramNodes = 64;
std::atomic<int> g_vram_used_fd[kMaxVramNodes] = {}; /* 0: not opened; else the fd plus one */
static int64_t sysfs_vram_free(int device, int64_t total) {
char bus[64] = {0};
if (hipDeviceGetPCIBusId(bus, (int)sizeof bus, device) != hipSuccess || !bus[0]) return -1;
const size_t buslen = std::strlen(bus);
for (int c = 0; c < 64; ++c) {
char path[160];
std::snprintf(path, sizeof path, "/sys/class/drm/card%d/device/uevent", c);
FILE* f = std::fopen(path, "r");
if (!f) continue;
bool match = false;
char line[256];
while (std::fgets(line, (int)sizeof line, f))
if (!std::strncmp(line, "PCI_SLOT_NAME=", 14) &&
!strncasecmp(line + 14, bus, buslen)) { match = true; break; }
std::fclose(f);
if (!match) continue;
auto read_u64 = [&](const char* leaf, long long* out_v) {
char p[160];
std::snprintf(p, sizeof p, "/sys/class/drm/card%d/device/%s", c, leaf);
FILE* g = std::fopen(p, "r");
if (!g) return false;
const bool ok = std::fscanf(g, "%lld", out_v) == 1 && *out_v >= 0;
std::fclose(g);
return ok;
};
long long tot = 0, used = 0;
if (!read_u64("mem_info_vram_total", &tot) || !read_u64("mem_info_vram_used", &used))
return -1;
if (tot != (long long)total) return -1; /* different accountings; do not mix them */
if (device >= 0 && device < kMaxVramNodes &&
g_vram_used_fd[device].load(std::memory_order_acquire) == 0) {
char p[160];
std::snprintf(p, sizeof p, "/sys/class/drm/card%d/device/mem_info_vram_used", c);
const int fd = ::open(p, O_RDONLY | O_CLOEXEC);
int none = 0;
if (fd >= 0 && !g_vram_used_fd[device].compare_exchange_strong(none, fd + 1))
::close(fd);
}
return total - (int64_t)used;
}
return -1;
}
/* A sysfs attribute is regenerated by a read at offset 0, so the descriptor is read with pread and
* never moved. */
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;
if (fd < 0) return RAD_E_UNSUPPORTED;
char buf[32];
const ssize_t n = ::pread(fd, buf, sizeof buf - 1, 0);
if (n <= 0) return RAD_E_IO;
buf[n] = '\0';
char* end = nullptr;
const long long v = std::strtoll(buf, &end, 10);
if (end == buf || v < 0) return RAD_E_IO;
*out = (int64_t)v;
return RAD_OK;
}
int d_integrated(int device) {
int v = 0;
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. */
static int64_t host_mem_available() {
FILE* f = std::fopen("/proc/meminfo", "r");
if (!f) return -1;
char line[256];
long long kb = -1;
while (std::fgets(line, (int)sizeof line, f))
if (std::sscanf(line, "MemAvailable: %lld kB", &kb) == 1) break;
std::fclose(f);
return kb >= 0 ? (int64_t)kb * 1024 : -1;
}
int d_props(int device, RadDeviceProps* out) {
if (!out) return RAD_E_INVAL;
hipDeviceProp_t p{};
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. */
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. */
if (char* c = std::strchr(out->arch, ':')) *c = '\0';
out->device_id = device;
out->n_cu = p.multiProcessorCount;
out->warp_size = p.warpSize;
out->vram_bytes = (int64_t)p.totalGlobalMem;
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. */
int prev = 0;
bool moved = false;
if (hipGetDevice(&prev) == hipSuccess && prev != device &&
hipSetDevice(device) == hipSuccess)
moved = true;
size_t freeb = 0, totalb = 0;
if (hipMemGetInfo(&freeb, &totalb) == hipSuccess) {
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. */
{
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. */
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. */
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. */
int n = d_count();
for (int i = 0; i < n && !out->supports_p2p; ++i) {
if (i == device) continue;
int can = 0;
if (hipDeviceCanAccessPeer(&can, device, i) == hipSuccess && can) out->supports_p2p = 1;
}
return RAD_OK;
}
int d_peer_access(int self, int peer) {
int can = 0;
HIP_TRY(hipDeviceCanAccessPeer(&can, self, peer));
return can ? 1 : 0;
}
int d_enable_peer(int self, int peer) {
if (self == peer) return RAD_OK;
int can = 0;
HIP_TRY(hipDeviceCanAccessPeer(&can, self, peer));
if (!can) {
device_set_error("rad_dev_enable_peer(%d, %d): the driver reports no peer path; "
"a kernel library's peer-to-peer all-reduce needs one (spec §9)", self,
peer);
return RAD_E_UNSUPPORTED;
}
int prev = 0;
HIP_TRY(hipGetDevice(&prev));
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. */
if (e != hipSuccess && e != hipErrorPeerAccessAlreadyEnabled)
return hip_fail(e, "hipDeviceEnablePeerAccess");
return RAD_OK;
}
/* ------------------------------------------------------------------ memory */
void* d_alloc(int64_t bytes, int kind) {
if (bytes <= 0) {
device_set_error("rad_dev_alloc(%lld): size must be positive", (long long)bytes);
return nullptr;
}
void* p = nullptr;
hipError_t e = hipSuccess;
switch (kind) {
case RAD_MEM_DEVICE:
e = hipMalloc(&p, (size_t)bytes);
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"). */
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. */
if (posix_memalign(&p, 4096, (size_t)((bytes + 4095) / 4096 * 4096)) != 0) p = nullptr;
if (!p) e = hipErrorOutOfMemory;
break;
default:
device_set_error("rad_dev_alloc: unknown memory kind %d", kind);
return nullptr;
}
if (e != hipSuccess || !p) {
hip_fail(e == hipSuccess ? hipErrorOutOfMemory : e, "rad_dev_alloc");
return nullptr;
}
return p;
}
void d_free(void* p, int kind) {
if (!p) return;
switch (kind) {
case RAD_MEM_DEVICE: HIP_NOTE(hipFree(p)); break;
case RAD_MEM_HOST: std::free(p); break;
case RAD_MEM_HOST_PINNED:
case RAD_MEM_HOST_MAPPED:
RAD_WARN("rad_dev_free(%p): pinned host memory is the AQL backend's; leaked", p);
break;
default:
RAD_WARN("rad_dev_free(%p): unknown memory kind %d; leaked rather than freed with the "
"wrong allocator", p, kind);
break;
}
}
void* d_host_ptr(void* p) {
if (!p) return nullptr;
hipPointerAttribute_t a{};
if (hipPointerGetAttributes(&a, p) != hipSuccess) return nullptr;
return a.hostPointer;
}
void* d_device_ptr(void* p) {
if (!p) return nullptr;
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. */
void* d = nullptr;
if (hipHostGetDevicePointer(&d, p, 0) == hipSuccess) return d;
return nullptr;
}
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. */
nullptr, nullptr, nullptr,
nullptr, nullptr, nullptr, nullptr,
nullptr, nullptr, nullptr,
nullptr,
nullptr, nullptr, nullptr, nullptr,
/* Recorded passes: likewise the AQL backend's. */
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"). */
nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
d_vram_used,
/* Plugin device code: the AQL backend's, which owns the fat-binary registrations. */
nullptr, nullptr,
d_integrated,
d_peer_access,
};
} /* namespace */
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. */
RAD_DEBUG("device: hipGetDeviceCount -> %s, %d device(s)", hipGetErrorName(e), n);
return nullptr;
}
return &g_hip;
}
} /* namespace rad */
#endif /* RAD_HAVE_HIP */
-793
View File
@@ -1,793 +0,0 @@
/* 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.
*
* 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 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.
*/
#include "device.h"
#include "../rad_internal.h"
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstdlib>
#include <cstring>
#include <mutex>
#include <thread>
#include <unordered_map>
#include <vector>
#include <sys/mman.h>
#include <unistd.h>
namespace rad {
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. */
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. */
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. */
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.
*
* `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. */
struct HostEvent {
std::mutex m;
std::condition_variable cv;
uint64_t recorded = 0;
uint64_t completed = 0;
Clock::time_point stamp{}; /* when the worker reached the most recent record */
std::atomic<int> refs{1};
bool host = false; /* RAD_EVENT_HOST_WAIT */
};
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. */
void event_release(HostEvent* e) {
if (e->refs.fetch_sub(1, std::memory_order_acq_rel) == 1) delete e;
}
/* ------------------------------------------------------------------ tasks */
struct Task {
enum Kind : uint8_t { Copy, Copy2D, Ranges, Memset, Record, Wait, Stop };
Kind kind = Stop;
void* dst = nullptr;
const void* src = nullptr;
int64_t a = 0, b = 0, c = 0, d = 0;
const void* aux = nullptr;
HostEvent* ev = nullptr;
uint64_t seq = 0;
};
/* ------------------------------------------------------------------ streams */
struct HostStream {
std::mutex m;
std::condition_variable cv_work; /* worker waits on this for a task or a stop */
std::condition_variable cv_room; /* producers wait on this when the ring is full */
std::condition_variable cv_done; /* rad_stream_sync waits on this */
std::vector<Task> ring;
size_t head = 0; /* next slot to pop */
size_t tail = 0; /* next slot to push */
size_t count = 0;
uint64_t submitted = 0; /* tasks ever pushed */
uint64_t retired = 0; /* tasks ever finished executing */
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. */
int stream_push(HostStream* s, const Task& t) {
std::unique_lock<std::mutex> lk(s->m);
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();
++s->count;
++s->submitted;
lk.unlock();
s->cv_work.notify_one();
return RAD_OK;
}
void stream_run(HostStream* s) {
for (;;) {
Task t;
{
std::unique_lock<std::mutex> lk(s->m);
s->cv_work.wait(lk, [s] { return s->count > 0; });
t = s->ring[s->head];
s->head = (s->head + 1) % s->ring.size();
--s->count;
}
s->cv_room.notify_one();
bool done = false;
switch (t.kind) {
case Task::Copy:
std::memcpy(t.dst, t.src, (size_t)t.a);
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. */
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);
break;
case Task::Ranges: {
/* a = prefix bytes, b = range count; the list is read now, as the device's is. */
std::memcpy(t.dst, t.src, (size_t)t.a);
const RadCopyRange* r = (const RadCopyRange*)t.aux;
for (int64_t i = 0; i < t.b; ++i)
std::memcpy((uint8_t*)t.dst + r[i].dst, (const uint8_t*)t.src + r[i].src,
(size_t)r[i].bytes);
break;
}
case Task::Memset:
std::memset(t.dst, (int)t.a, (size_t)t.b);
break;
case Task::Record: {
std::lock_guard<std::mutex> lk(t.ev->m);
if (t.seq > t.ev->completed) {
t.ev->completed = t.seq;
t.ev->stamp = Clock::now();
}
t.ev->cv.notify_all();
break;
}
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. */
std::unique_lock<std::mutex> lk(t.ev->m);
t.ev->cv.wait(lk, [&t] { return t.ev->completed >= t.seq; });
break;
}
case Task::Stop:
done = true;
break;
}
/* After the task's lock has gone out of scope: this may be the last reference. */
if (t.ev) event_release(t.ev);
{
std::lock_guard<std::mutex> lk(s->m);
++s->retired;
}
s->cv_done.notify_all();
if (done) return;
}
}
/* ------------------------------------------------------------------ allocation bookkeeping */
struct AllocRec {
int64_t bytes = 0;
int kind = 0;
int device = 0;
};
std::mutex& alloc_mutex() { static std::mutex m; return m; }
std::unordered_map<void*, AllocRec>& alloc_table() {
static std::unordered_map<void*, AllocRec> t;
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). */
std::atomic<int64_t> 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. */
void alloc_note(void* p, int64_t bytes, int kind, int device) {
std::lock_guard<std::mutex> lk(alloc_mutex());
alloc_table()[p] = AllocRec{bytes, kind, device};
}
bool alloc_take(void* p, AllocRec* out) {
std::lock_guard<std::mutex> 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) {
std::lock_guard<std::mutex> lk(alloc_mutex());
auto it = alloc_table().find(p);
if (it == alloc_table().end()) return false;
*out = it->second;
return true;
}
/* ------------------------------------------------------------------ devices */
int64_t env_i64(const char* key, int64_t dflt) {
const char* v = std::getenv(key);
if (!v || !*v) return dflt;
char* end = nullptr;
long long n = std::strtoll(v, &end, 10);
if (end == v || n < 0) {
RAD_WARN("%s=\"%s\" is not a non-negative integer; using %lld", key, v, (long long)dflt);
return dflt;
}
return (int64_t)n;
}
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). */
static int n = [] {
int64_t v = env_i64("RADIANCE_HOST_DEVICES", 1);
if (v < 1) v = 1;
if (v > kMaxFakeDevices) {
RAD_WARN("RADIANCE_HOST_DEVICES=%lld clamped to %d", (long long)v, kMaxFakeDevices);
v = kMaxFakeDevices;
}
if (v > 1) RAD_INFO("device: host backend presenting %lld fake devices", (long long)v);
return (int)v;
}();
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. */
thread_local int t_device = 0;
int64_t physical_ram() {
long pages = sysconf(_SC_PHYS_PAGES), page = sysconf(_SC_PAGESIZE);
if (pages <= 0 || page <= 0) return 8ll << 30;
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. */
int64_t host_vram_bytes() {
int64_t mib = env_i64("RADIANCE_HOST_VRAM_MIB", 0);
if (mib > 0) return mib << 20;
return (physical_ram() / 2) / host_count();
}
const char* cpu_model() {
static std::string s = [] {
std::string out = "host cpu";
FILE* f = std::fopen("/proc/cpuinfo", "r");
if (!f) return out;
char line[512];
while (std::fgets(line, sizeof line, f)) {
if (std::strncmp(line, "model name", 10) != 0) continue;
const char* c = std::strchr(line, ':');
if (!c) break;
++c;
while (*c == ' ' || *c == '\t') ++c;
out.assign(c);
while (!out.empty() && (out.back() == '\n' || out.back() == ' ')) out.pop_back();
break;
}
std::fclose(f);
return out;
}();
return s.c_str();
}
/* ------------------------------------------------------------------ the fourteen calls */
int h_count(void) { return host_count(); }
int h_set(int device) {
if (device < 0 || device >= host_count()) {
device_set_error("rad_dev_set(%d): host backend has %d device(s)", device, host_count());
return RAD_E_INVAL;
}
t_device = device;
return RAD_OK;
}
int h_props(int device, RadDeviceProps* out) {
if (!out) return RAD_E_INVAL;
if (device < 0 || device >= host_count()) {
device_set_error("rad_dev_props(%d): host backend has %d device(s)", device, host_count());
return RAD_E_INVAL;
}
std::memset(out, 0, sizeof *out);
snprintf(out->name, sizeof out->name, "%s", cpu_model());
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. */
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. */
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. */
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. */
out->supports_p2p = 1;
out->is_host_backend = 1;
return RAD_OK;
}
int h_enable_peer(int self, int peer) {
if (self < 0 || self >= host_count() || peer < 0 || peer >= host_count()) {
device_set_error("rad_dev_enable_peer(%d, %d): host backend has %d device(s)",
self, peer, host_count());
return RAD_E_INVAL;
}
return RAD_OK; /* one address space; nothing to enable */
}
void* h_alloc(int64_t bytes, int kind) {
if (bytes <= 0) {
device_set_error("rad_dev_alloc(%lld): size must be positive", (long long)bytes);
return nullptr;
}
if (kind < RAD_MEM_DEVICE || kind > RAD_MEM_HOST_MAPPED) {
device_set_error("rad_dev_alloc: unknown memory kind %d", 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. */
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);
return nullptr;
}
int dev = t_device;
alloc_note(p, bytes, kind, dev);
if (kind == RAD_MEM_DEVICE) g_used[dev].fetch_add(bytes, std::memory_order_relaxed);
return p;
}
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. */
RAD_WARN("rad_dev_free(%p, kind=%d): pointer was not allocated by the device layer",
p, kind);
return;
}
if (r.kind != kind)
RAD_WARN("rad_dev_free(%p): freed as kind %d, allocated as kind %d", p, kind, r.kind);
if (r.kind == RAD_MEM_DEVICE) g_used[r.device].fetch_sub(r.bytes, std::memory_order_relaxed);
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. */
void* h_host_ptr(void* p) {
if (!p) return nullptr;
AllocRec r;
return alloc_find(p, &r) ? p : nullptr;
}
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. */
(void)high_priority;
auto* s = new (std::nothrow) HostStream();
if (!s) { device_set_error("rad_stream_create: out of memory"); return RAD_E_NOMEM; }
s->ring.resize(kQueueDepth);
s->worker = std::thread(stream_run, s);
*out = (RadStream)s;
return RAD_OK;
}
void h_stream_destroy(RadStream st) {
if (!st) return;
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. */
stream_push(s, t);
if (s->worker.joinable()) s->worker.join();
delete s;
}
int h_stream_sync(RadStream st) {
if (!st) {
device_set_error("rad_stream_sync: null stream");
return RAD_E_INVAL;
}
auto* s = (HostStream*)st;
std::unique_lock<std::mutex> 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. */
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. */
int h_event_create(RadEvent* out, unsigned flags) {
if (!out) return RAD_E_INVAL;
auto* e = new (std::nothrow) HostEvent();
if (!e) { device_set_error("rad_event_create: out of memory"); return RAD_E_NOMEM; }
e->host = (flags & RAD_EVENT_HOST_WAIT) != 0;
*out = (RadEvent)e;
return RAD_OK;
}
/* Drops the handle. A record or wait still queued keeps the event alive until the worker is past
* it -- see HostEvent. */
void h_event_destroy(RadEvent ev) { if (ev) event_release((HostEvent*)ev); }
int h_event_record(RadEvent ev, RadStream st) {
if (!ev || !st) {
device_set_error("rad_event_record: null %s", ev ? "stream" : "event");
return RAD_E_INVAL;
}
auto* e = (HostEvent*)ev;
uint64_t seq;
{
std::lock_guard<std::mutex> lk(e->m);
seq = ++e->recorded; /* pending from this instant, on the host, before the push */
}
Task t;
t.kind = Task::Record;
t.ev = e;
t.seq = seq;
event_retain(e);
return stream_push((HostStream*)st, t);
}
int h_event_wait(RadStream st, RadEvent ev) {
if (!ev || !st) {
device_set_error("rad_event_wait: null %s", ev ? "stream" : "event");
return RAD_E_INVAL;
}
auto* e = (HostEvent*)ev;
uint64_t target;
{
std::lock_guard<std::mutex> 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. */
if (target == 0) return RAD_OK;
Task t;
t.kind = Task::Wait;
t.ev = e;
t.seq = target;
event_retain(e);
return stream_push((HostStream*)st, t);
}
int h_event_query(RadEvent ev) {
if (!ev) return RAD_E_INVAL;
auto* e = (HostEvent*)ev;
std::lock_guard<std::mutex> lk(e->m);
return e->completed >= e->recorded ? 1 : 0;
}
/* Host kernels read host memory directly, so there is nothing to make visible. */
void h_host_wrote(void) {}
int h_event_sync(RadEvent ev) {
if (!ev) return RAD_E_INVAL;
auto* e = (HostEvent*)ev;
if (!e->host) {
device_set_error("rad_event_sync: the event was made without RAD_EVENT_HOST_WAIT");
return RAD_E_INVAL;
}
std::unique_lock<std::mutex> lk(e->m);
const uint64_t target = e->recorded;
e->cv.wait(lk, [e, target] { return e->completed >= target; });
return RAD_OK;
}
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;
Clock::time_point ta, tb;
{
std::lock_guard<std::mutex> lk(ea->m);
if (ea->recorded == 0 || ea->completed < ea->recorded) return RAD_E_STATE;
ta = ea->stamp;
}
{
std::lock_guard<std::mutex> lk(eb->m);
if (eb->recorded == 0 || eb->completed < eb->recorded) return RAD_E_STATE;
tb = eb->stamp;
}
*out = std::chrono::duration<float, std::milli>(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. */
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, "
"create one with rad_stream_create", who);
return RAD_E_INVAL;
}
int h_memcpy_async(void* dst, const void* src, int64_t bytes, RadStream st) {
RAD_TRY(check_stream(st, "rad_memcpy_async"));
if (bytes == 0) return RAD_OK;
if (!dst || !src || bytes < 0) {
device_set_error("rad_memcpy_async(%p <- %p, %lld): invalid argument",
dst, src, (long long)bytes);
return RAD_E_INVAL;
}
Task t;
t.kind = Task::Copy;
t.dst = dst;
t.src = src;
t.a = bytes;
return stream_push((HostStream*)st, t);
}
int h_memcpy_2d_async(void* dst, int64_t dpitch, const void* src, int64_t spitch,
int64_t width, int64_t height, RadStream st) {
RAD_TRY(check_stream(st, "rad_memcpy_2d_async"));
if (width == 0 || height == 0) return RAD_OK;
if (!dst || !src || width < 0 || height < 0 || dpitch < width || spitch < width) {
device_set_error("rad_memcpy_2d_async: w=%lld h=%lld dpitch=%lld spitch=%lld "
"-- a pitch shorter than the row is a caller bug",
(long long)width, (long long)height,
(long long)dpitch, (long long)spitch);
return RAD_E_INVAL;
}
Task t;
t.kind = Task::Copy2D;
t.dst = dst;
t.src = src;
t.a = dpitch;
t.b = spitch;
t.c = width;
t.d = height;
return stream_push((HostStream*)st, t);
}
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);
return RAD_E_INVAL;
}
if (prefix == 0 && n == 0) return RAD_OK;
Task t;
t.kind = Task::Ranges;
t.dst = dst;
t.src = src;
t.a = prefix;
t.b = n;
t.aux = ranges;
return stream_push((HostStream*)st, t);
}
int h_memset_async(void* dst, int value, int64_t bytes, RadStream st) {
RAD_TRY(check_stream(st, "rad_memset_async"));
if (bytes == 0) return RAD_OK;
if (!dst || bytes < 0) {
device_set_error("rad_memset_async(%p, %lld): invalid argument", dst, (long long)bytes);
return RAD_E_INVAL;
}
Task t;
t.kind = Task::Memset;
t.dst = dst;
t.a = value & 0xff;
t.b = bytes;
return stream_push((HostStream*)st, t);
}
/* ------------------------------------------------------------------ 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.
*
* 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. */
constexpr int64_t kVmemGranule = RAD_ALIGN_POOL;
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. */
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);
if (raw == MAP_FAILED) {
device_set_error("vmem_reserve(%lld): mmap failed", (long long)bytes);
return nullptr;
}
char* base = (char*)align_up((int64_t)(uintptr_t)raw, align);
const size_t head = (size_t)(base - (char*)raw);
if (head) ::munmap(raw, head);
const size_t tail = raw_len - head - (size_t)bytes;
if (tail) ::munmap(base + bytes, tail);
return base;
}
void h_vmem_release(void* base, int64_t bytes) {
if (base && bytes > 0) ::munmap(base, (size_t)bytes);
}
int h_vmem_commit(void* addr, int64_t bytes) {
if (!addr || bytes <= 0) return RAD_E_INVAL;
void* p = ::mmap(addr, (size_t)bytes, PROT_READ | PROT_WRITE,
MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (p != addr) {
device_set_error("vmem_commit(%p, %lld): mmap failed", addr, (long long)bytes);
return RAD_E_NOMEM;
}
g_used[t_device].fetch_add(bytes, std::memory_order_relaxed);
return RAD_OK;
}
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. */
void* p = ::mmap(addr, (size_t)bytes, PROT_NONE,
MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
if (p != addr) {
device_set_error("vmem_decommit(%p, %lld): mmap failed", addr, (long long)bytes);
return RAD_E_INVAL;
}
g_used[t_device].fetch_sub(bytes, std::memory_order_relaxed);
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. */
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) {
device_set_error("vmem_protect(%p, %lld): mprotect failed", addr, (long long)bytes);
return RAD_E_INVAL;
}
return RAD_OK;
}
int h_vram_used(int device, int64_t* out) {
if (!out || device < 0 || device >= kMaxFakeDevices) return RAD_E_INVAL;
*out = g_used[device].load(std::memory_order_relaxed);
return RAD_OK;
}
const DeviceBackend g_host = {
"host",
h_count, h_set, h_props, h_enable_peer,
h_alloc, h_free, h_host_ptr, h_device_ptr,
h_stream_create, h_stream_destroy, h_stream_sync,
h_event_create, h_event_destroy, h_event_record, h_event_wait,
h_event_query, h_event_sync, h_event_elapsed_ms,
h_host_wrote,
h_memcpy_async, h_memcpy_2d_async, h_memset_async, h_memcpy_ranges_async,
/* 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. */
nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
/* Elastic memory, which the host backend DOES have: see above. */
h_vmem_granularity, h_vmem_reserve, h_vmem_release, h_vmem_commit, h_vmem_decommit,
h_vmem_protect,
h_vram_used,
};
} /* namespace */
const DeviceBackend* host_backend(void) { return &g_host; }
} /* namespace rad */
-2245
View File
File diff suppressed because it is too large. Load diff
-362
View File
@@ -1,362 +0,0 @@
/* 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.
*
* 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.
* 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
* explicit pool budgets.
* 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.
*/
#pragma once
#include "rad_core.h"
#include "build/startup.h"
#include "sched/mem_iface.h"
#include "sched/scheduler.h"
#include "sample/vocab_view.h"
#include "runtime/rank_barrier.h"
#include "text/tokenizer.h"
#include "format/radfile.h"
#include "format/table_copy.h"
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <memory>
#include <mutex>
#include <thread>
namespace rad {
class SSDTier;
class Kld;
struct TierPump;
struct TierJob;
struct StepSlot;
struct VramFacts; /* mem/vram_budget.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. */
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();
/* --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. */
int dump();
const Program& program() const;
const Config& config() const { return cfg_; }
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). */
struct Rank;
std::vector<std::unique_ptr<Rank>> ranks_;
/* THE DISK HALF OF THE IDLE TIERS. One store for the engine, not one per rank: it is
* keyed by a chained hash of TOKENS, which every rank computes identically, and a
* per-rank store would write the same key several times over. Off unless
* --prefix-cache-disk-mib and a directory are both given; it holds conversation content
* unencrypted and says so at startup.
*
* unique_ptr because engine.h is included by main.cpp and the tools, and SSDTier
* drags in the O_DIRECT device layer that none of them want to compile against. */
std::unique_ptr<SSDTier> kv_disk_;
/* THE TIERS' WORK IN FLIGHT: the copy to host memory the transfer streams are running and the
* disk batch the IO thread is writing. Declared after kv_disk_ so it goes first -- the thread
* writes into that store. */
std::unique_ptr<TierPump> pump_;
std::vector<std::thread> rank_threads_;
Config cfg_;
/* 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). */
std::unique_ptr<RadFile> file_;
std::unique_ptr<Checkpoint> ckpt_;
std::unique_ptr<CheckpointSources> ckpt_src_;
/* What rad_weight_encoding is answered from: the container's entries or the checkpoint's
* 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. */
std::vector<std::string> meta_kv_k_, meta_kv_v_;
std::vector<const char*> meta_kv_kp_, meta_kv_vp_;
void (*arch_step_)(RadCtx*, const RadBatch*) = nullptr;
int load_plugins();
int read_metadata();
int read_checkpoint_metadata();
int declare();
int plan();
/* --embedding-placement and --ngram-placement, resolved into Config before the card is split
* (engine_bringup.cpp says how auto chooses). */
int resolve_table_placement(const std::vector<VramFacts>& facts,
const std::vector<int64_t>& emb_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`). */
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. */
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. */
std::vector<TableCopy> table_copies_;
std::vector<void*> card_copies_;
std::vector<std::pair<const void*, void*>> 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. */
struct StepOut {
std::vector<Request*> reqs; /* the requests that wanted a row, in row order */
std::vector<int32_t> 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). */
int32_t n_rows = 0;
std::vector<int32_t> rows; /* [n_out] the device's answer, copied back */
int32_t* rb = nullptr; /* the pinned readback collect_issue filled */
std::vector<float> lg; /* the first row's logits, at -vv */
std::vector<int32_t> token; /* [n_seq] */
std::vector<int32_t> accepted; /* [n_seq] */
std::vector<uint8_t> eos; /* [n_seq] */
};
/* 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. */
std::shared_ptr<const Vocab> vocab_;
std::unique_ptr<VocabView> 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. */
ChunkGeometry geo_;
/* One scheduler for every rank: one decision per step, one batch, shared by pointer. */
Scheduler sched_;
std::unique_ptr<IKVManager> kv_iface_;
std::unique_ptr<IPrefixCache> pc_iface_;
/* The release point. Width is tp + 1 -- the scheduler thread is on both sides of it. */
std::unique_ptr<RankBarrier> barrier_;
std::atomic<const RadBatch*> 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. */
enum { kIssueAll = 0, kIssueModel = 1, kIssueSampler = 2 };
std::atomic<int> issue_what_{kIssueAll};
std::atomic<int> step_status_{RAD_OK};
std::atomic<bool> 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. */
std::atomic<int> 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. */
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
* does not allocate. See state_slots_of. */
std::vector<int32_t> ckpt_slots_;
bool state_slots_of(uint64_t seq, std::vector<int32_t>* out) const;
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. */
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);
int collect_step(const RadBatch* b, StepOut& so);
/* 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. */
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. */
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. */
std::vector<int32_t> 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. */
struct Readback {
int32_t* p = nullptr;
int64_t n = 0;
int32_t* reserve(int64_t count);
~Readback();
};
Readback readback_;
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);
/* 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). */
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
* asked for, and the rounds that ran. */
std::vector<Scheduler::SerialRow> serial_row_;
int serial_rounds_ = 0, serial_rows_ = 0, serial_done_ = 0;
/* The StepSlots and end-of-generation ids on every rank, and the pinned host copy of rank 0's
* slots the step reads back (sched/advance.h). */
int step_state_init();
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. */
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] = {};
int phase_n_ = 0;
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 */
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. */
int run_encodes();
int32_t enc_step_ = 0;
void drain_completed();
/* The terminal ids drain_completed() took, reused so a steady state allocates nothing. */
std::vector<uint64_t> done_;
/* THE TIERS' SIDE OF THE LOOP, every iteration: collect a copy that has landed, hand the next
* one out, collect and hand out the disk work. Nothing in it waits on the device or on a file,
* and the scheduler's lock is held only around the bookkeeping. */
void tier_tick();
bool submit_fetch(uint64_t tag, std::vector<TierJob>&& jobs);
uint64_t tier_last_ns_ = 0;
/* 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. */
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. */
int arena_step(const RadBatch* b);
void arena_tick(uint64_t now_ns);
std::vector<int64_t> arena_rows_;
int64_t arena_floor_ = 0;
int64_t arena_last_ = 0;
uint64_t arena_floor_ns_ = 0;
/* WHETHER THIS DRIVER RETURNS DECOMMITTED VRAM TO THE CARD, for the checkpoint slots -- the
* one part of the KV pool still backed on demand. Measured once at the end of bringup; it is
* not something the API promises. */
bool release_frees_card_ = true;
/* 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 checkpoint
* slots backed at the end of bringup leave both free, and the bringup's closing reading is
* checked against both. */
int64_t late_step_bytes_ = 0;
int64_t late_lazy_bytes_ = 0;
/* Every rank's checkpoint floor: a slot is backed only while the card keeps `keep` free. */
void set_checkpoint_floors(int64_t keep);
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. */
int run_kld();
int score_rows(const RadBatch* b, const StepOut& so);
std::unique_ptr<Kld> kld_;
std::vector<float*> kld_host_;
std::vector<int64_t> kld_vocab0_, kld_width_; /* per rank read: its logits columns */
/* The engine half of /server_info, as a JSON object. See the definition in engine.cpp. */
std::string engine_info() 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. */
void tiering_dispatch(Rank& r, int step);
void rank_loop(int rank);
};
} /* namespace rad */
File diff suppressed because it is too large. Load diff
-461
View File
@@ -1,461 +0,0 @@
/* 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.
*/
#include "engine_priv.h"
#include "sched/scheduler.h"
#include "device/device.h"
#include <algorithm>
#include <chrono>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <vector>
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. */
int Engine::step_state_init() {
std::vector<int32_t> eog;
if (vocab_) eog = vocab_->eog();
std::sort(eog.begin(), eog.end());
eog.erase(std::unique(eog.begin(), eog.end()), eog.end());
const int64_t n_slot = cfg_.max_seqs > 0 ? cfg_.max_seqs : 1;
const int64_t slot_bytes = n_slot * (int64_t)sizeof(StepSlot);
for (auto& rk : ranks_) {
RAD_TRY(rad_dev_set(rk->device));
rk->step_slots = static_cast<StepSlot*>(rad_dev_alloc(slot_bytes, RAD_MEM_DEVICE));
rk->n_eog = (int32_t)eog.size();
rk->eog = static_cast<int32_t*>(
rad_dev_alloc(std::max<int64_t>(1, (int64_t)eog.size()) * 4, RAD_MEM_DEVICE));
if (!rk->step_slots || !rk->eog) {
RAD_ERR("step state: no device memory for %lld slot(s) on card %d",
(long long)n_slot, rk->device);
return RAD_E_NOMEM;
}
RAD_TRY(rad_memset_async(rk->step_slots, 0, slot_bytes, rk->ctx.stream()));
if (!eog.empty())
RAD_TRY(rad_memcpy_async(rk->eog, eog.data(), (int64_t)eog.size() * 4,
rk->ctx.stream()));
RAD_TRY(rad_stream_sync(rk->ctx.stream()));
}
if (!ranks_.empty()) RAD_TRY(rad_dev_set(ranks_[0]->device));
slots_host_ = static_cast<StepSlot*>(rad_dev_alloc(slot_bytes, RAD_MEM_HOST_PINNED));
if (!slots_host_) return RAD_E_NOMEM;
RAD_TRY(rad_event_create_as(&step_end_, RAD_EVENT_LOCAL | RAD_EVENT_HOST_WAIT));
return RAD_OK;
}
void Engine::step_state_fini() {
for (auto& rk : ranks_) {
(void)rad_dev_set(rk->device);
if (rk->step_slots) rad_dev_free(rk->step_slots, RAD_MEM_DEVICE);
if (rk->eog) rad_dev_free(rk->eog, RAD_MEM_DEVICE);
rk->step_slots = nullptr;
rk->eog = nullptr;
}
if (slots_host_) rad_dev_free(slots_host_, RAD_MEM_HOST_PINNED);
slots_host_ = nullptr;
if (step_end_) rad_event_destroy(step_end_);
step_end_ = nullptr;
}
/* ------------------------------------------------------------------ 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).
*
* 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.
*
* 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.
*/
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;
}
/* 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. */
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];
AdvanceArgs a = sched_.advance_args((int)i);
if (rows >= 0 && rows < a.n_seq) a.n_seq = rows;
a.mode = mode;
a.round = round;
a.st = rk.step_slots;
a.eog = rk.eog;
a.n_eog = rk.n_eog;
if (from_proposal) {
a.src = static_cast<const int32_t*>(drafter_.proposal ? rk.ctx.buf_ptr(drafter_.proposal)
: rk.ctx.buf_ptr(rk.tok_buf));
a.src_pitch = (drafter_.proposal && drafter_.proposal_pitch > 0)
? drafter_.proposal_pitch : 1;
} else {
a.src = static_cast<const int32_t*>(rk.ctx.buf_ptr(rk.tok_buf));
}
if (!a.src || !a.st) {
RAD_ERR("drafter '%s': rank %zu has no %s to advance from", drafter_.name, i,
a.st ? "proposal buffer" : "step state");
return RAD_E_STATE;
}
RAD_TRY(step_advance(a, rk.ctx.stream()));
}
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) {
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. */
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));
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. */
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: <n> 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. */
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;
/* Pass 0, then rounds 2..rounds: round 1 has no pass of its own. */
for (int rd = 0; rd <= rounds; rd += rd == 0 ? 2 : 1) {
if (rd > 0 && n <= 0) break;
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. */
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. */
for (auto& rk : ranks_) {
int s = rk->sampler.build_greedy(drafter_.proposal ? 0 : drafted);
if (s < 0) {
RAD_ERR("drafter '%s': build_greedy: %s", drafter_.name, rad_strerror(s));
return s;
}
}
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. */
barrier_->arrive_and_wait();
const auto tC2 = std::chrono::steady_clock::now();
barrier_->arrive_and_wait();
const auto tD = std::chrono::steady_clock::now();
int st = step_status_.load(std::memory_order_acquire);
if (st < 0) {
RAD_ERR("drafter '%s': pass %d of step %d failed: %s -- the engine cannot continue",
drafter_.name, rd, step, rad_strerror(st));
return st;
}
if (stg) {
using us = std::chrono::duration<double, std::micro>;
a_batch += us(tB - tA).count();
a_samp += us(tC - tB).count();
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);
}
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). */
RAD_TRY(advance_all(ADV_TAKE, serial_done_, true, n));
Rank& r0 = *ranks_[0];
RAD_TRY(rad_memcpy_async(slots_host_, r0.step_slots,
(int64_t)cfg_.max_seqs * (int64_t)sizeof(StepSlot), r0.ctx.stream()));
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. */
int Engine::finish_serial_drafter(const StepOut& so) {
if (!serial_drafting() || serial_rounds_ <= 0) return RAD_OK;
const StepPlan& plan = sched_.plan();
if (serial_done_ > 0 && serial_rows_ > 0) {
for (size_t i = 0; i < plan.e.size(); ++i) {
const StepEntry& e = plan.e[i];
if (so.first_row[i] < 0) continue;
const StepSlot& S = slots_host_[e.card]; /* in range: the builder refuses others */
if (S.acc != so.accepted[i] || S.tok[0] != so.token[i]) {
RAD_ERR("drafter '%s': the card accepted %d draft(s) ending in token %d for "
"sequence %llu and the host %d ending in %d; the draft passes ran from "
"the card's", drafter_.name, S.acc, S.tok[0],
(unsigned long long)e.seq, so.accepted[i], so.token[i]);
return RAD_E_STATE;
}
}
}
sched_.serial_end(serial_done_);
if (serial_done_ <= 0 || serial_rows_ <= 0) return RAD_OK;
Rank& r0 = *ranks_[0];
const int rounds = serial_rounds_, done = serial_done_;
draft_out_.assign((size_t)serial_rows_ * (size_t)rounds, 0);
for (int i = 0; i < serial_rows_; ++i) {
const StepSlot& S = slots_host_[serial_row_[(size_t)i].card];
for (int rd = 1; rd <= done; ++rd)
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. */
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);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ 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).
*
* What there is instead is TWO passes with different shapes, and the split is what a
* block-diffusion architecture asks for:
*
* 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.
*
* 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.
*/
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. */
const int block = drafter_.block > 0 ? (int)drafter_.block : drafter_.depth + 1;
std::vector<Scheduler::BlockRow> rows((size_t)cfg_.max_seqs);
const int n = sched_.block_begin(block, steps, (int)drafter_.window, drafter_.mask_token,
rows.data(), (int)rows.size());
Rank& r0 = *ranks_[0];
void* prop = r0.ctx.buf_ptr(drafter_.proposal);
if (!prop) {
RAD_ERR("drafter '%s': `%s` was declared as the proposal buffer but never planned",
drafter_.name, r0.program.buffers[drafter_.proposal].name.c_str());
return RAD_E_STATE;
}
/* THE BISECT. RADIANCE_DRAFT_RAW=<buffer> 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. */
auto run_pass = [&](const RadBatch* db, const char* what) -> int {
for (auto& rk : ranks_) {
int s = rk->sampler.build_greedy(0);
if (s < 0) {
RAD_ERR("drafter '%s': build_greedy: %s", drafter_.name, rad_strerror(s));
return s;
}
}
issue_what_.store(kIssueAll, std::memory_order_release);
step_batch_.store(db, std::memory_order_release);
barrier_->arrive_and_wait();
barrier_->arrive_and_wait();
const int s = step_status_.load(std::memory_order_acquire);
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);
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"));
/* 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. */
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;
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_stream_sync(r0.ctx.stream()));
for (size_t i = 0; i < draft_out_.size(); ++i) draft_out_[i] = raw[i * (size_t)k];
}
}
sched_.block_end();
if (n <= 0 || draft_out_.empty()) return RAD_OK;
for (int i = 0; i < n; ++i) {
/* A request the sampler will not speculate on gets no draft; see finish_serial_drafter. */
if (!r0.sampler.allows_speculation(rows[(size_t)i].seq)) continue;
sched_.set_draft(rows[(size_t)i].seq, &draft_out_[(size_t)i * (size_t)steps], steps);
}
return RAD_OK;
}
} /* namespace rad */
-174
View File
@@ -1,174 +0,0 @@
/* 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. */
#include "engine_priv.h"
#include "kld.h"
#include "device/device.h"
#include "server/sink.h"
#include <chrono>
#include <memory>
#include <thread>
#include <vector>
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. */
const int64_t need = cfg_.max_tok + cfg_.max_seqs;
const int64_t nv = meta_.n_vocab;
kld_vocab0_.clear();
kld_width_.clear();
for (const auto& rk : ranks_) {
const Program& p = rk->program;
if (p.logits_buf == RAD_NULL_HANDLE || (size_t)p.logits_buf >= p.buffers.size()) {
RAD_ERR("kld: rank %d declared no logits buffer", rk->index);
return RAD_E_UNSUPPORTED;
}
const RadBufDecl& d = p.buffers[p.logits_buf].decl;
if (d.dtype != RAD_F32 || d.rank != 2 || d.shape[0] < need) {
RAD_ERR("kld: the '%s' plugin's logits buffer is %lld rows of %s; the KL mode needs "
"f32 rows for a whole step, %lld (it reads RadBuildCtx::max_out_rows)",
plugins_.arch_plugin.c_str(), (long long)d.shape[0],
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. */
const int64_t w = d.shape[1];
if (w >= nv) {
if (!kld_width_.empty()) continue;
kld_vocab0_.push_back(0);
kld_width_.push_back(nv);
continue;
}
const int64_t per = (nv + cfg_.tp - 1) / cfg_.tp;
kld_vocab0_.push_back(per * rk->index);
kld_width_.push_back(w);
}
int64_t cover = 0;
for (int64_t w : kld_width_) cover += w;
if (cover != nv) {
RAD_ERR("kld: the ranks' logits columns add up to %lld of a %lld-token vocabulary",
(long long)cover, (long long)nv);
return RAD_E_STATE;
}
kld_host_.assign(kld_width_.size(), nullptr);
for (size_t r = 0; r < kld_width_.size(); ++r) {
kld_host_[r] = static_cast<float*>(
rad_dev_alloc(cfg_.max_tok * kld_width_[r] * (int64_t)sizeof(float), RAD_MEM_HOST_PINNED));
if (!kld_host_[r]) {
RAD_ERR("kld: no pinned host memory for a step's logits (%lld MiB a rank); lower "
"--max-num-batched-tokens", (long long)(cfg_.max_tok * kld_width_[r] * 4 >> 20));
return RAD_E_NOMEM;
}
}
auto kld = std::make_unique<Kld>();
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. */
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();
std::vector<std::unique_ptr<server::Sink>> sinks(n);
std::vector<std::unique_ptr<Request>> reqs(n);
for (size_t d = 0; d < n; ++d) {
sinks[d] = std::make_unique<server::Sink>(64);
auto r = std::make_unique<Request>();
r->id = d + 1;
r->prompt = kld_->tokens(d);
r->max_tokens = 1;
r->ignore_eos = true;
r->sp.temp = 0.0f;
r->score = true;
r->sink = sinks[d].get();
sinks[d]->id = r->id;
reqs[d] = std::move(r);
}
std::vector<int> rc(n, RAD_OK);
sched_.add_all(reqs.data(), n, rc.data());
for (size_t d = 0; d < n; ++d) {
if (rc[d] >= 0) continue;
RAD_ERR("kld: the scheduler refused document %zu (%zu tokens): %s", d,
kld_->tokens(d).size(), rad_strerror(rc[d]));
return rc[d];
}
const auto t0 = std::chrono::steady_clock::now();
auto last = t0;
for (size_t first = 0;;) {
while (first < n && sinks[first]->done()) ++first;
if (first == n) break;
const int ls = loop_status_.load(std::memory_order_acquire);
if (ls < 0) return ls;
sinks[first]->wait(200);
const auto now = std::chrono::steady_clock::now();
if (now - last >= std::chrono::seconds(15)) {
last = now;
const double s = std::chrono::duration<double>(now - t0).count();
RAD_INFO("kld: %lld / %lld positions, %zu / %zu documents, %.0f s",
(long long)kld_->rows_done(), (long long)kld_->n_rows(), first, n, s);
}
}
int bad = 0;
for (size_t d = 0; d < n; ++d) {
const server::Finish f = sinks[d]->finish_reason();
if (f == server::Finish::Error || f == server::Finish::Cancelled) {
RAD_ERR("kld: document %zu did not finish: %s", d, rad_strerror(sinks[d]->status()));
++bad;
}
sched_.reap(sinks[d]->id);
}
if (bad) return RAD_E_STATE;
RAD_INFO("kld: %zu documents in %.0f s", n,
std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count());
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. */
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;
const StepPlan& plan = sched_.plan();
std::vector<KldSpan> spans;
int64_t row = 0;
for (const StepEntry& e : plan.e) {
if (!(e.req && e.req->score && e.is_prefill && e.hidden_row < 0)) continue;
spans.push_back({ e.req->id, (int64_t)e.ctx_len, (int64_t)e.n_tokens, row });
row += e.n_tokens;
}
if (row != n || n > cfg_.max_tok) {
RAD_ERR("kld: step %d names %lld scored rows and its plan %lld", b->step, (long long)n,
(long long)row);
return RAD_E_STATE;
}
for (size_t r = 0; r < kld_width_.size(); ++r) {
Rank& rk = *ranks_[r];
RAD_TRY(rad_dev_set(rk.device));
const auto* src = static_cast<const float*>(rk.ctx.buf_ptr(rk.program.logits_buf));
if (!src) return RAD_E_STATE;
RAD_TRY(rad_memcpy_async(kld_host_[r], src + (int64_t)so.n_rows * kld_width_[r],
n * kld_width_[r] * (int64_t)sizeof(float), rk.ctx.stream()));
}
for (size_t r = 0; r < kld_width_.size(); ++r) {
RAD_TRY(rad_dev_set(ranks_[r]->device));
RAD_TRY(rad_stream_sync(ranks_[r]->ctx.stream()));
}
RAD_TRY(rad_dev_set(ranks_[0]->device));
std::vector<KldShard> shards(kld_width_.size());
for (size_t r = 0; r < shards.size(); ++r)
shards[r] = { kld_host_[r], kld_vocab0_[r], kld_width_[r] };
return kld_->score(spans, shards);
}
} /* namespace rad */
-132
View File
@@ -1,132 +0,0 @@
/* 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.
*
* 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.
*
* 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.
*/
#include "engine_priv.h"
#include "mm/processor.h"
#include <cstdio>
#include <cstdlib>
namespace rad {
int Engine::run_encodes() {
std::vector<std::shared_ptr<mm::Item>> items;
sched_.take_encodes(&items);
if (items.empty()) return RAD_OK;
const RadEncoderDecl& enc = ranks_[0]->program.encoder;
const int64_t max_p = sched_.encoder_patches();
const int64_t n_embd = enc.n_embd;
Rank& r0 = *ranks_[0];
void* out = r0.ctx.buf_ptr(enc.out);
if (!out) {
RAD_ERR("encoder '%s': its output buffer was declared but never planned",
ranks_[0]->program.encoder_name.c_str());
return RAD_E_STATE;
}
/* A DIAGNOSTIC: RADIANCE_DEBUG_MM_DUMP=<dir> 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. */
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];
std::snprintf(path, sizeof path, "%s/mm_%016llx%016llx_%dx%dx%d%s", dump_dir,
(unsigned long long)it.key_hi, (unsigned long long)it.key_lo, it.grid_t,
it.grid_h, it.grid_w, ext);
if (FILE* f = std::fopen(path, "wb")) {
std::fwrite(p, sizeof(uint16_t), n, f);
std::fclose(f);
RAD_INFO("encoder: wrote %s", path);
}
};
for (auto& ip : items) {
if (ip->encoded) continue;
ip->embd.assign((size_t)(ip->n_rows() * n_embd), 0);
if (dump_dir && *dump_dir) dump(*ip, ".pix.bf16", ip->pixels.data(), ip->pixels.size());
}
size_t i = 0;
int32_t seg = 0;
while (i < items.size()) {
std::vector<BatchBuilder::EncoderPart> parts;
int64_t np = 0;
while (i < items.size()) {
mm::Item& it = *items[i];
if (it.encoded) { ++i; seg = 0; continue; }
const int64_t seg_p = (int64_t)it.grid_h * it.grid_w;
if (seg_p > max_p) {
RAD_ERR("encoder: a segment of %lld patches does not fit a pass of %lld",
(long long)seg_p, (long long)max_p);
return RAD_E_STATE;
}
const int64_t room = (max_p - np) / seg_p;
const int32_t can = (int32_t)std::min<int64_t>(it.n_seg - seg, room);
if (can <= 0) break;
parts.push_back({ &it, seg, can });
np += (int64_t)can * seg_p;
seg += can;
if (seg == it.n_seg) { ++i; seg = 0; }
}
if (parts.empty()) break;
const RadBatch* b = sched_.build_encoder(parts, enc_step_++);
if (!b) return RAD_E_STATE;
RAD_TRY(prepare_release(b));
/* kIssueModel: the pass and nothing behind it -- no sampler, and no tiering tick, which
* belongs to steps. */
issue_what_.store(kIssueModel, std::memory_order_release);
step_batch_.store(b, std::memory_order_release);
barrier_->arrive_and_wait();
barrier_->arrive_and_wait();
const int st = step_status_.load(std::memory_order_acquire);
if (st < 0) {
RAD_ERR("encoder pass failed: %s -- the engine cannot continue", rad_strerror(st));
return st;
}
/* The rows, in pass order: each part's segments are consecutive rows of its item. */
int64_t row = 0;
for (const BatchBuilder::EncoderPart& p : parts) {
mm::Item& it = *const_cast<mm::Item*>(p.item);
const int64_t rows = (int64_t)p.n_seg * it.seg_rows;
const int64_t bytes = rows * n_embd * (int64_t)sizeof(uint16_t);
RAD_TRY(rad_memcpy_async(it.embd.data() + (int64_t)p.seg0 * it.seg_rows * n_embd,
static_cast<const char*>(out) +
row * n_embd * (int64_t)sizeof(uint16_t),
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. */
for (auto& rk : ranks_) RAD_TRY(rad_stream_sync(rk->ctx.stream()));
}
for (auto& ip : items) {
mm::Item& it = *ip;
if (it.encoded) continue;
it.encoded = true;
it.pixels.clear();
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());
return RAD_OK;
}
} /* namespace rad */
-116
View File
@@ -1,116 +0,0 @@
/* engine_priv.h -- what the Engine's translation units share and nothing outside them sees.
*
* `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::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.
*/
#pragma once
#include "engine.h"
#include "mem/pools.h"
#include "mem/kv.h"
#include "mem/prefix.h"
#include "mem/kvtier.h"
#include "mem/sstier.h"
#include "runtime/tierexec.h"
#include "build/rad_build.h"
#include "place/heat.h"
#include "place/planner.h"
#include "place/mover.h"
#include "place/stager.h"
#include "runtime/ctx.h"
#include "sample/sampler.h"
#include "sched/advance.h"
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). */
struct Engine::Rank {
int index = 0;
int device = 0;
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. */
HeatEngine heat;
std::vector<int> 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<HeatRow> 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. */
uint64_t heat_credited = 0, heat_idle = 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. The disk store is rank 0's alone for the same
* reason the policy is: one store, keyed by a hash of tokens every rank agrees on.
* Both are inert unless the operator gave a tier a size. */
IdleTiers tiers;
TierExec tierx;
/* The activation arena's smaller levels, smallest step first (Engine::probe_arena_levels). */
std::vector<ArenaLevel> arena_levels;
/* 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<int64_t> 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. */
PrefillStager stager;
/* THE FILE STAGER (core/place/stager.h): a routed layer's file-tier experts, read 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. */
FileStager fstager;
StagerChain stagers;
Ctx ctx;
Sampler sampler; /* one per rank: each samples its own vocab shard (spec §9) */
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. */
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 -- and one disk batch out on the IO thread. */
struct TierPump {
std::vector<TierJob> copy;
std::vector<int> copy_st; /* per rank: 0 in flight, 1 landed, negative failed */
TierIO io;
int64_t max_copy = 0;
int slow_budget = 0;
/* The requests a read off disk is out for (IdleTiers::plan_fetch). Asked again while their
* read is out, they wait without walking their prompt; the read's collection lets them go. */
std::vector<uint64_t> waiting;
};
/* 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 = "");
} /* namespace rad */
-268
View File
@@ -1,268 +0,0 @@
/* 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.
*/
#include "engine_priv.h"
#include "build/rad_build.h"
#include "device/device.h"
#include <cstring>
#include <cstdint>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <string>
#include <vector>
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=<n>
* adds the first n elements verbatim (integers included) and RADIANCE_DUMP_TOPK=<k> 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. */
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;
}();
return cap;
}
static void dump_row(int step, const char* phase, const char* name, uint32_t dtype,
const std::vector<uint8_t>& raw) {
const int bits = rad_dtype_bits(dtype);
const int64_t cnt = bits > 0 ? (int64_t)raw.size() * 8 / bits : 0;
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. */
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 */
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. */
uint64_t h = 1469598103934665603ull;
for (size_t i = 0; i < raw.size(); ++i) { h ^= raw[i]; h *= 1099511628211ull; }
const int64_t good = cnt - bad;
RAD_TRACE("step %d%-8s %-28s %-5s n=%lld hash %016llx mean %.6f amax %.5f "
"nonfinite %lld%s [%.6f %.6f %.6f %.6f]",
step, phase, name, rad_dtype_name(dtype), (long long)cnt, (unsigned long long)h,
good > 0 ? sum / (double)good : 0.0, amax, (long long)bad,
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 ----------------------------------------
*
* `RADIANCE_DUMP_HEAD=<n>` 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. An OpenAI `logprobs` FIELD would
* need the normaliser, and `supports_logprobs` is false; this 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);
}();
if (head > 0) {
const int64_t n = std::min<int64_t>(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;
}
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 ---------------
*
* `RADIANCE_DUMP_TOPK=<k>` 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 returns no logprobs (`supports_logprobs` is
* never set, so it refuses them) 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;
/* A partial selection, not a sort: n is the whole vocabulary and this runs on the step path. */
std::vector<std::pair<float, int64_t>> 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;
if (!std::isfinite(v)) continue;
if ((int)best.size() < topk) {
best.emplace_back(v, k);
std::push_heap(best.begin(), best.end(), std::greater<>());
} else if (v > best.front().first) {
std::pop_heap(best.begin(), best.end(), std::greater<>());
best.back() = { v, k };
std::push_heap(best.begin(), best.end(), std::greater<>());
}
}
std::sort(best.begin(), best.end(), std::greater<>());
std::string line;
for (const auto& b : best) line += fmt(" %lld:%.5f", (long long)b.second, (double)b.first);
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. */
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) {
if (!names || !*names) return;
const Program& p = *ctx.program();
for (const char* s = names; *s; ) {
const char* e = s;
while (*e && *e != ',') ++e;
const std::string want(s, (size_t)(e - s));
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) {
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. */
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<int64_t>(row > 0 ? row : wi.stored_bytes, dump_cap());
std::vector<uint8_t> 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;
}
for (size_t i = 1; i < p.buffers.size(); ++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<int64_t>(row, dump_cap());
std::vector<uint8_t> 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;
}
next:;
}
}
} /* namespace rad */
-907
View File
@@ -1,907 +0,0 @@
/* checkpoint.cpp -- see checkpoint.h. */
#include "checkpoint.h"
#include "rad_plugin.h"
#include <nlohmann/json.hpp>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <map>
namespace rad {
/* ================================================================== metadata */
void MetaOwn::set(const std::string& k, const std::string& v) {
for (size_t i = 0; i < keys.size(); ++i)
if (keys[i] == k) { vals[i] = v; return; }
kv(k, v);
}
bool MetaOwn::has(const std::string& k) const {
return std::find(keys.begin(), keys.end(), k) != keys.end();
}
const char* MetaOwn::get(const std::string& k) const {
for (size_t i = 0; i < keys.size(); ++i)
if (keys[i] == k) return vals[i].c_str();
return nullptr;
}
void MetaOwn::finish() {
kp.clear();
vp.clear();
for (auto& s : keys) kp.push_back(s.c_str());
for (auto& s : vals) vp.push_back(s.c_str());
m.arch_id = arch.c_str();
m.name = name.c_str();
m.quant = quant.c_str();
m.n_kv = (int)keys.size();
m.kv_key = kp.data();
m.kv_val = vp.data();
}
/* ---------------------------------------------------------------- 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.
*
* 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.
*/
static void flatten_json(const nlohmann::json& j, const std::string& prefix, MetaOwn* out) {
for (auto it = j.begin(); it != j.end(); ++it) {
const std::string key = prefix.empty() ? it.key() : prefix + "." + it.key();
const nlohmann::json& v = it.value();
if (v.is_object()) flatten_json(v, key, out);
else if (v.is_boolean()) out->kv(key, v.get<bool>() ? "1" : "0");
else if (v.is_number_integer()) out->kv(key, fmt("%lld", (long long)v.get<int64_t>()));
else if (v.is_number()) out->kv(key, fmt("%.17g", v.get<double>()));
else if (v.is_string()) out->kv(key, v.get<std::string>());
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. */
std::string s;
bool ok = true;
for (const auto& e : v) {
if (!s.empty()) s += ' ';
if (e.is_number_integer()) s += fmt("%lld", (long long)e.get<int64_t>());
else if (e.is_number()) s += fmt("%.17g", e.get<double>());
else if (e.is_string()) s += e.get<std::string>();
else { ok = false; break; }
}
if (ok) out->kv(key, s);
}
}
}
/* 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. */
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);
if (!f) {
RAD_ERR("%s: no config.json. A draft checkpoint carries its own geometry there -- the "
"block size it was trained for, which trunk layers it reads, the selector's rank "
"-- and none of it is derivable from the target.", dir.c_str());
return RAD_E_NOTFOUND;
}
nlohmann::json j;
try { f >> j; }
catch (const std::exception& e) { RAD_ERR("%s: %s", path.c_str(), e.what()); return RAD_E_FORMAT; }
flatten_json(j, prefix, out);
return RAD_OK;
}
/* ---------------------------------------------------------------- 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. */
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 */
nlohmann::json j;
try { f >> j; }
catch (const std::exception& e) {
RAD_WARN("%s: %s; no sampling defaults are carried", path.c_str(), e.what());
return RAD_OK;
}
if (!j.is_object()) {
RAD_WARN("%s: not a JSON object; no sampling defaults are carried", path.c_str());
return RAD_OK;
}
flatten_json(j, "generation", out);
return RAD_OK;
}
/* ---------------------------------------------------------------- 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. */
int meta_merge_preprocessor_configs(const std::string& dir, MetaOwn* out) {
static const struct { const char* file; const char* prefix; } kFiles[] = {
{ "preprocessor_config.json", "preprocessor" },
{ "video_preprocessor_config.json", "video_preprocessor" },
};
for (const auto& f : kFiles) {
const std::string path = dir + "/" + f.file;
std::ifstream in(path);
if (!in) continue;
nlohmann::json j;
try { in >> j; }
catch (const std::exception& e) {
RAD_WARN("%s: %s; it is not carried", path.c_str(), e.what());
continue;
}
if (j.is_object()) flatten_json(j, f.prefix, out);
}
return RAD_OK;
}
int meta_from_config_json(const std::string& dir, MetaOwn* out) {
const std::string path = dir + "/config.json";
std::ifstream f(path);
if (!f) {
RAD_ERR("%s: no config.json. A safetensors checkpoint carries its architecture and its "
"dimensions there; without it nothing can be sized.", dir.c_str());
return RAD_E_NOTFOUND;
}
nlohmann::json j;
try { f >> j; }
catch (const std::exception& e) {
RAD_ERR("%s: %s", path.c_str(), e.what());
return RAD_E_FORMAT;
}
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. */
{
const size_t n = out->keys.size();
for (size_t i = 0; i < n; ++i) {
const std::string& k = out->keys[i];
if (k.rfind("text_config.", 0) != 0) continue;
const std::string bare = k.substr(12);
bool have = false;
for (size_t j2 = 0; j2 < n; ++j2) if (out->keys[j2] == bare) { have = true; break; }
if (!have) out->kv(bare, out->vals[i]);
}
}
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. */
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);
return v ? strtoll(v, nullptr, 10) : dflt;
};
auto gf = [&](const char* k, double dflt) -> double {
const char* v = gs((std::string("text_config.") + k).c_str());
if (!v) v = gs(k);
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. */
if (const char* mt = gs("model_type")) {
out->arch.clear();
for (const char* p = mt; *p; ++p) if (*p != '_') out->arch += *p;
}
if (const char* nm = gs("_name_or_path")) out->name = nm;
RadModelMeta& m = out->m;
m.n_layers = gi("num_hidden_layers", 0);
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. */
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. */
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);
m.n_expert = gi("num_experts", gi("num_local_experts", 0));
m.n_expert_used = gi("num_experts_per_tok", 0);
m.n_expert_shared = gi("shared_expert_intermediate_size", 0) ? 1 : 0;
m.rms_eps = (float)gf("rms_norm_eps", 1e-6);
m.rope_theta = (float)gf("rope_parameters.rope_theta", gf("rope_theta", 10000.0));
m.rope_scale = (float)gf("rope_scaling.factor", 1.0);
/* 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. */
if (const char* qm = gs("quantization_config.quant_method")) {
out->quant = qm;
if (const char* fm = gs("quantization_config.fmt")) { out->quant += "_"; out->quant += fm; }
}
out->finish();
return RAD_OK;
}
int meta_from_gguf(GgufFile& g, MetaOwn* out) {
if (!g.get_str("general.architecture", &out->arch)) {
RAD_ERR("the GGUF has no general.architecture, so no architecture plugin can be chosen");
return RAD_E_FORMAT;
}
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 `<arch>.<field>` convention; anything the struct does not name is passed through in
* the free-form KV list, which the core never interprets. */
const std::string a = out->arch;
auto gi = [&](const char* suffix, int64_t dflt) -> int64_t {
int64_t v = 0;
return g.get_i64(a + "." + suffix, &v) ? v : dflt;
};
auto gf = [&](const char* suffix, double dflt) -> double {
double v = 0;
return g.get_f64(a + "." + suffix, &v) ? v : dflt;
};
RadModelMeta& m = out->m;
m.n_layers = gi("block_count", 0);
m.n_embd = gi("embedding_length", 0);
m.n_head = gi("attention.head_count", 0);
m.n_head_kv = gi("attention.head_count_kv", m.n_head);
m.head_dim = gi("attention.key_length", m.n_head ? m.n_embd / m.n_head : 0);
m.n_ff = gi("feed_forward_length", 0);
m.n_ctx_train = gi("context_length", 0);
m.n_expert = gi("expert_count", 0);
m.n_expert_used = gi("expert_used_count", 0);
m.n_expert_shared= gi("expert_shared_count", 0);
m.rms_eps = (float)gf("attention.layer_norm_rms_epsilon", 1e-6);
m.rope_theta = (float)gf("rope.freq_base", 10000.0);
m.rope_scale = (float)gf("rope.scaling.factor", 1.0);
std::vector<std::string> toks;
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. */
for (const GgufKV& kv : g.kv()) {
if (kv.key.rfind("tokenizer.", 0) == 0) continue;
std::string v;
if (kv.is_array) {
v = fmt("[%zu values]", kv.type == GGUF_STR ? kv.s.size()
: !kv.i.empty() ? kv.i.size() : kv.f.size());
if (kv.type != GGUF_STR && kv.i.size() <= 8 && !kv.i.empty()) {
v.clear();
for (size_t j = 0; j < kv.i.size(); ++j)
v += fmt("%s%lld", j ? "," : "", (long long)kv.i[j]);
}
} else if (!kv.s.empty()) v = kv.s.front();
else if (!kv.f.empty() && kv.type == GGUF_F32) v = fmt("%g", kv.f.front());
else if (!kv.f.empty() && kv.type == GGUF_F64) v = fmt("%g", kv.f.front());
else if (!kv.i.empty()) v = fmt("%lld", (long long)kv.i.front());
if (v.size() > 240) v.resize(240);
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. */
int64_t ftype = 0;
const bool typed = g.get_i64("general.file_type", &ftype);
out->quant = !typed || ftype == 0 || ftype == 1 || ftype == 32
? std::string() : fmt("gguf_ftype_%lld", (long long)ftype);
out->finish();
return RAD_OK;
}
/* ================================================================== the checkpoint */
int Checkpoint::open_gguf(const std::string& path) {
RAD_TRY(gguf_.open(path.c_str()));
kind_ = Gguf;
for (const GgufTensor& t : gguf_.tensors()) {
SrcTensor s;
s.name = t.name;
s.ggml = t.ggml_type;
s.rad_dtype = gguf_to_rad_dtype(t.ggml_type);
/* GGUF is fastest-first; everything from here on is row-major. */
for (int d = (int)t.n_dims - 1; d >= 0; --d) s.shape.push_back(t.ne[d]);
s.data = gguf_.tensor_data(t);
s.bytes = (int64_t)t.bytes;
if (!s.data) {
RAD_ERR("%s: '%s' has no readable extent", path.c_str(), t.name.c_str());
return RAD_E_FORMAT;
}
index_.emplace(s.name, tensors_.size());
tensors_.push_back(std::move(s));
}
return meta_from_gguf(gguf_, &meta_);
}
int Checkpoint::add_shard(const std::string& p, const std::string& prefix) {
shards_.push_back(std::make_unique<SafeTensorsFile>());
RAD_TRY(shards_.back()->open(p));
for (const auto& t : shards_.back()->tensors()) {
if (t.dtype == RAD_DT_INVALID) {
RAD_ERR("%s: '%s' has dtype %s, which has no RAD equivalent", p.c_str(),
t.name.c_str(), t.dtype_str.c_str());
return RAD_E_DTYPE;
}
SrcTensor s;
s.name = prefix + t.name;
s.rad_dtype = t.dtype;
s.shape = t.shape; /* safetensors is already row-major */
s.data = t.data;
s.bytes = (int64_t)t.bytes;
index_.emplace(s.name, tensors_.size());
tensors_.push_back(std::move(s));
}
return RAD_OK;
}
namespace {
/* Every shard an index names, once each and in name order, or the one model.safetensors. */
int shard_list(const std::string& dir, const std::string& index, bool index_given,
std::vector<std::string>* out) {
std::unordered_map<std::string, std::string> map;
const int s = st_load_index(index, &map);
if (s == RAD_OK) {
for (auto& [t, f] : map)
if (std::find(out->begin(), out->end(), f) == out->end()) out->push_back(f);
std::sort(out->begin(), out->end());
for (auto& f : *out) f = dir + "/" + f;
return RAD_OK;
}
if (s != RAD_E_NOTFOUND || index_given) return s;
out->push_back(dir + "/model.safetensors");
return RAD_OK;
}
} /* namespace */
int Checkpoint::open_safetensors(const std::string& path) {
kind_ = SafeT;
/* One shard, an index, or the directory holding either: one namespace whichever it is. */
std::vector<std::string> shards;
const bool is_index = path.size() > 10 && path.compare(path.size() - 10, 10, "index.json") == 0;
const bool is_file = path.size() > 12 &&
path.compare(path.size() - 12, 12, ".safetensors") == 0;
if (is_file) {
shards.push_back(path);
} else {
RAD_TRY(shard_list(dir_, is_index ? path : dir_ + "/model.safetensors.index.json",
is_index, &shards));
}
for (const auto& sh : shards) RAD_TRY(add_shard(sh));
RAD_TRY(meta_from_config_json(dir_, &meta_));
RAD_TRY(meta_merge_generation_config(dir_, &meta_));
RAD_TRY(meta_merge_preprocessor_configs(dir_, &meta_));
/* FP8's block, where the checkpoint states one. */
if (const char* bs = meta_.get("quantization_config.weight_block_size")) {
long long r = 0, c = 0;
if (std::sscanf(bs, "%lld %lld", &r, &c) == 2 && r > 0 && c > 0) {
fp8_br_ = r;
fp8_bc_ = c;
}
}
meta_.finish();
return RAD_OK;
}
int Checkpoint::open(const std::string& path) {
path_ = path;
const bool gguf = path.size() > 5 && path.compare(path.size() - 5, 5, ".gguf") == 0;
dir_ = path;
const size_t slash = path.find_last_of('/');
auto ends = [&](const char* s) {
const size_t n = std::strlen(s);
return path.size() > n && path.compare(path.size() - n, n, s) == 0;
};
const bool is_file = gguf || ends(".safetensors") || ends("index.json");
if (is_file) dir_ = slash == std::string::npos ? "." : path.substr(0, slash);
return gguf ? open_gguf(path) : open_safetensors(path);
}
int Checkpoint::add_draft(const std::string& dir, const std::string& prefix) {
if (kind_ != SafeT) {
RAD_ERR("a drafter is merged into a safetensors target's namespace; %s is not one",
path_.c_str());
return RAD_E_UNSUPPORTED;
}
RAD_TRY(meta_merge_config_json(dir, prefix.empty() || prefix.back() != '.'
? prefix
: prefix.substr(0, prefix.size() - 1), &meta_));
std::vector<std::string> shards;
RAD_TRY(shard_list(dir, dir + "/model.safetensors.index.json", false, &shards));
for (const auto& sh : shards) RAD_TRY(add_shard(sh, prefix));
meta_.finish();
return RAD_OK;
}
const SrcTensor* Checkpoint::find(const std::string& n) const {
auto it = index_.find(n);
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. */
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 "
"-- rank 2 or more, with the stack on dim 0 -- has sub-tensors to take.",
declared, index, st.name.c_str(), st.shape.size());
return nullptr;
}
const int64_t n = st.shape[0];
if (index < 0 || index >= n) {
RAD_ERR("'%s' asks for sub-tensor %d of '%s', which holds %lld of them",
declared, index, st.name.c_str(), (long long)n);
return nullptr;
}
if (!st.data || st.bytes <= 0 || st.bytes % n != 0) {
RAD_ERR("'%s': '%s' is %lld byte(s) over %lld sub-tensor(s), which does not divide -- the "
"slice would straddle two of them",
declared, st.name.c_str(), (long long)st.bytes, (long long)n);
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. */
v.name = st.name + "[" + std::to_string(index) + "]";
v.ggml = st.ggml;
v.rad_dtype = st.rad_dtype;
v.shape.assign(st.shape.begin() + 1, st.shape.end());
v.bytes = st.bytes / n;
v.data = (const uint8_t*)st.data + (size_t)index * (size_t)v.bytes;
sliced_.push_back(std::move(v));
return &sliced_.back();
}
/* ================================================================== logical weights */
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) {
const size_t br = t.name.size() && t.name.back() == ']' ? t.name.rfind('[') : std::string::npos;
return br == std::string::npos ? t.name : t.name.substr(0, br);
}
bool ckpt_reads_any(const CkptWeight& w, const std::unordered_set<std::string>& names,
std::unordered_set<std::string>* hit) {
bool any = false;
for (const auto* list : { &w.pieces, &w.scales })
for (const SrcTensor* t : *list) {
if (!t) continue;
const std::string n = ckpt_tensor_of(*t);
if (names.count(n)) {
any = true;
if (hit) hit->insert(n);
}
}
return any;
}
int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, bool optional,
CkptWeight* out, std::string* why) {
auto refuse = [&](int rc, std::string m) {
if (why) *why = std::move(m);
return rc;
};
*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. */
std::vector<const RadNameMap*> maps;
for (const auto& nm : prog.name_map)
if (nm.declared && name == nm.declared) maps.push_back(&nm);
if (maps.empty()) return refuse(RAD_E_NOTFOUND, "the name map has no entry for it");
struct Src1 { const char* name; int index; };
std::vector<Src1> srcs;
for (const RadNameMap* pm : maps)
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.
*
* 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. */
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;
/* 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. */
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");
if (sc && !(sc = ck.slice(*sc, s1.index, name.c_str())))
return refuse(RAD_E_SHAPE, "its scale plane cannot be sliced at the same index");
}
if (!st) {
if (alternatives) continue;
if (optional) { out->pieces.clear(); break; }
return refuse(RAD_E_NOTFOUND, std::string("it needs checkpoint tensor '") + s1.name +
"', which is not in " + ck.path());
}
out->pieces.push_back(st);
out->scales.push_back(sc);
if (alternatives) break;
}
if (out->pieces.empty()) {
if (optional) return refuse(RAD_E_NOTFOUND, "none of its tensors is in the checkpoint");
std::string tried;
for (size_t k = 0; k < srcs.size(); ++k) tried += (k ? " or " : "") + std::string(srcs[k].name);
return refuse(RAD_E_NOTFOUND, "it needs one of " + tried + ", and " + ck.path() +
" holds none of them");
}
/* THE LOGICAL SHAPE: the pieces joined along concat_dim, every other extent agreeing. */
const SrcTensor& p0 = *out->pieces[0];
const int d = out->concat_dim;
if (p0.shape.empty() || p0.shape.size() > RAD_MAX_RANK || d < 0 || d >= (int)p0.shape.size())
return refuse(RAD_E_SHAPE, "'" + p0.name + "' cannot be joined along dim " +
std::to_string(d));
out->rank = (uint32_t)p0.shape.size();
for (uint32_t i = 0; i < out->rank; ++i) out->shape[i] = p0.shape[i];
for (size_t k = 1; k < out->pieces.size(); ++k) {
const SrcTensor& pk = *out->pieces[k];
bool fits = pk.shape.size() == p0.shape.size();
for (uint32_t i = 0; fits && i < out->rank; ++i)
if ((int)i != d && pk.shape[i] != p0.shape[i]) fits = false;
if (!fits)
return refuse(RAD_E_SHAPE, "'" + pk.name + "' and '" + p0.name +
"' do not join along dim " + std::to_string(d));
out->shape[d] += pk.shape[(size_t)d];
}
rad_enc_view(out->rank, out->shape, &out->rows, &out->cols);
/* THE ENCODING THE PIECES ARE, when it is trivial (spec §4.3). */
const uint32_t dt = p0.rad_dtype;
bool same = true, scaled = true, unscaled = true;
for (size_t k = 0; k < out->pieces.size(); ++k) {
if (out->pieces[k]->rad_dtype != dt) same = false;
if (out->scales[k]) unscaled = false; else scaled = false;
}
if (dt == RAD_DT_INVALID) {
out->why = std::string("'") + p0.name + "' is a GGUF " +
(gguf_dtype(p0.ggml) ? gguf_dtype(p0.ggml)->name : "block") + " tensor";
} else if (!same) {
out->why = "its pieces are stored in different dtypes";
} 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. */
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) {
const SrcTensor& pk = *out->pieces[k];
const SrcTensor& sk = *out->scales[k];
int64_t r = 0, c = 0;
rad_enc_view((uint32_t)pk.shape.size(), pk.shape.data(), &r, &c);
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);
if (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) + ", " +
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";
}
}
if (out->trivial) {
rad_enc_clear(&out->enc);
rad_enc_copy_str(out->enc.scheme, "affine");
rad_enc_add_plane(&out->enc, "codes", dt, 1, 1);
rad_enc_add_plane(&out->enc, "scale", sdt, br, bc);
}
} else if (!unscaled) {
out->why = "some of its pieces carry a scale plane and some do not";
} else if (dt == RAD_F8E4M3 || dt == RAD_F8E5M2) {
out->why = "it is FP8 with no scale plane beside it";
} else {
out->trivial = rad_dtype_bits(dt) >= 8;
if (out->trivial) out->enc = rad_enc_plain(dt);
else out->why = std::string("it is ") + rad_dtype_name(dt);
}
return RAD_OK;
}
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. */
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 };
int ggml_rows_f32(uint32_t type, const uint8_t* p, int64_t n, float* dst) {
auto half = [&](const uint8_t* q) { uint16_t h; std::memcpy(&h, q, 2); return rad_f16_to_f32(h); };
switch (type) {
case GGML_Q8_0:
for (int64_t b = 0; b < n / 32; ++b, p += 34) {
const float d = half(p);
for (int j = 0; j < 32; ++j) dst[b * 32 + j] = d * (float)(int8_t)p[2 + j];
}
return RAD_OK;
case GGML_Q4_0:
for (int64_t b = 0; b < n / 32; ++b, p += 18) {
const float d = half(p);
for (int j = 0; j < 16; ++j) {
dst[b * 32 + j] = d * (float)((p[2 + j] & 0x0F) - 8);
dst[b * 32 + j + 16] = d * (float)((p[2 + j] >> 4) - 8);
}
}
return RAD_OK;
case GGML_Q4_1:
for (int64_t b = 0; b < n / 32; ++b, p += 20) {
const float d = half(p), m = half(p + 2);
for (int j = 0; j < 16; ++j) {
dst[b * 32 + j] = d * (float)(p[4 + j] & 0x0F) + m;
dst[b * 32 + j + 16] = d * (float)(p[4 + j] >> 4) + m;
}
}
return RAD_OK;
case GGML_Q5_0:
for (int64_t b = 0; b < n / 32; ++b, p += 22) {
const float d = half(p);
uint32_t qh; std::memcpy(&qh, p + 2, 4);
for (int j = 0; j < 16; ++j) {
const int lo = (int)((p[6 + j] & 0x0F) | (((qh >> j) & 1u) << 4)) - 16;
const int hi = (int)((p[6 + j] >> 4) | (((qh >> (j + 16)) & 1u) << 4)) - 16;
dst[b * 32 + j] = d * (float)lo;
dst[b * 32 + j + 16] = d * (float)hi;
}
}
return RAD_OK;
case GGML_Q5_1:
for (int64_t b = 0; b < n / 32; ++b, p += 24) {
const float d = half(p), m = half(p + 2);
uint32_t qh; std::memcpy(&qh, p + 4, 4);
for (int j = 0; j < 16; ++j) {
const int lo = (int)((p[8 + j] & 0x0F) | (((qh >> j) & 1u) << 4));
const int hi = (int)((p[8 + j] >> 4) | (((qh >> (j + 16)) & 1u) << 4));
dst[b * 32 + j] = d * (float)lo + m;
dst[b * 32 + j + 16] = d * (float)hi + m;
}
}
return RAD_OK;
default:
return RAD_E_UNSUPPORTED;
}
}
/* Where flat element `i` of the joined tensor lives: which piece, and the element in it. A join
* along dim d repeats, for each index of the dims before d, every piece's [d..] extent in turn. */
struct Joined {
std::vector<int64_t> inner; /* each piece's elements per outer index */
int64_t total_inner = 0;
int n = 0;
void init(const std::vector<const SrcTensor*>& pieces, int d) {
n = (int)pieces.size();
inner.assign((size_t)n, 1);
total_inner = 0;
for (int k = 0; k < n; ++k) {
for (size_t i = (size_t)d; i < pieces[(size_t)k]->shape.size(); ++i)
inner[(size_t)k] *= pieces[(size_t)k]->shape[i];
total_inner += inner[(size_t)k];
}
}
/* Visit [a, b) as runs that lie in one piece: f(piece, element in it, count, at). */
template <class F> int walk(int64_t a, int64_t b, F f) const {
while (a < b) {
const int64_t o = a / total_inner;
int64_t w = a % total_inner, k = 0;
while (w >= inner[(size_t)k]) w -= inner[(size_t)k++];
const int64_t run = std::min<int64_t>(b - a, inner[(size_t)k] - w);
const int rc = f((int)k, o * inner[(size_t)k] + w, run);
if (rc < 0) return rc;
a += run;
}
return RAD_OK;
}
};
/* `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.rad_dtype == RAD_DT_INVALID) {
/* a GGUF block type: whole rows only, and 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);
return ggml_rows_f32(t.ggml, (const uint8_t*)t.data + (e / cols) * rb, n, out);
}
const uint8_t* p = (const uint8_t*)t.data;
switch (t.rad_dtype) {
case RAD_F32:
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. */
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;
std::memcpy(out + i, &u, 4);
}
return RAD_OK;
}
case RAD_F16: case RAD_F8E4M3: case RAD_F8E5M2:
case RAD_I8: case RAD_U8: case RAD_I16: case RAD_I32: case RAD_U32: case RAD_U16:
for (int64_t i = 0; i < n; ++i) out[i] = rad_load_f32(p, t.rad_dtype, e + i);
return RAD_OK;
default:
return RAD_E_UNSUPPORTED;
}
}
} /* namespace */
int ckpt_rows_f32(const CkptWeight& w, int64_t r0, int64_t nr, float* out, std::string* why) {
auto refuse = [&](int rc, std::string m) {
if (why) *why = std::move(m);
return rc;
};
if (r0 < 0 || nr < 0 || r0 + nr > w.rows) return refuse(RAD_E_SHAPE, "rows out of range");
Joined j;
j.init(w.pieces, w.concat_dim);
/* the runs come in order, so the cursor is the elements 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);
at += n;
return s;
});
if (rc < 0)
return refuse(rc, "'" + w.pieces[0]->name + "' is stored in a form that cannot be read "
"as f32 (" + (w.pieces[0]->rad_dtype == RAD_DT_INVALID
? std::string(gguf_dtype(w.pieces[0]->ggml)
? gguf_dtype(w.pieces[0]->ggml)->name
: "?")
: std::string(rad_dtype_name(w.pieces[0]->rad_dtype))) +
")");
/* FP8 IS ITS CODE TIMES ITS BLOCK'S SCALE: 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;
const int64_t bc = w.enc.n_planes > 1 ? w.enc.plane[1].block[1] : 128;
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 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)
out[(r - r0) * w.cols + c] *=
rad_load_f32(sk.data, sk.rad_dtype, ((r - base) / br) * sc + c / bc);
base += pr;
}
}
return RAD_OK;
}
int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* dst,
std::string* why) {
auto refuse = [&](int rc, std::string m) {
if (why) *why = std::move(m);
return rc;
};
if (!w.trivial || k < 0 || k >= w.enc.n_planes)
return refuse(RAD_E_STATE, "not a plane of a trivial encoding");
const std::vector<const SrcTensor*>& src = k == 0 ? w.pieces : w.scales;
int64_t pr = 0, pc = 0;
rad_enc_plane_dims(&w.enc.plane[k], w.rows, w.cols, &pr, &pc);
if (r0 < 0 || nr < 0 || r0 + nr > pr) return refuse(RAD_E_SHAPE, "plane rows out of range");
const uint32_t dt = w.enc.plane[k].dtype;
const int64_t eb = rad_dtype_bits(dt) / 8;
uint8_t* o = (uint8_t*)dst;
if (k == 0) {
/* the codes: the pieces joined, bytes as they are */
Joined j;
j.init(src, w.concat_dim);
return j.walk(r0 * pc, (r0 + nr) * pc, [&](int p, int64_t e, int64_t n) {
std::memcpy(o, (const uint8_t*)src[(size_t)p]->data + e * eb, (size_t)(n * eb));
o += n * eb;
return RAD_OK;
});
}
/* an FP8 scale plane: the pieces' scale rows one after another */
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);
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,
(size_t)((hi - lo) * scl * eb));
o += (hi - lo) * scl * eb;
}
base += sr;
}
return RAD_OK;
}
} /* namespace rad */
-169
View File
@@ -1,169 +0,0 @@
/* 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:
*
* - 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.
*
* Trivial is the set spec §4.3 names: plain f32, f16 and bf16 (GGUF's too), and block-scaled
* FP8, where `X.weight_scale_inv` is the scale plane of `X.weight`. Anything else is a weight
* whose served form needs quantisation work, which a recipe does ahead of time.
*/
#pragma once
#include "../rad_internal.h"
#include "../rad_core.h"
#include "safetensors.h"
#include "../text/gguf.h"
#include <deque>
#include <memory>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
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. */
struct SrcTensor {
std::string name;
uint32_t ggml = 0;
uint32_t rad_dtype = RAD_DT_INVALID; /* INVALID: a GGUF block type */
std::vector<int64_t> shape; /* row-major */
const void* data = nullptr;
int64_t bytes = 0;
int64_t numel() const {
int64_t n = 1;
for (int64_t d : shape) n *= d;
return shape.empty() ? 0 : n;
}
};
/* ================================================================== metadata */
/* The model's metadata as RadModelMeta, with the strings it points at owned here. */
struct MetaOwn {
std::string arch, name, quant;
std::vector<std::string> keys, vals;
std::vector<const char*> kp, vp;
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. */
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. */
void finish();
};
int meta_from_config_json(const std::string& dir, MetaOwn* out);
int meta_merge_config_json(const std::string& dir, const std::string& prefix, MetaOwn* out);
int meta_merge_generation_config(const std::string& dir, MetaOwn* out);
int meta_merge_preprocessor_configs(const std::string& dir, MetaOwn* out);
int meta_from_gguf(GgufFile& g, MetaOwn* out);
/* ================================================================== the checkpoint */
class Checkpoint {
public:
Checkpoint() = default;
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. */
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. */
int add_draft(const std::string& dir, const std::string& prefix);
const SrcTensor* find(const std::string& n) const;
const std::vector<SrcTensor>& tensors() const { return tensors_; }
bool is_gguf() const { return kind_ == Gguf; }
GgufFile& gguf() { return gguf_; }
const std::string& path() const { return path_; }
const std::string& dir() const { return dir_; } /* where config.json and tokenizer.json sit */
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. */
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_; }
private:
int add_shard(const std::string& p, const std::string& prefix = "");
int open_safetensors(const std::string& path);
int open_gguf(const std::string& path);
enum Kind { None, Gguf, SafeT } kind_ = None;
std::string path_, dir_;
GgufFile gguf_;
MetaOwn meta_;
std::vector<std::unique_ptr<SafeTensorsFile>> shards_;
std::vector<SrcTensor> tensors_;
std::unordered_map<std::string, size_t> index_;
std::deque<SrcTensor> sliced_; /* views; a deque never moves what it holds */
int64_t fp8_br_ = 128, fp8_bc_ = 128;
};
/* ================================================================== logical weights */
/* A declared weight's source, as the name map resolves it: pieces joined along `concat_dim`, and
* for block-scaled FP8 each piece's scale plane beside it. */
struct CkptWeight {
std::string name; /* the logical (declared) name */
std::vector<const SrcTensor*> pieces; /* the codes, in concatenation order */
std::vector<const SrcTensor*> scales; /* FP8 only: one a piece */
int concat_dim = 0;
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. */
bool trivial = false;
RadEncoding enc{};
std::string why;
};
/* Resolve `name` through `prog`'s name map. RAD_OK; RAD_E_NOTFOUND when the name map has no entry
* for it yet (declare may add one later) or, for an optional weight, none of its tensors is
* there; anything else with the reason in `why`. */
int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, bool optional,
CkptWeight* out, std::string* why);
/* The checkpoint tensor a piece or scale reads: its name without the "[index]" a slice of a
* stacked tensor carries, so an expert reads the stack it was cut from. */
std::string ckpt_tensor_of(const SrcTensor& t);
/* Whether `w` reads any tensor named in `names` (checkpoint names, as ckpt_tensor_of gives them),
* through a piece or a scale. Each name it reads is added to `hit` when that is given. */
bool ckpt_reads_any(const CkptWeight& w, const std::unordered_set<std::string>& names,
std::unordered_set<std::string>* hit = nullptr);
/* 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 `w`, in the plane's own elements, dense into
* `dst`: the bytes a container entry holds for it. */
int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* dst,
std::string* why);
} /* namespace rad */
-464
View File
@@ -1,464 +0,0 @@
/* encoding.cpp -- decoding a weight encoding to f32 and cutting its planes. See encoding.h, and
* abi/rad_encoding.h for what each plane means. */
#include "encoding.h"
#include "rad_plugin.h"
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <mutex>
#include <vector>
namespace rad {
void enc_view(const RadEncoding& e, int64_t rows, int64_t cols, const void* const* data,
EncodedView* v) {
v->enc = e;
v->rows = rows;
v->cols = cols;
for (int i = 0; i < RAD_ENC_MAX_PLANES; ++i) v->plane[i] = PlaneView{};
for (int i = 0; i < e.n_planes && i < RAD_ENC_MAX_PLANES; ++i) {
PlaneView& p = v->plane[i];
rad_enc_plane_dims(&e.plane[i], rows, cols, &p.rows, &p.cols);
p.row_bytes = rad_enc_row_bytes(e.plane[i].dtype, p.cols);
p.data = data ? data[i] : nullptr;
}
}
void fwht_inplace(float* 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];
v[j] = a + b;
v[j + h] = a - b;
}
}
std::string enc_name(const RadEncoding& e) {
char buf[512];
rad_enc_format(&e, buf, sizeof buf);
return buf;
}
namespace {
std::string fmt(const char* f, long long a = 0, long long b = 0, long long c = 0) {
char m[256];
std::snprintf(m, sizeof m, f, a, b, c);
return m;
}
/* A plane and the means to read element (i, j) of it as f32. */
struct Rd {
const PlaneView* v = nullptr;
const RadEncPlane* d = nullptr;
explicit operator bool() const { return v != nullptr; }
float at(int64_t i, int64_t j) const {
return rad_load_f32((const uint8_t*)v->data + i * v->row_bytes, d->dtype, j);
}
/* The element of a TILED plane covering logical (r, c). */
float cover(int64_t r, int64_t c) const {
return at(d->block[0] > 0 ? r / d->block[0] : 0, d->block[1] > 0 ? c / d->block[1] : 0);
}
};
/* Row `r` of a code plane as f32, its dtype resolved once for the row rather than per element.
* The values are rad_load_f32's: the same nibble order, the same sign extension. */
void codes_row(const Rd& p, int64_t r, int64_t n, float* out) {
const uint8_t* b = (const uint8_t*)p.v->data + r * p.v->row_bytes;
switch (p.d->dtype) {
case RAD_I4:
for (int64_t i = 0; i < n; ++i) {
const int c = (b[i >> 1] >> ((i & 1) * 4)) & 15;
out[i] = (float)((c ^ 8) - 8);
}
return;
case RAD_U4:
for (int64_t i = 0; i < n; ++i) out[i] = (float)((b[i >> 1] >> ((i & 1) * 4)) & 15);
return;
case RAD_I8:
for (int64_t i = 0; i < n; ++i) out[i] = (float)(int8_t)b[i];
return;
case RAD_U8:
for (int64_t i = 0; i < n; ++i) out[i] = (float)b[i];
return;
case RAD_F8E4M3:
for (int64_t i = 0; i < n; ++i) out[i] = rad_fp8e4m3_to_f32(b[i]);
return;
default:
for (int64_t i = 0; i < n; ++i) out[i] = rad_load_f32(b, p.d->dtype, i);
return;
}
}
Rd plane(const EncodedView& v, int idx) {
Rd r;
if (idx >= 0) {
r.v = &v.plane[idx];
r.d = &v.enc.plane[idx];
}
return r;
}
/* Undo a "givens" transform on one row in place: w = v . G_S^T ... G_1^T . D^-1. */
int givens_inverse(const EncodedView& v, float* row, std::string* why) {
const Rd pairs = plane(v, rad_enc_find(&v.enc, "t.pairs"));
const Rd angle = plane(v, rad_enc_find(&v.enc, "t.angle"));
const Rd scale = plane(v, rad_enc_find(&v.enc, "t.scale"));
const int64_t S = pairs.v->rows, K = v.cols;
if (pairs.v->cols != K || angle.v->rows != S || angle.v->cols != K / 2 || (K & 1) ||
(scale && (scale.v->rows != 1 || scale.v->cols != K))) {
if (why) *why = fmt("a givens transform's tables do not fit a %lld-column row", K);
return RAD_E_SHAPE;
}
for (int64_t s = S - 1; s >= 0; --s)
for (int64_t p = 0; p < K / 2; ++p) {
const int64_t a = (int64_t)pairs.at(s, 2 * p), b = (int64_t)pairs.at(s, 2 * p + 1);
if (a < 0 || a >= K || b < 0 || b >= K || a == b) {
if (why) *why = fmt("givens stage %lld pairs columns %lld and %lld", s, a, b);
return RAD_E_SHAPE;
}
const double t = angle.at(s, p), c = std::cos(t), sn = std::sin(t);
const double x = row[a], y = row[b];
row[a] = (float)(c * x - sn * y);
row[b] = (float)(sn * x + c * y);
}
if (scale)
for (int64_t k = 0; k < K; ++k) row[k] /= scale.at(0, k);
return RAD_OK;
}
} /* namespace */
namespace {
std::mutex g_dec_mu;
std::vector<RadQuantDecodeFn> g_decoders;
} // namespace
void enc_add_decoder(RadQuantDecodeFn fn) {
if (!fn) return;
std::lock_guard<std::mutex> lk(g_dec_mu);
g_decoders.push_back(fn);
}
void enc_remove_decoder(RadQuantDecodeFn fn) {
std::lock_guard<std::mutex> lk(g_dec_mu);
g_decoders.erase(std::remove(g_decoders.begin(), g_decoders.end(), fn), g_decoders.end());
}
int enc_decode_rows(const EncodedView& v, int64_t row0, int64_t n, float* out, std::string* why) {
const RadEncoding& e = v.enc;
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. */
std::vector<RadQuantDecodeFn> fns;
{
std::lock_guard<std::mutex> lk(g_dec_mu);
fns = g_decoders;
}
RadQuantWeight w{};
w.name = "";
w.rank = 2;
w.shape[0] = v.rows;
w.shape[1] = v.cols;
w.rows = v.rows;
w.cols = v.cols;
w.layer = w.expert = -1;
const void* planes[RAD_ENC_MAX_PLANES] = {};
for (int k = 0; k < e.n_planes && k < RAD_ENC_MAX_PLANES; ++k) planes[k] = v.plane[k].data;
for (RadQuantDecodeFn fn : fns) {
const int st = fn(&e, &w, planes, row0, n, out);
if (st == RAD_E_UNSUPPORTED) continue;
if (st != RAD_OK && why)
*why = "the quantiser that decodes scheme '" + std::string(e.scheme) +
"' refused: " + rad_strerror(st);
return st;
}
if (why) *why = "scheme '" + std::string(e.scheme) + "' is a quantiser's own, and no "
"loaded quantiser decodes it; the core decodes only plain and affine";
return RAD_E_UNSUPPORTED;
}
if (!rad_enc_valid(&e)) {
if (why) *why = "the encoding " + enc_name(e) + " is not well formed";
return RAD_E_FORMAT;
}
const int64_t fw = rad_enc_fwht(&e);
if (fw > 0 && v.cols % fw != 0) {
if (why) *why = fmt("an fwht%lld transform does not divide a %lld-column row", fw, v.cols);
return RAD_E_SHAPE;
}
if (row0 < 0 || n < 0 || row0 + n > v.rows) return RAD_E_SHAPE;
const Rd codes = plane(v, 0);
const Rd grid = plane(v, rad_enc_find(&e, "grid"));
const Rd table = plane(v, rad_enc_find(&e, "table"));
const Rd signs = plane(v, rad_enc_find(&e, "signs"));
const Rd zero = plane(v, rad_enc_find(&e, "zero"));
std::vector<Rd> scales, mins;
for (int lv = 0;; ++lv) {
const int i = rad_enc_find_level(&e, "scale", lv);
if (i < 0) break;
scales.push_back(plane(v, i));
}
for (int lv = 0;; ++lv) {
const int i = rad_enc_find_level(&e, "min", lv);
if (i < 0) break;
mins.push_back(plane(v, i));
}
const int64_t V = rad_enc_code_width(&e);
const bool perm = !std::strcmp(e.transform, "perm");
const bool giv = !std::strcmp(e.transform, "givens");
const Rd pm = plane(v, perm ? rad_enc_find(&e, "t.perm") : -1);
if (perm && (pm.v->rows != 1 || pm.v->cols != v.cols)) {
if (why) *why = fmt("a perm transform's table is not one entry a column (%lld)", v.cols);
return RAD_E_SHAPE;
}
std::vector<float> tmp(perm ? (size_t)v.cols : 0);
/* 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. */
const bool direct = V <= 1 && !table && !signs && !zero && mins.empty() && scales.size() <= 1;
for (int64_t i = 0; i < n; ++i) {
const int64_t r = row0 + i;
float* o = out + i * v.cols;
if (direct) {
codes_row(codes, r, v.cols, o);
if (!scales.empty()) {
const Rd& s = scales[0];
const int64_t bc = s.d->block[1] > 0 ? s.d->block[1] : v.cols;
const int64_t sr = s.d->block[0] > 0 ? r / s.d->block[0] : 0;
for (int64_t c0 = 0; c0 < v.cols; c0 += bc) {
const float k = s.at(sr, s.d->block[1] > 0 ? c0 / bc : 0);
const int64_t c1 = std::min(c0 + bc, v.cols);
for (int64_t c = c0; c < c1; ++c) o[c] *= k;
}
}
}
for (int64_t c = 0; !direct && c < v.cols; ++c) {
float q;
if (V > 1) {
const int64_t code = (int64_t)codes.at(r, c / V);
if (code < 0 || code >= grid.v->rows) {
if (why) *why = fmt("row %lld: code %lld is outside a %lld-entry grid", r, code,
grid.v->rows);
return RAD_E_FORMAT;
}
q = grid.at(code, c % V);
} else {
q = codes.at(r, c);
if (table) {
const int64_t code = (int64_t)q;
if (code < 0 || code >= table.v->cols) {
if (why) *why = fmt("row %lld: code %lld is outside a %lld-entry table", r,
code, table.v->cols);
return RAD_E_FORMAT;
}
q = table.at(0, code);
}
}
if (signs && signs.cover(r, c) != 0.0f) q = -q;
if (zero) q -= zero.cover(r, c);
for (const Rd& s : scales) q *= s.cover(r, c);
if (!mins.empty()) {
float m = 1.0f;
for (const Rd& s : mins) m *= s.cover(r, c);
q -= m;
}
o[c] = q;
}
if (fw > 0) {
for (int64_t g = 0; g < v.cols; g += fw) fwht_inplace(o + g, fw);
} else if (perm) {
for (int64_t c = 0; c < v.cols; ++c) {
const int64_t to = (int64_t)pm.at(0, c);
if (to < 0 || to >= v.cols) {
if (why) *why = fmt("perm sends column %lld to %lld", c, to);
return RAD_E_FORMAT;
}
tmp[(size_t)to] = o[c];
}
std::memcpy(o, tmp.data(), (size_t)v.cols * sizeof(float));
} else if (giv) {
const int st = givens_inverse(v, o, why);
if (st != RAD_OK) return st;
}
}
return RAD_OK;
}
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) {
auto refuse = [&](std::string m) {
if (why) *why = std::move(m);
return RAD_E_SHAPE;
};
if (n_sel < 1 || n_sel > e.n_planes) return refuse("no planes are selected");
if (n_sel == 1) {
const RadEncPlane& p = e.plane[sel[0]];
const int64_t r = rows[0], c = cols[0];
if (r * c != n)
return refuse("its plane holds " + std::to_string(r * c) + " elements and the reader "
"wants " + std::to_string(n));
const int64_t rb = rad_enc_row_bytes(p.dtype, c);
const uint8_t* src = (const uint8_t*)data[0];
if (p.dtype == dt && rb == rad_dtype_bytes(dt, c)) {
std::memcpy(out, src, (size_t)(r * rb));
return RAD_OK;
}
for (int64_t i = 0; i < r; ++i)
for (int64_t j = 0; j < c; ++j)
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. */
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 &&
e.plane[sel[1]].kind == RAD_PLANE_TABLE && e.plane[sel[1]].extent[0] == 1) {
const RadEncPlane& pc = e.plane[sel[0]];
const RadEncPlane& pt = e.plane[sel[1]];
const int64_t r = rows[0], c = cols[0], entries = pt.extent[1];
if (r * c != n)
return refuse("its codes hold " + std::to_string(r * c) + " elements and the reader "
"wants " + std::to_string(n));
const int64_t rb = rad_enc_row_bytes(pc.dtype, c);
const uint8_t* src = (const uint8_t*)data[0];
for (int64_t i = 0; i < r; ++i)
for (int64_t j = 0; j < c; ++j) {
const int64_t code = (int64_t)rad_load_f32(src + i * rb, pc.dtype, j);
if (code < 0 || code >= entries)
return refuse("code " + std::to_string(code) + " indexes a table of " +
std::to_string(entries));
rad_store_f32(out, dt, i * c + j, rad_load_f32(data[1], pt.dtype, code));
}
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. */
if (n_sel >= 2 && !std::strcmp(e.plane[sel[0]].role, "scale")) {
bool chain = true;
for (int k = 0; k < n_sel && chain; ++k) {
const RadEncPlane& p = e.plane[sel[k]];
chain = p.kind == RAD_PLANE_TILED && rad_enc_role_in_chain(p.role, "scale") &&
(k == 0 || std::strcmp(p.role, "scale") != 0);
}
if (chain) {
const RadEncPlane& p0 = e.plane[sel[0]];
const int64_t r = rows[0], c = cols[0];
if (r * c != n)
return refuse("its scales hold " + std::to_string(r * c) + " elements and the "
"reader wants " + std::to_string(n));
auto covers = [](int64_t b0, int64_t b) { return b <= 0 || (b0 > 0 && b % b0 == 0); };
for (int k = 1; k < n_sel; ++k) {
const RadEncPlane& p = e.plane[sel[k]];
if (!covers(p0.block[0], p.block[0]) || !covers(p0.block[1], p.block[1]))
return refuse(std::string("its '") + p.role + "' level does not cover whole '" +
p0.role + "' blocks");
}
const int64_t rb0 = rad_enc_row_bytes(p0.dtype, c);
for (int64_t i = 0; i < r; ++i)
for (int64_t j = 0; j < c; ++j) {
float v = rad_load_f32((const uint8_t*)data[0] + i * rb0, p0.dtype, j);
for (int k = 1; k < n_sel; ++k) {
const RadEncPlane& p = e.plane[sel[k]];
const int64_t li = p.block[0] > 0 ? i * p0.block[0] / p.block[0] : 0;
const int64_t lj = p.block[1] > 0 ? j * p0.block[1] / p.block[1] : 0;
if (li >= rows[k] || lj >= cols[k])
return refuse(std::string("its '") + p.role + "' level is " +
std::to_string(rows[k]) + "x" +
std::to_string(cols[k]) + " and does not reach scale " +
std::to_string(i) + "," + std::to_string(j));
v *= rad_load_f32((const uint8_t*)data[k] +
li * rad_enc_row_bytes(p.dtype, cols[k]),
p.dtype, lj);
}
rad_store_f32(out, dt, i * c + j, v);
}
return RAD_OK;
}
}
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. */
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)
return refuse("its planes do not tile the " + std::to_string(n) +
" elements the reader wants");
const int64_t c = n / r;
const void* d[RAD_ENC_MAX_PLANES] = {};
for (int k = 0; k < n_sel; ++k) d[sel[k]] = data[k];
EncodedView v;
enc_view(e, r, c, d, &v);
std::vector<float> f((size_t)n);
const int rc = enc_decode_rows(v, 0, r, f.data(), why);
if (rc != RAD_OK) return rc;
for (int64_t i = 0; i < n; ++i) rad_store_f32(out, dt, i, f[(size_t)i]);
return RAD_OK;
}
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) {
int64_t pr = 0, pc = 0;
rad_enc_plane_dims(&p, rows, cols, &pr, &pc);
if (p.kind == RAD_PLANE_TABLE) { /* every slice carries the whole table */
*out = PlaneRect{ 0, pr, 0, pc };
return RAD_OK;
}
auto cut = [&](int64_t lo, int64_t hi, int64_t extent, int64_t b, int64_t pext,
int64_t* e0, int64_t* en, const char* axis) -> bool {
if (lo < 0 || hi > extent || lo > hi) {
if (why) *why = std::string(axis) + fmt(" [%lld, %lld) is outside the weight's %lld",
lo, hi, extent);
return false;
}
if (b <= 0) { /* one element covers the whole extent: every slice has it */
*e0 = 0;
*en = pext;
return true;
}
if (lo % b != 0 || (hi % b != 0 && hi != extent)) {
if (why) *why = std::string(axis) + fmt(" [%lld, %lld) splits ", lo, hi) + "the '" +
p.role + fmt("' plane's %lld-wide blocks", b);
return false;
}
*e0 = lo / b;
*en = (hi + b - 1) / b - lo / b;
return true;
};
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. */
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) + " '" +
p.role + "' plane is not on a byte";
return RAD_E_SHAPE;
}
*out = r;
return RAD_OK;
}
} /* namespace rad */
-89
View File
@@ -1,89 +0,0 @@
/* encoding.h -- the core's half of a weight encoding: decoding one 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.
*/
#pragma once
#include "../rad_internal.h"
#include "rad_encoding.h"
#include "rad_quant.h"
#include <string>
namespace rad {
/* One whole plane of a weight, canonical: row-major, `row_bytes` a row. */
struct PlaneView {
const void* data = nullptr;
int64_t rows = 0, cols = 0; /* elements */
int64_t row_bytes = 0;
};
/* The planes of an encoding over a [rows, cols] weight, in the encoding's order. */
struct EncodedView {
RadEncoding enc{};
int64_t rows = 0, cols = 0; /* the logical view */
PlaneView plane[RAD_ENC_MAX_PLANES];
};
/* Fill `v`'s plane geometry for a weight of [rows, cols] in `e`, pointing plane i at `data[i]`. */
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. */
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. */
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. */
void fwht_inplace(float* v, int64_t n);
/* The canonical spelling of an encoding (rad_enc_format), as a string. */
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. */
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);
/* ================================================================== slicing */
/* A rectangle of a plane, in that plane's elements. */
struct PlaneRect {
int64_t row0 = 0, rows = 0;
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. */
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);
} /* namespace rad */
-417
View File
@@ -1,417 +0,0 @@
/* 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.
*/
#include "imatrix.h"
#include <cerrno>
#include <cstring>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
namespace rad {
namespace {
/* GGUF's value type tags. Only what a walker needs 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
};
constexpr uint32_t GGML_TYPE_F32 = 0;
struct Cursor {
const uint8_t* p;
const uint8_t* end;
bool ok = true;
bool take(uint64_t n, const void** out = nullptr) {
if (!ok || (uint64_t)(end - p) < n) { ok = false; return false; }
if (out) *out = p;
p += n;
return true;
}
template <class T> bool get(T* out) {
const void* q = nullptr;
if (!take(sizeof(T), &q)) return false;
std::memcpy(out, q, sizeof(T));
return true;
}
bool str(std::string* out) {
uint64_t n = 0;
if (!get(&n)) return false;
const void* q = nullptr;
if (!take(n, &q)) return false;
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. */
bool skip_value(uint32_t type) {
switch (type) {
case GT_U8: case GT_I8: case GT_BOOL: return take(1);
case GT_U16: case GT_I16: return take(2);
case GT_U32: case GT_I32: case GT_F32: return take(4);
case GT_U64: case GT_I64: case GT_F64: return take(8);
case GT_STR: return str(nullptr);
case GT_ARR: {
uint32_t et = 0; uint64_t n = 0;
if (!get(&et) || !get(&n)) return false;
for (uint64_t i = 0; i < n && ok; ++i) if (!skip_value(et)) return false;
return ok;
}
default: ok = false; return false;
}
}
};
} /* namespace */
ImatrixFile::~ImatrixFile() { close(); }
void ImatrixFile::close() {
if (map_) ::munmap(map_, (size_t)map_bytes_);
if (fd_ >= 0) ::close(fd_);
map_ = nullptr; map_bytes_ = 0; fd_ = -1;
gguf_ = false;
entries_.clear(); index_.clear(); owned_.clear();
dataset_.clear(); path_.clear();
chunk_count_ = chunk_size_ = 0;
}
int ImatrixFile::open(const std::string& path) {
close();
path_ = path;
fd_ = ::open(path.c_str(), O_RDONLY | O_CLOEXEC);
if (fd_ < 0) { RAD_ERR("%s: %s", path.c_str(), std::strerror(errno)); return RAD_E_IO; }
struct stat st{};
if (::fstat(fd_, &st) != 0) { RAD_ERR("%s: %s", path.c_str(), std::strerror(errno));
close(); return RAD_E_IO; }
map_bytes_ = (uint64_t)st.st_size;
if (map_bytes_ < 8) {
RAD_ERR("%s: %llu bytes -- too short to be an imatrix", path.c_str(),
(unsigned long long)map_bytes_);
close();
return RAD_E_FORMAT;
}
void* m = ::mmap(nullptr, (size_t)map_bytes_, PROT_READ, MAP_PRIVATE, fd_, 0);
if (m == MAP_FAILED) { RAD_ERR("%s: mmap: %s", path.c_str(), std::strerror(errno));
close(); return RAD_E_IO; }
map_ = (uint8_t*)m;
int s;
if (std::memcmp(map_, "GGUF", 4) == 0) { gguf_ = true; s = read_gguf(map_, map_bytes_); }
else { gguf_ = false; s = read_legacy(map_, map_bytes_); }
if (s < 0) { close(); return s; }
for (size_t i = 0; i < entries_.size(); ++i) index_.emplace(entries_[i].name, i);
RAD_INFO("imatrix %s: %s, %zu tensor(s)%s", path.c_str(), gguf_ ? "gguf" : "legacy",
entries_.size(),
chunk_count_ ? fmt(", %lld chunks of %lld", (long long)chunk_count_,
(long long)chunk_size_).c_str() : "");
return RAD_OK;
}
/* ------------------------------------------------------------------ legacy */
int ImatrixFile::read_legacy(const uint8_t* p, uint64_t n) {
Cursor c{ p, p + n };
int32_t n_entries = 0;
if (!c.get(&n_entries) || n_entries <= 0 || n_entries > (1 << 20)) {
RAD_ERR("%s: not a legacy imatrix (entry count %d)", path_.c_str(), n_entries);
return RAD_E_FORMAT;
}
owned_.reserve((size_t)n_entries);
entries_.reserve((size_t)n_entries);
for (int32_t i = 0; i < n_entries; ++i) {
int32_t name_len = 0;
if (!c.get(&name_len) || name_len < 0 || (uint64_t)name_len > (uint64_t)(c.end - c.p)) {
RAD_ERR("%s: entry %d has a %d-byte name, which does not fit", path_.c_str(), i,
name_len);
return RAD_E_FORMAT;
}
const void* np = nullptr;
if (!c.take((uint64_t)name_len, &np)) break;
std::string name((const char*)np, (size_t)name_len);
int32_t ncall = 0, nval = 0;
if (!c.get(&ncall) || !c.get(&nval) || nval < 0) {
RAD_ERR("%s: entry '%s' is truncated", path_.c_str(), name.c_str());
return RAD_E_FORMAT;
}
const void* vp = nullptr;
if (!c.take((uint64_t)nval * sizeof(float), &vp)) {
RAD_ERR("%s: entry '%s' claims %d values, which run past the end of the file",
path_.c_str(), name.c_str(), nval);
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. */
owned_.emplace_back((size_t)nval);
std::memcpy(owned_.back().data(), vp, (size_t)nval * sizeof(float));
ImatrixEntry e;
e.name = std::move(name);
e.sum2 = owned_.back().data();
e.counts = nullptr;
e.cols = nval;
e.n_expert = 1;
e.ncall = ncall;
entries_.push_back(std::move(e));
}
if (!c.ok && entries_.empty()) {
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. */
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());
return RAD_OK;
}
/* ------------------------------------------------------------------ gguf */
int ImatrixFile::read_gguf(const uint8_t* p, uint64_t n) {
Cursor c{ p + 4, p + n };
uint32_t version = 0;
uint64_t n_tensors = 0, n_kv = 0;
if (!c.get(&version) || !c.get(&n_tensors) || !c.get(&n_kv)) {
RAD_ERR("%s: truncated GGUF header", path_.c_str());
return RAD_E_FORMAT;
}
if (version != 3) {
RAD_ERR("%s: GGUF version %u; this reader handles 3", path_.c_str(), version);
return RAD_E_FORMAT;
}
uint64_t alignment = 32; /* GGUF's default when general.alignment is absent */
for (uint64_t i = 0; i < n_kv; ++i) {
std::string key;
uint32_t type = 0;
if (!c.str(&key) || !c.get(&type)) {
RAD_ERR("%s: truncated at KV %llu", path_.c_str(), (unsigned long long)i);
return RAD_E_FORMAT;
}
if (key == "general.alignment" && type == GT_U32) {
uint32_t a = 0;
if (!c.get(&a)) break;
if (a == 0 || (a & (a - 1)) != 0) {
RAD_ERR("%s: general.alignment is %u, which is not a power of two", path_.c_str(), a);
return RAD_E_FORMAT;
}
alignment = a;
} else if (key == "imatrix.chunk_count" && type == GT_U32) {
uint32_t v = 0; if (!c.get(&v)) break; chunk_count_ = v;
} else if (key == "imatrix.chunk_size" && type == GT_U32) {
uint32_t v = 0; if (!c.get(&v)) break; chunk_size_ = v;
} else if (key == "imatrix.datasets" && type == GT_ARR) {
uint32_t et = 0; uint64_t cnt = 0;
if (!c.get(&et) || !c.get(&cnt)) break;
for (uint64_t k = 0; k < cnt && c.ok; ++k) {
if (et == GT_STR) { std::string s; if (!c.str(&s)) break;
if (dataset_.empty()) dataset_ = s; }
else if (!c.skip_value(et)) break;
}
} else if (!c.skip_value(type)) {
RAD_ERR("%s: KV '%s' has type %u, which this walker does not know how to step over",
path_.c_str(), key.c_str(), type);
return RAD_E_FORMAT;
}
}
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. */
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 "
"cannot hold that many tensor infos", path_.c_str(),
(unsigned long long)n_tensors, (unsigned long long)(c.end - c.p));
return RAD_E_FORMAT;
}
struct Info { std::string name; std::vector<uint64_t> dims; uint32_t type; uint64_t off; };
std::vector<Info> infos;
infos.reserve((size_t)n_tensors);
for (uint64_t i = 0; i < n_tensors; ++i) {
Info t{};
uint32_t nd = 0;
if (!c.str(&t.name) || !c.get(&nd) || nd > 4) {
RAD_ERR("%s: truncated or malformed tensor info %llu", path_.c_str(),
(unsigned long long)i);
return RAD_E_FORMAT;
}
t.dims.resize(nd);
for (uint32_t d = 0; d < nd; ++d) if (!c.get(&t.dims[d])) break;
if (!c.get(&t.type) || !c.get(&t.off)) {
RAD_ERR("%s: truncated tensor info for '%s'", path_.c_str(), t.name.c_str());
return RAD_E_FORMAT;
}
infos.push_back(std::move(t));
}
const uint64_t here = (uint64_t)(c.p - p);
const uint64_t data_start = (here + alignment - 1) / alignment * alignment;
if (data_start > n) {
RAD_ERR("%s: the data section starts past the end of the file", path_.c_str());
return RAD_E_FORMAT;
}
/* Join `<base>.in_sum2` with `<base>.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. */
std::unordered_map<std::string, size_t> by_base;
struct Held { uint64_t sum2 = 0, counts = 0; };
std::vector<Held> held;
const uint64_t data_floats = (n - data_start) / sizeof(float);
for (const Info& t : infos) {
const bool is_sum2 = t.name.size() > 8 && t.name.compare(t.name.size() - 8, 8, ".in_sum2") == 0;
const bool is_counts = t.name.size() > 7 && t.name.compare(t.name.size() - 7, 7, ".counts") == 0;
if (!is_sum2 && !is_counts) continue;
if (t.type != GGML_TYPE_F32) {
RAD_WARN("%s: '%s' is ggml type %u, not f32 -- ignored", path_.c_str(),
t.name.c_str(), t.type);
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. */
uint64_t numel = 1;
bool fits = true;
for (uint64_t d : t.dims) if (d == 0) numel = 0;
for (uint64_t d : t.dims) {
if (numel == 0) break;
if (numel > data_floats / d) { fits = false; break; }
numel *= d;
}
const uint64_t bytes = numel * sizeof(float);
if (!fits || t.off > n - data_start || bytes > n - data_start - t.off) {
RAD_ERR("%s: '%s' runs past the end of the file", path_.c_str(), t.name.c_str());
return RAD_E_FORMAT;
}
const float* fp = (const float*)(p + data_start + t.off);
std::string base = t.name.substr(0, t.name.size() - (is_sum2 ? 8 : 7));
auto it = by_base.find(base);
if (it == by_base.end()) {
ImatrixEntry e;
e.name = base;
by_base.emplace(base, entries_.size());
it = by_base.find(base);
entries_.push_back(std::move(e));
held.emplace_back();
}
ImatrixEntry& e = entries_[it->second];
if (is_sum2) {
e.sum2 = fp;
e.cols = t.dims.empty() ? 0 : (int64_t)t.dims[0];
e.n_expert = t.dims.size() > 1 ? (int64_t)t.dims[1] : 1;
held[it->second].sum2 = numel;
} else {
e.counts = fp;
held[it->second].counts = numel;
}
}
/* 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. */
std::vector<ImatrixEntry> 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. */
if (!e.sum2 || e.cols <= 0) {
RAD_WARN("%s: '%s' has counts but no .in_sum2 -- dropped", path_.c_str(),
e.name.c_str());
continue;
}
if (e.n_expert < 1 || (uint64_t)e.cols > held[k].sum2 / (uint64_t)e.n_expert) {
RAD_WARN("%s: '%s.in_sum2' claims %lld column(s) for %lld expert(s) and holds %llu "
"value(s) -- dropped", path_.c_str(), e.name.c_str(), (long long)e.cols,
(long long)e.n_expert, (unsigned long long)held[k].sum2);
continue;
}
if (e.counts && held[k].counts < (uint64_t)e.n_expert) {
RAD_WARN("%s: '%s.counts' holds %llu value(s) for %lld expert(s) -- ignored, so this "
"tensor contributes no expert profile", path_.c_str(), e.name.c_str(),
(unsigned long long)held[k].counts, (long long)e.n_expert);
e.counts = nullptr;
}
kept.push_back(std::move(e));
}
entries_ = std::move(kept);
return RAD_OK;
}
/* ------------------------------------------------------------------ queries */
const ImatrixEntry* ImatrixFile::find(const std::string& name) const {
auto it = index_.find(name);
return it == index_.end() ? nullptr : &entries_[it->second];
}
bool ImatrixFile::importance(const std::string& name, int64_t expert,
std::vector<float>* out) const {
const ImatrixEntry* e = find(name);
if (!e || !e->sum2 || e->cols <= 0 || expert < 0 || expert >= e->n_expert) return false;
if (!out) return true;
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. */
out->resize((size_t)e->cols);
std::memcpy(out->data(), src, (size_t)e->cols * sizeof(float));
double sum = 0.0;
for (float v : *out) sum += (double)v;
const double mean = sum / (double)e->cols;
if (!(mean > 0.0)) { std::fill(out->begin(), out->end(), 1.0f); return true; }
const float inv = (float)(1.0 / mean);
for (float& v : *out) v *= inv;
return true;
}
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;
float v = 0.0f;
std::memcpy(&v, e->counts + expert, sizeof v);
return (double)v;
}
} /* namespace rad */
-97
View File
@@ -1,97 +0,0 @@
/* imatrix.h -- llama.cpp's importance matrix, both of the 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:
*
* - 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.
*
* Two formats, because llama.cpp has written two and both are in the wild:
*
* 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 `<name>.in_sum2` (f32 [cols] or [cols,n_expert])
* and `<name>.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.
*
* 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.
*/
#pragma once
#include "../rad_internal.h"
#include <string>
#include <unordered_map>
#include <vector>
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. */
struct ImatrixEntry {
std::string name; /* the checkpoint tensor name, suffix stripped */
const float* sum2 = nullptr; /* [n_expert][cols], expert-major and contiguous */
const float* counts = nullptr; /* [n_expert], or null in the legacy format */
int64_t cols = 0;
int64_t n_expert = 1; /* 1 for a dense tensor */
int64_t ncall = 0; /* legacy only: calls folded into sum2 */
};
class ImatrixFile {
public:
ImatrixFile() = default;
~ImatrixFile();
ImatrixFile(const ImatrixFile&) = delete;
ImatrixFile& operator=(const ImatrixFile&) = delete;
/* Sniffs the magic and picks a reader. RAD_E_FORMAT if it is neither. */
int open(const std::string& path);
void close();
const ImatrixEntry* find(const std::string& name) const;
const std::vector<ImatrixEntry>& entries() const { return entries_; }
const std::string& dataset() const { return dataset_; }
int64_t chunk_count() const { return chunk_count_; }
int64_t chunk_size() const { return chunk_size_; }
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. */
bool importance(const std::string& name, int64_t expert, std::vector<float>* out) const;
/* Raw activation count for one expert -- the popularity signal, unnormalised. 0 if absent. */
double count(const std::string& name, int64_t expert) const;
private:
int read_legacy(const uint8_t* p, uint64_t n);
int read_gguf(const uint8_t* p, uint64_t n);
int fd_ = -1;
uint8_t* map_ = nullptr;
uint64_t map_bytes_ = 0;
bool gguf_ = false;
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. */
std::vector<std::vector<float>> owned_;
std::vector<ImatrixEntry> entries_;
std::unordered_map<std::string, size_t> index_;
};
} /* namespace rad */
-45
View File
@@ -1,45 +0,0 @@
/* 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.
*/
#include "tunecache.h"
#include <cstring>
namespace rad {
std::string rad_machine_key() {
RadDeviceProps p{};
const int n = rad_dev_count();
/* 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) {
#if defined(__x86_64__)
return "host-x86_64";
#elif defined(__aarch64__)
return "host-aarch64";
#else
return "host-unknown";
#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;
for (char& c : name)
if (!((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')))
c = '_';
while (name.size() > 1 && name.back() == '_') name.pop_back();
if (name.empty()) name = "unknown";
const char* arch = p.arch[0] ? p.arch : "host";
return fmt("%s-x%d-%s", arch, n, name.c_str());
}
} /* namespace rad */
File diff suppressed because it is too large. Load diff
-373
View File
@@ -1,373 +0,0 @@
/* radfile.h -- the .rad reader and writer.
*
* 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:
*
* - 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.
*
* 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.
*/
#pragma once
#include "../rad_internal.h"
#include <functional>
#include <string>
#include <string_view>
#include <unordered_map>
#include <vector>
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:
*
* 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.
*
* 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.
*
* 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. */
struct VocabSection {
const RadVocabHeader* h = nullptr;
const rad_stroff* tok_text = nullptr; /* [n_tokens] */
const float* tok_score= nullptr; /* [n_tokens] or null */
const uint8_t* tok_type = nullptr; /* [n_tokens] or null */
const uint32_t* merges = nullptr; /* [n_merges][2] or null */
const RadVocabStep* steps = nullptr; /* [n_steps] or null */
explicit operator bool() const { return h != nullptr; }
};
/* ================================================================== reader */
class RadFile {
public:
RadFile() = default;
~RadFile();
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. */
int open(const char* path);
void close();
bool is_open() const { return base_ != nullptr; }
const char* path() const { return path_.c_str(); }
const RadFileHeader& header() const { return *hdr_; }
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. */
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. */
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. */
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. */
const char* str(rad_stroff off) const {
return (const char*)(base_ + hdr_->str_off + (off < str_bytes_ ? off : 0));
}
/* ------------------------------------------------------------ metadata */
int64_t meta_count() const { return (int64_t)hdr_->meta_count; }
const RadFileKV& meta_at(int64_t i) const { return meta_[i]; }
bool get_i(const char* key, int64_t* out) const;
bool get_f(const char* key, double* out) const;
const char* get_s(const char* key, const char* dflt = nullptr) const;
/* ------------------------------------------------------------ weight directory */
int64_t entry_count() const { return (int64_t)hdr_->dir_count; }
const RadFileEntry& entry(int64_t i) const { return dir_[i]; }
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. */
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];
}
const uint8_t* data(const RadFilePlane& p) const { return base_ + p.offset; }
int64_t encoding_count() const { return (int64_t)hdr_->enc_count; }
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. */
struct ExpertGroup {
int32_t layer = -1;
int32_t n_expert = 0;
int32_t n_slot = 0; /* gate/up/down = 3 */
int64_t first_index= 0; /* directory index of (expert 0, slot 0) */
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. */
uint64_t slot_off[8] = {0};
uint64_t slot_bytes[8] = {0};
};
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. */
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];
}
const RadFileEntry& expert_entry(const ExpertGroup& g, int32_t expert, int32_t slot) const {
return dir_[g.first_index + (int64_t)expert * g.n_slot + slot];
}
/* ------------------------------------------------------------ vocab and profile */
VocabSection vocab() const { return vocab_; }
int64_t profile_count() const { return (int64_t)hdr_->prof_count; }
const RadFileProfile* profile() const { return prof_; }
private:
int validate();
int index_experts();
std::string path_;
uint8_t* base_ = nullptr;
int64_t size_ = 0;
int fd_ = -1;
const RadFileHeader* hdr_ = nullptr;
const RadFileKV* meta_ = nullptr;
const RadFileEntry* dir_ = nullptr;
const RadFilePlane* planes_ = nullptr;
const RadEncoding* encs_ = nullptr;
const RadFileProfile* prof_ = nullptr;
uint64_t str_bytes_ = 1;
VocabSection vocab_;
std::vector<ExpertGroup> groups_;
std::unordered_map<std::string_view, int64_t> by_name_;
};
/* ================================================================== 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.
*
* 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.
*
* 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.
*/
class RadWriter {
public:
RadWriter() = default;
~RadWriter();
RadWriter(const RadWriter&) = delete;
RadWriter& operator=(const RadWriter&) = delete;
int begin(const char* path);
void abort(); /* discard, unlink both the target and the spill -- or, in
* append mode, cut the file back to its old length */
void set_arch(std::string_view s) { arch_ = s; }
void set_model_name(std::string_view s) { model_ = s; }
void set_quant(std::string_view s) { quant_ = s; }
void set_recipe(std::string_view s) { recipe_ = s; }
void set_created_by(std::string_view s) { created_by_ = s; }
void meta_i(std::string_view k, int64_t v);
void meta_f(std::string_view k, double v);
void meta_s(std::string_view k, std::string_view v);
struct Weight {
std::string name; /* the logical weight's name */
std::string quantizer; /* "" for the checkpoint's own planes */
std::string options; /* "k=v,k=v", sorted by key */
RadEncoding enc{};
uint32_t rank = 0;
int64_t shape[RAD_MAX_RANK] = {0}; /* logical */
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.
*
* 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
* `<path>.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. */
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. */
int64_t add_existing(const Weight& w, const RadFile& old, const RadFileEntry& e);
/* 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. */
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);
/* `bytes` of plane `k` of weight `idx`, at byte `off` within the plane. */
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. */
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. */
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(). */
int seal();
/* Writes the header and every table, then -- unsealed -- splices the spilled blob in at a
* 2 MiB boundary. */
int finish();
int64_t data_bytes() const { return blob_bytes_; }
int64_t weight_count() const { return (int64_t)dir_.size(); }
private:
rad_stroff intern(std::string_view s);
void layout(RadFileHeader* h);
uint32_t intern_encoding(const RadEncoding& e);
int check_unit_invariant(const Weight& w, uint64_t off, uint64_t unit_bytes);
std::string path_, spill_path_;
int fd_out_ = -1, fd_spill_ = -1;
int64_t spill_base_ = 0; /* where blob offset 0 is in fd_spill_: 0, append_base_ or
* the sealed data_off */
bool began_ = false;
bool sealed_ = false, late_ = false;
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. */
int finish_append();
int check_complete() const;
bool append_ = false;
int64_t old_size_ = 0, append_base_ = 0;
uint64_t old_data_off_ = 0;
RadFileHeader old_hdr_{};
std::vector<uint8_t> dir_abs_;
std::string arch_, model_, quant_, recipe_, created_by_;
std::string strblob_{std::string(1, '\0')};
std::unordered_map<std::string, rad_stroff> strmap_;
std::vector<RadFileKV> meta_;
std::vector<RadFileEntry> dir_;
std::vector<RadFilePlane> planes_;
std::vector<int64_t> written_; /* parallel to planes_ */
std::vector<RadEncoding> encs_;
std::vector<RadFileProfile> prof_;
/* The vocab section, assembled in memory and appended verbatim. */
std::vector<uint8_t> vocab_blob_;
bool have_vocab_ = false;
int64_t blob_bytes_ = 0; /* the blob's reserved length */
/* Movement-unit bookkeeping, so the fixed stride is a property the writer PROVES. */
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. */
std::vector<uint64_t> 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. */
std::string rad_unit_name(int32_t layer, int32_t expert);
} /* namespace rad */
-172
View File
@@ -1,172 +0,0 @@
/* recipe.cpp -- see recipe.h. */
#include "recipe.h"
#include <algorithm>
#include <cctype>
#include <cstdlib>
namespace rad {
std::string RecipeRule::options_text() const {
std::vector<std::pair<std::string, std::string>> o = options;
std::sort(o.begin(), o.end());
std::string s;
for (const auto& [k, v] : o) {
if (!s.empty()) s += ',';
s += k + "=" + v;
}
return s;
}
bool recipe_glob(const char* p, const char* n) {
/* Iterative, with one backtrack point: the last `*` and where it was tried from. */
const char *star = nullptr, *retry = nullptr;
while (*n) {
if (*p == '*') { star = p++; retry = n; continue; }
if (*p && (*p == '?' || *p == *n)) { ++p; ++n; continue; }
if (!star) return false;
p = star + 1;
n = ++retry;
}
while (*p == '*') ++p;
return *p == 0;
}
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. */
bool expand(const std::string& in, std::string* out, std::string* why) {
out->clear();
for (size_t i = 0; i < in.size(); ++i) {
if (in[i] != '$') { out->push_back(in[i]); continue; }
size_t b = i + 1, e;
const bool braced = b < in.size() && in[b] == '{';
if (braced) {
e = in.find('}', ++b);
if (e == std::string::npos) { *why = "an unclosed ${ in '" + in + "'"; return false; }
} else {
e = b;
while (e < in.size() && (std::isalnum((unsigned char)in[e]) || in[e] == '_')) ++e;
}
const std::string name = in.substr(b, e - b);
if (name.empty()) { *why = "a bare $ in '" + in + "'"; return false; }
const char* v = std::getenv(name.c_str());
if (!v) { *why = "$" + name + " is not set"; return false; }
out->append(v);
i = braced ? e : e - 1;
}
return true;
}
bool add_option(RecipeRule* r, const std::string& kv, std::string* why) {
const size_t eq = kv.find('=');
if (eq == std::string::npos || eq == 0) {
*why = "'" + kv + "' is not key=value";
return false;
}
std::string v;
if (!expand(kv.substr(eq + 1), &v, why)) return false;
for (const auto& o : r->options)
if (o.first == kv.substr(0, eq)) {
*why = "option '" + o.first + "' given twice";
return false;
}
r->options.emplace_back(kv.substr(0, eq), v);
return true;
}
} /* namespace */
int Recipe::add_text(const std::string& text, const std::string& origin, std::string* why) {
size_t at = 0;
int line = 0;
while (at <= text.size()) {
size_t nl = text.find('\n', at);
if (nl == std::string::npos) nl = text.size();
std::string l = text.substr(at, nl - at);
at = nl + 1;
++line;
const size_t hash = l.find('#');
if (hash != std::string::npos) l.resize(hash);
std::vector<std::string> words;
size_t i = 0;
while (i < l.size()) {
while (i < l.size() && std::isspace((unsigned char)l[i])) ++i;
const size_t s = i;
while (i < l.size() && !std::isspace((unsigned char)l[i])) ++i;
if (i > s) words.push_back(l.substr(s, i - s));
}
if (words.empty()) continue;
const std::string where = origin + ":" + std::to_string(line);
if (words.size() < 2) {
if (why) *why = where + ": a rule is PATTERN QUANTISER [key=value ...]";
return RAD_E_FORMAT;
}
RecipeRule r;
r.pattern = words[0];
r.quantizer = words[1];
r.origin = where;
for (size_t k = 2; k < words.size(); ++k) {
std::string w;
if (!add_option(&r, words[k], &w)) {
if (why) *why = where + ": " + w;
return RAD_E_FORMAT;
}
}
rules_.push_back(std::move(r));
}
return RAD_OK;
}
int Recipe::add_flag(const std::string& spec, std::string* why) {
const size_t eq = spec.find('=');
if (eq == std::string::npos || eq == 0) {
if (why) *why = "--quant '" + spec + "': PATTERN=QUANTISER[:key=value,...]";
return RAD_E_FORMAT;
}
RecipeRule r;
r.pattern = spec.substr(0, eq);
r.origin = "--quant";
const std::string rest = spec.substr(eq + 1);
const size_t colon = rest.find(':');
r.quantizer = rest.substr(0, colon);
if (r.quantizer.empty()) {
if (why) *why = "--quant '" + spec + "' names no quantiser";
return RAD_E_FORMAT;
}
if (colon != std::string::npos) {
const std::string opts = rest.substr(colon + 1);
size_t at = 0;
while (at <= opts.size()) {
size_t c = opts.find(',', at);
if (c == std::string::npos) c = opts.size();
std::string w;
if (c > at && !add_option(&r, opts.substr(at, c - at), &w)) {
if (why) *why = "--quant '" + spec + "': " + w;
return RAD_E_FORMAT;
}
at = c + 1;
}
}
rules_.push_back(std::move(r));
return RAD_OK;
}
const RecipeRule* Recipe::match(const std::string& name) const {
for (const RecipeRule& r : rules_)
if (recipe_glob(r.pattern.c_str(), name.c_str())) return &r;
return nullptr;
}
std::string Recipe::text() const {
std::string s;
for (const RecipeRule& r : rules_) {
s += r.pattern + " " + r.quantizer;
for (const auto& [k, v] : r.options) s += " " + k + "=" + v;
s += "\n";
}
return s;
}
} /* namespace rad */
-55
View File
@@ -1,55 +0,0 @@
/* 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:
*
* 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.
*/
#pragma once
#include "../rad_internal.h"
#include <string>
#include <utility>
#include <vector>
namespace rad {
struct RecipeRule {
std::string pattern, quantizer;
std::vector<std::pair<std::string, std::string>> 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. */
std::string options_text() const;
};
/* Does `name` match glob `pattern`? */
bool recipe_glob(const char* pattern, const char* name);
class Recipe {
public:
/* Rules from a recipe file's text, appended. RAD_OK, or RAD_E_FORMAT with the line in `why`. */
int add_text(const std::string& text, const std::string& origin, std::string* why);
/* One rule in the command-line spelling, appended. */
int add_flag(const std::string& spec, std::string* why);
/* The rule that decides `name`, or null when none matches. */
const RecipeRule* match(const std::string& name) const;
const std::vector<RecipeRule>& 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. */
std::string text() const;
private:
std::vector<RecipeRule> rules_;
};
} /* namespace rad */
-373
View File
@@ -1,373 +0,0 @@
/* 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.
*/
#include "safetensors.h"
#include <cerrno>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
namespace rad {
namespace {
/* ------------------------------------------------------------------ a scanner, not a parser */
struct Scan {
const char* p;
const char* end;
std::string err;
void ws() { while (p < end && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')) ++p; }
bool eat(char c) { ws(); if (p < end && *p == c) { ++p; return true; } return false; }
bool peek(char c) { ws(); return p < end && *p == c; }
bool fail(const char* what, const char* base) {
if (err.empty()) err = fmt("%s at byte %lld of the header", what, (long long)(p - base));
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. */
bool str(std::string* out, const char* base) {
ws();
if (p >= end || *p != '"') return fail("expected a string", base);
++p;
out->clear();
while (p < end && *p != '"') {
if (*p != '\\') { out->push_back(*p++); continue; }
if (++p >= end) return fail("string ends inside an escape", base);
switch (*p++) {
case '"': out->push_back('"'); break;
case '\\': out->push_back('\\'); break;
case '/': out->push_back('/'); break;
case 'b': out->push_back('\b'); break;
case 'f': out->push_back('\f'); break;
case 'n': out->push_back('\n'); break;
case 'r': out->push_back('\r'); break;
case 't': out->push_back('\t'); break;
case 'u': {
if (end - p < 4) return fail("truncated \\u escape", base);
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. */
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 };
const unsigned lo = (unsigned)std::strtoul(lo_hex, nullptr, 16);
if (lo >= 0xDC00 && lo < 0xE000) {
cp = 0x10000u + ((cp - 0xD800u) << 10) + (lo - 0xDC00u);
p += 6;
}
}
if (cp < 0x80) out->push_back((char)cp);
else if (cp < 0x800) {
out->push_back((char)(0xC0 | (cp >> 6)));
out->push_back((char)(0x80 | (cp & 0x3F)));
} else if (cp < 0x10000) {
out->push_back((char)(0xE0 | (cp >> 12)));
out->push_back((char)(0x80 | ((cp >> 6) & 0x3F)));
out->push_back((char)(0x80 | (cp & 0x3F)));
} else {
out->push_back((char)(0xF0 | (cp >> 18)));
out->push_back((char)(0x80 | ((cp >> 12) & 0x3F)));
out->push_back((char)(0x80 | ((cp >> 6) & 0x3F)));
out->push_back((char)(0x80 | (cp & 0x3F)));
}
break;
}
default: return fail("unknown escape", base);
}
}
if (p >= end) return fail("unterminated string", base);
++p;
return true;
}
bool i64(int64_t* out, const char* base) {
ws();
const char* s = p;
if (p < end && (*p == '-' || *p == '+')) ++p;
if (p >= end || *p < '0' || *p > '9') return fail("expected an integer", base);
while (p < end && *p >= '0' && *p <= '9') ++p;
*out = std::strtoll(std::string(s, p - s).c_str(), nullptr, 10);
return true;
}
/* Skip one value of any type, so an unknown key inside a tensor object is survivable. */
bool skip(const char* base) {
ws();
if (p >= end) return fail("truncated", base);
if (*p == '"') { std::string t; return str(&t, base); }
if (*p == '{' || *p == '[') {
const char open = *p, close = (open == '{') ? '}' : ']';
int depth = 0;
while (p < end) {
if (*p == '"') { std::string t; if (!str(&t, base)) return false; continue; }
if (*p == open) ++depth;
else if (*p == close && --depth == 0) { ++p; return true; }
++p;
}
return fail("unbalanced brackets", base);
}
while (p < end && *p != ',' && *p != '}' && *p != ']') ++p;
return true;
}
};
/* safetensors names its dtypes; we name ours. The table is the only place the two meet. */
uint32_t st_dtype(const std::string& s) {
if (s == "BF16") return RAD_BF16;
if (s == "F16") return RAD_F16;
if (s == "F32") return RAD_F32;
if (s == "I8") return RAD_I8;
if (s == "U8") return RAD_U8;
if (s == "I16") return RAD_I16;
if (s == "I32") return RAD_I32;
if (s == "I64") return RAD_I64;
if (s == "U32") return RAD_U32;
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. */
return RAD_DT_INVALID;
}
} /* namespace */
SafeTensorsFile::~SafeTensorsFile() { close(); }
void SafeTensorsFile::close() {
if (map_) ::munmap(map_, (size_t)map_bytes_);
if (fd_ >= 0) ::close(fd_);
map_ = nullptr; map_bytes_ = 0; fd_ = -1;
tensors_.clear(); index_.clear(); metadata_.clear(); path_.clear();
}
int SafeTensorsFile::open(const std::string& path) {
close();
path_ = path;
fd_ = ::open(path.c_str(), O_RDONLY | O_CLOEXEC);
if (fd_ < 0) { RAD_ERR("%s: %s", path.c_str(), std::strerror(errno)); return RAD_E_IO; }
struct stat st{};
if (::fstat(fd_, &st) != 0) { RAD_ERR("%s: %s", path.c_str(), std::strerror(errno));
close(); return RAD_E_IO; }
map_bytes_ = (uint64_t)st.st_size;
if (map_bytes_ < 8) {
RAD_ERR("%s: %llu bytes -- too short to be safetensors", path.c_str(),
(unsigned long long)map_bytes_);
close();
return RAD_E_FORMAT;
}
void* m = ::mmap(nullptr, (size_t)map_bytes_, PROT_READ, MAP_PRIVATE, fd_, 0);
if (m == MAP_FAILED) { RAD_ERR("%s: mmap: %s", path.c_str(), std::strerror(errno));
close(); return RAD_E_IO; }
map_ = (uint8_t*)m;
uint64_t hlen = 0;
std::memcpy(&hlen, map_, 8);
if (hlen == 0 || hlen > map_bytes_ - 8) {
RAD_ERR("%s: header length %llu does not fit in a %llu-byte file", path.c_str(),
(unsigned long long)hlen, (unsigned long long)map_bytes_);
close();
return RAD_E_FORMAT;
}
const uint8_t* data_base = map_ + 8 + hlen;
const uint64_t data_bytes = map_bytes_ - 8 - hlen;
const char* base = (const char*)map_ + 8;
Scan sc{ base, base + hlen, {} };
if (!sc.eat('{')) { RAD_ERR("%s: the header is not a JSON object", path.c_str());
close(); return RAD_E_FORMAT; }
while (!sc.peek('}')) {
std::string name;
if (!sc.str(&name, base) || !sc.eat(':')) {
RAD_ERR("%s: %s", path.c_str(), sc.err.empty() ? "malformed header" : sc.err.c_str());
close();
return RAD_E_FORMAT;
}
if (name == "__metadata__") {
const char* s = sc.p;
if (!sc.skip(base)) { RAD_ERR("%s: %s", path.c_str(), sc.err.c_str());
close(); return RAD_E_FORMAT; }
metadata_.assign(s, sc.p - s);
if (!sc.eat(',')) break;
continue;
}
if (!sc.eat('{')) { RAD_ERR("%s: '%s' is not an object", path.c_str(), name.c_str());
close(); return RAD_E_FORMAT; }
StTensor t;
t.name = name;
int64_t off_begin = -1, off_end = -1;
while (!sc.peek('}')) {
std::string key;
if (!sc.str(&key, base) || !sc.eat(':')) {
RAD_ERR("%s: malformed entry for '%s'", path.c_str(), name.c_str());
close();
return RAD_E_FORMAT;
}
if (key == "dtype") {
if (!sc.str(&t.dtype_str, base)) { RAD_ERR("%s: %s", path.c_str(), sc.err.c_str());
close(); return RAD_E_FORMAT; }
t.dtype = st_dtype(t.dtype_str);
} else if (key == "shape") {
if (!sc.eat('[')) { RAD_ERR("%s: '%s'.shape is not an array", path.c_str(),
name.c_str()); close(); return RAD_E_FORMAT; }
while (!sc.peek(']')) {
int64_t d;
if (!sc.i64(&d, base)) { RAD_ERR("%s: %s", path.c_str(), sc.err.c_str());
close(); return RAD_E_FORMAT; }
t.shape.push_back(d);
if (!sc.eat(',')) break;
}
if (!sc.eat(']')) { RAD_ERR("%s: '%s'.shape is unterminated", path.c_str(),
name.c_str()); close(); return RAD_E_FORMAT; }
} else if (key == "data_offsets") {
if (!sc.eat('[') || !sc.i64(&off_begin, base) || !sc.eat(',') ||
!sc.i64(&off_end, base) || !sc.eat(']')) {
RAD_ERR("%s: '%s'.data_offsets is not [begin, end]", path.c_str(),
name.c_str());
close();
return RAD_E_FORMAT;
}
} else if (!sc.skip(base)) {
RAD_ERR("%s: %s", path.c_str(), sc.err.c_str());
close();
return RAD_E_FORMAT;
}
if (!sc.eat(',')) break;
}
if (!sc.eat('}')) { RAD_ERR("%s: entry for '%s' is unterminated", path.c_str(),
name.c_str()); close(); return RAD_E_FORMAT; }
if (off_begin < 0 || off_end < off_begin || (uint64_t)off_end > data_bytes) {
RAD_ERR("%s: '%s' spans [%lld, %lld) of a %llu-byte data section -- truncated",
path.c_str(), name.c_str(), (long long)off_begin, (long long)off_end,
(unsigned long long)data_bytes);
close();
return RAD_E_FORMAT;
}
t.offset = (uint64_t)off_begin;
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. */
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;
for (int64_t d : t.shape) {
if (!shape_ok || elems == 0) break;
if (elems > INT64_MAX / d) { shape_ok = false; break; }
elems *= d;
}
const int64_t want = shape_ok && t.dtype != RAD_DT_INVALID
? (elems > INT64_MAX / 64 ? -1 : rad_dtype_bytes(t.dtype, elems))
: 0;
if (!shape_ok || want < 0 ||
(t.dtype != RAD_DT_INVALID && (uint64_t)want != t.bytes)) {
std::string sh;
for (size_t k = 0; k < t.shape.size(); ++k)
sh += (k ? ", " : "") + std::to_string(t.shape[k]);
RAD_ERR("%s: '%s' is %s [%s], which is not the %llu bytes its data_offsets span. The "
"header disagrees with its own data; the file is damaged or was written by a "
"tool that does not follow the format -- fetch or export it again.",
path.c_str(), name.c_str(), t.dtype_str.c_str(), sh.c_str(),
(unsigned long long)t.bytes);
close();
return RAD_E_FORMAT;
}
index_.emplace(t.name, tensors_.size());
tensors_.push_back(std::move(t));
if (!sc.eat(',')) break;
}
if (!sc.eat('}')) {
RAD_ERR("%s: the header object is unterminated", path.c_str());
close();
return RAD_E_FORMAT;
}
RAD_DEBUG("%s: %zu tensor(s), %s of data", path.c_str(), tensors_.size(),
humanb((int64_t)data_bytes).c_str());
return RAD_OK;
}
const StTensor* SafeTensorsFile::find(const std::string& name) const {
auto it = index_.find(name);
return it == index_.end() ? nullptr : &tensors_[it->second];
}
int st_load_index(const std::string& path, std::unordered_map<std::string, std::string>* out) {
if (!out) return RAD_E_INVAL;
out->clear();
FILE* f = ::fopen(path.c_str(), "rb");
if (!f) {
if (errno == ENOENT) return RAD_E_NOTFOUND;
RAD_ERR("%s: %s", path.c_str(), std::strerror(errno));
return RAD_E_IO;
}
std::string buf;
char chunk[65536];
size_t n;
while ((n = ::fread(chunk, 1, sizeof chunk, f)) > 0) buf.append(chunk, n);
::fclose(f);
/* One key matters: "weight_map". Find it, then read the flat string->string object. */
size_t at = buf.find("\"weight_map\"");
if (at == std::string::npos) {
RAD_ERR("%s: no \"weight_map\" object", path.c_str());
return RAD_E_FORMAT;
}
at = buf.find('{', at);
if (at == std::string::npos) { RAD_ERR("%s: weight_map is not an object", path.c_str());
return RAD_E_FORMAT; }
const char* base = buf.data();
Scan sc{ buf.data() + at, buf.data() + buf.size(), {} };
if (!sc.eat('{')) return RAD_E_FORMAT;
while (!sc.peek('}')) {
std::string k, v;
if (!sc.str(&k, base) || !sc.eat(':') || !sc.str(&v, base)) {
RAD_ERR("%s: %s", path.c_str(), sc.err.empty() ? "malformed weight_map"
: sc.err.c_str());
return RAD_E_FORMAT;
}
out->emplace(std::move(k), std::move(v));
if (!sc.eat(',')) break;
}
RAD_DEBUG("%s: %zu tensor(s) across the shards", path.c_str(), out->size());
return RAD_OK;
}
} /* namespace rad */
-67
View File
@@ -1,67 +0,0 @@
/* safetensors.h -- an 8-byte length, a JSON object, and a blob.
*
* 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.
*/
#pragma once
#include "../rad_internal.h"
#include <string>
#include <unordered_map>
#include <vector>
namespace rad {
struct StTensor {
std::string name;
uint32_t dtype = RAD_DT_INVALID; /* RAD_* ; RAD_DT_INVALID if unrecognised */
std::string dtype_str; /* as written, for the diagnostic */
std::vector<int64_t> shape;
uint64_t offset = 0; /* relative to the data section */
uint64_t bytes = 0;
const uint8_t* data = nullptr;
int64_t numel() const {
if (shape.empty()) return 0;
int64_t n = 1;
for (int64_t d : shape) n *= d;
return n;
}
};
class SafeTensorsFile {
public:
SafeTensorsFile() = default;
~SafeTensorsFile();
SafeTensorsFile(const SafeTensorsFile&) = delete;
SafeTensorsFile& operator=(const SafeTensorsFile&) = delete;
int open(const std::string& path);
void close();
const StTensor* find(const std::string& name) const;
const std::vector<StTensor>& tensors() const { return tensors_; }
const std::string& metadata() const { return metadata_; }
const std::string& path() const { return path_; }
private:
int fd_ = -1;
uint8_t* map_ = nullptr;
uint64_t map_bytes_ = 0;
std::string path_, metadata_;
std::vector<StTensor> tensors_;
std::unordered_map<std::string, size_t> 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. */
int st_load_index(const std::string& index_path,
std::unordered_map<std::string, std::string>* out);
} /* namespace rad */
-162
View File
@@ -1,162 +0,0 @@
/* share.cpp -- which bytes of a container entry one rank's declaration takes. See share.h. */
#include "share.h"
#include "encoding.h"
namespace rad {
int64_t PlaneShare::dense_bytes() const { return rows * rad_enc_row_bytes(dtype, cols); }
int weight_share(const WeightInfo& w, const RadEncoding& enc, uint32_t rank, const int64_t* shape,
int world, int index, PlaneShare out[RAD_ENC_MAX_PLANES], std::string* why) {
auto refuse = [&](const std::string& m) {
if (why) *why = m;
return RAD_E_SHAPE;
};
if (w.n_sel < 1 || w.n_sel > RAD_ENC_MAX_PLANES) return refuse("no planes selected");
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. */
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. */
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 &&
rad_dtype_bits(p0.dtype) >= 8 && R * C == w.sel_rows[0] * w.sel_cols[0]) {
R = w.sel_rows[0];
C = w.sel_cols[0];
}
}
int64_t VR = R, VC = C;
if (single) rad_enc_plane_dims(&enc.plane[w.sel[0]], R, C, &VR, &VC);
struct VRect { int64_t r0, r1, c0, c1; };
std::vector<VRect> view;
const bool span = w.shard_hi > 0;
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. */
uint32_t mat = rank;
for (uint32_t i = 1; i + 1 < rank; ++i)
if (shape[i] == 1) --mat;
if (mat > 2 || (rank == 1 && w.decl.shard == RAD_SHARD_COL))
return refuse(fmt("a %s shard of a rank-%u weight is not defined; declare it "
"RAD_SHARD_NONE", w.decl.shard == RAD_SHARD_ROW ? "ROW" : "COL",
rank));
const bool cols = w.decl.shard == RAD_SHARD_COL || rank == 1;
if (cols) {
int64_t c0 = w.shard_lo, c1 = w.shard_hi;
if (!span) {
if (VC % world) return refuse(fmt("%lld columns do not divide by %d ranks",
(long long)VC, world));
c0 = (int64_t)index * (VC / world);
c1 = c0 + VC / world;
}
if (c1 > VC) return refuse(fmt("the column span [%lld, %lld) is outside %lld",
(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. */
const int np = w.decl.n_row_parts > 1 ? w.decl.n_row_parts : 1;
if (span) {
if (VR % np) return refuse(fmt("%lld rows do not divide into %d parts",
(long long)VR, np));
const int64_t cpart = VR / np;
if (w.shard_hi > cpart)
return refuse(fmt("the row span [%lld, %lld) of each of %d part(s) does not "
"fit the entry's %lld rows", (long long)w.shard_lo,
(long long)w.shard_hi, np, (long long)VR));
for (int g = 0; g < np; ++g)
view.push_back({ g * cpart + w.shard_lo, g * cpart + w.shard_hi, 0, VC });
} else {
if (VR % world) return refuse(fmt("%lld rows do not divide by %d ranks",
(long long)VR, world));
const int64_t per = VR / world;
if (np == 1) {
view.push_back({ index * per, (index + 1) * per, 0, VC });
} else {
int64_t sum = 0;
for (int g = 0; g < np; ++g) sum += w.decl.row_parts[g];
if (sum != per)
return refuse(fmt("%d declared row parts sum to %lld, and the rank's share "
"of %lld rows at %d ranks is %lld", np, (long long)sum,
(long long)VR, world, (long long)per));
int64_t soff = 0;
for (int g = 0; g < np; ++g) {
const int64_t take = w.decl.row_parts[g];
view.push_back({ soff + index * take, soff + (index + 1) * take, 0, VC });
soff += take * world;
}
}
}
}
}
for (int k = 0; k < w.n_sel; ++k) {
const RadEncPlane& p = enc.plane[w.sel[k]];
PlaneShare& s = out[k];
s = PlaneShare{};
s.dtype = p.dtype;
int64_t pr = 0, pc = 0;
rad_enc_plane_dims(&p, R, C, &pr, &pc);
s.row_bytes = rad_enc_row_bytes(p.dtype, pc);
const int bits = rad_dtype_bits(p.dtype) > 0 ? rad_dtype_bits(p.dtype)
: 8 * (int)rad_dtype_bytes(p.dtype, 1);
PlaneRect last{ -1, -1, -1, -1 };
for (const VRect& q : view) {
PlaneRect pq;
if (single) {
pq = PlaneRect{ q.r0, q.r1 - q.r0, q.c0, q.c1 - q.c0 };
} else {
std::string m;
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. */
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. */
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),
rad_dtype_name(p.dtype), p.role));
if (!s.rects.empty() && pq.cols != s.cols)
return refuse("the share's parts differ in width");
PlaneShare::Rect r;
r.row0 = pq.row0;
r.rows = pq.rows;
r.byte0 = pq.col0 * bits / 8;
r.bytes = rad_enc_row_bytes(p.dtype, pq.cols);
s.rects.push_back(r);
s.rows += pq.rows;
s.cols = pq.cols;
}
if (s.rows != w.sel_rows[k] || s.cols != w.sel_cols[k])
return refuse(fmt("this rank's share of the '%s' plane is [%lld, %lld] and the "
"declaration says [%lld, %lld]", p.role, (long long)s.rows,
(long long)s.cols, (long long)w.sel_rows[k],
(long long)w.sel_cols[k]));
}
return RAD_OK;
}
} /* namespace rad */
-40
View File
@@ -1,40 +0,0 @@
/* 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.
*
* 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.
*/
#pragma once
#include "../rad_core.h"
#include <string>
#include <vector>
namespace rad {
/* One plane's share, as the rectangles of the plane that make it, in the order they lie end to
* end at the destination. A rectangle is `rows` rows from `row0`, and of each row the `bytes`
* bytes from `byte0`; a row of the plane is `row_bytes` long in the file. */
struct PlaneShare {
struct Rect { int64_t row0 = 0, rows = 0, byte0 = 0, bytes = 0; };
std::vector<Rect> rects;
uint32_t dtype = RAD_DT_INVALID;
int64_t rows = 0, cols = 0; /* the share's extents, in the plane's elements */
int64_t row_bytes = 0;
int64_t dense_bytes() const; /* the share laid out dense: rows * a row of `cols` */
};
/* This rank's share of every plane `w` selects, from an entry of encoding `enc` and logical
* shape (`rank`, `shape`), at tensor-parallel rank `index` of `world`. RAD_OK, or RAD_E_SHAPE with
* the reason in `why`: an extent that does not divide, a cut that splits a block or a byte, a
* share that is not what the declaration says. */
int weight_share(const WeightInfo& w, const RadEncoding& enc, uint32_t rank, const int64_t* shape,
int world, int index, PlaneShare out[RAD_ENC_MAX_PLANES], std::string* why);
} /* namespace rad */
-96
View File
@@ -1,96 +0,0 @@
/* table_copy.cpp -- see table_copy.h. */
#include "table_copy.h"
#include "../rad_internal.h"
#include <sys/mman.h>
#include <algorithm>
#include <atomic>
#include <cerrno>
#include <cstring>
#include <thread>
#include <vector>
namespace rad {
int table_copy_fill(const RadFile& file, const uint8_t* src, int64_t n, int64_t foff,
uint8_t* buf, std::string* why) {
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. */
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);
std::atomic<int> err{RAD_OK};
std::vector<std::thread> rd;
for (int i = 0; i < nt; ++i) {
const int64_t lo = (int64_t)i * span, hi = std::min(n, lo + span);
if (lo >= hi) break;
rd.emplace_back([&, lo, hi] {
for (int64_t o = lo; o < hi && err.load() == RAD_OK; o += piece) {
const int64_t b = std::min(piece, hi - o);
const int rc = file.read_at(buf + o, b, foff + o);
if (rc < 0) { err.store(rc); return; }
file.drop_range(foff + o, b);
}
});
}
for (std::thread& t : rd) t.join();
if (err.load() != RAD_OK) {
*why = fmt("reading the container failed (%s)", rad_strerror(err.load()));
return RAD_E_IO;
}
const int64_t probe = std::min<int64_t>(n, 4096);
bool same = std::memcmp(buf, src, (size_t)probe) == 0 &&
std::memcmp(buf + n - probe, src + n - probe, (size_t)probe) == 0;
for (int64_t o = 0; same && o + 4096 <= n; o += std::max<int64_t>(n / 64, 4096))
same = std::memcmp(buf + o, src + o, 4096) == 0;
if (!same) {
*why = "the copy does not match the container's mapping";
return RAD_E_IO;
}
return RAD_OK;
}
int table_copy_make(const RadFile& file, const uint8_t* src, int64_t n, int64_t foff,
TableCopy* out, std::string* why) {
if (!out || !why || !src || n <= 0) return RAD_E_INVAL;
*out = TableCopy{};
const size_t huge = (size_t)2 << 20;
const size_t sz = ((size_t)n + huge - 1) & ~(huge - 1);
void* m = ::mmap(nullptr, sz, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
-1, 0);
if (m == MAP_FAILED) {
*why = fmt("mmap of %s: %s", humanb((int64_t)sz).c_str(), std::strerror(errno));
return RAD_E_NOMEM;
}
(void)::madvise(m, sz, MADV_HUGEPAGE);
if (::mlock2(m, sz, MLOCK_ONFAULT) != 0) {
*why = fmt("mlock2 of %s: %s", humanb((int64_t)sz).c_str(), std::strerror(errno));
::munmap(m, sz);
return RAD_E_NOMEM;
}
const int rc = table_copy_fill(file, src, n, foff, static_cast<uint8_t*>(m), why);
if (rc != RAD_OK) {
::munlock(m, sz);
::munmap(m, sz);
return rc;
}
out->base = m;
out->bytes = sz;
return RAD_OK;
}
void table_copy_free(TableCopy* c) {
if (!c || !c->base) return;
::munlock(c->base, c->bytes);
::munmap(c->base, c->bytes);
*c = TableCopy{};
}
} /* namespace rad */
-41
View File
@@ -1,41 +0,0 @@
/* 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.
*
* 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. */
#pragma once
#include "radfile.h"
#include <cstddef>
#include <cstdint>
#include <string>
namespace rad {
struct TableCopy {
void* base = nullptr;
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. */
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). */
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. */
void table_copy_free(TableCopy* c);
} /* namespace rad */
-267
View File
@@ -1,267 +0,0 @@
/* 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.
*/
#include "tunecache.h"
#include <cstdlib>
#include <algorithm>
#include <cerrno>
#include <cstring>
#include <ctime>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
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. */
std::vector<std::string_view> split_ws_only(std::string_view s) {
std::vector<std::string_view> out;
size_t i = 0;
while (i < s.size()) {
while (i < s.size() && (s[i] == ' ' || s[i] == '\t')) ++i;
size_t j = i;
while (j < s.size() && s[j] != ' ' && s[j] != '\t') ++j;
if (j > i) out.push_back(s.substr(i, j - i));
i = j;
}
return out;
}
} /* namespace */
std::string TuneCache::rel_path(const std::string& machine) {
return "tune/" + machine + ".tune";
}
std::string TuneCache::path_for(const std::string& home, const std::string& machine) {
return home + "/" + rel_path(machine);
}
std::string TuneCache::now_iso8601() {
time_t t = ::time(nullptr);
struct tm g{};
::gmtime_r(&t, &g);
char buf[32];
::strftime(buf, sizeof buf, "%Y-%m-%dT%H:%M:%SZ", &g);
return buf;
}
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. */
std::vector<std::string> 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. */
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));
}
std::sort(kv.begin(), kv.end());
std::string out;
for (auto& s : kv) { if (!out.empty()) out += ' '; out += s; }
return out;
}
std::string TuneCache::canon_choice(const std::vector<std::pair<std::string, int64_t>>& c) {
std::vector<std::string> kv;
kv.reserve(c.size());
for (const auto& e : c) kv.push_back(fmt("%s=%lld", e.first.c_str(), (long long)e.second));
std::sort(kv.begin(), kv.end());
std::string out;
for (auto& s : kv) { if (!out.empty()) out += ','; out += s; }
return out;
}
std::vector<std::pair<std::string, int64_t>> TuneCache::parse_choice(std::string_view s) {
std::vector<std::pair<std::string, int64_t>> out;
if (s == "-") return out;
size_t i = 0;
while (i < s.size()) {
size_t comma = s.find(',', i);
if (comma == std::string_view::npos) comma = s.size();
std::string_view tok = s.substr(i, comma - i);
const size_t eq = tok.find('=');
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. */
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);
}
i = comma + 1;
}
return out;
}
std::string TuneCache::index_key(std::string_view k, std::string_view p, std::string_view g) {
std::string s;
s.reserve(k.size() + p.size() + g.size() + 2);
s.append(k); s.push_back('\x1f');
s.append(p); s.push_back('\x1f');
s.append(g);
return s;
}
const TuneRow* TuneCache::find(std::string_view k, std::string_view p, std::string_view g) const {
auto it = index_.find(index_key(k, p, g));
return it == index_.end() ? nullptr : &rows_[it->second];
}
void TuneCache::put(const TuneRow& r) {
std::string key = index_key(r.kernel, r.plugin, r.geom);
auto it = index_.find(key);
if (it != index_.end()) { rows_[it->second] = r; return; }
index_.emplace(std::move(key), rows_.size());
rows_.push_back(r);
}
int TuneCache::load(const std::string& home, const std::string& machine) {
rows_.clear();
index_.clear();
machine_ = 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. */
if (errno == ENOENT) return RAD_OK;
RAD_WARN("%s: %s", path.c_str(), std::strerror(errno));
return RAD_E_IO;
}
char line[4096];
int lineno = 0, bad = 0;
bool saw_magic = false;
while (::fgets(line, sizeof line, f)) {
++lineno;
std::string_view s(line);
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. */
auto tok = split_ws_only(s);
/* A line of blanks is a blank line, and 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);
::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());
::fclose(f);
return RAD_E_FORMAT;
}
saw_magic = true;
continue;
}
if (tok[0] == "machine") {
if (tok.size() >= 2 && std::string(tok[1]) != machine)
RAD_WARN("%s: measured on '%.*s' but this machine is '%s' -- the rows may not "
"describe this card", path.c_str(), (int)tok[1].size(), tok[1].data(),
machine.c_str());
continue;
}
if (tok.size() < 5) { ++bad; continue; }
TuneRow r;
r.kernel = std::string(tok[0]);
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]);
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; }
put(r);
}
::fclose(f);
if (!saw_magic) {
RAD_WARN("%s: empty or missing the 'radtune 2' line", path.c_str());
return RAD_E_FORMAT;
}
if (bad)
RAD_WARN("%s: %d malformed row(s) ignored. A cache is an optimisation; a typo in it must "
"not stop a server.", path.c_str(), bad);
RAD_DEBUG("tune cache %s: %zu row(s)", path.c_str(), rows_.size());
return RAD_OK;
}
int TuneCache::save(const std::string& home) const {
const std::string dir = home + "/tune";
const std::string path = path_for(home, machine_);
if (::mkdir(dir.c_str(), 0755) != 0 && errno != EEXIST) {
RAD_ERR("%s: %s", dir.c_str(), std::strerror(errno));
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. */
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; }
::fprintf(f, "radtune 2\n");
::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. */
std::vector<const TuneRow*> v;
v.reserve(rows_.size());
for (const auto& r : rows_) v.push_back(&r);
std::sort(v.begin(), v.end(), [](const TuneRow* a, const TuneRow* b) {
if (a->kernel != b->kernel) return a->kernel < b->kernel;
if (a->plugin != b->plugin) return a->plugin < b->plugin;
return a->geom < b->geom;
});
for (const TuneRow* r : v) {
if (r->kernel.find(' ') != std::string::npos ||
r->plugin.find(' ') != std::string::npos ||
r->choice.find(' ') != std::string::npos) {
RAD_WARN("tune cache: skipping '%s' -- a name with a space in it cannot be written "
"to a whitespace-delimited row", r->kernel.c_str());
continue;
}
::fprintf(f, "%s %s %s %.6f %s %s\n", r->kernel.c_str(), r->plugin.c_str(),
r->choice.empty() ? "-" : r->choice.c_str(), r->us,
r->measured.empty() ? "-" : r->measured.c_str(), r->geom.c_str());
}
if (::fflush(f) != 0 || ::fclose(f) != 0) {
RAD_ERR("%s: %s", tmp.c_str(), std::strerror(errno));
::unlink(tmp.c_str());
return RAD_E_IO;
}
if (::rename(tmp.c_str(), path.c_str()) != 0) {
RAD_ERR("%s -> %s: %s", tmp.c_str(), path.c_str(), std::strerror(errno));
::unlink(tmp.c_str());
return RAD_E_IO;
}
return RAD_OK;
}
} /* namespace rad */
-112
View File
@@ -1,112 +0,0 @@
/* tunecache.h -- the ONE 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.
*
* ================================================================= THE FORMAT
*
* $RADIANCE_HOME/tune/<machine>.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.
*
* line 1 `radtune 2` magic and format version
* line 2 `machine <machine-key>` must equal the reader's own key
* `#...` comment, ignored
* otherwise `<kernel> <plugin> <choice> <us> <measured> <geometry...>`
*
* 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.
* 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.
*
* 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.
*
* 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.
*/
#pragma once
#include "../rad_internal.h"
#include <string>
#include <utility>
#include <unordered_map>
#include <vector>
namespace rad {
struct TuneRow {
std::string kernel, plugin, choice, geom;
double us = 0.0;
std::string measured; /* ISO-8601 UTC, exactly as written */
};
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. */
int load(const std::string& radiance_home, const std::string& machine);
int save(const std::string& radiance_home) const;
const std::string& machine() const { return machine_; }
void set_machine(std::string m) { machine_ = std::move(m); }
const TuneRow* find(std::string_view kernel, std::string_view plugin,
std::string_view geom) const;
void put(const TuneRow& r);
const std::vector<TuneRow>& 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. */
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. */
static std::string canon_choice(const std::vector<std::pair<std::string, int64_t>>& 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. */
static std::vector<std::pair<std::string, int64_t>> parse_choice(std::string_view s);
static std::string path_for(const std::string& radiance_home, const std::string& machine);
/* The same path relative to a home, for finding the first home on a search path that has one. */
static std::string rel_path(const std::string& machine);
static std::string now_iso8601();
private:
static std::string index_key(std::string_view kernel, std::string_view plugin,
std::string_view geom);
std::string machine_;
std::vector<TuneRow> rows_;
std::unordered_map<std::string, size_t> 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. */
std::string rad_machine_key();
} /* namespace rad */
-118
View File
@@ -1,118 +0,0 @@
/* gen_config.cpp -- reading a checkpoint's own sampling. The header carries the argument. */
#include "gen_config.h"
#include "rad_internal.h"
#include <nlohmann/json.hpp>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
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. */
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;
if (ok) { *dst = (float)v; return; }
RAD_WARN("%s states %s %g, which is outside %s%g, %g]; ignoring it",
src, what, v, lo_open ? "(" : "[", lo, hi);
}
} /* namespace */
SamplingParams GenSampling::onto(SamplingParams base) const {
if (temp >= 0.0f) base.temp = temp;
if (top_p >= 0.0f) base.top_p = top_p;
if (min_p >= 0.0f) base.min_p = min_p;
if (top_k >= 0) base.top_k = top_k;
return base;
}
std::string GenSampling::describe(const SamplingParams& sp) {
char buf[160];
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.top_p, (double)sp.min_p);
return buf;
}
bool gen_sampling_parse(const std::string& json_text, const char* src, GenSampling* out) {
nlohmann::json j;
try { j = nlohmann::json::parse(json_text); }
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. */
auto it = j.find("do_sample");
if (it != j.end() && it->is_boolean() && !it->get<bool>()) { out->temp = 0.0f; return true; }
it = j.find("temperature");
if (it != j.end() && it->is_number()) take("temperature", src, it->get<double>(), 0.0, 2.0, false, &out->temp);
it = j.find("top_p");
if (it != j.end() && it->is_number()) take("top_p", src, it->get<double>(), 0.0, 1.0, true, &out->top_p);
it = j.find("min_p");
if (it != j.end() && it->is_number()) take("min_p", src, it->get<double>(), 0.0, 1.0, false, &out->min_p);
it = j.find("top_k");
if (it != j.end() && it->is_number_integer()) {
const int64_t v = it->get<int64_t>();
/* -1 is transformers' spelling of "no top_k" and this sampler's is 0; anything below that
* is not a count at all. */
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);
}
return out->any();
}
bool gen_sampling_from_file(const std::string& path, bool required, GenSampling* out) {
std::ifstream f(path);
if (!f) {
if (required) RAD_ERR("%s: cannot be read", path.c_str());
return false;
}
std::string text((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
return gen_sampling_parse(text, path.c_str(), out);
}
bool gen_sampling_from_kv(const std::function<const char*(const char*)>& 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. */
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) {
const char* v = get(k);
if (!v || !*v) continue;
if (std::strcmp(k, "do_sample") == 0) {
/* rad-convert writes a JSON boolean as "1" or "0". */
j[k] = (std::strcmp(v, "0") != 0);
continue;
}
char* end = nullptr;
const double d = std::strtod(v, &end);
if (end == v) {
RAD_WARN("the container states generation.%s as \"%s\", which is not a number; "
"ignoring it", k, v);
continue;
}
if (std::strcmp(k, "top_k") == 0) j[k] = (int64_t)d;
else j[k] = d;
}
if (j.empty()) return false;
return gen_sampling_parse(j.dump(), "the container's generation metadata", out);
}
std::string gen_sidecar_path(const std::string& model_path) {
const size_t slash = model_path.find_last_of("/\\");
const size_t dot = model_path.find_last_of('.');
const bool has_ext = dot != std::string::npos && (slash == std::string::npos || dot > slash);
return (has_ext ? model_path.substr(0, dot) : model_path) + ".generation.json";
}
} /* namespace rad */
-73
View File
@@ -1,73 +0,0 @@
/* gen_config.h -- the sampling a checkpoint states for itself.
*
* 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.
*
* 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.
*/
#pragma once
#include "rad_core.h"
#include <functional>
#include <string>
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. */
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. */
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. */
static std::string describe(const SamplingParams& sp);
};
/* 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. */
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. */
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. */
bool gen_sampling_from_kv(const std::function<const char*(const char*)>& get, GenSampling* out);
/* `<model>.rad` -> `<model>.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. */
std::string gen_sidecar_path(const std::string& model_path);
} /* namespace rad */
-600
View File
@@ -1,600 +0,0 @@
/* kld.cpp -- see kld.h. */
#include "kld.h"
#include "rad_internal.h"
#include "rad_plugin.h"
#include "text/tokenizer.h"
#include <nlohmann/json.hpp>
#include <algorithm>
#include <cerrno>
#include <cmath>
#include <cstring>
#include <ctime>
#include <fstream>
#include <limits>
#include <map>
#include <thread>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
namespace rad {
using json = nlohmann::ordered_json;
namespace {
constexpr const char* kFormat = "radiance-kld-1";
uint64_t fnv1a(const void* p, size_t n, uint64_t h = 1469598103934665603ull) {
const auto* b = static_cast<const uint8_t*>(p);
for (size_t i = 0; i < n; ++i) { h ^= b[i]; h *= 1099511628211ull; }
return h;
}
bool pwrite_all(int fd, const void* p, size_t n, int64_t off) {
const auto* b = static_cast<const char*>(p);
while (n) {
const ssize_t w = ::pwrite(fd, b, n, (off_t)off);
if (w < 0 && errno == EINTR) continue;
if (w <= 0) return false;
b += w; n -= (size_t)w; off += w;
}
return true;
}
bool pread_all(int fd, void* p, size_t n, int64_t off) {
auto* b = static_cast<char*>(p);
while (n) {
const ssize_t r = ::pread(fd, b, n, (off_t)off);
if (r < 0 && errno == EINTR) continue;
if (r <= 0) return false;
b += r; n -= (size_t)r; off += r;
}
return true;
}
bool write_file(const std::string& path, const void* p, size_t n) {
const int fd = ::open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd < 0) return false;
const bool ok = pwrite_all(fd, p, n, 0);
return ::close(fd) == 0 && ok;
}
/* A file of exactly `bytes`, sparse until its rows are written. */
int create_sized(const std::string& path, int64_t bytes) {
const int fd = ::open(path.c_str(), O_RDWR | O_CREAT | O_TRUNC, 0644);
if (fd < 0) return -1;
if (::ftruncate(fd, (off_t)bytes) != 0) { ::close(fd); return -1; }
return fd;
}
int open_sized(const std::string& path, int64_t bytes) {
const int fd = ::open(path.c_str(), O_RDONLY);
if (fd < 0) return -1;
struct stat st{};
if (::fstat(fd, &st) != 0 || (int64_t)st.st_size != bytes) { ::close(fd); return -2; }
return fd;
}
std::string now_iso() {
char buf[32];
const std::time_t t = std::time(nullptr);
std::tm tm{};
gmtime_r(&t, &tm);
std::strftime(buf, sizeof buf, "%Y-%m-%dT%H:%M:%SZ", &tm);
return buf;
}
int worker_count() {
const unsigned h = std::thread::hardware_concurrency();
return (int)std::clamp<unsigned>(h > 2 ? h - 2 : 1, 1, 32);
}
/* The q-quantile by linear interpolation between order statistics, numpy's default. */
double quantile(const std::vector<float>& sorted, double q) {
if (sorted.empty()) return 0.0;
const double x = q * (double)(sorted.size() - 1);
const size_t i = (size_t)x;
if (i + 1 >= sorted.size()) return sorted.back();
return sorted[i] + (x - (double)i) * (sorted[i + 1] - sorted[i]);
}
struct Summary {
int64_t n = 0;
double mean = 0, median = 0, p90 = 0, p95 = 0, p99 = 0, p999 = 0, p9999 = 0, max = 0;
double top1 = 0, ppl_q = 0, ppl_p = 0;
};
Summary summarise(std::vector<float> kl, int64_t top1, double nll_q, double nll_p) {
Summary s;
s.n = (int64_t)kl.size();
if (!s.n) return s;
std::sort(kl.begin(), kl.end());
double sum = 0;
for (float v : kl) sum += v;
s.mean = sum / (double)s.n;
s.median = quantile(kl, 0.5);
s.p90 = quantile(kl, 0.90);
s.p95 = quantile(kl, 0.95);
s.p99 = quantile(kl, 0.99);
s.p999 = quantile(kl, 0.999);
s.p9999 = quantile(kl, 0.9999);
s.max = kl.back();
s.top1 = (double)top1 / (double)s.n;
s.ppl_q = std::exp(nll_q / (double)s.n);
s.ppl_p = std::exp(nll_p / (double)s.n);
return s;
}
json summary_json(const Summary& s) {
json j;
j["positions"] = s.n;
j["kld"] = { {"mean", s.mean}, {"median", s.median}, {"p90", s.p90}, {"p95", s.p95},
{"p99", s.p99}, {"p99_9", s.p999}, {"p99_99", s.p9999}, {"max", s.max} };
j["top1_agreement"] = s.top1;
j["ppl"] = { {"candidate", s.ppl_q}, {"reference", s.ppl_p},
{"ratio", s.ppl_p > 0 ? s.ppl_q / s.ppl_p : 0.0} };
return j;
}
/* The logit of global token `id`, from whichever shard holds it. */
inline float logit_at(const std::vector<KldShard>& sh, int64_t at, int64_t id) {
for (const KldShard& s : sh)
if (id >= s.vocab0 && id < s.vocab0 + s.width) return s.rows[at * s.width + (id - s.vocab0)];
return -std::numeric_limits<float>::infinity();
}
struct TopEntry { int32_t id; float lp; };
} /* namespace */
Kld::Kld() {
for (uint32_t h = 0; h < 65536; ++h) f16_lut_[h] = rad_f16_to_f32((uint16_t)h);
}
Kld::~Kld() {
for (int fd : { fd_logp_, fd_top_, fd_rows_ }) if (fd >= 0) ::close(fd);
}
std::vector<int32_t> Kld::tokens(size_t d) const {
const Doc& doc = docs_[d];
return std::vector<int32_t>(tokens_.begin() + doc.off, tokens_.begin() + doc.off + doc.n);
}
int Kld::open(const Config& cfg, std::shared_ptr<const Vocab> vocab, int64_t n_vocab,
const std::string& model) {
if (cfg.kld_record.empty()) return score_against(cfg.kld_ref, cfg.kld_out, n_vocab, model);
RAD_TRY(load_corpus(cfg, vocab));
return record_into(cfg.kld_record, n_vocab, model);
}
int Kld::score_against(const std::string& dir, const std::string& out, int64_t n_vocab,
const std::string& model) {
record_ = false;
dir_ = dir;
out_ = out;
model_ = model;
n_vocab_ = n_vocab;
RAD_TRY(load_ref(dir_));
size_rows();
return RAD_OK;
}
void Kld::size_rows() {
seen_.assign((size_t)n_rows_, 0);
if (record_) return;
kl_.assign((size_t)n_rows_, 0.0f);
nll_q_.assign((size_t)n_rows_, 0.0f);
nll_p_.assign((size_t)n_rows_, 0.0f);
top1_.assign((size_t)n_rows_, 0);
}
int Kld::add_doc(const std::string& source, const std::vector<int32_t>& ids, int64_t score_from) {
Doc d;
d.source = source;
d.off = (int64_t)tokens_.size();
d.n = (int64_t)ids.size();
d.score_from = score_from;
if (d.score_from < 0 || d.rows() < 1) return RAD_E_INVAL;
d.row0 = n_rows_;
n_rows_ += d.rows();
tokens_.insert(tokens_.end(), ids.begin(), ids.end());
docs_.push_back(std::move(d));
return RAD_OK;
}
/* ------------------------------------------------------------------ the corpus (record) */
int Kld::load_corpus(const Config& cfg, const std::shared_ptr<const Vocab>& vocab) {
corpus_ = cfg.kld_corpus;
std::ifstream in(corpus_, std::ios::binary);
if (!in) { RAD_ERR("kld: cannot read --kld-corpus %s", corpus_.c_str()); return RAD_E_IO; }
Tokenizer tok;
RAD_TRY(tok.init(vocab));
std::string line;
int64_t lineno = 0;
corpus_hash_ = fnv1a(nullptr, 0);
while (std::getline(in, line)) {
++lineno;
corpus_hash_ = fnv1a(line.data(), line.size(), corpus_hash_);
if (line.empty()) continue;
json j;
try { j = json::parse(line); }
catch (const std::exception& e) {
RAD_ERR("kld: %s line %lld is not JSON: %s", corpus_.c_str(), (long long)lineno, e.what());
return RAD_E_FORMAT;
}
if (!j.contains("prompt") || !j["prompt"].is_string()) {
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. */
std::vector<int32_t> ids;
RAD_TRY(tok.encode(j["prompt"].get<std::string>(), ids, false, true));
const int64_t from = j.value("score_from", (int64_t)0);
if (add_doc(j.value("source", std::string()), ids, from) < 0) {
RAD_ERR("kld: %s line %lld: %zu tokens leave nothing to score from position %lld",
corpus_.c_str(), (long long)lineno, ids.size(), (long long)from);
return RAD_E_FORMAT;
}
}
if (docs_.empty()) { RAD_ERR("kld: %s holds no documents", corpus_.c_str()); return RAD_E_FORMAT; }
return RAD_OK;
}
int Kld::record_into(const std::string& dir, int64_t n_vocab, const std::string& model) {
record_ = true;
dir_ = dir;
model_ = model;
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. */
::mkdir(dir_.c_str(), 0755);
struct stat st{};
if (::stat((dir_ + "/kld.json").c_str(), &st) == 0) {
RAD_ERR("kld: %s already holds a reference; record into a new directory", dir_.c_str());
return RAD_E_INVAL;
}
if (!write_file(dir_ + "/tokens.i32", tokens_.data(), tokens_.size() * sizeof(int32_t))) {
RAD_ERR("kld: cannot write %s/tokens.i32: %s", dir_.c_str(), std::strerror(errno));
return RAD_E_IO;
}
fd_logp_ = create_sized(dir_ + "/logp.f16", n_rows_ * n_vocab_ * 2);
fd_top_ = create_sized(dir_ + "/top.bin", n_rows_ * kKldTop * (int64_t)sizeof(TopEntry));
fd_rows_ = create_sized(dir_ + "/rows.f32", n_rows_ * 2 * 4);
if (fd_logp_ < 0 || fd_top_ < 0 || fd_rows_ < 0) {
RAD_ERR("kld: cannot create the reference files in %s: %s", dir_.c_str(),
std::strerror(errno));
return RAD_E_IO;
}
RAD_INFO("kld: recording %lld positions over %zu documents (%zu tokens) into %s, %.1f GiB",
(long long)n_rows_, docs_.size(), tokens_.size(), dir_.c_str(),
(double)(n_rows_ * n_vocab_ * 2) / (1024.0 * 1024.0 * 1024.0));
return RAD_OK;
}
/* ------------------------------------------------------------------ the reference (ref) */
int Kld::load_ref(const std::string& dir) {
std::ifstream in(dir + "/kld.json");
if (!in) {
RAD_ERR("kld: %s has no kld.json -- not a reference, or its recording did not finish",
dir.c_str());
return RAD_E_IO;
}
json m;
try { in >> m; }
catch (const std::exception& e) {
RAD_ERR("kld: %s/kld.json: %s", dir.c_str(), e.what());
return RAD_E_FORMAT;
}
if (m.value("format", std::string()) != kFormat) {
RAD_ERR("kld: %s/kld.json is not %s", dir.c_str(), kFormat);
return RAD_E_FORMAT;
}
if (m.value("n_vocab", (int64_t)0) != n_vocab_ || m.value("top", 0) != kKldTop) {
RAD_ERR("kld: the reference in %s has a %lld-token vocabulary and this model %lld",
dir.c_str(), (long long)m.value("n_vocab", (int64_t)0), (long long)n_vocab_);
return RAD_E_INVAL;
}
ref_model_ = m.value("model", std::string());
corpus_ = m.value("corpus", std::string());
int64_t n_tok = 0;
for (const json& jd : m["docs"]) {
Doc d;
d.source = jd.value("source", std::string());
d.off = n_tok;
d.n = jd.at("tokens").get<int64_t>();
d.score_from = jd.at("score_from").get<int64_t>();
d.row0 = jd.at("row0").get<int64_t>();
if (d.row0 != n_rows_ || d.rows() < 1) {
RAD_ERR("kld: %s/kld.json: document %zu does not follow on", dir.c_str(), docs_.size());
return RAD_E_FORMAT;
}
n_rows_ += d.rows();
n_tok += d.n;
docs_.push_back(std::move(d));
}
if (n_rows_ != m.value("rows", (int64_t)-1)) {
RAD_ERR("kld: %s/kld.json: its documents add up to %lld rows, not %lld", dir.c_str(),
(long long)n_rows_, (long long)m.value("rows", (int64_t)-1));
return RAD_E_FORMAT;
}
tokens_.resize((size_t)n_tok);
const int fd = open_sized(dir + "/tokens.i32", n_tok * 4);
const bool ok = fd >= 0 && pread_all(fd, tokens_.data(), (size_t)n_tok * 4, 0);
if (fd >= 0) ::close(fd);
fd_logp_ = open_sized(dir + "/logp.f16", n_rows_ * n_vocab_ * 2);
fd_top_ = open_sized(dir + "/top.bin", n_rows_ * kKldTop * (int64_t)sizeof(TopEntry));
fd_rows_ = open_sized(dir + "/rows.f32", n_rows_ * 2 * 4);
if (!ok || fd_logp_ < 0 || fd_top_ < 0 || fd_rows_ < 0) {
RAD_ERR("kld: the files in %s are missing or not the size kld.json says", dir.c_str());
return RAD_E_FORMAT;
}
RAD_INFO("kld: scoring %lld positions over %zu documents against %s (%s)",
(long long)n_rows_, docs_.size(), dir.c_str(), ref_model_.c_str());
return RAD_OK;
}
/* ------------------------------------------------------------------ a step's rows */
int Kld::score(const std::vector<KldSpan>& spans, const std::vector<KldShard>& shards) {
std::vector<Job> jobs;
for (const KldSpan& s : spans) {
if (s.id == 0 || s.id > docs_.size()) continue;
const Doc& d = docs_[(size_t)(s.id - 1)];
for (int64_t j = 0; j < s.n; ++j) {
const int64_t p = s.pos0 + j;
if (p < d.score_from || p >= d.n - 1) continue;
jobs.push_back({ d.row0 + p - d.score_from, s.row0 + j, tokens_[(size_t)(d.off + p + 1)] });
}
}
if (jobs.empty()) return RAD_OK;
std::atomic<size_t> next{0};
auto work = [&] {
std::vector<uint16_t> f16((size_t)n_vocab_);
for (size_t i; (i = next.fetch_add(1, std::memory_order_relaxed)) < jobs.size();) {
const Job& j = jobs[i];
if (record_) record_row(j, shards, f16);
else score_row(j, shards, f16);
if (!seen_[(size_t)j.row]) {
seen_[(size_t)j.row] = 1;
done_n_.fetch_add(1, std::memory_order_relaxed);
}
}
};
const int nt = (int)std::min<size_t>((size_t)worker_count(), jobs.size());
std::vector<std::thread> th;
th.reserve((size_t)nt);
for (int t = 0; t < nt; ++t) th.emplace_back(work);
for (auto& t : th) t.join();
if (io_err_.load()) {
RAD_ERR("kld: reading or writing the reference in %s failed", dir_.c_str());
return RAD_E_IO;
}
return RAD_OK;
}
/* THE REFERENCE ROW: log-softmax over the whole vocabulary, in double where it sums. */
void Kld::record_row(const Job& j, const std::vector<KldShard>& sh, std::vector<uint16_t>& f16) {
float m = -std::numeric_limits<float>::infinity();
for (const KldShard& s : sh) {
const float* l = s.rows + j.at * s.width;
for (int64_t i = 0; i < s.width; ++i) m = std::max(m, l[i]);
}
double sum = 0;
for (const KldShard& s : sh) {
const float* l = s.rows + j.at * s.width;
for (int64_t i = 0; i < s.width; ++i) sum += std::exp(l[i] - m);
}
const double lse = (double)m + std::log(sum);
/* The head kept exactly: a min-heap on log p, so an entry leaves only for a strictly larger
* one and a tie keeps the lower id, which is the candidate's argmax rule. */
TopEntry top[kKldTop];
int n_top = 0;
auto worse = [](const TopEntry& a, const TopEntry& b) {
return a.lp > b.lp || (a.lp == b.lp && a.id < b.id);
};
double ent = 0;
for (const KldShard& s : sh) {
const float* l = s.rows + j.at * s.width;
for (int64_t i = 0; i < s.width; ++i) {
const float lp = (float)((double)l[i] - lse);
const int64_t id = s.vocab0 + i;
f16[(size_t)id] = rad_f32_to_f16(lp);
const double p = std::exp((double)lp);
if (p > 0) ent -= p * (double)lp;
if (n_top < kKldTop) {
top[n_top++] = { (int32_t)id, lp };
std::push_heap(top, top + n_top, worse);
} else if (lp > top[0].lp) {
std::pop_heap(top, top + n_top, worse);
top[n_top - 1] = { (int32_t)id, lp };
std::push_heap(top, top + n_top, worse);
}
}
}
std::sort(top, top + n_top, worse);
const float rows[2] = { (float)(lse - (double)logit_at(sh, j.at, j.next)), (float)ent };
const int64_t r = j.row;
if (!pwrite_all(fd_logp_, f16.data(), (size_t)n_vocab_ * 2, r * n_vocab_ * 2) ||
!pwrite_all(fd_top_, top, sizeof top, r * (int64_t)sizeof top) ||
!pwrite_all(fd_rows_, rows, sizeof rows, r * (int64_t)sizeof rows))
io_err_.store(1);
}
/* 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. */
void Kld::score_row(const Job& j, const std::vector<KldShard>& sh, std::vector<uint16_t>& f16) {
float m = -std::numeric_limits<float>::infinity();
int64_t arg = 0;
for (const KldShard& s : sh) {
const float* l = s.rows + j.at * s.width;
for (int64_t i = 0; i < s.width; ++i)
if (l[i] > m) { m = l[i]; arg = s.vocab0 + i; }
}
double sum = 0;
for (const KldShard& s : sh) {
const float* l = s.rows + j.at * s.width;
for (int64_t i = 0; i < s.width; ++i) sum += std::exp(l[i] - m);
}
const double lse = (double)m + std::log(sum);
TopEntry top[kKldTop];
float rows[2];
const int64_t r = j.row;
if (!pread_all(fd_logp_, f16.data(), (size_t)n_vocab_ * 2, r * n_vocab_ * 2) ||
!pread_all(fd_top_, top, sizeof top, r * (int64_t)sizeof top) ||
!pread_all(fd_rows_, rows, sizeof rows, r * (int64_t)sizeof rows)) {
io_err_.store(1);
return;
}
double S = 0, A = 0;
for (const KldShard& s : sh) {
const float* l = s.rows + j.at * s.width;
const uint16_t* h = f16.data() + s.vocab0;
for (int64_t i = 0; i < s.width; ++i) {
const float lp = f16_lut_[h[i]];
const double p = std::exp((double)lp);
if (!(p > 0)) continue;
S += p;
A += p * ((double)lp - ((double)l[i] - lse));
}
}
for (const TopEntry& t : top) {
const double lq = (double)logit_at(sh, j.at, t.id) - lse;
const float lp16 = f16_lut_[f16[(size_t)t.id]];
const double p16 = std::exp((double)lp16), px = std::exp((double)t.lp);
if (p16 > 0) { S -= p16; A -= p16 * ((double)lp16 - lq); }
if (px > 0) { S += px; A += px * ((double)t.lp - lq); }
}
kl_[(size_t)r] = (float)(A / S - std::log(S));
top1_[(size_t)r] = arg == (int64_t)top[0].id;
nll_q_[(size_t)r] = (float)(lse - (double)logit_at(sh, j.at, j.next));
nll_p_[(size_t)r] = rows[0];
}
/* ------------------------------------------------------------------ the end */
int Kld::finish() {
const int64_t missing = n_rows_ - done_n_.load();
if (missing) {
RAD_ERR("kld: %lld of %lld positions never came back from the engine", (long long)missing,
(long long)n_rows_);
return RAD_E_STATE;
}
if (!record_) return report();
for (int fd : { fd_logp_, fd_top_, fd_rows_ })
if (::fsync(fd) != 0) { RAD_ERR("kld: fsync: %s", std::strerror(errno)); return RAD_E_IO; }
json m;
m["format"] = kFormat;
m["model"] = model_;
m["corpus"] = corpus_;
m["corpus_fnv1a64"] = fmt("%016llx", (unsigned long long)corpus_hash_);
m["created"] = now_iso();
m["n_vocab"] = n_vocab_;
m["top"] = kKldTop;
m["rows"] = n_rows_;
json docs = json::array();
for (const Doc& d : docs_)
docs.push_back({ {"source", d.source}, {"tokens", d.n}, {"score_from", d.score_from},
{"row0", d.row0} });
m["docs"] = std::move(docs);
const std::string tmp = dir_ + "/kld.json.tmp", path = dir_ + "/kld.json";
{
std::ofstream o(tmp);
o << m.dump(1) << "\n";
if (!o) { RAD_ERR("kld: cannot write %s", tmp.c_str()); return RAD_E_IO; }
}
if (std::rename(tmp.c_str(), path.c_str()) != 0) {
RAD_ERR("kld: cannot rename %s: %s", tmp.c_str(), std::strerror(errno));
return RAD_E_IO;
}
RAD_INFO("kld: reference recorded: %lld positions in %s", (long long)n_rows_, dir_.c_str());
return RAD_OK;
}
int Kld::report() {
auto group = [&](const std::vector<size_t>& docs) {
std::vector<float> kl;
int64_t t1 = 0;
double nq = 0, np = 0;
for (size_t di : docs) {
const Doc& d = docs_[di];
for (int64_t r = d.row0; r < d.row0 + d.rows(); ++r) {
kl.push_back(kl_[(size_t)r]);
t1 += top1_[(size_t)r];
nq += nll_q_[(size_t)r];
np += nll_p_[(size_t)r];
}
}
return summarise(std::move(kl), t1, nq, np);
};
std::vector<size_t> all(docs_.size());
std::map<std::string, std::vector<size_t>> by_src;
for (size_t i = 0; i < docs_.size(); ++i) { all[i] = i; by_src[docs_[i].source].push_back(i); }
const Summary s = group(all);
RAD_INFO("kld: %s against %s, %lld positions over %zu documents", model_.c_str(),
ref_model_.c_str(), (long long)s.n, docs_.size());
RAD_INFO("kld: KLD mean %.6f median %.6f p99 %.5f p99.9 %.4f p99.99 %.4f max %.4f",
s.mean, s.median, s.p99, s.p999, s.p9999, s.max);
RAD_INFO("kld: top-1 agreement %.3f%% PPL %.4f vs reference %.4f (x%.4f)",
100.0 * s.top1, s.ppl_q, s.ppl_p, s.ppl_p > 0 ? s.ppl_q / s.ppl_p : 0.0);
json rep;
rep["model"] = model_;
rep["reference"] = ref_model_;
rep["ref_dir"] = dir_;
rep["corpus"] = corpus_;
rep["created"] = now_iso();
rep["docs"] = (int64_t)docs_.size();
rep["percentile"] = "linear interpolation between order statistics";
rep["all"] = summary_json(s);
json src = json::object();
for (const auto& [name, docs] : by_src) {
const Summary g = group(docs);
RAD_INFO("kld: %-24s %6lld pos mean %.5f median %.6f p99 %.4f p99.9 %.4f top-1 %.2f%%",
name.empty() ? "(no source)" : name.c_str(), (long long)g.n, g.mean, g.median,
g.p99, g.p999, 100.0 * g.top1);
src[name] = summary_json(g);
src[name]["docs"] = (int64_t)docs.size();
}
rep["by_source"] = std::move(src);
if (out_.empty()) return RAD_OK;
{
std::ofstream o(out_);
o << rep.dump(1) << "\n";
if (!o) { RAD_ERR("kld: cannot write %s", out_.c_str()); return RAD_E_IO; }
}
/* Every position, in reference row order: KL, the candidate's and the reference's NLL of the
* next token, and whether the argmaxes agreed. */
std::vector<float> rows((size_t)n_rows_ * 4);
for (int64_t r = 0; r < n_rows_; ++r) {
rows[(size_t)r * 4 + 0] = kl_[(size_t)r];
rows[(size_t)r * 4 + 1] = nll_q_[(size_t)r];
rows[(size_t)r * 4 + 2] = nll_p_[(size_t)r];
rows[(size_t)r * 4 + 3] = (float)top1_[(size_t)r];
}
if (!write_file(out_ + ".rows", rows.data(), rows.size() * sizeof(float))) {
RAD_ERR("kld: cannot write %s.rows", out_.c_str());
return RAD_E_IO;
}
RAD_INFO("kld: report in %s, every position in %s.rows", out_.c_str(), out_.c_str());
return RAD_OK;
}
} /* namespace rad */
Loaded 100 of 632 files, more files were not shown because too many files have changed in this diff. Show more