commit ae74a8aebf5c2c984d1d4318dfe030025fb0b001 Author: Deadcode Date: Sun Oct 4 12:02:41 2026 +0200 radiance 1.0.0 diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 00000000..a3f3866f --- /dev/null +++ b/.dockerignore @@ -0,0 +1,7 @@ +# 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 diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..6f389cdb --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +/build*/ +compile_commands.json +*.o +*.so +*.rad +/sync-jarvis.sh diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 00000000..20a54527 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,448 @@ +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.0 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($<$:-fsanitize=address,undefined> + $<$:-fno-omit-frame-pointer> + $<$:-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 /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. + $ + $) +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 $) + 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 --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 --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_` is set by the compiler modules for C and CXX and is EMPTY for HIP. + # Ninja's HIP rule still declares `depfile = $DEP_FILE` and `deps = gcc`, so it WAITS for a + # depfile the command was never told to write, and records nothing: + # + # $ ninja -t deps libr4d/CMakeFiles/libr4d.dir/r4d_model_bf16.hip.o + # ...hip.o: #deps 0, deps mtime ... (VALID) + # + # Zero. No header is a dependency of any .hip object, so editing a header libr4d includes -- + # r4d_emit.h, r4d_common.h, r4d_fp8_wmma.h, or the ABI itself -- recompiles nothing and RELINKS + # the plugin around stale objects. The library then exports one signature and the engine calls + # another -- a hook called with more arguments than it takes, which segfaults inside the plugin + # with a stack that blames the kernel -- and every test after the edit runs objects that predate + # it. + # + # It is a one-line omission with no upper bound on what it can hide, so it is fixed here rather + # than worked around with `touch`. + if(NOT CMAKE_DEPFILE_FLAGS_HIP) + set(CMAKE_DEPFILE_FLAGS_HIP "-MD -MT -MF ") + endif() + + # AND CMAKE DOES NOT SUPPLY A SYSTEM-INCLUDE FLAG FOR HIP EITHER, which is the same shape of + # omission as the optimisation level below and just as quiet. `CMAKE_INCLUDE_SYSTEM_FLAG_` + # is set by the compiler modules for C and CXX and is EMPTY for HIP, and CMake's fallback when it + # is empty is a plain `-I` -- so every SYSTEM include directory reaches a .hip translation unit as + # an ordinary user include and every warning inside it becomes ours. Without this, ONE + # target_include_directories(... SYSTEM ...) call reaches a CXX source as + # `-isystem /opt/rocm/include` and a .hip source as `-I/opt/rocm/include` -- so this is not + # something an author can get right at the call site. It is set once, here, for every HIP target + # in the tree, vendor/ included. + set(CMAKE_INCLUDE_SYSTEM_FLAG_HIP "-isystem ") + + # OPTIMISATION LEVEL, SET HERE FOR EVERY CONFIG BECAUSE CMAKE DOES NOT SUPPLY A USABLE ONE FOR + # HIP. Depending on the CMake version `CMAKE_HIP_FLAGS_` is either EMPTY -- every device + # kernel compiles at -O0 with asserts live while the host half gets -O2 -g -DNDEBUG -- or, from + # CMake 4.4's HIP toolchain on, pre-filled with the host-style '-O2 -g -DNDEBUG'. Nothing in the + # build says so either way: an absent flag reads as the default, a pre-filled one as a choice. + # + # It is the whole performance story. At -O0 decode reads weights at about 7 GB/s against a card + # that does ~640, and no kernel change can fix a build that does not optimise the kernel. -O3 and + # not -O2 because these are the kernels; -g is deliberately NOT carried onto the device side, + # where it costs compile time and inhibits scheduling for a symbol table no profiler here reads. + # + # THE ASSIGNMENT IS UNCONDITIONAL. A guard such as `if(NOT CMAKE_HIP_FLAGS_${cfg})` cannot tell a + # toolchain default from an operator's choice: on a CMake that pre-fills the variable it sees a + # value and leaves every device kernel at -O2 with debug info, and a build tree whose cache still + # holds -O3 from an older CMake hides that until its next fresh configure drops it, with no + # signal in the build output. An operator who genuinely wants other device flags says so BY NAME + # through RAD_HIP_FLAGS_. A deliberate override is a thing someone typed; a toolchain + # default that happens to be non-empty is not, and the two must not be spelled the same way. + 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) diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..994c0c67 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,190 @@ +# 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 /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"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + 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. diff --git a/NOTICE b/NOTICE new file mode 100644 index 00000000..387ffb55 --- /dev/null +++ b/NOTICE @@ -0,0 +1,15 @@ +radiance +Copyright 2026 Deadcode and the radiance contributors + +Written by Deadcode, with contributions from tcclaviger (the N-rank all-reduce kernels) and ggz14 +(the MXFP4 GEMM and the GDN kernels' overflow guards). + +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 diff --git a/README.md b/README.md new file mode 100644 index 00000000..ee7e8a56 --- /dev/null +++ b/README.md @@ -0,0 +1,136 @@ +# 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. + +## 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, then start a model from its compose file: + +```sh +docker pull stilldeadcode/radiance +cp -r 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'` +(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, 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`). + +```sh +./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 +``` + +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-27B FP8 and bf16, Qwen3.6-35B-A3B | `--tp 2 --max-num-seqs 8 --max-model-len 200000 --kv-cache-dtype fp8` | +| MiniCPM5-2B FP8 and bf16 | `--tp 2 --max-num-seqs 8 --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` | + +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 `. + +```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/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. diff --git a/abi/rad_abi.h b/abi/rad_abi.h new file mode 100644 index 00000000..3906fea5 --- /dev/null +++ b/abi/rad_abi.h @@ -0,0 +1,616 @@ +/* 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 */ diff --git a/abi/rad_builder.h b/abi/rad_builder.h new file mode 100644 index 00000000..21da7125 --- /dev/null +++ b/abi/rad_builder.h @@ -0,0 +1,690 @@ +/* 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 `` 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 "\n" / "\n\n\n", calls "\n" / "", + * "\n" / "\n", arguments "\n" / "" / "\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 , 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 */ diff --git a/abi/rad_device.h b/abi/rad_device.h new file mode 100644 index 00000000..01748bba --- /dev/null +++ b/abi/rad_device.h @@ -0,0 +1,79 @@ +/* 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 */ diff --git a/abi/rad_encoding.h b/abi/rad_encoding.h new file mode 100644 index 00000000..49538c1e --- /dev/null +++ b/abi/rad_encoding.h @@ -0,0 +1,421 @@ +/* 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 = 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 +#include + +#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 bf16 + * affine, codes and scales *[RxC]*[RxC] fp4_e2m1*fp8_e4m3[1x16]*f32[*x*] + * with an integer zero ...-[RxC] u2*f16[1x128]-u8[1x128] + * anything else :=,... affine:codes=u4[1x1],... + * and a 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 */ diff --git a/abi/rad_format.h b/abi/rad_format.h new file mode 100644 index 00000000..73a200f2 --- /dev/null +++ b/abi/rad_format.h @@ -0,0 +1,164 @@ +/* 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 */ diff --git a/abi/rad_plugin.h b/abi/rad_plugin.h new file mode 100644 index 00000000..6431cf2d --- /dev/null +++ b/abi/rad_plugin.h @@ -0,0 +1,520 @@ +/* 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 + +#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 */ diff --git a/abi/rad_quant.h b/abi/rad_quant.h new file mode 100644 index 00000000..6914211b --- /dev/null +++ b/abi/rad_quant.h @@ -0,0 +1,116 @@ +/* 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 */ diff --git a/abi/rad_runtime.h b/abi/rad_runtime.h new file mode 100644 index 00000000..6e676ae4 --- /dev/null +++ b/abi/rad_runtime.h @@ -0,0 +1,382 @@ +/* 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 */ diff --git a/abi/rad_sample.h b/abi/rad_sample.h new file mode 100644 index 00000000..cab52fde --- /dev/null +++ b/abi/rad_sample.h @@ -0,0 +1,135 @@ +/* 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 */ diff --git a/abi/rad_types.h b/abi/rad_types.h new file mode 100644 index 00000000..e2a07a42 --- /dev/null +++ b/abi/rad_types.h @@ -0,0 +1,363 @@ +/* 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 +#include +#include + +#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; + +#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 */ diff --git a/arch/CMakeLists.txt b/arch/CMakeLists.txt new file mode 100644 index 00000000..a5a730df --- /dev/null +++ b/arch/CMakeLists.txt @@ -0,0 +1,72 @@ +# 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 /radiance/arch/, so a +# plugin built against an installed radiance writes `#include `; the plugins in +# this tree write the same, through a directory in the build tree whose arch/ is this common/. +# A plugin here that could only be built here would not be a plugin like any other. +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 $) + +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 ` -- 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") diff --git a/arch/common/rad_arch.h b/arch/common/rad_arch.h new file mode 100644 index 00000000..cf96d903 --- /dev/null +++ b/arch/common/rad_arch.h @@ -0,0 +1,1011 @@ +/* rad_arch.h -- the scaffolding an architecture plugin sits on. + * + * spec.md §2.4 commits to one plugin per (architecture, quantisation). That is deliberate: a w4a8 + * model wants rmsnorm_had_quant_i8 where a bf16 model wants a plain rmsnorm, and pretending + * otherwise means a plugin full of branches on a quant descriptor -- which is how you get back to + * "unclear what actually runs". A declare function with no branches in it is a readable list of + * what this model does, in order. + * + * The file-count mitigation for the quant axis is this library. It is header-only, it is C++ + * (nothing here crosses an .so boundary -- only the four exported C symbols do), and it holds one + * small struct per transformer block with a declare() and a step(). A plugin is COMPOSITION. + */ +#ifndef RAD_ARCH_H +#define RAD_ARCH_H + +#include "rad_builder.h" +#include "rad_device.h" +#include "rad_runtime.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rad { +namespace arch { + +/* One thread per tensor-parallel rank, all in one process (spec §1), and declare runs once per + * rank. So a plugin's declared handles are per-rank state, not process state: a single global + * would have rank 1's declare overwrite rank 0's. libr4d supports 2/4/8-rank all-reduce, so eight + * is the bound worth carrying. */ +enum { MAX_RANKS = 8 }; + + +/* ================================================================== a debug residual probe + * + * THE ONE INSTRUMENT FOR A COMPOSITION FAULT, and it exists because nothing else in the tree can + * see one: rad-kbench falsifies an op against the oracle on the same inputs and a graph that wires + * the right ops to the wrong buffers -- or a block whose output is the wrong SIZE -- passes every + * one of those checks and still serves a different model. What a reader needs then is the residual + * stream's magnitude down the stack, which is smooth in a working model and steps in a broken one. + * + * It SYNCHRONISES THE STREAM and copies one row, so it is off unless RADIANCE_DEBUG_RESID is set, + * and it prints each (layer, site) once. bf16 buffers only -- every activation in this tree is. */ +struct DbgStat { double rms = -1.0, med = -1.0, max = -1.0; }; + +/* RMS, MEDIAN AND MAX TOGETHER, because a residual stream carries a handful of channels two orders + * of magnitude above the rest (the "massive activations" every model in this family has) and the + * RMS is theirs alone. The MEDIAN is the bulk, which is what a block's delta has to be compared + * against; reading the RMS by itself says twenty layers did nothing when they did. */ +inline DbgStat dbg_row_stat(RadCtx* c, rad_buf b, int64_t n) { + DbgStat s; + if (!b || n <= 0) return s; + void* p = rad_buf_ptr(c, b); + if (!p) return s; + std::vector h((size_t)n); + if (rad_memcpy_async(h.data(), p, n * 2, rad_stream(c)) < 0) return s; + rad_stream_sync(rad_stream(c)); + std::vector v((size_t)n); + double a = 0.0, mx = 0.0; + for (int64_t i = 0; i < n; ++i) { + const uint32_t u = (uint32_t)h[(size_t)i] << 16; + float f; + std::memcpy(&f, &u, 4); + a += (double)f * (double)f; + v[(size_t)i] = std::fabs(f); + if (v[(size_t)i] > mx) mx = v[(size_t)i]; + } + std::sort(v.begin(), v.end()); + s.rms = std::sqrt(a / (double)n); + s.med = v[(size_t)(n / 2)]; + s.max = mx; + return s; +} + +inline bool dbg_resid_on() { + static const bool on = std::getenv("RADIANCE_DEBUG_RESID") != nullptr; + return on; +} + +inline void dbg_resid(RadCtx* c, int layer, const char* site, int64_t n_embd, + rad_buf x, rad_buf delta) { + if (!dbg_resid_on()) return; + static int seen[512] = {0}; + const int slot = ((layer * 4) + (site[0] & 3)) & 511; + if (seen[slot]++) return; + const DbgStat sx = dbg_row_stat(c, x, n_embd), sd = dbg_row_stat(c, delta, n_embd); + std::fprintf(stderr, "D resid layer %2d %-4s: x rms %8.4f med %8.5f max %9.3f | " + "delta rms %8.4f med %8.5f max %9.3f\n", + layer, site, sx.rms, sx.med, sx.max, sd.rms, sd.med, sd.max); +} +/* ================================================================== the GPTQ calibration tap + * + * A block that wants to characterise one of its own activations declares an f32 [K, K] PERSIST + * buffer and a `gram_accum` op into it, then calls calib_write() when the corpus is done. These + * three helpers are the parts that are not block-specific: whether it is on, when to stop, and + * the file. + * + * PERSIST AND NOT TRANSIENT, and that is the whole reason this is not a debug probe: a transient + * buffer is liveness-analysed and may share storage with any other transient, so an accumulator + * declared transient would be overwritten between the launches it is meant to sum. + * + * THE CONSUMER IS ANOTHER PROCESS. rad-convert reads these files; the engine writes them. That + * is not an architectural preference but the only order that works -- GPTQ needs the Hessian of + * a layer's real input, which needs the model running, and a container is written before it can + * be served. The bootstrap is: convert with plain absmax, serve THAT, calibrate on it, convert + * again with the Hessians. A second moment is robust to the small perturbation the first + * container's own error puts on the activation. + * + * PER RANK, AND THE CONSUMER SUMS. Under expert parallelism a rank's `down` input is only the + * tokens routed to ITS experts, so no single rank holds the layer's distribution. Its `gate_up` + * input is the whole token set on every rank, so summing those double-counts by `world` -- which + * is a positive scale on H, and GPTQ is invariant to one (the damping is a fraction of the trace + * and the update uses ratios). So one rule, sum everything, and the gate_up case is harmless. */ +inline const char* calib_dir() { + static const char* d = std::getenv("RADIANCE_CALIB_DIR"); + return d && *d ? d : nullptr; +} + +/* The token count at which the tap dumps and switches itself off. Off by default in the sense + * that calib_dir() gates it; this only says how much is enough. */ +inline long long calib_target() { + static const long long n = [] { + const char* s = std::getenv("RADIANCE_CALIB_TOKENS"); + const long long v = s ? std::atoll(s) : 0; + return v > 0 ? v : 65536LL; + }(); + return n; +} + +/* /gram.r..bin, as a 32-byte header and k*k f32 in row-major order: + * + * char magic[8] = "RADGRAM2" + * uint32_t k the dimension, on both axes + * uint32_t rank which rank wrote it + * uint64_t rows activation rows accumulated, for provenance only + * uint32_t domain 0: the model's own activation; N: that activation rotated by the + * unnormalised Hadamard of width N, block by block -- what a rotated + * weight's kernel multiplies + * uint32_t pad + * + * `rows` is not a normaliser: nothing downstream divides by it, because H is used only up to a + * positive scale. It is there so a reader can tell a full calibration from one that was killed + * early -- and, for one expert's file (CalibExperts), an expert the corpus barely routed to from + * one it exercised: libquant reads a per-expert file only when it holds several times K rows. + * `domain` is what the tap actually summed, so a reader quantising in another one -- a rotated + * recipe over a bf16 model's Hessian -- brings the file there itself (libquant's calib_sum). */ +inline bool calib_write_host(const float* h, int64_t k, long long rows, const char* what, + uint32_t domain, int rank) { + const char* dir = calib_dir(); + if (!dir || !h || k <= 0) return false; + char path[512]; + std::snprintf(path, sizeof path, "%s/gram.r%d.%s.bin", dir, rank, what); + FILE* f = std::fopen(path, "wb"); + if (!f) { + std::fprintf(stderr, "radiance: calibration cannot write %s\n", path); + return false; + } + char hdr[32] = {}; + std::memcpy(hdr, "RADGRAM2", 8); + const uint32_t kk = (uint32_t)k, rk = (uint32_t)rank; + const uint64_t nr = (uint64_t)rows; + std::memcpy(hdr + 8, &kk, 4); + std::memcpy(hdr + 12, &rk, 4); + std::memcpy(hdr + 16, &nr, 8); + std::memcpy(hdr + 24, &domain, 4); + const size_t n = (size_t)(k * k); + const bool okw = std::fwrite(hdr, 1, sizeof hdr, f) == sizeof hdr && + std::fwrite(h, 4, n, f) == n; + std::fclose(f); + if (!okw) std::fprintf(stderr, "radiance: calibration write to %s was short\n", path); + return okw; +} + +/* The same file from a device accumulator: copied back on the block's stream, then written. */ +inline bool calib_write(RadCtx* c, rad_buf b, int64_t k, long long rows, const char* what, + uint32_t domain) { + if (!calib_dir() || !b || k <= 0) return false; + void* p = rad_buf_ptr(c, b); + if (!p) return false; + std::vector h((size_t)(k * k)); + if (rad_memcpy_async(h.data(), p, (int64_t)h.size() * 4, rad_stream(c)) < 0) return false; + rad_stream_sync(rad_stream(c)); + return calib_write_host(h.data(), k, rows, what, domain, rad_rank(c)); +} + +/* A pinned host buffer of at least `bytes`, one a rank and held for the life of the process, so a + * tap that brings a scratch back every pass copies it at the link's speed and not a pageable + * copy's. Null, said once, when the allocation fails. */ +inline float* calib_staging(RadCtx* c, int64_t bytes) { + static std::mutex mu; + static std::map> per_rank; + std::lock_guard lk(mu); + std::pair& s = per_rank[rad_rank(c)]; + if (s.second >= bytes) return (float*)s.first; + if (s.first) rad_dev_free(s.first, RAD_MEM_HOST_PINNED); + s.first = rad_dev_alloc(bytes, RAD_MEM_HOST_PINNED); + s.second = s.first ? bytes : 0; + if (!s.first) + std::fprintf(stderr, "radiance: calibration could not pin %lld MiB of host staging on " + "rank %d\n", (long long)(bytes >> 20), rad_rank(c)); + return (float*)s.first; +} + +/* ONE HESSIAN AN EXPERT, which is what a routed expert's `down` projection needs and the layer's + * pooled Gram is not. That projection's input is the expert's OWN intermediate units: channel i + * of one expert has nothing to do with channel i of another, so a Gram summed over the layer's + * experts describes none of them. It is dominated by whichever expert carries the most energy -- + * on Qwen3.8-Flash-Next one expert holds a quarter of some layers' -- and GPTQ fitted to it spends + * every other expert's error budget on that expert's channels. + * + * ON THE HOST, because the card has no room for it: 640^2 f32 for each of 256 experts a rank is + * 419 MB a layer, 20 GB over 48. A pass sums each expert's rows into one layer-sized scratch on + * the card; the scratch comes back through calib_staging() and its upper triangles are added + * here, packed -- a Gram is symmetric, so half the bytes, 10 GB a rank for that model. The cost is + * a stream sync a layer, which a calibration run reading its experts from disk does not notice. + * + * Accumulated in f32: each pass adds one partial sum an expert, so a 10M-token corpus is a few + * hundred adds deep, and the consumer damps H by a percent of its trace. */ +struct CalibExperts { + int64_t ne = 0, k = 0; + std::vector acc; /* `ne` upper triangles of k*(k+1)/2, row by row */ + std::vector rows; /* rows each expert was routed */ + + void init(int64_t n_expert, int64_t width) { + ne = n_expert; + k = width; + acc.assign((size_t)(ne * (k * (k + 1) / 2)), 0.0f); + rows.assign((size_t)ne, 0); + } + + /* `full` is `ne` row-major k x k Grams, back to back -- the scratch as the card wrote it. */ + void add(const float* full) { + const int64_t tri = k * (k + 1) / 2; + const unsigned hw = std::thread::hardware_concurrency(); + const unsigned nt = std::max(1u, std::min(8u, hw / 4)); + std::vector th; + for (unsigned t = 0; t < nt; ++t) + th.emplace_back([this, full, tri, nt, t] { + for (int64_t e = t; e < ne; e += nt) { + const float* s = full + (size_t)(e * k * k); + float* d = acc.data() + (size_t)(e * tri); + for (int64_t i = 0; i < k; ++i) { + const float* sr = s + (size_t)(i * k + i); + for (int64_t j = 0; j < k - i; ++j) d[j] += sr[j]; + d += k - i; + } + } + }); + for (std::thread& x : th) x.join(); + } + + /* Expert `e`'s Gram, whole and symmetric, into `h` (k x k row-major). */ + void unpack(int64_t e, float* h) const { + const float* d = acc.data() + (size_t)(e * (k * (k + 1) / 2)); + for (int64_t i = 0; i < k; ++i) + for (int64_t j = i; j < k; ++j, ++d) { + h[(size_t)(i * k + j)] = *d; + h[(size_t)(j * k + i)] = *d; + } + } + + /* One file an expert, `.`: the weight it will pack minus `.weight`, which + * is the name libquant looks for before the pooled ``. Every expert gets one, a + * never-routed expert's saying `rows` 0. */ + bool write(const char* stem, int64_t expert_base, uint32_t domain, int rank) const { + std::vector h((size_t)(k * k)); + bool ok = true; + for (int64_t e = 0; e < ne; ++e) { + unpack(e, h.data()); + char what[256]; + std::snprintf(what, sizeof what, "%s.%lld", stem, (long long)(expert_base + e)); + ok = calib_write_host(h.data(), k, rows[(size_t)e], what, domain, rank) && ok; + } + return ok; + } +}; + +/* ================================================================== names */ +/* Declared names outlive the call that built them -- the weight manifest, the graph dump and the + * checkpoint name map all hold the pointer. Interning in a deque keeps every c_str() stable for + * the life of the plugin, which a vector would not (it reallocates). + * + * The scope prefix comes from RadBuildCtx: a drafter or an encoder tower declared into the same + * builder must not collide with the language model's names (spec §10, §11). */ +class Names { +public: + explicit Names(const char* scope = "") + : scope_(scope && *scope ? std::string(scope) + "." : std::string()) {} + + /* A declared name, scope-prefixed. */ + const char* f(const char* fmt, ...) __attribute__((format(printf, 2, 3))) { + char buf[256]; + va_list ap; va_start(ap, fmt); vsnprintf(buf, sizeof buf, fmt, ap); va_end(ap); + pool_.emplace_back(scope_ + buf); + return pool_.back().c_str(); + } + /* A checkpoint-side name. Never scope-prefixed: the container says what it says. */ + const char* ckpt(const char* fmt, ...) __attribute__((format(printf, 2, 3))) { + char buf[256]; + va_list ap; va_start(ap, fmt); vsnprintf(buf, sizeof buf, fmt, ap); va_end(ap); + pool_.emplace_back(buf); + return pool_.back().c_str(); + } + +private: + std::deque pool_; + std::string scope_; +}; + +/* Errors are values. Declare walks a long list and any step of it can refuse; this propagates the + * first refusal without an early-return ladder swallowing the reason. */ +#define RAD_ARCH_TRY(expr) do { int _s = (expr); if (_s < 0) return _s; } while (0) + +/* ================================================================== C++-side decl helpers */ +/* rad_group_layer() and friends are C compound literals, which compile in C++ only as a GNU + * extension -- rad_builder.h says so and points here. A named function also reads better in an + * initialiser list than a cast-shaped macro does. */ +inline RadWeightGroup grp_model() { RadWeightGroup g{}; g.layer = -1; g.expert = -1; return g; } +inline RadWeightGroup grp_layer(int l) { RadWeightGroup g{}; g.layer = l; g.expert = -1; return g; } +inline RadWeightGroup grp_expert(int l, int e) { RadWeightGroup g{}; g.layer = l; g.expert = e; return g; } +/* ...AND THE SLOT, WHICH IS NOT OPTIONAL FOR AN EXPERT WITH MORE THAN ONE TENSOR. The container + * writes a layer's experts as fixed-stride units and checks that each unit's slots arrive + * 0..n-1 (core/format/radfile.cpp, check_unit_invariant) -- so two tensors of one expert that + * both leave `slot` at 0 are refused by name at convert time. A routed fp8 expert has four: the + * gate_up codes, their scale plane, the down codes and theirs. */ +inline RadWeightGroup grp_expert_slot(int l, int e, int s) { + RadWeightGroup g{}; g.layer = l; g.expert = e; g.slot = s; return g; +} + +/* `row_parts` is rows of THIS RANK per stacked projection, see RadWeightDecl. A single part is + * the same thing as none, so it is not recorded and the load path stays on its plain-rows + * branch. The pointer form exists because the fp8 linear derives its scale plane's parts by + * dividing the weight's, which an initializer_list cannot express. */ +inline rad_weight decl_w_n(RadBuilder* b, const char* name, uint32_t dtype, + std::initializer_list shape, + int access, int shard, RadWeightGroup group, int optional, + const int64_t* row_parts, int n_row_parts) { + RadWeightDecl d{}; + d.dtype = dtype; + d.rank = (uint32_t)shape.size(); + int i = 0; + for (int64_t s : shape) d.shape[i++] = s; + d.access = access; + d.shard = shard; + d.group = group; + d.optional = optional; + if (row_parts && n_row_parts > 1) { + d.n_row_parts = n_row_parts < RAD_MAX_ROW_PARTS ? n_row_parts : RAD_MAX_ROW_PARTS; + for (int j = 0; j < d.n_row_parts; ++j) d.row_parts[j] = row_parts[j]; + } + return rad_decl_weight(b, name, &d); +} + +inline rad_weight decl_w(RadBuilder* b, const char* name, uint32_t dtype, + std::initializer_list shape, + int access, int shard, RadWeightGroup group, int optional = 0, + std::initializer_list row_parts = {}) { + int64_t p[RAD_MAX_ROW_PARTS] = {0}; + int n = 0; + for (int64_t v : row_parts) if (n < RAD_MAX_ROW_PARTS) p[n++] = v; + return decl_w_n(b, name, dtype, shape, access, shard, group, optional, p, n); +} + +/* A VIEW: `planes` of the logical weight `source` (null: the weight named `name` itself), declared + * at what they select -- one plane's own dtype and extents, several planes' codes dtype and the + * logical extents (RadWeightDecl::source, spec §4.3). A block-fp8 linear is ONE stored weight + * that gemm_nt_q takes as two operands, so it is declared twice over the same source: its codes + * as `.weight` and its scales as `.scale`, `source` = `.weight`. Every view of + * a weight takes the weight's movement group. */ +inline rad_weight decl_view(RadBuilder* b, const char* name, const char* source, + const char* planes, uint32_t dtype, + std::initializer_list shape, int access, int shard, + RadWeightGroup group, const int64_t* row_parts = nullptr, + int n_row_parts = 0) { + RadWeightDecl d{}; + d.dtype = dtype; + d.rank = (uint32_t)shape.size(); + int i = 0; + for (int64_t s : shape) d.shape[i++] = s; + d.access = access; + d.shard = shard; + d.group = group; + if (row_parts && n_row_parts > 1) { + d.n_row_parts = n_row_parts < RAD_MAX_ROW_PARTS ? n_row_parts : RAD_MAX_ROW_PARTS; + for (int j = 0; j < d.n_row_parts; ++j) d.row_parts[j] = row_parts[j]; + } + d.source = source; + d.planes = planes; + return rad_decl_weight(b, name, &d); +} + +/* What the model holds `source` as -- its encoding, from the container, the checkpoint, or the + * recipe rad-convert is applying -- or false when nothing is known about it: a builder with no + * model behind it, or a name the name map has not been told about yet (declare the map first). */ +inline bool weight_enc(RadBuilder* b, const char* source, RadEncoding* out) { + return rad_weight_encoding(b, source, out, nullptr, nullptr) == RAD_OK; +} + +/* The dtype a view of every plane of `source` is declared at: the codes', when the encoding is + * known, else `dflt` -- the dtype a weight with nothing behind it is read as. */ +inline uint32_t weight_codes_dtype(RadBuilder* b, const char* source, uint32_t dflt) { + RadEncoding e{}; + return weight_enc(b, source, &e) && e.n_planes > 0 ? e.plane[0].dtype : dflt; +} + +inline rad_buf decl_b(RadBuilder* b, const char* name, uint32_t dtype, + std::initializer_list shape, + int kind = RAD_BUF_TRANSIENT, int domain = RAD_DOMAIN_DEVICE) { + RadBufDecl d{}; + d.dtype = dtype; + d.rank = (uint32_t)shape.size(); + int i = 0; + for (int64_t s : shape) d.shape[i++] = s; + d.kind = kind; + d.domain = domain; + return rad_decl_buffer(b, name, &d); +} + +/* Every map starts with src_index all -1: "the whole tensor", which is what all but the stacked + * expert case wants. Zero would mean sub-tensor 0 of every source, which is a silently wrong map. */ +inline RadNameMap map_base(const char* declared, int mode) { + RadNameMap m{}; + m.declared = declared; + m.mode = mode; + for (int i = 0; i < 8; ++i) m.src_index[i] = -1; + return m; +} + +/* A checkpoint tensor copied through unchanged. */ +inline int map_copy(RadBuilder* b, const char* declared, const char* src) { + RadNameMap m = map_base(declared, RAD_MAP_COPY); + m.n_src = 1; + m.src[0] = src; + return rad_decl_name_map(b, &m); +} + +/* A checkpoint tensor copied through, with alternatives: the first source the container actually + * holds wins. This is how a tied lm_head is expressed -- Qwen3 0.6B and 1.7B ship no + * output.weight and the embedding table serves as both, while 8B and up ship one. Without it the + * plugin would need two builds of the same architecture. */ +inline int map_copy_alt(RadBuilder* b, const char* declared, const char* a, const char* c) { + RadNameMap m = map_base(declared, RAD_MAP_COPY); + m.n_src = 2; + m.src[0] = a; + m.src[1] = c; + return rad_decl_name_map(b, &m); +} + +/* One expert's slice of a stacked checkpoint tensor. GGUF stores a MoE layer's experts as one + * ffn_gate_exps of shape [.., n_expert] while placement needs one declared weight per expert, + * because the movement unit is an expert and not a tensor (spec §4.1). src_index carries the + * expert; without it the index would survive only inside the declared name, as a convention + * rad-convert would have to parse. */ +inline int map_slice(RadBuilder* b, const char* declared, const char* src, int index) { + RadNameMap m = map_base(declared, RAD_MAP_COPY); + m.n_src = 1; + m.src[0] = src; + m.src_index[0]= index; + return rad_decl_name_map(b, &m); +} + +/* Two stacked tensors, the same expert out of each, concatenated: gate and up into gate_up. */ +inline int map_slice_concat(RadBuilder* b, const char* declared, + std::initializer_list src, int index, int dim = 0) { + RadNameMap m = map_base(declared, RAD_MAP_CONCAT); + m.n_src = (int)src.size(); + int i = 0; + for (const char* s : src) { m.src[i] = s; m.src_index[i] = index; ++i; } + m.concat_dim = dim; + return rad_decl_name_map(b, &m); +} + +/* A convert-time fusion: q/k/v into one qkv, gate and up into one gate_up. The plugin is the only + * component that knows both sides, and rad-convert reads the map from it (spec §2.4). The fusion + * is worth a comment on its cost: it buys one GEMM launch instead of three and one movement unit + * instead of three, and it costs the ability to place q, k and v on different tiers, which + * nothing wants to do. */ +inline int map_concat(RadBuilder* b, const char* declared, std::initializer_list src, + int dim = 0) { + RadNameMap m = map_base(declared, RAD_MAP_CONCAT); + m.n_src = (int)src.size(); + int i = 0; + for (const char* s : src) m.src[i++] = s; + m.concat_dim = dim; + return rad_decl_name_map(b, &m); +} + +/* ONE LOGICAL TENSOR THE CHECKPOINT STORES AS N SHARDS, named `` for i in + * [0, n). Qwen3.8-Flash-Next's n-gram embedding is 320,001,536 rows in 128 tensors called + * `...ngram_embedding.shard_0.weight` ... `shard_127.weight`, which is thirty times what + * RadNameMap's `src[8]` holds. + * + * So this emits ceil(n/8) CONCAT maps and the core joins them in call order -- see the merge rule + * in core/build/rad_builder.cpp for why the pieces are the answer rather than a bigger array. The + * ORDER IS THE CONCATENATION and shard 0 must come first: a hashed row id addresses the whole + * table and a permuted table is a model that loads, runs, and looks up the wrong embeddings. + * + * Returns the first refusal, or RAD_OK. */ +inline int map_concat_shards(RadBuilder* b, const char* declared, const char* prefix, + const char* suffix, int n, int dim = 0) { + if (n <= 0) return RAD_E_INVAL; + for (int i = 0; i < n; i += 8) { + RadNameMap m = map_base(declared, RAD_MAP_CONCAT); + m.concat_dim = dim; + m.n_src = 0; + char buf[8][256]; + for (int k = 0; k < 8 && i + k < n; ++k) { + std::snprintf(buf[k], sizeof buf[k], "%s%d%s", prefix, i + k, suffix); + m.src[m.n_src++] = buf[k]; + } + const int rc = rad_decl_name_map(b, &m); + if (rc != RAD_OK) return rc; + } + return RAD_OK; +} + +/* ================================================================== buffer liveness */ +/* An op's WEIGHT operands are named at declare; its BUFFER operands are not, and without them a + * transient has no declared use and the planner must assume it live for the whole program -- + * sound, because a plugin may issue any handle in any order, and as wasteful as it sounds. + * + * So every op this library emits states its read and write sets. Returning the handle rather than + * a status is what keeps the declaration one statement: a refusal from rad_op_reads is recorded by + * the builder, with the op named, and surfaces in declare's final report -- the same way a refusal + * from rad_decl_op does. */ +inline rad_op rw(RadBuilder* b, rad_op h, + std::initializer_list reads, + std::initializer_list writes) { + if (h == RAD_NULL_HANDLE) return h; /* an unresolved op has no liveness to declare */ + rad_op_reads (b, h, reads.begin(), (int)reads.size()); + rad_op_writes(b, h, writes.begin(), (int)writes.size()); + return h; +} + +/* ================================================================== geometry */ +/* Dimensions come from model metadata, so one plugin covers every size in a family. Everything + * here is ALREADY DIVIDED by world_size where it is sharded: the plugin declares divided + * dimensions and emits the collectives itself, because a sharding inference pass is a compiler + * pass whose failure mode is a model that produces fluent wrong text on a rank count nobody + * tested (spec §9). */ +/* THE PAGED BLOCK, IN TOKENS. `attn_paged` declares `block_size` RAD_DERIVED -- a value the + * KERNEL supplies -- and libr4d's rows all carry C_EQ("block_size", 16), so on the shipped path + * this is the value that would have been derived anyway and pinning it changes no resolution. + * + * It has to be pinned because DERIVED ONLY WORKS WHEN SOMETHING DERIVES IT. A geometry libr4d has + * no attention kernel for -- Qwen3.5-0.8B is head_dim 256 at gqa 4, and libr4d has 256/6 and + * 128/4 -- resolves to libref, which serves any block size and therefore names none; the KV + * group then cannot be sized and declare refuses the model by name. The block size is a property + * of the CACHE the model is asking for, so the model is the right place to say it. */ +enum { RAD_KV_BLOCK = 16 }; + +struct Geom { + int64_t n_layer = 0; + int64_t n_embd = 0; /* the residual stream. Replicated on every rank. */ + int64_t head_dim = 0; + int64_t n_vocab = 0; /* per rank: lm_head is vocab-sharded (spec §9) */ + int64_t n_vocab_all= 0; + int64_t vocab_off = 0; /* this rank's first vocab row, for the sampler's candidate merge */ + int64_t n_head = 0; /* per rank */ + int64_t n_head_kv = 0; /* per rank */ + int64_t n_head_all = 0; + int64_t n_head_kv_all = 0; + int64_t n_ff = 0; /* per rank */ + int64_t n_ff_all = 0; + int64_t max_tok = 0; + int64_t max_seqs = 0; + int64_t max_ctx = 0; + int max_spec = 0; + /* The most rows the sampler can want in one step: one per sequence, or one per draft position + * per sequence at a speculative verify. It bounds the logits buffer, which at a 248K vocab is + * the difference between 63 MiB and 8 GiB. */ + int64_t max_logit_rows = 0; + int rank = 0; + int world = 1; + /* 1 = the exact all-reduce, 0 = this deployment accepts a lossy wire. Straight through to + * every `all_reduce` this library emits; RadBuildCtx says what it costs and buys. */ + int wire_exact = 1; + /* The byte floor under which the lossy wire is refused and the exact kernel serves the + * message anyway. Straight through to `all_reduce`'s `min_bytes`; 0 leaves the choice to + * the kernel plugin, which has the measured default. */ + int64_t wire_min_bytes = 0; + float eps = 1e-6f; + /* GemmaRMSNorm's `1 +`. Qwen3.5, Qwen3-Next and Gemma normalise with `x_hat * (1 + w)` and + * store `w` around 0.1, not around 1.0 -- so reading the gain as a plain RMSNorm gain shrinks + * every normed activation by five to ten times, at every norm, in every layer. It is a + * property of the ARCHITECTURE and not of a block, which is why it lives here: `rmsnorm`, + * `rmsnorm_add`, `qk_norm_rope_gate` and `rmsnorm_had_quant_i8` all carry a `wadd` parameter + * for it (libref/ref_registry.cpp), every block that declares one passes this, and a + * family whose norms are plain leaves it at zero. + * + * NOT the gated delta net's own `ssm_norm`: RMSNormGated is a plain RMS norm in this family + * too, its gains are around 0.88 in the checkpoint, and `gdn_gated_rmsnorm` has no such + * parameter. Two conventions in one model, which is exactly why this is not a build flag. */ + float wadd = 0.0f; + /* The same question for the per-head q/k norms, separately: they are a different + * tensor with a different distribution (this checkpoint's are PARTLY NEGATIVE, which + * only `1 + w` explains) and a family could answer the two differently. */ + float wadd_qk = 0.0f; + float theta = 1e6f; + float rope_scale = 1.0f; + /* M-RoPE: the checkpoint's `mrope_section`, when it has one. A model whose rotary has several + * position components declares `rope` with `rope_mode` and these sections and hands it + * RadBatch::rope_pos; empty, the rotary is one-component NeoX over `positions`. Stored here + * rather than pointed at, because the container's strings are not guaranteed to outlive + * declare. */ + bool rope_mc = false; + char rope_mode[8] = "neox"; + char rope_sections[24] = ""; + const char* dtype = "bf16"; /* the OPERAND COMBINATION, spec §2.3's dtype key */ + uint32_t act_dtype = RAD_BF16; /* what activation buffers are made of */ + /* THE KV CACHE'S OWN WIDTH, and it is separate from `dtype` because it is a separate decision: + * `dtype` says what the WEIGHTS are and follows the checkpoint, while this follows the cache + * and is a deployment choice the checkpoint has no opinion about. They were one field, which + * read as "the cache is bf16 because the weights are fp8-with-bf16-activations" -- a sentence + * that is true of this checkpoint and is not a rule. Whatever this says must be the spelling + * `rad_dtype_name` gives, because the attention and kv_store rows band on it verbatim. */ + const char* kv_dtype = "bf16"; + /* THE LINEARS ARE PLAIN bf16 WEIGHTS, read by `gemm_nt` over the bf16 activation, in a model + * whose blocks are the fp8 family's (rad_fp8.h). A checkpoint served as it ships -- a dense bf16 + * release, converted without a quantising recipe -- has no scale planes and no use for E4M3 + * activations, so in this mode the producers in front of a linear quantise nothing and declare + * no codes: an `ActFP8` is its bf16 plane alone. It is the MODEL's answer and not a linear's, + * because the producer and its consumers have to agree on it; the plugin reads it off a trunk + * weight's encoding and every linear checks its own against it. */ + bool w_bf16 = false; + + int64_t q_dim() const { return n_head * head_dim; } + int64_t kv_dim() const { return n_head_kv * head_dim; } + int64_t qkv_dim() const { return q_dim() + 2 * kv_dim(); } + int64_t gqa() const { return n_head_kv ? n_head / n_head_kv : 0; } +}; + + +/* THE KV CACHE'S WIDTH, RESOLVED ONCE FOR EVERY ARCHITECTURE. RadBuildCtx::kv_dtype is + * --kv-cache-dtype; RAD_DT_INVALID means the operator did not state one and the plugin's own + * default stands. Every architecture in this tree passes RAD_BF16 as that default. + * + * It is one flag on the build context rather than a per-plugin environment switch: a switch read + * at declare is invisible in the startup log and gives "is this cache fp8" a different answer per + * architecture. It changes what the model computes, so it is a flag. */ +static inline uint32_t rad_kv_cache_dtype(const RadBuildCtx* c, uint32_t dflt) { + return (c && c->kv_dtype != RAD_DT_INVALID) ? (uint32_t)c->kv_dtype : dflt; +} +/* Divide, refusing rather than rounding. A rank count that does not divide the head count is not + * a configuration to approximate: it is a configuration to reject at declare, by name, before any + * weight is mapped. */ +inline int divide_or_fail(int64_t v, int world, const char* what, int64_t* out) { + if (world <= 0 || v % world != 0) { + fprintf(stderr, "radiance: %s = %lld is not divisible by world_size = %d\n", + what, (long long)v, world); + return RAD_E_INVAL; + } + *out = v / world; + return RAD_OK; +} + +/* The vocabulary is the one dimension that does not divide -- 151669 and 248320 are not multiples + * of anything convenient -- and refusing tensor parallel over an awkward vocab size would be + * absurd. So the last rank holds fewer rows. The sampler merges candidate sets rather than + * gathering full logits (spec §9, §13), so a ragged shard costs it nothing; a padded one would + * cost a fake token id that has to be masked everywhere forever. */ +inline int64_t shard_extent(int64_t total, int world, int rank) { + const int64_t per = (total + world - 1) / world; + const int64_t beg = per * rank; + const int64_t end = beg + per < total ? beg + per : total; + return end > beg ? end - beg : 0; +} +inline int64_t shard_begin(int64_t total, int world, int rank) { + const int64_t per = (total + world - 1) / world; + const int64_t beg = per * rank; + return beg < total ? beg : total; +} + +/* A container-header integer under either of the two spellings a key reaches us in: the GGUF one + * (`qwen35.ssm.state_size`) and the HuggingFace one (`linear_key_head_dim`). One plugin serves a + * .rad converted from either source, and the alternative is a second plugin that differs only in + * its string literals. `found` says whether the value was read or defaulted, because a geometry + * that silently defaults is a model that silently becomes a different model. */ +inline long long meta_int2(const RadModelMeta* m, const char* gguf_key, const char* hf_key, + long long dflt, bool* found = nullptr) { + const long long sentinel = -0x7FFFFFFFll; + long long v = rad_meta_geti(m, gguf_key, sentinel); + if (v == sentinel) v = rad_meta_geti(m, hf_key, sentinel); + if (found) *found = (v != sentinel); + return v == sentinel ? dflt : v; +} + +inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c, + const char* dtype, uint32_t act_dtype) { + if (!m || !c) return RAD_E_INVAL; + if (c->is_draft) { + /* A drafter declared into this plugin would need a second set of per-rank handles and a + * second name-map namespace. Nothing unimplemented returns success (spec §17). */ + fprintf(stderr, "radiance: this plugin has no draft scope\n"); + return RAD_E_UNSUPPORTED; + } + if (c->rank < 0 || c->rank >= MAX_RANKS) return RAD_E_INVAL; + + g.n_layer = m->n_layers; + g.n_embd = m->n_embd; + g.head_dim = m->head_dim ? m->head_dim : (m->n_head ? m->n_embd / m->n_head : 0); + g.n_head_all = m->n_head; + g.n_head_kv_all = m->n_head_kv ? m->n_head_kv : m->n_head; + g.n_ff_all = m->n_ff; + g.n_vocab_all = m->n_vocab; + g.max_tok = c->max_tok; + g.max_seqs = c->max_seqs; + g.max_ctx = c->max_ctx; + g.max_spec = c->max_spec; + g.max_logit_rows = c->max_seqs * (c->max_spec > 0 ? c->max_spec + 1 : 1); + if (g.max_logit_rows > c->max_tok) g.max_logit_rows = c->max_tok; + /* The engine's KL mode reads a row at every prompt position (RadBuildCtx::max_out_rows), which + * is more rows than tokens: the sampler's own rows come first and repeat a scored one. */ + if (c->max_out_rows > g.max_logit_rows) g.max_logit_rows = c->max_out_rows; + g.rank = c->rank; + g.world = c->world_size ? c->world_size : 1; + g.wire_exact= c->tp_wire_lossy ? 0 : 1; + g.wire_min_bytes = c->tp_wire_min_bytes; + g.eps = m->rms_eps; + g.theta = m->rope_theta; + g.rope_scale= m->rope_scale ? m->rope_scale : 1.0f; + g.dtype = dtype; + g.act_dtype = act_dtype; + { + const char* sec = rad_meta_gets(m, "rope_parameters.mrope_section", + rad_meta_gets(m, "text_config.rope_parameters.mrope_section", + "")); + if (sec && *sec) { + const bool inter = + rad_meta_geti(m, "rope_parameters.mrope_interleaved", + rad_meta_geti(m, "text_config.rope_parameters.mrope_interleaved", + 0)) != 0; + g.rope_mc = true; + std::snprintf(g.rope_mode, sizeof g.rope_mode, "%s", inter ? "imrope" : "mrope"); + std::snprintf(g.rope_sections, sizeof g.rope_sections, "%s", sec); + } + } + + if (g.n_layer <= 0 || g.n_embd <= 0 || g.head_dim <= 0 || g.n_head_all <= 0 || + g.n_ff_all <= 0 || g.n_vocab_all <= 0 || g.max_tok <= 0) + return RAD_E_INVAL; + /* eps and theta are read, not defaulted. A container that omits them and gets 1e-6 and 1e6 + * anyway is a container that silently becomes a different model, and the symptom is fluent + * wrong text. */ + if (!(g.eps > 0.0f) || !(g.theta > 0.0f)) { + fprintf(stderr, "radiance: container gives rms_eps=%g rope_theta=%g; both are required\n", + (double)g.eps, (double)g.theta); + return RAD_E_INVAL; + } + + int s; + if ((s = divide_or_fail(g.n_head_all, g.world, "n_head", &g.n_head)) < 0) return s; + /* A world size larger than n_head_kv would need the KV heads replicated across ranks rather + * than split, which is a different attention declaration and not a rounding decision. Refuse + * it here rather than have the block quietly produce a zero-width KV projection. */ + if ((s = divide_or_fail(g.n_head_kv_all, g.world, "n_head_kv", &g.n_head_kv)) < 0) return s; + if ((s = divide_or_fail(g.n_ff_all, g.world, "n_ff", &g.n_ff)) < 0) return s; + /* THE VOCABULARY IS SPLIT. r4d_sample_topk_f32 takes a vocabulary offset and packs its + * candidates as (u32 GLOBAL id, f32 logit) pairs, and the all-gather places every rank's + * pairs for one sampled position side by side, which is the layout sample_merge_topk reads. + * lm_head is therefore ROW-SHARDED and a rank reads half of it: on Qwen3.8-27B that is + * 1.27 GiB of the 16.1 GiB a rank reads per decode step, which makes the logits GEMM a + * large single item in the decode budget. + * + * The last rank is SHORT rather than padded -- 248320 and 151669 divide by nothing convenient + * -- because the sampler merges candidate sets rather than gathering full logits, so a ragged + * shard costs it nothing and a padded one would cost a fake token id masked everywhere + * forever. core/engine.cpp restates this split and checks its restatement against the width + * the plugin declared. */ + g.n_vocab = shard_extent(g.n_vocab_all, g.world, g.rank); + g.vocab_off = shard_begin (g.n_vocab_all, g.world, g.rank); + if (g.n_vocab <= 0) return RAD_E_INVAL; + return RAD_OK; +} + +/* ================================================================== a vocab-sharded draft head */ +/* WHETHER A DRAFTER'S OWN HEAD CAN BE VOCAB-SHARDED, and it lives here because both the block that + * declares the op and the plugin that sizes the buffer under it have to give the SAME answer -- a + * buffer that disagreed with the op declared over it is a read past its end. Every drafter asks + * the identical question, so the test lives in one place: two copies of a rule this exact are two + * things to keep in step. + * + * IT REFUSES A RAGGED OR UNALIGNED SHARD rather than working around it. The packed w2a8 layout is + * TILE-MAJOR at 16 output rows a block, so a rank whose share is not a multiple of 16 has a block + * spanning two ranks and there is no row shard of it at all; and the candidate merge's global ids + * are `rank * n_vocab + local`, which is only true of a contiguous, equally-sized split. Either + * one wrong is fluent text with the wrong tokens in it. */ +inline bool vocab_head_sharded(const Geom& g) { + return g.world > 1 && g.n_vocab > 0 && (g.n_vocab % 16) == 0 && + g.n_vocab * (int64_t)g.world == g.n_vocab_all && + g.vocab_off == (int64_t)g.rank * g.n_vocab; +} +/* Rows of such a head, and therefore the width of its logit plane, on THIS rank. */ +inline int64_t vocab_head_rows(const Geom& g) { + return vocab_head_sharded(g) ? g.n_vocab : g.n_vocab_all; +} + +/* ================================================================== the KV cache operand */ +/* attn_paged and kv_store take the group's cache as an operand. RadKVGroupBatch carries the slot + * mapping, the block table and the sequence lengths, but the pool base belongs to the block + * manager and not to the batch -- so the operand names the GROUP and the LAYER and the core + * resolves it, the same way it resolves a weight handle. */ +inline RadOperand kv_cache(rad_kvgroup group, int layer) { return RAD_KV(group, layer); } + +/* ================================================================== step-sized operands */ +/* EVERY OPERAND A STEP ISSUES CARRIES THE STEP'S ROW COUNT, NOT THE BUFFER'S. + * + * A ranged parameter is collapsed to a BAND when the instance is resolved (spec §2.2) and + * `rad_issue` carries the actual value as an integer rather than by rewriting the parameter list, + * so a kernel cannot read the row count out of `M`: it would get the band's upper bound. + * libref therefore reads every extent off the operands (libref/ref_ops.h), and an + * operand handed over at its declared extent means a single-row decode computed over all 8192 rows + * of an arena buffer -- reading uninitialised memory and writing over the next op's input. + * + * So the run phase narrows, and these three helpers are how. `rows` is dim 0, which is tokens for + * every activation buffer in this library; the strides are products of the trailing dimensions, so + * shortening the outermost one leaves all of them correct (core/runtime/issue.cpp says the same). + */ +inline RadOperand brows(rad_buf h, int64_t rows) { + RadOperand o = RAD_B(h); + o.rows = rows; + return o; +} + +/* A column slice narrowed to this step's rows: the two together, because every strided view this + * library takes is also row-narrowed and spelling it as two calls invites forgetting one. */ +inline RadOperand bcol(rad_buf h, int64_t first, int64_t width, int64_t rows) { + RadOperand o = RAD_B_COL(h, first, width); + o.rows = rows; + return o; +} + + +/* A COLUMN SLICE OF A RANGE OF ROWS. `offset` is a flat element offset and `cols` narrows the last + * dimension with the declared width kept as the stride, so the two compose: first_row * pitch + * picks the row, first_col picks the column within it (core/runtime/issue.cpp says the same). + * + * The mixed step is what needs it. A block that issues the recurrent path over the decode rows and + * the chunked path over the prefill ones is issuing each over a RANGE of tokens, and the operands + * it hands them are already column views of a fused projection. */ +inline RadOperand bcol_at(rad_buf h, int64_t first_row, int64_t pitch, + int64_t first_col, int64_t width, int64_t rows) { + RadOperand o = RAD_B(h); + o.offset = first_row * pitch + first_col; + o.rows = rows; + o.cols = width; + return o; +} + +/* A RANGE OF ROWS, offset and count. The element offset is `first * pitch` because a buffer's + * rows are its declared width apart and RadOperand::offset is in elements; dim 0 is then narrowed + * to `n`, which is what makes the slice a tensor the kernel sees as [n, pitch]. + * + * It exists because one op can cap the whole step. A libr4d kernel is constrained to a band, and + * an op whose widest kernel stops at M=64 forces every op in the step down to 64 tokens -- on this + * model that is the delta net's 96-column a|b projection, 0.5% of the layer's projection bytes, + * holding the prefill chunk of a 27B model to 64. Issuing that one op in slices costs a launch per + * 64 rows and lets everything else run at the chunk the scheduler wanted. */ +inline RadOperand brow_slice(rad_buf h, int64_t first, int64_t n, int64_t pitch) { + RadOperand o = RAD_B(h); + o.offset = first * pitch; + o.rows = n; + return o; +} + +/* A batch field: a pointer the core did not allocate, so it has no declared shape and the row + * count has to come from here. Without it the operand arrives rank 0 and a kernel that sizes its + * loop by numel(positions) runs one token. */ +/* A dense two-dimensional batch field: [rows, cols], packed. The block table is the one that + * needs it -- see RAD_P_T2 in rad_runtime.h for why a rank-1 spelling is not enough. */ +inline RadOperand praw2(const void* p, uint32_t dtype, int64_t rows, int64_t cols) { + return RAD_P_T2(p, dtype, rows, cols); +} + +inline RadOperand praw(const void* p, uint32_t dtype, int64_t rows) { + RadOperand o = RAD_P_T(p, dtype); + o.rows = rows; + return o; +} + +/* THE ROTARY POSITIONS OF A PASS, in the two forms its consumers take. + * + * `rope_pos1` is one component a token: RadBatch::rope_pos's plane 0 when the batch carries the + * planes, `positions` when it does not. It is what a cos/sin table is filled and read at, and it + * is exact for every token of a pass whose components agree (RadBatch::rope_mixed 0) -- so a + * fused path that reads it is taken only then. + * + * `rope_posmc` is what a multi-component `rope` takes: the dense [3, T] planes for an M-RoPE model + * with a batch that carries them, and the one-component form otherwise -- which every mode reads + * as NeoX, so a model without M-RoPE and a text-only deployment rotate over `positions` alone. */ +inline RadOperand rope_pos1(const RadBatch* b, int64_t T) { + return praw(b->rope_pos ? b->rope_pos : b->positions, RAD_I32, T); +} +inline RadOperand rope_posmc(const Geom& g, const RadBatch* b, int64_t T) { + if (g.rope_mc && b->rope_pos) return praw2(b->rope_pos, RAD_I32, 3, T); + return praw(b->positions, RAD_I32, T); +} +/* Does a pass have a token whose rotary components differ -- which a one-component fused path + * cannot rotate. */ +inline bool rope_mixed(const RadBatch* b) { return b->rope_pos && b->rope_mixed; } + +/* `rope` declared for the geometry's rotary: M-RoPE's mode and sections when the model has them, + * `mode` otherwise. */ +inline rad_op decl_rope(RadBuilder* b, const Geom& g, int64_t rows, int64_t head_dim, + int64_t n_head, int64_t n_head_kv, int64_t rot, const char* mode) { + if (g.rope_mc) + return RAD_OP(b, "rope", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", head_dim), + RAD_INT("n_head", n_head), RAD_INT("n_head_kv", n_head_kv), + RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale), + RAD_STR("mode", g.rope_mode), RAD_INT("rotary_dim", rot), + RAD_STR("sections", g.rope_sections)), + RAD_NOWEIGHTS); + return RAD_OP(b, "rope", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", head_dim), + RAD_INT("n_head", n_head), RAD_INT("n_head_kv", n_head_kv), + RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale), + RAD_STR("mode", mode), RAD_INT("rotary_dim", rot)), + RAD_NOWEIGHTS); +} + + +/* HOW MANY OF THIS STEP'S SEQUENCES ARE DECODE ROWS, AND WHERE THEIR TOKENS END. + * + * A block that issues one path over the decode rows and another over the prefill chunks needs the + * boundary, and for a MIXED step RadBatch::n_seq_decode is the only thing that carries it. For a + * pure step it is not: PREFILL means none of them and DECODE means all of them, by definition of + * the phase, and asking the phase first is what makes the two fields optional there. A batch that + * sets phase and leaves them zero -- a test, a bench harness, an out-of-tree caller -- would + * otherwise be handed the prefill path by a block that read them alone, with nothing to say so. + * tests/arch_test.cpp covers exactly that case. + * + * The core sets both fields on every step including the pure ones, so this agrees with them; it + * is the fallback that matters, not the answer. */ +inline void batch_split(const RadBatch* b, int64_t* n_seq_dec, int64_t* n_tok_dec) { + switch (b->phase) { + case RAD_PHASE_PREFILL: *n_seq_dec = 0; *n_tok_dec = 0; break; + case RAD_PHASE_DECODE: *n_seq_dec = b->n_seq; *n_tok_dec = b->n_tok; break; + default: *n_seq_dec = b->n_seq_decode; *n_tok_dec = b->n_tok_decode; break; + } +} + +/* The step batch's entry for one declared KV group. The batch is built once per step by the core + * and shared by every layer and every group (spec §8); this is the lookup, not a computation. */ +inline const RadKVGroupBatch* kv_batch(const RadBatch* b, rad_kvgroup group) { + for (int i = 0; i < b->n_kv_groups; ++i) + if (b->kv[i].group == group) return &b->kv[i]; + return nullptr; +} + +/* ================================================================== the plugin exports */ +/* The four C symbols spec §2.4 names, wired to a namespace. Defining them through a macro keeps + * the plugin source free of extern "C" boilerplate, and RAD_ARCH_NO_EXPORTS lets the unit test + * include two plugin sources into one translation unit without the exports colliding -- which is + * what makes the declared graph testable with no GPU and no model file. */ +/* QUANT is the container's quantisation descriptor this plugin serves, "" for an unquantised one. + * It is the second half of the selection key (spec §2.4, rad_builder.h): qwen35_bf16 and + * qwen35_fp8 both answer "qwen35" to rad_arch_id and differ only here. */ +#define RAD_ARCH_PLUGIN(NS, ID, QUANT, VERSION, DESC) \ + extern "C" const char* rad_arch_id(void) { return ID; } \ + extern "C" const char* rad_arch_quant(void) { return QUANT; } \ + extern "C" int rad_arch_declare(RadBuilder* b, const RadModelMeta* m, \ + const RadBuildCtx* c) { return NS::declare(b, m, c); } \ + extern "C" void rad_arch_step(struct RadCtx* c, const struct RadBatch* batch) { \ + NS::step(c, batch); \ + } \ + extern "C" uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; } \ + extern "C" const RadPluginInfo* rad_plugin_info(void) { \ + /* The PLUGIN's name, not the architecture id: rad_abi.h spells the convention out \ + * ("qwen3_dense_bf16"), the registry requires plugin names to be unique, and a family \ + * with one plugin per weight format has several plugins per architecture. Passing ID \ + * here would make qwen35_bf16 and qwen35_fp8 both "qwen35", and the second would be \ + * refused at load. */ \ + static const RadPluginInfo info = { RAD_PLUGIN_ARCH, #NS, VERSION, DESC, "" }; \ + return &info; \ + } + + +/* THE FIFTH EXPORT, AND IT IS OPT-IN. A plugin that has nothing to say before declare does not + * define it; the core reads the absence as "no opinion" and every field of RadArchProbe keeps its + * zero. Separate from RAD_ARCH_PLUGIN rather than folded into it so that adding a question to + * RadArchProbe never makes an existing plugin fail to compile. */ +#define RAD_ARCH_PROBE(NS) \ + extern "C" int rad_arch_probe(const RadModelMeta* m, RadArchProbe* out) { \ + return NS::probe(m, out); \ + } + +/* THE REPLY FORMAT, ALSO OPT-IN. A plugin whose model spells its reasoning and tool calls in a way + * the chat template's analysis does not find -- or finds wrongly -- states it here once, and the + * reply parser, the lazy call grammar and its trigger words all follow from it. NS::chat_format + * returns a pointer to static storage with struct_size = sizeof(RadChatFormat), or null to let + * the template decide for this particular model. */ +#define RAD_ARCH_CHAT_FORMAT(NS) \ + extern "C" const RadChatFormat* rad_arch_chat_format(const RadModelMeta* m) { \ + return NS::chat_format(m); \ + } + +} /* namespace arch */ +} /* namespace rad */ + +#endif /* RAD_ARCH_H */ diff --git a/arch/common/rad_block_attn_fp8.h b/arch/common/rad_block_attn_fp8.h new file mode 100644 index 00000000..935c01ed --- /dev/null +++ b/arch/common/rad_block_attn_fp8.h @@ -0,0 +1,225 @@ +/* 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 +#include + +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; + } + + 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 */ diff --git a/arch/common/rad_block_attn_gated.h b/arch/common/rad_block_attn_gated.h new file mode 100644 index 00000000..d59bde61 --- /dev/null +++ b/arch/common/rad_block_attn_gated.h @@ -0,0 +1,369 @@ +/* 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; + } + + /* ---- 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's business. */ + 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 */ diff --git a/arch/common/rad_block_attn_gated_fp8.h b/arch/common/rad_block_attn_gated_fp8.h new file mode 100644 index 00000000..16d8945e --- /dev/null +++ b/arch/common/rad_block_attn_gated_fp8.h @@ -0,0 +1,550 @@ +/* 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 +#include + +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; + + 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)); + 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)); + + /* 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 */ diff --git a/arch/common/rad_block_dflash2.h b/arch/common/rad_block_dflash2.h new file mode 100644 index 00000000..3033b210 --- /dev/null +++ b/arch/common/rad_block_dflash2.h @@ -0,0 +1,999 @@ +/* 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 */ diff --git a/arch/common/rad_block_dspark.h b/arch/common/rad_block_dspark.h new file mode 100644 index 00000000..7495d4fe --- /dev/null +++ b/arch/common/rad_block_dspark.h @@ -0,0 +1,926 @@ +/* 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 + * ``; 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 `` 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; + }; + 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); + op_fnorm[i] = decl_norm(w_fnorm[i], true); + if (!op_anorm[i] || !op_fnorm[i]) return RAD_E_INVAL; + } + op_outnorm = decl_norm(w_norm, true); + 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_outnorm || !op_qat) return RAD_E_INVAL; + + for (int64_t l = 0; l < g.n_layer; ++l) { + const int i = (int)l; + 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_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}); + + /* ---------------------------------------------------------------- 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 + `, 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 */ diff --git a/arch/common/rad_block_gdn.h b/arch/common/rad_block_gdn.h new file mode 100644 index 00000000..ae5155c4 --- /dev/null +++ b/arch/common/rad_block_gdn.h @@ -0,0 +1,398 @@ +/* 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 + +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 */ diff --git a/arch/common/rad_block_gdn_fp8.h b/arch/common/rad_block_gdn_fp8.h new file mode 100644 index 00000000..833e2af0 --- /dev/null +++ b/arch/common/rad_block_gdn_fp8.h @@ -0,0 +1,519 @@ +/* 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 +#include +#include + +namespace rad { +namespace arch { + +struct GdnFP8 { + /* The same geometry the bf16 block takes, with one addition: `ab_dim` is what the split costs + * in declared width, and it is 2 * n_head_v. */ + 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 */ diff --git a/arch/common/rad_block_hc.h b/arch/common/rad_block_hc.h new file mode 100644 index 00000000..4d93fa95 --- /dev/null +++ b/arch/common/rad_block_hc.h @@ -0,0 +1,402 @@ +/* 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. */ + rad_op ar_write(int64_t T) const { + return ar_wire_is_exact(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. */ + if (c.reduce && g.world == 2) + op_ar_write = 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_NOWEIGHTS), + {w.x.x, w.inj, w.h}, {w.x.x, w.h}); + if (op_ar_write && !g.wire_exact) + 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; + const bool shared = src.sh && src.sg; + gsrc = src; + /* EVERY ROW COUNT ONE PASS CARRIES, prefill chunks included: 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; + if (rows > g.max_tok) rows = g.max_tok; + 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_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; + RAD_ISSUE_N(c_, ar_wire_is_exact(g, T) ? op_ar_gather_write : op_ar_gather_write6, 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 */ diff --git a/arch/common/rad_block_mlp.h b/arch/common/rad_block_mlp.h new file mode 100644 index 00000000..7e93ce71 --- /dev/null +++ b/arch/common/rad_block_mlp.h @@ -0,0 +1,123 @@ +/* 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 */ diff --git a/arch/common/rad_block_mlp_fp8.h b/arch/common/rad_block_mlp_fp8.h new file mode 100644 index 00000000..326bb2e2 --- /dev/null +++ b/arch/common/rad_block_mlp_fp8.h @@ -0,0 +1,203 @@ +/* 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{ w.ffn.q, w.ffn.s, w.ffn.x } + : std::initializer_list{ 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 */ diff --git a/arch/common/rad_block_moe_fp8.h b/arch/common/rad_block_moe_fp8.h new file mode 100644 index 00000000..e490159b --- /dev/null +++ b/arch/common/rad_block_moe_fp8.h @@ -0,0 +1,1555 @@ +/* rad_block_moe_fp8.h -- the ROUTED feed-forward block with block-scaled FP8 experts. + * + * rmsnorm -> quant_act_fp8 -> router gemm -> router_topk -> moe_scatter + * -> gate_up moe_gemm_q -> silu_mul + quant -> down moe_gemm_q + * -> moe_gather + * -> [shared expert: gate_up -> silu_mul + quant -> down -> gate] + * -> add -> [all_reduce] -> residual add + * + * IT IS rad_block_mlp_fp8.h WITH THE FEED-FORWARD ROUTED, and everything that block's header + * argues -- why the gate/up fusion survives block scaling, why the norm and the residual add and + * the collective are one op, why the activations between ops stay bf16 -- is argued there and not + * repeated. What follows is only what routing changes. + * + * ============================== THE SHARED EXPERT IS NOT OPTIONAL HERE ============================== + * + * Qwen3.5-MoE runs a dense expert BESIDE the routed ones on every token, gated by a one-output + * projection: `y = routed(x) + sigmoid(shared_gate(x)) * shared(x)`. It is `mlp.shared_expert.*` + * and `mlp.shared_expert_gate.weight` in the checkpoint, and a block that dropped it would produce + * a plausible distribution and the wrong model. `moe_gather` does the multiply as it sums the + * routed slots -- see docs/OPS.md's `scale_rows` for why `mul` cannot do it, and note that the + * gate is applied to the SCALAR before the multiply, not to the product. + * + * A family without one passes `Src::shared` null and the whole arm disappears, buffers included. + * + * ============================== WHY THE BLOCK SLICES ITS ROWS ============================== + * + * The expert path's intermediates are `top_k` times as tall as the step: at an 8192-token chunk and + * top_k 8 the down-projection's input alone is 65536 rows, which at n_embd 2048 is 256 MiB of + * transient for ONE buffer. So the block runs in passes of at most `Config::rows` tokens and its + * buffers are declared at that height. Routing is per pass and has to be -- `expert_offset` and + * `sorted_tok` describe the rows of one pass -- which is not an approximation: a token's routing + * depends on that token alone, so a pass computes exactly the rows it names. + * + * THE DEFAULT IS 2048 AND THAT IS THE CHUNK, not a tuning choice: core/sched/geometry.cpp clamps + * the prefill chunk to the linear-state checkpoint interval, which on this family is 2048, so the + * shipped configuration is one pass and the slicing is inert. It exists so that a deployment with a + * larger chunk does not need this file edited. + * + * ============================== THE EXPERT WEIGHTS ARE EIGHT RUNS ============================== + * + * `moe_gemm_q` takes its weights as TABLES (RAD_OPD_WTAB), and a table is a run of CONSECUTIVELY + * DECLARED handles -- `RAD_WTAB(first, n)` names the first and the count. It takes each + * projection's experts as TWO tables by parity, the even experts and the odd ones, because every + * entry of a table has one geometry and a rank holding an uneven slice of each expert has two (see + * Config::ff_lo). So the arrays are declared in separate loops -- gate_up codes, gate_up scales, + * down codes, down scales, each for the even experts and then the odd ones -- and NOT as a group + * per expert. Interleaving them would give runs of stride two or four, which the operand cannot + * express; the failure would be a table whose second entry is a scale plane. + * + * The codes run and the scale run of a projection are two VIEWS of one stored weight -- its codes + * plane and its scale plane (RadWeightDecl::source) -- so an expert holds two logical weights, + * gate_up and down, and is its own movement unit (`grp_expert_slot`, slots 0 and 1) and + * RAD_ACCESS_CONDITIONAL, which is what lets the placement planner tier them and the heat engine + * promote the hot ones. + */ +#ifndef RAD_BLOCK_MOE_FP8_H +#define RAD_BLOCK_MOE_FP8_H + +#include "rad_fp8.h" +#include "rad_device.h" + +#include +#include +#include +#include +#include + +namespace rad { +namespace arch { + +/* THE MOST ROUTING SLOTS THE SORT SERVES IN ONE WORKGROUP, which is what bounds + * `router_topk_scatter`. It is libr4d's `kScatterSmall` and it is stated here rather than asked + * of the plugin for the reason every other such bound in this library is: the architecture has to + * decide, at declare time and identically on both ranks, whether the op exists at all. */ +static const int64_t kMoeSortRows = 1024; + + + +/* ---- RADIANCE_DEBUG_ROUTING: the routing WEIGHTS of token 0, which nothing else reports. + * + * The core's histogram (core/runtime/ctx.cpp) says which experts a step chose and rad_arch.h's + * dbg_resid says how big each arm's contribution was; neither shows the weights themselves, and a + * router whose top-k sums to 0.4 instead of 1 is a block that is right in every other respect and + * scaled down by more than half. It SYNCHRONISES THE STREAM and is off unless the variable is set: + * a layer number, or negative for every layer. */ +inline void moe_debug_weights(RadCtx* c_, int layer, int64_t top_k, rad_buf ids, rad_buf ew) { + static const char* dbg = std::getenv("RADIANCE_DEBUG_ROUTING"); + if (!dbg || !ids || !ew) return; + const int want = (int)std::strtol(dbg, nullptr, 10); + if (want >= 0 && layer != want) return; + static int seen[256] = {0}; + if (seen[layer & 255]++) return; + + void* pi = rad_buf_ptr(c_, ids); + void* pw = rad_buf_ptr(c_, ew); + if (!pi || !pw) return; + RadStream s = rad_stream(c_); + std::vector vi((size_t)top_k); + std::vector vw((size_t)top_k); + rad_memcpy_async(vi.data(), pi, top_k * 4, s); + rad_memcpy_async(vw.data(), pw, top_k * 2, s); + rad_stream_sync(s); + + std::string line; + double sum = 0.0; + for (int64_t r = 0; r < top_k; ++r) { + const uint32_t u = (uint32_t)vw[(size_t)r] << 16; + float f; + std::memcpy(&f, &u, 4); + sum += f; + char b[48]; + std::snprintf(b, sizeof b, "%s%d:%.4f", r ? " " : "", vi[(size_t)r], f); + line += b; + } + std::fprintf(stderr, "D moe layer %d token 0 top_k = %s (sum %.4f)\n", + layer, line.c_str(), sum); +} + +/* THE MOST EXPERTS A LAYER PROTECTS ON ONE RANK (MoeFP8::prot): libr4d's sort takes at most eight + * in its `protect` list. */ +constexpr int64_t kMaxProtected = 8; + +struct MoeFP8 { + struct Config { + /* ROUTED EXPERTS THIS RANK OWNS. Equal to `n_expert_all` in every deployment that does not + * use expert parallelism -- every rank then holds a slice of every expert (see ff_lo). A + * calibration run is the one that splits the experts themselves, because a Hessian is + * over an expert's whole K. */ + int64_t n_expert = 0; + /* THE MODEL'S expert count -- what the ROUTER is wide in and what top_k picks from. 0 means + * "the same as n_expert", the whole-model case. + * + * The router stays replicated under expert parallelism and that is the property the scheme + * rests on: every rank scores every expert from the same residual stream and picks the + * same top_k, so the ranks agree on the routing without a collective. Each then sorts only + * the slots that landed in ITS range and the block's end-of-block all-reduce sums the + * partials. Sharding the router instead would have two ranks disagree about where a token + * went, and the all-reduce would sum two different models. */ + int64_t n_expert_all = 0; + /* This rank's first expert id, in the model's numbering. Straight through to moe_scatter, + * which subtracts it so the offsets, the counts and the weight table are all local. */ + int64_t expert_base = 0; + int64_t top_k = 0; + int64_t n_ff_exp = 0; /* one expert's intermediate width, PER RANK */ + /* THE ROUTED EXPERTS' SLICE ON THIS RANK WHEN THEIR WIDTH DOES NOT HALVE INTO WHOLE fp8 + * SCALE BLOCKS: expert e's intermediate columns [ff_lo[e % 2], ff_hi[e % 2]) in the model's + * numbering, the slice depending on the expert's PARITY. hi 0 is the even split (or no + * split). `n_ff_exp` is then the wider slice, which is what the buffers between the two + * grouped GEMMs are. + * + * WHY BY PARITY. This family's expert is 640 columns, five 128-column blocks, so two ranks + * split each expert three blocks and two. Giving every expert's three blocks to one rank + * would make that rank read 3/5 of every routed expert; alternating which rank takes three + * by the expert's parity makes the ranks equal on average, and unequal only by the + * difference between how many even and odd experts a step routes -- a fifth of an expert + * per unit of that difference, where splitting the EXPERTS between the ranks (expert + * parallelism) is unequal by whole experts, the binomial spread of which rank the routed + * experts land on. The block's all-reduce turns that spread into the faster rank waiting, + * about a millisecond a step at one sequence. + * + * Every rank computes its slice of every routed expert: its gate/up rows and its K slice of + * down, and the all-reduce sums the partials -- the routing weight multiplies each partial, + * and the sum of the partials is the expert's output. Rounding moves (two partial sums + * where there was one), so this is checked by agreement rather than byte for byte. */ + int64_t ff_lo[2] = { 0, 0 }, ff_hi[2] = { 0, 0 }; + int64_t n_ff_shared = 0; /* the shared expert's, per rank; 0 = no shared expert */ + /* THE SHARED ARM'S SLICE ON THIS RANK, when its width does not halve into whole fp8 scale + * blocks: [shared_lo, shared_hi) of its columns in the model's numbering, with + * `n_ff_shared` then the slice's width. hi 0 is the even split (or no split at world 1); + * an empty slice declares no arm on this rank. + * + * WHY A SLICE AND NOT ONE RANK. This family's shared expert is 640 columns, five + * 128-column blocks, so two ranks cannot halve it -- and computing it on one rank alone + * makes the ranks unequal at every routed layer, which the block's all-reduce turns into + * the other rank waiting: about 20 us a layer at one sequence, which costs far more than + * the arm's own bytes. Slicing it three blocks and two puts both ranks within one block of + * each other: each computes its columns of the gate/up product, its own K slice of the + * down projection, scales that partial by the replicated gate, and the all-reduce sums the + * partials -- `sgate * (down_0 + down_1)` is the arm, since the gate is a per-token + * scalar. Rounding moves (two partial sums where there was one), so this is checked + * against the unsplit arm by agreement rather than byte for byte. + * + * The arm's stages run behind the routed ones on the same queue (see pass()): a routed + * GEMM's tail leaves compute units idle, and the arm fills them. */ + int64_t shared_lo = 0, shared_hi = 0; + int norm_topk = 1; /* renormalise the kept routing weights to sum to one */ + /* THE EXPERT WEIGHT AT FOUR BITS rather than E4M3, which for Qwen3.8-Flash-Next is the + * difference between a model that fits two cards and one that does not (the registry row + * for `moe_gemm_w4a8` carries the placement report that says so). It is the STORED + * encoding of the experts -- `i4*bf16[1x128]` against `fp8_e4m3*bf16[128x128]` -- so it is + * not a choice made here: probe() reads it off the first expert's encoding, which is the + * container's, the checkpoint's, or the recipe rad-convert is applying, and declare() + * refuses an expert whose encoding is not the one probed. + * + * A packed 4-bit row is K/2 bytes, so a width shard has to fall on a scale group; the + * per-rank checks in declare() say so by name. */ + int expert_w4 = 0; + /* AND ROTATED: a 128-wide Walsh-Hadamard along K baked into the stored expert weight and + * into the activation that meets it -- the encoding's `fwht128` transform, read off it as + * `expert_w4` is, and only meaningful with it (dtype `w4a8h`). + * + * WHAT IT COSTS AT RUNTIME, stated because it is the part that is easy to miss. The + * rotation itself is free: it rides in the quantiser's registers on a launch already + * being paid. The DOWN projection is free outright -- its input comes from this block's + * own gated quantiser, which nothing else reads, so that op simply becomes the rotated + * one. The GATE_UP projection is not: its input is the block's normed activation, which + * the SHARED expert also reads at fp8 and which must therefore stay unrotated, so a + * second (q, scale) pair and one extra `had_quant_act_fp8` launch a layer are the price + * of keeping the shared arm byte-identical. + * + * ON ITS OWN A ROTATION IS WORSE FOR ROUNDING: it fixes RANGE, and group-128 absmax + * already handles range -- 2x worse for RTN int4 on the 27B. It is the basis GPTQ's error + * feedback quantises in, and the pair is what the served container carries. */ + int expert_rot = 0; + /* AND A CODEBOOK: the rotated codes index a sixteen-entry `table` plane -- libquant's + * `table=w4nl`, non-uniform levels fitted to the rotated weights -- rather than standing + * for -8..7 (dtype `w4nla8h`). Only with `expert_rot`, which it implies; the scale grid, + * the activation and the GEMM are the rotated form's, and the codes view selects the table + * beside the codes so the kernel's relayout can check it is the table it decodes. */ + int expert_nl = 0; + /* AND ITS SCALES A 64 OF K: one E4M3 byte under a fixed 2^-13 (dtype `w4nl64a8h`, libr4d's + * kW4G64Scale) where the codebook form has one bf16 a 128 -- the same bytes. Only with + * `expert_nl`. The scale views select the fixed second level beside the scales, which the + * relayout checks is the kernel's constant. 2 for a 64, 4 for a 32 (`w4nl32a8h`, twice + * the scale bytes): the scale groups a 128 of K. */ + int expert_g64 = 0; + /* AND ITS CODES FIVE BITS: libquant's 32-level `table=w5nl` at w4nl64a8h's scales (dtype + * `w5nl64a8h`), the sign of each code its high bit. Only with `expert_g64` 2. This is the + * PROBED layer's; the 64-group codebook forms may differ by layer and by projection, and + * declare() resolves each layer's two (MoeFP8::fmt). */ + int expert_w5 = 0; + /* PLAIN bf16 -- the checkpoint's own experts, converted without a quantising recipe. Both + * GEMMs are then `moe_gemm` over one table of whole experts and the bf16 activation, with + * `silu_mul` between them, and the shared arm follows the trunk (Geom::w_bf16). An expert + * cannot be sliced by parity here -- a bf16 expert is served whole on its rank, which is + * also what keeps it one run of the container for the file tier. */ + int expert_bf16 = 0; + /* The layer and the GLOBAL expert whose gate_up probe() read the format from and therefore + * mapped; declare() maps every other. -1 for the layer: none. */ + int64_t probed_layer = -1; + int64_t probed_expert = 0; + /* How many experts from `probed_expert` on probe() mapped: it reads past experts a + * quantised layer keeps plain bf16 (see `prot`) to the first one in the layer's format. */ + int64_t probed_count = 1; + /* THE GPTQ CALIBRATION TAP. On, this block declares an f32 [K, K] PERSIST accumulator for + * each of its two expert projections and a `gram_accum` into it, running until + * RADIANCE_CALIB_TOKENS tokens have passed and then writing the pair to + * RADIANCE_CALIB_DIR and switching itself off. + * + * IT IS A SEPARATE RUN AND NOT A SERVING MODE. The accumulators are 1.34 GB across 48 + * layers at this model's widths, the dump synchronises the stream, and the two extra + * launches a layer are pure overhead once the corpus is in. Nothing reads the files at + * serve time -- rad-convert does, in another process, to pack the next container. + * + * IT TAPS THE QUANTISER'S OUTPUT, not the bf16 before it, and that is deliberate: the + * Hessian GPTQ wants is of the operand the expert GEMM actually contracts. Under + * `expert_rot` that operand is rotated, so the Hessian is in rotated coordinates -- which + * is the same basis the packer quantises in, and the only basis in which the two agree. */ + int calib = 0; + int64_t rows = 0; /* tokens per pass; 0 means the whole step */ + }; + + /* WHICH BUFFERS ARE A PASS TALL AND WHICH ARE THE STEP'S, and the division is the whole of what + * the slicing costs in bookkeeping. Only the four planes that carry one row per (token, slot) + * are a pass tall -- they are `top_k` times the step and they are what the slicing exists to + * bound. Everything else is one row per TOKEN, is a few megabytes at any chunk, and is sized + * at max_tok and sliced by the pass offset like every other activation in this tree. + * + * That is not a size optimisation, it is what keeps the pass offset expressible: LinearFP8 and + * GateQuantFP8 slice their INPUT and their OUTPUT with the same `r0`, so a shared expert whose + * output buffer were a pass tall would be written past its end on the second pass. The shipped + * chunk is one pass, so that overrun would show no symptom there. */ + struct Wire { + rad_buf x = 0; /* [max_tok, n_embd] the residual stream */ + ActFP8 h{}; /* [max_tok, n_embd] normed input, then the block's delta */ + /* THE ROTATED CODES OF THE SAME INPUT, and only `q` and `s` of it are used -- `x` is + * `h`'s. Declared only when `expert_rot` is set; the routed gate_up reads this pair and + * the shared expert goes on reading `h`'s. */ + ActFP8 hr{}; /* [max_tok, n_embd] q + scale only */ + /* the routing -- one row per TOKEN, so the step's height */ + rad_buf logits = 0; /* [max_tok, n_expert_all] bf16 -- the MODEL's expert count */ + rad_buf ids = 0; /* [max_tok, top_k] i32 */ + rad_buf ew = 0; /* [max_tok, top_k] bf16 */ + rad_buf eoff = 0; /* [n_expert + 1] i32 */ + rad_buf ecnt = 0; /* [n_expert] i32 */ + /* the expert planes -- one row per (token, slot), so a PASS's height */ + rad_buf sorted = 0; /* [rows * top_k] i32, pass-relative slot indices */ + rad_buf egu = 0; /* [rows * top_k, 2 * n_ff_exp] bf16 */ + ActFP8 eff{}; /* [rows * top_k, n_ff_exp] */ + rad_buf edn = 0; /* [rows * top_k, n_embd] bf16, in SORTED order */ + /* back in token order, and the shared expert beside it: the step's height again */ + rad_buf moe = 0; /* [max_tok, n_embd] bf16 */ + rad_buf sgu = 0; /* [max_tok, 2 * n_ff_shared] bf16 */ + ActFP8 sff{}; /* [max_tok, n_ff_shared] */ + rad_buf sout = 0; /* [max_tok, n_embd] bf16 */ + rad_buf sgate = 0; /* [max_tok, 1] bf16 */ + }; + + /* The checkpoint side. `experts` is a PREFIX -- "....mlp.experts" -- and the per-expert names + * are built from it, because a caller cannot pass 256 of them and a format string with the + * expert in it is a convention this file would have to parse. `shared` is the same for the + * dense expert beside them; null means the family has none, and `shared_gate` must then be + * null too. + * + * THE CONFIG TRAVELS IN HERE rather than as an argument to declare, and that is not tidiness: + * it makes this block's declare() arity IDENTICAL to MlpFP8's, which is what lets MtpBlockFP8 + * be a template over the two. A routed feed-forward and a dense one are the same thing in the + * same position of the same graph, and the only component that should know the difference is + * the plugin that picks one. */ + struct Src { + Config cfg{}; + const char* norm = nullptr; + const char* router = nullptr; /* mlp.gate.weight, [n_expert, n_embd] bf16 */ + const char* experts = nullptr; /* prefix; "..{gate,up,down}_proj.weight" */ + const char* shared = nullptr; /* prefix; ".{gate,up,down}_proj.weight" */ + /* A STACKED CHECKPOINT NAMES TWO TENSORS AND NOT A PREFIX, which is the shape every + * recent release uses: `mlp.experts.gate_up_proj` [n_expert, 2*n_ff, n_embd] and + * `mlp.experts.down_proj` [n_expert, n_embd, n_ff], one tensor holding every expert. + * Set these INSTEAD of `experts` and each declared expert maps to a dim-0 slice + * (rad_arch.h's map_slice; core/format/checkpoint.cpp takes the slice as a view, and a + * block-fp8 checkpoint's stacked `_scale_inv` plane at the same index). + * Note that a stacked gate_up is ALREADY FUSED in the order this block wants -- gate + * rows first -- so there is no concatenation left to do. */ + const char* experts_gate_up = nullptr; + const char* experts_down = nullptr; + const char* shared_gate = nullptr; /* mlp.shared_expert_gate.weight, [1, n_embd] */ + }; + + Geom g{}; + Config c{}; + Wire w{}; + int layer = 0; + + rad_weight w_norm = 0, w_router = 0, w_sgate = 0; + /* The input was normed and quantised by the caller; this block declares no norm. */ + bool ext_in = false; + /* The four runs. Only the FIRST handle and the count reach an issue (RAD_WTAB); the rest are + * held so that a declaration failure can be reported against the expert it happened on. */ + std::vector w_gu, w_gus, w_dn, w_dns; + + NormQuantFP8 nq_h{}; + GateQuantFP8 gq_exp{}, gq_sh{}; + LinearFP8 sh_gate_up{}, sh_down{}; + rad_op op_router = 0, op_topk = 0, op_scatter = 0; + /* `router_topk_scatter`, if it resolves: the two above in one launch. 0 leaves the pair, which + * is declared either way -- the fused form is bounded by the sort's single-workgroup shape and + * a prefill chunk is past it. */ + rad_op op_topk_scatter = 0; + int64_t topk_scatter_rows = 0; + /* The rotated re-quantisation of the block input, declared only when `expert_rot` is set and + * the caller does not already write `w.hr`. */ + rad_op op_hq = 0; + /* The caller's read writes the rotated pair (HyperConn::Config::rotate), so this block declares + * no quantiser for it. Set before declare. */ + bool hr_in = false; + rad_op op_gu = 0, op_dn = 0, op_gather = 0; + /* THE PROTECTED EXPERTS (declare): local experts a quantised layer keeps plain bf16 -- the few + * whose output dwarfs the rest's (docs/MOE-W4.md). The scatter sorts them last (`protect`, + * `prot_list`), the quantised GEMMs above serve the other `n_reg`, and a bf16 grouped GEMM + * pair serves these over the trailing run of the offsets: gate_up into `b_pgu`, the gate into + * `pff`, and down into the same `edn` rows the quantised down left zero. */ + std::vector prot; + const char* prot_list = nullptr; + int64_t n_reg = 0; + /* THIS LAYER'S gate_up AND down FORMATS (format_of's numbers), resolved by declare(): the + * probed layer's for both, except that among the codebook forms at E4M3 scales -- w4nl64a8h, + * w4nl32a8h, w5nl64a8h -- each projection of each layer takes its own experts'. */ + int fmt[2] = { 0, 0 }; + std::vector w_pgu, w_pdn; + rad_buf b_pgu = 0; + ActFP8 pff{}; + GateQuantFP8 gq_prot{}; + rad_op op_pgu = 0, op_pdn = 0; + /* The gather FOLDS the shared arm in wherever there is one: it takes `sout` and `sgate` and + * writes the block's delta straight into `h.x`, so `w.moe` is never written. */ + bool gfold = false; + /* THE WRITE BEHIND THIS BLOCK TAKES THE GATHER up to this many tokens -- HyperConn's + * gather_rows and gather_rows6, one a wire, set by the architecture after that write declared + * its fused forms, 0 where it did not. Where gather_taken() says so the block leaves its routed + * rows unsummed. */ + int64_t gather_out_rows = 0; + int64_t gather_out_rows6 = 0; + /* The calibration tap: two accumulators and the two ops that fill them. Zero unless + * `Config::calib` is set. `calib_rows` and `calib_done` are mutable because `pass` is const + * and the tap's whole state is a token count -- per block, so a block reaches its target on + * the same pass every other block does and nothing has to know which layer is last. */ + rad_buf b_gram_gu = 0, b_gram_dn = 0; + rad_op op_gram_gu = 0, op_gram_dn = 0; + /* The domain the tap sums in, which its files say (calib_write): the rotation's width when + * the GEMMs read rotated codes, the model's own otherwise. */ + uint32_t gram_domain = 0; + /* THE FILE IS NAMED AFTER THE WEIGHT IT WILL BE USED TO PACK, minus the expert index, and + * that is the whole protocol between this and the GPTQ quantiser: the recipe hands it the + * directory (`calib=`) and rad-convert the weight's logical name, and libquant strips + * `..weight` off the name to get the file. A name of this tap's own -- "blk3.gate_up" -- + * would have made the quantiser carry a table mapping one to the other, for every + * architecture. */ + const char* gram_gu_stem = nullptr; + const char* gram_dn_stem = nullptr; + mutable long long calib_rows = 0; + mutable bool calib_done = false; + /* THE DOWN PROJECTION'S HESSIAN AN EXPERT (rad_arch.h, CalibExperts), beside the pooled one: + * a layer-sized scratch, `ne` squares of [n_ff_exp, n_ff_exp], a `gram_accum` into each + * expert's square over that expert's rows, and the sum kept on the host. */ + rad_buf b_gram_dne = 0; + rad_op op_gram_dne = 0; + mutable CalibExperts calib_dne; + mutable bool calib_dne_failed = false; + void calib_experts_pass(RadCtx* c_, int64_t slots) const; + rad_op op_sgate = 0; + rad_op op_ar = 0, op_add = 0; + bool ar_out = false; + /* Which wires the consumer of this block's all-reduce takes. Set before declare; see + * AttnGatedFP8::ar_out_take. */ + int ar_out_take = kArOutNorm; + + /* THE STORED EXPERT FORMAT, read off the encoding of layer `l`'s first expert's gate_up -- + * its name map declared here, which declare() then leaves out -- into `cfg->expert_w4` and + * `cfg->expert_rot`. Asked before any layer is declared, because the architecture sizes the + * rotated activation and tells the connection in front of the block to write it. Nothing + * known about the weight (a builder with no model behind it) is block fp8. */ + static int probe(RadBuilder* b, Names& nm, int l, const Src& src, Config* cfg); + /* The format `e` names: 0 block fp8, 1 four-bit, 2 four-bit rotated, 3 plain bf16, 4 the + * rotated w4nl codebook, 5 and 6 that codebook at E4M3 scales a 64 and a 32 of K, 7 its + * five-bit form at a 64; RAD_E_DTYPE for an encoding this block serves none of. */ + static int format_of(const RadEncoding& e); + /* format_of's numbers as the grouped GEMMs' dtype strings. */ + static constexpr const char* kServed[8] = { "fp8a8", "w4a8", "w4a8h", "bf16", "w4nla8h", + "w4nl64a8h", "w4nl32a8h", "w5nl64a8h" }; + + 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 pass of at most `c.rows` tokens. */ + void pass(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const; + void shared_up(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const; +}; + +inline int MoeFP8::format_of(const RadEncoding& e) { + if (rad_enc_is(&e, "plain") && e.n_planes == 1 && e.plane[0].dtype == RAD_BF16) return 3; + if (!rad_enc_is(&e, "affine")) return RAD_E_DTYPE; + const RadEncPlane* sc = rad_enc_plane(&e, "scale"); + /* The codebook at E4M3 scales a 64 or 32 of K under one fixed f32 (w4nl64a8h, w4nl32a8h), and + * its five-bit form at a 64 (w5nl64a8h). */ + if (e.n_planes == 4 && sc && sc->dtype == RAD_F8E4M3) { + const RadEncPlane* s2 = rad_enc_plane(&e, "scale.1"); + const RadEncPlane* t = rad_enc_plane(&e, "table"); + if (!(s2 && s2->dtype == RAD_F32 && s2->block[0] == 0 && s2->block[1] == 0 && t && + t->kind == RAD_PLANE_TABLE && t->dtype == RAD_F32 && t->extent[0] == 1 && + sc->block[0] == 1 && std::strcmp(e.transform, "fwht128") == 0)) + return RAD_E_DTYPE; + if (t->extent[1] == 16 && e.plane[0].dtype == RAD_U4 && + (sc->block[1] == RAD_FP8_BLOCK / 2 || sc->block[1] == RAD_FP8_BLOCK / 4)) + return sc->block[1] == RAD_FP8_BLOCK / 2 ? 5 : 6; + if (t->extent[1] == 32 && e.plane[0].dtype == RAD_U5 && sc->block[1] == RAD_FP8_BLOCK / 2) + return 7; + return RAD_E_DTYPE; + } + if (!sc || sc->dtype != RAD_BF16) return RAD_E_DTYPE; + if (e.n_planes == 3) { + const RadEncPlane* t = rad_enc_plane(&e, "table"); + if (t && t->kind == RAD_PLANE_TABLE && t->dtype == RAD_F32 && t->extent[0] == 1 && + t->extent[1] == 16 && e.plane[0].dtype == RAD_U4 && sc->block[0] == 1 && + sc->block[1] == RAD_FP8_BLOCK && std::strcmp(e.transform, "fwht128") == 0) + return 4; + return RAD_E_DTYPE; + } + if (e.n_planes != 2) return RAD_E_DTYPE; + if (e.plane[0].dtype == RAD_F8E4M3 && !e.transform[0] && sc->block[0] == RAD_FP8_BLOCK && + sc->block[1] == RAD_FP8_BLOCK) + return 0; + if (e.plane[0].dtype == RAD_I4 && sc->block[0] == 1 && sc->block[1] == RAD_FP8_BLOCK) { + if (!e.transform[0]) return 1; + if (std::strcmp(e.transform, "fwht128") == 0) return 2; + } + return RAD_E_DTYPE; +} + +/* The gate_up and down name maps of one expert: a dim-0 slice of the stacked tensors, or the + * checkpoint's per-expert gate and up joined along rows. `gate_up` false maps down alone. */ +inline int moe_map_expert(RadBuilder* b, Names& nm, const MoeFP8::Src& src, const char* guw, + const char* dnw, long long ge, bool gate_up) { + if (src.experts_gate_up) { + /* THE SLICE INDEX IS GLOBAL: the checkpoint holds every expert, and this rank declares a + * window into it. Slicing by the local index would give every rank experts 0..E/W. */ + if (gate_up) RAD_ARCH_TRY(map_slice(b, guw, src.experts_gate_up, (int)ge)); + return map_slice(b, dnw, src.experts_down, (int)ge); + } + const char* gate = nm.ckpt("%s.%lld.gate_proj.weight", src.experts, ge); + const char* up = nm.ckpt("%s.%lld.up_proj.weight", src.experts, ge); + if (gate_up) RAD_ARCH_TRY(map_concat(b, guw, { gate, up })); + return map_copy(b, dnw, nm.ckpt("%s.%lld.down_proj.weight", src.experts, ge)); +} + +inline int MoeFP8::probe(RadBuilder* b, Names& nm, int l, const Src& src, Config* cfg) { + if (!cfg || (!src.experts && !src.experts_gate_up)) return RAD_E_INVAL; + /* The caller names the expert, in the model's numbering: the first one this rank will own if + * the experts are split between the ranks, which declare() then skips -- and an expert every + * rank declares a slice of otherwise, which every rank skips. */ + /* A PLAIN bf16 EXPERT DOES NOT SETTLE IT: a quantised layer keeps up to kMaxProtected of its + * experts plain, so the probe reads on past them to the first expert in another format, and + * only a run of plain ones longer than any protected set says the model is bf16. */ + const long long g0 = (long long)cfg->probed_expert; + const long long all = cfg->n_expert_all > 0 ? (long long)cfg->n_expert_all + : (long long)cfg->n_expert; + const long long gn = all > g0 ? all : g0 + 1; + cfg->probed_layer = l; + int f = 0; + for (long long ge = g0; ge < gn && ge <= g0 + kMaxProtected; ++ge) { + const char* guw = nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l, ge); + if (src.experts_gate_up) RAD_ARCH_TRY(map_slice(b, guw, src.experts_gate_up, (int)ge)); + else RAD_ARCH_TRY(map_concat(b, guw, { nm.ckpt("%s.%lld.gate_proj.weight", src.experts, ge), + nm.ckpt("%s.%lld.up_proj.weight", src.experts, ge) })); + cfg->probed_count = ge - g0 + 1; + RadEncoding e{}; + f = 0; + if (weight_enc(b, guw, &e) && (f = format_of(e)) < 0) { + char en[256]; + rad_enc_format(&e, en, sizeof en); + fprintf(stderr, "radiance: '%s' is %s, and the routed experts are served as block fp8 " + "(fp8_e4m3*bf16[128x128]), four-bit (i4*bf16[1x128], optionally " + "/fwht128; or u4 codes into a 16-entry f32 table, /fwht128) or plain " + "bf16; or the codebook at E4M3 scales a 64 or 32 of K under a fixed " + "f32, or its 32-entry five-bit form at a 64. " + "Convert it with a recipe that makes one of them.\n", guw, en); + return RAD_E_DTYPE; + } + if (f != 3) break; + } + cfg->expert_w4 = (f == 1 || f == 2 || f == 4 || f == 5 || f == 6 || f == 7) ? 1 : 0; + cfg->expert_rot = (f == 2 || f == 4 || f == 5 || f == 6 || f == 7) ? 1 : 0; + cfg->expert_nl = (f == 4 || f == 5 || f == 6 || f == 7) ? 1 : 0; + cfg->expert_g64 = (f == 5 || f == 7) ? 2 : f == 6 ? 4 : 0; + cfg->expert_w5 = f == 7 ? 1 : 0; + cfg->expert_bf16 = f == 3 ? 1 : 0; + return RAD_OK; +} + +inline int MoeFP8::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; c = src.cfg; w = wire; layer = l; + ar_out = ar_out_; + /* 0 means "not expert-parallel": this rank owns the model's whole expert set. Normalised once, + * here, so nothing below has to ask which case it is in. */ + if (c.n_expert_all <= 0) c.n_expert_all = c.n_expert; + if (c.n_expert <= 0 || c.top_k <= 0 || c.top_k > c.n_expert_all || c.n_ff_exp <= 0) + return RAD_E_INVAL; + /* THE SLICE HAS TO BE INSIDE THE MODEL. A base past the end silently routes nothing to this + * rank -- a model that serves and drops a fraction of its own feed-forward. */ + if (c.expert_base < 0 || c.expert_base + c.n_expert > c.n_expert_all) return RAD_E_INVAL; + if (c.rows <= 0) c.rows = g.max_tok; + /* A rank whose slice of the shared arm is empty (see Config) declares no arm, and the + * all-reduce carries the others' share. */ + const bool shared = c.n_ff_shared > 0 && src.shared; + + /* 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; + } else { + 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 EXPERTS' NAME MAPS, and from them which experts this layer PROTECTS. The maps are + * how the model is asked what each expert is (rad_weight_encoding): one a LOGICAL weight, + * gate_up and down, the scale views having none; the probed experts' gate_up is mapped + * already. Every expert is the format the block was set up for -- one table of experts takes + * one encoding -- except that a quantised layer may keep a few WHOLE experts plain bf16: the + * ones whose output dwarfs the rest's, where the same relative rounding error is a large + * absolute one (docs/MOE-W4.md). Those are sorted last and served by a bf16 GEMM pair of + * their own; they are found here, before the sort is declared, because the sort takes them. */ + const int64_t ne = c.n_expert; + for (int64_t e = 0; e < ne; ++e) { + const long long ge = (long long)(c.expert_base + e); /* the checkpoint's numbering */ + const bool probed = c.probed_layer == l && ge >= (long long)c.probed_expert && + ge < (long long)(c.probed_expert + c.probed_count); + RAD_ARCH_TRY(moe_map_expert(b, nm, src, nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l, ge), + nm.f("blk.%d.ffn_down_exps.%lld.weight", l, ge), ge, !probed)); + } + prot.clear(); + { + const int want = c.expert_bf16 ? 3 : c.expert_w5 ? 7 : c.expert_g64 == 4 ? 6 + : c.expert_g64 ? 5 : c.expert_nl ? 4 + : c.expert_w4 ? (c.expert_rot ? 2 : 1) : 0; + auto fmt_of = [&](int64_t e, RadEncoding (&enc)[2], int (&fe)[2], const char* (&nmv)[2]) { + const long long ge = (long long)(c.expert_base + e); + nmv[0] = nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l, ge); + nmv[1] = nm.f("blk.%d.ffn_down_exps.%lld.weight", l, ge); + for (int i = 0; i < 2; ++i) { + fe[i] = want; + if (weight_enc(b, nmv[i], &enc[i])) fe[i] = format_of(enc[i]); + } + }; + /* THE CODEBOOK FORMS AT E4M3 SCALES SHARE EVERYTHING BUT THE GEMM'S DTYPE -- the rotated + * input, the scale views, the fixed second level, the accumulators -- so the bits can go + * where the error is: a layer, and either projection of it, may be in any of them whatever + * the probed layer's. The first expert of the layer kept in one of them decides its two; + * every other must match. Outside that family a layer is the probed layer's form. */ + auto family = [](int f) { return f == 5 || f == 6 || f == 7; }; + fmt[0] = fmt[1] = want; + if (family(want)) + for (int64_t e = 0; e < ne; ++e) { + RadEncoding enc[2]{}; + int fe[2]; + const char* nmv[2]; + fmt_of(e, enc, fe, nmv); + if (fe[0] == 3 && fe[1] == 3) continue; + for (int i = 0; i < 2; ++i) + if (family(fe[i])) fmt[i] = fe[i]; + break; + } + for (int64_t e = 0; e < ne; ++e) { + RadEncoding enc[2]{}; + int fe[2]; + const char* names[2]; + fmt_of(e, enc, fe, names); + if (fe[0] == fmt[0] && fe[1] == fmt[1]) continue; + if (want != 3 && fe[0] == 3 && fe[1] == 3) { prot.push_back(e); continue; } + const int i = fe[0] != fmt[0] ? 0 : 1; + char en[256]; + rad_enc_format(&enc[i], en, sizeof en); + fprintf(stderr, "radiance: '%s' is %s, and this layer's experts are served as %s -- one " + "table of experts takes one encoding, and only a whole expert kept " + "plain bf16 is served beside it.\n", names[i], en, kServed[fmt[i]]); + return RAD_E_DTYPE; + } + } + n_reg = ne - (int64_t)prot.size(); + if (!prot.empty()) { + if ((int64_t)prot.size() > kMaxProtected) { + fprintf(stderr, "radiance: layer %d keeps %zu experts plain bf16 on this rank; the sort " + "places at most %lld last\n", l, prot.size(), (long long)kMaxProtected); + return RAD_E_INVAL; + } + /* The quantised GEMM takes its experts as two equal tables by parity. */ + if (n_reg % 2) { + fprintf(stderr, "radiance: layer %d keeps %zu experts plain bf16 on this rank, which " + "leaves %lld quantised; they come in pairs on a rank so the rest split " + "into two equal tables by parity\n", l, prot.size(), (long long)n_reg); + return RAD_E_INVAL; + } + /* The tap's per-expert files are named by expert, and the sort here numbers by place. */ + if (c.calib) { + fprintf(stderr, "radiance: calibrate the bf16 container: layer %d of this one keeps " + "experts plain bf16 and sorts them out of order\n", l); + return RAD_E_INVAL; + } + std::string lst; + for (int64_t e : prot) lst += (lst.empty() ? "" : ",") + std::to_string(e); + prot_list = nm.ckpt("%s", lst.c_str()); + } + + /* THE ROUTER IS REPLICATED, NOT SHARDED, and that is the property the whole block rests on. + * Every rank routes every token to the same experts -- the routing is computed from the full + * residual stream, which every rank holds -- so `sorted_tok` and `expert_offset` are identical + * across ranks and the expert GEMMs' row layout agrees without a collective. Sharding the + * router would make two ranks disagree about which expert a token went to, and the all-reduce + * at the end of the block would then sum two different models. */ + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ffn_gate_inp.weight", l), src.router)); + w_router = decl_w(b, nm.f("blk.%d.ffn_gate_inp.weight", l), RAD_BF16, + {c.n_expert_all, g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); + + 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)); + + op_router = rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", c.n_expert_all), + RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_router)), + {w.h.x}, {w.logits}); + op_topk = rw(b, RAD_OP(b, "router_topk", + RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n_expert", c.n_expert_all), + RAD_INT("top_k", c.top_k), RAD_INT("norm", c.norm_topk), + RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.logits}, {w.ids, w.ew}); + /* THE PROTECTED EXPERTS ARE SORTED LAST (`protect`), and only a layer that has them says so, + * so every other layer's sort is declared without a protect list. */ + if (!prot_list) + op_scatter = rw(b, RAD_OP(b, "moe_scatter", + RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n_expert", c.n_expert), + RAD_INT("top_k", c.top_k), + RAD_INT("expert_base", c.expert_base)), + RAD_NOWEIGHTS), + {w.ids}, {w.sorted, w.eoff, w.ecnt}); + else + op_scatter = rw(b, RAD_OP(b, "moe_scatter", + RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n_expert", c.n_expert), + RAD_INT("top_k", c.top_k), + RAD_INT("expert_base", c.expert_base), + RAD_STR("protect", prot_list)), + RAD_NOWEIGHTS), + {w.ids}, {w.sorted, w.eoff, w.ecnt}); + + /* THE TWO ABOVE IN ONE LAUNCH, and it is worth asking for because NEITHER IS WORK. At a decode + * shape each is a single 256-thread workgroup ranking about a kilobyte, so each costs a full + * dispatch for no arithmetic, once per layer per step, twice over. The sort reads + * `expert_ids` and nothing else and the selection writes it, so the launch between them buys a + * barrier and nothing more. + * + * BOUNDED BY THE SORT'S SINGLE-WORKGROUP FORM. `moe_scatter` runs one launch at + * M*top_k <= 1024 and three above it -- the three exist to keep the sort stable without an + * atomic deciding the order -- and only the first shape is fusible. That is the DECODE band by + * construction (eight sequences at depth 3 and top_k 10 is 320) and a prefill chunk is past + * it, which is also where the pair is amortised over real work and the fusion would buy + * nothing. Declared either way, so the graph and the buffer plan do not depend on it. */ + if (c.top_k > 0 && (int64_t)c.rows * c.top_k <= kMoeSortRows) + topk_scatter_rows = c.rows; + else + topk_scatter_rows = kMoeSortRows / c.top_k; + if (topk_scatter_rows > 0 && !prot_list) + op_topk_scatter = rw(b, RAD_OP(b, "router_topk_scatter", + RAD_PARAMS(RAD_RANGE("M", 1, topk_scatter_rows), + RAD_INT("n_expert", c.n_expert_all), + RAD_INT("n_local", c.n_expert), + RAD_INT("top_k", c.top_k), + RAD_INT("norm", c.norm_topk), + RAD_STR("dtype", g.dtype), + RAD_INT("expert_base", c.expert_base)), + RAD_NOWEIGHTS), + {w.logits}, {w.ids, w.ew, w.sorted, w.eoff, w.ecnt}); + else if (topk_scatter_rows > 0) + op_topk_scatter = rw(b, RAD_OP(b, "router_topk_scatter", + RAD_PARAMS(RAD_RANGE("M", 1, topk_scatter_rows), + RAD_INT("n_expert", c.n_expert_all), + RAD_INT("n_local", c.n_expert), + RAD_INT("top_k", c.top_k), + RAD_INT("norm", c.norm_topk), + RAD_STR("dtype", g.dtype), + RAD_INT("expert_base", c.expert_base), + RAD_STR("protect", prot_list)), + RAD_NOWEIGHTS), + {w.logits}, {w.ids, w.ew, w.sorted, w.eoff, w.ecnt}); + + /* EITHER a prefix or the two stacked tensors, never both and never neither. A checkpoint + * cannot be read two ways at once and a caller that set both has not decided. */ + const bool stacked = src.experts_gate_up != nullptr; + if (stacked != (src.experts_down != nullptr) || (stacked == (src.experts != nullptr))) { + fprintf(stderr, "radiance: a routed feed-forward takes EITHER an `experts` prefix or " + "both stacked tensors; got prefix %s, gate_up %s, down %s\n", + src.experts ? "yes" : "no", src.experts_gate_up ? "yes" : "no", + src.experts_down ? "yes" : "no"); + return RAD_E_INVAL; + } + + /* ---- the expert weights, in EIGHT RUNS: gate_up codes, gate_up scales, down codes and down + * scales, each for the even experts and then the odd ones. See the header: a weight table is a + * run of consecutive handles, and `moe_gemm_q` takes each projection's experts as two tables + * by parity -- entry e / 2 of class e % 2 -- so these loops must not be merged. */ + if (ne % 2) { + fprintf(stderr, "radiance: %lld routed experts on this rank; the grouped GEMM takes them as " + "two equal tables by parity, so the count must be even\n", (long long)ne); + return RAD_E_INVAL; + } + /* The quantised experts by their PLACE in the sort -- the protected ones sorted last are not + * among them -- which is also the expert slot each is declared in, so the routing counts the + * sort writes in place order credit the right unit. */ + std::vector reg; + reg.reserve((size_t)n_reg); + for (int64_t e = 0; e < ne; ++e) + if (std::find(prot.begin(), prot.end(), e) == prot.end()) reg.push_back(e); + w_gu.resize((size_t)ne); w_gus.resize((size_t)ne); + w_dn.resize((size_t)ne); w_dns.resize((size_t)ne); + /* Each parity's width on this rank: the Config's slice when the width is split unevenly, and + * `n_ff_exp` for both otherwise. The buffers between the two GEMMs are the wider one's. */ + const bool split = c.ff_hi[0] > 0; + int64_t wq[2] = { c.n_ff_exp, c.n_ff_exp }; + if (split) + for (int q = 0; q < 2; ++q) wq[q] = c.ff_hi[q] - c.ff_lo[q]; + if (split && (wq[0] <= 0 || wq[1] <= 0 || c.n_ff_exp != (wq[0] > wq[1] ? wq[0] : wq[1]))) { + fprintf(stderr, "radiance: the routed experts' slices [%lld, %lld) and [%lld, %lld) do not " + "describe a width of %lld\n", (long long)c.ff_lo[0], (long long)c.ff_hi[0], + (long long)c.ff_lo[1], (long long)c.ff_hi[1], (long long)c.n_ff_exp); + return RAD_E_INVAL; + } + for (int q = 0; q < 2; ++q) + if (wq[q] % RAD_FP8_BLOCK || g.n_embd % RAD_FP8_BLOCK || + (split && c.ff_lo[q] % RAD_FP8_BLOCK)) { + fprintf(stderr, "radiance: an expert is %lldx%lld per rank, which is not a whole number " + "of %dx%d scale blocks\n", + (long long)wq[q], (long long)g.n_embd, RAD_FP8_BLOCK, RAD_FP8_BLOCK); + return RAD_E_INVAL; + } + /* The codes' dtype, which is what the codes view is declared at, and the planes it selects: + * a codebook's table rides with its codes, so the relayout sees the table it is asked to + * decode by. */ + auto edt_of = [&](int f) { + return f == 7 ? (uint32_t)RAD_U5 : c.expert_nl ? (uint32_t)RAD_U4 + : c.expert_w4 ? (uint32_t)RAD_I4 : (uint32_t)RAD_F8E4M3; + }; + const uint32_t edt[2] = { edt_of(fmt[0]), edt_of(fmt[1]) }; + const char* const ecodes = c.expert_nl ? "codes,table" : "codes"; + /* UNDER EXPERT PARALLELISM AN EXPERT IS WHOLE, so its weights are not sharded at all: this + * rank holds all of the columns of the experts it owns and none of the others. Declaring them + * RAD_SHARD_ROW would have the loader slice each one again -- it refuses by name, because the + * declared row parts sum to the full width while the rank's share is half of it. */ + const bool ep = c.n_expert != c.n_expert_all; + if (ep && split) { + fprintf(stderr, "radiance: a rank either owns whole experts or a slice of every one; this " + "configuration asks for both\n"); + return RAD_E_INVAL; + } + /* A PACKED 4-BIT ROW SLICES ON ITS SCALE GROUPS AND NOWHERE ELSE: it is K/2 bytes with eight + * codes a dword, so a width shard along K is a byte range of every row exactly when it falls on + * a group of 128 -- which the per-rank check above already requires -- and a shard along the + * rows is whole rows. The rotation is a 128-wide Hadamard inside each group and is cut by + * neither. */ + /* THE ROTATION IS A PROPERTY OF THE 4-BIT PLANE AND HAS NO MEANING WITHOUT IT. There is no + * rotated fp8 expert format in this tree -- the fp8 layout hook writes a 128x128 tile scale + * and has no rotated form -- so `expert_rot` alone is a configuration that cannot be + * built, and saying so is better than silently serving the unrotated one. */ + if ((c.expert_rot && !c.expert_w4) || (c.expert_nl && !c.expert_rot)) { + fprintf(stderr, "radiance: rotated experts (expert_rot) require the 4-bit expert format, " + "and a codebook (expert_nl) the rotated one; there is no rotated E4M3 " + "expert plane and no unrotated codebook\n"); + return RAD_E_INVAL; + } + const int sh_row = ep ? RAD_SHARD_NONE : RAD_SHARD_ROW; + const int sh_col = ep ? RAD_SHARD_NONE : RAD_SHARD_COL; + const int n_parts = ep ? 0 : 2; + /* The scale grid the chosen weight format wants: one per 128x128 tile for E4M3, one per ROW + * per group of 128 along K for 4-bit -- which is what a sixteen-level grid needs, and is the + * only shape difference between the two declarations. `sdiv` is how many weight rows or + * columns one scale covers along the split dimension. */ + const int64_t sdiv = c.expert_w4 ? 1 : RAD_FP8_BLOCK; + /* A FORMAT A STRING, and the string is what selects the grouped GEMM; its layout hook then + * accepts the experts' encoding or the kernel is not a candidate. One a projection. */ + const char* const edtype[2] = { kServed[fmt[0]], kServed[fmt[1]] }; + /* The scale views: bf16, one a (row, 128 of K) -- or a 128x128 tile for E4M3 -- or at + * w4nl64a8h one E4M3 a (row, 64 of K), selected with the fixed second level beside it. TWO + * PLANES MAKE IT A VIEW OF THE LOGICAL WEIGHT, as the codes view is (rad_builder.cpp): it is + * declared at the weight's extents, its slice is in the weight's columns, and the stored + * plane under it -- [rows, K/64] bytes -- is the layout hook's. `sgk` is the K one declared + * scale column covers. */ + const uint32_t sdt = c.expert_g64 ? (uint32_t)RAD_F8E4M3 : (uint32_t)RAD_BF16; + const int64_t sgk = c.expert_g64 ? 1 : RAD_FP8_BLOCK; + const char* escale = c.expert_g64 ? "scale,scale.1" : "scale"; + /* A slice of each expert: the gate and up rows [lo, hi) of this parity for the gate/up pair, + * columns [lo, hi) for down, and the scale planes the same slice in their own units. */ + auto span = [&](rad_weight h, int q, int64_t unit) -> int { + if (!split || !h) return RAD_OK; + return rad_weight_shard_span(b, h, c.ff_lo[q] / unit, c.ff_hi[q] / unit); + }; + const bool rot = c.expert_rot != 0; + if (c.expert_bf16) { + /* ---- PLAIN bf16 EXPERTS: ONE TABLE A PROJECTION, of whole experts in expert order -- + * `moe_gemm`'s one weight operand, expert e at entry e -- so each projection's handles are + * declared in one loop and the two loops are not merged. An expert is its own movement + * unit as it is in every other format, and its bytes in the container are what the kernel + * reads, so the file tier can serve it as it lies. */ + if (split || rot || c.expert_w4) { + fprintf(stderr, "radiance: bf16 experts are whole on their rank (expert parallel, or " + "one rank) and unrotated; this configuration %s\n", + split ? "slices every expert" : "rotates or packs them"); + return RAD_E_INVAL; + } + for (int64_t e = 0; e < ne; ++e) { + const int64_t parts[2] = { c.n_ff_exp, c.n_ff_exp }; + w_gu[(size_t)e] = decl_w_n(b, nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l, + (long long)(c.expert_base + e)), + RAD_BF16, {2 * c.n_ff_exp, g.n_embd}, RAD_ACCESS_CONDITIONAL, + sh_row, grp_expert_slot(l, (int)e, 0), 0, parts, n_parts); + if (!w_gu[(size_t)e]) return RAD_E_INVAL; + } + for (int64_t e = 0; e < ne; ++e) { + w_dn[(size_t)e] = decl_w(b, nm.f("blk.%d.ffn_down_exps.%lld.weight", l, + (long long)(c.expert_base + e)), + RAD_BF16, {g.n_embd, c.n_ff_exp}, RAD_ACCESS_CONDITIONAL, + sh_col, grp_expert_slot(l, (int)e, 1)); + if (!w_dn[(size_t)e]) return RAD_E_INVAL; + } + /* The same two row orders as the quantised GEMMs, and for the same reason (see a_order + * above): gate_up gathers token rows, down reads its input in sorted order. */ + op_gu = rw(b, rad_decl_op(b, "moe_gemm", + RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", 2 * c.n_ff_exp), + RAD_INT("K", g.n_embd), RAD_INT("n_expert", ne), + RAD_INT("top_k", c.top_k), RAD_STR("a_order", "token"), + RAD_STR("dtype", "bf16")), + w_gu.data(), (int)ne), + {w.h.x, w.sorted, w.eoff}, {w.egu}); + /* silu(gate) * up into the bf16 plane the down GEMM reads: the gate's bf16 form, whatever + * the trunk's (rad_fp8.h, GateQuantFP8). */ + Geom gx = g; + gx.w_bf16 = true; + RAD_ARCH_TRY(gq_exp.declare(b, gx, w.egu, w.eff, c.n_ff_exp, "silu", c.rows * c.top_k, + true, false)); + op_dn = rw(b, rad_decl_op(b, "moe_gemm", + RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", g.n_embd), + RAD_INT("K", c.n_ff_exp), RAD_INT("n_expert", ne), + RAD_INT("top_k", c.top_k), RAD_STR("a_order", "sorted"), + RAD_STR("dtype", "bf16")), + w_dn.data(), (int)ne), + {w.eff.x, w.sorted, w.eoff}, {w.edn}); + if (!op_gu || !op_dn) return RAD_E_INVAL; + } else { + /* ---- the eight runs, declared as the views the header describes. */ + for (int q = 0; q < 2; ++q) + for (int64_t s = q; s < n_reg; s += 2) { + const int64_t e = reg[(size_t)s]; + const int64_t parts[2] = { wq[q], wq[q] }; + rad_weight& h = w_gu[(size_t)s]; + h = decl_view(b, nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l, + (long long)(c.expert_base + e)), + nullptr, ecodes, edt[0], {2 * wq[q], g.n_embd}, + RAD_ACCESS_CONDITIONAL, sh_row, grp_expert_slot(l, (int)s, 0), + parts, n_parts); + if (!h) return RAD_E_INVAL; + RAD_ARCH_TRY(span(h, q, 1)); + } + for (int q = 0; q < 2; ++q) + for (int64_t s = q; s < n_reg; s += 2) { + const int64_t e = reg[(size_t)s]; + const int64_t parts[2] = { wq[q] / sdiv, wq[q] / sdiv }; + rad_weight& h = w_gus[(size_t)s]; + h = decl_view(b, nm.f("blk.%d.ffn_gate_up_exps.%lld.scale", l, + (long long)(c.expert_base + e)), + nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l, + (long long)(c.expert_base + e)), + escale, sdt, + {c.expert_w4 ? 2 * wq[q] : fp8_blocks(2 * wq[q]), + c.expert_w4 ? g.n_embd / sgk : fp8_blocks(g.n_embd)}, + RAD_ACCESS_CONDITIONAL, sh_row, grp_expert_slot(l, (int)s, 0), + parts, n_parts); + if (!h) return RAD_E_INVAL; + RAD_ARCH_TRY(span(h, q, sdiv)); + } + for (int q = 0; q < 2; ++q) + for (int64_t s = q; s < n_reg; s += 2) { + const int64_t e = reg[(size_t)s]; + rad_weight& h = w_dn[(size_t)s]; + h = decl_view(b, nm.f("blk.%d.ffn_down_exps.%lld.weight", l, + (long long)(c.expert_base + e)), + nullptr, ecodes, edt[1], {g.n_embd, wq[q]}, + RAD_ACCESS_CONDITIONAL, sh_col, grp_expert_slot(l, (int)s, 1)); + if (!h) return RAD_E_INVAL; + RAD_ARCH_TRY(span(h, q, 1)); + } + for (int q = 0; q < 2; ++q) + for (int64_t s = q; s < n_reg; s += 2) { + const int64_t e = reg[(size_t)s]; + rad_weight& h = w_dns[(size_t)s]; + h = decl_view(b, nm.f("blk.%d.ffn_down_exps.%lld.scale", l, + (long long)(c.expert_base + e)), + nm.f("blk.%d.ffn_down_exps.%lld.weight", l, + (long long)(c.expert_base + e)), + escale, sdt, + {c.expert_w4 ? g.n_embd : fp8_blocks(g.n_embd), wq[q] / sgk}, + RAD_ACCESS_CONDITIONAL, sh_col, grp_expert_slot(l, (int)s, 1)); + if (!h) return RAD_E_INVAL; + RAD_ARCH_TRY(span(h, q, sgk)); + } + + /* ---- the two grouped GEMMs. `M` is the TOKEN count of a pass, not the sorted row count: the + * kernels read the row count off `y` and the parameter is what the scratch hook and the + * operand descriptions size from. + * + * THE TWO DISAGREE ABOUT `a_order` AND THAT IS THE WHOLE POINT OF THE PARAMETER. gate_up reads + * the block's normed INPUT, which is one row per TOKEN, so a sorted row gathers + * `a[sorted_tok[i] / top_k]`. down reads gate_up's output through the gated quantiser, which + * is already one row per (token, slot) IN THIS ORDER, so a sorted row is row i. Gathering the + * second one as well hands every slot of a token the FIRST slot's intermediate -- at decode, + * where a step has one token, all top_k experts then read slot 0 -- and the model still runs + * and answers plausibly and wrongly. If the reference and the kernel both gather they AGREE, + * and a workbench that builds the operand at the extent the gather wants cannot see the + * difference either -- this parameter is the only thing that states which order is meant. */ + /* THE ROUTED ARM'S OWN COPY OF THE INPUT, ROTATED. `w.h.q` is read by the shared expert too + * and that arm's weight is unrotated E4M3, so this cannot be done in place -- see Config's + * note on what the isolation buys and what it costs. Declared here, immediately before its + * one consumer, so the graph order and the issue order agree. */ + if (rot) { + if (!w.hr.q || !w.hr.s) { + fprintf(stderr, "radiance: rotated experts need the `hr` (q, scale) pair on the wire; " + "the architecture declares the buffers\n"); + return RAD_E_INVAL; + } + if (!hr_in) + op_hq = rw(b, RAD_OP(b, "had_quant_act_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n", g.n_embd), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.h.x}, {w.hr.q, w.hr.s}); + } + /* A table op's weights, in its table operands' order: the even experts' codes and scales, then + * the odd experts' (`w`, `w_scale`, `w_odd`, `w_odd_scale`). */ + auto tables = [&](const std::vector& wc, const std::vector& ws) { + std::vector tab; + tab.reserve((size_t)n_reg * 2); + for (int q = 0; q < 2; ++q) { + for (int64_t s = q; s < n_reg; s += 2) tab.push_back(wc[(size_t)s]); + for (int64_t s = q; s < n_reg; s += 2) tab.push_back(ws[(size_t)s]); + } + return tab; + }; + /* THE GATE/UP OUTPUT IS TWO PARTS OF THE WIDER CLASS'S WIDTH, gate then up, and the narrower + * class fills each part's leading columns and zeros the rest -- so the gated quantiser below + * reads one layout for every row, and a row of the narrower class quantises to zeros past its + * width, which its down projection does not read. */ + { + const std::vector tab = tables(w_gu, w_gus); + rad_op h = rad_decl_op(b, "moe_gemm_q", + RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", 2 * wq[0]), + RAD_INT("K", g.n_embd), RAD_INT("n_expert", n_reg), + RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK), + RAD_STR("a_order", "token"), RAD_STR("dtype", edtype[0]), + RAD_INT("N_odd", 2 * wq[1]), RAD_INT("K_odd", g.n_embd), + RAD_INT("parts", 2)), + tab.data(), (int)tab.size()); + op_gu = rw(b, h, {rot ? w.hr.q : w.h.q, rot ? w.hr.s : w.h.s, w.sorted, w.eoff}, {w.egu}); + } + /* THE DOWN PROJECTION'S INPUT IS FREE TO ROTATE IN PLACE, because `w.eff` is written here and + * read by exactly one op -- the down GEMM below, which takes the codes alone, so the bf16 + * product is not written. So the rotation is not an extra launch, it is the same launch + * resolving to the rotated op. */ + RAD_ARCH_TRY(gq_exp.declare(b, g, w.egu, w.eff, c.n_ff_exp, "silu", c.rows * c.top_k, + false, rot)); + { + const std::vector tab = tables(w_dn, w_dns); + rad_op h = rad_decl_op(b, "moe_gemm_q", + RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", g.n_embd), + RAD_INT("K", wq[0]), RAD_INT("n_expert", n_reg), + RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK), + RAD_STR("a_order", "sorted"), RAD_STR("dtype", edtype[1]), + RAD_INT("N_odd", g.n_embd), RAD_INT("K_odd", wq[1]), + RAD_INT("parts", 1)), + tab.data(), (int)tab.size()); + op_dn = rw(b, h, {w.eff.q, w.eff.s, w.sorted, w.eoff}, {w.edn}); + } + /* ---- THE PROTECTED EXPERTS' OWN PAIR. Their weights are the layer's, not expert slots: a + * container's experts in a layer are one fixed-size unit each, and these are four times the + * bytes -- so they are static, always resident, and joined to the layer's unit with the + * router. One run of handles a projection, a table of `prot.size()`; the GEMMs are handed the + * trailing run of the offsets, the rows the quantised down GEMM left zero, and write them. + * + * WHERE EVERY RANK HOLDS A SLICE OF EVERY EXPERT, IT HOLDS ONE OF THESE TOO, and an EVEN one: + * the parity split exists because a 640-wide expert is five 128-wide scale blocks, and a bf16 + * expert has no blocks -- so rank r takes intermediate units [r*w, (r+1)*w) of each, rows of + * gate and of up and columns of down, and the block's all-reduce sums the partials as it does + * every other expert's. */ + if (!prot.empty()) { + const int64_t np = (int64_t)prot.size(); + int64_t wp = c.n_ff_exp; + int psh_row = RAD_SHARD_NONE, psh_col = RAD_SHARD_NONE, pparts = 0; + if (split) { + /* `n_ff_exp` is this rank's wider slice here; the expert's whole width is where the + * parity slices end. */ + const int64_t full = c.ff_hi[0] > c.ff_hi[1] ? c.ff_hi[0] : c.ff_hi[1]; + if (full % g.world || (full / g.world) % 64) { + fprintf(stderr, "radiance: layer %d's plain experts are %lld wide, which %d ranks " + "cannot share in 64-wide tiles\n", l, (long long)full, g.world); + return RAD_E_INVAL; + } + wp = full / g.world; + psh_row = RAD_SHARD_ROW; + psh_col = RAD_SHARD_COL; + pparts = 2; + } + w_pgu.assign((size_t)np, 0); + w_pdn.assign((size_t)np, 0); + for (int64_t j = 0; j < np; ++j) { + const int64_t parts[2] = { wp, wp }; + w_pgu[(size_t)j] = decl_w_n(b, nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l, + (long long)(c.expert_base + prot[(size_t)j])), + RAD_BF16, {2 * wp, g.n_embd}, RAD_ACCESS_PER_TOKEN, + psh_row, grp_layer(l), 0, parts, pparts); + if (!w_pgu[(size_t)j]) return RAD_E_INVAL; + } + for (int64_t j = 0; j < np; ++j) { + w_pdn[(size_t)j] = decl_w(b, nm.f("blk.%d.ffn_down_exps.%lld.weight", l, + (long long)(c.expert_base + prot[(size_t)j])), + RAD_BF16, {g.n_embd, wp}, RAD_ACCESS_PER_TOKEN, psh_col, + grp_layer(l)); + if (!w_pdn[(size_t)j]) return RAD_E_INVAL; + } + /* The gate_up output and the gate's, a sorted row each and in bf16: the rows of the + * regular experts are never written and never read. */ + b_pgu = decl_b(b, nm.f("blk.%d.moe_prot_gu", l), RAD_BF16, {c.rows * c.top_k, 2 * wp}); + pff.x = decl_b(b, nm.f("blk.%d.moe_prot_ff", l), RAD_BF16, {c.rows * c.top_k, wp}); + if (!b_pgu || !pff.x) return RAD_E_INVAL; + op_pgu = rw(b, rad_decl_op(b, "moe_gemm", + RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", 2 * wp), + RAD_INT("K", g.n_embd), RAD_INT("n_expert", np), + RAD_INT("top_k", c.top_k), RAD_STR("a_order", "token"), + RAD_STR("dtype", "bf16")), + w_pgu.data(), (int)np), + {w.h.x, w.sorted, w.eoff}, {b_pgu}); + Geom gx = g; + gx.w_bf16 = true; + RAD_ARCH_TRY(gq_prot.declare(b, gx, b_pgu, pff, wp, "silu", c.rows * c.top_k, true, + false)); + op_pdn = rw(b, rad_decl_op(b, "moe_gemm", + RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", g.n_embd), + RAD_INT("K", wp), RAD_INT("n_expert", np), + RAD_INT("top_k", c.top_k), RAD_STR("a_order", "sorted"), + RAD_STR("dtype", "bf16")), + w_pdn.data(), (int)np), + {pff.x, w.sorted, w.eoff}, {w.edn}); + if (!op_pgu || !op_pdn) return RAD_E_INVAL; + } + } + /* ---- the calibration tap, declared LAST of the routed arm so its buffers cannot alias one + * the arm is still using. They are PERSIST, so the planner would not alias them anyway; the + * order is kept because declaration order IS the buffer plan and a reader should not have to + * check which kind a name is to know that. */ + if (c.calib) { + /* A rank holding a slice of each expert sees a slice of its K, and a Hessian of a slice is + * not the Hessian the packer needs. Calibration runs at one rank. */ + if (split) { + fprintf(stderr, "radiance: calibration runs at one rank; this rank holds a slice of " + "every expert's width, and its Hessians would be of the slice\n"); + return RAD_E_INVAL; + } + if (!calib_dir()) { + fprintf(stderr, "radiance: calibration is configured but RADIANCE_CALIB_DIR is not " + "set; there is nowhere to write the Hessians\n"); + return RAD_E_INVAL; + } + /* Both K are multiples of 128 already, which `expert_rot` also requires; gram_accum needs + * only a multiple of four, but the 128 is what makes a 64-wide output tile sit inside one + * scale group and there is no width here that does not. */ + if (!c.expert_bf16 && ((g.n_embd % RAD_FP8_BLOCK) || (c.n_ff_exp % RAD_FP8_BLOCK))) + return RAD_E_SHAPE; + gram_gu_stem = nm.f("blk.%d.ffn_gate_up_exps", l); + gram_dn_stem = nm.f("blk.%d.ffn_down_exps", l); + b_gram_gu = decl_b(b, nm.f("blk.%d.gram_gu", l), RAD_F32, {g.n_embd, g.n_embd}, + RAD_BUF_PERSIST); + b_gram_dn = decl_b(b, nm.f("blk.%d.gram_dn", l), RAD_F32, {c.n_ff_exp, c.n_ff_exp}, + RAD_BUF_PERSIST); + /* bf16 experts read the model's own activation, and the tap sums exactly that; the + * quantised ones read codes, rotated when the plane is, and the files say which. */ + gram_domain = rot ? (uint32_t)RAD_FP8_BLOCK : 0u; + if (c.expert_bf16) { + op_gram_gu = rw(b, RAD_OP(b, "gram_accum", + RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n", g.n_embd), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {w.h.x, b_gram_gu}, {b_gram_gu}); + op_gram_dn = rw(b, RAD_OP(b, "gram_accum", + RAD_PARAMS(RAD_RANGE("M", 1, c.rows * c.top_k), + RAD_INT("n", c.n_ff_exp), RAD_INT("group", RAD_FP8_BLOCK), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {w.eff.x, b_gram_dn}, {b_gram_dn}); + } else { + op_gram_gu = rw(b, RAD_OP(b, "gram_accum", + RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n", g.n_embd), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8")), + RAD_NOWEIGHTS), + {rot ? w.hr.q : w.h.q, rot ? w.hr.s : w.h.s, b_gram_gu}, {b_gram_gu}); + /* The down tap's M is the SORTED height, `rows * top_k`, because `w.eff` is one row per + * (token, slot). gate_up's is the token height -- its GEMM gathers internally, and every + * token is routed to exactly top_k experts, so the gathered distribution is the token + * distribution times top_k and H is used only up to a positive scale. */ + op_gram_dn = rw(b, RAD_OP(b, "gram_accum", + RAD_PARAMS(RAD_RANGE("M", 1, c.rows * c.top_k), + RAD_INT("n", c.n_ff_exp), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8")), + RAD_NOWEIGHTS), + {w.eff.q, w.eff.s, b_gram_dn}, {b_gram_dn}); + } + /* One expert's Gram a launch: the same op over that expert's run of the sorted rows, + * into that expert's square of the scratch. TRANSIENT, because nothing on the card reads + * it after the pass -- it goes back to the host before the next op is issued. */ + b_gram_dne = decl_b(b, nm.f("blk.%d.gram_dn_experts", l), RAD_F32, + {c.n_expert * c.n_ff_exp, c.n_ff_exp}); + if (c.expert_bf16) + op_gram_dne = rw(b, RAD_OP(b, "gram_accum", + RAD_PARAMS(RAD_RANGE("M", 1, c.rows * c.top_k), + RAD_INT("n", c.n_ff_exp), + RAD_INT("group", RAD_FP8_BLOCK), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {w.eff.x, b_gram_dne}, {b_gram_dne}); + else + op_gram_dne = rw(b, RAD_OP(b, "gram_accum", + RAD_PARAMS(RAD_RANGE("M", 1, c.rows * c.top_k), + RAD_INT("n", c.n_ff_exp), + RAD_INT("group", RAD_FP8_BLOCK), + RAD_STR("dtype", "fp8a8")), + RAD_NOWEIGHTS), + {w.eff.q, w.eff.s, b_gram_dne}, {b_gram_dne}); + if (!b_gram_dne || !op_gram_dne) return RAD_E_INVAL; + } + + /* THE GATHER FOLDS THE SHARED ARM IN, so `w.moe` is never written: `scale_rows` and a + * separate gather would be two dispatches a layer, with a 160 KiB round trip through the + * buffer between them on top. */ + gfold = shared; + { + rad_buf grd[5] = { w.edn, w.ew, w.sorted, w.sout, w.sgate }; + rad_buf gwr[1] = { w.h.x }; + op_gather = RAD_OP(b, "moe_gather", + RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n", g.n_embd), + RAD_INT("top_k", c.top_k), RAD_STR("dtype", g.dtype), + RAD_STR("act", gfold ? "sigmoid" : "none")), + RAD_NOWEIGHTS); + if (!op_gather) return RAD_E_INVAL; + rad_op_reads (b, op_gather, grd, gfold ? 5 : 3); + rad_op_writes(b, op_gather, gwr, 1); + } + + /* ---- the shared expert. Ordinary dense linears over the same normed input. */ + if (shared) { + /* THE SECOND LANE NEEDS THESE OUT OF THE SHARING POOL, and rad_buf_concurrent is where + * that is said. The arm runs beside the routed GEMMs, so a plan that laid `sgu` over + * `egu` -- legal from the linear order, which puts one range entirely after the other -- + * would have two streams writing the same arena bytes. It costs a few MiB of arena. */ + RAD_ARCH_TRY(rad_buf_concurrent(b, w.sgu)); + /* WHAT THE DOWN PROJECTION READS decides what the gate writes, so it is asked first: the + * codes, or the bf16 plane when the weight is plain -- a bf16 model, or a quantised one + * that keeps the shared expert at the checkpoint's precision. */ + const char* down_base = nm.f("blk.%d.ffn_down_shexp", l); + RAD_ARCH_TRY(sh_down.probe(b, nm, g, down_base, + { nm.ckpt("%s.down_proj.weight", src.shared) })); + /* The code pair the gate writes, E4M3 or the int8 one (ActFP8::q8_fed) -- and an int8 + * down projection that quantises for itself writes the int8 pair on this lane too. */ + if (w.sff.cq()) { + RAD_ARCH_TRY(rad_buf_concurrent(b, w.sff.cq())); + RAD_ARCH_TRY(rad_buf_concurrent(b, w.sff.cs())); + } + if (w.sff.q8 && !w.sff.q8_fed && sh_down.probed_i8) { + RAD_ARCH_TRY(rad_buf_concurrent(b, w.sff.q8)); + RAD_ARCH_TRY(rad_buf_concurrent(b, w.sff.s8)); + } + if (!w.sff.q || (sh_down.reads_x && !(w.sff.q8_fed && sh_down.probed_i8))) + RAD_ARCH_TRY(rad_buf_concurrent(b, w.sff.x)); + RAD_ARCH_TRY(rad_buf_concurrent(b, w.sout)); + RAD_ARCH_TRY(rad_buf_concurrent(b, w.sgate)); + /* The gate/up rows and the down columns of this rank's slice -- the even split, or the + * uneven one Config states -- and the split of gate from up stays, because that is a + * property of the stacked checkpoint tensor and not of the rank count. */ + RAD_ARCH_TRY(sh_gate_up.declare(b, nm, g, nm.f("blk.%d.ffn_gate_up_shexp", l), + 2 * c.n_ff_shared, g.n_embd, RAD_SHARD_ROW, grp_layer(l), + { nm.ckpt("%s.gate_proj.weight", src.shared), + nm.ckpt("%s.up_proj.weight", src.shared) }, + w.h, w.sgu, c.rows, + { c.n_ff_shared, c.n_ff_shared }, + c.shared_lo, c.shared_hi)); + /* An int8 down projection fed the int8 pair reads no bf16 plane, so none is written. */ + RAD_ARCH_TRY(gq_sh.declare(b, g, w.sgu, w.sff, c.n_ff_shared, "silu", c.rows, + sh_down.reads_x && !(w.sff.q8_fed && sh_down.probed_i8))); + RAD_ARCH_TRY(sh_down.declare(b, nm, g, down_base, + g.n_embd, c.n_ff_shared, RAD_SHARD_COL, grp_layer(l), + { nm.ckpt("%s.down_proj.weight", src.shared) }, + w.sff, w.sout, c.rows, {}, + c.shared_lo, c.shared_hi)); + /* The gate. REPLICATED like the router and for the same reason: it is computed from the + * whole residual stream and a sharded copy would give two ranks two different gates for + * one token. One output column, so the GEMM is skinny and the kernel clamps rather than + * masks its N tile -- which is why N = 1 is legal here. */ + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ffn_gate_shexp.weight", l), src.shared_gate)); + w_sgate = decl_w(b, nm.f("blk.%d.ffn_gate_shexp.weight", l), RAD_BF16, {1, g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); + op_sgate = rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", 1), + RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_sgate)), + {w.h.x}, {w.sgate}); + } + + 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; +} + +/* ONE PASS OF AT MOST `c.rows` TOKENS. Every op here is per row -- the norm and the quantiser group + * along K within a row, the router and the top-k are a row each, the grouped GEMMs give each sorted + * row its own accumulation, and the gather closes each token's sum over its own slots -- so a pass + * computes exactly the rows it names. + * + * THE EXPERT BUFFERS ARE ADDRESSED FROM ZERO, not from `r0`. They are one pass tall by declaration, + * and `sorted_tok` indexes them relative to the pass; the only operands that carry the pass offset + * are the ones that live at the step's height -- the residual stream and the normed input. */ + + +/* The shared arm's first stage: its one-column gate and its gate_up, both over the normed input. + * The shared expert is ordinary dense linears over that input, and every buffer it touches is the + * step's height -- so the pass offset goes through all of them exactly as it does through an + * MlpFP8 slice. */ +inline void MoeFP8::shared_up(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const { + RAD_ISSUE_N(c_, op_sgate, rows, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_W(w_sgate), + brow_slice(w.sgate, r0, rows, 1)); + sh_gate_up.step(c_, w.h, w.sgu, T, r0, rows); +} + +inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const { + /* `ne` is THIS RANK'S expert count and `ne_all` the model's: the logits plane and the top-k + * are the model's width, everything after the scatter is this rank's slice. */ + const int64_t ne = c.n_expert, ne_all = c.n_expert_all, k = c.top_k; + const bool shared = op_sgate != 0; + + if (!ext_in) nq_h.step(c_, T, r0, rows); + + /* THE SHARED ARM BESIDE THE ROUTED ONE, ON THE SAME QUEUE. It reads the same normed input the + * routed arm does and writes nothing the routed arm touches until the gather joins them, so + * each of its three stages is independent of the routed stage it is issued behind: its gate + * and gate_up beside the routed gate_up, its quantiser beside the routed one, its down beside + * the routed down. A recorded pass plays each such pair with the second launch unordered + * behind the first (Ctx::haz_mark), so the two run at once, and the next routed stage -- + * which waits for everything in front of it -- waits for the shorter shared stage too, which + * has long finished. That is the overlap a second queue would buy, without the queue's fork and + * join: a barrier packet on each side of the arm, and a join on another queue's signal that + * the packet processor sees microseconds late. Every buffer the arm writes is out of the + * sharing pool (see declare), so issuing it ahead of its declared position moves no byte. */ + + /* THE ROUTED ARM. */ + /* THE COUNTS GO STRAIGHT INTO THE CORE'S ROW for this layer when it keeps one, so the + * report at the end of step() hands them over with no copy -- otherwise a card-local blit + * a routed layer, a whole dependent dispatch for a kilobyte. */ + int32_t* const counts = rad_route_counts(c_, layer, ne); + const RadOperand ecnt = counts ? praw(counts, RAD_I32, ne) : brows(w.ecnt, ne); + RAD_ISSUE_N(c_, op_router, rows, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_W(w_router), + brow_slice(w.logits, r0, rows, ne_all)); + /* One launch or two. `w.ids` is the fused op's OUTPUT where it was the sort's input, and + * every other operand is the one the pair is handed. */ + if (op_topk_scatter && rows <= topk_scatter_rows) { + RAD_ISSUE_N(c_, op_topk_scatter, rows, brow_slice(w.logits, r0, rows, ne_all), + brow_slice(w.ids, r0, rows, k), brow_slice(w.ew, r0, rows, k), + brows(w.sorted, rows * k), brows(w.eoff, ne + 1), ecnt); + } else { + RAD_ISSUE_N(c_, op_topk, rows, brow_slice(w.logits, r0, rows, ne_all), + brow_slice(w.ids, r0, rows, k), brow_slice(w.ew, r0, rows, k)); + RAD_ISSUE_N(c_, op_scatter, rows, brow_slice(w.ids, r0, rows, k), + brows(w.sorted, rows * k), brows(w.eoff, ne + 1), ecnt); + } + + /* The rotated re-quantisation of the same input, when the expert plane carries a + * rotation and the caller's read did not write it. Without a rotation the GEMM reads + * `h`'s pair. */ + const bool rot = c.expert_rot != 0; + if (op_hq) + RAD_ISSUE_N(c_, op_hq, rows, brow_slice(w.h.x, r0, rows, g.n_embd), + brow_slice(w.hr.q, r0, rows, g.n_embd), + brow_slice(w.hr.s, r0, rows, g.n_embd / RAD_FP8_BLOCK)); + + /* The two grouped GEMMs, and the weight tables: the FIRST handle of each run and its length. + * The runs are contiguous by construction -- see declare -- so `w_gu[q] + i` is expert + * 2 * i + q, and each parity is its own pair of table operands. */ + if (c.expert_bf16) + RAD_ISSUE_N(c_, op_gu, rows, brow_slice(w.h.x, r0, rows, g.n_embd), + RAD_WTAB(w_gu[0], ne), brows(w.sorted, rows * k), brows(w.eoff, ne + 1), + brows(w.egu, rows * k)); + else + RAD_ISSUE_N(c_, op_gu, rows, + brow_slice(rot ? w.hr.q : w.h.q, r0, rows, g.n_embd), + brow_slice(rot ? w.hr.s : w.h.s, r0, rows, g.n_embd / RAD_FP8_BLOCK), + RAD_WTAB(w_gu[0], n_reg / 2), RAD_WTAB(w_gus[0], n_reg / 2), + brows(w.sorted, rows * k), brows(w.eoff, n_reg + 1), + RAD_WTAB(w_gu[1], n_reg / 2), RAD_WTAB(w_gus[1], n_reg / 2), + brows(w.egu, rows * k)); + if (shared) shared_up(c_, T, r0, rows); + gq_exp.step(c_, w.egu, rows * k, 0, rows * k); + if (shared) gq_sh.step(c_, w.sgu, T, r0, rows); + if (c.expert_bf16) + RAD_ISSUE_N(c_, op_dn, rows, brows(w.eff.x, rows * k), RAD_WTAB(w_dn[0], ne), + brows(w.sorted, rows * k), brows(w.eoff, ne + 1), brows(w.edn, rows * k)); + else + RAD_ISSUE_N(c_, op_dn, rows, + brows(w.eff.q, rows * k), brows(w.eff.s, rows * k), + RAD_WTAB(w_dn[0], n_reg / 2), RAD_WTAB(w_dns[0], n_reg / 2), + brows(w.sorted, rows * k), brows(w.eoff, n_reg + 1), + RAD_WTAB(w_dn[1], n_reg / 2), RAD_WTAB(w_dns[1], n_reg / 2), + brows(w.edn, rows * k)); + /* THE PROTECTED EXPERTS, over the trailing run of the offsets: their sorted rows are the + * ones the quantised down GEMM above zeroed as past its live count, and the down GEMM + * here writes them -- after it, which the shared `edn` orders. */ + if (op_pgu) { + const int64_t np = (int64_t)prot.size(); + const RadOperand poff = brow_slice(w.eoff, n_reg, np + 1, 1); + RAD_ISSUE_N(c_, op_pgu, rows, brow_slice(w.h.x, r0, rows, g.n_embd), + RAD_WTAB(w_pgu[0], np), brows(w.sorted, rows * k), poff, + brows(b_pgu, rows * k)); + gq_prot.step(c_, b_pgu, rows * k, 0, rows * k); + RAD_ISSUE_N(c_, op_pdn, rows, brows(pff.x, rows * k), RAD_WTAB(w_pdn[0], np), + brows(w.sorted, rows * k), poff, brows(w.edn, rows * k)); + } + if (shared) sh_down.step(c_, w.sff, w.sout, T, r0, rows); + /* THE CALIBRATION TAP, issued between the two GEMMs' inputs being written and the pass + * ending. It reads exactly the operands the GEMMs above read and writes nothing they + * touch, so removing it changes no number the model produces -- which is the property + * that lets a calibration run be compared against a serving one. */ + if (op_gram_gu && !calib_done) { + if (calib_rows == 0) { + /* The accumulators are arena memory and arrive holding whatever was there. */ + rad_memset_async(rad_buf_ptr(c_, b_gram_gu), 0, + g.n_embd * g.n_embd * 4, rad_stream(c_)); + rad_memset_async(rad_buf_ptr(c_, b_gram_dn), 0, + c.n_ff_exp * c.n_ff_exp * 4, rad_stream(c_)); + } + if (c.expert_bf16) { + RAD_ISSUE_N(c_, op_gram_gu, rows, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_NONE, + brows(b_gram_gu, g.n_embd)); + RAD_ISSUE_N(c_, op_gram_dn, rows * k, brows(w.eff.x, rows * k), RAD_NONE, + brows(b_gram_dn, c.n_ff_exp)); + } else { + RAD_ISSUE_N(c_, op_gram_gu, rows, + brow_slice(rot ? w.hr.q : w.h.q, r0, rows, g.n_embd), + brow_slice(rot ? w.hr.s : w.h.s, r0, rows, + g.n_embd / RAD_FP8_BLOCK), + brows(b_gram_gu, g.n_embd)); + RAD_ISSUE_N(c_, op_gram_dn, rows * k, + brows(w.eff.q, rows * k), brows(w.eff.s, rows * k), + brows(b_gram_dn, c.n_ff_exp)); + } + if (op_gram_dne) calib_experts_pass(c_, rows * k); + calib_rows += rows; + if (calib_rows >= calib_target()) { + const bool a = calib_write(c_, b_gram_gu, g.n_embd, calib_rows, gram_gu_stem, + gram_domain); + const bool bb = calib_write(c_, b_gram_dn, c.n_ff_exp, calib_rows * k, + gram_dn_stem, gram_domain); + const bool ce = !op_gram_dne || + (!calib_dne_failed && + calib_dne.write(gram_dn_stem, c.expert_base, gram_domain, + rad_rank(c_))); + calib_done = true; + if (layer == 0) + std::fprintf(stderr, "radiance: calibration wrote layer Hessians after %lld " + "tokens to %s%s\n", calib_rows, calib_dir(), + (a && bb && ce) ? "" : " (WITH ERRORS)"); + } + } + + /* THE GATHER LAST, because with the fold it reads the arm. Its operands are the routed slots + * plus `sout` and `sgate`, and it writes the block's delta straight into `h.x`. */ + if (!gather_taken(g, T, gather_out_rows, gather_out_rows6)) + RAD_ISSUE_N(c_, op_gather, rows, brows(w.edn, rows * k), brow_slice(w.ew, r0, rows, k), + brows(w.sorted, rows * k), + gfold ? brow_slice(w.sout, r0, rows, g.n_embd) : RAD_NONE, + gfold ? brow_slice(w.sgate, r0, rows, 1) : RAD_NONE, + brow_slice(w.h.x, r0, rows, g.n_embd)); + + /* A write that takes the all-reduce does it ONCE over the whole step, so it answers on T and + * this pass has to ask the same question of the same T, not of its own rows. */ + if (op_ar && !ar_taken(g, ar_out_take != kArOutNorm ? T : rows, ar_out, ar_out_take)) + RAD_ISSUE_N(c_, op_ar, rows * g.n_embd, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_NONE); + if (op_add) + RAD_ISSUE_N(c_, op_add, rows, brow_slice(w.x, r0, rows, g.n_embd), + brow_slice(w.h.x, r0, rows, g.n_embd), + brow_slice(w.x, r0, rows, g.n_embd)); +} + +/* ONE PASS OF THE PER-EXPERT TAP. The expert offsets the scatter wrote decide how many launches + * there are and where each reads, so they come back first; then the scratch is zeroed, each + * routed expert's run of the `slots` sorted rows is summed into its square, and the scratch comes + * back to be added on the host. Both syncs are on the block's own stream, with nothing issued + * after the tap, so every op the scratch could share storage with is finished before it is + * written and none is issued until it has been read. */ +inline void MoeFP8::calib_experts_pass(RadCtx* c_, int64_t slots) const { + if (calib_dne_failed) return; + const int64_t ne = c.n_expert, K = c.n_ff_exp; + const RadStream s = rad_stream(c_); + if (calib_dne.ne == 0) calib_dne.init(ne, K); + + std::vector off((size_t)(ne + 1)); + rad_memcpy_async(off.data(), rad_buf_ptr(c_, w.eoff), (ne + 1) * 4, s); + rad_stream_sync(s); + if (off[0] != 0 || off[(size_t)ne] < 0 || off[(size_t)ne] > slots) { + std::fprintf(stderr, "radiance: layer %d's expert offsets end at %d of %lld sorted rows; " + "the per-expert calibration stops\n", + layer, off[(size_t)ne], (long long)slots); + calib_dne_failed = true; + return; + } + + const int64_t bytes = ne * K * K * 4; + float* staging = calib_staging(c_, bytes); + if (!staging) { calib_dne_failed = true; return; } + void* scratch = rad_buf_ptr(c_, b_gram_dne); + rad_memset_async(scratch, 0, bytes, s); + for (int64_t e = 0; e < ne; ++e) { + const int64_t r0 = off[(size_t)e], n = off[(size_t)e + 1] - r0; + if (n <= 0) continue; + if (c.expert_bf16) + RAD_ISSUE_N(c_, op_gram_dne, n, brow_slice(w.eff.x, r0, n, K), RAD_NONE, + brow_slice(b_gram_dne, e * K, K, K)); + else + RAD_ISSUE_N(c_, op_gram_dne, n, brow_slice(w.eff.q, r0, n, K), + brow_slice(w.eff.s, r0, n, K / RAD_FP8_BLOCK), + brow_slice(b_gram_dne, e * K, K, K)); + calib_dne.rows[(size_t)e] += n; + } + rad_memcpy_async(staging, scratch, bytes, s); + rad_stream_sync(s); + calib_dne.add(staging); +} + +inline void MoeFP8::step(RadCtx* c_, const RadBatch* batch) const { + const int64_t T = batch->n_tok; + for (int64_t r0 = 0; r0 < T; r0 += c.rows) { + const int64_t n = (T - r0 < c.rows) ? (T - r0) : c.rows; + pass(c_, T, r0, n); + } + + /* ---- THE HANDOFF TO THE HEAT ENGINE, and it is a handoff and not a computation: the buffers + * below were written by ops this block already issued. `rad_route_report` copies the histogram + * back ASYNCHRONOUSLY and the heat engine consumes it on the NEXT step, so nothing here blocks + * the compute stream (spec §5.5). Without it the expert-tiered placement has no measurement to + * promote on, and every expert stays wherever the warm start put it. + * + * IT REPORTS THE LAST PASS, which on the shipped configuration is the whole step: `c.rows` + * defaults to the prefill chunk, so there is one pass. A deployment that raises the chunk past + * it gets the last pass's histogram -- a sample of the step rather than the whole of it, which + * is what the heat engine wants anyway (it is a popularity estimate consumed a step late). + * + * `expert_w` IS LEFT NULL rather than filled: RadRouting declares it `const float*` and this + * block's routing weights are bf16, which is what the gather multiplies. Nothing in the core + * reads the field -- the heat engine takes `expert_count` -- and handing it a bf16 plane under + * a float pointer would be a lie that survives until something does. */ + moe_debug_weights(c_, layer, c.top_k, w.ids, w.ew); + RadRouting r{}; + r.expert_ids = (const int32_t*)rad_buf_ptr(c_, w.ids); + r.expert_w = nullptr; + const int32_t* const counts = rad_route_counts(c_, layer, c.n_expert); + r.expert_count = counts ? counts : (const int32_t*)rad_buf_ptr(c_, w.ecnt); + r.sorted_tok = (const int32_t*)rad_buf_ptr(c_, w.sorted); + r.expert_offset = (const int32_t*)rad_buf_ptr(c_, w.eoff); + r.top_k = c.top_k; + r.n_expert = c.n_expert; + rad_route_report(c_, layer, &r); +} + +} /* namespace arch */ +} /* namespace rad */ + +#endif /* RAD_BLOCK_MOE_FP8_H */ diff --git a/arch/common/rad_block_mtp_fp8.h b/arch/common/rad_block_mtp_fp8.h new file mode 100644 index 00000000..44d13b04 --- /dev/null +++ b/arch/common/rad_block_mtp_fp8.h @@ -0,0 +1,478 @@ +/* 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 + +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 +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 +inline int MtpBlockFP8::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 +inline void MtpBlockFP8::step(RadCtx* c, const RadBatch* batch) const { + const int64_t T = batch->n_tok; + const int r = batch->draft_pass; + + /* The history pass gathers; the rounds after it read the head's own output, which the pass + * before left in the same buffer. */ + 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); + 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 nothing exists only to leave K and V behind. One that does + * 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; + if (L <= 0) return; + 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, 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; + +} /* namespace arch */ +} /* namespace rad */ + +#endif /* RAD_BLOCK_MTP_FP8_H */ diff --git a/arch/common/rad_block_mtp_hc.h b/arch/common/rad_block_mtp_hc.h new file mode 100644 index 00000000..75e068c3 --- /dev/null +++ b/arch/common/rad_block_mtp_hc.h @@ -0,0 +1,587 @@ +/* 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 + +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); + 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 -- and one that does + * not exists only to leave K and V behind. */ + int64_t L = T; /* the rows the lm_head runs over */ + if (r < 0) { + L = batch->n_draft_out; + if (L <= 0) return; + 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 */ diff --git a/arch/common/rad_block_ple.h b/arch/common/rad_block_ple.h new file mode 100644 index 00000000..8a82cfc5 --- /dev/null +++ b/arch/common/rad_block_ple.h @@ -0,0 +1,547 @@ +/* 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 on the card and cannot be staged onto it, so `embed_lookup_q` runs on the HOST + * over the container's own mmap and its result crosses the link once -- 5 KB a token at decode. + * libavx/avx_ngram.cpp carries that argument in full. 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. 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 a host kernel, so they live + * in the host arena; 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 ``; 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 + * host gather; `e` is written by the host 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. + * + * `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 */ diff --git a/arch/common/rad_block_vit.h b/arch/common/rad_block_vit.h new file mode 100644 index 00000000..33199b01 --- /dev/null +++ b/arch/common/rad_block_vit.h @@ -0,0 +1,345 @@ +/* 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 +#include +#include +#include + +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 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(P, ctx->max_tok); + P = std::max(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 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 */ diff --git a/arch/common/rad_fp8.h b/arch/common/rad_fp8.h new file mode 100644 index 00000000..753a2fe4 --- /dev/null +++ b/arch/common/rad_fp8.h @@ -0,0 +1,1003 @@ +/* rad_fp8.h -- the two pieces every block-scaled FP8 block is built from. + * + * One plugin per (architecture, quantisation) is spec §2.4, and the file-count mitigation is that + * the blocks are COMPOSITION (rad_arch.h). This is the composed piece the FP8 blocks share and the + * bf16 ones have no use for: a linear layer whose weight is E4M3 with a block scale plane, and the + * activation quantiser that feeds it. + * + * ============================== WHAT "BLOCK-SCALED FP8" IS ============================== + * + * The format is the checkpoint's, not this project's. Qwen3.8-27B-FP8 -- and every other + * `quantization_config: {quant_method: fp8, weight_block_size: [128,128]}` release -- stores each + * linear as + * + * .weight F8_E4M3, row-major [N][K] + * .weight_scale_inv BF16, row-major [ceil(N/128)][ceil(K/128)] + * + * and libr4d's gemm_fp8a16_nt_m1 / gemm_fp8a8_nt_m16 / gemm_fp8a8_tiled read exactly those bytes + * (libr4d/r4d_fp8_layout.cpp verified the grid against the real file). So rad-convert COPIES: + * no permutation, no repacking, no dequantisation, and a .rad costs what the checkpoint does. That + * is the whole reason this plugin family exists -- widening a 27B FP8 checkpoint to bf16 doubles + * the weight bytes, which does not fit the device memory this engine is built for. + * + * ============================== WHY THE SCALE PLANE IS A WEIGHT ============================== + * + * `gemm_nt_q`'s operand list is `a`, `a_scale`, `b`(w), `b_scale`(w) -> `y`, so the scale plane is + * a first-class WEIGHT OPERAND and is declared here as its own rad_weight. It is not an `aux` + * stream on the weight, and that is not a stylistic choice: + * + * - RadLayout can declare an aux stream beside a weight, but RadArgs has NO WAY TO DELIVER one + * to a launch (libr4d/r4d_fp8_layout.cpp reports this). An aux scale would be unreachable + * at run time by construction. + * - a weight can be placed, moved and load-time SHARDED on its own. The engine slices a + * row-sharded [136,40] plane at dim 0 exactly as it slices the [17408,5120] weight, and an aux + * stream has no shard axis at all. + * + * The cost is one extra declared weight per linear -- 2.1 KiB of scales against 89 MiB of weight at + * gate_proj's shape -- and one extra name-map entry, which is `_scale_inv` and is derived + * here rather than spelled at every call site. + * + * ============================== WHY THE ACTIVATIONS ARE FP8 TOO ============================== + * + * `dtype` is ONE string per declared op, so a linear is `fp8a16` or `fp8a8` and cannot be both. + * fp8a16 reads a bf16 activation directly and needs no quantise launch, which is strictly better -- + * and its kernel is `M <= 1`. One row. That serves a single-sequence decode and nothing else: at + * two concurrent sequences M is 2 and there is no kernel. So the shipped path is `fp8a8`, whose two + * kernels between them cover every M (`nt_m16` to 16, `tiled` above), and the price is one + * `quant_act_fp8` launch per activation that feeds a GEMM. + * + * PER ACTIVATION, NOT PER LINEAR. The three attention projections all read the post-norm hidden + * state, and the GDN block's in and z projections both read it; quantising once and pointing every + * linear at the same pair is the difference between one launch a layer and five. That is why + * QuantFP8 is a separate struct from LinearFP8 rather than a step inside it. + */ +#ifndef RAD_FP8_H +#define RAD_FP8_H + +#include "rad_arch.h" + +#include +#include + +namespace rad { +namespace arch { + +/* The scale block, in both dimensions. A property of the CHECKPOINT (`weight_block_size`), not a + * knob: libr4d compiles it in as a shift and its constraint rows carry C_EQ("group", 128), so a + * container quantised at any other width resolves to no kernel and says so by name. Declared as a + * named constant because three files have to agree about it. */ +enum { RAD_FP8_BLOCK = 128 }; + +/* Rows of the scale plane for an N-row weight, and columns for a K-wide one. */ +inline int64_t fp8_blocks(int64_t n) { return (n + RAD_FP8_BLOCK - 1) / RAD_FP8_BLOCK; } + +/* An activation and its fp8 twin. The bf16 buffer is what the rest of the graph reads and writes; + * the other two exist only between the quantiser and the GEMMs that consume them. */ +struct ActFP8 { + rad_buf x = 0; /* [max_tok, n] bf16 */ + rad_buf q = 0; /* [max_tok, n] e4m3 */ + rad_buf s = 0; /* [max_tok, ceil(n/block)] f32 */ + /* THE SAME ACTIVATION AT INT8 CODES, for an int8 linear (LinearFP8::i8): [max_tok, n] i8 and + * its f32 scale per (row, block). Declared only where a model's trunk is int8 (declare_qs's + * `i8`), and written either by the linear's own quant_act_i8g from `x` or, when `q8_fed`, by + * the producer itself. */ + rad_buf q8 = 0; + rad_buf s8 = 0; + /* THE PRODUCER WRITES q8/s8 ITSELF -- a connection read (HyperConn::Config::codes_i8), a gated + * quantiser, the attention's gate epilogue, the delta net's output epilogue -- in place of + * the E4M3 pair, so an int8 linear reading this input declares no quantiser of its own. Set by + * the model when it declares the pair, before the wires copy it. */ + bool q8_fed = false; + + /* The code pair the producer writes: int8 when the model fed it, E4M3 otherwise. */ + rad_buf cq() const { return q8_fed ? q8 : q; } + rad_buf cs() const { return q8_fed ? s8 : s; } + + /* Declare all three at once, since a caller that declared two of them is a caller with a bug. + * `x` is passed in rather than made here: it is usually a buffer the block already had. + * + * `rows` IS NOT OPTIONAL FOR A BUFFER THAT IS NOT ONE ROW A TOKEN, and leaving it at the + * default for one that is not is a silent arena overrun rather than a refusal. The default is + * `g.max_tok` because that is what an activation is; a MoE expert plane is `rows * top_k` and + * an encoder tower's is its own patch count. Getting it wrong is hard to see: a routed expert + * pair declared at max_tok while the gated quantiser writes `rows * top_k` overruns onto a + * buffer that may already be dead, so the model stays correct and only a later reader of that + * buffer sees it. core/runtime/issue.cpp refuses the issue by name, which is the guard; this + * is the honest declaration. */ + int declare_qs(RadBuilder* b, Names& nm, const Geom& g, const char* name, int64_t n, + int64_t rows = 0, bool i8 = false) { + /* A bf16 model's linears read `x` and nothing else (Geom::w_bf16), so there are no codes + * to declare: an arena plane nothing writes is a plane the planner still charges. */ + if (g.w_bf16) { q = s = q8 = s8 = 0; return RAD_OK; } + const int64_t m = rows > 0 ? rows : g.max_tok; + q = decl_b(b, nm.f("%s.q", name), RAD_F8E4M3, { m, n }); + s = decl_b(b, nm.f("%s.s", name), RAD_F32, { m, fp8_blocks(n) }); + if (i8) { + q8 = decl_b(b, nm.f("%s.q8", name), RAD_I8, { m, n }); + s8 = decl_b(b, nm.f("%s.s8", name), RAD_F32, { m, fp8_blocks(n) }); + if (!q8 || !s8) return RAD_E_INVAL; + } + return (q && s) ? RAD_OK : RAD_E_INVAL; + } +}; + +/* HOW MANY TOKEN ROWS THE fp8a16 MATVEC COVERS, which is the one number that decides both which + * GEMM a linear issues and whether the quantiser in front of it runs at all. + * + * IT IS ONE ROW. The multi-row matvec reads the weight once for all M rows, so widening the band + * looks free; it is not. The matvec is issue-bound above one row: the per-row work is 27 + * instructions per 16 weight bytes and eight rows of it do not fit in the issue budget, so + * effective weight bandwidth falls as M rises on identical weight traffic + * (r4d_gemm_fp8a16_nt_m1.hip has the ISA counts). The fp8a8 tile's cost is flat in M to 16, so it + * wins from two rows up and the crossover is not near eight. + * + * SO THE SHIPPED PATH IS W8A8, which is also what the checkpoint is: `quant=fp8_e4m3` with + * `activation_scheme: dynamic`, and prefill always quantises. A deployment that speculates + * runs T = 1 + n_spec on every trunk step, so it is W8A8 end to end and decode computes the + * same function prefill does. + * + * WHAT ONCE KEPT A ROW FOR THE MATVEC was the standalone `quant_act_fp8` in front of every linear + * -- one launch per activation per layer -- which the fp8a8 path needs and this one does not. The + * fusions below remove it: the producer that feeds a linear quantises in its own epilogue + * (`rmsnorm_quant_fp8`, `gated_quant_fp8`, `gate_quant_fp8`), so the fp8a8 path pays no extra + * launch and the last argument for a wider matvec band goes with it. */ +/* ...AND IT IS DECLINED, because of where the fp8 weight is stored and what the matvec can read. + * + * The fp8 weight is stored in WMMA FRAGMENT ORDER (libr4d/r4d_fp8_frag.h): a (16 row, 64 k) tile + * laid out as 32 lanes x 32 bytes, which is what lets the two fp8a8 GEMMs read a fragment straight + * from a coalesced global load instead of transposing 16 rows through LDS. Both of them do, and + * both are checked against the host reference. + * + * The matvec is built on the opposite premise -- "a lane reads 16 CONSECUTIVE k of one row", in + * three separate read paths with their own RB blocking -- and 16 consecutive k of a row are not + * contiguous in fragment order. Converting it is a rewrite of a tuned kernel, not an edit, so it + * is not done here and the op is not declared rather than declared and wrong. + * + * WHAT THAT COSTS is the one-row band falling back to the fp8a8 tile, which serves M <= 16 and + * therefore covers it. A deployment that speculates never takes this band at all: T is + * 1 + n_spec on every trunk step. */ +inline int64_t fp8_matvec_rows(const Geom& g) { + (void)g; + return 0; +} + +/* THE FUSED ATTENTION PROLOGUE'S BAND, asked here rather than restated because the block that + * issues the fused op, the op that fills the rope table, the QSA indexer that reads that table and + * the step that decides whether to fill it all have to agree on it. + * + * The fusion is bit-exact against the unfused path: the kernel reproduces `r4d_rmsnorm_bf16`'s + * sum-of-squares fold element by element rather than folding eight elements a lane, and + * r4d_selftest asserts byte equality over 1.8M elements at both gain widths. A fold order that + * merely agrees to a ULP is not enough here -- it moves the engine's transcript. + * + * IT STOPS AT THE DECODE BAND, because a fusion that replaces four launches with one pays where + * the launch is the cost and nowhere else. At a 2048-token chunk it is slightly slower than the + * four separate kernels: those are already wide enough to fill the device, and the fused form + * does strictly more arithmetic -- a rotary lane re-derives its partner's normed value rather than + * taking it from a register. 64 is the same decode band the narrow GEMM and the gated fold use, + * and for the same reason. */ +inline int64_t qk_fuse_rows(const Geom& g) { + return g.max_tok < 64 ? g.max_tok : 64; +} + +/* THE ROPE TABLE'S HEIGHT. `rope_table` writes each position at its OWN row, and the fused + * prologue and the QSA indexer read it there, so the table needs a row for every position a step + * can name -- and a speculative step names positions past the context bound. The last verify of a + * request that fills its context feeds position max_ctx - 2 and one more row a draft token, and a + * draft round rotates at positions ahead of the committed end as well: `max_spec` rows past + * `max_ctx` cover both, and the one after them keeps the bound from resting on that arithmetic + * being exact. The extra rows are (max_spec + 1) * rot floats. */ +inline int64_t rope_table_rows(const Geom& g) { + return g.max_ctx + (g.max_spec > 0 ? (int64_t)g.max_spec : 0) + 1; +} + +/* THE SMALLEST TOKEN COUNT AT WHICH A QUANTISED ACTIVATION IS ACTUALLY READ. + * + * `LinearFP8::step` takes the matvec at T <= fp8_matvec_rows(), and the matvec does not read + * `a.q` or `a.s` -- libr4d says so itself about that kernel: "the ONLY member of this family that + * does not need r4d_quant_act_fp8". Left unguarded, the quantiser in front of it runs anyway, so a + * single-sequence decode step issues 256 launches -- one per activation per layer -- to produce + * bytes nobody reads. A decode step's budget IS launches. + * + * The buffer PLAN is unaffected. Liveness comes from the declared op list, not from what a step + * issues, so `q` and `s` keep their arena slots and an op that does read them at a larger T still + * finds them where it expects. */ +inline int64_t fp8_quant_min_rows(const Geom& g) { + return fp8_matvec_rows(g) + 1; +} + +/* ================================================================== the activation quantiser */ +struct QuantFP8 { + ActFP8 a{}; + int64_t n = 0; + /* The smallest T at which some linear reads what this produces; see fp8_quant_min_rows. */ + int64_t min_rows = 1; + rad_op op = 0; + + int declare(RadBuilder* b, const Geom& g, const ActFP8& act, int64_t width); + /* `r0`/`rows` narrow it to a RANGE of rows, the same spelling every other helper here takes. + * A mixed step needs it: only the prefill rows want the standalone quantiser, because the + * recurrent path folds it into its own epilogue. */ + void step(RadCtx* c, int64_t T, int64_t r0 = 0, int64_t rows = 0) const; +}; + +inline int QuantFP8::declare(RadBuilder* b, const Geom& g, const ActFP8& act, int64_t width) { + a = act; + n = width; + /* Nothing to quantise for a bf16 model: no op, and step() issues nothing. */ + if (g.w_bf16) { op = 0; return a.x ? RAD_OK : RAD_E_INVAL; } + min_rows = fp8_quant_min_rows(g); + if (!a.x || !a.cq() || !a.cs() || n <= 0) return RAD_E_INVAL; + /* `dtype` here is the INPUT's, which is bf16 -- the output width is what the op name says. + * libr4d's row constrains it to bf16 for that reason and ref reads each operand's own dtype. + * An input the model feeds at int8 codes is quantised by quant_act_i8g into its int8 pair. */ + op = rw(b, RAD_OP(b, a.q8_fed ? "quant_act_i8g" : "quant_act_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", n), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + { a.x }, { a.cq(), a.cs() }); + return RAD_OK; +} + +inline void QuantFP8::step(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const { + if (!op) return; + if (rows <= 0) rows = T - r0; + if (rows < min_rows) return; + RAD_ISSUE(c, op, brow_slice(a.x, r0, rows, n), brow_slice(a.cq(), r0, rows, n), + brow_slice(a.cs(), r0, rows, n / RAD_FP8_BLOCK)); +} + +/* ================================== the quantiser folded into the op that PRODUCES the row + * + * QuantFP8 above is the standalone launch, and two thirds of them do not have to be. A decode + * step issues ~300 quantisers across both ranks, and each is dominated by launch cost rather than + * arithmetic: the work is 82 KiB of row. What it costs is a launch, a grid fill, and a second + * pass over a row the previous kernel had in registers -- and for ~190 of the ~300 the previous + * kernel is right there in the same block: + * + * rmsnorm -> quant the input of every attention, GDN and MLP linear + * silu_mul -> quant down_proj's input + * + * libr4d's `rmsnorm_quant_fp8` and `gated_quant_fp8` are those two producers with the quantiser on + * the same pass. They still write the bf16 output the unfused producer wrote -- the fp8a16 matvec + * reads it at one row -- and they take the codes over the BF16-ROUNDED value, so the bytes are the + * unfused pair's exactly and generated text does not move. + * + * AND THE RESIDUAL ADD FOLDS IN TOO, which is another ~130 launches. `add` is the cheapest kernel + * in the model and is almost entirely launch cost: 82 KiB of row is negligible traffic beside it. + * Every block in this architecture ends the same way -- out-projection into + * the shared `h` buffer, all-reduce, `x += h` -- and every block BEGINS with a norm of `x`. So the + * add moves from the end of one block to the front of the next, where a kernel is already reading + * both buffers, and `fold` is what says a block has a predecessor to add. + * + * The kernel rounds the sum to bf16 and STORES it before normalising, which is not what the int8 + * sibling does: that one keeps the f32 sum, which is more accurate. This one reproduces the pair + * it replaces to the byte, and byte-identical output across builds is the property this engine is + * checked against. + * + * THE FOLDED FORM HAS NO min_rows. QuantFP8 declines to run below the matvec's band + * because it would be producing bytes nobody reads; there is nothing to decline when the write is + * two stores on a pass that happens anyway. */ +/* WHETHER THE ALL-REDUCE AT `T` ROWS WILL GO OUT ON THE EXACT WIRE, which is the one question the + * fused form below turns on, and it is answered here rather than guessed because the plugin's + * `all_reduce` row answers it per call from the same three facts: an install that forbids a lossy + * wire, a message the rotation's group of 64 does not tile, or a message under the floor. Get this + * wrong in the optimistic direction and a step issues the fused kernel where the collective needed + * the compressed payload; get it wrong the other way and the pair runs, which merely costs the + * unfused launch. Both ranks evaluate it on the same T, so neither can take a different branch. + * + * The 6-bit wire pushes 2.6x fewer bytes than the exact one, and the fused kernel carries BOTH + * payloads -- so the question below decides which wire the fused op is issued with rather than + * whether it is issued at all, and `ar_fused_ok` is the separate question of whether a fused form + * exists for that answer. + * + * WHY THE FLOOR IS A FLOOR AND NOT A SWITCH: the trade is the message size, and it changes sign + * across the band. At a single sequence the message is small -- T * n_embd * 2 bytes with T on the + * order of 8 -- and the rotation's own arithmetic costs more than the bytes it saves, so the exact + * wire wins. From two concurrent sequences up the message is large enough that the compressed wire + * wins, and the margin grows monotonically with it, so there is no second crossover inside the + * band. M is C * (1 + n_spec), and 128 KiB sits between the two regimes. + */ +inline bool ar_wire_is_exact(const Geom& g, int64_t T) { + if (g.world != 2) return false; + const int64_t numel = T * g.n_embd; + if (numel <= 0) return false; + if (g.wire_exact) return true; + if (numel % 64) return true; + return numel * 2 < g.wire_min_bytes; /* bf16 on the wire */ +} + +/* WHAT THE COMPRESSED FUSED FORM NEEDS ON TOP OF THE WIRE ITSELF: the fused kernel gives a block + * whole ROWS, because a sum of squares closes only over one, and it packs the wire in chunks of + * this many elements -- so a chunk must not straddle a row, or the two ranks would disagree about + * which bytes a block owns. Stated here rather than asked of the plugin for the same reason the + * rotation's group of 64 is stated above: the architecture has to decide, at declare time and + * identically on both ranks, whether the op exists at all. */ +static const int64_t kArWire6Chunk = 512; + +/* Whether the all-reduce at `T` rows can be folded into the norm that follows it. The exact wire + * always can; the compressed one can when a chunk tiles the row. Both ranks evaluate it on the + * same T, so neither can take a different branch, and the block in FRONT asks the same question + * before deciding to skip its own collective. */ +inline bool ar_fused_ok(const Geom& g, int64_t T) { + if (g.world != 2 || T * g.n_embd <= 0) return false; + return ar_wire_is_exact(g, T) || (g.n_embd % kArWire6Chunk) == 0; +} + +/* WHICH WIRES THE CONSUMER OF A BLOCK'S ALL-REDUCE TAKES. A block is declared without knowing what + * follows it, so the architecture tells it: + * + * kArOutNorm the next block's norm, which takes either wire it has a fused form for + * (ar_fused_ok); + * kArOutExact a gated residual's write with the exact fused form only, so a message that would + * go out compressed stays with the block; + * kArOutBoth a gated residual's write with a fused form on each wire, which takes every + * message (HyperConn::ar_take). */ +enum ArOut : int { + kArOutNorm = 0, + kArOutExact = 1, + kArOutBoth = 2, +}; + +/* WHETHER A BLOCK SKIPS ITS OWN ALL-REDUCE because its consumer takes it. The consumer asks the + * same question of the same T, so the two cannot both skip it or both issue it. */ +inline bool ar_taken(const Geom& g, int64_t T, bool out, int take) { + if (!out) return false; + if (take == kArOutBoth) return true; + if (take == kArOutExact) return ar_wire_is_exact(g, T); + return ar_fused_ok(g, T); +} + +/* WHETHER A MoE BLOCK'S GATHER RIDES IN FRONT OF THE REDUCTION THAT FOLLOWS IT (ar_gather_hc_write). + * `rows` and `rows6` are the bounds the fused op was declared for on the exact and on the rotated + * wire, 0 where it was not: at most the tokens one MoE pass carries, so a step it serves is one + * pass whose gather is the whole step's. The wire the step's message goes out on picks the bound. + * The block that would issue the gather and the write that would absorb it ask this of the same T + * and the same bounds, so neither can skip it while the other issues it. */ +inline bool gather_taken(const Geom& g, int64_t T, int64_t rows, int64_t rows6) { + const int64_t r = ar_wire_is_exact(g, T) ? rows : rows6; + return r > 0 && T <= r; +} + +/* WHAT A NORM MAY ABSORB FROM THE COLLECTIVE IN FRONT OF IT. + * + * `kArAny` is every layer boundary: the predecessor reduced a PARTIAL SUM, both ranks contributed + * real values, and the compressed wire is the trade this model already makes there. + * + * `kArExact` is the EMBEDDING, and the difference is not stylistic. That collective sums DISJOINT + * rows -- one rank gathered the token and the other contributed zeros -- so the compressed wire + * takes a value that is already exactly right and degrades it, at the model's INPUT, before any + * layer runs. It also disagrees with the DRAFTER, whose own embedding reduction is exact, and a + * trunk and a drafter that see different embeddings reject each other's tokens. + * + * It is visible in the output, not just in principle: allowing the compressed wire here changes + * the greedy text, because a prompt of a few dozen tokens crosses --tp-wire-min-kb where an 8-row + * decode step does not. Exact-only keeps the decode fold -- which is the whole win -- and leaves + * prefill on the standalone collective. */ +enum ArFold : int { + kArNone = 0, + kArAny = 1, + kArExact = 2, +}; + +struct NormQuantFP8 { + ActFP8 a{}; + rad_weight w = 0; + /* What the norm is taken of. Without a fold that is the residual stream itself; with one it is + * the PREVIOUS block's delta, which this op adds into the stream first. */ + rad_buf src = 0; + rad_buf res = 0; + rad_op op = 0; + /* ...AND THE SAME OP WITH THE PRECEDING ALL-REDUCE FOLDED INTO IT. Declared only where the + * predecessor has an all-reduce whose output this norm is the sole consumer of, which is + * exactly where `residual` is non-null: `src` is then the delta buffer the collective wrote + * and nothing between the two reads it. BOTH are declared and the choice is made at step time, + * because the wire the collective picks depends on T and the fused kernel serves one of them. + * The predecessor asks the same question and skips its own all_reduce on the same answer. */ + rad_op op_arn = 0; + /* ...and the same fused op again with the ROTATED 6-BIT payload, which is the one a served + * step actually issues: the message is T * n_embd * 2 bytes and T is n_seq * (1 + n_spec), so + * it crosses --tp-wire-min-kb at the second concurrent sequence and stays across it. Declared + * separately rather than parameterised at step time because a wire is a declaration-time + * parameter of the op, and the two are chosen between exactly as `op_arn` and `op` are. */ + rad_op op_arn6 = 0; + Geom gm{}; + /* The row width, kept so a ROW SLICE can turn a row offset into an element offset. */ + int64_t n = 0; + + int declare(RadBuilder* b, const Geom& g, rad_weight gain, rad_buf x, const ActFP8& act, + int64_t n, rad_buf residual = 0, int64_t max_rows = 0, int fuse_ar = kArNone); + void step(RadCtx* c, int64_t T, int64_t r0 = 0, int64_t rows = 0) const; + /* Which of the three this step runs. The exact wire and the compressed one each have a fused + * form; without one, the pair. */ + rad_op pick(int64_t T) const { + if (op_arn && ar_wire_is_exact(gm, T)) return op_arn; + if (op_arn6 && ar_fused_ok(gm, T)) return op_arn6; + return op; + } + /* What the block in FRONT of this one asks before issuing its own collective. */ + bool takes_ar(int64_t T) const { return pick(T) != op; } +}; + +inline int NormQuantFP8::declare(RadBuilder* b, const Geom& g, rad_weight gain, rad_buf x, + const ActFP8& act, int64_t n, rad_buf residual, + int64_t max_rows, int fuse_ar) { + a = act; + w = gain; + src = x; + res = residual; + gm = g; + this->n = n; /* the parameter shadows the member; the member is the pitch */ + /* A bf16 model of this family takes every block input from its gated residual (hc_read) and + * declares no block norm; a pre-norm model served bf16 is the bf16 blocks' (rad_block_*.h), not + * these. Refused by name rather than declared as a quantiser nothing reads. */ + if (g.w_bf16) { + fprintf(stderr, "radiance: a fused norm and quantiser was declared on a model whose " + "linears are bf16; its blocks take a prepared input instead\n"); + return RAD_E_UNSUPPORTED; + } + if (!src || !a.x || !a.q || !a.s || !w || n <= 0) return RAD_E_INVAL; + op = RAD_OP(b, "rmsnorm_quant_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, max_rows > 0 ? max_rows : g.max_tok), + RAD_INT("n", n), RAD_F64("eps", g.eps), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype), + RAD_F64("wadd", g.wadd)), + RAD_WEIGHTS(w)); + if (!op) return RAD_E_INVAL; + /* Not rw()'s two initializer_lists, because the sets are conditional and a braced list in a + * ternary has no lifetime extension. `residual` is read AND written, so it is in both: the + * buffer planner reads these for liveness, and an INOUT that claimed only one of them is a + * use-after-free waiting for a plan that reorders around it. */ + rad_buf rd[2] = { src, res }; + rad_buf wr[4] = { a.q, a.s, a.x, res }; + rad_op_reads (b, op, rd, res ? 2 : 1); + rad_op_writes(b, op, wr, res ? 4 : 3); + + /* THE FUSED FORM'S EXTRA OUTPUT IS THE REDUCED MESSAGE IN `src`, and whether that is new + * liveness depends on which form this is. A FOLDED norm's `src` IS `a.x` -- the same buffer, + * already in the write set. An UNFOLDED one's `src` is the residual stream itself and is NOT, + * so it is added: the buffer planner reads these sets, and a collective writing a buffer it is + * not recorded as writing is a plan free to reorder a reader in front of it. + * + * `res` is NOT required. A fused collective mostly makes sense where the predecessor left a + * delta, but the EMBEDDING is a predecessor too, and with a vocab-sharded table its gather is + * partial and needs exactly this reduction. That case has no residual: `x` is the stream, not + * a delta to add to one. The kernel compiles the arm (r4d_fused_quant_fp8.hip dispatches + * `res ? true : false`) and the schema marks `residual` optional. */ + if (fuse_ar && g.world == 2) { + op_arn = RAD_OP(b, "ar_rmsnorm_quant_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, max_rows > 0 ? max_rows : g.max_tok), + RAD_INT("n", n), RAD_F64("eps", g.eps), + RAD_INT("group", RAD_FP8_BLOCK), + RAD_INT("world_size", g.world), + RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd)), + RAD_WEIGHTS(w)); + if (!op_arn) return RAD_E_INVAL; + rad_buf wr_ar[4] = { a.q, a.s, a.x, res ? res : src }; + rad_op_reads (b, op_arn, rd, res ? 2 : 1); + rad_op_writes(b, op_arn, wr_ar, 4); + + /* Declared only where the compressed wire can actually be reached and served: an install + * that forbids a lossy payload never picks it, and a width the wire's chunk does not tile + * would be a step-time shape refusal -- which in this engine is fatal -- rather than a + * choice not taken. */ + if (fuse_ar != kArExact && !g.wire_exact && (n % kArWire6Chunk) == 0) { + op_arn6 = RAD_OP(b, "ar_rmsnorm_quant_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, max_rows > 0 ? max_rows : g.max_tok), + RAD_INT("n", n), RAD_F64("eps", g.eps), + RAD_INT("group", RAD_FP8_BLOCK), + RAD_INT("world_size", g.world), + RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd), + RAD_INT("wire", 6)), + RAD_WEIGHTS(w)); + if (!op_arn6) return RAD_E_INVAL; + rad_op_reads (b, op_arn6, rd, res ? 2 : 1); + rad_op_writes(b, op_arn6, wr_ar, 4); + } + } + return RAD_OK; +} + +/* `r0` and `rows` are the ROW SLICE this issue covers, and they default to the whole step. At + * offset 0 `brow_slice` builds exactly the operand `brows` did -- same rows, offset zero -- so the + * unsliced path is unchanged by construction rather than by inspection. + * + * The slice is what lets a block run its rows in passes -- the routed feed-forward's, whose + * expert planes are one pass tall. Its correctness rests on the band rule in core/runtime/ctx.h: + * every slice must land in the same bucket-table band as the whole, or the op resolves to a + * different kernel with a different summation order. */ +inline void NormQuantFP8::step(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const { + if (rows <= 0) rows = T - r0; + RAD_ISSUE_N(c, pick(rows), rows, brow_slice(src, r0, rows, n), + res ? brow_slice(res, r0, rows, n) : RAD_NONE, RAD_W(w), + brow_slice(a.q, r0, rows, n), + brow_slice(a.s, r0, rows, n / RAD_FP8_BLOCK), + brow_slice(a.x, r0, rows, n)); +} + +/* `act` is the vocabulary's name for the gate and it is a NAME: "silu" is down_proj's input, + * "sigmoid" is a gated attention o_proj's. */ +struct GateQuantFP8 { + ActFP8 a{}; + rad_op op = 0; + /* WHETHER THE bf16 PRODUCT IS WRITTEN AT ALL. `out_bf16` is not an optimisation in general -- + * docs/OPS.md says a layer with a bf16 consumer of the fused value must ask for it or the + * fusion is a different function -- but a block-fp8 down_proj reads the E4M3 codes and their + * scale, and only a down_proj that reads the bf16 plane instead (LinearFP8::reads_x) reads the + * bf16 silu product. It is [T, n_ff] a layer: 18.2 GB of a 16k prefill and 71 MB of an + * 8-sequence decode step, written for one reader that is not there. Declared out of the write + * list rather than merely passed absent, so the plan says what actually happens. */ + bool want_x = true; + /* The row width. `gate_up` is 2n wide, the quantised output n; see NormQuantFP8::n. */ + int64_t n = 0; + /* `silu_mul` into the bf16 plane alone, for a model whose linears are bf16 (Geom::w_bf16). */ + bool bf16 = false; + + int declare(RadBuilder* b, const Geom& g, rad_buf gate_up, const ActFP8& act, int64_t n, + const char* act_name = "silu", int64_t max_rows = 0, bool bf16_out = true, + bool rot = false); + void step(RadCtx* c, rad_buf gate_up, int64_t T, int64_t r0 = 0, int64_t rows = 0) const; +}; + +/* `rot` PICKS A DIFFERENT OP, not a parameter on the same one: the codes are not the same codes, + * so the consumer is not free either -- only a weight stored with the matching rotation reads + * them. It exists for the routed MoE arm's down projection at four bits and nothing else, and + * `out_bf16` still receives the UNROTATED product in both cases. */ +inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up, const ActFP8& act, + int64_t n, const char* act_name, int64_t max_rows, + bool bf16_out, bool rot) { + a = act; + want_x = bf16_out; + this->n = n; + /* A bf16 model's down projection reads the product itself, so the producer is `silu_mul` and + * writes the bf16 plane alone. A rotation has no meaning without the codes it rotates. */ + bf16 = g.w_bf16; + if (bf16) { + if (!gate_up || !a.x || n <= 0 || rot || std::strcmp(act_name, "silu") != 0) { + fprintf(stderr, "radiance: a bf16 gate is silu over [gate|up] into a bf16 plane; " + "asked for '%s'%s\n", act_name, rot ? " rotated" : ""); + return RAD_E_INVAL; + } + want_x = true; + op = rw(b, RAD_OP(b, "silu_mul", + RAD_PARAMS(RAD_RANGE("M", 1, max_rows > 0 ? max_rows : g.max_tok), + RAD_INT("n", n), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + { gate_up }, { a.x }); + return op ? RAD_OK : RAD_E_INVAL; + } + if (!gate_up || !a.x || !a.cq() || !a.cs() || n <= 0) return RAD_E_INVAL; + /* The rotated codes are a four-bit expert's operand, which reads E4M3 only. */ + if (rot && a.q8_fed) return RAD_E_INVAL; + const char* opname = rot ? "gated_had_quant_fp8" : "gated_quant_fp8"; + op = want_x + ? rw(b, RAD_OP(b, opname, + RAD_PARAMS(RAD_RANGE("M", 1, max_rows > 0 ? max_rows : g.max_tok), + RAD_INT("n", n), RAD_INT("group", RAD_FP8_BLOCK), + RAD_STR("dtype", g.dtype), RAD_STR("act", act_name)), + RAD_NOWEIGHTS), + { gate_up }, { a.cq(), a.cs(), a.x }) + : rw(b, RAD_OP(b, opname, + RAD_PARAMS(RAD_RANGE("M", 1, max_rows > 0 ? max_rows : g.max_tok), + RAD_INT("n", n), RAD_INT("group", RAD_FP8_BLOCK), + RAD_STR("dtype", g.dtype), RAD_STR("act", act_name)), + RAD_NOWEIGHTS), + { gate_up }, { a.cq(), a.cs() }); + return op ? RAD_OK : RAD_E_INVAL; +} + +inline void GateQuantFP8::step(RadCtx* c, rad_buf gate_up, int64_t T, int64_t r0, + int64_t rows) const { + if (rows <= 0) rows = T - r0; + if (bf16) { + RAD_ISSUE_N(c, op, rows, brow_slice(gate_up, r0, rows, 2 * n), brow_slice(a.x, r0, rows, n)); + return; + } + RAD_ISSUE_N(c, op, rows, brow_slice(gate_up, r0, rows, 2 * n), + brow_slice(a.cq(), r0, rows, n), + brow_slice(a.cs(), r0, rows, n / RAD_FP8_BLOCK), + want_x ? brow_slice(a.x, r0, rows, n) : RAD_NONE); +} + +/* ================================================================== one block-scaled linear */ +struct LinearFP8 { + rad_weight w = 0, ws = 0; + rad_op op = 0; + int64_t N = 0, K = 0; + /* A PLAIN bf16 WEIGHT read by `gemm_nt` over the activation's bf16 plane, in a model whose + * linears are bf16 (Geom::w_bf16): one weight and no scale plane, and no quantiser in front. */ + bool bf16 = false; + /* AN INT8 WEIGHT, read by `gemm_nt_q` at dtype i8a8 against an INT8 activation: i8 codes and + * a bf16 scale per row per 128 of K (libquant `codes=i8 group=128 scale=bf16`), the activation + * i8 with an f32 scale per (row, 128) -- the E4M3 activation's grid at int8 codes, in the same + * two buffers (`a.q`, `a.s`). The weight carries a quarter of E4M3's error at the same bytes and + * the iu8 WMMA runs at the fp8 one's rate. `op_q` writes those codes from the bf16 plane + * (quant_act_i8g) when the producer in front writes E4M3; it is declared and issued before the + * GEMM. Read off the weight's encoding like `bf16`. */ + bool i8 = false; + rad_op op_q = 0; + /* What probe() read: the weight is int8. Lets a model learn its trunk's format from one linear + * before it declares the activation buffers that format decides (ActFP8::declare_qs's `i8`). */ + bool probed_i8 = false; + /* THE DECODE MATVEC, DECLARED BESIDE THE GEMM. libr4d has gemm_fp8a16_nt_m1 -- an M <= 1 + * kernel that reads the bf16 activation directly, with no quantise and no tiling -- and it is + * written for exactly the shape a single-sequence decode step issues. Declaring only fp8a8 + * leaves every decode on the TILED kernel at M = 1, which is the shape it is worst at. + * + * `dtype` is one string per declared op, so an op cannot be both: this is two ops over the + * same weights, banded so their bucket tables do not overlap, and step() picks by the token + * count. That is the same shape as the delta net's prefill/decode pair and for the same + * reason -- it is a choice between two DECLARED sequences, not a branch inside one. */ + rad_op op_m1 = 0; + /* The widest T that op_m1 serves. 0 when the matvec is declined. */ + int64_t mv_rows = 0; + /* WHETHER THIS LINEAR READS THE INPUT'S bf16 PLANE, known before its producer is declared. + * In a quantised model a producer writes the bf16 plane only when something reads it -- a + * gated quantiser writes the codes alone -- so the block asks probe() first and has the + * producer write the plane when this is set. Without that a plain weight reads arena bytes + * nothing wrote: finite nonsense on the first step, NaN once they hold one. */ + bool reads_x = false; + bool mapped = false; /* probe() made the name map; declare() does not make it again */ + + /* The name map, and from the encoding behind it whether the weight is plain bf16. `base` and + * `src` are what declare() is then given. */ + int probe(RadBuilder* b, Names& nm, const Geom& g, const char* base, + std::initializer_list src); + + /* `base` is the DECLARED name without a suffix ("blk.7.ffn_gate_up"); the logical weight is + * `.weight` and its two views are `.weight` (the codes) and `.scale`. `src` is the + * checkpoint side, one name or several to concatenate along dim 0 -- and a block-fp8 + * checkpoint's scale planes join with them, which is what makes a fusion of two fp8 linears + * expressible at all: [17408,5120]+[17408,5120] concatenates to [34816,5120] and + * [136,40]+[136,40] to [272,40], and 34816/128 is 272. A fusion whose parts are not whole + * multiples of the block would not line up, and none here are. */ + /* `span_lo`/`span_hi`, when hi is set, is this rank's uneven slice of the split dimension in + * the model's units -- rows of each row part for RAD_SHARD_ROW, columns for RAD_SHARD_COL -- + * and n_out / n_in is already its width; see rad_weight_shard_span. Whole scale blocks. */ + int declare(RadBuilder* b, Names& nm, const Geom& g, const char* base, + int64_t n_out, int64_t n_in, int shard, RadWeightGroup grp, + std::initializer_list src, + const ActFP8& a, rad_buf y, int64_t max_rows = 0, + std::initializer_list row_parts = {}, + int64_t span_lo = 0, int64_t span_hi = 0); + void step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, int64_t r0 = 0, + int64_t rows = 0) const; +}; + +/* THE NAME MAP OF A LINEAR, DECLARED BEFORE ITS WEIGHT: it is how the checkpoint -- or the recipe + * rad-convert applies -- is asked what the weight is (rad_weight_encoding), so it has to exist + * first. One source is copied; several are a convert-time fusion (gate and up into gate_up), + * concatenated along dim 0 -- and a block-fp8 checkpoint's scale planes join with them, which is + * why a fused part has to be a whole number of 128-row blocks. */ +inline int map_linear(RadBuilder* b, const char* wn, std::initializer_list src) { + if (src.size() == 1) return map_copy(b, wn, *src.begin()); + RadNameMap mw = map_base(wn, RAD_MAP_CONCAT); + int i = 0; + for (const char* q : src) { + if (i >= 8) return RAD_E_INVAL; + mw.src[i++] = q; + } + mw.n_src = i; + mw.concat_dim = 0; + return rad_decl_name_map(b, &mw); +} + +/* The int8 weight LinearFP8 serves at i8a8: i8 codes one a value, a bf16 scale per [1 x 128], no + * transform and no other plane -- what libr4d's i8 block layout hook accepts. */ +inline bool linear_is_w8(const RadEncoding& e) { + if (!rad_enc_is(&e, "affine") || e.n_planes != 2 || e.transform[0]) return false; + const RadEncPlane* sc = rad_enc_plane(&e, "scale"); + return e.plane[0].dtype == RAD_I8 && e.plane[0].block[1] == 1 && sc && sc->dtype == RAD_BF16 && + sc->block[0] == 1 && sc->block[1] == RAD_FP8_BLOCK; +} + +inline int LinearFP8::probe(RadBuilder* b, Names& nm, const Geom& g, const char* base, + std::initializer_list src) { + if (src.size() == 0) return RAD_E_INVAL; + const char* wn = nm.f("%s.weight", base); + RAD_ARCH_TRY(map_linear(b, wn, src)); + mapped = true; + RadEncoding enc{}; + const bool known = weight_enc(b, wn, &enc); + const bool plain = known && rad_enc_is(&enc, "plain") && enc.n_planes == 1 && + enc.plane[0].dtype == RAD_BF16; + probed_i8 = known && linear_is_w8(enc); + reads_x = g.w_bf16 || plain || probed_i8; + return RAD_OK; +} + +inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const char* base, + int64_t n_out, int64_t n_in, int shard, RadWeightGroup grp, + std::initializer_list src, + const ActFP8& a, rad_buf y, int64_t max_rows, + std::initializer_list row_parts, + int64_t span_lo, int64_t span_hi) { + N = n_out; + K = n_in; + if (N <= 0 || K <= 0 || src.size() == 0) return RAD_E_INVAL; + + /* THE NAME MAP FIRST: it is how the checkpoint -- or the recipe rad-convert applies -- is + * asked what the weight is, and that answer picks the branch below. */ + const char* wn = nm.f("%s.weight", base); + if (!mapped) RAD_ARCH_TRY(map_linear(b, wn, src)); + RadEncoding enc{}; + const bool known = weight_enc(b, wn, &enc); + const bool plain = known && rad_enc_is(&enc, "plain") && enc.n_planes == 1 && + enc.plane[0].dtype == RAD_BF16; + + /* ---- A bf16 WEIGHT, `gemm_nt` over `a.x`: every linear of a bf16 model, and one a quantised + * container keeps at the checkpoint's precision -- the QSA indexer's projection, whose top-k is + * a hard choice between blocks and costs 20 MB to keep exact. The row parts and an uneven + * slice apply to it as they would to the codes; there is no block to respect. */ + bf16 = g.w_bf16 || plain; + if (bf16) { + if (known && !plain) { + char en[256]; + rad_enc_format(&enc, en, sizeof en); + fprintf(stderr, "radiance: '%s' is %s, and this model's linears are plain bf16 -- a " + "bf16 container is served bf16 throughout\n", wn, en); + return RAD_E_DTYPE; + } + /* The input's bf16 plane is what a bf16 weight multiplies. A quantised model's producer + * may write only the codes -- a gated quantiser does -- and then there is nothing here to + * read; the weight has to be quantised with the rest. */ + if (!a.x) { + fprintf(stderr, "radiance: '%s' is plain bf16 and its input has no bf16 plane in this " + "model; quantise it with its neighbours\n", wn); + return RAD_E_DTYPE; + } + int64_t parts[RAD_MAX_ROW_PARTS] = {0}; + int np = 0; + for (int64_t p : row_parts) { + if (np >= RAD_MAX_ROW_PARTS) return RAD_E_INVAL; + parts[np++] = p; + } + w = decl_w_n(b, wn, RAD_BF16, { N, K }, RAD_ACCESS_PER_TOKEN, shard, grp, 0, parts, np); + if (!w) return RAD_E_INVAL; + if (span_hi > 0) RAD_ARCH_TRY(rad_weight_shard_span(b, w, span_lo, span_hi)); + op = rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, max_rows > 0 ? max_rows : g.max_tok), + RAD_INT("N", N), RAD_INT("K", K), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w)), + { a.x }, { y }); + return op ? RAD_OK : RAD_E_INVAL; + } + + /* ---- AN INT8 WEIGHT, `gemm_nt_q` at i8a8 over the input's int8 pair `a.q8` / `a.s8`. The + * scale plane is one bf16 per row per 128 of K, so it takes the weight's row parts and row + * slice as they are, and a column slice in groups of 128 -- which the per-rank K being a + * whole number of groups guarantees. The codes are the producer's own when the model feeds + * the pair (ActFP8::q8_fed); otherwise op_q writes them from `a.x`, so the producer in front + * has to write the bf16 plane (probe() set reads_x for it). Either way the model has to have + * declared the pair (ActFP8::declare_qs's `i8`). */ + i8 = known && linear_is_w8(enc); + if (i8) { + if (!a.x || !a.q8 || !a.s8) { + fprintf(stderr, "radiance: '%s' is an int8 weight, quantised from its input's bf16 " + "plane into its int8 code pair, and its input lacks one of them -- the " + "model did not learn its trunk is int8 before declaring it\n", wn); + return RAD_E_DTYPE; + } + if (N % 16 || K % RAD_FP8_BLOCK) { + fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an int8 weight takes rows in " + "16s and K in whole %d-column scale groups.\n", + base, (long long)N, (long long)K, RAD_FP8_BLOCK); + return RAD_E_INVAL; + } + int64_t parts[RAD_MAX_ROW_PARTS] = {0}; + int np = 0; + for (int64_t p : row_parts) { + if (np >= RAD_MAX_ROW_PARTS) return RAD_E_INVAL; + parts[np++] = p; + } + const char* sn = nm.f("%s.scale", base); + w = decl_view(b, wn, nullptr, "codes", RAD_I8, { N, K }, RAD_ACCESS_PER_TOKEN, shard, grp, + parts, np); + ws = decl_view(b, sn, wn, "scale", RAD_BF16, { N, K / RAD_FP8_BLOCK }, RAD_ACCESS_PER_TOKEN, + shard, grp, parts, np); + if (!w || !ws) return RAD_E_INVAL; + if (span_hi > 0) { + const bool col = shard == RAD_SHARD_COL; + if (col && (span_lo % RAD_FP8_BLOCK || span_hi % RAD_FP8_BLOCK)) { + fprintf(stderr, "radiance: '%s' is sliced [%lld, %lld) on this rank, which cuts a " + "%d-column scale group.\n", base, (long long)span_lo, + (long long)span_hi, RAD_FP8_BLOCK); + return RAD_E_INVAL; + } + RAD_ARCH_TRY(rad_weight_shard_span(b, w, span_lo, span_hi)); + RAD_ARCH_TRY(rad_weight_shard_span(b, ws, col ? span_lo / RAD_FP8_BLOCK : span_lo, + col ? span_hi / RAD_FP8_BLOCK : span_hi)); + } + const int64_t hi = max_rows > 0 ? max_rows : g.max_tok; + if (!a.q8_fed) + op_q = rw(b, RAD_OP(b, "quant_act_i8g", + RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("n", K), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { a.x }, { a.q8, a.s8 }); + op = rw(b, RAD_OP(b, "gemm_nt_q", + RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "i8a8")), + RAD_WEIGHTS(w, ws)), + { a.q8, a.s8 }, { y }); + return (op_q || a.q8_fed) && op ? RAD_OK : RAD_E_INVAL; + } + + /* An E4M3 weight reads the E4M3 pair, and an input the model feeds at int8 codes has none -- + * a container whose trunk mixes the two formats, which the model's one probe did not see. */ + if (a.q8_fed) { + fprintf(stderr, "radiance: '%s' is not an int8 weight, and its input is fed int8 codes " + "because this model's trunk is int8; quantise it with its neighbours\n", wn); + return RAD_E_DTYPE; + } + + /* The one geometric precondition, checked here so it is reported once per weight with the + * weight named rather than as a kernel miss with a band in it. These are PER-RANK extents, so + * this is also the check that a tensor-parallel width does not cut a scale block in half. */ + if (N % RAD_FP8_BLOCK || K % RAD_FP8_BLOCK) { + fprintf(stderr, "radiance: '%s' is %lldx%lld per rank, which is not a whole number of " + "%dx%d scale blocks. A block-scaled fp8 weight cannot be split inside a " + "block; use a bf16 linear here or a world_size that divides cleanly.\n", + base, (long long)N, (long long)K, RAD_FP8_BLOCK, RAD_FP8_BLOCK); + return RAD_E_INVAL; + } + + /* THE SCALE PLANE SPLITS WHERE THE WEIGHT DOES, in units of RAD_FP8_BLOCK rows. A fused + * [q|k|v] whose parts are 1024/1024/3072 rows per rank is 8/8/24 scale rows per rank, and the + * scale would otherwise be sliced contiguously while the weight it scales was not -- a + * mismatch that survives every shape check and shows up only as wrong numbers. A part that is + * not a whole number of blocks cannot be expressed either way, so it is refused by name. */ + int64_t wparts[RAD_MAX_ROW_PARTS] = {0}, sparts[RAD_MAX_ROW_PARTS] = {0}; + int np = 0; + for (int64_t p : row_parts) { + if (np >= RAD_MAX_ROW_PARTS) return RAD_E_INVAL; + if (p % RAD_FP8_BLOCK) { + fprintf(stderr, "radiance: '%s' stacks a %lld-row part, which is not a whole number " + "of %d-row scale blocks; it cannot be row-sharded.\n", + base, (long long)p, RAD_FP8_BLOCK); + return RAD_E_INVAL; + } + wparts[np] = p; + sparts[np] = p / RAD_FP8_BLOCK; + ++np; + } + + const char* sn = nm.f("%s.scale", base); + /* ONE STORED WEIGHT, TWO OPERANDS: the codes and the scale plane of `.weight`, which is + * block-fp8 in the checkpoint or made so by the recipe. A checkpoint that is not (a dense + * bf16 release) declares the same two views; what makes the planes exist is rad-convert. */ + w = decl_view(b, wn, nullptr, "codes", RAD_F8E4M3, { N, K }, + RAD_ACCESS_PER_TOKEN, shard, grp, wparts, np); + ws = decl_view(b, sn, wn, "scale", RAD_BF16, { fp8_blocks(N), fp8_blocks(K) }, + RAD_ACCESS_PER_TOKEN, shard, grp, sparts, np); + if (!w || !ws) return RAD_E_INVAL; + /* AN UNEVEN SLICE, and the scale plane takes the same slice in blocks. */ + if (span_hi > 0) { + if (span_lo % RAD_FP8_BLOCK || span_hi % RAD_FP8_BLOCK) { + fprintf(stderr, "radiance: '%s' is sliced [%lld, %lld) on this rank, which cuts a %d-" + "wide scale block.\n", base, (long long)span_lo, (long long)span_hi, + RAD_FP8_BLOCK); + return RAD_E_INVAL; + } + RAD_ARCH_TRY(rad_weight_shard_span(b, w, span_lo, span_hi)); + RAD_ARCH_TRY(rad_weight_shard_span(b, ws, span_lo / RAD_FP8_BLOCK, + span_hi / RAD_FP8_BLOCK)); + } + + /* `M` is ranged over the token count, which is what selects between libr4d's narrow (M<=16) + * and tiled instantiations. A caller with a tighter bound -- the lm_head, which runs only on + * the sampled rows -- passes it, because a band ceiling of max_tok would size the narrow + * kernel's split-K scratch for a step that cannot happen. */ + const int64_t hi = max_rows > 0 ? max_rows : g.max_tok; + /* The matvec first, up to the width its kernel serves, so a VERIFY STEP still takes it. + * fp8_matvec_rows is that width and says how it is chosen; at 0 the matvec is declined and + * every T goes to the fp8a8 GEMM below. */ + mv_rows = fp8_matvec_rows(g); + if (mv_rows > 0) + op_m1 = rw(b, RAD_OP(b, "gemm_nt_q", + RAD_PARAMS(RAD_RANGE("M", 1, mv_rows), RAD_INT("N", N), RAD_INT("K", K), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a16")), + RAD_WEIGHTS(w, ws)), + { a.x }, { y }); + op = rw(b, RAD_OP(b, "gemm_nt_q", + RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8")), + RAD_WEIGHTS(w, ws)), + { a.q, a.s }, { y }); + return RAD_OK; +} + +/* THE TWO TRAILING OPTIONAL OPERANDS ARE PASSED, as RAD_NONE. `gemm_nt_q`'s schema is seven long + * -- `a_sum` and `b_ref` sit after `y` for the asymmetric integer and mxfp4 grids -- and operands + * are POSITIONAL, so the runtime takes an operand count that disagrees with the schema as a miscount + * rather than as an omission (core/runtime/issue.cpp). An absent optional operand is a null tensor + * in the list, not a shorter list; an fp8 grid is symmetric and needs neither. */ +inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, int64_t r0, + int64_t rows) const { + if (rows <= 0) rows = T - r0; + if (bf16) { + RAD_ISSUE_N(c, op, rows, brow_slice(a.x, r0, rows, K), RAD_W(w), brow_slice(y, r0, rows, N)); + return; + } + if (i8) { + if (op_q) + RAD_ISSUE_N(c, op_q, rows, brow_slice(a.x, r0, rows, K), brow_slice(a.q8, r0, rows, K), + brow_slice(a.s8, r0, rows, K / RAD_FP8_BLOCK)); + RAD_ISSUE_N(c, op, rows, brow_slice(a.q8, r0, rows, K), + brow_slice(a.s8, r0, rows, K / RAD_FP8_BLOCK), + RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE); + return; + } + if (op_m1 && rows <= mv_rows) + RAD_ISSUE_N(c, op_m1, rows, brow_slice(a.x, r0, rows, K), RAD_NONE, + RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE); + else + RAD_ISSUE_N(c, op, rows, brow_slice(a.q, r0, rows, K), + brow_slice(a.s, r0, rows, K / RAD_FP8_BLOCK), + RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE); +} + + +/* ================================================== an fp8 weight with no op of its own + * + * LinearFP8's two views without the GEMM: a weight a block declares here and reads through an op + * of its own -- the DFlash2 and DSpark drafters' projections, which ship bf16 and are made block + * fp8 by the recipe, since they are read whole on every decode step and only have to be good + * enough to PROPOSE (every draft is verified against the trunk exactly). + * + * BOTH VIEWS ARE DECLARED AT WHAT THEY SELECT -- [N][K] E4M3 codes, [N/128][K/128] BF16 scales -- + * because that is the shape the runtime hands a kernel, and libr4d checks the scale plane's + * extents against ceil(N/128) x ceil(K/128) before it will run. The row parts follow it: the + * weight's are rows and the plane's are BLOCKS of 128 rows, the same division LinearFP8 makes. A + * part that is not a whole number of blocks cannot be sharded and is refused by name. + */ +struct DenseFP8 { + rad_weight w = 0, s = 0; + + int declare(RadBuilder* b, Names& nm, const char* base, int64_t N, int64_t K, + int access, int shard, RadWeightGroup grp, + std::initializer_list src, + std::initializer_list row_parts = {}); +}; + +inline int DenseFP8::declare(RadBuilder* b, Names& nm, const char* base, int64_t N, int64_t K, + int access, int shard, RadWeightGroup grp, + std::initializer_list src, + std::initializer_list row_parts) { + if (N <= 0 || K <= 0 || src.size() == 0) return RAD_E_INVAL; + if (N % RAD_FP8_BLOCK || K % RAD_FP8_BLOCK) { + fprintf(stderr, "radiance: '%s' is %lldx%lld per rank, which is not a whole number of " + "%dx%d scale blocks. A block-scaled fp8 weight cannot be split inside a " + "block; use a bf16 linear here or a world_size that divides cleanly.\n", + base, (long long)N, (long long)K, RAD_FP8_BLOCK, RAD_FP8_BLOCK); + return RAD_E_INVAL; + } + + int64_t wp[RAD_MAX_ROW_PARTS] = {0}, sp[RAD_MAX_ROW_PARTS] = {0}; + int np = 0; + for (int64_t p : row_parts) { + if (np >= RAD_MAX_ROW_PARTS) return RAD_E_INVAL; + if (p % RAD_FP8_BLOCK) { + fprintf(stderr, "radiance: '%s' stacks a %lld-row part, which is not a whole number " + "of %d-row scale blocks; it cannot be row-sharded.\n", + base, (long long)p, RAD_FP8_BLOCK); + return RAD_E_INVAL; + } + wp[np] = p; + sp[np] = p / RAD_FP8_BLOCK; + ++np; + } + + const char* wn = nm.f("%s.weight", base); + const char* sn = nm.f("%s.scale", base); + RAD_ARCH_TRY(map_linear(b, wn, src)); + w = decl_view(b, wn, nullptr, "codes", RAD_F8E4M3, { N, K }, access, shard, grp, wp, np); + s = decl_view(b, sn, wn, "scale", RAD_BF16, { fp8_blocks(N), fp8_blocks(K) }, access, shard, + grp, sp, np); + return w && s ? RAD_OK : RAD_E_INVAL; +} + +} /* namespace arch */ +} /* namespace rad */ + +#endif /* RAD_FP8_H */ diff --git a/arch/common/rad_qsa.h b/arch/common/rad_qsa.h new file mode 100644 index 00000000..0b3621e1 --- /dev/null +++ b/arch/common/rad_qsa.h @@ -0,0 +1,456 @@ +/* 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 hnc(1), hns(1), hsu(1), hsel(8); + std::vector 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 */ diff --git a/arch/llama_dense_fp8/CMakeLists.txt b/arch/llama_dense_fp8/CMakeLists.txt new file mode 100644 index 00000000..66db636d --- /dev/null +++ b/arch/llama_dense_fp8/CMakeLists.txt @@ -0,0 +1,11 @@ +# A plugin like any other: built here inside radiance's tree, or on its own against an installed +# radiance (`cmake -S arch/llama_dense_fp8 -B build -DCMAKE_PREFIX_PATH=`) -- the same +# rad_add_plugin either way (cmake/RadAddPlugin.cmake). +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(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) diff --git a/arch/llama_dense_fp8/llama_dense_fp8.cpp b/arch/llama_dense_fp8/llama_dense_fp8.cpp new file mode 100644 index 00000000..5d92c22b --- /dev/null +++ b/arch/llama_dense_fp8/llama_dense_fp8.cpp @@ -0,0 +1,19 @@ +/* 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" diff --git a/arch/llama_fp8/CMakeLists.txt b/arch/llama_fp8/CMakeLists.txt new file mode 100644 index 00000000..e11e277a --- /dev/null +++ b/arch/llama_fp8/CMakeLists.txt @@ -0,0 +1,11 @@ +# A plugin like any other: built here inside radiance's tree, or on its own against an installed +# radiance (`cmake -S arch/llama_fp8 -B build -DCMAKE_PREFIX_PATH=`) -- the same +# rad_add_plugin either way (cmake/RadAddPlugin.cmake). +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(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) diff --git a/arch/llama_fp8/llama_fp8.cpp b/arch/llama_fp8/llama_fp8.cpp new file mode 100644 index 00000000..342cdefe --- /dev/null +++ b/arch/llama_fp8/llama_fp8.cpp @@ -0,0 +1,759 @@ +/* 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 +#include +#include + +#include +#include +#include +#include + +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 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 + ` 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 diff --git a/arch/qwen35_bf16/CMakeLists.txt b/arch/qwen35_bf16/CMakeLists.txt new file mode 100644 index 00000000..5d9aeb99 --- /dev/null +++ b/arch/qwen35_bf16/CMakeLists.txt @@ -0,0 +1,11 @@ +# A plugin like any other: built here inside radiance's tree, or on its own against an installed +# radiance (`cmake -S arch/qwen35_bf16 -B build -DCMAKE_PREFIX_PATH=`) -- the same +# rad_add_plugin either way (cmake/RadAddPlugin.cmake). +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(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) diff --git a/arch/qwen35_bf16/qwen35_bf16.cpp b/arch/qwen35_bf16/qwen35_bf16.cpp new file mode 100644 index 00000000..8315c4b2 --- /dev/null +++ b/arch/qwen35_bf16/qwen35_bf16.cpp @@ -0,0 +1,576 @@ +/* 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 +#include +#include +#include +#include + +#include + +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 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 diff --git a/arch/qwen35_fp8/CMakeLists.txt b/arch/qwen35_fp8/CMakeLists.txt new file mode 100644 index 00000000..71142b36 --- /dev/null +++ b/arch/qwen35_fp8/CMakeLists.txt @@ -0,0 +1,11 @@ +# A plugin like any other: built here inside radiance's tree, or on its own against an installed +# radiance (`cmake -S arch/qwen35_fp8 -B build -DCMAKE_PREFIX_PATH=`) -- the same +# rad_add_plugin either way (cmake/RadAddPlugin.cmake). +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(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) diff --git a/arch/qwen35_fp8/qwen35_fp8.cpp b/arch/qwen35_fp8/qwen35_fp8.cpp new file mode 100644 index 00000000..31a3bf7e --- /dev/null +++ b/arch/qwen35_fp8/qwen35_fp8.cpp @@ -0,0 +1,1452 @@ +/* qwen35_fp8 -- Qwen3.5 / 3.6 / 3.8 dense, BLOCK-SCALED FP8 weights and FP8 activations. + * + * The sibling of qwen35_bf16 and the one that serves the production checkpoint. Same architecture, + * same graph, same metadata, same name maps for everything that is not a projection matrix -- so + * the architecture prose lives in qwen35_bf16.cpp and in the three block headers, and this file + * says only what makes it a different plugin. One plugin implements one architecture id for one + * quantisation scheme (spec §2.4), and this is the second scheme. + * + * ============================== WHAT IT SERVES ============================== + * + * A checkpoint whose config.json carries + * + * "quantization_config": { "quant_method": "fp8", "fmt": "e4m3", + * "activation_scheme": "dynamic", + * "weight_block_size": [128, 128] } + * + * which is Qwen3.8-27B-FP8, Qwen3.6-27B-FP8 and every other DeepSeek-style fp8 release of this + * family. Each large linear ships as `.weight` in F8_E4M3 [N][K] beside + * `.weight_scale_inv` in BF16 [ceil(N/128)][ceil(K/128)] -- the codes and the scale plane + * of one weight, `fp8_e4m3*bf16[128x128]`, which libr4d's three block-scaled fp8 GEMMs read as + * they are, so the checkpoint loads directly and a .rad of it costs what the checkpoint does. + * + * qwen35_bf16's header argues for widening to bf16 instead, and that argument holds only where + * libr4d's registry exposes no fp8-weight GEMM. It does expose them (libr4d/r4d_fp8.cpp), so the + * widening is not the cheaper path here: it doubles 24 GiB of weights to 48 GiB to buy nothing. + * + * ============================== WHAT IS AND IS NOT FP8 ============================== + * + * Read off `layers-0.safetensors` and `layers-3.safetensors` rather than assumed, because the + * pattern is not "the big ones": + * + * F8_E4M3 + scale self_attn.{q,k,v,o}_proj, mlp.{gate,up,down}_proj, + * linear_attn.{in_proj_qkv, in_proj_z, out_proj} + * BF16, no scale every norm, A_log, dt_bias, conv1d, embed_tokens, lm_head, AND + * linear_attn.in_proj_a / in_proj_b + * + * in_proj_a and in_proj_b emit one column per value head -- 48 of them -- and 48 is not a whole + * 128-row scale block, so the quantiser that made the checkpoint left them alone. That is why + * GdnFP8 splits the in-projection the bf16 block fuses; rad_block_gdn_fp8.h has the detail. + * + * The lm_head being bf16 in the checkpoint is worth stating too. It is declared at whatever the + * model holds it as -- bf16 loaded directly, block fp8 where a recipe quantised it -- and the + * logits kernel that reads that encoding is the one selected. + */ +/* ============================== ONE SOURCE, TWO PLUGINS ============================== + * + * `qwen35moe` is this architecture with the feed-forward ROUTED and everything above it identical: + * the same gated attention, the same gated delta net, the same layer schedule, the same rope, the + * same vocabulary edges, the same MTP head in the same position. Qwen3.6-35B-A3B-FP8 is the model, + * and reading its config beside Qwen3.8-27B-FP8's the only structural difference is `mlp.experts.*` + * plus a router and a shared expert where `mlp.{gate,up,down}_proj` was. + * + * So there is ONE source and two translation units, exactly as libr4d's attention dispatches are + * one set of kernel templates instantiated at three geometries. arch/qwen35moe_fp8/ is four lines + * that define the three macros below and include this file. The alternative is a second 1300-line + * plugin kept in step by hand, and two hand-kept copies of one thing drift apart -- the reason + * libr4d/r4d_rows.cpp keeps exactly one table of its kernels. + * + * EVERY DIFFERENCE IS BEHIND `#if QWEN35_MOE` AND THERE ARE SIX OF THEM: the expert-count check, + * the routing geometry read out of metadata, the block's buffers, the per-layer source names, the + * MTP head's feed-forward, and the plugin's own identity. Nothing else in this file knows. */ +#ifndef QWEN35_MOE +#define QWEN35_MOE 0 +#endif +#ifndef QWEN35_NS +#define QWEN35_NS qwen35_fp8 +#endif +#ifndef QWEN35_ARCH_ID +#define QWEN35_ARCH_ID "qwen35" +#endif + +#include +#include +#include +#include +#include +#if QWEN35_MOE +#include +#endif +#include +#include +#include + +#include +#include + +namespace QWEN35_NS { + +using namespace rad::arch; + +/* The feed-forward this build declares, and the ONE name the rest of the file uses for it. Both + * blocks take the same declare() arity over their own Wire and Src -- the routed one carries its + * geometry inside its Src for exactly that reason -- so every site below is spelled once. */ +#if QWEN35_MOE +using Ffn = MoeFP8; +using MtpHead = MtpBlockFP8; +#else +using Ffn = MlpFP8; +using MtpHead = MtpFP8; +#endif + +struct Layer { + int full = 0; + AttnGatedFP8 attn; + GdnFP8 gdn; + Ffn mlp; +}; + +struct Model { + Names nm{""}; + Geom g{}; + GdnFP8::Config gcfg{}; + int64_t n_rot = 0; + int64_t n_main = 0; + + 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_hout = 0, b_logits = 0; + ActFP8 a_h{}; + /* full attention */ + rad_buf b_qg = 0, b_k = 0, b_v = 0, b_q = 0; + /* [rope_table_rows, n_rot] f32, the rope cos/sin every attention layer reads. One buffer and + * one fill a step, against a rope launch a layer -- see rad_block_attn_gated_fp8.h at + * op_fused. */ + rad_buf b_rope_cs = 0; + ActFP8 a_attn{}; + /* gated delta net */ + ActFP8 a_in{}, a_go{}; + rad_buf b_ab = 0, b_gq = 0, b_gk = 0, b_gv = 0; + rad_buf b_gdec = 0, b_beta = 0, b_kkt = 0; + /* feed-forward */ + rad_buf b_gate_up = 0; + ActFP8 a_ffn{}; +#if QWEN35_MOE + /* ...and the routed one's, which are the expert path's intermediates. They are `moe_rows` + * tokens tall and not max_tok, because the expert planes are top_k times as tall as the step; + * rad_block_moe_fp8.h argues the slicing. */ + MoeFP8::Config moecfg{}; + rad_buf b_rlogits = 0, b_eids = 0, b_ew = 0, b_sorted = 0, b_eoff = 0, b_ecnt = 0; + rad_buf b_egu = 0, b_edn = 0, b_emoe = 0; + ActFP8 a_eff{}; + rad_buf b_sgu = 0, b_sout = 0, b_sgate = 0; + ActFP8 a_sff{}; +#endif + + /* THE DFLASH2 DRAFTER, declared only when the container carries one and the deployment + * speculates. It is the second drafter and it is not an alternative spelling of the first: an + * MTP head is one chained forward per draft token, this is one forward for the whole block. + * Both can be in a container; only one is declared, and DFlash2 wins because it is the better + * drafter on this target. */ + bool have_df = false; + Dflash2 df{}; + Dflash2::Wire dfw{}; + rad_kvgroup kv_draft = 0; + + /* the multi-token-prediction head, declared only when the deployment speculates */ + bool have_mtp = false; + MtpHead mtp{}; + rad_buf b_mtp_e = 0, b_mtp_c = 0, b_mtp_x = 0, b_mtp_h = 0; + rad_buf b_mtp_dq = 0, b_mtp_ds = 0, b_mtp_dsum = 0; + rad_buf b_mtp_dlog = 0, b_mtp_didx = 0, b_mtp_dval = 0; + + /* THE AUXILIARY HIDDEN-STATE TAPS, declared only when the container carries a drafter that + * asks for them. A DFlash2 drafter does not read the trunk's FINAL hidden state -- it reads + * the residual stream at several intermediate layers and projects the concatenation down, so + * `fc` is [n_embd, n_taps * n_embd] and its input has to be one contiguous row. The trunk + * keeps one residual buffer that every layer overwrites, so the rows have to be copied out as + * they pass, into the column slice that layer owns. Nothing else in the trunk changes, and on + * a container with no drafter none of this is declared. */ + 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; + + 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; + rad_op op_rope_cs = 0; /* rope_table, if the fused prologue is reachable */ + + /* ---- 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 layers; +}; + +/* "5 19 33 47 61" -> the layers whose output a drafter wants. rad-convert flattens a config.json + * array into a space-separated string (tools/rad_convert.cpp, flatten_json), so this is the shape + * every list-valued key arrives in. Out-of-range entries are dropped rather than clamped: a + * drafter that names a layer this model does not have is paired with the wrong target, and + * silently reading layer 63 instead of 71 would make that a quality mystery. */ +static int parse_tap_layers(const char* s, int64_t n_layer, int* out, int max) { + if (!s) return 0; + int n = 0; + for (const char* p = s; *p && n < max;) { + while (*p == ' ' || *p == ',') ++p; + if (!*p) break; + char* e = nullptr; + const long v = std::strtol(p, &e, 10); + if (e == p) break; + p = e; + if (v >= 0 && v < n_layer) out[n++] = (int)v; + } + return n; +} + +static Model g_model[MAX_RANKS]; + +static inline bool is_full_attention(int64_t l, int64_t interval) { + return interval > 0 && ((l + 1) % interval == 0); +} + +/* THE CONTAINER'S OWN LAYER SCHEDULE, CHECKED AGAINST THE ONE WE COMPUTE. + * + * `is_full_attention` derives the schedule from one integer: every `interval`-th layer is full + * attention and the rest are linear. That is llama.cpp's rule and it is right for this model. It + * is NOT a property of the family -- HuggingFace states the schedule explicitly, as a + * `layer_types` array of "linear_attention" / "full_attention", and rad-convert carries that array + * into the container as a space-separated string, which is what this function reads. + * + * A model whose array does not match the modular rule would be built with the WRONG LAYERS LINEAR. + * It would convert, load, and generate fluent text from a different architecture than the one on + * disk -- the exact silent-wrong-model failure this plugin's check_format exists to prevent one + * layer down. So: where the container states the schedule, it is authoritative and disagreement + * is fatal. + * + * A container that states nothing is accepted, for check_format's reason -- a .rad converted from + * a GGUF carries no HuggingFace config, and the modular rule is then the only evidence there is. + * `text_config.` is where it lands for a checkpoint whose config nests the language model. */ +static int check_layer_schedule(const RadModelMeta* meta, int64_t n_layer, int64_t interval) { + const char* s = rad_meta_gets(meta, "qwen35.layer_types", nullptr); + if (!s) s = rad_meta_gets(meta, "text_config.layer_types", nullptr); + if (!s) s = rad_meta_gets(meta, "layer_types", nullptr); + if (!s || !*s) return RAD_OK; + + int64_t l = 0; + for (const char* p = s; *p; ) { + while (*p == ' ') ++p; + if (!*p) break; + const char* tok = p; + while (*p && *p != ' ') ++p; + const size_t len = (size_t)(p - tok); + + const bool says_full = len == 14 && std::strncmp(tok, "full_attention", 14) == 0; + const bool says_lin = len == 16 && std::strncmp(tok, "linear_attention", 16) == 0; + if (!says_full && !says_lin) { + fprintf(stderr, "radiance: qwen35: layer_types[%lld] is '%.*s'; this plugin knows " + "'full_attention' and 'linear_attention' and will not guess at a " + "third kind of layer.\n", (long long)l, (int)len, tok); + return RAD_E_UNSUPPORTED; + } + /* Past the trunk is the MTP block, which the array may or may not include; it is not a + * trunk layer and its kind is the drafter's business (see declare_draft). */ + if (l >= n_layer) break; + if (says_full != is_full_attention(l, interval)) { + fprintf(stderr, "radiance: qwen35: the container says layer %lld is %s, and " + "full_attention_interval %lld makes it %s. The interval rule is " + "llama.cpp's and it is not a property of this family -- a model whose " + "layer_types differ from it would be built with the wrong layers " + "linear, and would load and generate fluent text from an architecture " + "that is not the one in the checkpoint. Read layer_types directly " + "before serving this model.\n", + (long long)l, says_full ? "full_attention" : "linear_attention", + (long long)interval, + is_full_attention(l, interval) ? "full_attention" : "linear_attention"); + return RAD_E_UNSUPPORTED; + } + ++l; + } + if (l && l < n_layer) { + fprintf(stderr, "radiance: qwen35: layer_types names %lld layers and the model has %lld. " + "A short schedule is not a schedule.\n", (long long)l, (long long)n_layer); + return RAD_E_UNSUPPORTED; + } + return RAD_OK; +} + +/* The container's own statement about its format. Checked rather than assumed, because every + * failure mode of getting it wrong is silent: a `weight_block_size` of [64,64] against kernels that + * shift by 7 reads the right bytes with the wrong gain, and an e5m2 checkpoint decodes as e4m3 into + * numbers that are merely implausible. A container that says nothing at all is accepted -- a .rad + * converted from a GGUF carries no HuggingFace quantization_config -- because the weight shapes and + * the scale planes are then the only evidence and they are checked where they are read. */ +static int check_format(const RadModelMeta* meta) { + const char* method = rad_meta_gets(meta, "quantization_config.quant_method", nullptr); + const char* fmt = rad_meta_gets(meta, "quantization_config.fmt", nullptr); + const char* block = rad_meta_gets(meta, "quantization_config.weight_block_size", nullptr); + + if (method && std::strcmp(method, "fp8") != 0) { + fprintf(stderr, "radiance: qwen35_fp8 refuses a container quantised by '%s'. This plugin " + "serves block-scaled fp8 only; qwen35_bf16 serves an unquantised one.\n", + method); + return RAD_E_UNSUPPORTED; + } + if (fmt && std::strcmp(fmt, "e4m3") != 0) { + fprintf(stderr, "radiance: qwen35_fp8 refuses fp8 format '%s'. libr4d's block-scaled GEMMs " + "decode E4M3 and nothing else; an e5m2 weight read as e4m3 is a different " + "number at every element.\n", fmt); + return RAD_E_UNSUPPORTED; + } + if (block) { + long long b0 = 0, b1 = 0; + if (std::sscanf(block, "%lld %lld", &b0, &b1) != 2) { b0 = 0; b1 = 0; } + if (b0 != RAD_FP8_BLOCK || b1 != RAD_FP8_BLOCK) { + fprintf(stderr, "radiance: qwen35_fp8 refuses weight_block_size [%lld, %lld]. The " + "block is %d in both dimensions and is compiled into libr4d as a " + "shift, so another width reads the right bytes with the wrong gain.\n", + b0, b1, RAD_FP8_BLOCK); + return RAD_E_UNSUPPORTED; + } + } + return RAD_OK; +} + +/* THE DFLASH2 DRAFTER: its geometry, its KV group, its buffers and its block. + * + * Split out of declare() because it is A SECOND MODEL and not a head. It has its own layer count, + * head count, feed-forward width, rope base, norm convention and vocabulary claim, none of which + * the trunk's Geom can carry -- so it starts from a COPY of the trunk's (n_embd, the deployment + * bounds, the rank and the wire) and overwrites everything the drafter's own config states. + * + * Nothing here is defaulted quietly. A container whose `draft.` config does not describe a + * drafter, or describes one this engine does not implement, is refused by name: a drafter that + * silently ignored a scale factor would simply accept less, which reads as a quality mystery and + * not as a missing feature (spec §17). */ +static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx, + Model& m, int base_layer) { + Names& nm = m.nm; + Geom dg = m.g; /* n_embd, the vocabulary, the deployment bounds, the rank, the wire */ + + dg.n_layer = rad_meta_geti(meta, "draft.num_hidden_layers", 0); + dg.head_dim = rad_meta_geti(meta, "draft.head_dim", 0); + dg.n_head_all = rad_meta_geti(meta, "draft.num_attention_heads", 0); + dg.n_head_kv_all = rad_meta_geti(meta, "draft.num_key_value_heads", 0); + dg.n_ff_all = rad_meta_geti(meta, "draft.intermediate_size", 0); + dg.eps = (float)rad_meta_getf(meta, "draft.rms_norm_eps", 0.0); + dg.theta = (float)rad_meta_getf(meta, "draft.rope_parameters.rope_theta", + rad_meta_getf(meta, "draft.rope_theta", 0.0)); + dg.rope_scale = 1.0f; + /* PLAIN RMS NORM. The drafter uses the ordinary norm where the trunk uses GemmaRMSNorm, and + * the checkpoint agrees rather than only vLLM -- rad_block_dflash2.h has the numbers. Two + * conventions in one process, which is exactly why this is a second Geom and not a flag. */ + dg.wadd = 0.0f; + dg.wadd_qk = 0.0f; + + if (dg.n_layer <= 0 || dg.head_dim <= 0 || dg.n_head_all <= 0 || dg.n_head_kv_all <= 0 || + dg.n_ff_all <= 0 || !(dg.eps > 0.0f) || !(dg.theta > 0.0f)) { + fprintf(stderr, "radiance: the container's `draft.` config does not describe a DFlash2 " + "drafter: layers %lld, heads %lld / kv %lld, head_dim %lld, ffn %lld, " + "rms_eps %g, rope_theta %g\n", + (long long)dg.n_layer, (long long)dg.n_head_all, (long long)dg.n_head_kv_all, + (long long)dg.head_dim, (long long)dg.n_ff_all, (double)dg.eps, (double)dg.theta); + return RAD_E_INVAL; + } + int s; + if ((s = divide_or_fail(dg.n_head_all, dg.world, "draft num_attention_heads", &dg.n_head)) < 0) return s; + if ((s = divide_or_fail(dg.n_head_kv_all, dg.world, "draft num_key_value_heads", &dg.n_head_kv)) < 0) return s; + if ((s = divide_or_fail(dg.n_ff_all, dg.world, "draft intermediate_size", &dg.n_ff)) < 0) return s; + + /* THE DRAFTER BORROWS THE TARGET'S EMBEDDING TABLE AND lm_head -- it ships neither -- so a + * vocabulary that disagrees is not a drafter for this target at all. */ + const long long dvocab = rad_meta_geti(meta, "draft.vocab_size", dg.n_vocab_all); + if (dvocab != dg.n_vocab_all) { + fprintf(stderr, "radiance: the DFlash2 drafter claims a %lld-token vocabulary and the " + "target has %lld. The drafter ships no embedding table and no lm_head; it " + "reads the target's, so the two have to be the same vocabulary.\n", + dvocab, (long long)dg.n_vocab_all); + return RAD_E_UNSUPPORTED; + } + + Dflash2::Config dc{}; + dc.n_taps = m.n_taps; + dc.block = ctx->max_spec + 1; + dc.taps = rad_meta_geti(meta, "draft.dflash_config.conv_kernel_size", 2); + dc.group = rad_meta_geti(meta, "draft.dflash_config.conv_group_size", 16); + dc.sel_rank = rad_meta_geti(meta, "draft.dflash_config.selector_rank", 0); + dc.sel_topk = rad_meta_geti(meta, "draft.dflash_config.selector_top_k", 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.dflash_config.swa_window_size", + rad_meta_geti(meta, "draft.sliding_window", 0)); + if (dc.sel_rank <= 0 || dc.sel_topk <= 0) { + fprintf(stderr, "radiance: the DFlash2 drafter states no selector geometry " + "(rank %lld, top_k %lld). Without it the block of drafts has no path " + "through it.\n", (long long)dc.sel_rank, (long long)dc.sel_topk); + return RAD_E_INVAL; + } + + /* THE QUERY BLOCK MUST BE A POWER OF TWO, and this is where that is said. The convolution + * masks a row's position within the block with `block_size - 1`, so any other value silently + * convolves one sequence's block into the next -- the shim rejects it, but by then the + * deployment has loaded four gigabytes of drafter to be told no. */ + const long long trained = rad_meta_geti(meta, "draft.dflash_config.block_size", 0); + if (dc.block < 2 || (dc.block & (dc.block - 1))) { + fprintf(stderr, "radiance: DFlash2's convolution masks the block position with " + "block_size - 1, so the query block has to be a power of two. This serve " + "asks for %d draft tokens, which makes it %lld; the checkpoint was trained " + "at %lld (%lld draft tokens).\n", + ctx->max_spec, (long long)dc.block, trained, trained - 1); + return RAD_E_UNSUPPORTED; + } + if (trained > 0 && trained != dc.block) + rad_note(b, "DFlash2 was trained at block_size %lld (%lld draft tokens) and this serve " + "asks for %lld. A block-diffusion drafter denoises a fixed number of mask " + "positions and was trained for one block length; it will run, and it will " + "accept less than the checkpoint can do", + trained, trained - 1, (long long)dc.block); + + /* Three scalars this drafter's family can carry that this implementation does not apply. + * Each of them changes what the drafter proposes, and each would show up as acceptance that + * is merely disappointing rather than as anything that looks like a bug. */ + const double escale = rad_meta_getf(meta, "draft.dflash_config.input_embedding_scale", 1.0); + const double omul = rad_meta_getf(meta, "draft.dflash_config.output_multiplier", 1.0); + const double scap = rad_meta_getf(meta, "draft.dflash_config.final_logit_softcapping", 0.0); + if (escale != 1.0 || omul != 1.0 || scap != 0.0) { + fprintf(stderr, "radiance: this DFlash2 checkpoint scales its input embedding by %g and " + "its draft logits by %g, and soft-caps them at %g. None of the three is " + "implemented, and a drafter that ignored them would just accept less.\n", + escale, omul, scap); + return RAD_E_UNSUPPORTED; + } + + /* THE DRAFTER'S OWN KV CACHE, a group of its own. It cannot share the trunk's: different head + * count, different head_dim, five layers against sixteen, and -- the one that matters -- a + * WINDOW. RAD_KV_WINDOW recycles the blocks that fall below it, so this cache is sized by the + * drafter's 2048-token window and not by the model's context length. Its width is the trunk's, + * --kv-cache-dtype: one flag says what every attention cache of the deployment is made of. */ + RadKVGroupDecl dd{}; + dd.kind = dc.window > 0 ? RAD_KV_WINDOW : RAD_KV_FULL; + dd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16); + dd.window = dc.window; + dd.n_head_kv = dg.n_head_kv; + dd.head_dim = dg.head_dim; + m.kv_draft = rad_decl_kv_group(b, nm.f("kv_draft"), &dd); + for (int64_t l = 0; l < dg.n_layer; ++l) + RAD_ARCH_TRY(rad_bind_layer_kv(b, base_layer + (int)l, m.kv_draft)); + dg.kv_dtype = rad_dtype_name(dd.dtype); + + /* 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; + + Dflash2::Wire& dw = m.dfw; + dw.src = m.b_dfsrc; + dw.c = decl_b(b, nm.f("df_c"), dg.act_dtype, {dg.max_tok, dg.n_embd}); + dw.ck = decl_b(b, nm.f("df_ck"), dg.act_dtype, {dg.max_tok, kvd}); + dw.cv = decl_b(b, nm.f("df_cv"), dg.act_dtype, {dg.max_tok, kvd}); + dw.x = decl_b(b, nm.f("df_x"), dg.act_dtype, {qr, dg.n_embd}); + dw.h = decl_b(b, nm.f("df_h"), dg.act_dtype, {qr, dg.n_embd}); + dw.h2 = decl_b(b, nm.f("df_h2"), dg.act_dtype, {qr, dg.n_embd}); + dw.coef = decl_b(b, nm.f("df_coef"), dg.act_dtype, {qr, dc.coef_dim(dg.n_embd)}); + dw.q = decl_b(b, nm.f("df_q"), dg.act_dtype, {qr, qd}); + dw.k = decl_b(b, nm.f("df_k"), dg.act_dtype, {qr, kvd}); + dw.v = decl_b(b, nm.f("df_v"), dg.act_dtype, {qr, kvd}); + dw.attn = decl_b(b, nm.f("df_attn"), dg.act_dtype, {qr, qd}); + dw.gate_up = decl_b(b, nm.f("df_gate_up"), dg.act_dtype, {qr, 2 * dg.n_ff}); + dw.ffn = decl_b(b, nm.f("df_ffn"), dg.act_dtype, {qr, dg.n_ff}); + /* THE FP8 TWINS. The drafter's six linears are block-scaled fp8 over a bf16 checkpoint + * (rad_fp8.h's DenseFP8), so every activation that feeds one carries an E4M3 copy and a plane + * of f32 scales beside it. `srcq` is the largest of them by a distance -- 50 MiB at a + * 2048-token chunk and five taps, against the 100 MiB `dflash_src` it shadows -- and it buys + * half the bytes of the one GEMM the context pass spends its time in. */ + dw.srcq = decl_b(b, nm.f("df_srcq"), RAD_F8E4M3, + {dg.max_tok, dc.n_taps * dg.n_embd}); + dw.srcs = decl_b(b, nm.f("df_srcs"), RAD_F32, + {dg.max_tok, fp8_blocks(dc.n_taps * dg.n_embd)}); + dw.cq = decl_b(b, nm.f("df_cq"), RAD_F8E4M3, {dg.max_tok, dg.n_embd}); + dw.cs = decl_b(b, nm.f("df_cs"), RAD_F32, {dg.max_tok, fp8_blocks(dg.n_embd)}); + dw.h2q = decl_b(b, nm.f("df_h2q"), RAD_F8E4M3, {qr, dg.n_embd}); + dw.h2s = decl_b(b, nm.f("df_h2s"), RAD_F32, {qr, fp8_blocks(dg.n_embd)}); + dw.atq = decl_b(b, nm.f("df_atq"), RAD_F8E4M3, {qr, qd}); + dw.ats = decl_b(b, nm.f("df_ats"), RAD_F32, {qr, fp8_blocks(qd)}); + dw.ffq = decl_b(b, nm.f("df_ffq"), RAD_F8E4M3, {qr, dg.n_ff}); + dw.ffs = decl_b(b, nm.f("df_ffs"), RAD_F32, {qr, fp8_blocks(dg.n_ff)}); + dw.sel_h = decl_b(b, nm.f("df_selh"), dg.act_dtype, {sr, dg.n_embd}); + dw.hp = decl_b(b, nm.f("df_hp"), dg.act_dtype, {sr, dc.sel_rank}); + dw.dq = decl_b(b, nm.f("df_dq"), RAD_I8, {sr, dg.n_embd}); + dw.ds = decl_b(b, nm.f("df_ds"), RAD_F32, {sr, 1}); + /* GROUP-major, [n_embd/group][ceil(M/16)*16] -- quant_act_i8's asum plane, whose first + * dimension is the K group and not the token. */ + dw.dsum = decl_b(b, nm.f("df_dsum"), RAD_F32, {dg.n_embd / 128, spad}); + /* THIS RANK'S plane. `head_rows` is the block's own answer to whether the 2-bit head is + * vocab-sharded, asked here rather than re-derived, because a buffer that disagreed with the + * op declared over it is a read past its end. */ + dw.dlog = decl_b(b, nm.f("df_dlog"), dg.act_dtype, {sr, Dflash2::head_rows(dg)}); + dw.cand = decl_b(b, nm.f("df_cand"), RAD_I32, {sr, dc.sel_topk}); + dw.unary = decl_b(b, nm.f("df_unary"), RAD_F32, {sr, dc.sel_topk}); + /* The vocab-parallel candidate exchange, and only when there is one: this rank's top-R as + * (int32 id, float value) pairs and the all-gathered world_size * R of them. */ + if (Dflash2::head_sharded(dg)) { + dw.dpair = decl_b(b, nm.f("df_dpair"), RAD_F32, {sr, dc.sel_topk, 2}); + dw.dgath = decl_b(b, nm.f("df_dgath"), RAD_F32, {sr, (int64_t)dg.world * dc.sel_topk, 2}); + } + /* NAMED, because the engine reads the draft out of it by name: a DFlash2 pass proposes through + * the selector and never through the sampler's token buffer. */ + dw.tokens = decl_b(b, nm.f("dflash_tokens"), RAD_I32, {dg.max_seqs, dc.steps()}); + + RAD_ARCH_TRY(m.df.declare(b, nm, dg, dc, base_layer, m.kv_draft, m.w_tok, "draft", + nm.ckpt("lm_head.weight"), dw)); + m.have_df = true; + + /* WHAT THE ENGINE DRIVES. Block: a context pass that mirrors the trunk step, then ONE pass + * that fills the whole block. `mask_token_id` is read HERE and nowhere else: it travels in the + * drafter declaration, so no other component has to sniff the container for a drafter. + * + * `window` must be the number this plugin gated its OWN attention with, because the scheduler + * stages the block pass against it: two readings of "how far back can the drafter see" is + * a drafter attending to positions the scheduler did not stage. */ + RadDrafterDecl drf{}; + drf.name = "dflash2"; + drf.kind = RAD_DRAFT_BLOCK; + drf.depth = ctx->max_spec; + /* THE ANCHOR ROW PREDICTS NOTHING here, so the block is one row longer than the depth and the + * head runs over rows 1..depth. Stated rather than defaulted: it is the half of the row + * alignment that lives in this plugin, and the other convention is a real drafter + * (rad_builder.h, RadDrafterDecl::block). */ + 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.dflash_config.mask_token_id", -1); + if (drf.mask_token < 0) { + fprintf(stderr, "radiance: this DFlash2 checkpoint declares no " + "dflash_config.mask_token_id, and every drafted position embeds it -- " + "there is nothing to run.\n"); + return RAD_E_FORMAT; + } + RAD_ARCH_TRY(rad_declare_drafter(b, &drf)); + + rad_note(b, "the DFlash2 drafter is declared: %lld layers of its own at absolute %d..%d, " + "%lld heads / %lld kv x %lld, ffn %lld, %s attention with a %lld-token window, " + "reading the trunk at %d tap(s). ONE forward proposes %lld tokens -- there are no " + "rounds -- and the candidate selector walks a path through the block", + (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.steps()); + 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 and it is what every op but the fp8 linears matches on: the + * norms, rope, attention, the delta-net kernels and the collectives all run on bf16 here, and + * the E4M3 activations exist only between quant_act_fp8 and the GEMM that reads them. Saying + * "fp8" here would be saying it about the residual stream, which is false. */ + RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16)); + +#if QWEN35_MOE + if (meta->n_expert <= 0) { + fprintf(stderr, "radiance: qwen35moe_fp8 needs a routed checkpoint and this one declares " + "no experts; that is qwen35\n"); + return RAD_E_UNSUPPORTED; + } +#else + if (meta->n_expert > 0) { + fprintf(stderr, "radiance: qwen35_fp8 refuses a checkpoint with %lld experts; that is " + "qwen35moe\n", (long long)meta->n_expert); + return RAD_E_UNSUPPORTED; + } +#endif + + Geom& g = m.g; + Names& nm = m.nm; + + 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; + + 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; + } + + GdnFP8::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; + } + 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(); + + /* ---- the three KV groups. The attention cache is BF16 and `kv_dtype` follows it. + * + * --kv-cache-dtype fp8 MAKES IT E4M3, AND IT IS THE ONE KNOB HERE THAT IS WORTH REAL TIME + * AT DEPTH. The attention cache is + * `n_head_kv * head_dim * 2` bytes a token a layer -- 2 KiB a rank on this model -- and ONLY + * the 16 attention layers pay it, because the 48 delta-net layers carry fixed-size state + * instead. At eight sequences of 16k that is 4.3 GB of read traffic a step, which is most of + * what depth costs at that concurrency, and halving the width halves it. It also halves what a + * sequence costs in --vram-kv-mib, which is context and batch size as well as time. + * + * IT IS OFF BY DEFAULT ON A QUALITY ARGUMENT, not as a precaution. Greedy continuations from a + * long prompt agree between bf16 and fp8 for the first few hundred tokens and then diverge, + * and the fp8 side can produce syntactically broken code where the bf16 side stays clean -- + * and this model is a CODER, so that is the workload. + * + * Comparing the two formats takes more than a byte comparison: a few hundred tokens of + * agreement is not evidence that survives a longer sample, and once the text moves the only + * question left is whether what it moved to is WORSE, which needs reading and more than one + * prompt. Alternate the two -- bf16 / fp8 / bf16 / fp8 -- so a difference between the FORMATS + * can be told from a difference between two runs of one. + * + * `--kv-cache-dtype fp8` turns it on. The descales stay at libr4d's default of 1.0, which is + * vLLM's default too; the kernels index them per (sequence, head), so a calibrated pair needs + * no different mechanism. + * + * Nothing else moves with it: the fp8kv attention rows and their `k_descale` / `v_descale` + * operands are in libr4d, the core sizes a page from the group's own dtype, and + * `kv_store_fp8` is the write side. The drafter's cache takes the same width + * (declare_dflash2). */ + RadKVGroupDecl fd{}; + fd.kind = RAD_KV_FULL; + fd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16); + fd.n_head_kv = g.n_head_kv; + fd.head_dim = g.head_dim; + m.kv_full = rad_decl_kv_group(b, nm.f("kv_attn"), &fd); + /* The op parameter has to be the SAME SPELLING the rows band on, and the rows band on + * rad_dtype_name's, so it is taken from there rather than written out twice. */ + g.kv_dtype = rad_dtype_name(fd.dtype); + + /* THE SSM STATE CACHE IS f32. + * + * The state read and write ARE the two GDN kernels: one [128,128] state is 64 KiB at f32, and + * a speculative step writes one PER CANDIDATE TOKEN PER HEAD, because which candidate survives + * verification is not known until after the layer has run. At depth 7 that is hundreds of + * megabytes a rank a step, and one of the largest single kernels after the fp8 GEMMs. An f16 + * state would halve it. + * + * libr4d compiles both widths (`SDT`), and it argues the numerics where the kernel lives: the + * elements are O(0.1) with no range problem and f16's eleven mantissa bits are four more than + * bf16's, which puts the round-trip error at 5e-4 relative. vLLM allocates this cache from + * `--mamba-ssm-cache-dtype`, and reference serves of this model pass `float16`. + * + * f32 ALL THE SAME, because f16 changes the generated text, and nothing else in this plugin + * does that without being asked to. */ + 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); + + 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. Every activation that FEEDS A GEMM carries an fp8 twin: an E4M3 + * plane of the same shape and an f32 scale plane one column per 128. The twins are transients + * like everything else here, so the liveness analysis shares their storage with whatever else + * is dead at that point -- but they are not free, and the largest is `ffn`: 8192 x 17408 bytes + * is 143 MiB against the 285 MiB the bf16 buffer it shadows already costs. */ + 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_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.a_attn.x = decl_b(b, nm.f("attn_out"), g.act_dtype, {g.max_tok, q_dim}); + /* THE ROPE TABLE, and it is the model's rather than a layer's because sixteen layers rotate at + * the same positions with the same theta. Only the rows a step names are written, so the fill + * is kilobytes; the plane has a row per position, past `max_ctx` by the speculative window + * (rope_table_rows), because the fused kernel indexes it by ABSOLUTE position. f32, so the + * cosines the fused rotation multiplies are the ones `rope` computes. */ + /* PERSIST, not transient. A transient may share storage with another transient, and this one is + * written once at the top of a step and read by sixteen layers spread across the whole of it -- + * so anything the planner overlaps it with lands in the middle of its live range. It is also + * the only buffer here whose rows outlive the step that wrote them, which is what PERSIST is + * for. */ + m.b_rope_cs = decl_b(b, nm.f("rope_cs"), RAD_F32, {rope_table_rows(g), m.n_rot}, + RAD_BUF_PERSIST); + RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", q_dim)); + + /* `gdn_in` is conv_dim + v_dim and not in_dim: a and b are their own buffer here because the + * checkpoint keeps them bf16, and the output gate is the tail of THIS one because it does not + * (rad_block_gdn_fp8.h). The convolution and the gate are column views of it. */ + m.a_in.x = decl_b(b, nm.f("gdn_in"), g.act_dtype, {g.max_tok, conv_dim + v_dim}); + RAD_ARCH_TRY(m.a_in.declare_qs(b, nm, g, "gdn_in", conv_dim + v_dim)); + m.b_ab = decl_b(b, nm.f("gdn_ab"), g.act_dtype, {g.max_tok, gc.ab_dim()}); + 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}); + m.b_gdec = decl_b(b, nm.f("gdn_g"), RAD_F32, {g.max_tok, gc.n_head_v}); + m.b_beta = decl_b(b, nm.f("gdn_beta"), RAD_F32, {g.max_tok, gc.n_head_v}); + /* BF16, not f32. gdn_kkt_solve WRITES this plane as `unsigned short*` and gdn_chunk_scan reads + * it back the same way -- libr4d's rows say "bf16 k and A out" and "bf16 q/k/v/A". Declaring + * it f32 sizes it at twice the bytes and makes the two kernels disagree about every element; + * libref reads the operand's own dtype and is correct either way, which is exactly why nothing + * on the host path would catch that. */ + m.b_kkt = decl_b(b, nm.f("gdn_kkt"), RAD_BF16, {g.max_tok, gc.n_head_v, gc.chunk}); + /* RANK 3, because libr4d's scan and recurrent kernels require it there -- and the quantiser + * takes it that way, reading dim 0 as the row. */ + m.a_go.x = decl_b(b, nm.f("gdn_o"), g.act_dtype, {g.max_tok, gc.n_head_v, gc.head_v}); + RAD_ARCH_TRY(m.a_go.declare_qs(b, nm, g, "gdn_o", v_dim)); + +#if QWEN35_MOE + /* ---- THE ROUTING GEOMETRY, read here rather than in the block so that a refusal names the + * container's key and not an internal struct field. `n_ff` is already the PER-RANK expert + * width: rad-convert falls `intermediate_size` back to `moe_intermediate_size`, which on a + * routed checkpoint is the only one there is, and geom_from divided it by world_size. + * + * THE EXPERT COUNT IS NOT DIVIDED. Every rank holds every expert and routes every token the + * same way; what tensor parallel splits is each expert's INTERMEDIATE width, which is the + * division geom_from already made. Sharding the expert SET instead would make the two ranks + * compute different tokens and the block's all-reduce would sum two models. */ + { + MoeFP8::Config& mc = m.moecfg; + mc.n_expert = meta->n_expert; + mc.top_k = meta->n_expert_used > 0 ? meta->n_expert_used + : meta_int2(meta, "qwen35.expert_used_count", + "num_experts_per_tok", 0); + mc.n_ff_exp = g.n_ff; + /* `norm_topk_prob` defaults TRUE in this family (Qwen2-MoE onward), and a container that + * does not say so gets the family's answer rather than an off switch. It is the difference + * between routing weights that sum to one and weights that sum to whatever the top-k of a + * softmax over 256 experts happened to be -- roughly 0.4 here, so reading it the other way + * scales every routed contribution down by more than half. */ + mc.norm_topk = (int)meta_int2(meta, "qwen35.expert_weights_norm", "norm_topk_prob", 1); + const int64_t sh_all = meta_int2(meta, "qwen35.expert_shared_feed_forward_length", + "shared_expert_intermediate_size", 0); + if (sh_all > 0) { + int s2; + if ((s2 = divide_or_fail(sh_all, g.world, "shared_expert_intermediate_size", + &mc.n_ff_shared)) < 0) return s2; + } + /* The pass height. 2048 is the prefill chunk this family runs at, so the shipped + * configuration is one pass; a deployment with a larger chunk slices rather than carrying + * top_k times a whole chunk of expert intermediates. */ + const int64_t moe_rows = 2048; + mc.rows = g.max_tok < moe_rows ? g.max_tok : moe_rows; + if (mc.top_k <= 0 || mc.top_k > mc.n_expert) { + fprintf(stderr, "radiance: qwen35moe: top_k %lld is not in [1, %lld]; the container " + "must give num_experts_per_tok\n", + (long long)mc.top_k, (long long)mc.n_expert); + return RAD_E_INVAL; + } + } + { + /* THE STEP'S HEIGHT FOR EVERYTHING THAT IS ONE ROW A TOKEN, and a PASS's height only for + * the four planes that carry one row per (token, slot). rad_block_moe_fp8.h states the + * rule at Wire and says what breaks if it is not kept. */ + const MoeFP8::Config& mc = m.moecfg; + const int64_t R = g.max_tok, K = mc.rows * mc.top_k; + m.b_rlogits = decl_b(b, nm.f("moe_logits"), g.act_dtype, {R, mc.n_expert}); + m.b_eids = decl_b(b, nm.f("moe_ids"), RAD_I32, {R, mc.top_k}); + m.b_ew = decl_b(b, nm.f("moe_w"), g.act_dtype, {R, mc.top_k}); + m.b_sorted = decl_b(b, nm.f("moe_sorted"), RAD_I32, {K}); + m.b_eoff = decl_b(b, nm.f("moe_off"), RAD_I32, {mc.n_expert + 1}); + /* PERSIST: the histogram's only reader is rad_route_report, which is not a declared op, so + * liveness would see it dead the moment moe_scatter wrote it. See qwen4exp_fp8.cpp. */ + m.b_ecnt = decl_b(b, nm.f("moe_cnt"), RAD_I32, {mc.n_expert}, + RAD_BUF_PERSIST); + m.b_egu = decl_b(b, nm.f("moe_gate_up"), g.act_dtype, {K, 2 * mc.n_ff_exp}); + m.a_eff.x = decl_b(b, nm.f("moe_ffn"), g.act_dtype, {K, mc.n_ff_exp}); + m.a_eff.q = decl_b(b, nm.f("moe_ffn.q"), RAD_F8E4M3, {K, mc.n_ff_exp}); + m.a_eff.s = decl_b(b, nm.f("moe_ffn.s"), RAD_F32, {K, fp8_blocks(mc.n_ff_exp)}); + m.b_edn = decl_b(b, nm.f("moe_down"), g.act_dtype, {K, g.n_embd}); + if (mc.n_ff_shared > 0) { + m.b_emoe = decl_b(b, nm.f("moe_out"), g.act_dtype, {R, g.n_embd}); + m.b_sgu = decl_b(b, nm.f("shexp_gate_up"), g.act_dtype, {R, 2 * mc.n_ff_shared}); + m.a_sff.x = decl_b(b, nm.f("shexp_ffn"), g.act_dtype, {R, mc.n_ff_shared}); + m.a_sff.q = decl_b(b, nm.f("shexp_ffn.q"), RAD_F8E4M3, {R, mc.n_ff_shared}); + m.a_sff.s = decl_b(b, nm.f("shexp_ffn.s"), RAD_F32, {R, fp8_blocks(mc.n_ff_shared)}); + m.b_sout = decl_b(b, nm.f("shexp_out"), g.act_dtype, {R, g.n_embd}); + m.b_sgate = decl_b(b, nm.f("shexp_gate"), g.act_dtype, {R, 1}); + } + } +#else + 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)); +#endif + + m.b_hout = decl_b(b, nm.f("h_out"), g.act_dtype, {g.max_logit_rows, g.n_embd}); + + /* The auxiliary taps. Gated on the DRAFTER being in the container AND on the deployment + * intending to speculate: the buffer is one residual stream per tap, 100 MiB at a 2048-token + * chunk and five taps, which a server that never drafts should not be carrying. `cast` is the + * copy -- see libr4d/r4d_rows.cpp on why the destination is a column slice. */ + if (ctx->max_spec > 0) { + const char* da = rad_meta_gets(meta, "draft.architectures", ""); + if (da && std::strstr(da, "DFlash")) { + m.n_taps = parse_tap_layers( + rad_meta_gets(meta, "draft.dflash_config.target_layer_ids", nullptr), + m.n_main, m.tap_layer, Model::MAX_TAPS); + if (m.n_taps > 0) { + m.b_dfsrc = decl_b(b, nm.f("dflash_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}); + } + } + } + m.b_logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab}); + RAD_ARCH_TRY(rad_declare_logits(b, m.b_logits)); + + /* ---- vocabulary edges. The embedding is bf16 in this checkpoint. The lm_head is whatever the + * model holds it as -- bf16 as the checkpoint ships it, or block fp8 where the recipe made it + * so -- and it is declared at its codes' dtype, so the logits kernel that reads that encoding + * is the one selected: the widest GEMM in the model at half the bytes when it is fp8. + * + * AND BOTH ARE ROW-SHARDED WITH THE VOCABULARY. Sharding one end and replicating the other + * would put 248320 x 5120 in bf16 -- 2.43 GiB -- on EVERY rank, and that is KV cache. + * `embed_lookup` takes a `vocab_offset`, so a rank gathers the ids in its own slice and writes + * a zero row for the rest, and the all_reduce below sums the ranks back into x. Every token + * lands on exactly one rank, so the sum is exact and `exact` is not the wire's choice to make + * here. + * + * The name maps come first: they are how the checkpoint is asked what each weight is. */ + 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"))); + 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. */ + 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 -- which layer 0's norm folds + * in at two ranks, so there is no other place to put them (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, unconditionally, and not g.wire_exact. Every other all_reduce in this model sums + * partial products where a lossy wire trades a little error for bandwidth; this one sums + * DISJOINT rows -- each token's embedding comes from exactly one rank and every other rank + * contributes a zero -- so a lossy wire would be pure loss on a value that is already the + * answer. min_bytes is left at 0 for the same reason. */ + 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. */ + /* The rope table's fill, declared before the layers that read it. If it does not resolve the + * buffer stays zero and every attention block falls back to its unfused norm + rope pair -- + * which is why `aw.cos_sin` is cleared rather than left pointing at a plane nothing fills. Its + * band is the fused prologue's (qk_fuse_rows), so a step the prologue does not serve -- a + * prefill chunk, where the fill's grid is one block a TOKEN -- issues no fill either. */ + m.op_rope_cs = rw(b, RAD_OP(b, "rope_table", + RAD_PARAMS(RAD_RANGE("M", 1, qk_fuse_rows(g)), RAD_INT("rot", m.n_rot), + RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + {}, {m.b_rope_cs}); + + AttnGatedFP8::Wire aw{}; + aw.x = m.b_x; aw.h = m.a_h; aw.qg = m.b_qg; aw.k = m.b_k; aw.v = m.b_v; + aw.q = m.b_q; aw.attn = m.a_attn; + aw.cos_sin = m.op_rope_cs ? m.b_rope_cs : 0; + + GdnFP8::Wire gw{}; + gw.x = m.b_x; gw.h = m.a_h; gw.in = m.a_in; gw.ab = m.b_ab; + 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.a_go; + + Ffn::Wire mw{}; +#if QWEN35_MOE + mw.x = m.b_x; mw.h = m.a_h; + mw.logits = m.b_rlogits; mw.ids = m.b_eids; mw.ew = m.b_ew; + mw.sorted = m.b_sorted; mw.eoff = m.b_eoff; mw.ecnt = m.b_ecnt; + mw.egu = m.b_egu; mw.eff = m.a_eff; mw.edn = m.b_edn; mw.moe = m.b_emoe; + mw.sgu = m.b_sgu; mw.sff = m.a_sff; mw.sout = m.b_sout; mw.sgate = m.b_sgate; +#else + mw.x = m.b_x; mw.h = m.a_h; mw.gate_up = m.b_gate_up; mw.ffn = m.a_ffn; +#endif + + /* ---- WHERE THE RESIDUAL ADD HAPPENS, which is the one thing this chain has to agree on. + * + * Every block ends `x += h` and every block begins `norm(x)`, so the add can move to the front + * of the NEXT block's norm and stop being a launch of its own (rad_fp8.h, NormQuantFP8): ~128 + * of them a step, each a full dispatch for 82 KiB of row. `fold` says a block adds its predecessor's + * delta; `add_out` says the block after it will not, so this one must. + * + * TWO THINGS READ `x` BETWEEN BLOCKS and each keeps the add at the end of its block: + * + * - THE DRAFTER'S TAPS. `op_tap` copies the residual stream after a named layer, and what + * DFlash2 conditions on has to be that layer's real output. So a tap layer's MLP keeps its + * own add, and the block after it has nothing to fold. + * - THE FINAL NORM, which is a plain `rmsnorm` and has no residual operand. The last layer + * keeps its add. + * + * The MTP head below is left unfolded for the same reason in reverse: it is a second chain + * over a different residual buffer, it is not the shipped drafter, and two launches a step is + * not worth a second copy of this argument. */ + auto is_tap = [&](int64_t l) { + for (int t = 0; t < m.n_taps; ++t) + if (m.tap_layer[t] == (int)l) return true; + return false; + }; + + m.layers.resize((size_t)m.n_main); + for (int64_t l = 0; l < m.n_main; ++l) { + Layer& lay = m.layers[(size_t)l]; + lay.full = is_full_attention(l, interval) ? 1 : 0; + + /* The mixer folds unless it is first in the chain or its predecessor's MLP kept its add. */ + const bool mix_fold = l > 0 && !is_tap(l - 1); + /* ...and never adds itself, because the MLP beside it always folds. */ + const bool mlp_fold = true; + const bool mix_add = !mlp_fold; + const bool mlp_add = is_tap(l) || l + 1 >= m.n_main; + /* ...AND THE COLLECTIVE MOVES WITH THE ADD, one boundary at a time. A block's all-reduce + * can become the next block's first pass exactly where that block folds -- the fold is + * what says the delta in `h` is still there and that this norm is its only reader -- so + * `ar_in` is the fold and `ar_out` is the successor's fold, which is the flag already + * computed as `!*_add`. Two ranks or nothing: at tp1 there is no collective to fold, and + * at four the kernel does not exist. See rad_fp8.h. */ + const bool tp2 = g.world == 2; + /* ...AND LAYER 0 ABSORBS THE EMBEDDING'S. Its mixer does not FOLD -- there is no previous + * block and so no delta to add -- but the embedding table is vocab-sharded, so there IS a + * collective in front of it, and the fused norm takes one without the other. That is the + * only place `ar_in` and `fold` come apart, and it is why they are separate flags. + * rad_fp8.h::NormQuantFP8 declares the fused op without a residual. */ + const int mix_ar_in = !tp2 ? kArNone + : mix_fold ? kArAny + : (l == 0 && m.op_embed_ar) ? kArExact /* the embedding; see rad_fp8.h */ + : kArNone; + const bool mix_ar_out = !mix_add && tp2; + const bool mlp_ar_in = mlp_fold && tp2; + const bool mlp_ar_out = !mlp_add && tp2; + + const char* pre = "model.language_model.layers"; + if (lay.full) { + AttnGatedFP8::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, + mix_fold, mix_add, mix_ar_in, mix_ar_out)); + } else { + GdnFP8::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, + mix_fold, mix_add, mix_ar_in, mix_ar_out)); + } + + Ffn::Src ms{}; +#if QWEN35_MOE + ms.cfg = m.moecfg; + ms.norm = nm.ckpt("%s.%lld.post_attention_layernorm.weight", pre, (long long)l); + ms.router = nm.ckpt("%s.%lld.mlp.gate.weight", pre, (long long)l); + ms.experts = nm.ckpt("%s.%lld.mlp.experts", pre, (long long)l); + if (m.moecfg.n_ff_shared > 0) { + ms.shared = nm.ckpt("%s.%lld.mlp.shared_expert", pre, (long long)l); + ms.shared_gate = nm.ckpt("%s.%lld.mlp.shared_expert_gate.weight", pre, (long long)l); + } +#else + 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); +#endif + RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw, ms, mlp_fold, mlp_add, + mlp_ar_in, mlp_ar_out)); + } + + 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.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 multi-token-prediction head (rad_block_mtp_fp8.h). + * + * DECLARED ONLY WHEN THE DEPLOYMENT SPECULATES. It is half a gigabyte of weights that a + * non-speculative server would read off disk, place in VRAM and never issue, and `max_spec` + * is the engine already saying whether it intends to draft. rad-convert declares at a + * non-zero max_spec on purpose, because a CONTAINER should carry what the model can serve + * even when the run that made it would not have used it. + * + * AND ONLY WHEN THERE IS NO DFLASH2 DRAFTER, which `n_taps` is the sign of. A container can + * carry both; a deployment drafts with one, and DFlash2 is the better one on this target -- + * one forward a block against one chained forward a token. Declaring both would put half a + * gigabyte of MTP weights on the card for a head nothing ever issues. */ + if (nextn > 0 && g.max_spec > 0 && m.n_taps == 0) { + /* AT max_tok, NOT max_logit_rows. A draft round is one row a sequence, but the history + * pass that fills the head's own K and V is one row a TOKEN and runs over a whole prefill + * chunk. 26 MiB at a 512-token chunk, against the 477 MiB of head weights beside it. */ + m.b_mtp_h = decl_b(b, nm.f("mtp_h"), g.act_dtype, {g.max_tok, g.n_embd}); + m.b_mtp_e = decl_b(b, nm.f("mtp_e"), g.act_dtype, {g.max_tok, g.n_embd}); + m.b_mtp_c = decl_b(b, nm.f("mtp_c"), g.act_dtype, {g.max_tok, 2 * g.n_embd}); + m.b_mtp_x = decl_b(b, nm.f("mtp_x"), g.act_dtype, {g.max_tok, g.n_embd}); + + /* The 2-bit draft head's working set, at max_logit_rows: only a DRAFT round reaches any of + * it, and a draft round is one row a sequence. `mtp_dsum` is the odd one -- it is + * quant_act_i8's group-major [n_embd/128][ceil(M/16)*16] plane, so its first dimension is + * the K group and not the token. */ + if (mtp_draft_head_q2(b, nm.f("mtp.draft_head.weight"), nm.ckpt("lm_head.weight"))) { + const int64_t dmpad = ((g.max_logit_rows + 15) / 16) * 16; + m.b_mtp_dq = decl_b(b, nm.f("mtp_dq"), RAD_I8, {g.max_logit_rows, g.n_embd}); + m.b_mtp_ds = decl_b(b, nm.f("mtp_ds"), RAD_F32, {g.max_logit_rows, 1}); + m.b_mtp_dsum = decl_b(b, nm.f("mtp_dsum"), RAD_F32, {g.n_embd / 128, dmpad}); + m.b_mtp_dlog = decl_b(b, nm.f("mtp_dlog"), g.act_dtype, {g.max_logit_rows, g.n_vocab_all}); + /* NAMED, because the engine finds it by name: a draft round's proposal comes out of + * row_topk and never through the sampler's token buffer. */ + m.b_mtp_didx = decl_b(b, nm.f("mtp_didx"), RAD_I32, {g.max_logit_rows, 1}); + m.b_mtp_dval = decl_b(b, nm.f("mtp_dval"), RAD_F32, {g.max_logit_rows, 1}); + } + + /* The layer's working set is the trunk's: `attn_qg`, `attn_k`, the ffn planes and `h` are + * all dead by the time a draft round runs, and a second set would be 150 MiB of transients + * for one layer. Only the residual stream is the head's own -- it must not be the trunk's + * `x`, which the next step's prefill still needs. */ + AttnGatedFP8::Wire tw_attn = aw; tw_attn.x = m.b_mtp_x; + Ffn::Wire tw_mlp = mw; tw_mlp.x = m.b_mtp_x; + + MtpHead::Wire tw{}; + tw.src = m.a_h.x; tw.hout = m.b_mtp_h; tw.logits = m.b_logits; + tw.e = m.b_mtp_e; tw.c = m.b_mtp_c; tw.x = m.b_mtp_x; + tw.dq = m.b_mtp_dq; tw.ds = m.b_mtp_ds; tw.dsum = m.b_mtp_dsum; + tw.dlog = m.b_mtp_dlog; tw.didx = m.b_mtp_didx; tw.dval = m.b_mtp_dval; + tw.attn = tw_attn; tw.mlp = tw_mlp; + + MtpHead::Src ts{}; + ts.fc = nm.ckpt("mtp.fc.weight"); + ts.norm = nm.ckpt("mtp.norm.weight"); + ts.pre_norm_hidden = nm.ckpt("mtp.pre_fc_norm_hidden.weight"); + ts.pre_norm_embedding = nm.ckpt("mtp.pre_fc_norm_embedding.weight"); + ts.attn.norm = nm.ckpt("mtp.layers.0.input_layernorm.weight"); + ts.attn.qg = nm.ckpt("mtp.layers.0.self_attn.q_proj.weight"); + ts.attn.k = nm.ckpt("mtp.layers.0.self_attn.k_proj.weight"); + ts.attn.v = nm.ckpt("mtp.layers.0.self_attn.v_proj.weight"); + ts.attn.q_norm = nm.ckpt("mtp.layers.0.self_attn.q_norm.weight"); + ts.attn.k_norm = nm.ckpt("mtp.layers.0.self_attn.k_norm.weight"); + ts.attn.o = nm.ckpt("mtp.layers.0.self_attn.o_proj.weight"); + ts.mlp.norm = nm.ckpt("mtp.layers.0.post_attention_layernorm.weight"); +#if QWEN35_MOE + /* THE HEAD'S FEED-FORWARD IS ROUTED TOO, and it has its own 256 experts -- `mtp.layers.0` + * carries `mlp.experts.*`, `mlp.gate` and a shared expert exactly as a trunk layer does. + * That is what MtpBlockFP8 is a template for; a head hard-wired to the dense block could + * not declare it, and the container would carry a drafter nothing could run. */ + ts.mlp.cfg = m.moecfg; + ts.mlp.router = nm.ckpt("mtp.layers.0.mlp.gate.weight"); + ts.mlp.experts = nm.ckpt("mtp.layers.0.mlp.experts"); + if (m.moecfg.n_ff_shared > 0) { + ts.mlp.shared = nm.ckpt("mtp.layers.0.mlp.shared_expert"); + ts.mlp.shared_gate = nm.ckpt("mtp.layers.0.mlp.shared_expert_gate.weight"); + } +#else + ts.mlp.gate = nm.ckpt("mtp.layers.0.mlp.gate_proj.weight"); + ts.mlp.up = nm.ckpt("mtp.layers.0.mlp.up_proj.weight"); + ts.mlp.down = nm.ckpt("mtp.layers.0.mlp.down_proj.weight"); +#endif + /* The trunk maps this same tensor as `output.weight`; the draft head maps it again under a + * name of its own, which the recipe quantises to two bits (mtp_draft_head_q2). */ + ts.lm = nm.ckpt("lm_head.weight"); + + /* Bound as one more layer of the trunk's full-attention group, at absolute index n_main, + * so a draft round writes its K and V at the slot the trunk's token for that position + * owns. rad_block_mtp_fp8.h argues the case; the short version is that it makes a rejected + * draft self-correcting instead of something to roll back. */ + RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)m.n_main, m.kv_full)); + m.mtp.media = m.media; + RAD_ARCH_TRY(m.mtp.declare(b, nm, g, (int)m.n_main, m.kv_full, m.n_rot, m.w_tok, + m.w_lm_head, final_wadd, tw, ts)); + m.have_mtp = true; + + /* WHAT THE ENGINE DRIVES. Serial: `max_spec` dependent passes, each embedding what the + * last one proposed. `proposal` is the buffer a pass leaves its token in, and the two + * heads differ -- the 2-bit head takes its own argmax into `mtp_didx`, the bf16 head goes + * through the ordinary sampler chain and 0 says so. Declaring it is what keeps the engine + * from having to work it out from buffer names. */ + RadDrafterDecl dd{}; + dd.name = "mtp"; + dd.kind = RAD_DRAFT_SERIAL; + dd.depth = ctx->max_spec; + dd.proposal = m.b_mtp_didx; + dd.proposal_pitch = 1; + dd.mask_token = -1; + RAD_ARCH_TRY(rad_declare_drafter(b, &dd)); + } + + /* ---- the DFlash2 drafter (rad_block_dflash2.h), at absolute layers n_main.. of its own KV + * group. Gated on the same two things the taps are: a drafter in the container, and a + * deployment that means to speculate. `n_taps` is already both -- it is non-zero only when + * `draft.architectures` named a DFlash model AND max_spec was positive. */ + if (m.n_taps > 0) { + RAD_ARCH_TRY(declare_dflash2(b, meta, ctx, m, (int)m.n_main)); + if (nextn > 0) + rad_note(b, "the DFlash2 drafter DISPLACES the %lld-layer MTP head, which is not " + "declared and whose weights this container therefore does not carry. One " + "drafter a container: the two are 4.3 GB between them and a deployment " + "drafts with one of them. Convert without --draft-model for the MTP one", + (long long)nextn); + } + + 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, "weights are block-scaled fp8: E4M3 [N,K] with a bf16 [N/%d,K/%d] scale plane, " + "one stored weight taken by gemm_nt_q at dtype fp8a8 as two operands -- no " + "repacking and no dequantisation, so the model costs what the checkpoint does", + RAD_FP8_BLOCK, RAD_FP8_BLOCK); + rad_note(b, "activations are quantised to E4M3 every step (activation_scheme: dynamic): one " + "quant_act_fp8 per activation that feeds a GEMM, not per GEMM -- the three " + "attention projections share one, and so do the delta net's qkv and z"); + rad_note(b, "NOT fp8 in the checkpoint: every norm, A_log, dt_bias, conv1d, the embedding, the " + "lm_head (unless a recipe made it so), and the delta net's in_proj_a / in_proj_b " + "-- 48 columns each, which is not a whole %d-row scale block, so the checkpoint " + "left them bf16 and this plugin runs them as a separate bf16 gemm_nt instead of " + "fusing them into the qkv row", RAD_FP8_BLOCK); + rad_note(b, "gdn: %lld key heads x %lld, %lld value heads x %lld, conv width %lld, chunk %lld; " + "conv row %lld channels, a|b row %lld", + (long long)gc.n_head_k, (long long)gc.head_k, (long long)gc.n_head_v, + (long long)gc.head_v, (long long)gc.conv_width, (long long)gc.chunk, + (long long)conv_dim, (long long)gc.ab_dim()); + rad_note(b, "ssm_a_log carries A_log AS A LOG: the kernels form -exp(A_log)*softplus(a+dt). " + "A container built from a GGUF has ssm_a = -exp(A_log) already applied and must " + "undo it, or every head's decay collapses"); + rad_note(b, "rope is mrope over %lld of %lld head dims, sections [11,11,10]; RadBatch carries " + "one position component per token, so the three sections see the same position -- " + "exact for text, wrong for an image span", + (long long)m.n_rot, (long long)g.head_dim); + if (!have_interval) + rad_note(b, "the container did not state full_attention_interval; assuming %lld, which " + "makes layers 3,7,... full attention", (long long)interval); + if (m.have_mtp) + rad_note(b, "the MTP head is declared: %lld NextN layer(s) exist under an `mtp.` prefix of " + "their own and the FIRST is served, as absolute layer %lld of the " + "full-attention KV group. It drafts; the trunk verifies. mtp.fc reads the " + "normed embedding then the normed hidden state", + (long long)nextn, (long long)m.n_main); + else if (nextn > 0) + rad_note(b, "%lld MTP/NextN layer(s) sit BESIDE the %lld trunk layers -- under an `mtp.` " + "prefix of their own, not as layers %lld.. -- and are NOT declared, because " + "this deployment asked for no speculative window (max_spec 0). Half a " + "gigabyte of weights stays off the card", + (long long)nextn, (long long)m.n_main, (long long)m.n_main); + + /* THE VISION TOWER, LAST: an encoder pass issues nothing else, so its activations share the + * arena with every buffer declared above. Its weight groups start past every text layer, the + * MTP head and a drafter's. */ + 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; + } + + /* AN MTP PASS runs the head and NOTHING ELSE. The trunk already ran this step and left its + * hidden states in `h`; the head reads the rows it wants out of them and turns them into + * either a draft token or one more position of its own attention history. Which of the two + * is the SIGN of `draft_pass`, and rad_block_mtp_fp8.h says why there are two. + * + * Zero is a trunk step, so a zeroed RadBatch runs the model -- the same convention, and for + * the same reason, as `num_accepted` (docs/OPS.md). */ + if (batch->draft_pass != 0) { + /* THE DRAFTER'S OWN cos/sin ROWS FIRST, AND THE TRUNK DID NOT WRITE THEM. `rope_table` + * fills the rows THIS STEP'S POSITIONS name, and a drafter pass runs PAST the committed + * end -- the MTP head's round k is at position head_i + k - 1, which the trunk step + * before it never reached. Without this the head rotates by whatever the plane held at a + * row nothing had written, which costs only ACCEPTANCE (a mis-rotated draft is rejected + * and the text is still the trunk's) and therefore has no symptom at all. + * + * A row is a function of its POSITION ALONE, so re-filling is idempotent and can never + * write a row a later reader disagrees with. qwen4exp_fp8.cpp carries the same call for + * the same reason and says more about it. */ + if (m.op_rope_cs && batch->n_tok <= qk_fuse_rows(m.g) && !rope_mixed(batch)) + RAD_ISSUE_N(c, m.op_rope_cs, batch->n_tok, + rope_pos1(batch, batch->n_tok), RAD_B(m.b_rope_cs)); + /* THE FIELD MEANS "A DRAFTER PASS, AND THE SIGN SAYS WHICH KIND", and both drafters read + * it that way even though only the MTP head has rounds. For DFlash2 the two kinds are the + * two passes: positive is the QUERY pass, which proposes the whole block in one go, and + * negative is the CONTEXT pass, which turns the tokens the trunk just committed into the + * drafter's own K and V. There is no third kind and no round counter -- a block-diffusion + * drafter runs its layers once per step. */ + if (m.have_df) { + if (batch->draft_pass > 0) m.df.step(c, batch); + else m.df.context(c, batch); + return; + } + if (!m.have_mtp) { + rad_step_fail(c, "the batch asks for a drafter pass and no drafter is declared: the " + "container has neither an `mtp.` block nor a `draft.` one, or " + "declare ran at max_spec 0, which is the engine saying it would not " + "draft"); + return; + } + m.mtp.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 -- ONLY WHERE LAYER 0'S NORM WILL NOT DO IT, which is the same + * sentence every block in this model already carries about its own collective. At tp1 there + * is no op and the graph is what it always was; at tp2 the fused norm takes it and this is + * not issued at all, which for n_embd 5120 is every step. The standalone op stays DECLARED + * because ar_fused_ok is a question about T and a width, and a model whose n_embd the + * compressed wire cannot tile would fall back to it. */ + if (m.op_embed_ar && !ar_wire_is_exact(m.g, batch->n_tok)) + RAD_ISSUE_N(c, m.op_embed_ar, (int64_t)batch->n_tok * m.g.n_embd, + brows(m.b_x, batch->n_tok), RAD_NONE); + + /* ONE FILL A STEP, HERE, because every attention layer below reads it and they all rotate at + * the same positions. Only the rows this step names are written -- and only on a step whose + * width the fusion actually serves, because the table has exactly one consumer and a prefill + * chunk takes the unfused pair. The band is asked of `qk_fuse_rows` rather than restated, so + * the fill and the op that reads it cannot disagree about which steps have a table. */ + if (m.op_rope_cs && batch->n_tok <= qk_fuse_rows(m.g) && !rope_mixed(batch)) + RAD_ISSUE_N(c, m.op_rope_cs, batch->n_tok, + rope_pos1(batch, batch->n_tok), RAD_B(m.b_rope_cs)); + + for (int64_t li = 0; li < (int64_t)m.layers.size(); ++li) { + const Layer& l = m.layers[(size_t)li]; + if (l.full) l.attn.step(c, batch); + else l.gdn.step(c, batch); + dbg_resid(c, (int)li, "mix", m.g.n_embd, m.b_x, m.a_h.x); + l.mlp.step(c, batch); + dbg_resid(c, (int)li, "ffn", m.g.n_embd, m.b_x, m.a_h.x); + + /* THE TAP, AFTER the layer, because what a drafter conditions on is this layer's OUTPUT. + * The residual stream is one buffer the next layer overwrites, so the rows are copied into + * the column slice this tap owns while they are still here. Linear in the tap count and + * only over the layers named. */ + 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)); + } +} + + +/* ================================================================== the probe + * + * WHAT THIS CONTAINER'S DRAFTER IS WORTH SPECULATING TO, answered before anything is declared + * because `max_spec` is an input to declaration -- it sizes the drafter's buffers, bands the + * kernels and sets the scheduler's window. The core asks; it reads none of these keys itself. + * + * THE DRAFT DEPTH IS A PROPERTY OF THE DRAFTER, not something an operator has to remember. The two + * numbers below are far apart because the two drafters propose in different shapes. + * + * An MTP head is SERIAL: depth d is d chained forward passes, each one embedding the token the + * last one proposed, so the marginal token gets more expensive exactly as it gets less likely. On + * Qwen3.8-27B-FP8 at two ranks throughput is flat across depths 2, 3 and 4 and falls away after, + * so 3 is the top of that plateau. + * + * DFlash2 is block-diffusion and proposes the WHOLE block in one pass, so its depth is not a + * throughput trade at all: it is the block length the checkpoint was trained at, and asking for + * anything else is a silently worse draft. This one ships trained at block_size 8, which is one + * anchor and 7 mask positions. + * + * 0 when the container carries no drafter, which is the right answer to "speculate as deeply as + * this model can" on a model that cannot. */ +static int probe(const RadModelMeta* meta, RadArchProbe* out) { + if (!meta || !out) return RAD_E_INVAL; + const char* da = rad_meta_gets(meta, "draft.architectures", ""); + if (da && std::strstr(da, "DFlash2")) { + const long long bs = rad_meta_geti(meta, "draft.dflash_config.block_size", 8); + out->draft_depth = bs > 1 ? (int)(bs - 1) : 7; + out->draft_depth_fixed = 1; /* trained at exactly this block; any other is a refusal */ + return RAD_OK; + } + if (meta_int2(meta, "qwen35.nextn_predict_layers", "mtp_num_hidden_layers", 0) > 0) + out->draft_depth = 3; + return RAD_OK; +} + +} /* namespace QWEN35_NS */ + +#ifndef RAD_ARCH_NO_EXPORTS +/* ONE MORE LEVEL OF EXPANSION, and it is load-bearing. RAD_ARCH_PLUGIN stringifies its NS argument + * to name the plugin, and `#` applies to the parameter as WRITTEN -- so passing QWEN35_NS directly + * would register a plugin called "QWEN35_NS", which the registry would then refuse the second copy + * of by name. An argument that is not stringified in the intermediate macro IS macro-expanded + * before substitution, so these two forward the expanded namespace. */ +#define QWEN35_PROBE_X(NS) RAD_ARCH_PROBE(NS) +#define QWEN35_PLUGIN_X(NS, ...) RAD_ARCH_PLUGIN(NS, __VA_ARGS__) +QWEN35_PROBE_X(QWEN35_NS) +#if QWEN35_MOE +QWEN35_PLUGIN_X(QWEN35_NS, QWEN35_ARCH_ID, "fp8_e4m3", "0.1.0", + "Qwen3.5 / 3.6 MoE (35B-A3B), block-scaled fp8 weights and fp8 activations: the " + "dense graph with a routed feed-forward -- 256 experts, 8 a token, a shared expert " + "beside them -- gated attention over paged KV every fourth layer and gated delta " + "net between") +#else +QWEN35_PLUGIN_X(QWEN35_NS, QWEN35_ARCH_ID, "fp8_e4m3", "0.1.0", + "Qwen3.5 / 3.6 / 3.8 dense (0.8B..27B), block-scaled fp8 weights and fp8 " + "activations, gated attention over paged KV every fourth layer and gated delta " + "net between") +#endif +#endif diff --git a/arch/qwen35moe_fp8/CMakeLists.txt b/arch/qwen35moe_fp8/CMakeLists.txt new file mode 100644 index 00000000..565c4d54 --- /dev/null +++ b/arch/qwen35moe_fp8/CMakeLists.txt @@ -0,0 +1,11 @@ +# A plugin like any other: built here inside radiance's tree, or on its own against an installed +# radiance (`cmake -S arch/qwen35moe_fp8 -B build -DCMAKE_PREFIX_PATH=`) -- the same +# rad_add_plugin either way (cmake/RadAddPlugin.cmake). +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(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) diff --git a/arch/qwen35moe_fp8/qwen35moe_fp8.cpp b/arch/qwen35moe_fp8/qwen35moe_fp8.cpp new file mode 100644 index 00000000..c15a20a1 --- /dev/null +++ b/arch/qwen35moe_fp8/qwen35moe_fp8.cpp @@ -0,0 +1,24 @@ +/* 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" diff --git a/arch/qwen4exp_fp8/CMakeLists.txt b/arch/qwen4exp_fp8/CMakeLists.txt new file mode 100644 index 00000000..20e15414 --- /dev/null +++ b/arch/qwen4exp_fp8/CMakeLists.txt @@ -0,0 +1,11 @@ +# A plugin like any other: built here inside radiance's tree, or on its own against an installed +# radiance (`cmake -S arch/qwen4exp_fp8 -B build -DCMAKE_PREFIX_PATH=`) -- the same +# rad_add_plugin either way (cmake/RadAddPlugin.cmake). +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(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) diff --git a/arch/qwen4exp_fp8/qwen4exp_fp8.cpp b/arch/qwen4exp_fp8/qwen4exp_fp8.cpp new file mode 100644 index 00000000..5123c29c --- /dev/null +++ b/arch/qwen4exp_fp8/qwen4exp_fp8.cpp @@ -0,0 +1,1453 @@ +/* qwen4exp_fp8 -- Qwen4-Exp (`model_type: qwen4_exp`), the architecture Qwen3.8-Flash-Next ships + * and the one Qwen says Qwen4 will be built on. DENSE bf16 checkpoint, quantised by a recipe ahead + * of time (data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe is the served one): int8 or fp8 trunk + * linears with activations of the same kind, four-bit routed experts, or bf16 throughout. + * + * ============================== WHAT IT IS, RELATIVE TO WHAT ALREADY RUNS ============================== + * + * In transformers it is `Qwen4ExpTextModel`, a subclass of `Qwen3_5MoeTextModel` -- and this tree + * already serves that (arch/qwen35moe_fp8, Qwen3.6-35B-A3B-FP8). So most of this file is + * composition over the same blocks, and what is genuinely new is small and named: + * + * SAME, reused as-is the Gated DeltaNet (conv width 4, key/value head dim 128), the + * GATED full attention (`attn_output_gate`, q_proj twice as wide, + * half of it a sigmoid gate on the attention output), partial rotary + * (64 of 256 dims), the routed feed-forward with a shared expert and + * its own sigmoid gate, the MTP position. + * NEW, in this tree the GATED RESIDUAL (arch/common/rad_block_hc.h), the n-gram / PLE + * layer (arch/common/rad_block_ple.h), QSA's indexer + * (arch/common/rad_qsa.h), the STACKED dense expert tensors + * (tools/rad_convert.cpp's slice_stacked), gqa 12, and the delta + * net's SIGMOID output gate. The last two sections of this comment + * say what the first two of those are for. + * + * Qwen3.8-Flash-Next: 48 layers of 12 x (3 x GatedDeltaNet -> MoE, then 1 x QSA -> MoE), hidden + * 2560, hc_count 4 so the residual stream is 10240, 512 experts of 640 at top-10 plus a shared 640, + * 24 query heads and 2 KV heads at head_dim 256, vocab 248320. + * + * ============================== THE RESIDUAL STREAM IS FOUR TIMES AS WIDE ============================== + * + * There is no `input_layernorm`, no `post_attention_layernorm` and no final `norm` in this + * checkpoint. In their place every block has a GATED RESIDUAL connection -- a grouped norm over a + * 10240 stream, a low-rank data-dependent read gate that mixes the four sub-streams down to 2560, + * and four data-dependent scalars that gain the block's output back into all four. 96 of them, plus + * a 97th with no write half that collapses the stream for the lm_head. + * + * arch/common/rad_block_hc.h holds the arithmetic and docs/OPS.md's `hc_read` / `hc_write` rows + * hold the schema. What matters HERE is that the blocks do not own their norms: this plugin + * passes `Src::norm = nullptr`, which is the three fp8 blocks' "the input is already normed and + * quantised" mode, and it therefore also gives up the two fusions that mode is built on -- the + * residual add folded into the next norm, and the all-reduce folded into it. The all-reduce rides + * in the gated residual's write instead, wherever a kernel serves that (HyperConn::Config::reduce, + * see declare()). + * + * ============================== WHAT IS AND IS NOT FP8 ============================== + * + * The checkpoint is bf16 THROUGHOUT -- it carries no `quantization_config` at all -- so this + * plugin's quantisation descriptor is the EMPTY one and the formats it serves are made by a + * recipe (data/recipes/qwen4exp-*.recipe). The plugin reads each weight's encoding and declares + * what that is; the blocks that read a weight in more than one format choose their ops by it: + * + * block fp8 or int8 self_attn.{q,k,v,o}_proj, linear_attn.{in_proj_qkv, in_proj_z, out_proj}, + * the shared expert's three (LinearFP8); the indexer's qk projection + * unless the recipe leaves it bf16, as the served one does + * fp8, four-bit every routed expert's gate_up and down, each layer and projection in its + * or bf16 own form (MoeFP8::probe) + * E4M3 rows or bf16 each connection's input_mix_weight_{down,up}, whose lowrank of 320 is 2.5 + * scale blocks and so is scaled a row group at a time (HyperConn), and the + * MTP head's fc_hidden / fc_embedding + * fp8, int8, bf16 the lm_head (whichever logits_gemm kernel reads it) + * BF16 every norm gain, A_log, dt_bias, conv1d, in_proj_a / in_proj_b (48 rows is + * not a whole scale block), the router, shared_expert_gate, embed_tokens, + * the PLE projections and inject weights + * + * ============================== HOW TENSOR PARALLEL SPLITS AN EXPERT ============================== + * + * `moe_intermediate_size` is 640 = 5 x 128. A rank's even share at tp2 is 320, which is NOT a whole + * number of 128-column blocks -- the fp8 scale block, the 4-bit scale group and the rotation all + * sit on them. So each rank takes three blocks of the experts of one parity and two of the + * other's, the router stays replicated so both ranks agree on the routing, each rank computes its + * slice of every routed expert, and THE BLOCK'S EXISTING END-OF-BLOCK ALL-REDUCE SUMS THE + * PARTIALS. No all-to-all, no extra collective. The section in declare() carries the detail, and + * why this is preferred to splitting the experts themselves between the ranks. + * + * ============================== PLE AND QSA ============================== + * + * PLE / THE N-GRAM EMBEDDING is 51B of the model's 180B parameters -- a 320,001,536-row table of + * 160-dim embeddings, gathered 16 rows a token by a hash of the last three token ids, read once at + * layer 1 and injected into the wide stream. Without it this is a 125B model missing a third of + * its parameters. + * + * QSA'S INDEXER picks the best `indexer_budget / indexer_compress_ratio` = 512 blocks of 4 tokens + * for each query and attends to those alone. Below `indexer_budget + indexer_compress_ratio - 1` = + * 2051 tokens of context EVERY complete block is selected, so QSA is DENSE CAUSAL ATTENTION bit + * for bit -- which is the oracle any change to it is checked against, and is also why the engine + * issues the cheaper dense attention there. Above it the selection is per QUERY on both paths + * (docs/QSA.md, arch/common/rad_qsa.h), so a long prompt is prefilled with the model's own + * attention and not a denser stand-in. + * + * The vision tower is declared through arch/common/rad_block_vit.h, only when the container + * carries one and the deployment asked for media; rad-convert writes only declared weights. + */ +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace qwen4exp_fp8 { + +using namespace rad::arch; + +struct Layer { + int full = 0; + HyperConn hc_mix; /* in front of the attention or the delta net */ + HyperConn hc_ffn; /* in front of the routed feed-forward */ + AttnGatedFP8 attn; + QsaIndexer qsa; /* full-attention layers only; inert when the checkpoint has none */ + GdnFP8 gdn; + MoeFP8 mlp; +}; + +struct Model { + Names nm{""}; + Geom g{}; + GdnFP8::Config gcfg{}; + MoeFP8::Config moecfg{}; + /* The trunk's linears are int8 (LinearFP8::i8), read off the first delta-net layer's input + * projection before the activation buffers are declared. */ + bool trunk_i8 = false; + HyperConn::Config hccfg{}; + QsaIndexer::Config qsacfg{}; + QsaIndexer::Wire qsaw{}; + rad_kvgroup kv_qsa_bkey = 0; /* created by the first QSA layer's declare() */ + + int64_t n_rot = 0; + int64_t n_run = 0; /* layers this step actually issues; the bisect truncates it */ + + rad_kvgroup kv_full = 0, kv_state = 0, kv_conv = 0; + /* PLE lives on exactly one layer; -1 when the checkpoint has none or this build does not + * declare that layer. */ + PleLayer ple; + int64_t ple_layer = -1; + + /* THE WIDE STREAM and the narrow block input. `b_h` is the residual stream -- hc * n_embd a + * token -- and `a_x` is what a connection's read produces and what the block it fronts writes + * its delta back into. One of each for the whole model, as qwen35_fp8 has one `x` and one `h`: + * a connection's read is immediately followed by its block and then by its write, so nothing + * in `a_x` or `b_inj` has to survive past the write that consumes it. DECLARATION ORDER IS + * WHAT THE BUFFER PLANNER'S LIVENESS IS (see the note at declare()), so that sentence is a + * statement about this file's order and not a hope. */ + rad_buf b_h = 0; + ActFP8 a_x{}; + rad_buf b_inj = 0; + + /* the attention block's own activations, shared across the 12 attention layers */ + rad_buf b_qg = 0, b_k = 0, b_v = 0, b_q = 0, b_rope_cs = 0, b_gate = 0; + ActFP8 a_attn{}; + + /* the delta net's */ + ActFP8 a_in{}, a_go{}; + rad_buf b_ab = 0, b_gq = 0, b_gk = 0, b_gv = 0, b_gdec = 0, b_beta = 0, b_kkt = 0; + + /* the routed feed-forward's */ + rad_buf b_rlogits = 0, b_eids = 0, b_ew = 0, b_sorted = 0, b_eoff = 0, b_ecnt = 0; + rad_buf b_egu = 0, b_edn = 0, b_emoe = 0, b_sgu = 0, b_sout = 0, b_sgate = 0; + ActFP8 a_eff{}, a_sff{}; + /* The ROTATED codes of the block input, for the routed arm alone -- only `q` and `s` are used + * and `x` stays zero, because the bf16 it was quantised from is `a_x`'s and is unrotated. + * Declared only when the container asks for a rotation; zero otherwise, which is how the MoE block + * knows the pair is absent. */ + ActFP8 a_hr{}; + + rad_buf b_hout = 0, b_logits = 0; + + /* ---- the multi-token-prediction head (arch/common/rad_block_mtp_hc.h). Declared only when + * the deployment speculates -- it is ~2.5 GiB of weights a non-speculative server would read + * off disk, place in VRAM and never issue, and `max_spec` is the engine already saying whether + * it intends to draft. rad-convert declares at a non-zero max_spec on purpose, because a + * CONTAINER should carry what the model can serve even when the run that made it would not. */ + bool have_mtp = false; + MtpHcBlock mtp{}; + rad_buf b_mtp_hin = 0, b_mtp_hw = 0, b_mtp_e = 0, b_mtp_hout = 0; + rad_buf b_mtp_dq = 0, b_mtp_ds = 0, b_mtp_dsum = 0; + rad_buf b_mtp_dlog = 0, b_mtp_didx = 0, b_mtp_dval = 0; + rad_buf b_mtp_dpair = 0, b_mtp_dgath = 0; + + HcEnter enter; + HyperConn mixer; /* the 97th connection: no write half */ + + std::vector layers; + + rad_weight w_tok = 0, w_lm_head = 0; + rad_op op_embed = 0, op_embed_ar = 0, op_rope_cs = 0, op_gather = 0, op_logits = 0; + + /* ---- media (arch/common/rad_block_vit.h): the vision tower an encoder pass runs, and the + * scatter that puts its rows over the token embeddings. Declared only when the container + * carries a tower and the deployment asked for media (RadBuildCtx::max_enc_patches). */ + bool media = false; + VisionTower vit{}; + MediaRows mrows{}; + +}; + +static Model g_model[MAX_RANKS]; + +static inline bool is_full_attention(int64_t l, int64_t interval) { + return interval > 0 && ((l + 1) % interval == 0); +} + +/* THE CONTAINER'S OWN SCHEDULE, CHECKED AGAINST THE ONE WE DERIVE -- qwen35_fp8 argues this at + * length and the argument is identical here, with one addition: Qwen4-Exp's config says + * "full_attention" for the layers that actually run QSA (the HuggingFace post_init rewrites them to + * "qwen_sparse_attention" in memory and the file on disk says the former), so BOTH spellings are + * accepted for a full layer and neither is accepted for a linear one. */ +static int check_layer_schedule(const RadModelMeta* meta, int64_t n_layer, int64_t interval) { + const char* s = rad_meta_gets(meta, "text_config.layer_types", nullptr); + if (!s) s = rad_meta_gets(meta, "layer_types", nullptr); + if (!s || !*s) return RAD_OK; + + int64_t l = 0; + const char* p = s; + while (*p && l < n_layer) { + while (*p == ' ') ++p; + if (!*p) break; + const char* e = p; + while (*e && *e != ' ') ++e; + const size_t n = (size_t)(e - p); + const bool says_full = (n == 15 && std::strncmp(p, "full_attention", 14) == 0) || + (n == 14 && std::strncmp(p, "full_attention", 14) == 0) || + (n == 22 && std::strncmp(p, "qwen_sparse_attention", 21) == 0) || + (n == 21 && std::strncmp(p, "qwen_sparse_attention", 21) == 0); + const bool says_lin = (n == 17 && std::strncmp(p, "linear_attention", 16) == 0) || + (n == 16 && std::strncmp(p, "linear_attention", 16) == 0); + if (!says_full && !says_lin) { + fprintf(stderr, "radiance: qwen4exp: layer_types[%lld] is '%.*s', which is neither a " + "linear_attention nor a full/sparse attention layer\n", + (long long)l, (int)n, p); + return RAD_E_UNSUPPORTED; + } + if (says_full != is_full_attention(l, interval)) { + fprintf(stderr, "radiance: qwen4exp: the container says layer %lld is %s and the " + "interval rule (every %lld-th) says %s. The schedule decides which " + "layers are linear, so a disagreement is a different model.\n", + (long long)l, says_full ? "full attention" : "linear", + (long long)interval, is_full_attention(l, interval) ? "full" : "linear"); + return RAD_E_UNSUPPORTED; + } + ++l; + p = e; + } + if (l != n_layer) { + fprintf(stderr, "radiance: qwen4exp: layer_types names %lld layers and the container has " + "%lld\n", (long long)l, (long long)n_layer); + return RAD_E_UNSUPPORTED; + } + return RAD_OK; +} + +/* An env switch that is OFF unless set to something other than "0". Spelled once because there are + * four of them and each one is a statement that the model being run is not the model on disk. */ +/* HOW MANY ROWS THE N-GRAM TABLE HAS, and it is a prime search because the checkpoint's own answer + * arrives too late. + * + * Each of the `heads` hash heads gets its own vocabulary: the 1st, 2nd, ... nth prime above + * `ngram_vocab_size_base - 1`. The table is their sum, padded to `divisor`. The reference builds + * exactly this in `Qwen4ExpTextNGramEmbedding.__init__` and the resulting per-head sizes ARE in the + * checkpoint -- `ngram_heads_vocab_sizes` -- which is where the served hash reads them from, and + * nothing here re-derives those. + * + * WHAT IS DERIVED IS THE TOTAL, and only because a weight's shape must be declared before any + * tensor has been opened. Getting it wrong would ship a container whose directory claims one row + * count and carries another's bytes, so rad-convert refuses exactly that: the declared leading + * extent of a multi-source concat has to equal its sources'. This search is checked against 128 + * shards of real bytes on every convert. + * + * The cost is 16 primes near 2e7 by trial division -- a few hundred thousand divisions, once, at + * declare. */ +static bool ngram_is_prime(int64_t v) { + if (v < 2) return false; + if (v % 2 == 0) return v == 2; + for (int64_t d = 3; d * d <= v; d += 2) + if (v % d == 0) return false; + return true; +} + +static int64_t ngram_table_rows(int64_t base, int64_t heads, int64_t divisor) { + if (base <= 1 || heads <= 0) return 0; + int64_t total = 0, p = base - 1; + for (int64_t i = 0; i < heads; ++i) { + do { ++p; } while (!ngram_is_prime(p)); + total += p; + } + return divisor > 1 ? ((total + divisor - 1) / divisor) * divisor : total; +} + +static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { + if (!b || !meta || !ctx) return RAD_E_INVAL; + if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL; + + /* A SIZING DECLARE WRITES SCRATCH. The step reads g_model, which the real declare filled at + * the real max_tok; one sized for a smaller step must not replace it (RadBuildCtx). */ + static thread_local Model probe_model; + Model& m = ctx->shape_probe ? probe_model : g_model[ctx->rank]; + m = Model{}; + m.nm = Names(ctx->scope ? ctx->scope : ""); + Names& nm = m.nm; + + RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16)); + Geom& g = m.g; + + /* Qwen4-Exp's norms are all `x_hat * (1 + w)` -- `Qwen3NextRMSNorm.forward` is + * `_norm(x.float()) * (1.0 + weight.float())` with the weight initialised to ZEROS -- and its + * delta net's gated output norm is the plain `weight * x` with weights initialised to ONES. + * That is read off the reference rather than inferred from the checkpoint: one answer, from + * the source. */ + g.wadd = 1.0f; + g.wadd_qk = 1.0f; + + /* ---- the gated residual's geometry. */ + m.hccfg.hc = meta_int2(meta, "qwen4exp.hc_count", "hc_count", 0); + m.hccfg.lowrank = meta_int2(meta, "qwen4exp.hc_lowrank", "hc_lowrank", 0); + if (m.hccfg.hc <= 1 || m.hccfg.lowrank <= 0) { + fprintf(stderr, "radiance: qwen4exp: the container does not describe the gated residual " + "(hc_count %lld, hc_lowrank %lld). Every norm in this architecture is one " + "of these connections, so there is nothing to fall back to.\n", + (long long)m.hccfg.hc, (long long)m.hccfg.lowrank); + return RAD_E_INVAL; + } + /* EVERY BLOCK'S ALL-REDUCE RIDES IN THE WRITE THAT FOLLOWS IT, wherever a kernel serves that + * (HyperConn::Config::reduce): the block's partial sum is the write's input, so the pair + * becomes one launch. The blocks are told below, per connection, whether it resolved. */ + m.hccfg.reduce = 1; + const int64_t HN = m.hccfg.hc * g.n_embd; + + /* ---- partial rotary. 0.25 of head_dim 256 is 64, and the other 192 dims pass through. */ + { + const double pr = rad_meta_getf(meta, "text_config.rope_parameters.partial_rotary_factor", + rad_meta_getf(meta, "rope_parameters.partial_rotary_factor", + rad_meta_getf(meta, "partial_rotary_factor", 1.0))); + m.n_rot = (int64_t)((double)g.head_dim * pr); + if (m.n_rot <= 0 || m.n_rot > g.head_dim || (m.n_rot % 2)) { + fprintf(stderr, "radiance: qwen4exp: partial_rotary_factor %.6g of head_dim %lld is " + "%lld rotary dims, which is not an even count in (0, head_dim]\n", + pr, (long long)g.head_dim, (long long)m.n_rot); + return RAD_E_INVAL; + } + } + /* THERE IS NO BRING-UP SLICE, and the rule is worth stating: if a model ever arrives too large + * for the target device, the answer is a converter flag that writes a NAMED partial container + * -- not an environment variable that makes a full one silently mean something else. A slice + * declared at serve time is a server computing something that is not the model while looking + * exactly like one that is. */ + + /* ---- the layer schedule. */ + const int64_t interval = meta_int2(meta, "qwen4exp.full_attention_interval", + "full_attention_interval", 0); + if (interval <= 1) { + fprintf(stderr, "radiance: qwen4exp: full_attention_interval is %lld; this is a hybrid " + "architecture and the interval decides which layers are linear\n", + (long long)interval); + return RAD_E_INVAL; + } + /* The container's `layer_types` names every layer of the WHOLE model, and the count check + * inside is against the layer count passed here rather than against the array's length. */ + RAD_ARCH_TRY(check_layer_schedule(meta, g.n_layer, interval)); + + /* ---- the delta net. */ + { + GdnFP8::Config& gc = m.gcfg; + const int64_t nk = meta_int2(meta, "qwen4exp.ssm.key_head_count", + "linear_num_key_heads", 0); + const int64_t nv = meta_int2(meta, "qwen4exp.ssm.value_head_count", + "linear_num_value_heads", 0); + gc.head_k = meta_int2(meta, "qwen4exp.ssm.key_head_dim", "linear_key_head_dim", 0); + gc.head_v = meta_int2(meta, "qwen4exp.ssm.value_head_dim", "linear_value_head_dim", 0); + gc.conv_width = meta_int2(meta, "qwen4exp.ssm.conv_kernel", "linear_conv_kernel_dim", 0); + gc.chunk = 64; + /* `output_gate_type` is a CHECKPOINT property: Qwen3.5/3.6 leave it unset and mean silu, + * Qwen4-Exp states "sigmoid". libr4d's gated norm has both arms. */ + const char* ogt = rad_meta_gets(meta, "text_config.output_gate_type", + rad_meta_gets(meta, "output_gate_type", nullptr)); + if (!ogt || !*ogt) ogt = rad_meta_gets(meta, "text_config.hidden_act", + rad_meta_gets(meta, "hidden_act", "silu")); + gc.act = ogt; + if (nk <= 0 || nv <= 0 || gc.head_k <= 0 || gc.head_v <= 0 || gc.conv_width <= 0) { + fprintf(stderr, "radiance: qwen4exp: 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)nk, (long long)nv, (long long)gc.head_k, (long long)gc.head_v, + (long long)gc.conv_width); + return RAD_E_INVAL; + } + int s; + if ((s = divide_or_fail(nk, g.world, "linear_num_key_heads", &gc.n_head_k)) < 0) return s; + if ((s = divide_or_fail(nv, g.world, "linear_num_value_heads", &gc.n_head_v)) < 0) return s; + } + + /* ---- the routed feed-forward. + * + * n_ff is `moe_intermediate_size` and geom_from already divided it by world_size -- and that + * division is exactly what the header's tensor-parallel section is about. */ + { + MoeFP8::Config& mc = m.moecfg; + mc.n_expert = meta_int2(meta, "qwen4exp.expert_count", "num_experts", 0); + mc.top_k = meta_int2(meta, "qwen4exp.expert_used_count", "num_experts_per_tok", 0); + mc.n_ff_exp = g.n_ff; + mc.n_ff_shared = meta_int2(meta, "qwen4exp.expert_shared_feed_forward_length", + "shared_expert_intermediate_size", 0); + /* THE SHARED ARM IS SPLIT BY WHOLE fp8 SCALE BLOCKS: evenly when its width halves into + * them, and otherwise as evenly as whole blocks allow -- this family's 640 columns are + * five blocks, three on rank 0 and two on rank 1. See MoeFP8::Config::shared_lo. */ + if (mc.n_ff_shared > 0 && g.world > 1 && (mc.n_ff_shared / g.world) % RAD_FP8_BLOCK == 0) { + int s; + if ((s = divide_or_fail(mc.n_ff_shared, g.world, + "shared_expert_intermediate_size", &mc.n_ff_shared)) < 0) + return s; + } else if (mc.n_ff_shared > 0 && g.world > 1) { + if (mc.n_ff_shared % RAD_FP8_BLOCK) { + fprintf(stderr, "radiance: the shared expert is %lld columns, which is not a whole " + "number of %d-column fp8 scale blocks, so it cannot be split " + "across %d ranks.\n", (long long)mc.n_ff_shared, RAD_FP8_BLOCK, + g.world); + return RAD_E_INVAL; + } + const int64_t nb = mc.n_ff_shared / RAD_FP8_BLOCK; + const int64_t base = nb / g.world, extra = nb % g.world; + const int64_t b0 = (int64_t)g.rank * base + std::min(g.rank, extra); + const int64_t b1 = b0 + base + ((int64_t)g.rank < extra ? 1 : 0); + mc.shared_lo = b0 * RAD_FP8_BLOCK; + mc.shared_hi = b1 * RAD_FP8_BLOCK; + mc.n_ff_shared = mc.shared_hi - mc.shared_lo; + rad_note(b, "the shared expert does not halve into %d-column fp8 scale blocks, so rank " + "%d computes columns [%lld, %lld) of it -- %lld of %lld blocks -- and the " + "block's all-reduce sums the ranks' partials.", RAD_FP8_BLOCK, g.rank, + (long long)mc.shared_lo, (long long)mc.shared_hi, (long long)(b1 - b0), + (long long)nb); + } + mc.norm_topk = 1; + /* THE GPTQ CALIBRATION RUN, gated by the same variable that says where to write: there is + * no second switch, because a calibration with nowhere to put its answer is a 1.34 GB + * allocation and two extra launches a layer for nothing. It is a separate run from + * serving -- see MoeFP8::Config::calib. */ + mc.calib = calib_dir() != nullptr ? 1 : 0; + /* Tokens a pass. 2048 is the linear-state checkpoint interval this family's scheduler + * clamps the prefill chunk to, so the shipped configuration is ONE pass and the slicing is + * inert -- but it also sizes four buffers at `rows * top_k`, so a deployment whose + * max_tok is smaller must not pay for rows it cannot present. */ + mc.rows = g.max_tok < 2048 ? g.max_tok : 2048; + if (mc.n_expert <= 0 || mc.top_k <= 0 || mc.top_k > mc.n_expert) { + fprintf(stderr, "radiance: qwen4exp: the container describes %lld expert(s) with " + "top_k %lld\n", (long long)mc.n_expert, (long long)mc.top_k); + return RAD_E_INVAL; + } + /* ---- THE EXPERTS' STORED FORMAT -- block fp8, four-bit, four-bit rotated, or the + * checkpoint's plain bf16 -- read off one expert's encoding (MoeFP8::probe) before anything + * is sized by it: how the experts are split between the ranks, the rotated copy of the + * block input, the connection in front of every routed block, and -- for bf16 -- every + * linear in the model. It is the container's, the checkpoint's, or the recipe's that + * rad-convert is applying, so a container cannot be served in a format other than the one + * it holds. + * + * THE EXPERT ASKED IS THE FIRST ONE THIS RANK OWNS UNDER EXPERT PARALLELISM. The answer + * decides whether the experts are split that way, so it has to be asked before; and the + * expert is declared on this rank either way -- whole under expert parallelism, a slice of + * it under the parity split -- so the block skips exactly the map the probe made. */ + mc.probed_expert = (g.world > 1 && mc.n_expert % g.world == 0) + ? (int64_t)g.rank * (mc.n_expert / g.world) : 0; + { + MoeFP8::Src ps{}; + ps.experts_gate_up = nm.ckpt("model.language_model.layers.0.mlp.experts.gate_up_proj"); + ps.experts_down = nm.ckpt("model.language_model.layers.0.mlp.experts.down_proj"); + RAD_ARCH_TRY(MoeFP8::probe(b, nm, 0, ps, &mc)); + } + /* A CHECKPOINT SERVED AS IT SHIPS IS bf16 THROUGHOUT. Plain experts mean a container + * converted without a quantising recipe, and every linear of it is then plain too: the + * blocks issue bf16 GEMMs over the bf16 activation and nothing in front of them quantises + * (Geom::w_bf16). Each linear checks its own encoding against this and refuses a quantised + * one. The other way round is allowed: a quantised container may keep a linear plain -- + * the QSA indexer's projection -- and LinearFP8 reads that one as bf16. */ + g.w_bf16 = mc.expert_bf16 != 0; + /* ...and the connections in front of the blocks emit no codes, since nothing reads any. */ + m.hccfg.quant = g.w_bf16 ? 0 : 1; + /* ============================== EVERY RANK HOLDS A SLICE OF EVERY EXPERT ============================== + * + * An expert of this model is 640 columns, five 128-column blocks -- the fp8 scale block, + * the 4-bit plane's scale group and the rotation's width all at once -- so two ranks + * cannot halve one. Each rank takes three blocks of the experts of one parity and two of + * the other's: rank r's slice of expert e is the first three blocks when e % 2 == r and + * the last two otherwise (MoeFP8::Config::ff_lo says why by parity). The router stays + * replicated, every rank computes its slice of every routed expert, and the block's + * all-reduce sums the partials. + * + * WHY NOT EXPERT PARALLELISM, which splits the EXPERTS: rank r owns [r*E/W, (r+1)*E/W) + * whole. The bytes a rank reads are the same on average either way, but which rank a + * routed expert lands on is a coin flip, and a verify step's forty routed slots leave one + * rank about five experts ahead -- which the all-reduce turns into the other rank waiting, + * about a millisecond a step at one sequence. Split by parity the ranks differ by a fifth + * of an expert per unit of the even/odd difference instead. + * + * A width that divides into whole blocks at the rank count is split evenly and has one + * slice; five blocks at more than two ranks would need more slices than two parities, and + * is refused by name. + * + * A CALIBRATION RUN SPLITS THE EXPERTS INSTEAD, whole experts per rank. The down + * projection's Hessian is over an expert's whole K, and a rank holding a slice of each + * expert has only its slice's block of it -- the cross terms live on the other rank. Whole + * experts give each rank the Hessian of every expert it holds, which is what the packer + * sums (rad_arch.h's calib_dir). */ + mc.n_expert_all = mc.n_expert; + /* AND bf16 EXPERTS ARE SPLIT THE SAME WAY, whole experts per rank: a slice of a bf16 expert + * is two row ranges and a column range of the container, which the file tier cannot read + * as one run, and nothing about bf16 needs the parity split's balance -- a bf16 model is + * served to calibrate and to compare, not for its decode rate. */ + if (g.world > 1 && (mc.calib || mc.expert_bf16)) { + int s; + int64_t per = 0; + if ((s = divide_or_fail(mc.n_expert_all, g.world, "expert_count", &per)) < 0) return s; + mc.n_ff_exp = g.n_ff_all; + mc.n_expert = per; + mc.expert_base = (int64_t)g.rank * per; + rad_note(b, "%s: rank %d owns experts [%lld, %lld) of %lld whole.", + mc.calib ? "calibration (each expert's Hessian is over its whole width)" + : "bf16 experts", g.rank, + (long long)mc.expert_base, (long long)(mc.expert_base + mc.n_expert), + (long long)mc.n_expert_all); + } else if (g.world > 1) { + if (g.n_ff_all % RAD_FP8_BLOCK) { + fprintf(stderr, "radiance: qwen4exp: an expert is %lld columns, which is not a whole " + "number of %d-column blocks and cannot be split across ranks.\n", + (long long)g.n_ff_all, RAD_FP8_BLOCK); + return RAD_E_INVAL; + } + const int64_t nb = g.n_ff_all / RAD_FP8_BLOCK; + if (nb % g.world == 0) { + mc.n_ff_exp = g.n_ff_all / g.world; + } else if (g.world == 2) { + const int64_t base = nb / 2, extra = nb % 2; + for (int q = 0; q < 2; ++q) { + /* This rank's place in expert parity q's split: first for its own parity. */ + const int64_t p = (g.rank - q + 2) % 2; + const int64_t b0 = p * base + std::min(p, extra); + const int64_t b1 = b0 + base + (p < extra ? 1 : 0); + mc.ff_lo[q] = b0 * RAD_FP8_BLOCK; + mc.ff_hi[q] = b1 * RAD_FP8_BLOCK; + } + mc.n_ff_exp = std::max(mc.ff_hi[0] - mc.ff_lo[0], mc.ff_hi[1] - mc.ff_lo[1]); + rad_note(b, "routed experts: rank %d computes columns [%lld, %lld) of each even " + "expert and [%lld, %lld) of each odd one, of %lld. The width is %lld " + "blocks of %d, which two ranks split unevenly, so the rank taking the " + "extra block alternates with the expert's parity; the block's " + "all-reduce sums the partials.", + g.rank, (long long)mc.ff_lo[0], (long long)mc.ff_hi[0], + (long long)mc.ff_lo[1], (long long)mc.ff_hi[1], (long long)g.n_ff_all, + (long long)nb, RAD_FP8_BLOCK); + } else { + fprintf(stderr, "radiance: qwen4exp: an expert is %lld blocks of %d, which %d ranks " + "cannot split into two slices; the uneven split alternates by " + "parity and so serves two ranks.\n", + (long long)nb, RAD_FP8_BLOCK, g.world); + return RAD_E_INVAL; + } + } + } + + + /* ---- the n-gram embedding's layer and the indexer's geometry, each stated in a note where it + * changes what this build computes. */ + { + const char* ple = rad_meta_gets(meta, "text_config.ple_layer_ids", + rad_meta_gets(meta, "ple_layer_ids", nullptr)); + if (ple && *ple) { + /* ONE-INDEXED, and the whole layer hangs off getting that right: `ple_layer_ids: [2]` + * is layer_idx 1. The reference says so twice -- `config.ple_layer_ids.index(layer_idx + * + 1)` at construction and a [1, num_hidden_layers] bound in the validator. */ + m.ple_layer = (int64_t)std::strtoll(ple, nullptr, 10) - 1; + if (m.ple_layer < 0 || m.ple_layer >= g.n_layer) { + /* Out of the declared range, which a DECL_LAYERS slice makes ordinary: the layer + * simply is not in this build. Said rather than skipped, because a slice that + * silently drops PLE looks exactly like one that has it. */ + rad_note(b, "ple_layer_ids = %s is outside the %lld layers declared, so the n-gram " + "embedding is not in this build.", ple, (long long)g.n_layer); + m.ple_layer = -1; + } + } + } + { + const int64_t budget = meta_int2(meta, "qwen4exp.indexer_budget", "indexer_budget", 0); + const int64_t ratio = meta_int2(meta, "qwen4exp.indexer_compress_ratio", + "indexer_compress_ratio", 0); + m.qsacfg.budget = budget; + m.qsacfg.ratio = ratio; + m.qsacfg.heads = meta_int2(meta, "qwen4exp.indexer_n_heads", "indexer_n_heads", 0); + m.qsacfg.head_dim = meta_int2(meta, "qwen4exp.indexer_head_dim", "indexer_head_dim", 0); + m.qsacfg.rot = m.n_rot; + m.qsacfg.topk = (ratio > 0) ? budget / ratio : 0; + m.qsacfg.max_blocks = (ratio > 0) ? (g.max_ctx + ratio - 1) / ratio : 0; + m.qsacfg.max_work = (ratio > 0) ? (g.max_tok + ratio - 1) / ratio + g.max_seqs : 0; + /* The tail's ring, and QsaIndexer::Config::ring is where the arithmetic is argued. It is + * `max_spec` and not `n_spec`: a deployment that can speculate three deep sizes for + * three, whatever a given step turns out to carry. */ + m.qsacfg.ring = ratio + g.max_spec; + if (budget > 0 && ratio > 0) { + /* THE EXACTNESS BOUND, and it is the whole reason dense attention is not an + * approximation here: with `pos + 1 <= budget + ratio - 1` tokens visible, the number + * of COMPLETE blocks is at most budget/ratio, the indexer's top-k keeps all of them, + * and the tail is attended unconditionally -- so the selected set is every visible + * token and QSA is dense causal attention bit for bit. */ + const int64_t exact_to = budget + ratio - 1; + /* THERE IS NO CAP ON `--max-ctx` HERE. Prefill selects per query exactly as decode + * does (arch/common/rad_qsa.h, docs/QSA.md), so above the bound this runs the model's + * own attention rather than a denser stand-in -- and there is no force-dense switch, + * because above the bound the dense path is NOT the trained attention and such a + * switch would make a server quietly serve a different model. */ + if (g.max_ctx > exact_to) + rad_note(b, "QSA: sparse past %lld tokens of context -- %lld blocks of %lld a " + "query, selected per query at prefill and at decode. At or below that " + "the selection is every visible block and the engine issues the " + "cheaper dense attention, which is the same answer to the bit.", + (long long)exact_to, (long long)(budget / ratio), (long long)ratio); + else + rad_note(b, "QSA: dense attention is EXACT to %lld tokens of context and " + "--max-ctx is %lld, so the indexer selects every visible block " + "and changes nothing.", (long long)exact_to, (long long)g.max_ctx); + } + } + + rad_note(b, "gated residual: %lld streams of %lld (%lld wide), low-rank gate %lld; %lld " + "connections plus the mixer", + (long long)m.hccfg.hc, (long long)g.n_embd, (long long)HN, + (long long)m.hccfg.lowrank, (long long)(2 * g.n_layer)); + + /* ---- the KV groups. Same three as qwen35_fp8 and for the same reasons. */ + { + 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); + + RadKVGroupDecl sd{}; + sd.kind = RAD_KV_LINEAR; + sd.dtype = RAD_F32; /* f16 trades draft acceptance for a sliver of step time */ + sd.n_head_kv = m.gcfg.n_head_v; + sd.state_dim[0] = m.gcfg.head_v; + sd.state_dim[1] = m.gcfg.head_k; + m.kv_state = rad_decl_kv_group(b, nm.f("kv_gdn_state"), &sd); + + RadKVGroupDecl cd{}; + cd.kind = RAD_KV_CONV; + cd.dtype = RAD_BF16; + cd.n_head_kv = 2 * m.gcfg.n_head_k + m.gcfg.n_head_v; + cd.head_dim = m.gcfg.head_k; + cd.conv_width = m.gcfg.conv_width; + m.kv_conv = rad_decl_kv_group(b, nm.f("kv_gdn_conv"), &cd); + if (!m.kv_full || !m.kv_state || !m.kv_conv) return RAD_E_INVAL; + + /* ---- the QSA indexer's TAIL, which is state and not a buffer. + * + * It carries an unfinished block's raw index keys across steps, so it has to be indexed + * by the SEQUENCE and by the LAYER -- and a buffer can express neither. The batch row is + * step-local and the keys are per-layer; arch/common/rad_qsa.h's Wire is the full + * argument. As a linear group the engine keeps a slot stable for the life of a sequence, + * zeroes it when it hands one out, and saves and restores it with the rest of the linear + * state when the prefix cache checkpoints -- which is also the only thing that makes a + * resume onto a half-built block read anything defined. + * + * `n_head_kv` 1 and `state_dim` {ring, head_dim}: one state is `ring` raw keys, a few + * kilobytes a layer a sequence. */ + if (m.qsacfg.heads > 0 && m.qsacfg.head_dim > 0 && m.qsacfg.ring > 0) { + RadKVGroupDecl td{}; + td.kind = RAD_KV_LINEAR; + td.dtype = g.act_dtype; + td.n_head_kv = 1; + td.state_dim[0] = m.qsacfg.ring; + td.state_dim[1] = m.qsacfg.head_dim; + m.qsacfg.kv_tail = rad_decl_kv_group(b, nm.f("kv_qsa_tail"), &td); + if (!m.qsacfg.kv_tail) return RAD_E_INVAL; + } + } + + /* ---- THE TRUNK'S STORED FORMAT, read off the first delta-net layer's input projection the way + * the experts' is read off one expert: the activation buffers below carry an int8 code pair + * only when the trunk's linears are int8 (LinearFP8::i8), so it has to be known before they + * are declared. The probe maps that weight through the layer's own LinearFP8, which then does + * not map it again. */ + m.layers.resize((size_t)g.n_layer); + { + const char* pre0 = "model.language_model.layers"; + for (int64_t l = 0; l < g.n_layer; ++l) { + if (is_full_attention(l, interval)) continue; + RAD_ARCH_TRY(m.layers[(size_t)l].gdn.in.probe( + b, nm, g, nm.f("blk.%lld.ssm_inz", (long long)l), + { nm.ckpt("%s.%lld.linear_attn.in_proj_qkv.weight", pre0, (long long)l), + nm.ckpt("%s.%lld.linear_attn.in_proj_z.weight", pre0, (long long)l) })); + m.trunk_i8 = m.layers[(size_t)l].gdn.in.probed_i8; + break; + } + } + + /* ---- buffers. */ + const int64_t q_dim = g.q_dim(); + const int64_t kv_dim = g.kv_dim(); + const int64_t v_dim = m.gcfg.v_dim(); + const int64_t conv_dim = m.gcfg.conv_dim(); + const int64_t T = g.max_tok; + const int64_t ER = m.moecfg.rows * m.moecfg.top_k; + + m.b_h = decl_b(b, nm.f("h_wide"), g.act_dtype, {T, HN}); + m.a_x.x = decl_b(b, nm.f("x"), g.act_dtype, {T, g.n_embd}); + RAD_ARCH_TRY(m.a_x.declare_qs(b, nm, g, "x", g.n_embd, 0, m.trunk_i8)); + /* THE CONNECTIONS WRITE THE INT8 CODES THEMSELVES when every reader of their codes is an int8 + * linear: the trunk's are, and the routed experts read the rotated twin (or the bf16 plane), + * never these. Experts that read the plain E4M3 codes keep them, and the int8 linears then + * quantise for themselves. */ + m.hccfg.codes_i8 = (m.trunk_i8 && (m.moecfg.expert_rot || m.moecfg.expert_bf16)) ? 1 : 0; + m.a_x.q8_fed = m.hccfg.codes_i8 != 0; + m.b_inj = decl_b(b, nm.f("hc_inj"), g.act_dtype, {T, m.hccfg.hc}); + + m.b_qg = decl_b(b, nm.f("attn_qg"), g.act_dtype, {T, g.n_head, 2 * g.head_dim}); + m.b_k = decl_b(b, nm.f("attn_k"), g.act_dtype, {T, kv_dim}); + m.b_v = decl_b(b, nm.f("attn_v"), g.act_dtype, {T, kv_dim}); + m.b_q = decl_b(b, nm.f("attn_q"), g.act_dtype, {T, q_dim}); + m.a_attn.x = decl_b(b, nm.f("attn_out"), g.act_dtype, {T, q_dim}); + RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", q_dim, 0, m.trunk_i8)); + /* The gate epilogue in front of the int8 out projection writes its int8 codes itself. */ + m.a_attn.q8_fed = m.trunk_i8; + /* The bf16 gate's own plane (AttnGatedFP8::Wire::gate); the fp8 path fuses it away. */ + if (g.w_bf16) m.b_gate = decl_b(b, nm.f("attn_gate"), g.act_dtype, {T, q_dim}); + /* THE QSA INDEXER'S TWO PLANES, shared by every full-attention layer the way `attn_out` is. + * Declared only when the checkpoint carries an indexer, so a container without one allocates + * nothing and the layer's declare() is a no-op. */ + if (m.qsacfg.heads > 0 && m.qsacfg.head_dim > 0) { + m.qsaw.qk = decl_b(b, nm.f("qsa_qk"), g.act_dtype, + { g.max_tok, (m.qsacfg.heads + 1) * m.qsacfg.head_dim }); + m.qsaw.q = decl_b(b, nm.f("qsa_q"), g.act_dtype, + { g.max_tok, m.qsacfg.heads * m.qsacfg.head_dim }); + const int64_t hd = m.qsacfg.head_dim, rt = m.qsacfg.ratio, wk = m.qsacfg.max_work; + m.qsaw.stage = decl_b(b, nm.f("qsa_stage"), g.act_dtype, { wk * rt, hd }); + m.qsaw.page = decl_b(b, nm.f("qsa_page"), RAD_I32, { wk }); + /* Three components a block under M-RoPE (arch/common/rad_qsa.h). */ + m.qsaw.bpos = g.rope_mc ? decl_b(b, nm.f("qsa_bpos"), RAD_I32, { wk, 3 }) + : decl_b(b, nm.f("qsa_bpos"), RAD_I32, { wk }); + m.qsaw.nc = decl_b(b, nm.f("qsa_nc"), RAD_I32, { g.max_seqs }); + /* ONE ROW A QUERY, not one a sequence -- QSA Stage B, arch/common/rad_qsa.h. The score + * plane is the only buffer in this model whose size is a PRODUCT of the two deployment + * bounds, so it is refused here by name rather than discovered as an allocation failure + * halfway through the arena: 2 GiB is already an absurd answer and the message says which + * two flags produced it. */ + const int64_t sc_elems = g.max_tok * m.qsacfg.max_blocks; + if (sc_elems > (int64_t)512 * 1024 * 1024) { + fprintf(stderr, + "radiance: qwen4exp: the QSA score plane would be %lld MiB -- " + "--max-num-batched-tokens %lld by --max-ctx %lld / compress ratio %lld. " + "Lower either.\n", + (long long)(sc_elems * 4 / (1024 * 1024)), (long long)g.max_tok, + (long long)g.max_ctx, (long long)m.qsacfg.ratio); + return RAD_E_UNSUPPORTED; + } + m.qsaw.score = decl_b(b, nm.f("qsa_score"), RAD_F32, + { g.max_tok, m.qsacfg.max_blocks }); + m.qsaw.sel = decl_b(b, nm.f("qsa_sel"), RAD_I32, + { g.max_tok, m.qsacfg.topk + 1 }); + m.qsaw.nsel = decl_b(b, nm.f("qsa_nsel"), RAD_I32, { g.max_tok }); + m.qsaw.sequ = decl_b(b, nm.f("qsa_sequ"), RAD_I32, { g.max_tok }); + if (!m.qsaw.qk || !m.qsaw.q || !m.qsaw.stage || !m.qsaw.page || + !m.qsaw.bpos || !m.qsaw.nc || !m.qsaw.score || !m.qsaw.sel || !m.qsaw.nsel || + !m.qsaw.sequ) + return RAD_E_INVAL; + } + + m.a_in.x = decl_b(b, nm.f("gdn_in"), g.act_dtype, {T, conv_dim + v_dim}); + RAD_ARCH_TRY(m.a_in.declare_qs(b, nm, g, "gdn_in", conv_dim + v_dim)); + m.b_ab = decl_b(b, nm.f("gdn_ab"), g.act_dtype, {T, m.gcfg.ab_dim()}); + m.b_gq = decl_b(b, nm.f("gdn_q"), g.act_dtype, {T, m.gcfg.n_head_k, m.gcfg.head_k}); + m.b_gk = decl_b(b, nm.f("gdn_k"), g.act_dtype, {T, m.gcfg.n_head_k, m.gcfg.head_k}); + m.b_gv = decl_b(b, nm.f("gdn_v"), g.act_dtype, {T, m.gcfg.n_head_v, m.gcfg.head_v}); + /* F32 AND NOT THE ACTIVATION DTYPE, both of them, and the kernels say so rather than tolerate + * it: `gdn_conv_prep` ends `R4D_DT(g, RAD_F32); R4D_DT(beta, RAD_F32)`. The log decay is a + * cumulative sum that the chunked scan exponentiates differences of, and beta is its + * companion; bf16's eight mantissa bits are not enough for either. The refusal is + * "dtype this kernel does not serve" at the first step, which is the right failure and not an + * obvious one to read. */ + m.b_gdec = decl_b(b, nm.f("gdn_gdec"), RAD_F32, {T, m.gcfg.n_head_v}); + m.b_beta = decl_b(b, nm.f("gdn_beta"), RAD_F32, {T, m.gcfg.n_head_v}); + m.b_kkt = decl_b(b, nm.f("gdn_kkt"), RAD_BF16, {T, m.gcfg.n_head_v, m.gcfg.chunk}); + m.a_go.x = decl_b(b, nm.f("gdn_o"), g.act_dtype, {T, m.gcfg.n_head_v, m.gcfg.head_v}); + RAD_ARCH_TRY(m.a_go.declare_qs(b, nm, g, "gdn_o", v_dim, 0, m.trunk_i8)); + /* So does the delta net's output epilogue, and its prefill quantiser is the int8 one. */ + m.a_go.q8_fed = m.trunk_i8; + + /* THE MODEL'S expert count, not this rank's: the router is replicated under expert + * parallelism and scores every expert. */ + m.b_rlogits = decl_b(b, nm.f("moe_logits"), g.act_dtype, {T, m.moecfg.n_expert_all}); + m.b_eids = decl_b(b, nm.f("moe_ids"), RAD_I32, {T, m.moecfg.top_k}); + m.b_ew = decl_b(b, nm.f("moe_ew"), g.act_dtype, {T, m.moecfg.top_k}); + m.b_eoff = decl_b(b, nm.f("moe_eoff"), RAD_I32, {m.moecfg.n_expert + 1}); + /* PERSIST, NOT TRANSIENT, and it is the one buffer here that has to be. `moe_scatter` writes + * the per-expert histogram and NO DECLARED OP READS IT -- the reader is rad_route_report, + * which is a handoff and not an op -- so liveness analysis sees it die the instant it is + * written and is free to alias its storage with anything later in the step. Declared + * transient, a wide enough prefill chunk gives the planner something to lay over it and the + * histogram comes back holding values a sum of placements cannot be -- negative counts. A + * small step may miss it entirely, so this is not a fault a short run reveals. + * + * The buffer is one int32 an expert. */ + m.b_ecnt = decl_b(b, nm.f("moe_ecnt"), RAD_I32, {m.moecfg.n_expert}, + RAD_BUF_PERSIST); + m.b_sorted = decl_b(b, nm.f("moe_sorted"), RAD_I32, {ER}); + m.b_egu = decl_b(b, nm.f("moe_egu"), g.act_dtype, {ER, 2 * m.moecfg.n_ff_exp}); + m.a_eff.x = decl_b(b, nm.f("moe_eff"), g.act_dtype, {ER, m.moecfg.n_ff_exp}); + /* ER ROWS, NOT max_tok: this is an EXPERT plane, one row per (token, slot). Taking + * declare_qs's default declares it `top_k` times too short, and the gated quantiser then + * writes that many times past the end of it -- see ActFP8::declare_qs, which is where the + * guard and the argument live. */ + RAD_ARCH_TRY(m.a_eff.declare_qs(b, nm, g, "moe_eff", m.moecfg.n_ff_exp, ER)); + if (m.moecfg.expert_rot) + RAD_ARCH_TRY(m.a_hr.declare_qs(b, nm, g, "moe_hr", g.n_embd)); + m.b_edn = decl_b(b, nm.f("moe_edn"), g.act_dtype, {ER, g.n_embd}); + m.b_emoe = decl_b(b, nm.f("moe_out"), g.act_dtype, {T, g.n_embd}); + if (m.moecfg.n_ff_shared > 0) { + m.b_sgu = decl_b(b, nm.f("moe_sgu"), g.act_dtype, {T, 2 * m.moecfg.n_ff_shared}); + m.a_sff.x = decl_b(b, nm.f("moe_sff"), g.act_dtype, {T, m.moecfg.n_ff_shared}); + RAD_ARCH_TRY(m.a_sff.declare_qs(b, nm, g, "moe_sff", m.moecfg.n_ff_shared, 0, + m.trunk_i8)); + /* And the shared expert's gated quantiser in front of its int8 down projection. */ + m.a_sff.q8_fed = m.trunk_i8; + m.b_sout = decl_b(b, nm.f("moe_sout"), g.act_dtype, {T, g.n_embd}); + m.b_sgate = decl_b(b, nm.f("moe_sgate"), g.act_dtype, {T, 1}); + } + + m.b_hout = decl_b(b, nm.f("hout"), g.act_dtype, {g.max_logit_rows, g.n_embd}); + m.b_logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab}); + RAD_ARCH_TRY(rad_declare_logits(b, m.b_logits)); + + /* ---- the vocabulary edges, both row-sharded as qwen35_fp8 has them. `lm_head.weight` is + * present in this checkpoint (tie_word_embeddings is false), but the alternative spelling + * costs nothing and a smaller member of the family may tie them. + * + * THE HEAD IS DECLARED OVER EVERY PLANE IT HAS, at the codes' dtype: bf16 as the checkpoint + * ships it, block fp8 where a recipe makes it so. Which `logits_gemm` kernel serves it is + * then the selector's -- a kernel whose layout does not read the head's encoding is not a + * candidate -- so one declaration serves both. The maps come first: they are how the model + * is asked what the head is. */ + RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), + nm.ckpt("model.language_model.embed_tokens.weight"))); + RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"), + 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_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()); + if (!m.w_tok || !m.w_lm_head) return RAD_E_INVAL; + + m.op_embed = rw(b, RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, T), 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.a_x.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, T, g.n_embd, m.a_x.x)); + /* EXACT unconditionally: every other collective here sums partial products, this one sums + * DISJOINT rows -- a token's embedding comes from exactly one rank. qwen35_fp8 says the same. */ + 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, T * g.n_embd), + RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)), + RAD_NOWEIGHTS), + {m.a_x.x}, {m.a_x.x}); + + /* THE STREAM'S FIRST VALUE: hc identical copies of the embedding. */ + RAD_ARCH_TRY(m.enter.declare(b, g, m.hccfg.hc, m.a_x.x, m.b_h)); + + /* ---- the layers. + * + * DECLARATION ORDER IS WHAT THE BUFFER PLANNER'S LIVENESS IS: a transient's lifetime is + * [first definition, last use] over OP INDICES in this order, and two transients whose ranges + * are disjoint MAY share bytes (core/build/rad_bufplan.cpp). Every buffer above is shared by + * every layer, so the order below has to be the order step() issues in -- read, block, write, + * read, block, write -- and it is. A connection declared out of that order would make a false + * statement about liveness and the planner would alias two buffers that are both live inside + * one step; the symptom is fluent output with one arm of the model reading the other's + * leftovers, which nothing downstream flags. + */ + m.op_rope_cs = rw(b, RAD_OP(b, "rope_table", + RAD_PARAMS(RAD_RANGE("M", 1, qk_fuse_rows(g)), + RAD_INT("rot", m.n_rot), RAD_F64("theta", g.theta), + RAD_F64("scale", g.rope_scale), RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + {}, {m.b_rope_cs = decl_b(b, nm.f("rope_cs"), RAD_F32, + {rope_table_rows(g), m.n_rot})}); + + AttnGatedFP8::Wire aw{}; + aw.x = m.b_h; aw.h = m.a_x; aw.qg = m.b_qg; aw.k = m.b_k; aw.v = m.b_v; + aw.q = m.b_q; aw.attn = m.a_attn; aw.gate = m.b_gate; + aw.cos_sin = m.op_rope_cs ? m.b_rope_cs : 0; + /* AND THE INDEXER READS THE SAME PLANE. Its rotation is at `m.n_rot`, `g.theta` and + * `g.rope_scale` -- the three the table was built from -- so the rows this step's positions + * name are already written, and the twelve trunk layers plus the head's four passes stop + * issuing `heads` norms and a rope each. Set HERE rather than where `m.qsaw`'s buffers are + * declared because the table is declared after them, and `tw.qsa = m.qsaw` below copies this + * wire to the MTP head, which is how the head's passes get it too. */ + m.qsaw.cos_sin = aw.cos_sin; + + GdnFP8::Wire gw{}; + gw.x = m.b_h; gw.h = m.a_x; gw.in = m.a_in; gw.ab = m.b_ab; + 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.a_go; + + MoeFP8::Wire mw{}; + mw.x = m.b_h; mw.h = m.a_x; mw.hr = m.a_hr; + mw.logits = m.b_rlogits; mw.ids = m.b_eids; mw.ew = m.b_ew; + mw.sorted = m.b_sorted; mw.eoff = m.b_eoff; mw.ecnt = m.b_ecnt; + mw.egu = m.b_egu; mw.eff = m.a_eff; mw.edn = m.b_edn; mw.moe = m.b_emoe; + mw.sgu = m.b_sgu; mw.sff = m.a_sff; mw.sout = m.b_sout; mw.sgate = m.b_sgate; + + HyperConn::Wire hw{}; + hw.h = m.b_h; hw.x = m.a_x; hw.inj = m.b_inj; + + m.layers.resize((size_t)g.n_layer); + const char* pre = "model.language_model.layers"; + for (int64_t l = 0; l < g.n_layer; ++l) { + Layer& lay = m.layers[(size_t)l]; + lay.full = is_full_attention(l, interval) ? 1 : 0; + + /* PLE COMES FIRST, BEFORE THE ATTENTION CONNECTION READS THE STREAM, because the reference + * adds it into `hidden_states` at the top of the decoder layer's forward -- so the gated + * residual that follows normalises a stream the n-gram features are already in. + * + * DECLARATION ORDER IS THE BUFFER PLANNER'S LIVENESS, so this has to be here and not + * hoisted out of the loop: every buffer the block owns is live from here to its `add`, and + * declaring it earlier would overstate that and cost the planner a sharing it could have + * had. The same rule the connections below follow. */ + if (l == m.ple_layer) { + PleLayer::Config pc{}; + pc.hc = m.hccfg.hc; + pc.embed_dim = meta_int2(meta, "qwen4exp.ple_embed_dim", "ple_embed_dim", 0); + pc.ngram = meta_int2(meta, "qwen4exp.ngram_size", "ngram_size", 0); + const int64_t per_ngram = + meta_int2(meta, "qwen4exp.heads_per_ngram", "heads_per_ngram", 0); + pc.heads = (pc.ngram - 1) * per_ngram; + pc.eos = meta_int2(meta, "qwen4exp.eos_token_id", "eos_token_id", -1); + pc.shards = meta_int2(meta, "qwen4exp.split_ngram_parts", "split_ngram_parts", 0); + pc.conv_width = meta_int2(meta, "qwen4exp.ple_conv_kernel_size", + "ple_conv_kernel_size", 0); + /* THE DILATION IS THE N-GRAM SIZE. `conv_dilation = config.ngram_size` in the + * reference's PLE layer -- not a separate key, and not 1. */ + pc.dilation = pc.ngram; + pc.rows = ngram_table_rows( + meta_int2(meta, "qwen4exp.ngram_vocab_size_base", "ngram_vocab_size_base", 0), + pc.heads, + meta_int2(meta, "qwen4exp.make_ngram_vocab_size_divisible_by", + "make_ngram_vocab_size_divisible_by", 1)); + + PleLayer::Wire pw{}; + pw.h = m.b_h; + + PleLayer::Src ps{}; + ps.shard_prefix = nm.ckpt("%s.%lld.ple.ple_embedding.ngram_embedding.shard_", + pre, (long long)l); + ps.shard_suffix = ".weight"; + ps.mult = nm.ckpt("%s.%lld.ple.ple_embedding.layer_multipliers", + pre, (long long)l); + ps.vocab_sizes = nm.ckpt("%s.%lld.ple.ple_embedding.ngram_heads_vocab_sizes", + pre, (long long)l); + ps.offsets = nm.ckpt("%s.%lld.ple.ple_embedding.ngram_heads_offsets", + pre, (long long)l); + ps.key_proj = nm.ckpt("%s.%lld.ple.key_proj.weight", pre, (long long)l); + ps.value_proj = nm.ckpt("%s.%lld.ple.value_proj.weight", pre, (long long)l); + ps.norm_key = nm.ckpt("%s.%lld.ple.norm_key.weight", pre, (long long)l); + ps.norm_query = nm.ckpt("%s.%lld.ple.norm_query.weight", pre, (long long)l); + ps.norm_conv = nm.ckpt("%s.%lld.ple.norm_conv.weight", pre, (long long)l); + ps.conv1d = nm.ckpt("%s.%lld.ple.conv1d.weight", pre, (long long)l); + RAD_ARCH_TRY(m.ple.declare(b, nm, g, pc, (int)l, pw, ps)); + } + + HyperConn::Src mixs{}; + mixs.norm = nm.ckpt("%s.%lld.attn_hyper_connection.hc_norm.weight", pre, (long long)l); + mixs.mix_down = nm.ckpt("%s.%lld.attn_hyper_connection.input_mix_weight_down.weight", + pre, (long long)l); + mixs.mix_up = nm.ckpt("%s.%lld.attn_hyper_connection.input_mix_weight_up.weight", + pre, (long long)l); + mixs.inject_w = nm.ckpt("%s.%lld.attn_hyper_connection.block_inject_weight.weight", + pre, (long long)l); + RAD_ARCH_TRY(lay.hc_mix.declare(b, nm, g, nm.f("blk.%lld.attn_hc", (long long)l), + m.hccfg, hw, mixs)); + + /* `Src::norm = nullptr` is the blocks' "the input is already normed and quantised" mode, + * and `add_out = false` stops them adding into the stream -- the write half of the + * connection does that, with the four gains the read produced. `fold` and `ar_in` are both + * off for the same reason: both fuse into a norm this block does not have. */ + if (lay.full) { + AttnGatedFP8::Src as{}; + 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); + /* THE KV PAGE IS THE QSA COMPRESS BLOCK when that is asked for. A page of 4 makes the + * indexer's selected set a paged block table rather than a new attention kernel + * (docs/QSA.md); the attention kernel's rows have to declare the same 4 or nothing + * resolves, which is what keeps this honest. + * + * A page size is pure storage, so the only thing it can move is the block-table walk: + * a page of 4 and a page of 16 cost the same at long context and produce identical + * text. */ + lay.attn.kv_block = 4; + /* THE SELECTION IS SET BEFORE THE ATTENTION IS DECLARED, and the order is + * load-bearing: `attn_paged` declares `sel` and `seqused` as READS, and a read + * declared after the op is not a read at all -- see rad_block_attn_gated_fp8.h. The + * indexer itself is declared after the attention block (its ops have to sit where the + * sparse attention reads them), which is why the two halves of this are apart. + * + * Below the indexer's budget the selection is every visible block, so the sparse + * and dense paths must produce identical text and a difference is a defect rather + * than a model change. */ + if (m.qsaw.qk) { + lay.attn.qsa_sel = m.qsaw.sel; + lay.attn.qsa_sequ = m.qsaw.sequ; + lay.attn.qsa_topk = m.qsacfg.topk; + /* THE BOUND, so the attention keeps the cheaper dense issue where the two paths + * are the same answer. Decode ignores it and always takes the sparse path, which + * is what keeps that path exercised on every step this engine runs. */ + lay.attn.qsa_exact_to = m.qsacfg.budget + m.qsacfg.ratio - 1; + } + RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv_full)); + lay.attn.ar_out_take = lay.hc_mix.ar_take(); + RAD_ARCH_TRY(lay.attn.declare(b, nm, g, (int)l, m.kv_full, m.n_rot, aw, as, + false, false, kArNone, lay.hc_mix.op_ar_write != 0)); + /* THE INDEXER, after the attention block so its ops sit where the sparse attention + * reads them. It reads the same normed fp8 input the projections do; arch/common/ + * rad_qsa.h is the declaration side of docs/QSA.md. */ + if (m.qsaw.qk) { + QsaIndexer::Config qc = m.qsacfg; + qc.mode = lay.attn.mode; + qc.qk_proj = nm.ckpt("%s.%lld.self_attn.indexer.index_qk_proj.weight", + pre, (long long)l); + qc.q_norm = nm.ckpt("%s.%lld.self_attn.indexer.q_layernorm.weight", + pre, (long long)l); + qc.k_norm = nm.ckpt("%s.%lld.self_attn.indexer.k_layernorm.weight", + pre, (long long)l); + qc.kv_attn = m.kv_full; + qc.emit_sel = lay.attn.qsa_sel != 0; + RAD_ARCH_TRY(lay.qsa.declare(b, nm, g, (int)l, qc, m.qsaw, aw.h, + &m.kv_qsa_bkey)); + } + } else { + GdnFP8::Src gs{}; + 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)); + lay.gdn.ar_out_take = lay.hc_mix.ar_take(); + RAD_ARCH_TRY(lay.gdn.declare(b, nm, g, m.gcfg, (int)l, m.kv_state, m.kv_conv, gw, gs, + false, false, kArNone, lay.hc_mix.op_ar_write != 0)); + } + + HyperConn::Src ffns{}; + ffns.norm = nm.ckpt("%s.%lld.mlp_hyper_connection.hc_norm.weight", pre, (long long)l); + ffns.mix_down = nm.ckpt("%s.%lld.mlp_hyper_connection.input_mix_weight_down.weight", + pre, (long long)l); + ffns.mix_up = nm.ckpt("%s.%lld.mlp_hyper_connection.input_mix_weight_up.weight", + pre, (long long)l); + ffns.inject_w = nm.ckpt("%s.%lld.mlp_hyper_connection.block_inject_weight.weight", + pre, (long long)l); + /* The rotated expert plane's input codes come out of this read, beside the plain ones + * the shared arm takes, so the routed arm declares no quantiser of its own. */ + HyperConn::Config fcfg = m.hccfg; + HyperConn::Wire fw = hw; + if (m.moecfg.expert_rot) { fcfg.rotate = 1; fw.rq = m.a_hr.q; fw.rs = m.a_hr.s; } + RAD_ARCH_TRY(lay.hc_ffn.declare(b, nm, g, nm.f("blk.%lld.ffn_hc", (long long)l), + fcfg, fw, ffns)); + + MoeFP8::Src ms{}; + ms.cfg = m.moecfg; + ms.router = nm.ckpt("%s.%lld.mlp.gate.weight", pre, (long long)l); + ms.experts_gate_up = nm.ckpt("%s.%lld.mlp.experts.gate_up_proj", pre, (long long)l); + ms.experts_down = nm.ckpt("%s.%lld.mlp.experts.down_proj", pre, (long long)l); + if (m.moecfg.n_ff_shared > 0) { + ms.shared = nm.ckpt("%s.%lld.mlp.shared_expert", pre, (long long)l); + ms.shared_gate = nm.ckpt("%s.%lld.mlp.shared_expert_gate.weight", pre, (long long)l); + } + lay.mlp.ar_out_take = lay.hc_ffn.ar_take(); + lay.mlp.hr_in = fcfg.rotate != 0; + RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw, ms, false, false, kArNone, + lay.hc_ffn.op_ar_write != 0)); + /* The write behind the block takes its gather where it can, declared after the block so + * the buffers it reads are the block's outputs in declaration order. */ + { + HyperConn::GatherSrc gs{}; + gs.ye = lay.mlp.w.edn; + gs.ew = lay.mlp.w.ew; + gs.sorted = lay.mlp.w.sorted; + if (lay.mlp.gfold) { gs.sh = lay.mlp.w.sout; gs.sg = lay.mlp.w.sgate; } + gs.top_k = lay.mlp.c.top_k; + gs.rows = lay.mlp.c.rows; + RAD_ARCH_TRY(lay.hc_ffn.declare_gather(b, gs)); + lay.mlp.gather_out_rows = lay.hc_ffn.gather_rows; + lay.mlp.gather_out_rows6 = lay.hc_ffn.gather_rows6; + } + } + + /* ---- the 97th connection. No write half, no fp8 twin: it produces the one hidden state the + * lm_head reads, as a bf16 input. Its `hc_norm` is what a pre-norm model calls the + * final norm -- this checkpoint has no `model.language_model.norm.weight` at all. */ + { + HyperConn::Config mc = m.hccfg; + mc.inject = 0; + mc.quant = 0; + HyperConn::Wire mixw{}; + mixw.h = m.b_h; mixw.x.x = m.a_x.x; /* q/s deliberately absent */ + HyperConn::Src mixs{}; + mixs.norm = nm.ckpt("model.language_model.hyper_connection_mixer.hc_norm.weight"); + mixs.mix_down = nm.ckpt("model.language_model.hyper_connection_mixer." + "input_mix_weight_down.weight"); + mixs.mix_up = nm.ckpt("model.language_model.hyper_connection_mixer." + "input_mix_weight_up.weight"); + RAD_ARCH_TRY(m.mixer.declare(b, nm, g, nm.f("output_hc"), mc, mixw, mixs)); + } + + 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_x.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}); + if (!m.op_embed || !m.op_gather || !m.op_logits) return RAD_E_INVAL; + + /* ---- the multi-token-prediction head (arch/common/rad_block_mtp_hc.h). + * + * AFTER op_logits, and that is load-bearing rather than tidy. Declaration order IS the buffer + * planner's liveness, so a drafter declared before the trunk's tail ops would make the planner + * read those ops as living AFTER the drafter is done -- and share a trunk buffer with one of + * the head's. The symptom is fluent output with acceptance EXACTLY zero; arch/qwen35_fp8 + * declares its own drafter in this same position for the same reason. + * + * DECLARED ONLY WHEN THE DEPLOYMENT SPECULATES. `mtp_num_hidden_layers` says the checkpoint + * carries a head and `max_spec` says the engine intends to use one; at max_spec 0 the weights + * stay off the card and the container still carries them, because rad-convert declares at a + * non-zero max_spec on purpose. */ + const int64_t nextn = meta_int2(meta, "qwen4exp.mtp_num_hidden_layers", + "mtp_num_hidden_layers", 0); + if (nextn > 0 && g.max_spec > 0) { + const char* mpre = "mtp"; + /* AT max_tok, NOT max_logit_rows. A draft round is one row a sequence, but the history + * pass that fills the head's own K and V is one row a TOKEN over a whole prefill chunk. */ + m.b_mtp_hin = decl_b(b, nm.f("mtp_hin"), g.act_dtype, {T, HN}); + m.b_mtp_hw = decl_b(b, nm.f("mtp_hw"), g.act_dtype, {T, HN}); + m.b_mtp_e = decl_b(b, nm.f("mtp_e"), g.act_dtype, {T, g.n_embd}); + m.b_mtp_hout = decl_b(b, nm.f("mtp_hout"), g.act_dtype, {g.max_logit_rows, g.n_embd}); + /* THE 2-BIT DRAFT HEAD, when the model holds one: asked once, here, because the answer + * declares the head's buffers and the block reads it back from them. */ + if (mtp_draft_head_q2(b, MtpHcBlock::head_name(nm), nm.ckpt("lm_head.weight"))) { + const int64_t dmpad = ((g.max_logit_rows + 15) / 16) * 16; + m.b_mtp_dq = decl_b(b, nm.f("mtp_dq"), RAD_I8, {g.max_logit_rows, g.n_embd}); + m.b_mtp_ds = decl_b(b, nm.f("mtp_ds"), RAD_F32, {g.max_logit_rows, 1}); + m.b_mtp_dsum = decl_b(b, nm.f("mtp_dsum"), RAD_F32, {g.n_embd / 128, dmpad}); + /* AT THIS RANK'S ROWS, not the model's: the 2-bit head is vocab-parallel and the + * merge below puts the halves back together. rad_arch.h owns the rule. */ + m.b_mtp_dlog = decl_b(b, nm.f("mtp_dlog"), g.act_dtype, + {g.max_logit_rows, vocab_head_rows(g)}); + if (vocab_head_sharded(g)) { + m.b_mtp_dpair = decl_b(b, nm.f("mtp_dpair"), RAD_F32, + {g.max_logit_rows, kDraftTopR, 2}); + m.b_mtp_dgath = decl_b(b, nm.f("mtp_dgath"), RAD_F32, + {g.max_logit_rows, (int64_t)g.world * kDraftTopR, 2}); + } + /* NAMED and declared, because the engine reads the proposal straight out of it: a + * draft round's token comes from row_topk and never through the sampler. */ + /* kDraftTopR COLUMNS, and a draft reads one. The rest are the coarse head's other + * candidates, which `logit_rerank` scores before column 0 is taken, and their width + * is also what gives the vocab-parallel all-gather a 16-byte row; rad_block_mtp_hc.h's + * kDraftTopR says why. */ + m.b_mtp_didx = decl_b(b, nm.f("mtp_didx"), RAD_I32, {g.max_logit_rows, kDraftTopR}); + m.b_mtp_dval = decl_b(b, nm.f("mtp_dval"), RAD_F32, {g.max_logit_rows, kDraftTopR}); + } + + MtpHcBlock::Wire tw{}; + tw.src = m.b_h; tw.hin = m.b_mtp_hin; tw.hw = m.b_mtp_hw; + tw.e = m.b_mtp_e; tw.inj = m.b_inj; tw.hout = m.b_mtp_hout; + tw.logits = m.b_logits; tw.x = m.a_x; + tw.dq = m.b_mtp_dq; tw.ds = m.b_mtp_ds; tw.dsum = m.b_mtp_dsum; + tw.dlog = m.b_mtp_dlog; tw.didx = m.b_mtp_didx; tw.dval = m.b_mtp_dval; + tw.dpair = m.b_mtp_dpair; tw.dgath = m.b_mtp_dgath; + /* The layer's working set is the TRUNK's: every one of these is dead by the time a draft + * round runs, and a second set would be 150 MiB of activation planes for one layer. Only + * the wide stream and the carry are the head's own, because those must survive the round + * that produced them. */ + tw.attn = aw; tw.attn.x = m.b_mtp_hw; + tw.mlp = mw; tw.mlp.x = m.b_mtp_hw; + /* Everything in the wire is within-step scratch and a draft round is its own step, so the + * head shares all of it. The QSA tail is the exception and it is not in the wire at all: + * a head leaving its own index keys where a trunk layer pools them is a layer pooling + * another layer's keys, so the tail is `kv_qsa_tail` -- per sequence and per layer -- and + * declare() binds this layer to it like any other. */ + tw.qsa = m.qsaw; + + MtpHcBlock::Src ts{}; + ts.fc_hidden = nm.ckpt("%s.fc_hidden.weight", mpre); + ts.fc_embedding = nm.ckpt("%s.fc_embedding.weight", mpre); + ts.pre_norm_hidden = nm.ckpt("%s.pre_fc_norm_hidden.weight", mpre); + ts.pre_norm_embedding = nm.ckpt("%s.pre_fc_norm_embedding.weight", mpre); + + ts.hc_attn.norm = nm.ckpt("%s.layers.0.attn_hyper_connection.hc_norm.weight", mpre); + ts.hc_attn.mix_down = nm.ckpt("%s.layers.0.attn_hyper_connection." + "input_mix_weight_down.weight", mpre); + ts.hc_attn.mix_up = nm.ckpt("%s.layers.0.attn_hyper_connection." + "input_mix_weight_up.weight", mpre); + ts.hc_attn.inject_w = nm.ckpt("%s.layers.0.attn_hyper_connection." + "block_inject_weight.weight", mpre); + ts.hc_mlp.norm = nm.ckpt("%s.layers.0.mlp_hyper_connection.hc_norm.weight", mpre); + ts.hc_mlp.mix_down = nm.ckpt("%s.layers.0.mlp_hyper_connection." + "input_mix_weight_down.weight", mpre); + ts.hc_mlp.mix_up = nm.ckpt("%s.layers.0.mlp_hyper_connection." + "input_mix_weight_up.weight", mpre); + ts.hc_mlp.inject_w = nm.ckpt("%s.layers.0.mlp_hyper_connection." + "block_inject_weight.weight", mpre); + /* The head's own mixer, and it has no `block_inject_weight` for the same reason the + * trunk's 97th connection has none: nothing follows it to write back into. */ + ts.hc_mix.norm = nm.ckpt("%s.hyper_connection_mixer.hc_norm.weight", mpre); + ts.hc_mix.mix_down = nm.ckpt("%s.hyper_connection_mixer.input_mix_weight_down.weight", + mpre); + ts.hc_mix.mix_up = nm.ckpt("%s.hyper_connection_mixer.input_mix_weight_up.weight", mpre); + + ts.attn.qg = nm.ckpt("%s.layers.0.self_attn.q_proj.weight", mpre); + ts.attn.k = nm.ckpt("%s.layers.0.self_attn.k_proj.weight", mpre); + ts.attn.v = nm.ckpt("%s.layers.0.self_attn.v_proj.weight", mpre); + ts.attn.q_norm = nm.ckpt("%s.layers.0.self_attn.q_norm.weight", mpre); + ts.attn.k_norm = nm.ckpt("%s.layers.0.self_attn.k_norm.weight", mpre); + ts.attn.o = nm.ckpt("%s.layers.0.self_attn.o_proj.weight", mpre); + + ts.mlp.cfg = m.moecfg; + ts.mlp.router = nm.ckpt("%s.layers.0.mlp.gate.weight", mpre); + ts.mlp.experts_gate_up = nm.ckpt("%s.layers.0.mlp.experts.gate_up_proj", mpre); + ts.mlp.experts_down = nm.ckpt("%s.layers.0.mlp.experts.down_proj", mpre); + if (m.moecfg.n_ff_shared > 0) { + ts.mlp.shared = nm.ckpt("%s.layers.0.mlp.shared_expert", mpre); + ts.mlp.shared_gate = nm.ckpt("%s.layers.0.mlp.shared_expert_gate.weight", mpre); + } + + /* THE ATTENTION'S TWO SETTINGS ARE SET BEFORE declare(), for the reason the trunk's are: + * `attn_paged` declares `sel` and `seqused` as READS, and a read declared after the op is + * not a read at all. */ + m.mtp.attn.kv_block = 4; + if (m.qsaw.qk) { + m.mtp.attn.qsa_sel = m.qsaw.sel; + m.mtp.attn.qsa_sequ = m.qsaw.sequ; + m.mtp.attn.qsa_topk = m.qsacfg.topk; + m.mtp.attn.qsa_exact_to = m.qsacfg.budget + m.qsacfg.ratio - 1; + ts.qsa = m.qsacfg; + ts.qsa.mode = m.mtp.attn.mode; + ts.qsa.qk_proj = nm.ckpt("%s.layers.0.self_attn.indexer.index_qk_proj.weight", mpre); + ts.qsa.q_norm = nm.ckpt("%s.layers.0.self_attn.indexer.q_layernorm.weight", mpre); + ts.qsa.k_norm = nm.ckpt("%s.layers.0.self_attn.indexer.k_layernorm.weight", mpre); + ts.qsa.kv_attn = m.kv_full; + ts.qsa.emit_sel = m.mtp.attn.qsa_sel != 0; + } + + m.mtp.media = m.media; + RAD_ARCH_TRY(m.mtp.declare(b, nm, g, (int)g.n_layer, m.kv_full, &m.kv_qsa_bkey, m.n_rot, + m.w_tok, m.w_lm_head, m.hccfg, g.max_spec, tw, ts)); + m.have_mtp = true; + + /* WHAT THE ENGINE DRIVES. Serial: `max_spec` dependent passes, each embedding what the + * last one proposed. `proposal` is the buffer a pass leaves its token in, and the two + * heads differ -- the 2-bit head takes its own argmax into `mtp_didx`, the bf16 head goes + * through the ordinary sampler chain and 0 says so. */ + RadDrafterDecl dd{}; + dd.name = "mtp"; + dd.kind = RAD_DRAFT_SERIAL; + dd.depth = ctx->max_spec; + dd.proposal = m.b_mtp_didx; + dd.proposal_pitch = kDraftTopR; /* the pick is column 0; see kDraftTopR */ + dd.mask_token = -1; + RAD_ARCH_TRY(rad_declare_drafter(b, &dd)); + rad_note(b, "MTP head: one gated-attention layer with 512 routed experts, over the WIDE " + "stream, %d serial draft round(s)", ctx->max_spec); + } else if (nextn > 0) { + rad_note(b, "the checkpoint carries an `mtp.` head and this deployment asked for no " + "speculative window (max_spec 0). Its weights stay off the card"); + } + + /* THERE IS NO LAYER BISECT AND THERE ARE NO BLOCK ABLATIONS HERE, which is a deliberate + * absence rather than an omission. + * + * A switch that truncates the layer loop, or drops a block from it, is a real instrument for a + * COMPOSITION fault -- the class an op oracle structurally cannot see, because it compares one + * op's device result against the host's on the operands the device handed it, and a graph + * wired wrongly hands both sides the same wrong operands. + * + * What such a switch costs is that it makes the server compute something that is NOT the model + * while looking exactly like a server that is. It is read at declare, it is invisible in a bug + * report, and a "THIS IS NOT THE MODEL" note is one line in a startup log nobody re-reads. A + * deployment would be one stale shell export away from being fluent and wrong. A composition + * bisect belongs in a tool that names what it is doing in its own output, not in an + * environment variable read by a production path. + * + * The residual probe (RADIANCE_DEBUG_RESID) is the instrument that fits that rule: it MEASURES + * the composition rather than breaking it, so a server carrying it still serves the model. */ + m.n_run = g.n_layer; + /* THE VISION TOWER, LAST: an encoder pass issues nothing else, so its activations can share + * the arena with every buffer the language model declared above. Its weight groups start past + * every text layer and the MTP head. */ + if (m.media) RAD_ARCH_TRY(m.vit.declare(b, meta, ctx, nm, g.n_embd, (int)g.n_layer + 64)); + return RAD_OK; +} + + +static void step(RadCtx* c, const RadBatch* batch) { + Model& m = g_model[rad_rank(c)]; + const Geom& g = m.g; + const int64_t T = batch->n_tok; + + /* AN ENCODER PASS RUNS THE VISION TOWER AND NOTHING ELSE (RadBatch::enc). */ + if (batch->enc) { + m.vit.step(c, batch); + return; + } + + /* AN MTP PASS RUNS THE HEAD AND NOTHING ELSE. The trunk already ran this step and left its + * wide stream in `h`; the head reads the rows it wants out of it and turns them into either a + * draft token or one more position of its own attention history. Which of the two is the SIGN + * of `draft_pass`, and rad_block_mtp_hc.h says why there are two. + * + * Zero is a trunk step, so a zeroed RadBatch runs the model -- the same convention, and for + * the same reason, as `num_accepted` (docs/OPS.md). */ + if (batch->draft_pass != 0) { + if (!m.have_mtp) { + rad_step_fail(c, "the batch asks for a drafter pass and no drafter is declared: the " + "container carries no `mtp.` head, or declare ran at max_spec 0, " + "which is the engine saying it would not draft"); + return; + } + /* THE HEAD'S OWN cos/sin ROWS, AND THE TRUNK DID NOT WRITE THEM. `rope_table` fills the + * rows THIS STEP'S POSITIONS name, and a draft round runs PAST the committed end -- the + * scheduler says so where it reserves the lookahead blocks: "round k writes the head's K + * and V at position head_i + k - 1, which runs past the committed end". The trunk step + * before this one covered head_i and no further, so without this call rounds past the + * first would rotate by whatever the table held at a row nothing had written yet. + * + * LEAVING IT OUT COSTS ONLY ACCEPTANCE, WHICH IS WHY IT IS EASY TO MISS. A draft is + * verified; a mis-rotated one is rejected and the text is still the trunk's, so the + * failure has no symptom except a draft that agrees less often. It becomes visible only + * once the indexer reads the same table: the head's QSA selection moves, its drafts move, + * and the accepted text moves with them at tie level -- a transcript difference at long + * context and none at all below the exactness bound, where every block is selected + * regardless. + * + * A row is a function of its POSITION ALONE -- the angle for position P is the same angle + * for every request and every step -- so re-filling costs nothing but the launch and can + * never write a row a reader disagrees with. */ + if (m.op_rope_cs && T <= qk_fuse_rows(g) && !rope_mixed(batch)) + RAD_ISSUE_N(c, m.op_rope_cs, T, rope_pos1(batch, T), RAD_B(m.b_rope_cs)); + m.mtp.step(c, batch); + return; + } + + RAD_ISSUE(c, m.op_embed, + praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.a_x.x, T)); + m.mrows.step(c, batch, m.a_x.x, T); + /* Unconditional, unlike qwen35_fp8's: there is no norm in front of the first block to fold it + * into, because the first thing that touches the stream is a gated-residual read. */ + if (m.op_embed_ar) + RAD_ISSUE_N(c, m.op_embed_ar, T * g.n_embd, brows(m.a_x.x, T), RAD_NONE); + /* The PLE's hash, ahead of every layer: its host gather waits for it, and the layers issued + * between the two keep the device busy while the host gathers (rad_block_ple.h). */ + if (m.ple_layer >= 0) m.ple.ids(c, batch); + m.enter.step(c, T); + + if (m.op_rope_cs && T <= qk_fuse_rows(g) && !rope_mixed(batch)) + RAD_ISSUE_N(c, m.op_rope_cs, T, rope_pos1(batch, T), RAD_B(m.b_rope_cs)); + + for (int64_t li = 0; li < m.n_run && li < (int64_t)m.layers.size(); ++li) { + const Layer& l = m.layers[(size_t)li]; + /* Before the attention connection reads the stream, which is where the reference puts it. */ + if (li == m.ple_layer) m.ple.step(c, batch); + { + l.hc_mix.read(c, T, 0, T); + /* THE INDEXER RUNS FIRST, because the attention reads its selection. It can: this + * block's input is normed and quantised by the caller (`ext_in`), so `w.h` is already + * what it will be when the attention runs. */ + if (l.full) { l.qsa.step(c, l.attn.w.h, batch); l.attn.step(c, batch); } + else l.gdn.step(c, batch); + l.hc_mix.write(c, T, 0, T); + } + dbg_resid(c, (int)li, "mix", g.n_embd, m.b_h, m.a_x.x); + { + l.hc_ffn.read(c, T, 0, T); + l.mlp.step(c, batch); + l.hc_ffn.write(c, T, 0, T); + } + dbg_resid(c, (int)li, "ffn", g.n_embd, m.b_h, m.a_x.x); + } + + m.mixer.read(c, T, 0, T); + + if (batch->n_out > 0) { + RAD_ISSUE_N(c, m.op_gather, batch->n_out, + brows(m.a_x.x, T), praw(batch->out_ids, RAD_I32, batch->n_out), + brows(m.b_hout, batch->n_out)); + RAD_ISSUE_N(c, m.op_logits, batch->n_out, + brows(m.b_hout, batch->n_out), RAD_W(m.w_lm_head), + brows(m.b_logits, batch->n_out)); + } +} + +/* WHAT THE PLUGIN WOULD DRAFT AT, which is what `--num-speculative-tokens auto` takes and what + * rad-convert declares at when the run that makes a container would not itself have drafted. + * + * 3 and not `mtp_num_hidden_layers`: the checkpoint says the head EXISTS (one layer), never how + * deep a chain of it is worth running. It is an operating point, not a property of the model, + * which is why `draft_depth_fixed` stays 0 and the flag overrides it. + * + * THREE IS WHERE THROUGHPUT PEAKS on this model. Per-POSITION acceptance stays high at every + * depth, so the head is not what runs out; what runs out is the VERIFY step. Each extra query row + * costs real time here because the model's weights do not fit device memory -- more rows mean more + * experts streamed and more n-gram rows faulted out of the mapped table -- and most of what a + * deeper step adds is that, not the head's own ops. */ +static int probe(const RadModelMeta* meta, RadArchProbe* out) { + if (!meta || !out) return RAD_E_INVAL; + out->draft_depth = 0; + if (meta_int2(meta, "qwen4exp.mtp_num_hidden_layers", "mtp_num_hidden_layers", 0) > 0) + out->draft_depth = 3; + out->shape_probe_ok = 1; /* declare() writes scratch under shape_probe */ + return RAD_OK; +} + +} /* namespace qwen4exp_fp8 */ + +#ifndef RAD_ARCH_NO_EXPORTS +RAD_ARCH_PROBE(qwen4exp_fp8) +RAD_ARCH_PLUGIN(qwen4exp_fp8, "qwen4exp", "", "0.1.0", + "Qwen4-Exp (Qwen3.8-Flash-Next): hybrid Gated DeltaNet / gated attention, a GATED " + "RESIDUAL four streams wide, and 512 routed experts -- from a DENSE bf16 " + "checkpoint, quantised ahead of time by a recipe") +#endif diff --git a/build.sh b/build.sh new file mode 100755 index 00000000..e8ba1a37 --- /dev/null +++ b/build.sh @@ -0,0 +1,35 @@ +#!/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=[;...] 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 diff --git a/cmake/RadAddPlugin.cmake b/cmake/RadAddPlugin.cmake new file mode 100644 index 00000000..9c540986 --- /dev/null +++ b/cmake/RadAddPlugin.cmake @@ -0,0 +1,206 @@ +# 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}/ +# 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 /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 + # /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 $<$:-ffp-contract=off>) + # THE DEVICE OPTIMISATION LEVEL, ON THE TARGET, because CMake supplies no usable one for HIP: + # depending on its version CMAKE_HIP_FLAGS_ is empty -- the kernels compile at -O0 with + # asserts live -- or the host-style '-O2 -g'. The top-level CMakeLists.txt sets the variables for + # the tree; a plugin built out of tree gets the same levels here, after the toolchain's flags on + # the command line, so they win. A later -O replaces an earlier one but a later -O does not undo + # -g, so the levels outside Debug end in -g0: device debug info costs compile time, inhibits + # scheduling, and makes an out-of-tree build's code objects differ from the tree's. NDEBUG is not + # decoration on the device: an assert is a hostcall, and the engine's queues provide no hostcall + # buffer (docs/PLUGIN.md). RAD_HIP_FLAGS_ overrides, as it does in the tree. + 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 "$<$,$>:${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 $<$:--no-offload-compress>) + target_link_options(${tgt} PRIVATE $<$:--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() diff --git a/cmake/radiance-config.cmake.in b/cmake/radiance-config.cmake.in new file mode 100644 index 00000000..30f694fb --- /dev/null +++ b/cmake/radiance-config.cmake.in @@ -0,0 +1,104 @@ +# 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 -MF ") + endif() + if(NOT CMAKE_INCLUDE_SYSTEM_FLAG_HIP) + set(CMAKE_INCLUDE_SYSTEM_FLAG_HIP "-isystem ") + endif() +endif() + +# The build-tree $RADIANCE_HOME for the CONSUMER's build, so that a freshly built out-of-tree plugin +# can be exercised with RADIANCE_HOME=/radiance_home before it is installed -- +# which is how an in-tree plugin is tested, and there is no reason the boundary should make that +# harder. Not forced: a consumer who has already set it keeps their own. +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) diff --git a/core/CMakeLists.txt b/core/CMakeLists.txt new file mode 100644 index 00000000..3bba2e3b --- /dev/null +++ b/core/CMakeLists.txt @@ -0,0 +1,103 @@ +# 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 "$") + # 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) diff --git a/core/build/rad_bufplan.cpp b/core/build/rad_bufplan.cpp new file mode 100644 index 00000000..0693a4a0 --- /dev/null +++ b/core/build/rad_bufplan.cpp @@ -0,0 +1,244 @@ +/* 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 +#include + +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 + +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& placed) { + std::vector> 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 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(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 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 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 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 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 */ diff --git a/core/build/rad_build.h b/core/build/rad_build.h new file mode 100644 index 00000000..17cdb5a4 --- /dev/null +++ b/core/build/rad_build.h @@ -0,0 +1,285 @@ +/* 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 +#include +#include +#include +#include +#include +#include + +/* The handle the plugin holds. rad_builder.h only forward-declares it; core/build/ owns it, and + * making it a base of rad::Builder means the C shims are a static_cast rather than a lookup. */ +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 offset; + std::vector decl; +}; +/* Lay out `probe`'s buffers -- a sizing declare at `rows` -- over `full`'s. Refused, with the + * reason in `why`, when the two declares do not describe the same buffers with only their rows + * smaller: anything else cannot share the real plan's fixed region and kernels. */ +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; + +/* ------------------------------------------------------------------ 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; } + + 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& 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; + + std::vector 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 reads, writes; }; + std::vector op_bufs_; + + /* Buffers the architecture said it touches from the second lane. See rad_buf_concurrent: + * their declared op range does not bound when their bytes are in use, so liveness gives them + * the whole program instead. */ + std::set concurrent_bufs_; + + /* Parallel to prog_.kv_groups: where in the op list the group was declared, and which op was + * found to consume it. Declaration order is the binding, because nothing else links an op to + * a group -- see find_kv_consumer(). */ + std::vector kv_decl_at_; + std::vector kv_consumer_; + + /* Declared name -> the index in prog_.name_map of its FIRST entry, so a repeated declaration + * can be checked against it in constant time. A linear scan would be quadratic in the weight + * count, and a routed model declares tens of thousands of them. */ + std::unordered_map name_map_first_; + + /* Declared weight name -> its handle, for the same reason: Flash-Next declares about a hundred + * thousand weights a rank, and a scan of the ones before each made declare take seconds. */ + std::unordered_map weight_by_name_; + + /* The model's answers, asked once a source: a routed model declares each expert's codes and + * scales as two weights over one source, and a checkpoint lookup is a name-map walk. */ + WeightSourceFn sources_; + std::unordered_map> 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* 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* errors = nullptr); + +} /* namespace rad */ + +/* ------------------------------------------------------------------ PROPOSED ABI ADDITION */ +/* These two belong in include/rad/rad_builder.h beside rad_decl_op, and they are declared here + * only because that header is frozen and this one is not. They are purely additive: no existing + * signature changes and no existing plugin breaks. + * + * Without them, an op names its weight operands and not its buffer operands, so the declare phase + * cannot compute activation liveness and the arena is the sum of every transient rather than the + * peak of them -- on a 64-layer model with a per-layer residual and a per-layer FFN intermediate + * that is the difference between one buffer and a hundred and twenty-eight. The declaration reads: + * + * rad_op h = RAD_OP(b, "gemm_nt", RAD_PARAMS(...), RAD_WEIGHTS(w)); + * rad_op_reads (b, h, RAD_BUFS(x)); + * rad_op_writes(b, h, RAD_BUFS(y)); + * + * Separate calls rather than more arguments to rad_decl_op, so the common declaration stays one + * line and the buffer plan is opt-in per op. */ +#ifdef __cplusplus +extern "C" { +#endif + +int rad_op_reads (RadBuilder* b, rad_op h, const rad_buf* bufs, int n); +int rad_op_writes(RadBuilder* b, rad_op h, const rad_buf* bufs, int n); + +#define RAD_BUFS(...) ((const rad_buf[]){ __VA_ARGS__ }), \ + (int)(sizeof((const rad_buf[]){ __VA_ARGS__ }) / sizeof(rad_buf)) + +#ifdef __cplusplus +} /* extern "C" */ +#endif diff --git a/core/build/rad_builder.cpp b/core/build/rad_builder.cpp new file mode 100644 index 00000000..3232ba26 --- /dev/null +++ b/core/build/rad_builder.cpp @@ -0,0 +1,1671 @@ +/* rad_builder.cpp -- the Builder, and the C surface of rad_builder.h that drives it. + * + * Handles are 1-based indices into the Program's tables, so index 0 is a sentinel and a failed + * decl_* is falsy. That is not a convention for its own sake: it is what lets an architecture + * plugin write + * + * rad_op h = decl_op(b, "rmsnorm_had_quant_i8", ...); + * if (!h) { ... emit the unfused sequence ... } + * + * and have fusion be a selection rather than a compiler pass (spec §2.3). + */ +#include "rad_build.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace rad { + +/* ================================================================== interning */ +const char* intern(std::string_view s) { + /* A node-based set: insertion never moves an existing element, so the pointer we hand out + * stays valid for the life of the process. Declare runs once per rank on its own thread + * (spec §1), hence the lock -- taken a few thousand times at startup and never again. */ + static std::unordered_set pool; + static std::mutex m; + std::lock_guard lk(m); + return pool.emplace(s).first->c_str(); +} + +/* ================================================================== small helpers */ +/* Names for the enums the graph dump prints. `bld_` prefixed because tier_name and site_name in + * rad_core.h belong to the planner and these are the same kind of thing for a different axis -- + * two components should not race for one symbol. */ +const char* bld_domain_name(int d) { return d == RAD_DOMAIN_HOST ? "host" : "device"; } + +/* The full-detail rendering of one miss, used by --debug-graph and by the device-hole report. + * Defined here rather than in the header so that the domain has exactly one spelling. */ +std::string Program::Miss::line() const { + return fmt("%-22s %s [%s] -> %s", op.c_str(), geom.c_str(), bld_domain_name(domain), + why.c_str()); +} + +const char* bld_access_name(int a) { + switch (a) { + case RAD_ACCESS_PER_TOKEN: return "per-token"; + case RAD_ACCESS_PER_REQUEST: return "per-request"; + case RAD_ACCESS_CONDITIONAL: return "conditional"; + case RAD_ACCESS_RARE: return "rare"; + case RAD_ACCESS_VOCAB: return "vocab"; + default: return "?"; + } +} + +const char* bld_buf_kind_name(int k) { + switch (k) { + case RAD_BUF_TRANSIENT: return "transient"; + case RAD_BUF_PERSIST: return "persist"; + case RAD_BUF_DERIVED: return "derived"; + default: return "?"; + } +} + +const char* bld_kv_kind_name(int k) { + switch (k) { + case RAD_KV_FULL: return "full"; + case RAD_KV_WINDOW: return "window"; + case RAD_KV_LINEAR: return "linear"; + case RAD_KV_CONV: return "conv"; + default: return "?"; + } +} + +static int64_t decl_numel(uint32_t rank, const int64_t* shape) { + if (rank == 0 || rank > RAD_MAX_RANK) return 0; + int64_t n = 1; + for (uint32_t i = 0; i < rank; ++i) { + if (shape[i] <= 0) return 0; + n *= shape[i]; + } + return n; +} + +/* ================================================================== construction */ +Builder::Builder(Registry& reg, const RadModelMeta& meta, const RadBuildCtx& ctx) + : reg_(reg) { + prog_.meta = meta; + prog_.ctx = ctx; + scope_ = ctx.scope ? ctx.scope : ""; + + /* Sentinels. Handle 0 is never valid, so a zeroed struct is an unset handle. */ + prog_.weights.emplace_back(); + prog_.buffers.emplace_back(); + prog_.ops.emplace_back(); + prog_.kv_groups.emplace_back(); + op_bufs_.emplace_back(); + kv_decl_at_.push_back(-1); + kv_consumer_.push_back(-1); +} + +uint32_t Builder::err(int code, const char* f, ...) { + char msg[1024]; + va_list ap; + va_start(ap, f); + vsnprintf(msg, sizeof msg, f, ap); + va_end(ap); + errors_.emplace_back(msg); + /* First class wins: a later error is usually a consequence of the first, and the list carries + * all of them anyway. */ + if (status_ == RAD_OK) status_ = code; + RAD_ERR("declare: %s", msg); + return RAD_NULL_HANDLE; +} + +/* The scope prefixes declared names so a drafter, a vision tower and the language model can share + * one builder without colliding (spec §10, §11). Op names are NOT scoped: they are the shared + * vocabulary the selector matches on. */ +std::string Builder::scoped(const char* name) const { + if (scope_.empty()) return name ? name : ""; + return scope_ + "." + (name ? name : ""); +} + +/* ================================================================== weights */ +rad_weight Builder::decl_weight(const char* name, const RadWeightDecl* d) { + if (finished_) return err(RAD_E_STATE, "decl_weight('%s') after declare finished", name ? name : ""); + if (!name || !*name || !d) return err(RAD_E_INVAL, "decl_weight: null name or declaration"); + + std::string n = scoped(name); + if (weight_by_name_.count(n)) + return err(RAD_E_DUPLICATE, "weight '%s' declared twice; the container has one entry " + "for that name and two declarations cannot both own it", + n.c_str()); + + int64_t numel = decl_numel(d->rank, d->shape); + if (numel == 0) + return err(RAD_E_SHAPE, "weight '%s': rank %u with a zero or negative extent", + n.c_str(), d->rank); + + WeightInfo w; + w.name = n; + w.decl = *d; + /* Under tensor parallel the plugin declares dimensions ALREADY DIVIDED (spec §9), so this is + * what THIS RANK holds. The core does not reason about sharding propagation and does not + * divide anything: a sharding inference pass is a compiler pass, and its failure mode is a + * model that produces fluent wrong text on a rank count nobody tested. */ + w.logical_bytes = rad_dtype_bytes(d->dtype, numel); + if (w.logical_bytes == 0 && d->dtype < RAD_DT_PLUGIN_BASE) + return err(RAD_E_DTYPE, "weight '%s': dtype %u is not one the core can size", n.c_str(), + d->dtype); + + /* WHAT IT IS A VIEW OF (spec §4.3): the source's encoding as the model holds it, and the planes + * this declaration takes. With nothing behind the builder the weight is its own plain plane + * in the declared dtype, which is what a test or a synthetic tool declares against. */ + w.source = (d->source && *d->source) ? scoped(d->source) : n; + WeightSource ws; + w.enc_known = lookup_source(w.source, &ws) == RAD_OK; + w.enc = w.enc_known ? ws.enc : rad_enc_plain(d->dtype); + int64_t vr = 0, vc = 0; /* the declared extents as a [rows, cols] view */ + rad_enc_view(d->rank, d->shape, &vr, &vc); + if (!w.enc_known) { + w.n_sel = 1; + w.sel[0] = 0; + } else if (!d->planes || !*d->planes) { + w.n_sel = w.enc.n_planes; + for (int k = 0; k < w.n_sel; ++k) w.sel[k] = k; + } else { + std::string list(d->planes); + size_t at = 0; + while (at <= list.size()) { + size_t comma = list.find(',', at); + if (comma == std::string::npos) comma = list.size(); + std::string role = list.substr(at, comma - at); + while (!role.empty() && role.front() == ' ') role.erase(role.begin()); + while (!role.empty() && role.back() == ' ') role.pop_back(); + const int k = rad_enc_find(&w.enc, role.c_str()); + char e[256]; + rad_enc_format(&w.enc, e, sizeof e); + if (k < 0) + return err(RAD_E_SHAPE, "weight '%s' takes plane '%s' of '%s', which is %s and has " + "no such plane", n.c_str(), role.c_str(), w.source.c_str(), e); + if (w.n_sel == RAD_ENC_MAX_PLANES) + return err(RAD_E_INVAL, "weight '%s': more than %d planes", n.c_str(), + RAD_ENC_MAX_PLANES); + w.sel[w.n_sel++] = k; + at = comma + 1; + } + } + + /* THE DECLARATION AGAINST THE PLANES. One plane is declared at its own dtype and extents -- + * this rank's share of them under a shard -- and several at the codes' dtype and the logical + * extents. A dtype that is not the plane's is an exact widening the loader performs, or it is + * a quantisation, which belongs to rad-convert and is refused here by name. */ + const RadEncPlane& p0 = w.enc.plane[w.sel[0]]; + if (p0.dtype != d->dtype) { + const bool widen = w.n_sel == 1 && d->dtype == RAD_F32 && + (p0.dtype == RAD_BF16 || p0.dtype == RAD_F16); + char e[256]; + rad_enc_format(&w.enc, e, sizeof e); + if (!widen) + return err(RAD_E_DTYPE, "weight '%s' is declared %s, and '%s' holds %s as %s: only an " + "exact widening is done at load -- anything else is a " + "quantisation, which a recipe does before the container is " + "written (spec §4.4)", n.c_str(), rad_dtype_name(d->dtype), + w.source.c_str(), p0.role, e); + w.widen = true; + } + int64_t sr = 0, sc = 0; /* the source's logical [rows, cols] */ + if (w.enc_known) rad_enc_view(ws.rank, ws.shape, &sr, &sc); + for (int k = 0; k < w.n_sel; ++k) { + const RadEncPlane& pk = w.enc.plane[w.sel[k]]; + int64_t fr = vr, fc = vc; /* the plane's whole extents */ + if (w.n_sel == 1) { + w.sel_rows[k] = vr; + w.sel_cols[k] = vc; + if (w.enc_known) rad_enc_plane_dims(&pk, sr, sc, &fr, &fc); + } else { + rad_enc_plane_dims(&pk, vr, vc, &w.sel_rows[k], &w.sel_cols[k]); + fr = sr; fc = sc; + } + /* Unsharded, the declaration IS the plane (or, for several, the logical weight), and a + * mismatch is the plugin and the model disagreeing about a shape -- named now rather than + * found at load as a byte count. A shard's share is the loader's to check. */ + const bool whole = d->shard == RAD_SHARD_NONE || prog_.ctx.world_size <= 1; + /* A RESHAPE IS NOT A DISAGREEMENT: one whole plane of single elements, a byte or more + * each, declared under another shape of the same count -- a conv kernel [O, C, T, H, W] + * read as the [O, C*T*H*W] matrix it is. Row-major, its bytes do not move. */ + const bool reshape = w.n_sel == 1 && whole && pk.kind == RAD_PLANE_TILED && + pk.block[0] == 1 && pk.block[1] == 1 && + rad_dtype_bits(pk.dtype) >= 8 && fr * fc == vr * vc; + if (w.enc_known && whole && !reshape && (k == 0 || w.n_sel == 1) && + (w.n_sel == 1 ? (fr != vr || fc != vc) : (sr != vr || sc != vc))) + return err(RAD_E_SHAPE, "weight '%s' is declared [%lld, %lld], and %s of '%s' is " + "[%lld, %lld]", n.c_str(), (long long)vr, (long long)vc, + w.n_sel == 1 ? pk.role : "the logical extent", w.source.c_str(), + (long long)(w.n_sel == 1 ? fr : sr), (long long)(w.n_sel == 1 ? fc : sc)); + } + + /* The stored form defaults to the selected plane as it is. finish_layouts() overwrites it when + * the resolved kernel asks for something else through its layout hook (spec §4.3); a kernel + * with no hook, or one that answers RAD_E_UNSUPPORTED, takes exactly this. */ + w.identity = true; + w.stored_dtype = w.widen ? d->dtype : p0.dtype; + w.stored_bytes = w.widen ? rad_dtype_bytes(d->dtype, vr * vc) + : vr * rad_enc_row_bytes(p0.dtype, vc); + w.stored_rank = d->rank; + for (uint32_t i = 0; i < RAD_MAX_RANK; ++i) + w.stored_shape[i] = i < d->rank ? d->shape[i] : 0; + w.align = RAD_ALIGN_UNIT; + + prog_.weights.push_back(w); + const rad_weight h = (rad_weight)(prog_.weights.size() - 1); + weight_by_name_.emplace(prog_.weights.back().name, h); + return h; +} + +int Builder::lookup_source(const std::string& name, WeightSource* out) { + if (!sources_) return RAD_E_NOTFOUND; + auto it = source_cache_.find(name); + if (it != source_cache_.end()) { + *out = it->second.second; + return it->second.first; + } + WeightSource ws; + const int st = sources_(name, prog_, &ws); + /* Only an answer is remembered: a weight not found before its name map entry was declared + * may be found after it. */ + if (st == RAD_OK) source_cache_.emplace(name, std::make_pair(st, ws)); + *out = ws; + return st; +} + +int Builder::weight_encoding(const char* source, RadEncoding* out, int64_t* shape, + uint32_t* rank) { + if (!source || !*source || !out) return RAD_E_INVAL; + WeightSource ws; + const int st = lookup_source(scoped(source), &ws); + if (st != RAD_OK) return st; + *out = ws.enc; + if (rank) *rank = ws.rank; + if (shape) + for (int i = 0; i < RAD_MAX_RANK; ++i) shape[i] = i < (int)ws.rank ? ws.shape[i] : 0; + return RAD_OK; +} + +/* ================================================================== buffers */ +int64_t buffer_bytes(const RadBufDecl& d) { + int64_t numel = decl_numel(d.rank, d.shape); + if (numel == 0) return 0; + return rad_dtype_bytes(d.dtype, numel); +} + +rad_buf Builder::decl_buffer(const char* name, const RadBufDecl* d) { + if (finished_) return err(RAD_E_STATE, "decl_buffer('%s') after declare finished", name ? name : ""); + if (!name || !*name || !d) return err(RAD_E_INVAL, "decl_buffer: null name or declaration"); + + std::string n = scoped(name); + for (size_t i = 1; i < prog_.buffers.size(); ++i) + if (prog_.buffers[i].name == n) + return err(RAD_E_DUPLICATE, "buffer '%s' declared twice", n.c_str()); + + if (d->kind < RAD_BUF_TRANSIENT || d->kind > RAD_BUF_DERIVED) + return err(RAD_E_INVAL, "buffer '%s': unknown kind %d", n.c_str(), d->kind); + if (d->domain != RAD_DOMAIN_DEVICE && d->domain != RAD_DOMAIN_HOST) + return err(RAD_E_INVAL, "buffer '%s': unknown domain %d", n.c_str(), d->domain); + + BufferInfo b; + b.name = n; + b.decl = *d; + b.bytes = buffer_bytes(*d); + if (b.bytes == 0) + return err(RAD_E_SHAPE, "buffer '%s': the core cannot size dtype %u at rank %u -- an " + "activation must be a dtype the buffer planner understands", + n.c_str(), d->dtype, d->rank); + + prog_.buffers.push_back(std::move(b)); + return (rad_buf)(prog_.buffers.size() - 1); +} + +/* ================================================================== KV groups */ +rad_kvgroup Builder::decl_kv_group(const char* name, const RadKVGroupDecl* d) { + if (finished_) return err(RAD_E_STATE, "decl_kv_group('%s') after declare finished", name ? name : ""); + if (!name || !*name || !d) return err(RAD_E_INVAL, "decl_kv_group: null name or declaration"); + if (d->kind < RAD_KV_FULL || d->kind > RAD_KV_CONV) + return err(RAD_E_INVAL, "kv group '%s': unknown kind %d", name, d->kind); + + std::string n = scoped(name); + for (size_t i = 1; i < prog_.kv_groups.size(); ++i) + if (prog_.kv_groups[i].name == n) + return err(RAD_E_DUPLICATE, "kv group '%s' declared twice", n.c_str()); + + KVGroupInfo g; + g.name = n; + g.decl = *d; + prog_.kv_groups.push_back(std::move(g)); + kv_decl_at_.push_back((int32_t)prog_.ops.size()); /* where in the op list we are now */ + kv_consumer_.push_back(-1); + return (rad_kvgroup)(prog_.kv_groups.size() - 1); +} + +int Builder::bind_layer_kv(int layer, rad_kvgroup g) { + if (g == 0 || g >= prog_.kv_groups.size()) { + err(RAD_E_INVAL, "bind_layer_kv(layer %d): kv group handle %u is not one this builder " + "handed out", layer, g); + return RAD_E_INVAL; + } + if (layer < 0) { err(RAD_E_INVAL, "bind_layer_kv: layer %d", layer); return RAD_E_INVAL; } + auto& v = prog_.kv_groups[g].layers; + if (std::find(v.begin(), v.end(), layer) == v.end()) v.push_back(layer); + return RAD_OK; +} + +/* Which op reads this group. + * + * Nothing in the ABI links an op to a KV group: rad_decl_op names parameters and weight operands, + * and a group is not either of those. Declaration order is therefore the binding, and it is the + * order the documentation already prescribes -- "declare the group, declare the op, then ask + * rad_kv_block_size()" (docs/OPS.md, spec §7.2). The consuming op is the first op declared after + * the group that carries a block_size, and an op serves at most one group, so a hybrid model's + * full and sliding-window groups each claim their own attention op. + * + * "Carries a block_size" means any of three things, and all three are checked because an + * architecture plugin may legitimately do none of the others: the op DECLARED one, its SCHEMA + * names one (attn_paged does, so the op is recognisable even when the plugin left the value off + * precisely because it is about to ask for it), or its resolved kernel CONSTRAINS one. */ +int32_t Builder::find_kv_consumer(rad_kvgroup g) { + if (kv_consumer_[g] >= 0) return kv_consumer_[g]; + + for (int32_t i = kv_decl_at_[g]; i < (int32_t)prog_.ops.size(); ++i) { + bool claimed = false; + for (size_t k = 1; k < kv_consumer_.size(); ++k) if (kv_consumer_[k] == i) claimed = true; + if (claimed) continue; + + const OpInfo& o = prog_.ops[i]; + bool carries = o.base.has("block_size"); + if (!carries && o.schema && o.schema->params) + for (int c = 0; c < o.schema->n_params && !carries; ++c) + if (o.schema->params[c].key && !std::strcmp(o.schema->params[c].key, "block_size")) + carries = true; + if (!carries) + for (const Band& b : o.bands) + for (int d = 0; d < RAD_N_DOMAINS && !carries; ++d) + if (b.dom[d] && b.dom[d].row && b.dom[d].row->info) + for (int c = 0; c < b.dom[d].row->info->n_constraints; ++c) + if (!std::strcmp(b.dom[d].row->info->constraints[c].key, "block_size")) + carries = true; + if (carries) { kv_consumer_[g] = i; return i; } + } + return -1; +} + +int64_t Builder::kv_block_size(rad_kvgroup g) { + if (g == 0 || g >= prog_.kv_groups.size()) { + err(RAD_E_INVAL, "rad_kv_block_size: handle %u is not a kv group this builder handed out", g); + return 0; + } + KVGroupInfo& gi = prog_.kv_groups[g]; + + /* A per-sequence state has no block size and asking for one is a category error, not a + * failure. Say so once and return 0; the caller wants bytes_per_state. */ + if (gi.decl.kind == RAD_KV_LINEAR || gi.decl.kind == RAD_KV_CONV) { + RAD_WARN("kv group '%s' is per-sequence state; it has no block size", gi.name.c_str()); + return 0; + } + if (gi.block_size) return gi.block_size; + + int32_t consumer = find_kv_consumer(g); + if (consumer < 0) { + /* A silent zero here becomes a division by zero in the block manager three components + * later, so it is an error with the reason attached. */ + err(RAD_E_STATE, + "rad_kv_block_size('%s'): no op that reads this group has been declared yet. The " + "block size comes off the RESOLVED attention kernel's block_size constraint, so the " + "attention op has to exist before there is an answer (spec §7.2)", gi.name.c_str()); + return 0; + } + + const OpInfo& o = prog_.ops[consumer]; + + /* The kernel's own constraint is the answer, read with core/plugin/'s own accessor: a second + * constraint walk here would be a second reading of the same rows. A core that picked its own + * block size would be a core that has to be edited when a kernel changes (spec §7.2). */ + for (const Band& b : o.bands) + for (int d = 0; d < RAD_N_DOMAINS; ++d) { + if (!b.dom[d] || !b.dom[d].row) continue; + long long bs = 0; + if (kernel_constraint(*b.dom[d].row, "block_size", RAD_C_EQ, &bs) && bs > 0) { + gi.block_size = bs; + return gi.block_size; + } + } + + /* No kernel constrained it: this kernel serves any block size (libref does exactly + * that -- correct, slow, no geometry constraints, spec §17). Then the number is the plugin's + * declared parameter, which is still not the core choosing one. */ + long long v = 0; + if (o.base.get_i("block_size", &v) && v > 0) { gi.block_size = v; return gi.block_size; } + + /* Nothing to read it off, and the reason is almost always the same one, so it is named here in + * full rather than left as "0". + * + * A constraint whose key the geometry does not carry does NOT hold (rad_util.cpp, and it is + * libr4d's rule for good reasons). So a kernel constrained to `block_size == 16` cannot be + * selected by a query that omits block_size -- which means an attention op declared WITHOUT a + * block_size can never resolve to the kernel whose constraint the answer was supposed to come + * from. The plugin has to declare the block size it wants; the resolved kernel's constraint + * then either confirms it or refuses it by name, and THAT is what keeps the number the + * kernel's rather than the core's (spec §7.2). */ + bool resolved_anywhere = false; + for (const Band& b : o.bands) + for (int d = 0; d < RAD_N_DOMAINS; ++d) if (b.dom[d]) resolved_anywhere = true; + + err(RAD_E_STATE, + "rad_kv_block_size('%s'): op '%s' consumes this group but %s. Declare block_size on the " + "op with the value this model wants: a kernel constrained to a block size cannot be " + "selected by a query that omits it, so leaving it off means the resolution it was to be " + "read from never happens (spec §7.2)", + gi.name.c_str(), o.op.c_str(), + resolved_anywhere ? "neither its resolved kernel nor its declared parameters name a " + "block_size" + : "it resolved to no kernel at all, so there is no constraint to read"); + return 0; +} + +/* ================================================================== ops */ +void Builder::record_tune_request(const Resolved& r) { + if (!r.row || !r.row->info || r.row->info->n_tunables <= 0) return; + /* ONE REQUEST PER KERNEL INSTANTIATION, and the instantiation is (kernel, plugin, the input + * params it was resolved at). Every distinct shape a kernel is asked for is a separate + * benchmark, and the same shape asked for by sixty-four layers is one (spec §15). + * + * `geom_key` and not geom.str(): the tuner and the selector must key the same way or the cache + * never hits, and geom_key is tunecache.h's canonical spelling -- sorted, and taken BEFORE the + * tuned axes were folded into the geometry. geom.str() preserves declaration order and now + * also carries the axes, so keying on it would make the key depend on its own answer. */ + const std::string key = r.row->info->name + std::string("\x1f") + r.row->plugin + + std::string("\x1f") + r.geom_key; + for (auto& t : prog_.tune_requests) + if (t.kernel + std::string("\x1f") + t.plugin + std::string("\x1f") + t.geom_key == key) + return; + + Program::TuneRequest req; + req.kernel = r.row->info->name; + req.plugin = r.row->plugin; + req.geom = r.geom; + req.geom_key = r.geom_key; + req.info = r.row->info; + prog_.tune_requests.push_back(std::move(req)); +} + +/* The geometry a band is DISPLAYED as: the fixed parameters plus the ranged one at the band's + * upper bound. Diagnostics only -- a resolved band already carries the geometry the registry froze + * it at, and that is the one the kernel is handed. */ +static Geometry display_geometry(const OpInfo& oi, const Band& b) { + Geometry g = oi.base; + if (!oi.ranged_key.empty() && b.hi != INT64_MAX) g.set_i(oi.ranged_key, b.hi); + return g; +} + +void Builder::resolve_bands(OpInfo& oi) { + /* The bucket table is core/plugin/'s and this component does not second-guess it: the + * boundaries are the union of the constraint values candidate kernels place on the ranged + * parameter, clamped to the declared range, and both domains are resolved AT EACH BAND'S UPPER + * BOUND -- the worst case in the band and therefore the only value safe to select and size on. + * An empty ranged_key comes back as exactly one band whose hi is INT64_MAX, so the + * no-ranged-parameter case needs no separate path and band_for() always finds it. */ + /* A KERNEL THAT CANNOT READ A WEIGHT'S ENCODING IS NOT A CANDIDATE FOR THE OP. Its layout + * hook says so with RAD_E_DTYPE, and a device row with no hook reads one plane as it is and + * nothing else -- so a bf16 head goes to the bf16 GEMM rather than being refused by the fp8 + * one, and the same declaration serves a checkpoint and its quantised container. The host + * domain's hookless rows are libref, which reads canonically and is gated elsewhere. */ + const Registry::RowFilter accept = [&](const KernelRow& r, const Geometry& g) -> std::string { + const RadKernelInfo* ki = r.info; + for (size_t wi = 0; wi < oi.weights.size(); ++wi) { + const rad_weight h = oi.weights[wi]; + if (h == 0 || h >= prog_.weights.size()) continue; + const WeightInfo& w = prog_.weights[h]; + if (sources_ && !w.enc_known && w.decl.optional) continue; + const int operand = wi < oi.weight_opd.size() && oi.weight_opd[wi] >= 0 + ? (int)oi.weight_opd[wi] : (int)wi; + char enc[256]; + if (!ki->layout) { + if (ki->domain == RAD_DOMAIN_DEVICE && w.n_sel > 1) { + rad_enc_format(&w.enc, enc, sizeof enc); + return fmt("reads '%s' as stored, and it is %d planes of %s", w.name.c_str(), + w.n_sel, enc); + } + continue; + } + RadTensor t[RAD_ENC_MAX_PLANES]; + weight_planes(w, t); + RadLayout L{}; + if (ki->layout(g.params(), g.n_params(), operand, &w.enc, w.sel, t, w.n_sel, &L) == + RAD_E_DTYPE) { + rad_enc_format(&w.enc, enc, sizeof enc); + return fmt("does not read '%s' encoded %s", w.name.c_str(), enc); + } + } + return std::string(); + }; + oi.bands = reg_.build_bands(oi.op, oi.ranged_key, oi.range_lo, oi.range_hi, oi.base, + oi.weights.empty() ? nullptr : &accept); + + if (oi.bands.empty()) { + /* No rows for this op at all. The range still owes an answer, so the miss report names a + * band rather than saying nothing about the op. */ + oi.bands.emplace_back(); + oi.bands.back().hi = oi.ranged_key.empty() ? INT64_MAX : oi.range_hi; + for (int d = 0; d < RAD_N_DOMAINS; ++d) + oi.bands.back().miss[d] = "no kernel implements this op in this domain"; + } + + for (Band& b : oi.bands) { + for (int d = 0; d < RAD_N_DOMAINS; ++d) { + Resolved& r = b.dom[d]; + + if (!r) { + /* One entry per op per band per domain that resolved to nothing, each carrying the + * constraint that refused it. build_bands records and does not abort -- a device + * miss is fatal for that band and a host miss removes a placement option, and + * which of those matters is not selection's call. Declare always completes and + * reports the list whole (spec §3.1). */ + prog_.misses.push_back({ oi.op, display_geometry(oi, b).str(), b.span, + b.miss[d].empty() ? "no kernel matched" : b.miss[d], + d }); + continue; + } + + /* Scratch at the same value the band was selected at. r.geom IS that value, frozen by + * the registry, so asking it here cannot drift from what the choice was made against. + * RadArgs carries no tensors: a scratch hook is a function of the geometry, which is + * the whole reason it can be called at declare at all. */ + if (r.row->info && r.row->info->scratch) { + RadArgs a{}; + a.p = r.geom.params(); + a.n_p = r.geom.n_params(); + a.rank = prog_.ctx.rank; + a.world_size = prog_.ctx.world_size; + int64_t s = r.row->info->scratch(&a); + if (s < 0) + err(RAD_E_SCRATCH, "%s: kernel %s refused to size its scratch for %s: %s", + oi.op.c_str(), r.row->info->name, r.geom.str().c_str(), + rad_strerror((int)s)); + else if (s > r.scratch_bytes) + r.scratch_bytes = s; + } + if (r.scratch_bytes > prog_.scratch_bytes) prog_.scratch_bytes = r.scratch_bytes; + + record_tune_request(r); + } + } +} + +/* init() once per resolved instance -- one op, one band, one domain -- run once the WHOLE graph + * has resolved (spec §2.1). Not during resolution: one kernel's failing init would then abort + * declare before the miss report was assembled, and the miss report is the point of the phase. + * + * A negative init is not a runtime condition. The kernel matched the constraints and then refused + * the instance, so the band becomes a miss and the report names it here, rather than the failure + * surfacing at the first launch three frames away. */ +void Builder::finish_instances() { + for (size_t i = 1; i < prog_.ops.size(); ++i) { + OpInfo& oi = prog_.ops[i]; + for (Band& b : oi.bands) { + for (int d = 0; d < RAD_N_DOMAINS; ++d) { + Resolved& r = b.dom[d]; + if (!r) continue; + const int s = reg_.init_instance(r, prog_.ctx.rank, prog_.ctx.world_size); + if (s >= 0) continue; + + err(s, "%s: kernel %s matched %s and then its init() refused the instance: %s", + oi.op.c_str(), r.row->info ? r.row->info->name : "?", + r.geom.str().c_str(), rad_strerror(s)); + b.miss[d] = fmt("init() refused the instance: %s", rad_strerror(s)); + prog_.misses.push_back({ oi.op, display_geometry(oi, b).str(), b.span, + b.miss[d], d }); + r = Resolved{}; + } + } + } +} +rad_op Builder::decl_op(const char* opname, const RadParam* p, int n_p, + const rad_weight* w, int n_w) { + if (finished_) return err(RAD_E_STATE, "decl_op('%s') after declare finished", opname ? opname : ""); + if (!opname || !*opname) return err(RAD_E_INVAL, "decl_op: null op name"); + if (n_p < 0 || n_w < 0) return err(RAD_E_INVAL, "decl_op('%s'): negative count", opname); + + /* ---- the schema, checked by the component that owns it. + * + * Registry::validate covers the whole parameter side: no such op (with the near miss named, so + * a typo and an unimplemented op are not the same diagnostic), an unknown key, a key given + * twice, a type mismatch, an empty range, and the one-ranged-parameter rule. A second copy of + * that check here would be a second answer to one question, and the two would drift. The + * sentence it fills in is written for an architecture-plugin author, so it goes into the + * report unchanged. */ + std::string verr; + const int v = reg_.validate(opname, p, n_p, &verr); + if (v < 0) return err(v, "%s", verr.c_str()); + + const RadOpSchema* sc = reg_.schema(opname); + if (!sc) return err(RAD_E_NOSCHEMA, "op '%s' has no declared schema", opname); + + /* ---- parameters. validate() already guaranteed the shape of this list, so this only has to + * split the fixed parameters from the single ranged one. */ + Geometry base; + std::string ranged_key; + int64_t lo = 0, hi = 0; + + for (int i = 0; i < n_p; ++i) { + const RadParam& q = p[i]; + switch (q.kind) { + case RAD_P_INT: base.set_i(q.key, q.ival); break; + case RAD_P_STR: base.set_s(q.key, q.sval); break; + /* A float parameter carries a value the kernel reads and NOTHING THE SELECTOR MATCHES + * ON: a tolerance is not a predicate, and a kernel that cares about eps to that + * precision has a bug (docs/OPS.md). So it goes into the geometry, where the kernel + * finds it, and never becomes a band boundary. */ + case RAD_P_F64: base.set_f(q.key, q.dval); break; + case RAD_P_RANGE: ranged_key = q.key; lo = q.ival; hi = q.ihi; break; + default: + return err(RAD_E_INVAL, "op '%s': parameter '%s' has kind %d, which is not INT, " + "F64, STR or RANGE", opname, q.key, q.kind); + } + } + + /* ---- operand count, which validate() does not see: it is handed the parameters and not the + * operands. Arguments are positional, so a count that disagrees with the schema means the same + * call means different things to different kernels -- not a diagnosable failure at issue, but + * silent numerical garbage (spec §2.3). Only the WEIGHT operands are named at declare, so that + * is what is counted here; the full count is checked against this same schema at issue. */ + size_t before = errors_.size(); + int w_req = 0, w_max = 0, n_tab = 0; + for (int i = 0; sc->operands && i < sc->n_operands; ++i) { + if (sc->operands[i].role == RAD_OPD_WTAB) { ++n_tab; continue; } + if (sc->operands[i].role != RAD_OPD_WEIGHT) continue; + ++w_max; + if (!sc->operands[i].optional) ++w_req; + } + /* ---- and where the operand is a TABLE, the run length. + * + * A RAD_OPD_WTAB position consumes a RUN of declared weights, so the count alone does not + * say how the list divides. The rule is EQUAL DIVISION: whatever is left after the fixed + * weight positions have taken one each is split evenly across the table positions, in + * declaration order. That is exactly right for the case tables exist for -- `moe_gemm_q`'s + * codes and scale planes are one of each per expert, always the same count -- and a division + * that does not come out whole is refused here rather than silently mis-grouped, which is the + * only failure the rule can have. */ + int per_tab = 0; + if (n_tab > 0) { + const int rest = n_w - w_max; + if (rest <= 0 || rest % n_tab != 0) { + err(RAD_E_SCHEMA, + "op '%s': %d weight operands declared; the schema has %d fixed weight operands and " + "%d weight TABLE operands, so %d must divide evenly among the tables and it does " + "not. A table takes one weight per expert and every table of one op takes the same " + "number", opname, n_w, w_max, n_tab, rest); + } else { + per_tab = rest / n_tab; + } + } else if (n_w < w_req || n_w > w_max) { + err(RAD_E_SCHEMA, "op '%s': %d weight operands declared, but the schema has %d (%d " + "required) among its %d operands", opname, n_w, w_max, w_req, + sc->n_operands); + } + + for (int i = 0; i < n_w; ++i) + if (w[i] == 0 || w[i] >= prog_.weights.size()) + err(RAD_E_INVAL, "op '%s': weight operand %d is handle %u, which this builder did not " + "hand out", opname, i, w[i]); + + if (errors_.size() != before) return RAD_NULL_HANDLE; + + /* ---- resolve. */ + OpInfo oi; + oi.op = opname; + oi.base = std::move(base); + oi.schema = sc; + oi.index = (int32_t)prog_.ops.size(); + if (!ranged_key.empty()) { + oi.ranged_key = ranged_key; + oi.range_lo = lo; + oi.range_hi = hi; + } + oi.weights.assign(w, w + n_w); + /* The many-to-one map from declared weight to schema operand position, built here so the + * layout pass, the converter and the issue path all read one answer. A fixed weight position + * takes one; a table position takes `per_tab` in a row. */ + oi.weight_opd.assign((size_t)n_w, -1); + { + int wi = 0; + for (int k = 0; sc->operands && k < sc->n_operands && wi < n_w; ++k) { + const int role = sc->operands[k].role; + if (role == RAD_OPD_WTAB) { + for (int j = 0; j < per_tab && wi < n_w; ++j) oi.weight_opd[(size_t)wi++] = k; + } else if (role == RAD_OPD_WEIGHT) { + oi.weight_opd[(size_t)wi++] = k; + } + } + } + + if (ref_) { + const size_t at = prog_.ops.size(); + if (at >= ref_->ops.size() || ref_->ops[at].op != oi.op) + return err(RAD_E_STATE, "sizing declare: op %zu is '%s', and the real declare had " + "'%s' there -- the plugin declares a different graph at a " + "smaller max_tok", at, opname, + at < ref_->ops.size() ? ref_->ops[at].op.c_str() : "nothing"); + /* AND WITH THE SAME FIXED PARAMETERS. The kernel was chosen for the real declare's, and it + * runs with them: an op whose fixed geometry follows max_tok -- a row count declared as a + * constant rather than a range -- would be handed the real size while its buffers are the + * smaller level's, and write past them into whatever the arena lent out. */ + const Geometry& rb = ref_->ops[at].base; + auto role_of = [&](const char* key) { + for (int k = 0; sc->params && k < sc->n_params; ++k) + if (sc->params[k].key && std::strcmp(sc->params[k].key, key) == 0) + return sc->params[k].role; + return (int)RAD_PROLE_NONE; + }; + const RadParam* ra = rb.params(); + const RadParam* rq = oi.base.params(); + const int na = rb.n_params(), nq = oi.base.n_params(); + std::string moved = na == nq ? "" : "the parameter list itself"; + for (int x = 0; x < na && moved.empty(); ++x) { + const RadParam* y = nullptr; + for (int k = 0; k < nq; ++k) + if (std::strcmp(rq[k].key, ra[x].key) == 0) { y = &rq[k]; break; } + if (!y || y->kind != ra[x].kind) { moved = ra[x].key; break; } + bool same = false; + switch (ra[x].kind) { + case RAD_P_INT: + /* A CAPACITY MAY SHRINK: its kernel writes by its operands' extents. */ + same = y->ival == ra[x].ival || + (role_of(ra[x].key) == RAD_PROLE_CAPACITY && y->ival <= ra[x].ival); + break; + case RAD_P_STR: same = std::strcmp(y->sval ? y->sval : "", + ra[x].sval ? ra[x].sval : "") == 0; break; + default: same = y->dval == ra[x].dval; break; + } + if (!same) moved = ra[x].key; + } + if (!moved.empty()) + return err(RAD_E_STATE, "sizing declare: op %zu ('%s') changes '%s' with the step size " + "(%s at the smaller max_tok, %s at the real one), and its " + "kernel was chosen and runs with the real one", at, opname, + moved.c_str(), oi.base.str().c_str(), rb.str().c_str()); + oi.bands = ref_->ops[at].bands; + } else { + resolve_bands(oi); + } + + rad_op h = (rad_op)prog_.ops.size(); + bool resolved = true; + for (const Band& b : oi.bands) + if (!b.dom[RAD_DOMAIN_DEVICE] && !b.dom[RAD_DOMAIN_HOST]) resolved = false; + + prog_.ops.push_back(std::move(oi)); + op_bufs_.emplace_back(); + + /* An op recorded but not handed back: the graph dump still shows it and its holes, and the + * plugin gets a falsy handle so it can offer the unfused sequence instead. A miss is not an + * error yet -- it becomes one only if the plugin issues it (spec §2.3, §3.2). */ + return resolved ? h : RAD_NULL_HANDLE; +} + +int Builder::op_resolved(rad_op h) const { + if (h == 0 || h >= prog_.ops.size()) return 0; + const OpInfo& o = prog_.ops[h]; + if (o.bands.empty()) return 0; + for (const Band& b : o.bands) + if (!b.dom[RAD_DOMAIN_DEVICE] && !b.dom[RAD_DOMAIN_HOST]) return 0; + return 1; +} + +int Builder::op_reads(rad_op h, const rad_buf* b, int n) { + if (h == 0 || h >= prog_.ops.size()) return RAD_E_INVAL; + for (int i = 0; i < n; ++i) { + if (b[i] == 0 || b[i] >= prog_.buffers.size()) return RAD_E_INVAL; + op_bufs_[h].reads.push_back(b[i]); + } + return RAD_OK; +} + +int Builder::op_writes(rad_op h, const rad_buf* b, int n) { + if (h == 0 || h >= prog_.ops.size()) return RAD_E_INVAL; + for (int i = 0; i < n; ++i) { + if (b[i] == 0 || b[i] >= prog_.buffers.size()) return RAD_E_INVAL; + op_bufs_[h].writes.push_back(b[i]); + } + return RAD_OK; +} + +/* SEE rad_buf_concurrent. A buffer a second lane touches is not bounded by the op range its + * declarations imply, so liveness hands it the whole program. Recorded rather than applied here + * because liveness runs at finish(), after every declaration is in. */ +int Builder::buf_concurrent(rad_buf b) { + if (finished_) { err(RAD_E_STATE, "buf_concurrent after declare finished"); return RAD_E_STATE; } + if (b == 0 || b >= prog_.buffers.size()) return RAD_E_INVAL; + concurrent_bufs_.insert(b); + return RAD_OK; +} + +/* SEE rad_weight_shard_span. Checked against the declaration here, where the plugin that got it + * wrong can be named; the loader checks it against the container. */ +int Builder::weight_shard_span(rad_weight h, int64_t lo, int64_t hi) { + if (finished_) { err(RAD_E_STATE, "weight_shard_span after declare finished"); return RAD_E_STATE; } + if (h == 0 || h >= prog_.weights.size()) return RAD_E_INVAL; + WeightInfo& w = prog_.weights[h]; + const RadWeightDecl& d = w.decl; + if (d.shard != RAD_SHARD_ROW && d.shard != RAD_SHARD_COL) { + err(RAD_E_INVAL, "weight '%s': a shard span on a weight that is not row- or column-sharded", + w.name.c_str()); + return RAD_E_INVAL; + } + if (lo < 0 || hi <= lo) { + err(RAD_E_INVAL, "weight '%s': shard span [%lld, %lld) is empty", w.name.c_str(), + (long long)lo, (long long)hi); + return RAD_E_INVAL; + } + /* The declared extent is the rank's own, so it has to be the span's length: each stacked + * part's for ROW, the columns for COL. */ + bool ok; + if (d.shard == RAD_SHARD_ROW) { + if (d.n_row_parts > 1) { + ok = true; + for (int g = 0; g < d.n_row_parts; ++g) ok = ok && d.row_parts[g] == hi - lo; + } else { + ok = d.rank >= 1 && d.shape[0] == hi - lo; + } + } else { + ok = d.rank == 2 && d.shape[1] == hi - lo; + } + if (!ok) { + err(RAD_E_SHAPE, "weight '%s': shard span [%lld, %lld) is %lld wide and the declared " + "extent of the split dimension is not", w.name.c_str(), (long long)lo, + (long long)hi, (long long)(hi - lo)); + return RAD_E_SHAPE; + } + w.shard_lo = lo; + w.shard_hi = hi; + return RAD_OK; +} + +/* ================================================================== name map */ +int Builder::decl_name_map(const RadNameMap* m) { + if (finished_) { err(RAD_E_STATE, "decl_name_map after declare finished"); return RAD_E_STATE; } + if (!m || !m->declared) { err(RAD_E_INVAL, "decl_name_map: null map"); return RAD_E_INVAL; } + if (m->n_src < 1 || m->n_src > 8) { + err(RAD_E_INVAL, "name map for '%s': %d source tensors, 1..8 allowed", m->declared, m->n_src); + return RAD_E_INVAL; + } + if (m->mode != RAD_MAP_COPY && m->mode != RAD_MAP_CONCAT) { + err(RAD_E_INVAL, "name map for '%s': unknown mode %d", m->declared, m->mode); + return RAD_E_INVAL; + } + + RadNameMap c{}; + c.declared = intern(scoped(m->declared)); + c.mode = m->mode; + c.n_src = m->n_src; + c.concat_dim = m->concat_dim; + for (int i = 0; i < m->n_src; ++i) { + if (!m->src[i]) { + err(RAD_E_INVAL, "name map for '%s': source %d is null", m->declared, i); + return RAD_E_INVAL; + } + c.src[i] = intern(m->src[i]); + } + /* AND `src_index`, BECAUSE THIS COPY IS FIELD BY FIELD. Every field added to RadNameMap has to + * be added here too, and the cost of missing one is not that the value is lost: `RadNameMap + * c{}` value-initialises it to ZERO, and zero means "sub-tensor 0 of this source" while the + * ABI's own default and arch/common/rad_arch.h's map_base() both say -1, "the whole tensor". + * A dropped field is therefore every map in every model quietly asking for slice 0 of its + * source (rad_convert.cpp refuses an index it cannot serve rather than ignoring it). */ + for (int i = 0; i < m->n_src; ++i) c.src_index[i] = m->src_index[i]; + for (int i = m->n_src; i < 8; ++i) c.src_index[i] = -1; + + /* A CONCAT MAP MAY BE DECLARED IN PIECES, AND EVERY OTHER REPEAT IS A BUG. + * + * `src[8]` is the ABI's cap and a sharded checkpoint blows straight through it: + * Qwen3.8-Flash-Next stores its 320-million-row n-gram embedding as 128 tensors named + * `...ngram_embedding.shard_K.weight`. Growing the array is the wrong answer -- there is one + * map per declared weight and the full model declares about fifty thousand of them, so 8 -> 128 + * would cost ~80 MB of Program to serve one tensor. + * + * So successive CONCAT maps for one declared name EXTEND it, in call order, and rad-convert + * joins their sources end to end. arch/common/rad_arch.h's map_concat_shards() is the one-line + * form; nothing else in the tree needs more than eight. + * + * Every OTHER repeat is refused rather than merged, and the refusal is the point. A lookup + * built with `std::map::emplace` KEEPS THE FIRST and drops the rest without a word, so two + * maps for one weight -- a copy-paste, a loop with a constant index -- convert a model whose + * weights came from the wrong tensors and say nothing. A merge rule that is a merge rule has + * to say which repeats it is not. */ + auto seen = name_map_first_.find(c.declared); + if (seen != name_map_first_.end()) { + const RadNameMap& first = prog_.name_map[seen->second]; + if (c.mode != RAD_MAP_CONCAT || first.mode != RAD_MAP_CONCAT) { + err(RAD_E_INVAL, "name map for '%s': declared twice, and only a CONCAT map may be " + "extended -- a repeated COPY map means two sources for one weight, and " + "which one wins is not something a declaration can express", + c.declared); + return RAD_E_INVAL; + } + if (c.concat_dim != first.concat_dim) { + err(RAD_E_INVAL, "name map for '%s': extended at concat_dim %d having been declared at " + "%d; the pieces of one concatenation join along one axis", + c.declared, c.concat_dim, first.concat_dim); + return RAD_E_INVAL; + } + } else { + name_map_first_.emplace(c.declared, prog_.name_map.size()); + } + + prog_.name_map.push_back(c); + return RAD_OK; +} + +/* Which buffer the core samples from. Refusing a second call rather than letting the last one win: + * two plugins declaring into one builder (a target and its drafter, spec §10) both have logits, + * and silently keeping the second would sample the draft model's distribution into the target's + * tokens -- fluent wrong text, and nothing would say so. The drafter's own logits are reached + * through its scope, not through this. */ +int Builder::declare_logits(rad_buf b) { + if (finished_) { err(RAD_E_STATE, "declare_logits after declare finished"); return RAD_E_STATE; } + if (b == RAD_NULL_HANDLE || (size_t)b >= prog_.buffers.size()) { + err(RAD_E_INVAL, "declare_logits: %u is not a declared buffer", (unsigned)b); + return RAD_E_INVAL; + } + if (prog_.logits_buf != RAD_NULL_HANDLE && prog_.logits_buf != b) { + err(RAD_E_STATE, "declare_logits: '%s' was already named as the logits buffer; '%s' is a " + "second one. A scoped sub-model's logits are its own, not the step's.", + prog_.buffers[prog_.logits_buf].name.c_str(), prog_.buffers[b].name.c_str()); + return RAD_E_STATE; + } + prog_.logits_buf = b; + return RAD_OK; +} + + +/* WHAT THE ENCODER IS. Checked here, at declare, for the drafter's reason: an encoder is exercised + * only when a request carries media, so a declaration the engine cannot drive would otherwise + * surface on the first image as a pass that reads or writes past a buffer. + * + * `max_patches` must be what the deployment asked for, because the plugin sized every activation + * of its tower with RadBuildCtx::max_enc_patches and the core stages up to this many patches; a + * disagreement is a tower declared for one pass size and driven at another. `out` has to hold a + * whole pass's rows, since the core reads them back from it. */ +int Builder::declare_encoder(const RadEncoderDecl* d) { + if (finished_) { err(RAD_E_STATE, "declare_encoder after declare finished"); return RAD_E_STATE; } + if (!d) { err(RAD_E_INVAL, "declare_encoder: null declaration"); return RAD_E_INVAL; } + if (d->modalities == 0) return RAD_OK; /* declaring nothing is declaring nothing */ + const char* nm = d->name && *d->name ? d->name : "(unnamed)"; + if (prog_.encoder.modalities != 0) { + err(RAD_E_STATE, "declare_encoder: '%s' already declared this program's encoder; '%s' is " + "a second one", prog_.encoder_name.c_str(), nm); + return RAD_E_STATE; + } + if ((d->modalities & ~(uint32_t)(RAD_MM_IMAGE | RAD_MM_VIDEO)) != 0) { + err(RAD_E_INVAL, "declare_encoder '%s': modalities 0x%x names a kind this engine has no " + "processor for", nm, (unsigned)d->modalities); + return RAD_E_INVAL; + } + if (d->patch_dim <= 0 || d->merge <= 0 || d->n_embd <= 0) { + err(RAD_E_INVAL, "declare_encoder '%s': patch_dim %lld, merge %lld, n_embd %lld -- all " + "three must be positive", nm, (long long)d->patch_dim, + (long long)d->merge, (long long)d->n_embd); + return RAD_E_INVAL; + } + if (d->max_patches <= 0 || d->max_patches != prog_.ctx.max_enc_patches || + d->max_patches % d->merge != 0) { + err(RAD_E_INVAL, "declare_encoder '%s': max_patches %lld, but this program was declared " + "with max_enc_patches %lld and a merge of %lld. The plugin sized its " + "activations with max_enc_patches and the core stages up to that many " + "patches a pass; they cannot differ, and a pass's patches must divide into " + "whole output rows.", nm, (long long)d->max_patches, + (long long)prog_.ctx.max_enc_patches, (long long)d->merge); + return RAD_E_INVAL; + } + if (d->out == RAD_NULL_HANDLE || (size_t)d->out >= prog_.buffers.size()) { + err(RAD_E_INVAL, "declare_encoder '%s': out %u is not a declared buffer", nm, + (unsigned)d->out); + return RAD_E_INVAL; + } + const RadBufDecl& ob = prog_.buffers[d->out].decl; + int64_t numel = 1; + for (uint32_t i = 0; i < ob.rank; ++i) numel *= ob.shape[i]; + if (ob.dtype != RAD_BF16 || ob.domain != RAD_DOMAIN_DEVICE || + numel < d->max_patches / d->merge * d->n_embd) { + err(RAD_E_INVAL, "declare_encoder '%s': out '%s' must be a device bf16 buffer of at least " + "%lld x %lld elements -- one pass's rows", nm, + prog_.buffers[d->out].name.c_str(), (long long)(d->max_patches / d->merge), + (long long)d->n_embd); + return RAD_E_INVAL; + } + prog_.encoder = *d; + prog_.encoder_name = nm; + prog_.encoder.name = nullptr; /* the plugin's storage; encoder_name is the copy */ + return RAD_OK; +} + +/* WHAT THE DRAFT HEAD IS. Every field is checked here rather than at the first draft pass: a + * drafter is exercised only once a request is speculating, so a decl that is wrong in a way the + * engine cannot act on would otherwise surface as acceptance that is quietly zero. + * + * `depth` must equal what the deployment was configured for. The plugin was TOLD the number in + * RadBuildCtx::max_spec and sized its own buffers with it, so a disagreement is not a preference + * to reconcile -- it is the plugin having declared a graph for one depth and a drafter for + * another, and the engine would drive the second against the first. */ +int Builder::declare_drafter(const RadDrafterDecl* d) { + if (finished_) { + err(RAD_E_STATE, "declare_drafter after declare finished"); + return RAD_E_STATE; + } + if (!d) { err(RAD_E_INVAL, "declare_drafter: null declaration"); return RAD_E_INVAL; } + if (d->kind == RAD_DRAFT_NONE) return RAD_OK; /* declaring nothing is declaring nothing */ + + const char* nm = d->name && *d->name ? d->name : "(unnamed)"; + if (d->kind != RAD_DRAFT_SERIAL && d->kind != RAD_DRAFT_BLOCK) { + err(RAD_E_INVAL, "declare_drafter '%s': kind %d is neither RAD_DRAFT_SERIAL nor " + "RAD_DRAFT_BLOCK", nm, d->kind); + return RAD_E_INVAL; + } + if (prog_.drafter.kind != RAD_DRAFT_NONE) { + err(RAD_E_STATE, "declare_drafter: '%s' already declared this program's drafter; '%s' is a " + "second one. One step has one draft head -- `draft_pass` carries a sign " + "and a round, and it has no room for a third meaning.", + prog_.drafter_name.c_str(), nm); + return RAD_E_STATE; + } + if (d->depth <= 0) { + err(RAD_E_INVAL, "declare_drafter '%s': depth %d. A drafter that proposes nothing is not " + "declared at all -- leave the call out.", nm, d->depth); + return RAD_E_INVAL; + } + if (prog_.ctx.max_spec > 0 && d->depth != prog_.ctx.max_spec) { + err(RAD_E_INVAL, "declare_drafter '%s': depth %d, but this program was declared with " + "max_spec %d. The plugin sized its own buffers with max_spec and the " + "engine drives this depth; they cannot differ.", + nm, d->depth, prog_.ctx.max_spec); + return RAD_E_INVAL; + } + if (d->proposal != RAD_NULL_HANDLE && (size_t)d->proposal >= prog_.buffers.size()) { + err(RAD_E_INVAL, "declare_drafter '%s': proposal buffer %u is not a declared buffer", + nm, (unsigned)d->proposal); + return RAD_E_INVAL; + } + if (d->proposal_pitch < 0) { + err(RAD_E_INVAL, "declare_drafter '%s': proposal_pitch %lld", nm, + (long long)d->proposal_pitch); + return RAD_E_INVAL; + } + /* A BLOCK PASS EMBEDS THE MASK ID AT EVERY POSITION IT HAS NOT FILLED. Without one there is + * nothing to run, and the failure without this check is a block of whatever token id 0 is. */ + if (d->kind == RAD_DRAFT_BLOCK && d->mask_token < 0) { + err(RAD_E_INVAL, "declare_drafter '%s': RAD_DRAFT_BLOCK with no mask_token. Every " + "position the block has not filled embeds it; there is nothing to run.", + nm); + return RAD_E_INVAL; + } + /* A BLOCK drafter's proposal cannot come from the sampler: the whole block is filled by one + * pass and the sampler writes one token a row. SERIAL may use either. */ + if (d->kind == RAD_DRAFT_BLOCK && d->proposal == RAD_NULL_HANDLE) { + err(RAD_E_INVAL, "declare_drafter '%s': RAD_DRAFT_BLOCK with no proposal buffer. One pass " + "fills %d positions and the sampler writes one token a row, so there is " + "nowhere for the rest of the block to arrive.", nm, d->depth); + return RAD_E_INVAL; + } + /* THE BLOCK'S ROW COUNT, defaulted and then checked against the depth it has to carry. The + * head runs over the LAST `depth` rows of the block (rad_builder.h), so a block shorter than + * the depth names rows that do not exist, and a block more than one row longer than the depth + * leaves leading rows that nothing reads -- neither is a convention, both are a mistake in + * the plugin, and both produce a drafter whose proposals are simply shifted. */ + int64_t block = d->block; + if (d->kind == RAD_DRAFT_BLOCK) { + if (block == 0) block = (int64_t)d->depth + 1; + if (block < 2 || block < (int64_t)d->depth || block > (int64_t)d->depth + 1) { + err(RAD_E_INVAL, "declare_drafter '%s': block %lld rows at depth %d. The head runs " + "over the last %d rows of the block, so the block is either %d rows " + "(the anchor predicts nothing) or %d (it does).", + nm, (long long)block, d->depth, d->depth, d->depth + 1, d->depth); + return RAD_E_INVAL; + } + } else if (block != 0) { + err(RAD_E_INVAL, "declare_drafter '%s': block %lld on a SERIAL drafter. A serial drafter " + "runs one row a round; there is no block to size.", + nm, (long long)block); + return RAD_E_INVAL; + } + + /* THE NAME LIVES IN drafter_name AND ONLY THERE. `drafter.name` is the plugin's pointer, into + * storage this program does not own, and pointing it at drafter_name instead would not + * survive the program being moved or copied out of the builder: a short name is stored inside + * the std::string object itself, so the pointer would name the builder's copy after it is + * gone. Left null, a reader that forgets this gets nothing rather than freed memory; the + * engine points its own copy of the decl at its own copy of the string. */ + prog_.drafter = *d; + prog_.drafter_name = nm; + prog_.drafter.name = nullptr; + prog_.drafter.block = block; + if (prog_.drafter.proposal_pitch == 0) prog_.drafter.proposal_pitch = 1; + return RAD_OK; +} + +void Builder::note_v(const char* f, va_list ap) { + char msg[1024]; + vsnprintf(msg, sizeof msg, f ? f : "", ap); + prog_.notes.emplace_back(msg); +} + +/* ================================================================== finalise */ +void Builder::finish_weight_uses() { + /* Layer offload is a scheduling problem and not a prediction one precisely because this walk + * exists: declare enumerated every op with its weight operands in order, so the core knows + * the entire future access sequence statically and prefetch is exact (spec §5). + * + * An op that did not resolve still counts here. That widens a weight's interval by at most the + * op the plugin fell back from, and widening it means prefetching earlier and freeing later -- + * conservative in the safe direction. */ + for (size_t i = 1; i < prog_.ops.size(); ++i) { + const OpInfo& o = prog_.ops[i]; + for (rad_weight h : o.weights) { + if (h == 0 || h >= prog_.weights.size()) continue; + WeightInfo& w = prog_.weights[h]; + if (w.first_use_op < 0) w.first_use_op = o.index; + w.last_use_op = o.index; + } + } +} + +/* The weight layout pass (spec §4.3). + * + * Nothing in the core knows that libr4d's gemm_w4a8 wants its codes in WMMA fragment order: libr4d + * says so through its layout hook, given the weight's encoding and this rank's share of its + * planes, and the manifest records what it said. The loader produces it with the same kernel's + * relayout. The hook is also where a kernel REFUSES an encoding it does not read, and that refusal + * is a declare-time error naming the weight, the encoding and the kernel. + * + * A weight touched by two kernels that want DIFFERENT stored forms is a real, diagnosable failure + * and it is named here: a weight is stored once. Discovering that at load, as a shape mismatch, + * would be much worse. */ +void Builder::finish_layouts() { + /* Who asked for each weight's layout, so a conflict names both kernels rather than one. */ + std::vector claimant(prog_.weights.size()); + + for (size_t i = 1; i < prog_.ops.size(); ++i) { + const OpInfo& o = prog_.ops[i]; + if (o.weights.empty()) continue; + + /* The hook indexes the schema's POSITIONAL operand list, not the weight list, and + * OpInfo::weight_opd is that map -- recorded at declare because RAD_OPD_WTAB makes it + * many-to-one, so it is not a function of the weight's index. */ + for (size_t wi = 0; wi < o.weights.size(); ++wi) { + rad_weight h = o.weights[wi]; + if (h == 0 || h >= prog_.weights.size()) continue; + /* An optional weight the source does not hold is absent, and no kernel reads it. */ + if (sources_ && !prog_.weights[h].enc_known && prog_.weights[h].decl.optional) + continue; + int operand = wi < o.weight_opd.size() && o.weight_opd[wi] >= 0 + ? (int)o.weight_opd[wi] : (int)wi; + + for (size_t bi = 0; bi < o.bands.size(); ++bi) { + const Band& b = o.bands[bi]; + for (int d = 0; d < RAD_N_DOMAINS; ++d) { + const Resolved& r = b.dom[d]; + if (!r || !r.row->info) continue; + const RadKernelInfo* ki = r.row->info; + WeightInfo& w = prog_.weights[h]; + + /* THIS RANK'S PLANES, as geometry: what the kernel will be handed, minus the + * bytes. */ + RadTensor t[RAD_ENC_MAX_PLANES]; + weight_planes(w, t); + + /* A ROW WITH NO LAYOUT HOOK IS NOT SILENT: it is asserting that it reads the + * selected plane AS IT IS. Reading it as "no opinion" instead admits a whole + * class of bug. + * + * The bands of one op can resolve to different kernels -- M <= 32 to one and + * M <= 64 to another -- and they all read THE SAME STORED BYTES, because a + * weight is stored once. If one of them relayouts and another does not, the + * second reads the first one's arrangement under a different interpretation, + * and nothing downstream can catch that: the byte count matches. + * + * The shape it takes, on an fp8 lm_head: logits_gemm_fp8 serves M <= 32 and + * asks for codes and scales in one row; the band above it falls to + * logits_gemm_bf16, which has no hook and reads the E4M3 codes as bf16. Such a + * model loads, serves every request under 32 rows correctly, and returns EMPTY + * completions the moment enough sequences batch together. + * + * THE HOST DOMAIN IS EXEMPT from claiming the plane as it is, and that is not + * an oversight. libref reads every weight canonically and declares no hook, so + * every op with a relaying device kernel would collide with its own reference + * fallback and no model would declare at all. The reference reading a + * relayed weight is a real hazard, but it is the one + * rad_gate_reference_kernels already refuses to serve on. */ + RadLayout L{}; + const int st = ki->layout ? ki->layout(r.geom.params(), r.geom.n_params(), + operand, &w.enc, w.sel, t, w.n_sel, &L) + : RAD_E_UNSUPPORTED; + char enc[256]; + rad_enc_format(&w.enc, enc, sizeof enc); + if (st == RAD_E_DTYPE) { + err(st, "%s: kernel %s does not read '%s' (operand %d) encoded %s -- " + "convert it to an encoding the kernel reads, or select another " + "kernel", o.op.c_str(), ki->name, w.name.c_str(), operand, enc); + continue; + } + if (st < 0 && st != RAD_E_UNSUPPORTED) { + err(st, "%s: kernel %s could not describe what it stores for operand %d " + "('%s', %s): %s", o.op.c_str(), ki->name, operand, w.name.c_str(), + enc, rad_strerror(st)); + continue; + } + if (st == RAD_E_UNSUPPORTED && d != RAD_DOMAIN_DEVICE) continue; + + const std::string tag = st == RAD_OK ? (L.tag && *L.tag ? L.tag : ki->name) + : std::string(); + if (!claimant[h].empty() && w.layout_tag != tag) { + err(RAD_E_SHAPE, + "weight '%s' is wanted in two stored forms: '%s' by %s and '%s' by %s. " + "A weight is stored once. Bands of the same op resolving to different " + "kernels is the usual cause: every band reads the same stored bytes, " + "so a kernel that relayouts has to cover the whole range or none of it", + w.name.c_str(), + w.layout_tag.empty() ? "(as it is)" : w.layout_tag.c_str(), + claimant[h].c_str(), tag.empty() ? "(as it is)" : tag.c_str(), + ki->name); + continue; + } + if (!claimant[h].empty()) continue; /* the same form, asked again */ + claimant[h] = ki->name; + + if (tag.empty()) { + if (w.n_sel != 1) + err(RAD_E_SHAPE, "%s: kernel %s reads '%s' as it is, but the " + "declaration takes %d planes of '%s' as one operand, " + "and only a kernel's layout can join planes", + o.op.c_str(), ki->name, w.name.c_str(), w.n_sel, + w.source.c_str()); + continue; /* the stored defaults decl_weight set stand */ + } + if (w.widen) { + err(RAD_E_DTYPE, "'%s' is declared %s over a %s plane and kernel %s " + "relayouts it; a widening and a relayout are not both " + "done at load", w.name.c_str(), + rad_dtype_name(w.decl.dtype), + rad_dtype_name(w.enc.plane[w.sel[0]].dtype), ki->name); + continue; + } + w.layout_tag = tag; + w.identity = false; + w.lay_op = (int32_t)i; + w.lay_band = (int32_t)bi; + w.lay_dom = d; + w.lay_operand = operand; + w.stored_dtype = L.dtype ? L.dtype : w.decl.dtype; + w.stored_rank = L.rank; + for (uint32_t k = 0; k < RAD_MAX_RANK; ++k) + w.stored_shape[k] = k < L.rank ? L.shape[k] : 0; + if (L.align > 0) w.align = L.align; + /* The hook's byte count wins: it includes whatever padding the layout implies, + * and the core cannot derive that from a shape. */ + if (L.bytes > 0) { + w.stored_bytes = L.bytes; + } else { + int64_t nel = 1; + for (uint32_t k = 0; k < L.rank && k < RAD_MAX_RANK; ++k) nel *= L.shape[k]; + const int64_t bs = rad_dtype_bytes(w.stored_dtype, nel); + if (bs <= 0) { + err(RAD_E_SHAPE, "%s: kernel %s stores '%s' as dtype %u and gave no " + "byte count, which the core cannot size", + o.op.c_str(), ki->name, w.name.c_str(), w.stored_dtype); + continue; + } + w.stored_bytes = bs; + } + } + } + } + } + + /* A weight taking several planes as one operand needs a kernel to join them; one no op reads + * has none. */ + for (size_t h = 1; h < prog_.weights.size(); ++h) { + const WeightInfo& w = prog_.weights[h]; + if (w.n_sel > 1 && w.identity && claimant[h].empty()) + err(RAD_E_SHAPE, "'%s' takes %d planes of '%s' as one weight and no op reads it, so " + "nothing says how they are stored", w.name.c_str(), w.n_sel, + w.source.c_str()); + } +} + +void Builder::finish_kv_groups() { + for (size_t g = 1; g < prog_.kv_groups.size(); ++g) { + KVGroupInfo& gi = prog_.kv_groups[g]; + const RadKVGroupDecl& d = gi.decl; + + if ((d.kind == RAD_KV_FULL || d.kind == RAD_KV_WINDOW) && gi.block_size == 0) { + /* The plugin may never have asked. The manifest still needs the answer, and asking + * here reports the same diagnostic it would have got. */ + kv_block_size((rad_kvgroup)g); + } + + int64_t elem_n_head = d.n_head_kv > 0 ? d.n_head_kv : 1; + /* EVERY LAYER BOUND TO THE GROUP, because that is what a page is. KVManager documents both + * of these as covering the whole bundle -- "one page covers every layer bound to the group. + * That is where the zero-padding property lives" -- and its own fallback formula multiplies + * by the layer count. A figure computed here for ONE layer under-sizes the pool by the + * layer count, because that fallback is unreachable whenever the builder supplies a value: + * the manager then divides a one-layer page across every bound layer, giving a per-layer + * stride that is a fraction of a layer and a layer base pointer that need not even be + * 2-byte aligned. It surfaces as an alignment refusal from the attention kernel at the + * SECOND bound layer, layer 0 being at offset 0. */ + const int64_t n_bound = gi.layers.empty() ? 1 : (int64_t)gi.layers.size(); + switch (d.kind) { + case RAD_KV_FULL: + case RAD_KV_WINDOW: + /* One block holds K and V for block_size tokens: the pair is the unit the block + * manager allocates, so it is the unit sized here. */ + gi.bytes_per_block = + rad_dtype_bytes(d.dtype, 2 * gi.block_size * elem_n_head * d.head_dim) * n_bound; + gi.bytes_per_state = 0; + break; + case RAD_KV_LINEAR: + /* Per sequence and fixed size: 32 heads of 128x128 fp32 is 2 MiB a layer, which + * is why it cannot be snapshotted per block (spec §7.3). */ + gi.bytes_per_block = 0; + gi.bytes_per_state = rad_dtype_bytes( + d.dtype, elem_n_head * (d.state_dim[0] ? d.state_dim[0] : 1) + * (d.state_dim[1] ? d.state_dim[1] : 1)) * n_bound; + break; + case RAD_KV_CONV: { + /* A rolling window of conv_width-1 + n_spec + 1 entries, so a speculative + * rejection is a change of read offset rather than a recompute (spec §10). The + * window is sized for the largest speculative window this deployment was + * configured for. + * + * THE +1 IS THE VERIFY STEP'S OWN OUTPUT, and it is not optional. A verify writes + * 1 + n_spec conv outputs before anyone knows which survive, so peak occupancy is + * the conv_width-1 of retained history PLUS all 1 + n_spec of them. Sizing this + * `conv_width - 1 + max_spec` instead -- six entries at width 4 depth 3 -- puts it + * one short of the modulus BatchBuilder::init and Scheduler::conv_window cycle + * `conv_cursor` by, which is `conv_width - 1 + n_spec + 1`, seven: `(cursor + 1 + + * a) % 7` reaches 6, one past the end of the allocation and into the slot that + * belongs to the next sequence. At n_spec 0 the two agree (modulus conv_width, + * history conv_width-1 plus the one output), so the discrepancy hides there. */ + int64_t entries = (d.conv_width > 0 ? d.conv_width - 1 : 0) + + (prog_.ctx.max_spec > 0 ? prog_.ctx.max_spec : 0) + 1; + if (entries <= 0) entries = 1; + gi.bytes_per_block = 0; + gi.bytes_per_state = + rad_dtype_bytes(d.dtype, elem_n_head * d.head_dim * entries) * n_bound; + break; + } + default: break; + } + std::sort(gi.layers.begin(), gi.layers.end()); + + /* A group nothing is bound to is a group the block manager cannot size: how many state + * instances a sequence owns is the layer count, and assuming one would make the page size + * a guess. KVManager::configure refuses it, so it is refused here where the name of the + * missing call is still obvious. */ + if (gi.layers.empty()) + err(RAD_E_STATE, + "kv group '%s' has no layers bound: call rad_bind_layer_kv(b, layer, g) for every " + "layer that owns state in this group, or the block manager cannot tell how many " + "state instances a sequence holds", gi.name.c_str()); + } +} + +void Builder::finish_buffer_liveness() { + const int32_t last_op = (int32_t)prog_.ops.size() - 1; + /* A program that runs a second lane gets a second scratch region with it: see + * Program::scratch_regions. The concurrent buffers are how an architecture says it has one. */ + prog_.scratch_regions = concurrent_bufs_.empty() ? 1 : 2; + + for (size_t i = 1; i < prog_.buffers.size(); ++i) { + BufferInfo& b = prog_.buffers[i]; + + /* PERSIST survives across steps and DERIVED is written once per step by the core before + * any op runs. Both are live at every op by construction, and saying so here rather than + * leaving -1 means one rule reads the field and the plan and the dump agree. */ + if (b.decl.kind != RAD_BUF_TRANSIENT) { + b.first_def = 0; + b.last_use = last_op > 0 ? last_op : 0; + continue; + } + + /* The second lane: the declared range is not a bound on when the bytes are in use. */ + if (concurrent_bufs_.count((rad_buf)i)) { + b.first_def = 0; + b.last_use = last_op > 0 ? last_op : 0; + continue; + } + + int32_t first = -1, last = -1; + for (size_t o = 1; o < op_bufs_.size(); ++o) { + auto touches = [&](const std::vector& v) { + return std::find(v.begin(), v.end(), (rad_buf)i) != v.end(); + }; + if (!touches(op_bufs_[o].reads) && !touches(op_bufs_[o].writes)) continue; + if (first < 0) first = (int32_t)o; + last = (int32_t)o; + } + + if (first < 0) { + /* Nothing declared a use. The sound assumption is the whole program: an op may issue + * any handle obtained during declare, in any order, so declaration position proves + * nothing about when a buffer is read. It costs sharing, and --debug-graph says how + * much (see rad_build.h on rad_op_reads/rad_op_writes). */ + b.first_def = 0; + b.last_use = last_op > 0 ? last_op : 0; + } else { + b.first_def = first; + b.last_use = last; + } + + /* THE LOGITS BUFFER IS READ AFTER THE DECLARED OP LIST AND NOT BY IT. The plugin's lm_head + * WRITES it and declares that write, so liveness derived from declarations alone ends its + * life at that op -- and everything that actually consumes it comes later: the sampler's + * stages (core/sample/sampler.cpp declares its ops with no buffer lists, because its own + * planes are PERSIST for the same reason), the logprob readback, and the engine. + * + * Extending it to the last op is the truthful statement and costs nothing measurable: the + * lm_head is at the end of the graph, so the set of buffers still live after it is nearly + * empty and nothing that shared with logits before is prevented from doing so. The + * undeclared-use guard in core/runtime/issue.cpp is what refuses the untruthful version. */ + if ((rad_buf)i == prog_.logits_buf && last_op > b.last_use) b.last_use = last_op; + } +} + +int Builder::finish() { + if (finished_) return status_; + finished_ = true; + + /* A sizing declare wants its buffers and their liveness and nothing else: its kernels are the + * real declare's, already initialised, and its weights and KV groups are never used. */ + if (ref_) { + finish_buffer_liveness(); + return status_; + } + + /* A WEIGHT DECLARED BEFORE ITS NAME MAP was read as plain in its declared dtype, and its + * kernels were chosen for that: the checkpoint or the recipe behind the builder is searched + * through the name map, so asking first finds nothing. Asked again now, a source that answers + * is that ordering, named rather than served as the wrong encoding. */ + if (sources_) + for (size_t h = 1; h < prog_.weights.size(); ++h) { + const WeightInfo& w = prog_.weights[h]; + WeightSource ws; + if (!w.enc_known && lookup_source(w.source, &ws) == RAD_OK) + err(RAD_E_STATE, "weight '%s' was declared before the name map entry for '%s', so " + "it was read as plain %s and its kernels chosen for that -- " + "declare the map first (rad_weight_encoding)", w.name.c_str(), + w.source.c_str(), rad_dtype_name(w.decl.dtype)); + } + + finish_instances(); + finish_weight_uses(); + finish_layouts(); + finish_kv_groups(); + finish_buffer_liveness(); + + int s = plan_buffers(prog_, &bufrep_); + if (s < 0 && status_ == RAD_OK) status_ = s; + + if (!prog_.misses.empty()) { + /* Reported whole, at the end, never the first failure at the top (spec §1 step 4). Which + * of these is fatal is the engine's call: a device miss covered by a host kernel costs + * speed, a host miss costs a placement option, and one covered by neither costs the + * model. + * + * SPLIT BY DOMAIN, because the two counts mean different things and one total means + * neither. Every caller of this that is not the engine -- rad-check, rad-tune, rad-convert + * -- reads this line and nothing else, so it has to say which kind it found. */ + /* A device miss whose op resolved on the HOST for the same band is not a hole -- the + * planner runs it there (engine_bringup.cpp's miss_report says the same thing at more + * length). Counting it as a device miss makes a deliberately host-only op open every run + * with a warning that names a hole there is not. */ + std::set> no_host; + for (const Program::Miss& m : prog_.misses) + if (m.domain == RAD_DOMAIN_HOST) no_host.emplace(m.op, m.span); + size_t dev = 0; + for (const Program::Miss& m : prog_.misses) + if (m.domain != RAD_DOMAIN_HOST && no_host.count(std::make_pair(m.op, m.span))) ++dev; + /* A host-only miss set is not a warning at all -- see the report in engine_bringup.cpp -- + * so it does not get warned about here either. The device count is the one that means + * something to a tool reading this line and nothing else. */ + RAD_LOG_AT(dev ? Log::Warn : Log::Debug, + "declare: %zu device band(s) and %zu host band(s) resolved to nothing; " + "run with --debug-graph for the full list", dev, prog_.misses.size() - dev); + } + return status_; +} + +} /* namespace rad */ + +/* ================================================================== the C surface */ +/* Every entry point in rad_builder.h. Each is a static_cast and a forward: the handle IS the + * builder, so there is no table lookup between a plugin's call and the work. */ +extern "C" { + +static rad::Builder* B(RadBuilder* b) { return static_cast(b); } + +rad_weight rad_decl_weight(RadBuilder* b, const char* name, const RadWeightDecl* d) { + if (!b) return RAD_NULL_HANDLE; + return B(b)->decl_weight(name, d); +} + +int rad_weight_encoding(RadBuilder* b, const char* source, RadEncoding* out, int64_t* shape, + uint32_t* rank) { + if (!b) return RAD_E_INVAL; + return B(b)->weight_encoding(source, out, shape, rank); +} + +rad_buf rad_decl_buffer(RadBuilder* b, const char* name, const RadBufDecl* d) { + if (!b) return RAD_NULL_HANDLE; + return B(b)->decl_buffer(name, d); +} + +rad_kvgroup rad_decl_kv_group(RadBuilder* b, const char* name, const RadKVGroupDecl* d) { + if (!b) return RAD_NULL_HANDLE; + return B(b)->decl_kv_group(name, d); +} + +int64_t rad_kv_block_size(RadBuilder* b, rad_kvgroup g) { + if (!b) return 0; + return B(b)->kv_block_size(g); +} + +int rad_bind_layer_kv(RadBuilder* b, int layer, rad_kvgroup g) { + if (!b) return RAD_E_INVAL; + return B(b)->bind_layer_kv(layer, g); +} + +rad_op rad_decl_op(RadBuilder* b, const char* op, const RadParam* params, int n_params, + const rad_weight* weights, int n_weights) { + if (!b) return RAD_NULL_HANDLE; + return B(b)->decl_op(op, params, n_params, weights, n_weights); +} + +int rad_op_resolved(RadBuilder* b, rad_op h) { + if (!b) return 0; + return B(b)->op_resolved(h); +} + +/* Proposed additions to rad_builder.h -- defined here so the mechanism exists and core-side + * callers (rad-convert, the tests) can use it. A C plugin cannot until the declarations + * move into the frozen header. */ +int rad_op_reads(RadBuilder* b, rad_op h, const rad_buf* bufs, int n) { + if (!b || (!bufs && n)) return RAD_E_INVAL; + return B(b)->op_reads(h, bufs, n); +} + +int rad_op_writes(RadBuilder* b, rad_op h, const rad_buf* bufs, int n) { + if (!b || (!bufs && n)) return RAD_E_INVAL; + return B(b)->op_writes(h, bufs, n); +} + +int rad_buf_concurrent(RadBuilder* b, rad_buf buf) { + if (!b) return RAD_E_INVAL; + return B(b)->buf_concurrent(buf); +} + +int rad_weight_shard_span(RadBuilder* b, rad_weight w, int64_t lo, int64_t hi) { + if (!b) return RAD_E_INVAL; + return B(b)->weight_shard_span(w, lo, hi); +} + +int rad_decl_name_map(RadBuilder* b, const RadNameMap* m) { + if (!b) return RAD_E_INVAL; + return B(b)->decl_name_map(m); +} + +int rad_declare_logits(RadBuilder* b, rad_buf logits) { + if (!b) return RAD_E_INVAL; + return B(b)->declare_logits(logits); +} + +int rad_declare_drafter(RadBuilder* b, const RadDrafterDecl* d) { + if (!b) return RAD_E_INVAL; + return B(b)->declare_drafter(d); +} + +int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d) { + if (!b) return RAD_E_INVAL; + return B(b)->declare_encoder(d); +} + +void rad_note(RadBuilder* b, const char* f, ...) { + if (!b) return; + va_list ap; + va_start(ap, f); + B(b)->note_v(f, ap); + va_end(ap); +} + +/* ---- model metadata accessors. The free-form key/value the container header carried, which the + * struct above does not name. The core never interprets these; a plugin reads what it needs. */ +static const char* meta_lookup(const RadModelMeta* m, const char* key) { + if (!m || !key || !m->kv_key || !m->kv_val) return nullptr; + for (int i = 0; i < m->n_kv; ++i) + if (m->kv_key[i] && !std::strcmp(m->kv_key[i], key)) return m->kv_val[i]; + return nullptr; +} + +long long rad_meta_geti(const RadModelMeta* m, const char* key, long long dflt) { + const char* v = meta_lookup(m, key); + if (!v || !*v) return dflt; + char* end = nullptr; + long long r = std::strtoll(v, &end, 0); + return (end && end != v) ? r : dflt; +} + +double rad_meta_getf(const RadModelMeta* m, const char* key, double dflt) { + const char* v = meta_lookup(m, key); + if (!v || !*v) return dflt; + char* end = nullptr; + double r = std::strtod(v, &end); + return (end && end != v) ? r : dflt; +} + +const char* rad_meta_gets(const RadModelMeta* m, const char* key, const char* dflt) { + const char* v = meta_lookup(m, key); + return v ? v : dflt; +} + +} /* extern "C" */ diff --git a/core/build/rad_graph.cpp b/core/build/rad_graph.cpp new file mode 100644 index 00000000..a595918b --- /dev/null +++ b/core/build/rad_graph.cpp @@ -0,0 +1,828 @@ +/* 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 + +#include +#include +#include +#include + +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 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& v) { + std::string s; + for (size_t i = 0; i < v.size(); ++i) { if (i) s += ", "; s += v[i]; } + return s; +} + +} /* namespace */ + +std::string dump_graph_str(const Program& p, const std::vector* errors) { + 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 names; + for (rad_weight h : o.weights) + names.push_back(h < p.weights.size() ? p.weights[h].name : fmt("", h)); + s += fmt(" weights %s\n", join_names(names).c_str()); + } + + /* 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 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(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 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 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* 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 order; /* unique keys, first-seen order */ + std::vector seq; /* every declared op, in order, by key */ + std::unordered_map group; + std::unordered_map 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 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 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 */ diff --git a/core/build/startup.cpp b/core/build/startup.cpp new file mode 100644 index 00000000..180dd6fd --- /dev/null +++ b/core/build/startup.cpp @@ -0,0 +1,381 @@ +/* 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 + +#include +#include + +namespace rad { + +/* One Registry for the life of the process. A Resolved, a Band and a KernelRow all point into a + * plugin's static tables, and the Program outlives the call that built it, so the registry cannot + * be a local. registry.h says the same thing about the engine. */ +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* 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 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 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 rad_home_dirs(const std::string& home) { + std::vector 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 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 home_subdirs(const std::string& home, const char* sub) { + std::vector 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& 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 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 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 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 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 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 lk(mu_); + auto it = missing_.find(name); + return it == missing_.end() ? std::string() : it->second; +} + +std::vector CheckpointSources::refused() const { + std::lock_guard lk(mu_); + std::vector 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& also, + const Program* ref, const WeightSourceFn& sources) { + 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); + + 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 */ diff --git a/core/build/startup.h b/core/build/startup.h new file mode 100644 index 00000000..d761f38c --- /dev/null +++ b/core/build/startup.h @@ -0,0 +1,148 @@ +/* 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 +#include +#include +#include +#include + +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 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 rad_home_dirs(const std::string& home); +/* `/` for the first home on the path that has it; the first home's when none does. */ +std::string rad_home_file(const std::string& home, const std::string& rel); + +/* The Registry loaded into is process-lifetime, because a Resolved, a Band and a KernelRow all + * point into a plugin's static tables and the Program outlives this call. */ +/* `arch_id` and `quant` are BOTH halves of the selection key (spec §2.4, rad_builder.h): a family + * has one plugin per weight format and they all answer the same architecture id. `quant` is the + * container's own descriptor -- RadModelMeta::quant, RadFileHeader::quant -- and "" is the + * unquantised case, which matches a plugin that says "" and nothing else. */ +int rad_tools_load_plugins(const std::string& radiance_home, + const std::vector& 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. */ +int rad_tools_declare(const LoadedPlugins& plugins, const RadModelMeta& meta, + const RadBuildCtx& ctx, Program* out, + const std::function& also = {}, + const Program* ref = nullptr, const WeightSourceFn& sources = {}); + +/* 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 refused() const; + +private: + int answer(const std::string& name, const Program& prog, WeightSource* out); + Checkpoint& ck_; + mutable std::mutex mu_; + std::map got_; + std::map refused_; + std::map missing_; +}; + + +/* ------------------------------------------------------------------ the reference-kernel gate */ +/* A reference library -- one that declares itself so, RadPluginReferenceFn -- is BOTH the fallback + * that makes an unsupported model run at reduced speed and the oracle rad-kbench measures against + * (spec §17). The first of those is a hazard in production and + * the second is not, so which one is happening has to be a decision and not a discovery: a model + * that silently fell back to the reference implementation for its GEMMs is a model running orders + * of magnitude below what the machine can do, and nothing in the output says so. + * + * So: resolving to a reference library is FATAL unless --debug-accept-reference-kernels was + * passed. The flag is spelled with `debug` in it because that is what it is for. */ + +int rad_reference_ops(const Program& p, std::vector* out); + +/* Report and refuse, or report and continue when `allow`. `what` names the caller ("serve", + * "the container's layout") so the message says what the consequence actually is. */ +int rad_gate_reference_kernels(const Program& p, bool allow, const char* what); + +Registry& rad_tools_registry(); + +} /* namespace rad */ diff --git a/core/config.cpp b/core/config.cpp new file mode 100644 index 00000000..a040318f --- /dev/null +++ b/core/config.cpp @@ -0,0 +1,393 @@ +/* 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 +#include + +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" }, + { "--tp-wire-min-kb", "N", "smallest all-reduce, in KiB, the wht6 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" }, + { "--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" }, + { "--mm-max-patches", "N", "patches one encoder pass carries, and so the largest image (a patch is 16x16\n" + "pixels). Default `auto`: 16384 when the container carries a vision tower. 0\n" + "serves text only and keeps the tower off the card" }, + { "--generation-config", "PATH", "a generation_config.json whose sampler settings become the default\n" + " for requests that send none. Without it the container's own\n" + " `generation.*` metadata is used, then a .generation.json\n" + " beside the container, then the built-in defaults" }, + { "--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 and answer nothing. \"none\" turns thinking off" }, + + { "--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"); +} + +static std::vector split_commas(const std::string& s) { + std::vector out; + size_t i = 0; + while (i <= s.size()) { + size_t j = s.find(',', i); + if (j == std::string::npos) j = s.size(); + if (j > i) out.push_back(s.substr(i, j - i)); + i = j + 1; + } + return out; +} + +/* 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("--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("--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("--generation-config")) { if (!(v = need(i))) return RAD_E_INVAL; + c->generation_config = v; } + /* A NEGATIVE VALUE IS REFUSED HERE, not left to the range checks below: the fields use + * a negative number to mean "not set", so `--temp -0.5` would otherwise be read as no + * flag at all and the container's default served in its place. */ + else if (S("--temp")) { if (!(v = need(i))) return RAD_E_INVAL; + c->sample_temp = (float)atof(v); + if (!(c->sample_temp >= 0.0f)) { + RAD_ERR("--temp must be in [0, 2], not '%s'", v); + return RAD_E_INVAL; } } + else if (S("--top-k")) { if (!(v = need(i))) return RAD_E_INVAL; + c->sample_top_k = atoi(v); + if (c->sample_top_k < 0) { + RAD_ERR("--top-k must be >= 0 (0 disables " + "it), not '%s'", v); + return RAD_E_INVAL; } } + else if (S("--top-p")) { if (!(v = need(i))) return RAD_E_INVAL; + c->sample_top_p = (float)atof(v); + if (!(c->sample_top_p >= 0.0f)) { + RAD_ERR("--top-p must be in (0, 1], not '%s'", v); + return RAD_E_INVAL; } } + else if (S("--min-p")) { if (!(v = need(i))) return RAD_E_INVAL; + c->sample_min_p = (float)atof(v); + if (!(c->sample_min_p >= 0.0f)) { + RAD_ERR("--min-p must be in [0, 1], not '%s'", v); + return RAD_E_INVAL; } } + 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; + } + + /* THE SAME RANGES THE REQUEST PARSER ENFORCES, and refused here rather than at the first + * request. A default outside them would otherwise be a 400 on every request that omits the + * field -- a server that starts, reports healthy, and answers nothing. */ + if (c->sample_temp >= 0.0f && c->sample_temp > 2.0f) { + RAD_ERR("--temp must be in [0, 2]"); return RAD_E_INVAL; } + if (c->sample_top_p >= 0.0f && !(c->sample_top_p > 0.0f && c->sample_top_p <= 1.0f)) { + RAD_ERR("--top-p must be in (0, 1]"); return RAD_E_INVAL; } + if (c->sample_min_p >= 0.0f && c->sample_min_p > 1.0f) { + RAD_ERR("--min-p must be in [0, 1]"); return RAD_E_INVAL; } + + return RAD_OK; +} + +} /* namespace rad */ diff --git a/core/device/aql.cpp b/core/device/aql.cpp new file mode 100644 index 00000000..b5d5a5c3 --- /dev/null +++ b/core/device/aql.cpp @@ -0,0 +1,2207 @@ +/* aql.cpp -- the AQL device backend: every stream is an HSA queue the engine owns, and every + * kernel, copy, fill and fence on it is an AQL packet this file writes. + * + * WHY THE ENGINE WRITES ITS OWN PACKETS. hipLaunchKernel costs 0.5-1.3 us of host time a + * dispatch, where writing the packet is 6 ns; and HIP fences every kernel at SYSTEM scope, which + * costs the device about half a microsecond between two dependent kernels that an AGENT-scope + * fence does not. A decode step is ~1600 dispatches a rank, so both are milliseconds a step. HIP + * also retires a Command object per launch on a thread of its own, which is most of a core under + * load. None of that is needed to put a kernel on a queue. + * + * WHAT STAYS WITH HIP. Allocation, device properties, peer access, IPC and elastic memory are + * HIP's, through the HIP backend's own entry points. So is compiling and REGISTERING kernels: a + * kernel library is built by hipcc and calls hipLaunchKernel exactly as it would under HIP. This + * file defines hipLaunchKernel in the executable, which the dynamic linker binds every plugin's + * reference to ahead of the HIP runtime's, and it records what __hipRegisterFatBinary and + * __hipRegisterFunction are told so a host stub maps to its own code object. A launch onto a + * stream this backend did not create is forwarded to HIP unchanged. + * + * THE FENCES. Two kernels on one queue see each other's writes through the L2 with an agent-scope + * fence; the system scope is only needed where memory the L2 does not see is involved: + * + * - the kernel argument ring lives in VRAM and the host writes it through the BAR, which the L2 + * does not snoop. A slot is rewritten one ring lap after it was last read, so a system-scope + * acquire is placed at least once per half lap: at agent scope alone, every kernel after the + * first lap reads its predecessor's arguments. Slots are 1 KiB so that no + * kernel's argument fetch shares a cache line with the next slot; + * - memory the host wrote. The first dispatch after the host has waited on any queue takes a + * system-scope acquire, since that wait is what host writes for the next step follow; + * - copies that read or write host or peer memory carry the scope themselves, and so do the + * barrier packets that implement events and synchronisation. + */ +#include "device.h" + +#if defined(RAD_HAVE_HIP) && RAD_HAVE_HIP + +/* The standard headers first: HIP's defines __noinline__, which (reached through + * ) uses as an attribute name. */ +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "aql.h" +#include "rad_format.h" +#include "../rad_internal.h" + +#include +#include +#include +#include + + +namespace rad { + +int aql_vmem_device_of(const void* addr, int* dev); + +namespace aql { +namespace { + +constexpr uint64_t kStreamMagic = 0x5241442d41514c53ull; /* "RAD-AQLS" */ +constexpr uint64_t kEventMagic = 0x5241442d41514c45ull; /* "RAD-AQLE" */ +constexpr uint64_t kTapeMagic = 0x5241442d41514c54ull; /* "RAD-AQLT" */ +constexpr uint32_t kQueuePackets = 4096; +constexpr uint32_t kKargSlot = 1024; +constexpr uint32_t kKargMax = kKargSlot - 256; +constexpr int kMaxDevices = 64; +constexpr size_t kBounceBytes = 8u << 20; + +/* ------------------------------------------------------------------ the HIP entry points */ + +struct Real { + hipError_t (*launch)(const void*, dim3, dim3, void**, size_t, hipStream_t) = nullptr; + hipError_t (*memcpy2d)(void*, size_t, const void*, size_t, size_t, size_t, hipMemcpyKind, + hipStream_t) = nullptr; + hipError_t (*memcpy)(void*, const void*, size_t, hipMemcpyKind, hipStream_t) = nullptr; + hipError_t (*memset)(void*, int, size_t, hipStream_t) = nullptr; + hipError_t (*memset_sync)(void*, int, size_t) = nullptr; + hipError_t (*sync)(hipStream_t) = nullptr; + hipError_t (*last)(void) = nullptr; + hipError_t (*peek)(void) = nullptr; + hipError_t (*ev_record)(hipEvent_t, hipStream_t) = nullptr; + hipError_t (*wait_ev)(hipStream_t, hipEvent_t, unsigned) = nullptr; + void** (*reg_fat)(const void*) = nullptr; + void (*reg_fn)(void**, const void*, char*, const char*, unsigned, void*, void*, void*, void*, + int*) = nullptr; + void (*unreg_fat)(void**) = nullptr; +}; + +template void bind(F*& f, const char* name) { + if (!f) f = reinterpret_cast(dlsym(RTLD_NEXT, name)); +} + +Real& real() { + static Real* r = [] { + Real* x = new Real(); + bind(x->launch, "hipLaunchKernel"); + bind(x->memcpy2d, "hipMemcpy2DAsync"); + bind(x->memcpy, "hipMemcpyAsync"); + bind(x->memset, "hipMemsetAsync"); + bind(x->memset_sync, "hipMemset"); + bind(x->sync, "hipStreamSynchronize"); + bind(x->last, "hipGetLastError"); + bind(x->peek, "hipPeekAtLastError"); + bind(x->ev_record, "hipEventRecord"); + bind(x->wait_ev, "hipStreamWaitEvent"); + bind(x->reg_fat, "__hipRegisterFatBinary"); + bind(x->reg_fn, "__hipRegisterFunction"); + bind(x->unreg_fat, "__hipUnregisterFatBinary"); + return x; + }(); + return *r; +} + +/* THE LAST-ERROR SLOT, AS HIP KEEPS IT. Every HIP call overwrites the thread's last error with + * its own result, success included, and a plugin's `launch; if (hipGetLastError())` depends on + * exactly that: an error left by some earlier call must not be reported against the launch. An + * entry point handled here records its result and marks itself as the thread's latest call, and + * hipGetLastError answers from it while the mark stands. */ +thread_local hipError_t t_err = hipSuccess; +thread_local bool t_ours = false; + +inline hipError_t ret(hipError_t e) { t_err = e; t_ours = true; return e; } +thread_local uint8_t t_next_fence = 0; + +/* WHETHER ANYTHING WAS EVER HANDED TO HIP'S OWN STREAMS. Every submission this process makes goes + * to the backend's queues; a HIP stream gets work only when a caller passes one the backend does + * not own, and that is forwarded. Until then HIP's default stream is empty, so synchronising it is + * a no-op answered here -- asking HIP would make it build the stream's queue first. */ +std::atomic g_hip_streams_used{false}; + +/* ------------------------------------------------------------------ kernels */ + +struct KernelRec { + uint64_t object = 0; + uint32_t kernarg_size = 0; + uint32_t group_size = 0; + uint32_t private_size = 0; + uint16_t n_explicit = 0; + std::vector ex_off, ex_size; + int32_t hid[16]; /* offset of each Hidden kind, or -1 */ + uint8_t hid_size[16]; + std::string name; +}; + +struct ModuleImage { + const void* co = nullptr; + size_t size = 0; + std::string err; + std::unordered_map meta; + bool parsed = false; +}; + +struct Module { + const void* bundle = nullptr; + std::mutex mu; + std::unordered_map image; /* by isa */ + hsa_executable_t exec[kMaxDevices] = {}; + bool loaded[kMaxDevices] = {}; + std::string load_err[kMaxDevices]; +}; + +struct Func { + Module* mod = nullptr; + std::string name; + std::atomic rec[kMaxDevices]; + std::string err[kMaxDevices]; + Func() { for (auto& r : rec) r.store(nullptr, std::memory_order_relaxed); } +}; + +struct Registry { + std::mutex mu; + std::unordered_map by_handle; + std::unordered_map by_stub; + /* Every registration in the order it happened, so the fat binaries one dlopen brought in are a + * contiguous run the plugin loader can check against the card (a_code_runs). */ + std::vector order; +}; + +Registry& reg() { + static Registry* r = new Registry(); /* never destroyed: unregistration runs from atexit */ + return *r; +} + +/* ------------------------------------------------------------------ devices */ + +struct Dev { + hsa_agent_t agent{}; + std::string isa; /* the agent's name, "gfx1201": for messages */ + std::vector isas; /* the targets it accepts, preferred first; see agent_isas */ + hsa_amd_memory_pool_t vram{}; + bool has_vram = false; +}; + +struct Global { + bool ok = false; + std::string why; + hsa_agent_t cpu{}; + hsa_amd_memory_pool_t host_fine{}; + bool has_host_fine = false; + std::vector dev; /* by HIP ordinal */ + uint64_t ts_freq = 1; + /* Bumped whenever the host has waited on a queue: the next dispatch on every queue takes a + * system-scope acquire, because what the host writes for the next step follows such a wait. */ + std::atomic host_epoch{1}; + std::mutex streams_mu; + std::vector streams; + /* Host waits; see "host waits". */ + int kfd = -1; /* the driver, for its event waits */ + hsa_signal_t fault{0}; /* fired by a queue fault, to end every wait */ + std::atomic faulted{false}; +}; + +Global& G() { + static Global* g = new Global(); + return *g; +} + +std::string agent_isa(hsa_agent_t a) { + char name[64] = {0}; + hsa_agent_get_info(a, HSA_AGENT_INFO_NAME, name); + return name; +} + +hsa_status_t collect_isa(hsa_isa_t isa, void* data) { + uint32_t len = 0; + if (hsa_isa_get_info_alt(isa, HSA_ISA_INFO_NAME_LENGTH, &len) != HSA_STATUS_SUCCESS || len == 0 || + len > 256) + return HSA_STATUS_SUCCESS; + std::vector name((size_t)len + 1, '\0'); + if (hsa_isa_get_info_alt(isa, HSA_ISA_INFO_NAME, name.data()) == HSA_STATUS_SUCCESS) + static_cast*>(data)->emplace_back(name.data()); + return HSA_STATUS_SUCCESS; +} + +/* The code-object targets an agent runs, in the runtime's order of preference: its own processor + * first, then the generic target of its family, each with the modes the agent is in -- for one of + * these R9700s "gfx1201" then "gfx12-generic". A kernel library built for either loads; asking the + * runtime rather than keeping a family table here is what keeps a card released after this file + * from needing an edit to it. */ +std::vector agent_isas(hsa_agent_t a) { + std::vector v; + hsa_agent_iterate_isas(a, collect_isa, &v); + if (v.empty()) v.push_back("amdgcn-amd-amdhsa--" + agent_isa(a)); + return v; +} + +hsa_status_t collect_gpu(hsa_agent_t a, void* data) { + hsa_device_type_t t; + if (hsa_agent_get_info(a, HSA_AGENT_INFO_DEVICE, &t) != HSA_STATUS_SUCCESS) return HSA_STATUS_SUCCESS; + auto* v = static_cast*>(data); + if (t == HSA_DEVICE_TYPE_GPU) v->push_back(a); + else if (t == HSA_DEVICE_TYPE_CPU && !G().cpu.handle) G().cpu = a; + return HSA_STATUS_SUCCESS; +} + +hsa_status_t find_vram(hsa_amd_memory_pool_t p, void* data) { + hsa_amd_segment_t seg; + uint32_t flags = 0; + bool alloc = false; + hsa_amd_memory_pool_get_info(p, HSA_AMD_MEMORY_POOL_INFO_SEGMENT, &seg); + if (seg != HSA_AMD_SEGMENT_GLOBAL) return HSA_STATUS_SUCCESS; + hsa_amd_memory_pool_get_info(p, HSA_AMD_MEMORY_POOL_INFO_GLOBAL_FLAGS, &flags); + hsa_amd_memory_pool_get_info(p, HSA_AMD_MEMORY_POOL_INFO_RUNTIME_ALLOC_ALLOWED, &alloc); + Dev* d = static_cast(data); + if (alloc && (flags & HSA_AMD_MEMORY_POOL_GLOBAL_FLAG_COARSE_GRAINED) && !d->has_vram) { + d->vram = p; + d->has_vram = true; + } + return HSA_STATUS_SUCCESS; +} + +hsa_status_t find_host_fine(hsa_amd_memory_pool_t p, void*) { + hsa_amd_segment_t seg; + uint32_t flags = 0; + bool alloc = false; + hsa_amd_memory_pool_get_info(p, HSA_AMD_MEMORY_POOL_INFO_SEGMENT, &seg); + if (seg != HSA_AMD_SEGMENT_GLOBAL) return HSA_STATUS_SUCCESS; + hsa_amd_memory_pool_get_info(p, HSA_AMD_MEMORY_POOL_INFO_GLOBAL_FLAGS, &flags); + hsa_amd_memory_pool_get_info(p, HSA_AMD_MEMORY_POOL_INFO_RUNTIME_ALLOC_ALLOWED, &alloc); + if (alloc && (flags & HSA_AMD_MEMORY_POOL_GLOBAL_FLAG_FINE_GRAINED) && !G().has_host_fine) { + G().host_fine = p; + G().has_host_fine = true; + } + return HSA_STATUS_SUCCESS; +} + +/* Whether a wait on the signal can block: the packet that completes it posts an event and raises + * an interrupt. */ +bool interrupts(hsa_signal_t s) { + return s.handle && reinterpret_cast(s.handle)->event_mailbox_ptr != 0; +} + +/* HIP's ordinals and HSA's agents are matched by PCI address rather than by position: the CPU's + * integrated graphics is an HSA agent too, and HIP's visible-device mask can hide any of them. */ +bool init_devices() { + Global& g = G(); + if (hsa_init() != HSA_STATUS_SUCCESS) { g.why = "hsa_init failed"; return false; } + g.kfd = open("/dev/kfd", O_RDWR | O_CLOEXEC); + if (g.kfd < 0) { g.why = fmt("/dev/kfd could not be opened: %s", std::strerror(errno)); return false; } + if (hsa_signal_create(0, 0, nullptr, &g.fault) != HSA_STATUS_SUCCESS || !interrupts(g.fault)) { + g.why = "the runtime makes no interrupt signals, and every host wait blocks on one"; + return false; + } + std::vector gpus; + hsa_iterate_agents(collect_gpu, &gpus); + if (!g.cpu.handle) { g.why = "no CPU agent"; return false; } + hsa_amd_agent_iterate_memory_pools(g.cpu, find_host_fine, nullptr); + if (!g.has_host_fine) { g.why = "no fine-grained host memory pool"; return false; } + hsa_system_get_info(HSA_SYSTEM_INFO_TIMESTAMP_FREQUENCY, &g.ts_freq); + if (!g.ts_freq) g.ts_freq = 1; + + int n = 0; + if (hipGetDeviceCount(&n) != hipSuccess || n <= 0) { g.why = "no HIP devices"; return false; } + if (n > kMaxDevices) { g.why = "more devices than the backend tracks"; return false; } + g.dev.resize((size_t)n); + for (int i = 0; i < n; ++i) { + char bus[64] = {0}; + unsigned dom = 0, b = 0, d = 0, f = 0; + if (hipDeviceGetPCIBusId(bus, (int)sizeof bus, i) != hipSuccess || + std::sscanf(bus, "%x:%x:%x.%x", &dom, &b, &d, &f) != 4) { + g.why = fmt("could not read the PCI address of HIP device %d", i); + return false; + } + const uint32_t want = (b << 8) | (d << 3) | f; + bool found = false; + for (hsa_agent_t a : gpus) { + uint32_t bdf = 0, adom = 0; + hsa_agent_get_info(a, (hsa_agent_info_t)HSA_AMD_AGENT_INFO_BDFID, &bdf); + hsa_agent_get_info(a, (hsa_agent_info_t)HSA_AMD_AGENT_INFO_DOMAIN, &adom); + if (bdf == want && adom == dom) { + g.dev[(size_t)i].agent = a; + g.dev[(size_t)i].isa = agent_isa(a); + g.dev[(size_t)i].isas = agent_isas(a); + hsa_amd_agent_iterate_memory_pools(a, find_vram, &g.dev[(size_t)i]); + found = true; + break; + } + } + if (!found || !g.dev[(size_t)i].has_vram) { + g.why = fmt("HIP device %d (%s) has no matching HSA agent with a VRAM pool", i, bus); + return false; + } + } + return true; +} + +/* ------------------------------------------------------------------ code object loading */ + +const KernelMeta* module_meta(Module* m, const std::vector& isas, + const ModuleImage** img, const std::string& sym, std::string* why) { + /* Keyed by the card's preferred target with its modes, which is what decides the choice. */ + ModuleImage& im = m->image[isas.front()]; + if (!im.parsed) { + im.parsed = true; + if (!bundle_code_object(m->bundle, isas, &im.co, &im.size, &im.err)) return nullptr; + std::vector ks; + if (!code_object_kernels(im.co, im.size, &ks, &im.err)) { im.co = nullptr; return nullptr; } + for (KernelMeta& k : ks) im.meta.emplace(k.symbol, std::move(k)); + } + *img = &im; + if (!im.co) { *why = im.err; return nullptr; } + auto it = im.meta.find(sym); + if (it == im.meta.end()) { *why = "the code object has no metadata for " + sym; return nullptr; } + return &it->second; +} + +bool module_load(Module* m, int ord, const ModuleImage& im, std::string* why) { + if (m->loaded[ord]) { + if (!m->load_err[ord].empty()) { *why = m->load_err[ord]; return false; } + return true; + } + m->loaded[ord] = true; + const Dev& d = G().dev[(size_t)ord]; + hsa_code_object_reader_t rd; + hsa_executable_t ex; + if (hsa_code_object_reader_create_from_memory(im.co, im.size, &rd) != HSA_STATUS_SUCCESS || + hsa_executable_create_alt(HSA_PROFILE_FULL, HSA_DEFAULT_FLOAT_ROUNDING_MODE_DEFAULT, nullptr, + &ex) != HSA_STATUS_SUCCESS) { + m->load_err[ord] = "could not create an executable for the code object"; + } else if (hsa_executable_load_agent_code_object(ex, d.agent, rd, nullptr, nullptr) != + HSA_STATUS_SUCCESS || + hsa_executable_freeze(ex, nullptr) != HSA_STATUS_SUCCESS) { + m->load_err[ord] = "the code object did not load on " + d.isa; + } else { + m->exec[ord] = ex; + } + if (!m->load_err[ord].empty()) { *why = m->load_err[ord]; return false; } + return true; +} + +/* Kernel objects by name, for the queue dump: a stalled queue is read by what it is stuck on. */ +std::mutex g_names_mu; +std::unordered_map g_names; + +KernelRec* resolve(Func* fn, int ord) { + if (KernelRec* k = fn->rec[ord].load(std::memory_order_acquire)) return k; + Module* m = fn->mod; + std::lock_guard lk(m->mu); + if (KernelRec* k = fn->rec[ord].load(std::memory_order_acquire)) return k; + if (!fn->err[ord].empty()) return nullptr; + + const Dev& d = G().dev[(size_t)ord]; + const std::string sym = fn->name + ".kd"; + std::string why; + const ModuleImage* im = nullptr; + const KernelMeta* meta = module_meta(m, d.isas, &im, sym, &why); + if (!meta || !module_load(m, ord, *im, &why)) { + fn->err[ord] = why; + return nullptr; + } + hsa_executable_symbol_t s; + if (hsa_executable_get_symbol_by_name(m->exec[ord], sym.c_str(), &d.agent, &s) != + HSA_STATUS_SUCCESS) { + fn->err[ord] = "the loaded executable has no symbol " + sym; + return nullptr; + } + auto k = std::make_unique(); + k->name = fn->name; + hsa_executable_symbol_get_info(s, HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_OBJECT, &k->object); + hsa_executable_symbol_get_info(s, HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_KERNARG_SEGMENT_SIZE, + &k->kernarg_size); + hsa_executable_symbol_get_info(s, HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_GROUP_SEGMENT_SIZE, + &k->group_size); + hsa_executable_symbol_get_info(s, HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_PRIVATE_SEGMENT_SIZE, + &k->private_size); + /* THE ARGUMENT SLOT IS FIXED AT 1 KiB, and a kernel whose segment does not fit leaves less + * than the guard the fence scheme needs between one slot and the next. Refused by name: no + * kernel in this tree comes near it. */ + if (k->kernarg_size > kKargMax) { + fn->err[ord] = fmt("its kernel argument segment is %u bytes and the backend's slot holds %u", + k->kernarg_size, kKargMax); + return nullptr; + } + /* A dynamic stack needs a scratch size the kernel cannot state; HIP guesses one. This backend + * does not guess, and no kernel in this tree has one. */ + if (meta->dynamic_stack) { + fn->err[ord] = "it uses a dynamic stack, which the AQL backend does not size"; + return nullptr; + } + for (int h = 0; h < 16; ++h) { k->hid[h] = -1; k->hid_size[h] = 0; } + for (const KernelArg& a : meta->args) { + if (a.hidden == Hidden::None) { + k->ex_off.push_back(a.offset); + k->ex_size.push_back(a.size); + } else if (a.hidden == Hidden::Unsupported) { + fn->err[ord] = "it takes the implicit argument " + a.kind + ", which the AQL backend " + "does not provide"; + return nullptr; + } else if (a.hidden != Hidden::Pad) { + k->hid[(int)a.hidden] = (int32_t)a.offset; + k->hid_size[(int)a.hidden] = (uint8_t)a.size; + } + } + k->n_explicit = (uint16_t)k->ex_off.size(); + { + std::lock_guard nl(g_names_mu); + g_names[k->object] = k->name; + } + KernelRec* out = k.release(); + fn->rec[ord].store(out, std::memory_order_release); + return out; +} + +/* One lookup a launch, so a thread-local direct-mapped cache sits in front of the registry. */ +struct CacheEnt { const void* stub; int ord; KernelRec* k; }; +thread_local CacheEnt t_cache[512]; + +KernelRec* kernel_for(const void* stub, int ord, std::string* why) { + const size_t h = (((uintptr_t)stub >> 4) ^ ((uintptr_t)stub >> 13) ^ (size_t)ord) & 511u; + CacheEnt& c = t_cache[h]; + if (c.stub == stub && c.ord == ord && c.k) return c.k; + Func* fn = nullptr; + { + Registry& r = reg(); + std::lock_guard lk(r.mu); + auto it = r.by_stub.find(stub); + if (it != r.by_stub.end()) fn = it->second; + } + if (!fn) { *why = "the kernel was never registered with HIP"; return nullptr; } + KernelRec* k = resolve(fn, ord); + if (!k) { *why = fn->name + ": " + fn->err[ord]; return nullptr; } + c = { stub, ord, k }; + return k; +} + +/* ------------------------------------------------------------------ streams */ + +struct Stream { + uint64_t magic = kStreamMagic; + int ord = 0; + uint32_t id = 0; /* index into g_queue_by_id, never reused */ + hsa_agent_t agent{}; + hsa_queue_t* q = nullptr; + uint64_t mask = 0; + char* karg = nullptr; /* VRAM, CPU-mapped through the BAR */ + std::atomic busy{false}; + uint64_t wr = 0; /* next packet index */ + uint64_t rd = 0; /* last read index seen */ + int64_t last_sys_acq = -(int64_t)kQueuePackets; + uint64_t epoch = 0; /* host epoch at the last system acquire */ + std::atomic fault{0}; + char* bounce = nullptr; /* pinned, for pageable copies */ + std::mutex bounce_mu; + + void lock() { + while (busy.exchange(true, std::memory_order_acquire)) + while (busy.load(std::memory_order_relaxed)) _mm_pause(); + } + void unlock() { busy.store(false, std::memory_order_release); } +}; + +/* EVERY QUEUE THIS PROCESS HAS MADE, by a number that is never reused, so a record of "the wait + * packet at index i of queue n" stays meaningful after the queue is destroyed: a destroyed queue's + * entry is null, and everything it held has been consumed. */ +constexpr uint32_t kMaxQueues = 1024; +std::atomic g_queue_by_id[kMaxQueues]; +std::atomic g_next_queue_id{0}; + +inline Stream* ours(const void* s) { + if ((uintptr_t)s < 4096) return nullptr; + const Stream* p = static_cast(s); + return p->magic == kStreamMagic ? const_cast(p) : nullptr; +} + +void on_queue_error(hsa_status_t st, hsa_queue_t*, void* data) { + Stream* s = static_cast(data); + const char* m = nullptr; + hsa_status_string(st, &m); + s->fault.store((int)st, std::memory_order_release); + G().faulted.store(true, std::memory_order_release); + hsa_signal_store_screlease(G().fault, 1); + RAD_ERR("device %d: the AQL queue faulted: %s", s->ord, m ? m : "?"); +} + +/* WHAT EVERY QUEUE IS DOING, printed once when a host wait has not come back for five seconds. + * Nothing on the step path takes that long, so a wait that does is a queue stuck on a packet -- + * a barrier on a signal nothing will decrement, or a kernel that faulted without a report -- and + * the packet at the read index is the answer. */ +void dump_queues(const char* where) { + std::lock_guard lk(G().streams_mu); + RAD_ERR("device: %s has waited 5 s; the queues:", where); + for (Stream* s : G().streams) { + const uint64_t rd = hsa_queue_load_read_index_scacquire(s->q); + const uint64_t wr = hsa_queue_load_write_index_scacquire(s->q); + std::string what = "idle"; + if (rd < wr) { + auto* p = static_cast(s->q->base_address) + (rd & s->mask); + const uint16_t h = __atomic_load_n(&p->header, __ATOMIC_ACQUIRE); + const int type = (h >> HSA_PACKET_HEADER_TYPE) & 0xff; + if (type == HSA_PACKET_TYPE_KERNEL_DISPATCH) { + std::lock_guard nl(g_names_mu); + auto it = g_names.find(p->kernel_object); + what = "kernel " + (it != g_names.end() ? it->second : fmt("%#" PRIx64, p->kernel_object)); + } else if (type == HSA_PACKET_TYPE_BARRIER_AND) { + auto* b = reinterpret_cast(p); + what = "barrier-and"; + for (int i = 0; i < 5; ++i) + if (b->dep_signal[i].handle) + what += fmt(" dep[%d]=%" PRId64, i, (int64_t)hsa_signal_load_relaxed(b->dep_signal[i])); + if (b->completion_signal.handle) + what += fmt(" done=%" PRId64, (int64_t)hsa_signal_load_relaxed(b->completion_signal)); + } else { + what = fmt("packet type %d", type); + } + } + RAD_ERR(" device %d queue %p: written %" PRIu64 ", read %" PRIu64 " -> %s", s->ord, + (void*)s->q, wr, rd, what.c_str()); + } +} + +/* How long a host wait goes before it reports the queues; see dump_queues. */ +constexpr uint32_t kStallMs = 5000; + +/* A spin that notices when it has gone on too long. Checked every 64k iterations, so the clock + * is read a few thousand times a second at most. */ +struct Stall { + const char* where; + uint32_t n = 0; + bool told = false; + std::chrono::steady_clock::time_point t0 = std::chrono::steady_clock::now(); + explicit Stall(const char* w) : where(w) {} + void tick() { + if (told || (++n & 0xffff)) return; + check(); + } + /* Every call, for a loop that sleeps between calls and so makes few of them. */ + void check() { + if (!told && std::chrono::steady_clock::now() - t0 > std::chrono::milliseconds(kStallMs)) { + told = true; + dump_queues(where); + } + } +}; + +/* The slot for packet `idx`, once the packet processor has consumed far enough that it is free. + * A packet with the barrier bit having been LAUNCHED means every packet before it has COMPLETED -- + * which is what a kernel argument slot, read by the whole of its kernel, needs. A played tape + * leaves the bit off on at most kTapeOverlapRun packets in a row (see TapeRec::overlap), so of any + * kTapeOverlapRun + 1 consecutive packets one carries it; the margin is that run and one more. */ +constexpr uint64_t kReserveMargin = (uint64_t)kTapeOverlapRun + 2; + +inline int reserve(Stream* s, uint64_t* out) { + const uint64_t idx = s->wr; + const uint64_t size = s->mask + 1; + if (idx + kReserveMargin - s->rd > size) { + Stall st("a full queue"); + for (;;) { + s->rd = hsa_queue_load_read_index_scacquire(s->q); + if (idx + kReserveMargin - s->rd <= size) break; + if (s->fault.load(std::memory_order_relaxed)) return RAD_E_DEVICE; + st.tick(); + _mm_pause(); + } + } + *out = idx; + return RAD_OK; +} + +inline void publish(Stream* s, uint64_t idx, uint16_t header, uint16_t setup) { + s->wr = idx + 1; + hsa_queue_store_write_index_relaxed(s->q, idx + 1); + _mm_sfence(); /* the argument slot is write-combined VRAM */ + __atomic_store_n(reinterpret_cast( + static_cast(s->q->base_address) + + (idx & s->mask)), + (uint32_t)header | ((uint32_t)setup << 16), __ATOMIC_RELEASE); + hsa_signal_store_relaxed(s->q->doorbell_signal, (hsa_signal_value_t)idx); +} + +/* ------------------------------------------------------------------ recorded passes + * + * A PASS RECORDED ONCE IS WRITTEN STRAIGHT INTO THE QUEUES AFTERWARDS. The engine issues the same + * pass -- the same kernels with the same arguments -- step after step, and nearly all of a + * dispatch's host cost is producing it: the architecture's block code, the runtime's operand + * resolution, the kernel library's argument packing. A recorded dispatch is the finished packet and + * its finished argument block, which lives in VRAM for as long as the tape does, so playing it back + * is a 60-byte copy into the queue and a header store. + * + * WHAT IS RECORDED is what THIS THREAD submits while a capture is open: dispatches -- kernels, and + * the backend's own copies and fills -- and event records and waits. Those are kept by EVENT and + * replayed through the ordinary calls, because a record takes a fresh signal every time (see + * "events"). A pageable copy stages through the host and waits, which a tape cannot reproduce, and + * it makes the tape unusable. Other threads' submissions to the same queues are theirs and are not + * recorded. */ +enum : uint8_t { kTapeDispatch = 0, kTapeRecord = 1, kTapeWait = 2 }; + +struct TapeRec { + uint8_t kind = kTapeDispatch; + uint8_t fence = 0; /* a dispatch's kFence* flags */ + uint32_t karg_off = 0; /* a dispatch's argument block, in the tape's */ + uint32_t karg_len = 0; + Stream* s = nullptr; + void* ev = nullptr; /* a record's or a wait's event */ + hsa_kernel_dispatch_packet_t pkt{}; /* a dispatch's packet, all but the header word */ + /* A dispatch played WITHOUT the barrier bit, which lets the packet processor launch it while + * the packets before it on its queue are still running. Set by the recorder only where it has + * shown the dispatch reads and writes nothing those packets write (tape_set_overlap). */ + uint8_t overlap = 0; +}; + +struct Tape { + uint64_t magic = kTapeMagic; + std::vector rec; + std::vector karg_host; /* the argument blocks, kept to compare tapes by */ + char* karg = nullptr; /* VRAM, CPU-mapped, from the end of the capture on */ + std::string bad; /* why this tape cannot be played, if it cannot */ + /* The last packet the latest play wrote on each queue. The argument block is freed only once + * each of them has been consumed. */ + std::vector> last; +}; + +thread_local Tape* t_tape = nullptr; +thread_local int t_tape_pause = 0; + +inline bool capturing() { return t_tape && t_tape_pause == 0; } + +/* A dispatch just written at `p` on `s`, with its argument block `ka`. */ +void tape_note_dispatch(Stream* s, const hsa_kernel_dispatch_packet_t* p, uint16_t setup, + const unsigned char* ka, uint32_t n, uint8_t fence) { + Tape* t = t_tape; + TapeRec r; + r.kind = kTapeDispatch; + r.fence = fence; + r.s = s; + r.pkt = *p; + r.pkt.header = 0; + r.pkt.setup = setup; + const size_t off = (t->karg_host.size() + 63) & ~size_t(63); + t->karg_host.resize(off + n); + std::memcpy(t->karg_host.data() + off, ka, n); + r.karg_off = (uint32_t)off; + r.karg_len = n; + t->rec.push_back(r); +} + +inline uint16_t header(hsa_packet_type_t type, int acq, int rel, bool barrier = true) { + return (uint16_t)((type << HSA_PACKET_HEADER_TYPE) | + ((barrier ? 1u : 0u) << HSA_PACKET_HEADER_BARRIER) | + (acq << HSA_PACKET_HEADER_SCACQUIRE_FENCE_SCOPE) | + (rel << HSA_PACKET_HEADER_SCRELEASE_FENCE_SCOPE)); +} + +/* Whether the packet at `idx` must acquire at system scope, and the bookkeeping if it does. */ +inline int acquire_scope(Stream* s, uint64_t idx, bool forced) { + const uint64_t ep = G().host_epoch.load(std::memory_order_acquire); + const bool lap = (int64_t)idx - s->last_sys_acq >= (int64_t)(kQueuePackets / 2); + if (forced || lap || s->epoch != ep) { + s->last_sys_acq = (int64_t)idx; + s->epoch = ep; + return HSA_FENCE_SCOPE_SYSTEM; + } + return HSA_FENCE_SCOPE_AGENT; +} + +int barrier(Stream* s, hsa_signal_t dep, hsa_signal_t done, int acq, int rel, + uint64_t* out_idx = nullptr) { + s->lock(); + uint64_t idx = 0; + const int rc = reserve(s, &idx); + if (rc < 0) { s->unlock(); return rc; } + if (out_idx) *out_idx = idx; + auto* p = reinterpret_cast( + static_cast(s->q->base_address) + (idx & s->mask)); + p->reserved0 = 0; + p->reserved1 = 0; + p->dep_signal[0] = dep; + for (int i = 1; i < 5; ++i) p->dep_signal[i].handle = 0; + p->reserved2 = 0; + p->completion_signal = done; + if (acq == HSA_FENCE_SCOPE_SYSTEM) { + s->last_sys_acq = (int64_t)idx; + s->epoch = G().host_epoch.load(std::memory_order_acquire); + } + publish(s, idx, header(HSA_PACKET_TYPE_BARRIER_AND, acq, rel), 0); + s->unlock(); + return RAD_OK; +} + +int dispatch(Stream* s, const KernelRec* k, dim3 g, dim3 b, void** args, size_t shm, uint8_t fence) { + const uint64_t gx = (uint64_t)g.x * b.x, gy = (uint64_t)g.y * b.y, gz = (uint64_t)g.z * b.z; + if (!gx || !gy || !gz) return RAD_OK; + if (gx > UINT32_MAX || gy > UINT32_MAX || gz > UINT32_MAX) return RAD_E_INVAL; + if ((uint64_t)k->group_size + shm > 65536) return RAD_E_INVAL; + + alignas(64) unsigned char ka[kKargMax]; + const uint32_t n = (k->kernarg_size + 15u) & ~15u; + std::memset(ka, 0, n); + for (uint16_t i = 0; i < k->n_explicit; ++i) + std::memcpy(ka + k->ex_off[i], args[i], k->ex_size[i]); + auto put = [&](Hidden h, uint64_t v) { + const int32_t off = k->hid[(int)h]; + if (off >= 0) std::memcpy(ka + off, &v, k->hid_size[(int)h]); + }; + put(Hidden::BlockCountX, g.x); put(Hidden::BlockCountY, g.y); put(Hidden::BlockCountZ, g.z); + put(Hidden::GroupSizeX, b.x); put(Hidden::GroupSizeY, b.y); put(Hidden::GroupSizeZ, b.z); + put(Hidden::GridDims, 3); + put(Hidden::DynamicLds, shm); + + s->lock(); + uint64_t idx = 0; + const int rc = reserve(s, &idx); + if (rc < 0) { s->unlock(); return rc; } + char* slot = s->karg + (size_t)(idx & s->mask) * kKargSlot; + std::memcpy(slot, ka, n); + auto* p = static_cast(s->q->base_address) + (idx & s->mask); + p->workgroup_size_x = (uint16_t)b.x; + p->workgroup_size_y = (uint16_t)b.y; + p->workgroup_size_z = (uint16_t)b.z; + p->reserved0 = 0; + p->grid_size_x = (uint32_t)gx; + p->grid_size_y = (uint32_t)gy; + p->grid_size_z = (uint32_t)gz; + p->private_segment_size = k->private_size; + p->group_segment_size = k->group_size + (uint32_t)shm; + p->kernel_object = k->object; + p->kernarg_address = slot; + p->reserved2 = 0; + p->completion_signal.handle = 0; + constexpr uint16_t setup = 3u << HSA_KERNEL_DISPATCH_PACKET_SETUP_DIMENSIONS; + if (capturing()) tape_note_dispatch(s, p, setup, ka, n, fence); + const int acq = acquire_scope(s, idx, (fence & kFenceAcquireSystem) != 0); + const int rel = (fence & kFenceReleaseSystem) ? HSA_FENCE_SCOPE_SYSTEM : HSA_FENCE_SCOPE_AGENT; + publish(s, idx, header(HSA_PACKET_TYPE_KERNEL_DISPATCH, acq, rel), setup); + s->unlock(); + return RAD_OK; +} + +/* A RUN OF RECORDED DISPATCHES ONTO ONE QUEUE, under one hold of the queue's lock and with the + * doorbell rung once for every kPlayRing packets rather than once a packet: the doorbell is an + * uncached write across the link, and a pass is over a thousand dispatches. Each packet's body is + * copied as recorded and its header -- whose acquire scope depends on what the host wrote since -- + * decided now, as dispatch() decides it. The argument blocks were written to VRAM when the tape + * was made, so there is nothing to fence before the header. A reserve that would wait for room + * rings first: the packet processor only takes packets the doorbell has announced. */ +constexpr int kPlayRing = 64; + +/* WHERE THIS THREAD'S PLAYS LAST LEFT EACH QUEUE. A queue found further on has had packets put on + * it that no recording saw -- a weight-table patch or a mover wait between two played stretches, + * another thread's copy -- and the next played packet on it keeps its barrier bit whatever the + * recording's analysis said: the analysis proved it independent of the packets recorded before + * it, and those are no longer the ones in front of it. A queue not in the list is treated the + * same way. */ +struct PlayLeft { uint32_t q = UINT32_MAX; uint64_t wr = 0; }; +constexpr int kPlayLeft = 8; +thread_local PlayLeft t_left[kPlayLeft]; + +struct PlayRun { + Stream* s = nullptr; + uint64_t next = 0; /* the write index after the last packet written */ + int unrung = 0; + bool foreign = true; /* the next packet's queue has packets this thread did not play */ + + void ring() { + if (!unrung) return; + hsa_queue_store_write_index_relaxed(s->q, next); + hsa_signal_store_relaxed(s->q->doorbell_signal, (hsa_signal_value_t)(next - 1)); + unrung = 0; + } + void end() { + if (!s) return; + ring(); + int i = 0, empty = -1; + while (i < kPlayLeft && t_left[i].q != s->id) { + if (t_left[i].q == UINT32_MAX && empty < 0) empty = i; + ++i; + } + if (i == kPlayLeft) i = empty >= 0 ? empty : (int)(s->id % kPlayLeft); + t_left[i] = PlayLeft{ s->id, s->wr }; + s->unlock(); + s = nullptr; + } + static bool moved(const Stream* q) { + for (int i = 0; i < kPlayLeft; ++i) + if (t_left[i].q == q->id) return t_left[i].wr != q->wr; + return true; + } + /* `done`, when set, is the packet's completion signal and `rel_min` the least release scope + * it must carry -- a record riding on this dispatch; see a_tape_play. */ + int put(const TapeRec& r, uint64_t* out_idx, hsa_signal_t done = hsa_signal_t{0}, + int rel_min = HSA_FENCE_SCOPE_NONE) { + if (s != r.s) { + end(); + s = r.s; + s->lock(); + foreign = moved(s); + } + const uint64_t idx = s->wr; + if (idx + kReserveMargin - s->rd > s->mask + 1) { + ring(); + uint64_t got = 0; + const int rc = reserve(s, &got); + if (rc < 0) return rc; + } + auto* p = static_cast(s->q->base_address) + (idx & s->mask); + std::memcpy(reinterpret_cast(p) + 4, reinterpret_cast(&r.pkt) + 4, + sizeof(hsa_kernel_dispatch_packet_t) - 4); + if (done.handle) p->completion_signal = done; + const int acq = acquire_scope(s, idx, (r.fence & kFenceAcquireSystem) != 0); + int rel = (r.fence & kFenceReleaseSystem) ? HSA_FENCE_SCOPE_SYSTEM : HSA_FENCE_SCOPE_AGENT; + if (rel < rel_min) rel = rel_min; + /* A record riding on the dispatch keeps the bit: its completion signal stands for + * everything before it on the queue, which an unordered dispatch's completion does not. */ + const bool ordered = foreign || !r.overlap || done.handle; + const uint16_t h = header(HSA_PACKET_TYPE_KERNEL_DISPATCH, acq, rel, ordered); + __atomic_store_n(reinterpret_cast(p), (uint32_t)h | ((uint32_t)r.pkt.setup << 16), + __ATOMIC_RELEASE); + foreign = false; + s->wr = idx + 1; + next = idx + 1; + *out_idx = idx; + if (++unrung >= kPlayRing) ring(); + return RAD_OK; + } +}; + +/* One completion signal a thread for synchronous waits, an interrupt signal (see "host waits"): + * two threads waiting on the same queue each get their own, and a signal is only ever waited on by + * the thread that armed it. */ +hsa_signal_t thread_signal() { + thread_local hsa_signal_t s{0}; + if (!s.handle && hsa_signal_create(0, 0, nullptr, &s) != HSA_STATUS_SUCCESS) s.handle = 0; + return s; +} + +/* ------------------------------------------------------------------ host waits + * + * A HOST WAIT BLOCKS IN THE DRIVER UNTIL THE DEVICE SAYS IT IS DONE. Every signal the host waits + * on is an interrupt signal: when the packet that carries it completes, the packet processor posts + * the signal's event and raises an interrupt, and the driver wakes the threads blocked on that + * event. A wait costs the host one system call and one wake-up whatever its length, and it makes + * no guess at how long the device will take, so it can neither sleep past a device that finished + * early nor spin through one that runs late. What it does cost is the interrupt's delivery: some + * tens of microseconds between the packet completing and the thread running. That is hidden + * rather than shortened. The engine keeps work queued behind every point it waits for -- the next + * step behind a step's end, the layers that do not read a host op's output behind that op's join + * -- so the device is still running when the host wakes. + * + * THE WAIT GOES TO THE DRIVER DIRECTLY. The runtime's own blocking wait polls the signal for a + * stretch before it blocks, which spends a short wait's whole length on a core; the driver's wait + * on the signal's event spends nothing until the interrupt arrives. + * + * NO WAKE-UP IS LOST. The driver counts each event's firings (its age), and a wait that names an + * age returns at once if the event has fired since. A thread keeps the age each event last woke it + * at, so an interrupt that lands between reading the signal and entering the driver ends the wait + * instead of being missed; an age gone stale costs one early return and a second look. + * + * A FAULT ENDS EVERY WAIT. A faulted queue never completes the signal a wait is on, so every wait + * also names the fault signal's event, which the queue-error callback fires. */ + +/* The age an event last woke this thread at; 1 is the driver's "never fired". */ +uint64_t& seen_age(uint32_t ev) { + thread_local std::vector age; + if (ev >= age.size()) age.resize((size_t)ev + 1, 1); + return age[ev]; +} + +int host_wait(hsa_signal_t sig) { + if (hsa_signal_load_scacquire(sig) != 0) { + if (!interrupts(sig)) { + device_set_error("a host wait on a signal that raises no interrupt"); + return RAD_E_DEVICE; + } + Stall st("a synchronisation"); + kfd_event_data ev[2] = {}; + ev[0].event_id = reinterpret_cast(sig.handle)->event_id; + ev[1].event_id = reinterpret_cast(G().fault.handle)->event_id; + do { + if (G().faulted.load(std::memory_order_acquire)) return RAD_E_DEVICE; + for (kfd_event_data& e : ev) e.signal_event_data.last_event_age = seen_age(e.event_id); + kfd_ioctl_wait_events_args w{}; + w.events_ptr = (uint64_t)(uintptr_t)ev; + w.num_events = 2; + w.wait_for_all = 0; + w.timeout = kStallMs; + if (ioctl(G().kfd, AMDKFD_IOC_WAIT_EVENTS, &w) < 0) { + if (errno == EINTR) continue; + device_set_error("a host wait failed in the driver: %s", std::strerror(errno)); + return RAD_E_DEVICE; + } + for (const kfd_event_data& e : ev) seen_age(e.event_id) = e.signal_event_data.last_event_age; + if (w.wait_result == KFD_IOC_WAIT_RESULT_TIMEOUT) st.check(); + } while (hsa_signal_load_scacquire(sig) != 0); + } + G().host_epoch.fetch_add(1, std::memory_order_acq_rel); + return RAD_OK; +} + +/* The store that arms a signal is silent: an interrupt signal's ordinary store also fires its + * event, which would wake nobody and cost a system call. */ +int stream_drain(Stream* s) { + hsa_signal_t sig = thread_signal(); + if (!sig.handle) return RAD_E_DEVICE; + hsa_signal_silent_store_relaxed(sig, 1); + uint64_t idx = 0; + RAD_TRY(barrier(s, hsa_signal_t{0}, sig, HSA_FENCE_SCOPE_SYSTEM, HSA_FENCE_SCOPE_SYSTEM, &idx)); + return host_wait(sig); +} + +/* ------------------------------------------------------------------ where a pointer lives */ + +enum Loc : uint8_t { kDevLocal, kDevPeer, kHost, kPageable }; + +/* THE ALLOCATIONS A THREAD COPIES BETWEEN, REMEMBERED. hsa_amd_pointer_info takes the runtime's + * global lock and walks its allocation map, and every copy asks it about both ends -- a few hundred + * questions a step about the same dozen allocations, about 17 us of each rank thread's step. A hit + * here answers from the allocation's own range. + * + * Only an answer about a live allocation is kept, never "pageable": memory the runtime does not + * know may be registered later, and an allocation's kind cannot change while it lives. What can + * change is WHICH allocation an address belongs to, and only by a free or an unmap -- every one of + * those in this backend moves `g_loc_gen` first, and an entry of an older generation is ignored. + * The ranges come back from the runtime itself (sizeInBytes), so a hit is exactly the answer the + * call would give. A reserved-but-unbacked address is not kept: its card is the reservation's and + * is looked up per page. */ +struct LocHit { + uintptr_t lo = 0, hi = 0; /* the allocation's range, as the host addresses it */ + intptr_t shift = 0; /* agent address minus host address (pinned host memory) */ + uint64_t owner = 0; /* the owning card's agent handle; 0 for host memory */ + uint64_t gen = 0; +}; +constexpr int kLocWays = 16; +thread_local LocHit t_loc[kLocWays]; +thread_local unsigned t_loc_next = 0; +std::atomic g_loc_gen{1}; + +/* Every entry in every thread's cache stops answering. */ +void loc_forget() { g_loc_gen.fetch_add(1, std::memory_order_acq_rel); } + +void loc_keep(const void* host_base, size_t bytes, intptr_t shift, uint64_t owner, uint64_t gen) { + if (!host_base || !bytes) return; + LocHit& h = t_loc[t_loc_next++ % kLocWays]; + h.lo = (uintptr_t)host_base; + h.hi = h.lo + bytes; + h.shift = shift; + h.owner = owner; + h.gen = gen; +} + +Loc locate(const void* p, const Stream* s, const void** gpu) { + *gpu = p; + const uintptr_t a = (uintptr_t)p; + const uint64_t gen = g_loc_gen.load(std::memory_order_acquire); + for (const LocHit& h : t_loc) { + if (h.gen != gen || a - h.lo >= h.hi - h.lo) continue; + *gpu = (const void*)(a + (uintptr_t)h.shift); + if (!h.owner) return kHost; + return h.owner == s->agent.handle ? kDevLocal : kDevPeer; + } + hsa_amd_pointer_info_t info{}; + info.size = sizeof info; + if (hsa_amd_pointer_info(const_cast(p), &info, nullptr, nullptr, nullptr) != + HSA_STATUS_SUCCESS) + return kPageable; + switch (info.type) { + case HSA_EXT_POINTER_TYPE_LOCKED: + *gpu = (const char*)info.agentBaseAddress + ((const char*)p - (const char*)info.hostBaseAddress); + loc_keep(info.hostBaseAddress, info.sizeInBytes, + (intptr_t)((uintptr_t)info.agentBaseAddress - (uintptr_t)info.hostBaseAddress), + 0, gen); + return kHost; + case HSA_EXT_POINTER_TYPE_HSA: + case HSA_EXT_POINTER_TYPE_HSA_VMEM: + case HSA_EXT_POINTER_TYPE_GRAPHICS: { + hsa_device_type_t t; + if (hsa_agent_get_info(info.agentOwner, HSA_AGENT_INFO_DEVICE, &t) != HSA_STATUS_SUCCESS) + return kPageable; + if (t == HSA_DEVICE_TYPE_CPU) { + loc_keep(info.agentBaseAddress, info.sizeInBytes, 0, 0, gen); + return kHost; + } + loc_keep(info.agentBaseAddress, info.sizeInBytes, 0, info.agentOwner.handle, gen); + return info.agentOwner.handle == s->agent.handle ? kDevLocal : kDevPeer; + } + case HSA_EXT_POINTER_TYPE_IPC: + return kDevPeer; + case HSA_EXT_POINTER_TYPE_RESERVED_ADDR: { + int d = 0; + if (aql_vmem_device_of(p, &d) < 0) return kDevLocal; + return d == s->ord ? kDevLocal : kDevPeer; + } + default: + return kPageable; + } +} + +std::atomic g_pageable_bytes{0}; + +} // namespace + +void set_next_fence(uint8_t f) { t_next_fence = f; } + +} // namespace aql + +/* ------------------------------------------------------------------ the backend */ + +namespace { + +using namespace aql; + +int a_stream_create(RadStream* out, int high_priority) { + if (!out) return RAD_E_INVAL; + int ord = 0; + if (hipGetDevice(&ord) != hipSuccess || ord < 0 || ord >= (int)G().dev.size()) { + device_set_error("rad_stream_create: no current device"); + return RAD_E_DEVICE; + } + const Dev& d = G().dev[(size_t)ord]; + auto s = std::make_unique(); + s->ord = ord; + s->agent = d.agent; + if (hsa_queue_create(d.agent, kQueuePackets, HSA_QUEUE_TYPE_SINGLE, on_queue_error, s.get(), + UINT32_MAX, UINT32_MAX, &s->q) != HSA_STATUS_SUCCESS) { + device_set_error("rad_stream_create: hsa_queue_create failed on device %d", ord); + return RAD_E_DEVICE; + } + s->mask = s->q->size - 1; + hsa_amd_profiling_set_profiler_enabled(s->q, 1); + if (high_priority) hsa_amd_queue_set_priority(s->q, HSA_AMD_QUEUE_PRIORITY_HIGH); + void* ka = nullptr; + if (hsa_amd_memory_pool_allocate(d.vram, (size_t)(s->mask + 1) * kKargSlot, 0, &ka) != + HSA_STATUS_SUCCESS || + hsa_amd_agents_allow_access(1, &G().cpu, nullptr, ka) != HSA_STATUS_SUCCESS) { + hsa_queue_destroy(s->q); + device_set_error("rad_stream_create: the kernel argument ring could not be placed in VRAM " + "the host can write -- the AQL backend needs a large BAR"); + return RAD_E_DEVICE; + } + s->karg = static_cast(ka); + void* bb = nullptr; + if (hsa_amd_memory_pool_allocate(G().host_fine, kBounceBytes, 0, &bb) != HSA_STATUS_SUCCESS || + hsa_amd_agents_allow_access(1, &d.agent, nullptr, bb) != HSA_STATUS_SUCCESS) { + hsa_amd_memory_pool_free(ka); + hsa_queue_destroy(s->q); + device_set_error("rad_stream_create: no pinned bounce buffer"); + return RAD_E_NOMEM; + } + s->bounce = static_cast(bb); + s->id = g_next_queue_id.fetch_add(1, std::memory_order_relaxed); + if (s->id >= kMaxQueues) { + hsa_amd_memory_pool_free(bb); + hsa_amd_memory_pool_free(ka); + hsa_queue_destroy(s->q); + device_set_error("rad_stream_create: more than %u streams in one process", kMaxQueues); + return RAD_E_NOMEM; + } + g_queue_by_id[s->id].store(s->q, std::memory_order_release); + { + std::lock_guard lk(G().streams_mu); + G().streams.push_back(s.get()); + } + *out = (RadStream)s.release(); + return RAD_OK; +} + +void a_stream_destroy(RadStream rs) { + Stream* s = ours(rs); + if (!s) return; + (void)stream_drain(s); + { + std::lock_guard lk(G().streams_mu); + auto& v = G().streams; + for (size_t i = 0; i < v.size(); ++i) if (v[i] == s) { v.erase(v.begin() + (long)i); break; } + } + g_queue_by_id[s->id].store(nullptr, std::memory_order_release); + hsa_queue_destroy(s->q); + hsa_amd_memory_pool_free(s->karg); + hsa_amd_memory_pool_free(s->bounce); + s->magic = 0; + delete s; +} + +int a_stream_sync(RadStream rs) { + Stream* s = ours(rs); + if (!s) { device_set_error("rad_stream_sync: not a stream of this backend"); return RAD_E_INVAL; } + const int rc = stream_drain(s); + if (rc < 0) device_set_error("rad_stream_sync: the queue on device %d faulted", s->ord); + return rc; +} + +/* ---- events. + * + * A RECORD TAKES A FRESH SIGNAL, and a signal is only reused once nothing can still name it. That + * means two things: its own record has completed, AND every wait packet that was enqueued against + * it has been consumed. Reusing a signal whose record has completed but whose waiters have not yet + * been reached re-arms it under them: a lagging queue's wait for record r then waits for whatever + * record reused the signal, which can sit behind a wait on that same lagging queue. Two lanes that + * join each other every layer produce exactly that cycle within a step. + * + * So each signal carries the (queue, packet index) of every wait that names it, and returns to the + * free list when both conditions hold. Nothing here ever blocks the host: a signal that cannot be + * reused yet is simply not reused, and the pool grows to the number of records in flight. */ +struct Sig { + hsa_signal_t h{}; + bool irq = false; /* an interrupt signal */ + hsa_agent_t agent{}; /* where it was recorded */ + std::vector> waiters; /* queue id, packet index */ +}; + +struct SigPool { + std::mutex mu; + std::vector free[2]; /* by irq */ + std::deque retiring; /* in the order they were retired */ +}; + +SigPool& pool() { + static SigPool* p = new SigPool(); + return *p; +} + +bool reusable(const Sig* g) { + if (hsa_signal_load_relaxed(g->h) != 0) return false; + for (const auto& w : g->waiters) { + hsa_queue_t* q = g_queue_by_id[w.first].load(std::memory_order_acquire); + if (q && hsa_queue_load_read_index_relaxed(q) <= w.second) return false; + } + return true; +} + +/* A signal for one record: an interrupt signal for an event the host waits on, and a GPU_ONLY one + * otherwise. Only the first kind can end a host wait (see "host waits"), and it costs what the + * second does not: a driver event, of which a process has a few thousand, and an interrupt at every + * completion, which an event recorded dozens of times a step and only ever waited on by other + * queues has no use for. */ +Sig* sig_get(bool irq) { + SigPool& p = pool(); + std::lock_guard lk(p.mu); + /* THE OLDEST FIRST. A signal retires when its event is recorded again, so the retiring list is + * in record order and its front is the signal most likely to be done: taking from the front + * until one of the kind asked for is free costs a look or two, where a walk of the whole list + * reads every signal's value and every waiter's queue out of memory the device writes. The + * walk is kept for when the front is not done -- the host plays a step while the card is + * still on the one before, and the records that step retired are then still in flight. */ + while (p.free[irq].empty() && !p.retiring.empty() && reusable(p.retiring.front())) { + Sig* g = p.retiring.front(); + p.retiring.pop_front(); + g->waiters.clear(); + p.free[g->irq].push_back(g); + } + if (p.free[irq].empty()) { + /* In place and in order, so the front stays the oldest. */ + size_t kept = 0; + for (size_t i = 0; i < p.retiring.size(); ++i) { + Sig* g = p.retiring[i]; + if (reusable(g)) { + g->waiters.clear(); + p.free[g->irq].push_back(g); + } else { + p.retiring[kept++] = g; + } + } + p.retiring.resize(kept); + } + if (!p.free[irq].empty()) { + Sig* g = p.free[irq].back(); + p.free[irq].pop_back(); + return g; + } + auto g = std::make_unique(); + g->irq = irq; + const hsa_status_t st = irq ? hsa_signal_create(0, 0, nullptr, &g->h) + : hsa_amd_signal_create(0, 0, nullptr, HSA_AMD_SIGNAL_AMD_GPU_ONLY, &g->h); + if (st != HSA_STATUS_SUCCESS || (irq && !interrupts(g->h))) return nullptr; + return g.release(); +} + +void sig_retire(Sig* g) { + SigPool& p = pool(); + std::lock_guard lk(p.mu); + p.retiring.push_back(g); +} + +struct Event { + uint64_t magic = kEventMagic; + Sig* cur = nullptr; /* the latest record; null before the first */ + bool local = false; /* RAD_EVENT_LOCAL: the record releases card-wide */ + bool host = false; /* RAD_EVENT_HOST_WAIT: the host may synchronise on it */ + std::mutex mu; +}; + +inline Event* ev_of(RadEvent e) { + Event* p = static_cast(e); + return (p && p->magic == kEventMagic) ? p : nullptr; +} + +int a_event_create(RadEvent* out, unsigned flags) { + if (!out) return RAD_E_INVAL; + Event* e = new (std::nothrow) Event(); + if (!e) return RAD_E_NOMEM; + e->local = (flags & RAD_EVENT_LOCAL) != 0; + e->host = (flags & RAD_EVENT_HOST_WAIT) != 0; + *out = (RadEvent)e; + return RAD_OK; +} + +/* The event goes; its signal stays with the pool until the waits that name it are consumed. */ +void a_event_destroy(RadEvent re) { + Event* e = ev_of(re); + if (!e) return; + Sig* g = nullptr; + { + std::lock_guard lk(e->mu); + g = e->cur; + e->cur = nullptr; + e->magic = 0; + } + if (g) sig_retire(g); + delete e; +} + +/* A fresh signal armed for one record of `e` on `s`, and the release scope that record needs. The + * caller puts it on a packet and then hands it to record_adopt. */ +Sig* record_arm(Event* e, Stream* s, int* rel) { + Sig* g = sig_get(e->host); + if (!g) return nullptr; + hsa_signal_silent_store_relaxed(g->h, 1); + g->agent = s->agent; + /* A LOCAL EVENT RELEASES TO THE CARD, which its own L2 already is. The system scope has to + * wait out every write still on its way to host memory, and while the link is carrying + * weights that is a stall of up to tens of microseconds in the recording stream. */ + *rel = e->local ? HSA_FENCE_SCOPE_AGENT : HSA_FENCE_SCOPE_SYSTEM; + return g; +} + +/* The record carrying `g` is on its queue: it becomes the event's latest, and the one before goes + * back to the pool once the waits that name it are consumed. */ +void record_adopt(Event* e, Sig* g) { + Sig* old = nullptr; + { + std::lock_guard lk(e->mu); + old = e->cur; + e->cur = g; + } + if (old) sig_retire(old); +} + +int a_event_record(RadEvent re, RadStream rs) { + Event* e = ev_of(re); + Stream* s = ours(rs); + if (!e || !s) { device_set_error("rad_event_record: null or foreign argument"); return RAD_E_INVAL; } + if (capturing()) { + TapeRec r; + r.kind = kTapeRecord; + r.s = s; + r.ev = re; + t_tape->rec.push_back(r); + } + int rel = HSA_FENCE_SCOPE_NONE; + Sig* g = record_arm(e, s, &rel); + if (!g) { device_set_error("rad_event_record: no signal could be made"); return RAD_E_DEVICE; } + uint64_t idx = 0; + const int rc = barrier(s, hsa_signal_t{0}, g->h, HSA_FENCE_SCOPE_NONE, rel, &idx); + if (rc < 0) return rc; /* the queue faulted; the signal stays armed and unused */ + record_adopt(e, g); + return RAD_OK; +} + +/* The event's lock is held across the enqueue so the signal cannot be retired between being read + * and having this wait noted against it. */ +int a_event_wait(RadStream rs, RadEvent re) { + Event* e = ev_of(re); + Stream* s = ours(rs); + if (!e || !s) { device_set_error("rad_event_wait: null or foreign argument"); return RAD_E_INVAL; } + if (capturing()) { + TapeRec r; + r.kind = kTapeWait; + r.s = s; + r.ev = re; + t_tape->rec.push_back(r); + } + std::lock_guard lk(e->mu); + if (!e->cur) return RAD_OK; /* never recorded: nothing to wait for */ + uint64_t idx = 0; + /* A producer on this stream's own card wrote through the L2 this stream reads, so the acquire + * need only reach the card; one on another card, or the host, needs the system's. */ + const int acq = e->cur->agent.handle == s->agent.handle ? HSA_FENCE_SCOPE_AGENT + : HSA_FENCE_SCOPE_SYSTEM; + RAD_TRY(barrier(s, e->cur->h, hsa_signal_t{0}, acq, HSA_FENCE_SCOPE_NONE, &idx)); + e->cur->waiters.emplace_back(s->id, idx); + return RAD_OK; +} + +int a_event_query(RadEvent re) { + Event* e = ev_of(re); + if (!e) return RAD_E_INVAL; + std::lock_guard lk(e->mu); + if (!e->cur) return 1; + return hsa_signal_load_scacquire(e->cur->h) == 0 ? 1 : 0; +} + +/* Only an event made for host waits can be synchronised: its records carry interrupt signals. */ +int a_event_sync(RadEvent re) { + Event* e = ev_of(re); + if (!e) return RAD_E_INVAL; + if (!e->host) { + device_set_error("rad_event_sync: the event was made without RAD_EVENT_HOST_WAIT, so its " + "records raise no interrupt a host wait could block on"); + return RAD_E_INVAL; + } + hsa_signal_t sig; + { + std::lock_guard lk(e->mu); + if (!e->cur) return RAD_OK; + sig = e->cur->h; + } + return host_wait(sig); +} + +/* The host wrote memory the device is about to read: the next dispatch on every queue acquires at + * system scope, exactly as after a host wait. */ +void a_host_wrote(void) { G().host_epoch.fetch_add(1, std::memory_order_acq_rel); } + +/* ---- recorded passes: the calls. See "recorded passes" above. */ + +inline Tape* tape_of(RadTape t) { + Tape* p = static_cast(t); + return (p && p->magic == kTapeMagic) ? p : nullptr; +} + +/* Tapes destroyed while a play of theirs may still be in a queue. */ +std::mutex g_tape_mu; +std::vector g_tape_retired; + +/* Whether every packet the tape's latest play wrote has completed, or its queue is gone: a packet + * kReserveMargin past it has been launched, which proves it for the reason reserve() gives. */ +bool tape_idle(const Tape* t) { + for (const auto& l : t->last) { + hsa_queue_t* q = g_queue_by_id[l.first].load(std::memory_order_acquire); + if (q && hsa_queue_load_read_index_scacquire(q) < l.second + kReserveMargin) return false; + } + return true; +} + +void tape_free(Tape* t) { + if (t->karg) hsa_amd_memory_pool_free(t->karg); + t->magic = 0; + delete t; +} + +void tape_reap() { + std::lock_guard lk(g_tape_mu); + for (size_t i = 0; i < g_tape_retired.size();) { + if (tape_idle(g_tape_retired[i])) { + tape_free(g_tape_retired[i]); + g_tape_retired[i] = g_tape_retired.back(); + g_tape_retired.pop_back(); + } else { + ++i; + } + } +} + +int a_tape_begin(void) { + if (t_tape) { device_set_error("rad tape: a capture is already open on this thread"); return RAD_E_STATE; } + t_tape = new (std::nothrow) Tape(); + t_tape_pause = 0; + return t_tape ? RAD_OK : RAD_E_NOMEM; +} + +int a_tape_mark(void) { return t_tape ? (int)t_tape->rec.size() : RAD_E_STATE; } + +void a_tape_pause(int on) { + if (on) ++t_tape_pause; + else if (t_tape_pause > 0) --t_tape_pause; +} + +/* The argument blocks go to VRAM on the card the tape's queues belong to, where the packet + * processor reads them as it reads the ring's; the packets are then final but for their header. */ +RadTape a_tape_end(int keep) { + Tape* t = t_tape; + t_tape = nullptr; + t_tape_pause = 0; + tape_reap(); + if (!t) return nullptr; + if (!keep) { tape_free(t); return nullptr; } + if (!t->bad.empty()) { + device_set_error("the pass cannot be recorded: %s", t->bad.c_str()); + tape_free(t); + return nullptr; + } + int ord = -1; + for (const TapeRec& r : t->rec) { + if (ord < 0) ord = r.s->ord; + else if (r.s->ord != ord) { + device_set_error("the pass cannot be recorded: it submits to devices %d and %d", ord, + r.s->ord); + tape_free(t); + return nullptr; + } + } + if (!t->karg_host.empty()) { + void* ka = nullptr; + if (hsa_amd_memory_pool_allocate(G().dev[(size_t)ord].vram, t->karg_host.size(), 0, &ka) != + HSA_STATUS_SUCCESS || + hsa_amd_agents_allow_access(1, &G().cpu, nullptr, ka) != HSA_STATUS_SUCCESS) { + if (ka) hsa_amd_memory_pool_free(ka); + device_set_error("the pass cannot be recorded: %zu bytes of kernel arguments could " + "not be placed in VRAM", t->karg_host.size()); + tape_free(t); + return nullptr; + } + std::memcpy(ka, t->karg_host.data(), t->karg_host.size()); + _mm_sfence(); + t->karg = static_cast(ka); + for (TapeRec& r : t->rec) + if (r.kind == kTapeDispatch) r.pkt.kernarg_address = t->karg + r.karg_off; + } + return t; +} + +int a_tape_len(RadTape rt) { + const Tape* t = tape_of(rt); + return t ? (int)t->rec.size() : RAD_E_INVAL; +} + +int a_tape_record(RadTape rt, int i, int* kind, uint32_t* queue) { + const Tape* t = tape_of(rt); + if (!t || i < 0 || i >= (int)t->rec.size()) return RAD_E_INVAL; + const TapeRec& r = t->rec[(size_t)i]; + if (kind) *kind = r.kind == kTapeDispatch ? 0 : 1; + if (queue) *queue = r.s->id; + return RAD_OK; +} + +int a_tape_set_overlap(RadTape rt, int i, int on) { + Tape* t = tape_of(rt); + if (!t || i < 0 || i >= (int)t->rec.size() || t->rec[(size_t)i].kind != kTapeDispatch) + return RAD_E_INVAL; + t->rec[(size_t)i].overlap = on ? 1 : 0; + return RAD_OK; +} + +int a_tape_play(RadTape rt, int from, int to) { + Tape* t = tape_of(rt); + if (!t || from < 0 || to > (int)t->rec.size() || from > to) { + device_set_error("rad tape: play of a null tape or of records [%d, %d)", from, to); + return RAD_E_INVAL; + } + ++t_tape_pause; + int rc = RAD_OK; + PlayRun run; + for (int i = from; i < to && rc >= 0; ++i) { + const TapeRec& r = t->rec[(size_t)i]; + if (r.kind == kTapeDispatch) { + /* A RECORD DIRECTLY BEHIND A DISPATCH ON THE SAME QUEUE RIDES ON THE DISPATCH. The + * kernel packet carries the barrier bit, so its completion already means everything + * before it on the queue is done -- which is all the record's own barrier packet says + * -- and the packet processor decrements its completion signal after its release + * fence, raised here to the scope the record needs. The separate packet costs the + * recording queue a packet of its own between two kernels, and a queue waiting on the + * record sees the signal that much later. */ + const TapeRec* nx = i + 1 < to ? &t->rec[(size_t)i + 1] : nullptr; + Event* ne = (nx && nx->kind == kTapeRecord && nx->s == r.s) ? ev_of(nx->ev) : nullptr; + Sig* g = nullptr; + int rel = HSA_FENCE_SCOPE_NONE; + if (ne && !(g = record_arm(ne, r.s, &rel))) { + device_set_error("rad tape: no signal could be made for a record"); + rc = RAD_E_DEVICE; + break; + } + uint64_t idx = 0; + rc = run.put(r, &idx, g ? g->h : hsa_signal_t{0}, rel); + if (rc < 0) break; + bool found = false; + for (auto& l : t->last) + if (l.first == r.s->id) { l.second = idx; found = true; break; } + if (!found) t->last.emplace_back(r.s->id, idx); + if (g) { + /* Announced before the event names it, as the record's own path does: another + * queue is about to wait on it. The event's lock is taken with no queue held. */ + run.end(); + record_adopt(ne, g); + ++i; + } + continue; + } + /* An event takes its queue's lock itself, and a wait on another queue must not sit behind + * packets this run has written and not yet announced. */ + run.end(); + rc = r.kind == kTapeRecord ? a_event_record(r.ev, (RadStream)r.s) + : a_event_wait((RadStream)r.s, r.ev); + } + run.end(); + --t_tape_pause; + return rc; +} + +int a_tape_diff(RadTape ra, RadTape rb, char* why, int cap) { + const Tape* a = tape_of(ra); + const Tape* b = tape_of(rb); + auto say = [&](int at, const std::string& m) { + if (why && cap > 0) std::snprintf(why, (size_t)cap, "record %d: %s", at, m.c_str()); + return at; + }; + if (!a || !b) return say(0, "a null tape"); + const size_t n = std::min(a->rec.size(), b->rec.size()); + auto kname = [](uint64_t obj) { + std::lock_guard nl(g_names_mu); + auto it = g_names.find(obj); + return it != g_names.end() ? it->second : fmt("%#" PRIx64, obj); + }; + for (size_t i = 0; i < n; ++i) { + const TapeRec& x = a->rec[i]; + const TapeRec& y = b->rec[i]; + if (x.kind != y.kind || x.s != y.s || x.ev != y.ev || x.fence != y.fence) + return say((int)i, fmt("kind %d on queue %u against kind %d on queue %u", x.kind, + x.s->id, y.kind, y.s->id)); + if (x.kind != kTapeDispatch) continue; + hsa_kernel_dispatch_packet_t px = x.pkt, py = y.pkt; + px.kernarg_address = py.kernarg_address = nullptr; + if (std::memcmp(&px, &py, sizeof px) != 0) + return say((int)i, fmt("kernel %s against %s, grid %ux%ux%u against %ux%ux%u", + kname(x.pkt.kernel_object).c_str(), + kname(y.pkt.kernel_object).c_str(), x.pkt.grid_size_x, + x.pkt.grid_size_y, x.pkt.grid_size_z, y.pkt.grid_size_x, + y.pkt.grid_size_y, y.pkt.grid_size_z)); + const size_t len = x.karg_len; + if (len != y.karg_len || + std::memcmp(a->karg_host.data() + x.karg_off, b->karg_host.data() + y.karg_off, len) != 0) { + size_t k = 0; + while (k < len && k < y.karg_len && + a->karg_host[x.karg_off + k] == b->karg_host[y.karg_off + k]) ++k; + return say((int)i, fmt("kernel %s: its arguments differ at byte %zu", + kname(x.pkt.kernel_object).c_str(), k)); + } + } + if (a->rec.size() != b->rec.size()) + return say((int)n, fmt("%zu records against %zu", a->rec.size(), b->rec.size())); + return -1; +} + +void a_tape_destroy(RadTape rt) { + Tape* t = tape_of(rt); + if (!t) return; + { + std::lock_guard lk(g_tape_mu); + g_tape_retired.push_back(t); + } + tape_reap(); +} + +int a_event_elapsed_ms(RadEvent ra, RadEvent rb, float* out) { + Event* a = ev_of(ra); + Event* b = ev_of(rb); + if (!a || !b || !out) return RAD_E_INVAL; + if (a == b) { *out = 0.0f; return a->cur ? RAD_OK : RAD_E_INVAL; } + hsa_amd_profiling_dispatch_time_t ta{}, tb{}; + { + std::scoped_lock lk(a->mu, b->mu); + if (!a->cur || !b->cur) return RAD_E_INVAL; + if (hsa_amd_profiling_get_dispatch_time(a->cur->agent, a->cur->h, &ta) != HSA_STATUS_SUCCESS || + hsa_amd_profiling_get_dispatch_time(b->cur->agent, b->cur->h, &tb) != HSA_STATUS_SUCCESS) { + device_set_error("rad_event_elapsed_ms: no timestamps on the event packets"); + return RAD_E_DEVICE; + } + } + *out = (float)((double)((int64_t)tb.end - (int64_t)ta.end) * 1e3 / (double)G().ts_freq); + return RAD_OK; +} + +/* ---- copies and fills */ + +int blit_copy(Stream* s, void* dst, const void* src, int64_t bytes, uint8_t fence) { + set_next_fence(fence); + const bool link = (fence & (kFenceAcquireSystem | kFenceReleaseSystem)) != 0; + const int rc = rad_aql_blit_copy(dst, src, (uint64_t)bytes, s, link); + set_next_fence(0); + return rc < 0 ? RAD_E_DEVICE : RAD_OK; +} + +/* PAGEABLE MEMORY IS BOUNCED THROUGH PINNED MEMORY AND WAITED FOR, one bounce buffer at a time, + * which is what HIP does with it too. It is counted: a pageable copy on the step path is a host + * wait in the middle of a step, and the counter is how such a caller is found. */ +int pageable_copy(Stream* s, void* dst, Loc ld, const void* src, Loc ls, int64_t bytes) { + g_pageable_bytes.fetch_add(bytes, std::memory_order_relaxed); + if (capturing() && t_tape->bad.empty()) + t_tape->bad = fmt("a copy of %lld bytes to or from pageable memory, which stages through " + "the host and waits", (long long)bytes); + std::lock_guard lk(s->bounce_mu); + for (int64_t off = 0; off < bytes; off += (int64_t)kBounceBytes) { + const int64_t n = std::min((int64_t)kBounceBytes, bytes - off); + if (ls == kPageable && ld == kPageable) { + std::memcpy((char*)dst + off, (const char*)src + off, (size_t)n); + } else if (ls == kPageable) { + /* The bounce buffer is reused by the next chunk, so the copy out of it has to have run + * before the host overwrites it. */ + RAD_TRY(stream_drain(s)); + std::memcpy(s->bounce, (const char*)src + off, (size_t)n); + RAD_TRY(blit_copy(s, (char*)dst + off, s->bounce, n, + kFenceAcquireSystem | (ld == kDevLocal ? 0 : kFenceReleaseSystem))); + } else { + RAD_TRY(blit_copy(s, s->bounce, (const char*)src + off, n, + kFenceReleaseSystem | (ls == kDevLocal ? 0 : kFenceAcquireSystem))); + RAD_TRY(stream_drain(s)); + std::memcpy((char*)dst + off, s->bounce, (size_t)n); + } + } + if (ls == kPageable) RAD_TRY(stream_drain(s)); + return RAD_OK; +} + +int a_memcpy_async(void* dst, const void* src, int64_t bytes, RadStream rs) { + Stream* s = ours(rs); + if (!s) { device_set_error("rad_memcpy_async: not a stream of this backend"); return RAD_E_INVAL; } + if (bytes == 0) return RAD_OK; + if (bytes < 0) return RAD_E_INVAL; + const void* gd = nullptr; + const void* gs = nullptr; + const Loc ld = locate(dst, s, &gd); + const Loc ls = locate(src, s, &gs); + if (ld == kPageable || ls == kPageable) + return pageable_copy(s, ld == kPageable ? dst : (void*)gd, ld, + ls == kPageable ? src : gs, ls, bytes); + const uint8_t fence = (ls != kDevLocal ? kFenceAcquireSystem : 0) | + (ld != kDevLocal ? kFenceReleaseSystem : 0); + return blit_copy(s, (void*)gd, gs, bytes, fence); +} + +int a_memcpy_2d_async(void* dst, int64_t dpitch, const void* src, int64_t spitch, int64_t width, + int64_t height, RadStream rs) { + Stream* s = ours(rs); + if (!s) { device_set_error("rad_memcpy_2d_async: not a stream of this backend"); return RAD_E_INVAL; } + if (width == 0 || height == 0) return RAD_OK; + if (width < 0 || height < 0 || dpitch < width || spitch < width) return RAD_E_INVAL; + const void* gd = nullptr; + const void* gs = nullptr; + const Loc ld = locate(dst, s, &gd); + const Loc ls = locate(src, s, &gs); + if (ld == kPageable || ls == kPageable) { + /* Row by row through the 1-D path: a pitched copy of pageable memory has no fast form and + * no caller on the step path. */ + for (int64_t r = 0; r < height; ++r) + RAD_TRY(a_memcpy_async((char*)dst + r * dpitch, (const char*)src + r * spitch, width, rs)); + return RAD_OK; + } + const uint8_t fence = (ls != kDevLocal ? kFenceAcquireSystem : 0) | + (ld != kDevLocal ? kFenceReleaseSystem : 0); + set_next_fence(fence); + const int rc = rad_aql_blit_copy2d((void*)gd, (uint64_t)dpitch, gs, (uint64_t)spitch, + (uint64_t)width, (uint64_t)height, s); + set_next_fence(0); + return rc < 0 ? RAD_E_DEVICE : RAD_OK; +} + +/* NO PAGEABLE FORM: the kernel reads the range list and the source where they are, so both have + * to be memory the card reaches, and bouncing them would be a host wait inside the copy. */ +int a_memcpy_ranges_async(void* dst, const void* src, int64_t prefix, const RadCopyRange* ranges, + int n, RadStream rs) { + Stream* s = ours(rs); + if (!s) { + device_set_error("rad_memcpy_ranges_async: not a stream of this backend"); + return RAD_E_INVAL; + } + if (prefix < 0 || (prefix & 15) || n < 0 || (n > 0 && !ranges)) { + device_set_error("rad_memcpy_ranges_async: prefix %lld (a multiple of 16), %d ranges", + (long long)prefix, n); + return RAD_E_INVAL; + } + if (prefix == 0 && n == 0) return RAD_OK; + const void* gd = nullptr; + const void* gs = nullptr; + const void* gr = ranges; + const Loc ld = locate(dst, s, &gd); + const Loc ls = locate(src, s, &gs); + const Loc lr = n > 0 ? locate(ranges, s, &gr) : kDevLocal; + if (ld == kPageable || ls == kPageable || lr == kPageable || + (((uintptr_t)gd | (uintptr_t)gs) & 15)) { + device_set_error("rad_memcpy_ranges_async(%p <- %p, ranges %p): every address must be one " + "the card reaches, and both bases 16-byte aligned", dst, src, + (const void*)ranges); + return RAD_E_UNSUPPORTED; + } + set_next_fence((ls != kDevLocal || lr != kDevLocal ? kFenceAcquireSystem : 0) | + (ld != kDevLocal ? kFenceReleaseSystem : 0)); + const int rc = rad_aql_blit_ranges((void*)gd, gs, (uint64_t)prefix, (const RadCopyRange*)gr, + n, s); + set_next_fence(0); + return rc < 0 ? RAD_E_DEVICE : RAD_OK; +} + +int a_memset_async(void* dst, int value, int64_t bytes, RadStream rs) { + Stream* s = ours(rs); + if (!s) { device_set_error("rad_memset_async: not a stream of this backend"); return RAD_E_INVAL; } + if (bytes == 0) return RAD_OK; + const void* gd = nullptr; + const Loc ld = locate(dst, s, &gd); + if (ld == kPageable) { + device_set_error("rad_memset_async(%p, %lld): the destination is not device-accessible " + "-- RAD_MEM_HOST is pageable and the GPU has never seen it. Use " + "RAD_MEM_HOST_PINNED or RAD_MEM_HOST_MAPPED, or memset it on the host.", + dst, (long long)bytes); + return RAD_E_UNSUPPORTED; + } + set_next_fence(ld != kDevLocal ? kFenceReleaseSystem : 0); + const int rc = rad_aql_blit_fill((void*)gd, value, (uint64_t)bytes, s); + set_next_fence(0); + return rc < 0 ? RAD_E_DEVICE : RAD_OK; +} + +/* ---- elastic memory, through HSA. + * + * HIP's virtual-memory calls build HIP's own default-stream queue on the card the first time a + * range is backed -- hipMemCreate hands the new pages to HIP's command machinery -- and that queue + * is a hardware queue this process never submits to. A card runs only so many queues at once; past + * that it time-slices them, every kernel on the busy ones pays for the switch, and the two lanes of + * a rank stop overlapping. The same reservations, backings and unmappings through HSA touch no + * queue at all. + * + * A CARD WHOSE POOL REPORTS NO ALLOCATION GRANULE REPORTS A GRANULARITY OF ZERO, and every pool is + * then sized once and allocated whole (VMem::supported()). A backed range is readable and writable + * by its reservation's card only: every elastic pool belongs to one rank, and tensor parallel shares + * through the all-reduce buffers, not these. + * + * WHICH CARD A RESERVATION BELONGS TO is recorded when it is made, because the pages a commit maps + * go on a device and the vtable names none: the device current at RESERVE time is the rank's -- + * every rank reserves its pools with its own card selected -- while the thread that later grows a + * pool may have visited another card since. A mapping's handle is kept until the unmap, which is + * what releases it. */ +struct VRes { uintptr_t base; uintptr_t end; int ord; }; +std::mutex g_vres_mu; +std::vector g_vres; +std::unordered_map g_vmaps; + +int vres_ord(const void* addr) { + const uintptr_t a = (uintptr_t)addr; + std::lock_guard lk(g_vres_mu); + for (const VRes& r : g_vres) + if (a >= r.base && a < r.end) return r.ord; + return -1; +} + +int64_t a_vmem_granularity(void) { + int dev = 0; + if (hipGetDevice(&dev) != hipSuccess || dev < 0 || dev >= (int)G().dev.size()) return 0; + size_t gran = 0; + if (hsa_amd_memory_pool_get_info(G().dev[(size_t)dev].vram, + HSA_AMD_MEMORY_POOL_INFO_RUNTIME_ALLOC_REC_GRANULE, &gran) != + HSA_STATUS_SUCCESS || gran == 0) + return 0; + /* The pool's own answer is a floor and not the quantum to use: a map is tens of microseconds + * whatever it covers. RAD_ALIGN_POOL is what every pool is aligned to already, and taking it + * makes this backend's granule the host backend's. */ + const int64_t g = (int64_t)gran < (int64_t)RAD_ALIGN_POOL ? (int64_t)RAD_ALIGN_POOL : (int64_t)gran; + return align_up(g, (int64_t)RAD_ALIGN_POOL); +} + +void* a_vmem_reserve(int64_t bytes, int64_t align) { + if (bytes <= 0) return nullptr; + int dev = 0; + if (hipGetDevice(&dev) != hipSuccess) dev = 0; + void* p = nullptr; + if (hsa_amd_vmem_address_reserve_align(&p, (size_t)bytes, 0, + (uint64_t)(align > 0 ? align : 0), 0) != + HSA_STATUS_SUCCESS || !p) { + device_set_error("vmem: %lld bytes of address space could not be reserved", + (long long)bytes); + return nullptr; + } + std::lock_guard lk(g_vres_mu); + g_vres.push_back({ (uintptr_t)p, (uintptr_t)p + (uintptr_t)bytes, dev }); + return p; +} + +void a_vmem_release(void* base, int64_t bytes) { + if (!base || bytes <= 0) return; + loc_forget(); + { + std::lock_guard lk(g_vres_mu); + for (size_t i = 0; i < g_vres.size(); ++i) + if (g_vres[i].base == (uintptr_t)base) { g_vres.erase(g_vres.begin() + (long)i); break; } + } + (void)hsa_amd_vmem_address_free(base, (size_t)bytes); +} + +/* Backed, and readable and writable by the reservation's card at once: HSA grants access per + * mapping, so there is nothing for a later protect over a longer run to add. */ +int a_vmem_commit(void* addr, int64_t bytes) { + if (!addr || bytes <= 0) return RAD_E_INVAL; + int dev = vres_ord(addr); + if (dev < 0 && hipGetDevice(&dev) != hipSuccess) return RAD_E_DEVICE; + if (dev < 0 || dev >= (int)G().dev.size()) return RAD_E_DEVICE; + const Dev& d = G().dev[(size_t)dev]; + hsa_amd_vmem_alloc_handle_t h{}; + if (hsa_amd_vmem_handle_create(d.vram, (size_t)bytes, MEMORY_TYPE_NONE, 0, &h) != + HSA_STATUS_SUCCESS) { + device_set_error("vmem: %lld bytes could not be backed on device %d", (long long)bytes, dev); + return RAD_E_NOMEM; + } + if (hsa_amd_vmem_map(addr, (size_t)bytes, 0, h, 0) != HSA_STATUS_SUCCESS) { + (void)hsa_amd_vmem_handle_release(h); + device_set_error("vmem: a map of %lld bytes at %p failed", (long long)bytes, addr); + return RAD_E_DEVICE; + } + const hsa_amd_memory_access_desc_t acc{ HSA_ACCESS_PERMISSION_RW, d.agent }; + if (hsa_amd_vmem_set_access(addr, (size_t)bytes, &acc, 1) != HSA_STATUS_SUCCESS) { + (void)hsa_amd_vmem_unmap(addr, (size_t)bytes); + (void)hsa_amd_vmem_handle_release(h); + device_set_error("vmem: device %d could not be given access to %p", dev, addr); + return RAD_E_DEVICE; + } + std::lock_guard lk(g_vres_mu); + g_vmaps[(uintptr_t)addr] = h; + loc_forget(); /* the range is backed now, and no longer only reserved */ + return RAD_OK; +} + +int a_vmem_protect(void* addr, int64_t bytes) { + return (!addr || bytes <= 0) ? RAD_E_INVAL : RAD_OK; +} + +int a_vmem_decommit(void* addr, int64_t bytes) { + if (!addr || bytes <= 0) return RAD_E_INVAL; + loc_forget(); + hsa_amd_vmem_alloc_handle_t h{}; + bool have = false; + { + std::lock_guard lk(g_vres_mu); + auto it = g_vmaps.find((uintptr_t)addr); + if (it != g_vmaps.end()) { h = it->second; have = true; g_vmaps.erase(it); } + } + if (hsa_amd_vmem_unmap(addr, (size_t)bytes) != HSA_STATUS_SUCCESS) { + device_set_error("vmem: an unmap of %lld bytes at %p failed", (long long)bytes, addr); + return RAD_E_DEVICE; + } + if (have) (void)hsa_amd_vmem_handle_release(h); + return RAD_OK; +} + +/* HIP's own free, behind the forgetting every free needs (locate's cache). */ +void (*g_hip_free)(void*, int) = nullptr; +void a_free(void* p, int kind) { + loc_forget(); + if (g_hip_free) g_hip_free(p, kind); +} + +/* ------------------------------------------------------------------ plugin device code */ + +size_t a_code_mark(void) { + Registry& r = reg(); + std::lock_guard lk(r.mu); + return r.order.size(); +} + +/* Whether every fat binary registered in [from, to) holds a code object `device` runs -- the + * same choice the first launch out of each will make (module_meta), made now, while a library + * that carries nothing for this card can still be left out of selection rather than chosen and + * failed at its first launch. */ +int a_code_runs(size_t from, size_t to, int device, char* why, int cap) { + if (device < 0 || (size_t)device >= G().dev.size()) return RAD_E_INVAL; + const std::vector& isas = G().dev[(size_t)device].isas; + std::vector bundles; + { + Registry& r = reg(); + std::lock_guard lk(r.mu); + for (size_t i = from; i < to && i < r.order.size(); ++i) bundles.push_back(r.order[i]->bundle); + } + for (const void* b : bundles) { + const void* co = nullptr; + size_t size = 0; + std::string err; + if (!bundle_code_object(b, isas, &co, &size, &err)) { + if (why && cap > 0) std::snprintf(why, (size_t)cap, "%s", err.c_str()); + return 0; + } + } + return 1; +} + +DeviceBackend g_aql; + +} // namespace + +const DeviceBackend* aql_backend_if_present(void) { + static const DeviceBackend* b = []() -> const DeviceBackend* { + const DeviceBackend* hip = hip_backend_if_present(); + if (!hip) return nullptr; + /* THE INTERPOSITION HAS TO BE LIVE, or every plugin launch would hand HIP a queue it has + * never heard of. It is live when this executable exports hipLaunchKernel, which every + * target linking the core does (core/CMakeLists.txt); a binary that does not is a build + * error, reported as one rather than run on the other backend. */ + void* bound = dlsym(RTLD_DEFAULT, "hipLaunchKernel"); + if (bound != reinterpret_cast(&::hipLaunchKernel)) { + RAD_ERR("device: this executable does not export hipLaunchKernel, so kernel plugins " + "would launch through HIP onto queues HIP does not own. Link it with the " + "core's interface link options."); + std::abort(); + } + if (!init_devices()) { + RAD_ERR("device: the AQL backend cannot start: %s", G().why.c_str()); + std::abort(); + } + G().ok = true; + g_aql = *hip; + g_aql.name = "aql"; + g_hip_free = hip->free; + g_aql.free = a_free; + g_aql.stream_create = a_stream_create; + g_aql.stream_destroy = a_stream_destroy; + g_aql.stream_sync = a_stream_sync; + g_aql.event_create = a_event_create; + g_aql.event_destroy = a_event_destroy; + g_aql.event_record = a_event_record; + g_aql.event_wait = a_event_wait; + g_aql.event_query = a_event_query; + g_aql.event_sync = a_event_sync; + g_aql.host_wrote = a_host_wrote; + g_aql.event_elapsed_ms = a_event_elapsed_ms; + g_aql.memcpy_async = a_memcpy_async; + g_aql.memcpy_2d_async = a_memcpy_2d_async; + g_aql.memset_async = a_memset_async; + g_aql.memcpy_ranges_async = a_memcpy_ranges_async; + g_aql.vmem_granularity = a_vmem_granularity; + g_aql.vmem_reserve = a_vmem_reserve; + g_aql.vmem_release = a_vmem_release; + g_aql.vmem_commit = a_vmem_commit; + g_aql.vmem_decommit = a_vmem_decommit; + g_aql.vmem_protect = a_vmem_protect; + g_aql.tape_begin = a_tape_begin; + g_aql.tape_mark = a_tape_mark; + g_aql.tape_pause = a_tape_pause; + g_aql.tape_end = a_tape_end; + g_aql.tape_len = a_tape_len; + g_aql.tape_play = a_tape_play; + g_aql.tape_diff = a_tape_diff; + g_aql.tape_record = a_tape_record; + g_aql.code_mark = a_code_mark; + g_aql.code_runs = a_code_runs; + g_aql.tape_set_overlap = a_tape_set_overlap; + g_aql.tape_destroy = a_tape_destroy; + return &g_aql; + }(); + return b; +} + +int64_t aql_pageable_bytes(void) { return aql::g_pageable_bytes.load(std::memory_order_relaxed); } + +int aql_vmem_device_of(const void* addr, int* dev) { + const int d = vres_ord(addr); + if (d < 0) return RAD_E_NOTFOUND; + *dev = d; + return RAD_OK; +} + +} // namespace rad + +/* ================================================================== the HIP entry points + * + * Defined in the executable, so the dynamic linker binds a plugin's references here ahead of the + * HIP runtime's. Each forwards anything that is not this backend's to HIP. */ + +using namespace rad::aql; + +extern "C" { + +void** __hipRegisterFatBinary(const void* data) { + void** h = real().reg_fat ? real().reg_fat(data) : nullptr; + /* The wrapper is { magic, version, binary, reserved }; `binary` is the offload bundle. */ + struct Wrapper { unsigned magic, version; const void* binary; void* reserved; }; + const Wrapper* w = static_cast(data); + if (w && w->binary) { + Registry& r = reg(); + std::lock_guard lk(r.mu); + /* HIP hands back no handle for a fat binary with nothing for any visible device. It is + * still counted, under a record nothing can launch from, because that is exactly the + * plugin the loader's check exists to catch. */ + if (!h) { + Module* m = new Module(); + m->bundle = w->binary; + r.order.push_back(m); + return h; + } + Module*& m = r.by_handle[h]; + /* A handle HIP hands out again after a plugin was unloaded -- the loader closes one it + * refuses -- names a new fat binary, and the old record's parsed code object points into a + * mapping that is gone. Records are never freed (see __hipUnregisterFatBinary), so the old + * one is simply left behind. */ + if (!m || m->bundle != w->binary) m = new Module(); + m->bundle = w->binary; + r.order.push_back(m); + } + return h; +} + +void __hipRegisterFunction(void** modules, const void* host_fn, char* device_fn, + const char* device_name, unsigned thread_limit, void* tid, void* bid, + void* block_dim, void* grid_dim, int* wsize) { + if (real().reg_fn) + real().reg_fn(modules, host_fn, device_fn, device_name, thread_limit, tid, bid, block_dim, + grid_dim, wsize); + Registry& r = reg(); + std::lock_guard lk(r.mu); + auto it = r.by_handle.find(modules); + if (it == r.by_handle.end() || !host_fn || !device_name) return; + Func*& f = r.by_stub[host_fn]; + if (!f) f = new Func(); + f->mod = it->second; + f->name = device_name; +} + +void __hipUnregisterFatBinary(void** modules) { + /* The module's executables stay loaded: a process that unloads a kernel plugin is exiting, + * and the records above are what a late launch would otherwise dereference. */ + if (real().unreg_fat) real().unreg_fat(modules); +} + +hipError_t hipLaunchKernel(const void* f, dim3 g, dim3 b, void** args, size_t shm, hipStream_t st) { + Stream* s = ours(st); + if (!s) { + g_hip_streams_used.store(true, std::memory_order_relaxed); + return real().launch ? real().launch(f, g, b, args, shm, st) : hipErrorNotSupported; + } + const uint8_t fence = t_next_fence; + t_next_fence = 0; + std::string why; + KernelRec* k = kernel_for(f, s->ord, &why); + if (!k) { + RAD_ERR("device %d: cannot dispatch a kernel: %s", s->ord, why.c_str()); + return ret(hipErrorInvalidDeviceFunction); + } + return ret(dispatch(s, k, g, b, args, shm, fence) < 0 ? hipErrorLaunchFailure : hipSuccess); +} + +hipError_t hipMemcpy2DAsync(void* dst, size_t dpitch, const void* src, size_t spitch, size_t width, + size_t height, hipMemcpyKind kind, hipStream_t st) { + if (!ours(st)) { + g_hip_streams_used.store(true, std::memory_order_relaxed); + return real().memcpy2d ? real().memcpy2d(dst, dpitch, src, spitch, width, height, kind, st) + : hipErrorNotSupported; + } + return ret(rad_memcpy_2d_async(dst, (int64_t)dpitch, src, (int64_t)spitch, (int64_t)width, + (int64_t)height, (RadStream)st) < 0 ? hipErrorInvalidValue + : hipSuccess); +} + +hipError_t hipMemcpyAsync(void* dst, const void* src, size_t bytes, hipMemcpyKind kind, + hipStream_t st) { + if (!ours(st)) { + g_hip_streams_used.store(true, std::memory_order_relaxed); + return real().memcpy ? real().memcpy(dst, src, bytes, kind, st) : hipErrorNotSupported; + } + return ret(rad_memcpy_async(dst, src, (int64_t)bytes, (RadStream)st) < 0 ? hipErrorInvalidValue + : hipSuccess); +} + +hipError_t hipMemsetAsync(void* dst, int value, size_t bytes, hipStream_t st) { + if (!ours(st)) { + g_hip_streams_used.store(true, std::memory_order_relaxed); + return real().memset ? real().memset(dst, value, bytes, st) : hipErrorNotSupported; + } + return ret(rad_memset_async(dst, value, (int64_t)bytes, (RadStream)st) < 0 ? hipErrorInvalidValue + : hipSuccess); +} + +/* A SYNCHRONOUS FILL, ON ONE OF THE BACKEND'S OWN QUEUES FOR THE CURRENT DEVICE. Kernel libraries + * zero their small private blocks this way -- an all-reduce's flags at init, a split-K GEMM's + * arrival counters on first use -- and HIP would serve each by building its default stream's + * queues on that card. Those are hardware queues this process never otherwise uses, and a card + * whose compute work is spread over more queues than it runs at once time-slices them: every + * kernel on the busy ones then pays a switch, and the two lanes of a rank stop overlapping. + * + * The fill goes on the first queue this process made on the device, which is the compute stream of + * the rank that owns it, and is waited for there. A device with no queue yet -- a peer's buffers + * set up before its rank has started -- gets one for the fill and loses it again, so no queue + * outlives the call. It is never part of a recorded pass: it runs once for a block that is then + * kept. */ +hipError_t hipMemset(void* dst, int value, size_t bytes) { + if (!G().ok) return real().memset_sync ? real().memset_sync(dst, value, bytes) : hipErrorNotSupported; + int dev = -1; + if (hipGetDevice(&dev) != hipSuccess) return ret(hipErrorInvalidDevice); + Stream* s = nullptr; + { + std::lock_guard lk(G().streams_mu); + for (Stream* x : G().streams) + if (x->ord == dev) { s = x; break; } + } + RadStream own = nullptr; + if (!s) { + if (rad_stream_create(&own, 0) < 0) return ret(hipErrorOutOfMemory); + s = ours(own); + } + ++t_tape_pause; + int rc = rad_memset_async(dst, value, (int64_t)bytes, (RadStream)s); + if (rc >= 0) rc = stream_drain(s); + --t_tape_pause; + if (own) rad_stream_destroy(own); + return ret(rc < 0 ? hipErrorInvalidValue : hipSuccess); +} + +hipError_t hipStreamSynchronize(hipStream_t st) { + if (!st && !g_hip_streams_used.load(std::memory_order_relaxed)) return ret(hipSuccess); + if (!ours(st)) return real().sync ? real().sync(st) : hipErrorNotSupported; + return ret(rad_stream_sync((RadStream)st) < 0 ? hipErrorLaunchFailure : hipSuccess); +} + +/* The two stream APIs a plugin could plausibly reach for that have no meaning on a queue of this + * backend: events are the engine's, through rad_event_*. Refused by name rather than handed to + * HIP, which would dereference the queue as one of its own streams. */ +hipError_t hipEventRecord(hipEvent_t e, hipStream_t st) { + if (!ours(st)) return real().ev_record ? real().ev_record(e, st) : hipErrorNotSupported; + RAD_ERR("hipEventRecord on an engine stream: use rad_event_record"); + return ret(hipErrorNotSupported); +} + +hipError_t hipStreamWaitEvent(hipStream_t st, hipEvent_t e, unsigned flags) { + if (!ours(st)) return real().wait_ev ? real().wait_ev(st, e, flags) : hipErrorNotSupported; + RAD_ERR("hipStreamWaitEvent on an engine stream: use rad_event_wait"); + return ret(hipErrorNotSupported); +} + +hipError_t hipGetLastError(void) { + if (t_ours) { + const hipError_t e = t_err; + t_ours = false; + t_err = hipSuccess; + /* HIP's own slot holds whatever came before this backend's call, which that call + * overwrote. */ + if (real().last) (void)real().last(); + return e; + } + return real().last ? real().last() : hipSuccess; +} + +hipError_t hipPeekAtLastError(void) { + if (t_ours) return t_err; + return real().peek ? real().peek() : hipSuccess; +} + +} // extern "C" + +#endif /* RAD_HAVE_HIP */ diff --git a/core/device/aql.h b/core/device/aql.h new file mode 100644 index 00000000..cdb56126 --- /dev/null +++ b/core/device/aql.h @@ -0,0 +1,90 @@ +/* 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 +#include +#include +#include + +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; /* ".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 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& 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* 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); +} diff --git a/core/device/aql_blit.hip b/core/device/aql_blit.hip new file mode 100644 index 00000000..24bfdc01 --- /dev/null +++ b/core/device/aql_blit.hip @@ -0,0 +1,252 @@ +/* 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 + +#include + +#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(); +} diff --git a/core/device/aql_code.cpp b/core/device/aql_code.cpp new file mode 100644 index 00000000..9ef8bcd1 --- /dev/null +++ b/core/device/aql_code.cpp @@ -0,0 +1,324 @@ +/* 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 + +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> 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& isas, const void** out, + size_t* out_size, std::string* why) { + static const char kMagic[] = "__CLANG_OFFLOAD_BUNDLE__"; + const unsigned char* b = static_cast(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 "-amdgcn-amd-amdhsa--". 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 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(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 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(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* out, + std::string* why) { + out->clear(); + const unsigned char* b = static_cast(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 diff --git a/core/device/device.h b/core/device/device.h new file mode 100644 index 00000000..2001034f --- /dev/null +++ b/core/device/device.h @@ -0,0 +1,379 @@ +/* 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 +#include +#include +#include + +/* AN EVENT THAT ONLY ORDERS WORK ON ONE CARD. Its record makes the recording stream's writes + * visible to the rest of that card and to nothing else, so it may be waited on by another stream + * of the same card and queried or synchronised by the host for WHEN, but the host must not read + * device-written memory on the strength of it, and no other card may wait on it. What that buys + * is the release: making writes visible to the system waits for every write still in flight to + * host memory, and with the link busy streaming weights that is most of a microsecond at best and + * over ten at worst on every record, where the card-wide release costs the packet alone. */ +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); +}; + + +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::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> 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 */ diff --git a/core/device/directio.cpp b/core/device/directio.cpp new file mode 100644 index 00000000..0d159968 --- /dev/null +++ b/core/device/directio.cpp @@ -0,0 +1,228 @@ +/* directio.cpp -- see directio.h for why the page cache is not wanted here. */ +#include "directio.h" +#include "../rad_internal.h" + +#include +#include +#include +#include + +#include +#include +#include +#include + +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 */ diff --git a/core/device/directio.h b/core/device/directio.h new file mode 100644 index 00000000..3f51ca6a --- /dev/null +++ b/core/device/directio.h @@ -0,0 +1,80 @@ +/* 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 + +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 */ diff --git a/core/device/dispatch.cpp b/core/device/dispatch.cpp new file mode 100644 index 00000000..1bae7081 --- /dev/null +++ b/core/device/dispatch.cpp @@ -0,0 +1,493 @@ +/* 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 +#include +#include +#include +#include +#include +#include +#include + +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 bytes{0}; + std::atomic 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 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 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 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 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; } +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" */ diff --git a/core/device/hip.cpp b/core/device/hip.cpp new file mode 100644 index 00000000..4141a3cf --- /dev/null +++ b/core/device/hip.cpp @@ -0,0 +1,393 @@ +/* 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. + * + * 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 + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +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 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_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: + /* The mover's staging pool and the O_DIRECT landing zone. Pinned so a transfer is a + * DMA the driver does not have to stage through its own bounce buffer (spec §5.4). */ + e = hipHostMalloc(&p, (size_t)bytes, hipHostMallocDefault); + break; + case RAD_MEM_HOST_MAPPED: + /* The zero-copy execution site: tier host, site device, no slab slot -- row three of + * spec §5.1's table. hipHostMallocMapped is what makes the allocation addressable from + * a kernel over the link, which is the whole mechanism. The cost is that every read is + * a link read, so this is for read-once weights and the planner decides which + * (spec §19.3). */ + e = hipHostMalloc(&p, (size_t)bytes, hipHostMallocMapped); + break; + 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_PINNED: + case RAD_MEM_HOST_MAPPED: HIP_NOTE(hipHostFree(p)); break; + case RAD_MEM_HOST: std::free(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, +}; + +} /* 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 */ diff --git a/core/device/host.cpp b/core/device/host.cpp new file mode 100644 index 00000000..87284227 --- /dev/null +++ b/core/device/host.cpp @@ -0,0 +1,793 @@ +/* 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 +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +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 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 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 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 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 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 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 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& alloc_table() { + static std::unordered_map 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 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 lk(alloc_mutex()); + alloc_table()[p] = AllocRec{bytes, kind, device}; +} + +bool alloc_take(void* p, AllocRec* out) { + std::lock_guard lk(alloc_mutex()); + auto it = alloc_table().find(p); + if (it == alloc_table().end()) return false; + *out = it->second; + alloc_table().erase(it); + return true; +} + +bool alloc_find(void* p, AllocRec* out) { + std::lock_guard 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 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 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 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 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 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 lk(ea->m); + if (ea->recorded == 0 || ea->completed < ea->recorded) return RAD_E_STATE; + ta = ea->stamp; + } + { + std::lock_guard lk(eb->m); + if (eb->recorded == 0 || eb->completed < eb->recorded) return RAD_E_STATE; + tb = eb->stamp; + } + *out = std::chrono::duration(tb - ta).count(); + return RAD_OK; +} + +/* A null stream is refused on both backends, and that is a decision rather than an oversight. + * HIP's stream 0 carries legacy implicit-synchronisation semantics: work on it serialises against + * every other blocking stream in the process. That is the exact opposite of spec §5.4's + * requirement that a transfer involve no host synchronisation and not serialise the step, so the + * engine never wants it, and letting it through here would let a caller pick it up by accident and + * only find out on a real device. */ +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 */ diff --git a/core/engine.cpp b/core/engine.cpp new file mode 100644 index 00000000..0f3111c2 --- /dev/null +++ b/core/engine.cpp @@ -0,0 +1,2082 @@ +/* engine.cpp -- the step loop and the server. + * + * The Engine's construction, the per-rank threads, the one loop that runs a step, and the server + * it runs under; bring-up, the drafters and the buffer probe have files of their own. See + * engine_priv.h for what the four share. + */ +#include "engine_priv.h" +#include "kld.h" +#include "mm/processor.h" + +#include "build/startup.h" +#include "build/rad_build.h" +#include "device/device.h" +#include "format/radfile.h" +#include "gen_config.h" +#include "sample/accept.h" +#include "sched/scheduler.h" +#include "server/adapters.h" +#include "server/server.h" +#include "server/liveview.h" +#include "text/tokenizer.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rad { + + + +Engine::Engine(Config cfg) : cfg_(std::move(cfg)) {} + +int32_t* Engine::Readback::reserve(int64_t count) { + if (count <= n) return p; + if (p) rad_dev_free(p, RAD_MEM_HOST_PINNED); + p = static_cast(rad_dev_alloc(count * (int64_t)sizeof(int32_t), RAD_MEM_HOST_PINNED)); + n = p ? count : 0; + return p; +} + +Engine::Readback::~Readback() { + if (p) rad_dev_free(p, RAD_MEM_HOST_PINNED); +} + +Engine::~Engine() { + /* WHERE --profile-ops LEAVES ITS FINAL TABLE. Here, because this is the last moment the + * program still holds the op table the rows name -- and it has to be printed somewhere: a + * flag that pays for the synchronisations, warns that the run is not comparable, and then + * says nothing is worse than no flag at all. */ + if (cfg_.profile_ops) for (auto& r : ranks_) r->ctx.dump_profile(); + for (float* p : kld_host_) if (p) rad_dev_free(p, RAD_MEM_HOST_PINNED); + /* The disk thread first: it reads the host arena and writes the store, both of which go with + * the ranks and kv_disk_ below. */ + if (pump_) pump_->io.stop(); + /* WHAT THE TIERING ACTUALLY DID, and it is printed here for the same reason: this is the last + * moment the plan the rows name is still alive. Only when the plan was dynamic -- a static + * one has nothing to say and a banner saying nothing is a banner people learn to skip. The + * per-layer residency histogram at the end of it is the number that says whether the global + * ranking starved a layer, which is the failure this engine has and a hit rate cannot show. */ + for (auto& r : ranks_) { + if (!r->heat.enabled()) continue; + LogRank lr(r->index); + RAD_INFO("%s", r->heat.report().c_str()); + RAD_INFO(" routing evidence: %llu layer-histograms credited, %llu layer-sweeps found " + "nothing new, %llu dropped by a ring shallower than the run-ahead", + (unsigned long long)r->heat_credited, (unsigned long long)r->heat_idle, + (unsigned long long)r->ctx.route_dropped()); + RAD_INFO("%s", r->mover.report().c_str()); + } + for (auto& r : ranks_) r->ctx.shutdown(); + step_state_fini(); + ranks_.clear(); + rad_tools_registry().close(); +} + + +/* ================================================================== 7. serve */ +/* The step loop, which is the one place every component meets. Threading is spec §1's exactly: + * HTTP threads feed a request queue, ONE scheduler thread produces ONE step, one thread per + * tensor-parallel rank each owning one device. + * + * The ranks share an address space, so the batch is shared BY POINTER and the whole of the + * handoff is a barrier -- no serialisation, no pipe, no pickling, which is most of what a Python + * engine's multiprocessing budget actually buys (rank_barrier.h). The barrier is entered TWICE + * per step: once to release the ranks against the batch, once to join them before the sampler's + * answer is read. The scheduler thread is a participant on both sides, which is why the barrier's + * width is tp + 1 and not tp. + */ + +int Engine::declare_sampler(int rank, RadBuilder* b, int64_t logits_width, bool sizing) { + Rank& r = *ranks_[(size_t)rank]; + /* A SIZING DECLARE DECLARES INTO A SAMPLER OF ITS OWN. The chain has to be in the Program for + * the buffer list to match the real one, but the rank's sampler keeps the handles the real + * declare gave it -- the ones every step issues. */ + Sampler scratch; + Sampler& smp = sizing ? scratch : r.sampler; + rad_buf scratch_tok = 0; + rad_buf& tok = sizing ? scratch_tok : r.tok_buf; + + SamplerConfig sc{}; + sc.n_vocab = meta_.n_vocab; + /* WHAT THIS RANK ACTUALLY PRODUCES, taken from the logits buffer the plugin declared rather + * than re-derived from n_vocab and world_size. `program.meta` is the CONTAINER's metadata and + * carries the whole model's n_vocab on every rank, so reading it here would be wrong the + * moment a vocabulary is split; and computing the split a second time here would be wrong + * again the moment a plugin decides not to split it, which is where rad_arch.h stands + * and says why. Either mistake is a sampler reading past the end of every logits row. */ + sc.n_vocab_local = logits_width > 0 ? logits_width : meta_.n_vocab; + /* THIS RANK'S FIRST VOCABULARY ROW, and it is the one thing the declared width cannot say: + * a width tells you how many rows a rank owns, not which. The rule is arch/common/rad_arch.h's + * shard_begin -- ceil(total/world) per rank with the last one short -- and it is restated here + * rather than carried through the ABI, so the restatement is CHECKED against what the plugin + * actually declared. A plugin that shards some other way gets a named refusal at startup + * instead of a sampler that names rank 0's tokens with rank 1's ids. */ + sc.vocab_off = 0; + if (sc.n_vocab_local < sc.n_vocab) { + const int64_t per = (sc.n_vocab + cfg_.tp - 1) / cfg_.tp; + sc.vocab_off = per * rank; + const int64_t want = std::min(per, sc.n_vocab - sc.vocab_off); + if (sc.vocab_off >= sc.n_vocab || want != sc.n_vocab_local) { + RAD_ERR("rank %d declared %lld logits columns of a %lld-token vocabulary at --tp %d; " + "the contiguous equal split this sampler assumes wants %lld. The plugin and " + "core/engine.cpp disagree about which rows this rank owns.", + rank, (long long)sc.n_vocab_local, (long long)sc.n_vocab, cfg_.tp, + (long long)want); + return RAD_E_INVAL; + } + } + sc.max_seqs = cfg_.max_seqs; + sc.max_spec = cfg_.n_spec; + sc.rank = rank; + sc.world_size = cfg_.tp; + RAD_TRY(smp.declare(b, sc)); + + /* Where the chain writes the sampled ids. The sampler takes it as an argument rather than + * declaring it, because rad-kbench drives the same chain against a buffer it owns -- so the + * engine is the one that has to provide one. PERSIST, not transient: the step loop copies it + * back after the step, by which time a transient's storage may belong to another buffer. */ + RadBufDecl d{}; + d.dtype = RAD_I32; + d.rank = 1; + d.shape[0] = cfg_.max_seqs * (cfg_.n_spec > 0 ? cfg_.n_spec + 1 : 1); + d.kind = RAD_BUF_PERSIST; + tok = rad_decl_buffer(b, "sampler.tokens", &d); + return tok ? RAD_OK : RAD_E_STATE; +} + + +/* ------------------------------------------------------------------ the tiering seam + * + * WHERE THE HEAT ENGINE RUNS, AND WHY IT IS A STEP AND NOT A LAYER. mover.h writes its run-phase + * contract as "the order a layer dispatch calls it", and ctx.cpp states the invariant that + * decides the unit: THE MOVER RELOCATES BETWEEN STEPS, NEVER DURING ONE -- `weights_dirty_` is + * honoured once at the top of run_step, so a table edit made mid-step would be seen by some + * issues and not others. A step is therefore the dispatch, and this pair brackets it. + * + * IT RUNS ONCE A STEP, AFTER THE STEP'S FORWARD PASS IS ON THE QUEUE: + * + * - AFTER, because nothing in it is work the pass waits for. Ahead of a draft pass the device + * is idle -- the previous pass was drained to read its proposal -- so whatever the rank thread + * does before its first dispatch is time the device sits out; behind the issue it runs under + * the pass instead. Nothing it changes can reach the pass just issued: table edits are + * honoured at the top of the NEXT run_step, and a slot it frees is quarantined behind an event + * on the compute stream recorded after this pass. + * - ONCE A STEP, on the trunk pass and not the draft passes, because a swap almost never + * clears the hysteresis between two passes of one step and every call ranks the whole + * movable set. The draft head's histograms are not lost by it: they accumulate in the step's + * bank and are credited at the next step, weighted by the passes they stand for. + * - `begin_dispatch` only RETIRES. It never starts anything, so a loop that retires without + * issuing is not a slower engine but a stuck one (mover.h says so at length). The issue call + * below is the other half and they are written together for that reason. + * - The histograms this credits are the PREVIOUS step's -- a copy is asynchronous and lands + * while the step that produced it is still running (spec §5.5) -- and `histogram_ready` says + * which have landed. + * + * ON A LONG PREFILL CHUNK ALMOST NONE OF THIS LANDS, and the counters below say so rather than + * leaving it to be inferred from a placement that will not settle. This runs BEFORE run_step and + * every issue path is enqueue-and-return, so on a chunk worth most of a second of device time the + * host is many steps ahead of the card: the freshest bank holds a copy the device has not reached, + * `histogram_ready` is 0, and the layer is skipped. Through a prefill of 2048-token chunks about 2% + * of the layer-histograms are credited and the rest skipped as not yet landed, against effectively + * all of them at a decode shape, where the step is short enough that the device keeps up. The same + * shortfall is what the link panel's expert-streaming share is computed from, so it reads near zero + * through a prefill that is in fact streaming. + * + * `heat_seen` is what stops a layer being credited twice. A bank holds its counts until the next + * report overwrites them, so a step in which some layer did not route -- a drafter pass, or a + * bisect running fewer layers -- would otherwise credit the stale plane again and again. + */ +void Engine::tiering_dispatch(Rank& r, int step) { + if (!r.heat.enabled()) return; + + r.mover.begin_dispatch(step, &r.heat); + + const int n_layer = r.ctx.n_route_layers(); + if ((int)r.heat_seen.size() != n_layer) r.heat_seen.assign((size_t)n_layer, -1); + /* THE SWEEP'S HISTOGRAMS ARE FOUND FIRST AND CREDITED SECOND, in the same order. A histogram + * is a row the card copied into host memory, so every line of it is a miss, and one layer's + * credit is too little work to hide the next row's fetch behind. With the rows known up front + * each is prefetched while an earlier one is credited: two rows ahead is 32 lines in flight, + * about what one core keeps outstanding to memory, so further ahead would only queue. */ + int8_t landed[kRouteBanks]; + std::memset(landed, -1, sizeof landed); + std::vector& rows = r.heat_rows; + rows.clear(); + for (int l = 0; l < n_layer; ++l) { + /* DRAIN THE LAYER, do not take one and move on. The host reaches this once per step it + * ISSUES, and on a long chunk it issues far ahead of the card -- so between two visits the + * device can have produced many of this layer's histograms. Taking only the newest would + * throw the rest away and, worse, usually find the newest still in flight and take + * nothing. */ + int seen = r.heat_seen[(size_t)l]; + bool any = false; + for (;;) { + const int bank = r.ctx.next_histogram(l, seen, step, landed); + if (bank < 0) break; + const int32_t* h = r.ctx.last_histogram(l, bank); + if (!h) break; + rows.push_back({l, bank, h}); + seen = r.ctx.last_histogram_step(l, bank); + any = true; + } + if (!any) ++r.heat_idle; + } + const int32_t n_ex = (int32_t)r.ctx.route_n_expert(); + constexpr size_t kAhead = 2; + for (size_t i = 0; i < rows.size() && i < kAhead; ++i) r.heat.prefetch(rows[i].h, n_ex); + for (size_t i = 0; i < rows.size(); ++i) { + if (i + kAhead < rows.size()) r.heat.prefetch(rows[i + kAhead].h, n_ex); + const Rank::HeatRow& hr = rows[i]; + /* One histogram can stand for more than one pass: a draft head reports once per draft + * pass and they all land in the same bank. Crediting such a bank once underprices that + * layer's experts by the number of passes, and the engine then drains the layer. */ + const int reps = r.ctx.last_histogram_reports(hr.layer, hr.bank); + r.heat.observe(hr.layer, hr.h, n_ex, reps > 1 ? (float)reps : 1.0f); + r.heat_seen[(size_t)hr.layer] = r.ctx.last_histogram_step(hr.layer, hr.bank); + r.ctx.mark_credited(hr.layer, hr.bank); + ++r.heat_credited; + } + + std::vector swaps; + if (r.heat.step(&swaps) < 0) return; + for (const Swap& s : swaps) { + /* CONTRACT: every unit the engine named is BUSY on the way out, and a proposal that is + * silently dropped leaves the pair busy forever. `issue` clears it; `abandon` is what + * this owes the engine when the mover cannot take it. */ + if (r.mover.issue(s, &r.heat) < 0) r.heat.abandon(s); + } + + /* AFTER the swaps, because a swap is what the policy asked for and a fill is what the memory + * allows: spending a move record on a fill that the next swap then needs would let a + * boundary the arbiter happens to be moving reorder the engine's own decisions. */ + (void)r.mover.balance(&r.heat); +} +/* ------------------------------------------------------------------ the rank thread */ +void Engine::rank_loop(int index) { + Rank& r = *ranks_[(size_t)index]; + if (r.ctx.bind_thread() < 0) { + RAD_ERR("rank %d: could not bind its device", index); + step_status_.store(RAD_E_DEVICE, std::memory_order_release); + } + + for (;;) { + barrier_->arrive_and_wait(); /* released against this step's batch */ + if (stopping_.load(std::memory_order_acquire)) break; + + const RadBatch* b = step_batch_.load(std::memory_order_acquire); + if (b) { + /* This rank's view of the step: the same numbers, pointed at this card's staging. + * The upload that filled it was issued on THIS stream, so the ordering is an + * ordinary same-stream dependency and no cross-rank fence is needed. */ + const RadBatch* mine = sched_.batch_for(index); + if (!mine) { + RAD_ERR("rank %d: the builder has no batch for this rank", index); + step_status_.store(RAD_E_STATE, std::memory_order_release); + barrier_->arrive_and_wait(); + continue; + } + b = mine; + const int what = issue_what_.load(std::memory_order_acquire); + int s = what == kIssueSampler ? RAD_OK : r.ctx.run_step(b); + if (s < 0) { + RAD_ERR("rank %d step %d: %s", index, b->step, r.ctx.step_error()); + step_status_.store(s, std::memory_order_release); + } else if (b->n_out > 0 && what != kIssueModel) { + /* WAIT FOR THE STAGING, WHICH THE SCHEDULER IS DOING RIGHT NOW UNDER THE MODEL + * THIS THREAD JUST ENQUEUED. Everything above is enqueue-and-return, so arriving + * here means the device has a forward pass in front of it and this wait costs + * nothing it was not going to spend in collect_step anyway. */ + int bst = RAD_OK; + { + std::unique_lock lk(build_mu_); + build_cv_.wait(lk, [this] { return build_ready_; }); + bst = build_status_; + } + /* The sampler chain is issued on the SAME stream, right behind the model, with no + * host synchronisation between them: it is more ops on the compute stream and not + * a second phase (spec §13). */ + if (bst >= 0) { + s = r.sampler.run(&r.ctx, r.program.logits_buf, r.tok_buf); + if (s < 0) { + RAD_ERR("rank %d step %d: sampler: %s", index, b->step, rad_strerror(s)); + step_status_.store(s, std::memory_order_release); + } + } + } + /* Behind the pass, once a step: see tiering_dispatch. */ + if (s >= 0 && b->draft_pass == 0 && what != kIssueModel) tiering_dispatch(r, b->step); + + } + barrier_->arrive_and_wait(); /* joined; the scheduler may read */ + } +} + +/* ------------------------------------------------------------------ the scheduler thread */ +int Engine::prepare_release(const RadBatch* b) { + /* THE ARENA LEVEL, AND THE ARENA'S MEMORY BACK FROM THE SLAB IF THIS STEP NEEDS IT. Every + * rank thread is parked, so a level can change and a recall can drain both streams. */ + if (const int as = arena_step(b); as < 0) return as; + /* THE FOLLOWERS' POOLS, BEFORE THE TABLE THAT INDEXES THEM. Admission grew rank 0's cache for + * this step and the ids are already in the block table; a follower still at the old mark + * would read pages it never mapped. Here rather than on the arbiter's tick because the tick + * is 100 ms away and this step is about to run, and safe here because every rank thread is + * parked at the release. */ + for (size_t i = 1; i < ranks_.size(); ++i) { + if (rad_dev_set(ranks_[i]->device) < 0) continue; + if (ranks_[i]->kv.follow(ranks_[0]->kv) < 0) + step_status_.store(RAD_E_NOMEM, std::memory_order_release); + } + if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device); + return RAD_OK; +} + +int Engine::issue_ahead(const RadBatch** out) { + *out = nullptr; + if (!pipelining_) return RAD_OK; + for (int i = 0; i < serial_rows_ && serial_done_ > 0; ++i) + sched_.expect_draft(serial_row_[(size_t)i].seq, serial_done_); + const RadBatch* nb = sched_.step_next(); + if (!nb) return RAD_OK; + /* Its rows' tokens, positions and slots, from where this step's acceptance and drafts leave + * them -- in stream order behind all of it. */ + RAD_TRY(advance_all(ADV_TRUNK, 0, false)); + RAD_TRY(prepare_release(nb)); + issue_what_.store(kIssueModel, std::memory_order_release); + step_batch_.store(nb, 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("step %d, issued ahead, failed: %s -- the engine cannot continue", nb->step, + rad_strerror(st)); + return st; + } + *out = nb; + return RAD_OK; +} + +void Engine::phase_mark(int p) { + const auto now = std::chrono::steady_clock::now(); + phase_us_[p] += std::chrono::duration(now - phase_t_).count(); + phase_t_ = now; +} + +/* EVERY WAY OUT OF THE STEP LOOP ON AN ERROR GOES THROUGH HERE, because leaving it is three + * obligations and forgetting one is a server that looks alive and serves nothing: + * + * - the rank threads are parked on the barrier, and only an abort lets them see `stopping_`; + * - every request queued or running is waiting on a step that will never come, so it is failed + * now and its connection answered, and the scheduler refuses anything submitted after; + * - run_server watches `loop_status_` and takes the HTTP side down, so the process exits with + * the error rather than accepting requests into a queue nothing drains (spec §17). */ +int Engine::fail_loop(int st) { + stopping_.store(true, std::memory_order_release); + if (barrier_) barrier_->abort(); + sched_.shutdown("the engine stopped on an error and is not serving"); + loop_status_.store(st < 0 ? st : RAD_E_STATE, std::memory_order_release); + return st; +} + +int Engine::step_loop() { + /* The batch is built on rank 0's stream into rank 0's memory and shared by pointer, so + * this thread lives on rank 0's device. The backend's current device is thread-local: + * a fresh thread starts on device 0, which is right only by accident. */ + if (rad_dev_set(ranks_[0]->device) < 0) + RAD_ERR("step loop: could not bind rank 0's device"); + StepOut so; + int idle = 0; + std::vector cancel; + /* Not in the KL mode: its scored rows are copied out of the logits buffer after the step is + * collected, and a pass issued ahead would have overwritten them by then. */ + pipelining_ = !cfg_.kld() && drafter_.kind != RAD_DRAFT_BLOCK && + (serial_drafting() || cfg_.n_spec <= 0); + const bool t_on = (int)log_level() >= (int)Log::Debug; + /* Read once. See the block in the idle branch below for what it is for. */ + /* "kv" | "arena" | "all" | "kv:," -- the last narrows the KV scrub to named groups, + * which is the level below "it is the pool" and the one that names the defect. */ + const char* const scrub_s_ = std::getenv("RADIANCE_DEBUG_IDLE_SCRUB"); + std::string scrub_groups_; + int scrub_ = 0; + if (scrub_s_ && *scrub_s_) { + if (!std::strncmp(scrub_s_, "kv:", 3)) { scrub_ = 1; scrub_groups_ = std::string(",") + (scrub_s_ + 3) + ","; } + else if (!std::strcmp(scrub_s_, "kv")) scrub_ = 1; + else if (!std::strcmp(scrub_s_, "arena")) scrub_ = 2; + else scrub_ = 3; + } + if (scrub_) + RAD_WARN("RADIANCE_DEBUG_IDLE_SCRUB=%d: the %s%s%s will be ZEROED every time the engine " + "goes idle. This is a determinism diagnostic and it is not free.", scrub_, + (scrub_ & 1) ? "KV pool" : "", scrub_ == 3 ? " and the " : "", + (scrub_ & 2) ? "activation arena" : ""); + + /* THE NEXT STEP'S FORWARD PASS, when it is already on the card: issued behind the step before + * it, before that step was read back (Scheduler::step_next). */ + const RadBatch* ahead = nullptr; + while (!stopping_.load(std::memory_order_acquire)) { + phase_t_ = std::chrono::steady_clock::now(); + /* MEDIA A WAITING REQUEST NEEDS, encoded while nothing is in flight: the last step has been + * collected and none was issued ahead of it -- the scheduler issues none while a request + * is waiting, and one whose media is not encoded waits. */ + if (!ahead && sched_.encodes_pending()) { + if (const int es = run_encodes(); es < 0) return fail_loop(es); + } + const bool issued = ahead != nullptr; + const RadBatch* b = ahead; + ahead = nullptr; + if (issued) sched_.promote_next(); + else b = sched_.step(); + if (!b) { + /* Nothing to run is not an error. Back off in small steps rather than spinning a core + * at idle; the first wait is short, because a request arriving into an empty engine + * should not pay for the queue having been empty. */ + step_batch_.store(nullptr, std::memory_order_release); + drain_completed(); + sched_.publish(/*idle=*/true); + /* Nothing could run because what can run is waiting on the encoder: go round now. */ + if (sched_.encodes_pending()) { idle = 0; continue; } + /* A RELEASE THE LAST STEP DEFERRED AND NO COMMIT WILL NOW MAKE. A request cancelled + * while a drafter pass was being built keeps its blocks until the passes that name + * them have run (Scheduler::cancel), and commit() is where that normally lands -- an + * idle engine runs none, and blocks held by a cancelled request can be exactly what + * keep the next one from being admitted. The streams are drained first so no pass + * still in flight can be reading those blocks when they are handed on. */ + if (sched_.has_deferred()) { + for (auto& rk : ranks_) (void)rad_stream_sync(rk->ctx.stream()); + sched_.release_deferred(); + } + tier_tick(); + loan_tick(/*idle=*/true); + /* RADIANCE_DEBUG_IDLE_SCRUB -- a DIAGNOSTIC, not a fix, and the one question it + * answers is whether request N+1 differs from request N because of bytes request N + * left behind. The engine is idle here: no sequence is live, so nothing in either the + * KV pool or the activation arena is owned by anybody and zeroing all of it is safe. + * + * `kv` zeroes every KV group's pool -- paged blocks included, which are NOT cleared on + * grab (see StateClear in mem/kv.h). `arena` zeroes the buffer plan, which is where + * every RAD_BUF_PERSIST buffer lives -- `qsa_tail` and `mtp_qsa_tail` among them, and + * those are indexed by SEQUENCE SLOT and are cleared for a new sequence by nothing at + * all. `all` does both. + * + * If the difference survives the scrub, bytes left behind are not its cause. */ + if (scrub_ && idle == 0) { + for (auto& rk : ranks_) { + if (scrub_ & 1) + for (const KVGroupPlan& p : rk->kv.plans()) { + if (!p.base || p.pool_bytes <= 0) continue; + /* `name`, or `name@L`, or `name@LO-HI` -- a LAYER RANGE, because the + * groups are bundles and the layers in one bundle are not one thing. + * kv_attn carries the twelve trunk QSA layers AND the MTP draft head's + * at index 12, and "which of those" is the question the group level + * cannot answer. The pool is layer-major, so a layer is a contiguous + * `layer_stride()` at `base + L * layer_stride()`. */ + int64_t lo = 0, hi = p.n_layers - 1; + if (!scrub_groups_.empty()) { + const size_t at = scrub_groups_.find("," + p.name + "@"); + const size_t plain = scrub_groups_.find("," + p.name + ","); + if (at == std::string::npos && plain == std::string::npos) continue; + if (at != std::string::npos) { + const char* q = scrub_groups_.c_str() + at + p.name.size() + 2; + lo = hi = std::strtoll(q, nullptr, 10); + if (const char* d = std::strchr(q, '-')) + if (d < std::strchr(q, ',')) hi = std::strtoll(d + 1, nullptr, 10); + } + } + if (lo < 0) lo = 0; + if (hi > p.n_layers - 1) hi = p.n_layers - 1; + const int64_t stride = p.layer_stride(); + for (int64_t L = lo; L <= hi && stride > 0; ++L) + rad_memset_async((char*)p.base + L * stride, 0, stride, + rk->ctx.stream()); + } + /* The arena's lent top holds expert weights, so it comes back first. */ + if ((scrub_ & 2) && !rk->arena_lent.empty()) { + (void)rad_dev_set(rk->device); + (void)rk->mover.reclaim(Mover::kLendArena, 0, &rk->heat); + (void)rk->ctx.set_level(0); + arena_floor_ = cfg_.max_tok; + arena_floor_ns_ = rad_mono_ns(); + } + if (scrub_ & 2) + if (void* ab = rk->ctx.arena_base()) + if (const int64_t n = rk->ctx.arena_bytes(); n > 0) + rad_memset_async(ab, 0, n, rk->ctx.stream()); + rad_stream_sync(rk->ctx.stream()); + } + } + if (idle < 200) ++idle; + std::this_thread::sleep_for(std::chrono::microseconds(idle * 5)); + continue; + } + idle = 0; + if (t_on) phase_mark(PH_PLAN); + + /* A FRESHLY ASSIGNED RECURRENT SLOT IS ZEROED BEFORE THE STEP THAT READS IT. The manager + * recorded the grab and cannot do the write itself (StateClear in core/mem/kv.h); this is + * the first moment a stream exists and the last before the ranks are released, and it is + * off the hot path -- the list is empty on every step but a sequence's first. Every rank + * clears its own pool: the slot number is the scheduler's, the memory is the rank's. */ + for (const StateClear& c : ranks_[0]->kv.state_clears()) { + const KVGroupPlan* gp = ranks_[0]->kv.plan(c.group); + if (!gp || !gp->stateful()) continue; + const int64_t bytes = gp->layer_bytes_per_state(); + for (auto& rk : ranks_) + for (int64_t l = 0; l < gp->n_layers; ++l) + if (void* p = rk->kv.state_ptr(c.group, (int32_t)l, c.slot)) + rad_memset_async(p, 0, bytes, rk->ctx.stream()); + } + ranks_[0]->kv.clear_state_clears(); + + /* Which entries want a logits row, in the order BatchBuilder wrote out_ids: entries with + * produces_token, 1 + n_spec rows each. Everything downstream indexes off this, because + * row index and sequence index are NOT the same -- a prefill chunk in the middle of a long + * prompt produces no row at all. */ + const StepPlan& plan = sched_.plan(); + /* ONE ENTRY PER REQUEST, and the row counter is separate. Sampler::build_step expands + * each request into 1 + n_draft rows of its own -- that is where the per-position RNG + * coordinate comes from -- so pushing the request once per row here would stage (1+n)^2 + * rows and overrun the arena whenever a drafter sets Request::n_draft. `first_row` is what + * indexes the sampled tokens, so it counts rows and not requests. */ + so.reqs.clear(); + so.first_row.assign(plan.e.size(), -1); + int32_t logit_row = 0; + for (size_t i = 0; i < plan.e.size(); ++i) { + const StepEntry& e = plan.e[i]; + if (!e.produces_token) continue; + so.first_row[i] = logit_row; + logit_row += 1 + e.n_spec; + so.reqs.push_back(const_cast(e.req)); + } + so.n_rows = logit_row; + + /* THE SAMPLER'S HOST WORK, staged by this lambda either in front of the ranks or -- by + * default, see build_mu_ in engine.h -- underneath them. It touches request state and the + * host grammar automata, which no rank thread reaches: every upload in the sampler chain + * is issued by Sampler::run, after the gate this fills. + * + * CANCELLATIONS ARE COLLECTED, NOT APPLIED. A cancel touches scheduler state that the + * rank threads are reading through batch_for() while this runs; they are applied after the + * join, ahead of collect_step. */ + auto stage_sampler = [&]() -> int { + if (!so.reqs.empty()) { + /* PER-REQUEST SAMPLER STATE IS BUILT HERE, ON FIRST SIGHT. A grammar arrives compiled + * from admission and is only positioned here; a DRY sequence-breaker set is resolved + * against the vocabulary once. Both belong off the step path, and this is the first + * point on the scheduler thread where a request is known to be about to sample. + * Without it `seqs_` stays permanently empty, and `grammar` and + * `dry_sequence_breakers` are accepted by the API, carried through the request, and + * then quietly do nothing -- the one outcome core/server/oai.h's header forbids. + * + * EVERY RANK, because every rank masks its own vocabulary shard from its own automaton. + * + * A FAILURE HERE FAILS THE REQUEST, NOT THE ENGINE. A grammar this machine cannot run + * (left recursion, say) is a bad request, and taking the server down with it would let + * one caller end every other caller's generation. The server compiles at admission so + * this should already be unreachable; if it is reached, the request is cancelled with + * the reason in the log and the rest of the step goes on. */ + for (Request* rq : so.reqs) { + if (!rq) continue; + bool failed = false; + for (auto& rk : ranks_) { + if (rk->sampler.has_request(rq->id)) continue; + std::string err; + if (rk->sampler.begin_request(rq->id, rq->sp, &err) < 0) { + RAD_ERR("sampler: request %llu could not be started: %s; cancelling it", + (unsigned long long)rq->id, err.c_str()); + failed = true; + break; + } + } + if (failed) { + for (auto& rk : ranks_) rk->sampler.end_request(rq->id); + cancel.push_back(rq->id); + continue; + } + rq->speculation_fixed = ranks_[0]->sampler.speculation_fixed(rq->id); + } + if (t_on) phase_mark(PH_BEGIN); + for (auto& rk : ranks_) { + const int s = rk->sampler.build_step(so.reqs); + if (s < 0) { RAD_ERR("sampler build_step: %s", rad_strerror(s)); return s; } + /* A request the sampler could not serve is cancelled, not returned: the step goes + * on for everyone else in the batch. */ + for (uint64_t id : rk->sampler.take_failed()) cancel.push_back(id); + } + if (t_on) phase_mark(PH_BUILD); + } + return RAD_OK; + }; + + cancel.clear(); + int bst = RAD_OK; + + /* ONE LINE PER STEP, on request. The shape of a step -- its phase, how many sequences, + * how many tokens each, and what context each is continuing from -- is the first thing + * anyone debugging a wrong answer needs, and no other log line carries it: -v prints the + * tokenizer and the loader and nothing about the steps that follow. Off by + * default because it is a line per step and decode steps are thousands of them. */ + if (std::getenv("RADIANCE_LOG_STEPS")) { + std::string s = fmt("step %d %s n_seq=%lld n_tok=%lld", b->step, + b->phase == RAD_PHASE_PREFILL ? "prefill" : + b->phase == RAD_PHASE_DECODE ? "decode" : "MIXED", + (long long)b->n_seq, (long long)b->n_tok); + for (int i = 0; i < b->n_seq && i < 8; ++i) + s += fmt(" [%d] slot=%d q=%d ctx=%d", i, plan.e[(size_t)i].slot, + plan.e[(size_t)i].n_tokens, plan.e[(size_t)i].ctx_len); + RAD_INFO("%s", s.c_str()); + } + + /* THE RECURRENT HALF OF A PREFIX HIT, restored BEFORE the step that reads it. The adopted + * blocks carry the attention layers; this carries the recurrent ones. Enqueued on each + * rank's own stream ahead of the release, so it is ordered before the kernels without a + * synchronisation -- the same way collect_step's readback is ordered after them. + * + * UNDER THE SCHEDULER'S LOCK, because it reads the sequence table and backs checkpoint + * slots in rank 0's manager, which an HTTP thread's cancel mutates under that lock. Taken + * only on a step that has a restore in it. */ + bool any_restore = false; + for (const StepEntry& e : plan.e) if (e.ckpt_restore >= 0) { any_restore = true; break; } + if (any_restore) { + const int rs = sched_.locked([&]() -> int { + for (const StepEntry& e : plan.e) { + if (e.ckpt_restore < 0) continue; + if (!state_slots_of(e.seq, &ckpt_slots_)) continue; + for (auto& rk : ranks_) { + /* THIS RANK'S DEVICE, BECAUSE THE COPY MAY HAVE TO MAP MEMORY FIRST. A + * checkpoint slot is backed by the rank that writes it + * (KVManager::back_checkpoint), and a commit must land on the card whose pool + * it backs -- a commit on card 0 mapped into rank 1's range succeeds, grants + * access to the wrong card, and rank 1's next kernel faults on a page that is + * present somewhere else. */ + if (ranks_.size() > 1) (void)rad_dev_set(rk->device); + const int s = rk->kv.checkpoint_restore(ckpt_slots_.data(), + (int)ckpt_slots_.size(), + e.ckpt_restore, rk->ctx.stream()); + if (s < 0) { + RAD_ERR("could not restore sequence %llu from checkpoint slot %d: %s", + (unsigned long long)e.seq, (int)e.ckpt_restore, + rad_strerror(s)); + if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device); + return s; + } + } + if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device); + } + return RAD_OK; + }); + if (rs < 0) return fail_loop(rs); + } + + /* WHICH SIDE OF THE BARRIER THE TIME IS ON. Everything above this point is scheduler-thread + * work the device is idle for -- build_step, the grammar, the plan; everything between the + * two arrivals is the ranks ENQUEUEING, not running. A step that is slow for a host reason + * and one that is slow for a device reason look identical in total step time; this split + * is the only thing that tells them apart. */ + if (t_on) phase_mark(PH_PRE); + + if (!issued) { + /* The gate is reset while every rank is still parked at the release, so there is no + * window in which one can read a stale ready flag from the step before. */ + { + std::lock_guard lk(build_mu_); + build_ready_ = false; + build_status_ = RAD_OK; + } + if (const int ps = prepare_release(b); ps < 0) return fail_loop(ps); + issue_what_.store(kIssueAll, std::memory_order_release); + step_batch_.store(b, std::memory_order_release); + barrier_->arrive_and_wait(); /* release the ranks */ + { + /* HERE IS THE POINT OF ALL OF IT: the ranks are enqueueing the forward pass and + * the device is running it while this thread stages the sampler and walks the + * grammar. */ + bst = stage_sampler(); + { + std::lock_guard lk(build_mu_); + build_ready_ = true; + build_status_ = bst; + } + build_cv_.notify_all(); + } + barrier_->arrive_and_wait(); /* wait for them */ + } else { + /* THE FORWARD PASS IS ALREADY ON THE CARD, issued behind the last step, and that step + * has now committed -- so the sampler is staged from exactly the state it would have + * been, and the ranks put the chain behind the pass while the card is still in it. */ + bst = stage_sampler(); + { + std::lock_guard lk(build_mu_); + build_ready_ = true; + build_status_ = bst; + } + issue_what_.store(kIssueSampler, std::memory_order_release); + step_batch_.store(b, std::memory_order_release); + barrier_->arrive_and_wait(); + barrier_->arrive_and_wait(); + } + if (t_on) phase_mark(PH_RANKS); + + /* Deferred out of the staging, where the rank threads were reading the scheduler. */ + for (uint64_t id : cancel) sched_.cancel(id); + cancel.clear(); + + /* A staging failure is discovered with the ranks already released, so they have to be + * let go before this thread leaves -- the gate above carries the failure, so they have + * skipped the sampler and arrived at the join. */ + if (bst < 0) return fail_loop(bst); + + int st = step_status_.load(std::memory_order_acquire); + if (st < 0) { + /* A device fault is not recoverable in process, and we do not serve from a wedged + * queue (spec §17): stop, release anyone parked on the barrier, and return. */ + RAD_ERR("step %d failed: %s -- the engine cannot continue", b->step, rad_strerror(st)); + return fail_loop(st); + } + + /* AND THE SNAPSHOT, taken AFTER the step that produced the state. The chunker split this + * chunk so its last token IS the checkpoint position, so what copy 0 holds now is exactly + * the state at that position. It is issued before collect_step's readback synchronises, so + * the copy overlaps whatever is left of the step rather than adding to it. + * + * Under the scheduler's lock for the reason the restore above is, and only on a step that + * writes a checkpoint. */ + bool any_save = false; + for (const StepEntry& e : plan.e) + if (e.ckpt_slot >= 0 && e.ckpt_tok >= 0) { any_save = true; break; } + if (any_save) { + const int ss = sched_.locked([&]() -> int { + for (const StepEntry& e : plan.e) { + if (e.ckpt_slot < 0 || e.ckpt_tok < 0) continue; + if (!state_slots_of(e.seq, &ckpt_slots_)) continue; + for (auto& rk : ranks_) { + /* THIS RANK'S DEVICE, for the reason the restore gives: the copy may have to + * back the slot first, and the pages belong on this rank's card. */ + if (ranks_.size() > 1) (void)rad_dev_set(rk->device); + const int s = rk->kv.checkpoint_save(ckpt_slots_.data(), + (int)ckpt_slots_.size(), + e.ckpt_slot, rk->ctx.stream()); + if (s < 0) { + RAD_ERR("rank %d could not snapshot sequence %llu into checkpoint slot " + "%d: %s", rk->index, (unsigned long long)e.seq, + (int)e.ckpt_slot, rad_strerror(s)); + if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device); + return s; + } + } + if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device); + } + return RAD_OK; + }); + if (ss < 0) return fail_loop(ss); + } + + if (t_on) phase_mark(PH_SAVE); + /* A SERIAL DRAFTER'S PASSES GO IN BEHIND THE STEP BEFORE ANYTHING WAITS FOR IT. The card + * works out the acceptance itself and every pass reads it from there (sched/advance.h), + * so the host has nothing to wait for until the step's last pass -- and the one wait below + * then covers the whole step. */ + st = issue_serial_drafter(b->step, b, so); + if (st < 0) return fail_loop(st); + st = mark_step_end(b, so); + if (st < 0) return fail_loop(st); + /* AND THE NEXT STEP'S FORWARD PASS, BEHIND ALL OF IT, before this step is read back. Its + * rows continue where the card's acceptance leaves them and verify what the drafter just + * proposed; its sampler waits for this step's commit, which it is staged from. So the card + * goes from this step's last pass straight into the next step's first, and the host's + * wait, commit and staging all happen while it runs. */ + st = issue_ahead(&ahead); + if (st < 0) return fail_loop(st); + st = collect_step(b, so); + if (t_on) phase_mark(PH_COLLECT); + if (st < 0) return fail_loop(st); + if (cfg_.kld()) { + st = score_rows(b, so); + if (st < 0) return fail_loop(st); + } + + /* The buffer probe, after the trunk step: RADIANCE_DUMP_BUF names the buffers to print + * and trace level gates it, because dumping reads device memory back to the host and no + * serving run should pay for that. The drafters dump their own buffers after their own + * passes, for the reason engine_priv.h gives. */ + if ((int)log_level() >= (int)Log::Trace) + dump_buffers(ranks_[0]->ctx, b->step, std::getenv("RADIANCE_DUMP_BUF")); + + /* --profile-ops PRINTS WHILE THE SERVER IS STILL RUNNING rather than once at the end. + * The counters are cumulative, so each dump is the run so far and the us/call column is + * an average over it; a reader wants the table during the run it is diagnosing. + * + * Every 32 steps by default, and RADIANCE_PROFILE_EVERY moves it. Per-op timing restores + * a synchronisation around every launch -- over a thousand of them a step on a large + * model -- so a profiled step is several times slower and 32 of them is minutes. Often + * enough to read, rare enough not to bury the log. */ + static const int prof_every = [] { + const char* v = std::getenv("RADIANCE_PROFILE_EVERY"); + const int n = (v && *v) ? (int)std::strtol(v, nullptr, 10) : 32; + return n > 0 ? n : 32; + }(); + if (cfg_.profile_ops && b->step > 0 && (b->step % prof_every) == 0) + for (auto& rk : ranks_) rk->ctx.dump_profile(); + + /* One line a step at -vv. It is the only view of the loop there is: everything else the + * engine prints happens at startup, so a request that goes in and never comes out looks + * exactly like a request that never arrived. */ + RAD_TRACE("step %d: %lld tok / %lld seq, %lld logit row(s) -> tokens %s", b->step, + (long long)b->n_tok, (long long)b->n_seq, (long long)b->n_out, + so.token.empty() ? "(none)" : fmt("%d%s", so.token[0], + so.token.size() > 1 ? " ..." : "").c_str()); + /* AND WHAT WENT IN. Every op in the forward pass can agree with the reference and the + * answer still be wrong if the ids are not the ids the model was trained on; the two look + * identical from the logits, which is why this is printed beside them rather than left to + * be inferred. Bounded at 32 because a 2048-token prefill's ids are not a log line. */ + if ((int)log_level() >= (int)Log::Trace && b->n_tok > 0 && b->token_ids) { + std::string ids; + const int64_t n = std::min(b->n_tok, 32); + std::vector host((size_t)n); + if (rad_memcpy_async(host.data(), b->token_ids, n * 4, ranks_[0]->ctx.stream()) >= 0 && + rad_stream_sync(ranks_[0]->ctx.stream()) >= 0) { + for (int64_t i = 0; i < n; ++i) ids += fmt("%s%d", i ? " " : "", host[(size_t)i]); + RAD_TRACE("step %d in: [%s%s]", b->step, ids.c_str(), + b->n_tok > n ? " ..." : ""); + } + } + + Scheduler::StepResult res{}; + res.n_seq = (int)plan.e.size(); + res.n_accepted = so.accepted.data(); + res.token = so.token.data(); + res.eos = so.eos.data(); + st = sched_.commit(res); + if (t_on) phase_mark(PH_COMMIT); + if (st < 0) { RAD_ERR("commit: %s", rad_strerror(st)); return fail_loop(st); } + + /* THE DRAFTER FOR THE NEXT STEP. A block drafter runs here, because its passes are staged + * from the committed sequence; a serial one already ran on the card behind the step, and + * what is left is to check its acceptance against the host's and publish its proposals. + * + * ONE SWITCH ON A DECLARED SHAPE, not on a model. Both drivers return RAD_OK immediately + * when the declared kind is not theirs, so a program with no drafter costs a compare. */ + st = drafter_.kind == RAD_DRAFT_BLOCK ? run_block_drafter(b->step) + : finish_serial_drafter(so); + if (st < 0) return fail_loop(st); + /* AND NOW THE STEP IS OVER. The draft rounds above are forward passes and they belong to + * the step that paid for them; charging the step at commit would leave them in the gap + * between one iteration and the next, which nothing measures. Scheduler::step_finished + * says what that costs. */ + sched_.step_finished(); + tier_tick(); + loan_tick(/*idle=*/false); + arena_tick(rad_mono_ns()); + drain_completed(); + sched_.publish(/*idle=*/false); + + /* ONE LINE EVERY 128 STEPS, and it adds up to the step. `ranks` is the enqueue, not the + * execution: the device work is waited for in `collect`, which is the only host + * synchronisation a step has, so `collect` is where device time shows up and any host + * cost the ranks could have been running under is time `collect` did not get to hide. */ + if (t_on) { + phase_mark(PH_DRAFT); + if (++phase_n_ == 128) { + double tot = 0; + for (int i = 0; i < PH_N; ++i) tot += phase_us_[i]; + RAD_DEBUG("step %s: %.2f ms = plan %.2f begin %.2f build %.2f pre %.2f " + "ranks %.2f save %.2f collect %.2f commit %.2f draft %.2f (mean/128)", + b->phase == RAD_PHASE_DECODE ? "decode" : "other", tot / 128000.0, + phase_us_[PH_PLAN] / 128000.0, phase_us_[PH_BEGIN] / 128000.0, + phase_us_[PH_BUILD] / 128000.0, phase_us_[PH_PRE] / 128000.0, + phase_us_[PH_RANKS] / 128000.0, phase_us_[PH_SAVE] / 128000.0, + phase_us_[PH_COLLECT] / 128000.0, phase_us_[PH_COMMIT] / 128000.0, + phase_us_[PH_DRAFT] / 128000.0); + for (int i = 0; i < PH_N; ++i) phase_us_[i] = 0; + phase_n_ = 0; + } + } + } + return RAD_OK; +} + +/* THE SAMPLED IDS ON THEIR WAY TO THE HOST: a copy into pinned memory behind the sampler, and + * nothing waited for. Issued by the serial drafter before its passes -- a head that samples + * through the sampler's own buffer overwrites the ids -- and otherwise right before the wait. */ +int Engine::collect_issue(const RadBatch* b, StepOut& so) { + so.rb = nullptr; + so.lg.clear(); + if (so.n_rows <= 0) return RAD_OK; + Rank& r0 = *ranks_[0]; + void* src = r0.ctx.buf_ptr(r0.tok_buf); + if (!src) { + RAD_ERR("the sampler's token buffer has no address -- it was declared but never planned"); + return RAD_E_STATE; + } + so.rb = readback_.reserve(so.n_rows); + if (!so.rb) return RAD_E_NOMEM; + RAD_TRY(rad_memcpy_async(so.rb, src, (int64_t)so.n_rows * 4, r0.ctx.stream())); + + /* THE FIRST FEW LOGITS, at -vv. There is no other window into the forward pass: rad-kbench can + * falsify one op against the oracle but nothing compares a whole layer, so when every op agrees + * and the model still answers the same token to every prompt, the question "are the logits even + * a function of the input" has no cheaper answer than looking. One copy on a path that already + * synchronises, and only when the operator asked for trace. */ + const int64_t nv = meta_.n_vocab; + if ((int)log_level() >= (int)Log::Trace && nv > 0) { + void* lp = r0.ctx.buf_ptr(r0.program.logits_buf); + if (lp) { + so.lg.resize((size_t)nv); + rad_memcpy_async(so.lg.data(), lp, nv * 4, r0.ctx.stream()); + } + } + return RAD_OK; +} + +int Engine::mark_step_end(const RadBatch* b, StepOut& so) { + if (so.n_rows > 0 && !so.rb) RAD_TRY(collect_issue(b, so)); + return rad_event_record(step_end_, ranks_[0]->ctx.stream()); +} + +/* Wait for the sampled ids and turn them into the three per-sequence arrays the scheduler wants. + * This is the ONE host synchronisation on the step path: the host needs the tokens to commit them + * and to stream them. Everything else in a step is enqueued and never waited on (spec §5.4). */ +int Engine::collect_step(const RadBatch* b, StepOut& so) { + const StepPlan& plan = sched_.plan(); + so.token.assign(plan.e.size(), 0); + so.accepted.assign(plan.e.size(), 0); + so.eos.assign(plan.e.size(), 0); + if (so.n_rows <= 0) return RAD_OK; + + so.rows.resize((size_t)so.n_rows); + /* The step's one wait. For the step's end and not for the stream: a step issued ahead is + * behind it, and the host's commit and staging are what that step runs over. */ + RAD_TRY(rad_event_sync(step_end_)); + std::memcpy(so.rows.data(), so.rb, (size_t)so.n_rows * sizeof(int32_t)); + so.rb = nullptr; + const std::vector& lg = so.lg; + const int64_t nv = meta_.n_vocab; + if (!lg.empty()) { + /* The top three of the first sampled row. A sampler that answers the same token to every + * prompt is either reading a distribution with a fixed spike in it or not reading the + * distribution at all, and the two look identical from outside. */ + int64_t i0 = 0, i1 = 0, i2 = 0; + for (int64_t i = 1; i < nv; ++i) { + if (lg[(size_t)i] > lg[(size_t)i0]) { i2 = i1; i1 = i0; i0 = i; } + else if (lg[(size_t)i] > lg[(size_t)i1]) { i2 = i1; i1 = i; } + else if (lg[(size_t)i] > lg[(size_t)i2]) { i2 = i; } + } + double sum = 0, amax = 0; + for (int64_t i = 0; i < nv; ++i) { sum += lg[(size_t)i]; amax = std::max(amax, (double)std::fabs(lg[(size_t)i])); } + RAD_TRACE("step %d logits: top %lld=%.4f %lld=%.4f %lld=%.4f mean %.4f amax %.4f", + b->step, (long long)i0, (double)lg[(size_t)i0], (long long)i1, + (double)lg[(size_t)i1], (long long)i2, (double)lg[(size_t)i2], + sum / (double)nv, amax); + } + + for (size_t i = 0; i < plan.e.size(); ++i) { + if (so.first_row[i] < 0) continue; + const StepEntry& e = plan.e[i]; + + if (e.n_spec > 0) { + /* THE COMPARISON IS AGAINST THE TARGET'S OWN SAMPLED TOKEN, AND THAT IS EXACT AT ANY + * TEMPERATURE. It looks as though everything but temperature 0 has to be refused: a + * positive temperature needs rejection sampling, and rejection sampling needs the + * target's probability planes, which this path does not bring back. Both halves are + * true and the conclusion does not follow, because there is a third rule that needs + * no planes at all: + * + * accept draft[k] when it equals the token the target ITSELF drew at position k. + * + * That is exact because the sampler gives every verified position its own RNG + * coordinate -- `p.pos = n_out + k`, "its randomness is the same whether it arrived + * through speculation or one token at a time" (sampler.cpp). So y_k is the draw the + * target's own distribution specifies at that output position. The first emitted token + * is y_0 whether or not the draft agreed; every later one is conditioned on a prefix + * that was accepted only because it matched, so the conditioning is the one the target + * asked for. The emitted sequence is a draw from the target, not an approximation of + * one. + * + * IT IS NOT, HOWEVER, BYTE-IDENTICAL TO A NON-SPECULATIVE RUN ABOVE TEMPERATURE 0, and + * that is worth stating because the paragraph above sounds like it should be. The rule + * is exact given the same logits; the logits themselves are shape-dependent, because a + * verify step computes 1 + n_spec rows where a decode step computes one and split-K + * picks its count from M. At temperature 0 that survives the argmax and the text + * matches exactly. Above it a sampled pick near a CDF boundary can land the other way, + * so spec and non-spec agree on most prompts and not all -- deterministic and + * reproducible either way, and a property of the GEMMs rather than of acceptance. + * + * It accepts less often than optimal rejection sampling -- P(y == x) rather than + * min(1, p/q) -- and that is the whole price. Refusing instead would cost the request + * every drafted token AND take the step down with it, failing every other request + * batched alongside, for the common case of a client that left temperature at 1. + * + * `so.rows` is the sampler's OUTPUT, which is the sampled token -- at temperature 0 + * that is the argmax, which is why the greedy-acceptance name still fits. */ + if (!e.req) continue; + int32_t out[RAD_SCHED_MAX_SPEC + 1] = { 0 }; + int32_t acc = 0; + RAD_TRY(accept_greedy(e.draft, e.n_spec, &so.rows[(size_t)so.first_row[i]], out, &acc)); + + /* THE TURN CAN END IN THE MIDDLE OF AN ACCEPTED RUN, and stopping only on the last + * token of it is how the engine generates past the end of a turn. accept_greedy stops + * at the first DISAGREEMENT, not at the first end-of-generation token -- and a drafter + * that correctly predicts the model is about to stop AGREES about the stop token, so + * the run continues past it. Everything after it is the model writing the next turn: + * `<|im_end|><|im_start|>user ...` decoded, with the control tokens rendering as + * nothing, which reads as a model that rambles rather than as a bug in the accept + * path. Truncating here rather than in the scheduler keeps one definition of "how far + * did this step get" -- `accepted` and `token` are what the KV rollback, the conv + * cursor and the emitted text are all derived from. */ + for (int32_t j = 0; j <= acc; ++j) { + if (vocab_ && vocab_->is_eog(out[j])) { acc = j; break; } + } + + so.accepted[i] = acc; + so.token[i] = out[acc]; + so.eos[i] = vocab_ && vocab_->is_eog(so.token[i]) ? 1 : 0; + /* EVERY token that leaves, in order: the grammar's state has to advance over the + * accepted drafts too, or the next step's mask is built n_accepted tokens behind. + * Bounded by the truncated `acc`, so it sees exactly the tokens the client does. */ + if (e.req) + for (auto& rk : ranks_) + for (int32_t j = 0; j <= acc; ++j) { + const int as = rk->sampler.accept_token(e.req->id, out[j]); + /* A parse that outgrew the grammar's bounds is the request's, not a + * defect: the backend is dead and the request fails at its next mask. */ + if (as == RAD_E_FULL || as == RAD_E_NOMEM) + RAD_WARN("engine: req %llu: its grammar's parse outgrew the bounds a " + "grammar may use at token %d; the request fails at its next " + "step", (unsigned long long)e.req->id, out[j]); + else if (as < 0) + RAD_ERR("engine: req %llu emitted token %d (position %d of %d " + "accepted, n_spec %d) that its grammar forbids -- the mask and " + "the pick disagree. The same condition on the speculative WALK " + "is expected and is a debug line in gbnf.cpp; only this one, " + "on an ACCEPTED token, is a defect.", + (unsigned long long)e.req->id, out[j], j, acc, e.n_spec); + } + continue; + } + so.token[i] = so.rows[(size_t)so.first_row[i]]; + so.eos[i] = vocab_ && vocab_->is_eog(so.token[i]) ? 1 : 0; + /* The grammar must see the token it just emitted, or the next step's mask is built from a + * state one token behind the sequence. EVERY rank, not just rank 0: each rank builds the + * mask for its own vocabulary shard from its own automaton, so a rank whose grammar did + * not advance masks the next step against the previous token's state. */ + if (e.req) + for (auto& rk : ranks_) rk->sampler.accept_token(e.req->id, so.token[i]); + } + + /* WHETHER EACH REQUEST MAY BE SPECULATED ON NEXT STEP, decided HERE and not in the block that + * starts requests, because the answer changes exactly where this loop just changed it: a lazy + * grammar becomes constraining inside accept_token, above. Deciding it any later means the + * scheduler sizes the next step from a stale answer and hands a constrained request a draft + * the sampler will then refuse. */ + for (size_t i = 0; i < plan.e.size(); ++i) { + const StepEntry& e = plan.e[i]; + if (!e.req) continue; + Request* r = const_cast(e.req); + r->may_speculate = ranks_[0]->sampler.allows_speculation(r->id); + } + return RAD_OK; +} + +/* Requests that reached a terminal state. The server drains the text through the sink and calls + * reap(), which is what finally lets the Request go -- only the HTTP thread knows when it has + * stopped writing into it. All this does is drop the sampler's per-request host state. */ +/* ------------------------------------------------------------------ the idle-tier tick */ +/* EVERY ITERATION, ON BOTH PATHS. A copy to host memory is asynchronous and reported when its + * event has signalled, so the tick that collects it is simply the first one after it landed; the + * next copy is handed out on the same tick. Tying either to a slower clock would only delay the + * moment a finished conversation's VRAM can be given up. The disk half runs once a second -- its + * thresholds are measured in minutes -- and at once when the host tier has refused a copy for + * want of room, since that copy is waiting on it. + * + * THE SCHEDULER'S LOCK IS HELD FOR THE BOOKKEEPING ONLY. Planning a batch and reporting one touch + * rank 0's manager, the prefix cache and -- through the tiers' drop sinks -- the index an HTTP + * thread's cancel also changes; issuing the transfers and polling them touch none of that, and a + * transfer's records are pending the whole time it is out, which is what keeps everything else off + * them without a lock. */ +/* THE ONE PLACE THE BOUNDARY BETWEEN THE KV CACHE AND THE EXPERT SLAB MOVES. + * + * The budget divides the card once, at startup: a KV block nothing holds is VRAM no expert can + * use, and an expert that does not fit is read across the link on the critical path of every step + * that routes to it. The cache therefore LENDS what it is not holding, at the addresses it already + * owns -- nothing is allocated, mapped or released, so the loan moves with no driver call and the + * card's free VRAM is the same before and after. There is exactly one lender: two owners with two + * opinions about how much is spare is the same memory in two pools. + * + * THE ORDER IS THE WHOLE SAFETY ARGUMENT: + * + * 1. the cache says what it can spare -- above the highest block it holds, less its buffer; + * 2. the cache's mark is set from the larger of that and what every rank's slab ACTUALLY + * HOLDS -- a shrink is met as units leave the slots, and reading the offer instead would put + * the same blocks in both pools; + * 3. only then are the slabs told the offer, which they fill into or drain out of. + * + * A request that cannot wait for a shrink does not wait for one: the cache calls back into every + * slab and has the blocks at once (KVManager::set_reclaim, installed in start()). */ +void Engine::loan_tick(bool idle) { + if (!lending_) return; + const uint64_t now = rad_mono_ns(); + if (now - loan_last_ns_ < 100000000ull) return; /* 100 ms */ + loan_last_ns_ = now; + + /* UNDER THE SCHEDULER'S LOCK: the loan moves rank 0's live mark and free count, which an HTTP + * thread's cancel changes under that lock when it frees a sequence, and /metrics reads them + * under it. */ + const auto lk = sched_.hold(); + Rank& lead = *ranks_[0]; + + /* A FINISHED CONVERSATION'S VRAM GOES FIRST, when the slabs have a use for it. An entry whose + * host copy has landed loses nothing by leaving -- a return restores it from host memory -- + * so while any slab has slots the loan does not yet cover, every such entry is released and + * its blocks count toward what the cache can spare below. Past that point the VRAM would sit + * empty in the slab, and the entries stay where a return finds them for free. */ + int64_t ceiling = 0; + for (auto& r : ranks_) ceiling = std::max(ceiling, r->mover.loan_ceiling(Mover::kLendKV)); + if (lead.kv.loan_tokens() < ceiling) (void)lead.prefix.drop_clean(); + + /* WHAT THE CACHE CAN DO WITHOUT, AND WHAT THE SLABS STILL OCCUPY. A loan grows as soon as the + * cache can spare it -- the slots are filled on the next dispatch or the next idle tick -- but + * only by at least a prefill chunk, so a cache breathing by a few blocks does not have its + * boundary chase it. It shrinks at once, and the cache gets the blocks back as the slabs + * leave them: the cache's mark is never above the deepest slot any rank's slab still holds. */ + const int64_t cur = lead.kv.loan_tokens(); + const int64_t spare = lead.kv.spare_tokens(); + const int64_t chunk = std::max(cfg_.max_tok, 1); + int64_t offer = cur; + if (spare < cur || spare >= cur + chunk) offer = spare; + int64_t held = 0; + for (auto& r : ranks_) held = std::max(held, r->mover.loan_held(Mover::kLendKV)); + + /* THE CACHE FIRST WHEN THE LOAN GROWS, THE SLABS FIRST WHEN IT SHRINKS. Either way no block is + * both handed out by the cache and a slot in a slab: a growing loan is lent only once the + * cache has stopped handing those blocks out, and a shrinking one is returned to the cache + * only as the slabs leave it. */ + if (lead.kv.set_loan(std::max(offer, held)) < 0) { + RAD_ERR("kv loan: the cache refused a loan of %lld tokens it said it could spare; lending " + "stops", (long long)std::max(offer, held)); + lending_ = false; + return; + } + for (size_t i = 1; i < ranks_.size(); ++i) (void)ranks_[i]->kv.follow(lead.kv); + for (auto& r : ranks_) { + if (rad_dev_set(r->device) < 0) continue; + (void)r->mover.set_loan(Mover::kLendKV, offer); + if (idle) { + const int st = r->mover.idle_tick(&r->heat); + if (st < 0) RAD_WARN("rank %d: filling the lent slots while idle: %s", r->index, + rad_strerror(st)); + } + } + (void)rad_dev_set(ranks_[0]->device); +} + +/* ------------------------------------------------------------------ the arena's level */ +/* WHICH LEVEL THE STEP RUNS AT, AND WHAT THE SLAB MAY KEEP OF THE ARENA WHILE IT DOES. + * + * The rows a step puts through the arena are its tokens and, after it, the drafter's passes -- + * at most one row per drafted position of every sequence. The smallest level serving that many is + * the one the step runs at; a step larger than every level runs at the full plan, which lends + * nothing. + * + * A LEVEL THAT NEEDS MORE THAN THE SLAB LEFT IT TAKES IT BACK BEFORE THE STEP, synchronously: the + * units in the slots it needs go back to their host copies, which is a change of address and not + * a copy, and both streams that can read a slot are drained before this returns. The first chunk + * of a prefill pays that once; the chunks after it find the memory already theirs, because the + * loan does not grow again until the steps have been small for a while (arena_tick). */ +int Engine::arena_step(const RadBatch* b) { + if (arena_rows_.size() <= 1 || !b) return RAD_OK; + /* AN ENCODER PASS TAKES THE FULL PLAN: its activations are sized by the pass, not by a step's + * rows, and only the full plan holds them (a plugin declares them small under shape_probe). */ + const int64_t need = b->enc ? INT64_MAX : std::max( + b->n_tok, (int64_t)b->n_seq * (1 + std::max(cfg_.n_spec, 0))); + int level = 0; + for (size_t k = 1; k < arena_rows_.size(); ++k) + if (arena_rows_[k] >= need && (level == 0 || arena_rows_[k] < arena_rows_[(size_t)level])) + level = (int)k; + const uint64_t now = rad_mono_ns(); + arena_last_ = arena_rows_[(size_t)level]; + if (arena_last_ >= arena_floor_) { arena_floor_ = arena_last_; arena_floor_ns_ = now; } + for (auto& r : ranks_) { + const int64_t allow = r->arena_lent[(size_t)level]; + if (r->mover.loan(Mover::kLendArena) > allow || + r->mover.loan_held(Mover::kLendArena) > allow) { + RAD_TRY(rad_dev_set(r->device)); + const int st = r->mover.reclaim(Mover::kLendArena, allow, &r->heat); + if (st < 0) { + RAD_ERR("rank %d: taking the arena back from the expert slab for a %lld-token step: " + "%s", r->index, (long long)b->n_tok, rad_strerror(st)); + return st; + } + } + RAD_TRY(r->ctx.set_level(level)); + /* The full plan lends nothing, so its top -- the staging region -- is the step's. */ + r->stager.set_full_arena(level == 0); + } + if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device); + return RAD_OK; +} + +/* THE LOAN GROWS ONLY ONCE THE LARGE STEPS HAVE STOPPED. A prefill is a run of chunks with decode + * steps between them, and lending the arena out after every chunk would refill the slab across + * the link and recall it at the next one. So the floor -- the largest step seen -- holds for two + * seconds after it was last reached, and only then falls to the size of the latest step. */ +void Engine::arena_tick(uint64_t now_ns) { + if (arena_rows_.size() <= 1) return; + if (arena_last_ < arena_floor_ && now_ns - arena_floor_ns_ > 2000000000ull) { + arena_floor_ = arena_last_; + arena_floor_ns_ = now_ns; + } + int level = 0; + for (size_t k = 1; k < arena_rows_.size(); ++k) + if (arena_rows_[k] >= arena_floor_ && + (level == 0 || arena_rows_[k] < arena_rows_[(size_t)level])) + level = (int)k; + for (auto& r : ranks_) { + const int64_t want = r->arena_lent[(size_t)level]; + if (want <= r->mover.loan(Mover::kLendArena)) continue; + if (rad_dev_set(r->device) < 0) continue; + (void)r->mover.set_loan(Mover::kLendArena, want); + } + if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device); +} + +void Engine::tier_tick() { + Rank& lead = *ranks_[0]; + if (!pump_ || !lead.tierx.enabled()) return; + TierPump& P = *pump_; + const uint64_t now = rad_mono_ns(); + + /* ---- a copy that has landed on every rank is reported ---------------------------------- */ + if (!P.copy.empty()) { + bool all = true, good = true; + for (size_t i = 0; i < ranks_.size(); ++i) { + if (P.copy_st[i] == 0) P.copy_st[i] = ranks_[i]->tierx.copy_state(); + if (P.copy_st[i] == 0) all = false; + else if (P.copy_st[i] < 0) good = false; + } + if (ranks_.size() > 1) (void)rad_dev_set(lead.device); + if (all) { + /* A COPY IS GOOD ONLY IF EVERY RANK'S SHARD LANDED. One that did not leaves an entry + * whose host copy is part this card's bytes and part stale, which is not restorable + * anywhere, so the whole batch is a failure and every slot goes back. */ + const std::vector ok(P.copy.size(), good ? 1 : 0); + { + const auto lk = sched_.hold(); + lead.tierx.report_pass(P.copy, ok, now); + } + P.copy.clear(); + } + } + + /* ---- reads off disk that have landed --------------------------------------------------- */ + /* THEIR REQUESTS GO NEXT STEP: the records are host records now, held for them, and the + * admission that asks again restores them out of host memory. */ + { + TierIO::Fetch f; + while (P.io.take_fetch(&f)) { + for (size_t i = 0; i < f.fences.size() && i < ranks_.size(); ++i) { + if (!f.fences[i]) continue; + (void)rad_dev_set(ranks_[i]->device); + rad_event_destroy(f.fences[i]); + } + if (ranks_.size() > 1) (void)rad_dev_set(lead.device); + const auto lk = sched_.hold(); + lead.tierx.report_pass(f.jobs, f.ok, now); + P.waiting.erase(std::remove(P.waiting.begin(), P.waiting.end(), f.tag), P.waiting.end()); + } + } + + /* ---- the disk batch the thread finished ------------------------------------------------ */ + { + std::vector jobs; + std::vector ok; + if (P.io.take(&jobs, &ok)) { + const auto lk = sched_.hold(); + lead.tierx.report_pass(jobs, ok, now); + } + } + + /* ---- the next copy ---------------------------------------------------------------------- */ + if (P.copy.empty() && lead.tiers.writeback_waiting()) { + { + const auto lk = sched_.hold(); + lead.tiers.plan_writeback(P.max_copy, &P.copy); + } + if (!P.copy.empty()) { + P.copy_st.assign(ranks_.size(), 0); + for (size_t i = 0; i < ranks_.size(); ++i) { + const int st = ranks_[i]->tierx.issue_copy(P.copy, ranks_[i]->ctx.stream()); + if (st < 0) P.copy_st[i] = st; + } + if (ranks_.size() > 1) (void)rad_dev_set(lead.device); + } + } + + /* ---- the slow half ---------------------------------------------------------------------- */ + /* AS SOON AS A DISK COPY IS WAITING, not on the clock: until it lands, the entry's host slot + * cannot be given up for nothing, and a full arena is then a restore that cannot read through + * it. The thread takes one batch at a time, so this is also as fast as the disk takes them. */ + if (!P.io.busy() && (lead.tiers.disk_waiting() || lead.tiers.starved() || + now - tier_last_ns_ >= 1000000000ull)) { + tier_last_ns_ = now; + std::vector jobs; + lead.tiers.plan(P.slow_budget, &jobs); + if (!jobs.empty() && !P.io.submit(std::move(jobs))) { + /* The thread is not running -- no disk tier -- and a plan without one holds only drops, + * which move nothing. They are reported here. */ + std::vector ok(jobs.size(), 1); + const auto lk = sched_.hold(); + lead.tierx.report_pass(jobs, ok, now); + } + } +} + +/* HAND A READ OFF DISK TO THE IO THREAD, fenced on every rank's transfer stream: the slots it + * writes may have been given up by entries a restore is still copying out of. False when it could + * not be handed over, and then the reads are reported unstarted -- the records stay on disk and the + * request is admitted with what the host tier holds. */ +bool Engine::submit_fetch(uint64_t tag, std::vector&& jobs) { + TierPump& P = *pump_; + TierIO::Fetch f; + f.tag = tag; + f.jobs = std::move(jobs); + int st = RAD_OK; + for (auto& r : ranks_) { + RadEvent e = nullptr; + if (st == RAD_OK) st = r->tierx.fence(&e); + f.fences.push_back(e); + } + if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device); + if (st == RAD_OK && P.io.submit_fetch(std::move(f))) { + P.waiting.push_back(tag); + return true; + } + RAD_ERR("kv tiers: a read off disk could not be handed to the IO thread (%s); the request is " + "admitted with what host memory holds", st < 0 ? rad_strerror(st) : "not running"); + for (size_t i = 0; i < f.fences.size(); ++i) { + if (!f.fences[i]) continue; + (void)rad_dev_set(ranks_[i]->device); + rad_event_destroy(f.fences[i]); + } + if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device); + const std::vector ok(f.jobs.size(), 0); + ranks_[0]->tierx.report_pass(f.jobs, ok, rad_mono_ns()); + return false; +} + +void Engine::drain_completed() { + /* TAKEN, NOT READ. The list is appended to by HTTP threads' cancels, so walking it by + * reference would race them; and nothing else consumes it -- the server learns of a terminal + * request through its sink and reaps it on its own -- so each id is seen here exactly once and + * the cost stays proportional to what finished rather than to everything that ever has. */ + sched_.take_completed(&done_); + for (uint64_t id : done_) for (auto& rk : ranks_) rk->sampler.end_request(id); +} + +int Engine::serve() { + if (ranks_.empty() || !ranks_[0]->ctx.program()) { + RAD_ERR("serve: start() has not run, or stopped at --debug-graph"); + return RAD_E_STATE; + } + if (ranks_[0]->program.logits_buf == RAD_NULL_HANDLE) { + RAD_ERR("the '%s' plugin declared no logits buffer (rad_declare_logits), so there is " + "nothing to sample. An encoder-only plugin cannot serve completions.", + plugins_.arch_plugin.c_str()); + return RAD_E_UNSUPPORTED; + } + + /* The scheduler drives ONE block manager. Block ids are pure bookkeeping and identical on + * every rank -- the heads divide equally, so every rank's pool has the same geometry and its + * free list evolves identically. What differs per rank is the pool BASE, and that lives in + * KVPoolBinding. So rank 0's manager owns the bookkeeping and the others exist to own their + * own card's allocation. If the geometries ever disagree the block tables mean different + * things on different cards, so it is checked rather than assumed. */ + for (size_t i = 1; i < ranks_.size(); ++i) { + const auto& a = ranks_[0]->kv.plans(); + const auto& c = ranks_[i]->kv.plans(); + if (a.size() != c.size()) { + RAD_ERR("rank %zu carved %zu KV groups and rank 0 carved %zu", i, c.size(), a.size()); + return RAD_E_STATE; + } + for (size_t g = 0; g < a.size(); ++g) { + if (a[g].n_blocks == c[g].n_blocks && a[g].n_states == c[g].n_states) continue; + RAD_ERR("KV group '%s': rank 0 carved %lld blocks / %lld states, rank %zu carved " + "%lld / %lld. One block table serves every rank, so they must agree.", + a[g].name.c_str(), (long long)a[g].n_blocks, (long long)a[g].n_states, + i, (long long)c[g].n_blocks, (long long)c[g].n_states); + return RAD_E_STATE; + } + } + + /* BACK TO RANK 0 BEFORE THE SCHEDULER IS BUILT. The per-rank loops above left this + * thread on the LAST rank's device, and the scheduler is given ranks_[0]->ctx.stream() + * -- so its staging buffers and its staging EVENT would be created on one card and + * recorded on another card's stream, which fails every step with "could not record + * the staging event". One batch serves every rank (spec §1), and rank 0 owns it. */ + RAD_TRY(rad_dev_set(ranks_[0]->device)); + + kv_iface_ = std::make_unique>(&ranks_[0]->kv); + pc_iface_ = std::make_unique>(&ranks_[0]->prefix); + /* THE RESTORE PATH, installed only when the tiers are on. The scheduler calls this before the + * admission lookup and must not know what a tier is; the engine does, so the knowledge lives + * here as a callable rather than as an include in core/sched. + * + * EVERY RANK RESTORES ITS OWN SHARD, and rank 0 goes first because its TierExec is the one + * holding the policy -- it allocates the blocks and reports the job, and the others follow + * into the same block ids. A rank that fails leaves the prefix shorter and nothing worse, + * which is why none of this returns an error upward: a miss is always safe. */ + if (ranks_[0]->tierx.enabled()) { + auto* b = static_cast*>(pc_iface_.get()); + /* CALLED FROM INSIDE Scheduler::step(), UNDER ITS LOCK -- which is what makes it safe to + * touch the cache and rank 0's manager here, and why nothing below may call back into the + * scheduler. */ + /* A restored session's state needs a device checkpoint slot, and which snapshot gives + * one up is the cache's decision: it knows which ones a lookup this step handed out. */ + ranks_[0]->tierx.set_checkpoint_room( + [this] { return ranks_[0]->prefix.free_checkpoint_for_restore(); }); + b->restore_fn = [this](const Request& req) -> IPrefixCache::Restore { + using R = IPrefixCache::Restore; + PrefixCache& pc = ranks_[0]->prefix; + TierPump& P = *pump_; + if (std::find(P.waiting.begin(), P.waiting.end(), req.id) != P.waiting.end()) + return R::Wait; + std::vector chain; + std::vector mk; + media_keys(req, &mk); + const std::vector want = pc.restorable_from(req.prompt, mk, &chain); + /* THE DISK PART IS READ FIRST, ON THE IO THREAD, while this request waits and every + * other one runs; the restore below then copies host memory and nothing else. Asked + * only when something could be on disk or in flight: a chain wholly in VRAM is the + * common case, and it is thousands of keys. */ + if (!want.empty() || !P.waiting.empty()) { + std::vector reads; + if (ranks_[0]->tiers.plan_fetch(chain, &reads, rad_mono_ns())) { + if (reads.empty() || submit_fetch(req.id, std::move(reads))) return R::Wait; + } + } + if (want.empty()) return R::Done; + /* THE WHOLE CHAIN IN ONE RESTORE. A 4-token block makes a long conversation tens of + * thousands of entries, and one transfer an entry is tens of thousands of host round + * trips before the turn can start; as one restore it is a launch per (group, layer) + * per staging batch and a copy per run of arena slots. */ + std::vector jobs; + jobs.reserve(want.size()); + for (const BlockHash& h : want) { + TierJob j; + if (!ranks_[0]->tierx.plan_promote(h, &j)) break; + jobs.push_back(std::move(j)); + } + if (jobs.empty()) return R::Done; + std::vector ok(jobs.size(), 1); + for (auto& r : ranks_) { + std::vector mine; + (void)r->tierx.issue_restore(jobs, r->ctx.stream(), &mine); + for (size_t i = 0; i < ok.size(); ++i) ok[i] = ok[i] && i < mine.size() && mine[i]; + } + /* Back to rank 0's card before anything else runs on this thread: the admission this + * restore is part of grows rank 0's pool next. */ + if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device); + ranks_[0]->tierx.report_pass(jobs, ok, rad_mono_ns()); + /* EVERY ENTRY THAT CAME BACK IS REBOUND, not only the leading run: the tiers have + * already marked each one resident at its new blocks, and an entry the cache did not + * take would name blocks nothing references. */ + const std::vector& cg = pc.cached_groups(); + for (size_t i = 0; i < jobs.size(); ++i) { + TierJob& j = jobs[i]; + if (!ok[i]) continue; + const int rb = pc.rebind(j.key, j.blocks); + if (rb != RAD_OK) { + /* A PROMOTION WITH NO ENTRY TO LAND IN. The blocks were reserved for the entry + * and nothing else holds them; the record the tiers just marked resident names + * them too, and would be released later from under whoever the pool gives them + * to. Both are let go, so the blocks return to the pool and the key is simply + * unknown. */ + for (size_t k = 0; k < cg.size() && k < j.blocks.size(); ++k) + if (j.blocks[k] >= 0) ranks_[0]->kv.release_block(cg[k], j.blocks[k]); + ranks_[0]->tiers.forget(j.key); + if (j.ck_dev >= 0) ranks_[0]->kv.free_checkpoint(j.ck_dev); + continue; + } + /* AND THE RECURRENT HALF, into the slot the restore allocated for it. Without this + * the session gets its attention hit back and replays every linear layer from + * token zero, which on a long transcript is most of a prefill. NOBODY ELSE OWNS + * THAT SLOT UNTIL THE CACHE TAKES IT: if the index entry the snapshot belongs to + * was retired, the slot has no path back to the free list. */ + if (j.ck_dev >= 0 && pc.reattach_snapshot(j.key, j.ck_dev) != RAD_OK) + ranks_[0]->kv.free_checkpoint(j.ck_dev); + } + return R::Done; + }; + } + /* EVERY RANK'S CARD, STREAM AND ARENA. The batch is one build shared by pointer (spec §1) and + * that is right for the host side; the DEVICE side is staged per rank, because a rank reading + * another card's staging is both a PCIe read on the step path and, worse, unordered against + * the copies that fill it -- see the Set comment in batch.h. */ + std::vector rio; + rio.reserve(ranks_.size()); + for (auto& rk : ranks_) + rio.push_back({ rk->device, rk->ctx.stream(), &rk->program }); + RAD_TRY(sched_.init(ranks_[0]->program, cfg_, kv_iface_.get(), pc_iface_.get(), rio, &geo_)); + + for (auto& r : ranks_) r->sampler.attach_vocab(vocab_view_.get()); + + barrier_ = std::make_unique(cfg_.tp + 1); + stopping_.store(false, std::memory_order_release); + step_status_.store(RAD_OK, std::memory_order_release); + loop_status_.store(RAD_OK, std::memory_order_release); + done_.reserve((size_t)cfg_.max_seqs); + + rank_threads_.clear(); + for (int i = 0; i < cfg_.tp; ++i) rank_threads_.emplace_back([this, i] { rank_loop(i); }); + std::thread stepper([this] { step_loop(); }); + + int s = cfg_.kld() ? run_kld() : run_server(); + + /* Stop the step loop before anything the server owns is destroyed: Request::sink is a raw + * pointer into the server's storage, and a request the scheduler has not finished is a request + * still writing into it (server.h). */ + stopping_.store(true, std::memory_order_release); + barrier_->abort(); + if (stepper.joinable()) stepper.join(); + for (auto& t : rank_threads_) if (t.joinable()) t.join(); + rank_threads_.clear(); + /* A step loop that died is the answer, whatever the transport said on the way down: the + * process should exit with the engine's error, not report a clean shutdown of a server that + * stopped serving. */ + const int ls = loop_status_.load(std::memory_order_acquire); + return ls < 0 ? ls : s; +} + +/* THE STATE SLOTS A SEQUENCE OWNS, one per KV group, -1 where the group is not stateful. + * + * Read from RANK 0 and applied to every rank, which is correct for the same reason the batch hands + * one `state_index` row to all of them: only rank 0's KVManager tracks sequences (kv_iface_ is + * bound to it), while every rank's pool has identical geometry, so a slot index means the same + * offset everywhere and only the base pointer differs. Looking the sequence up in any other rank's + * manager returns "not found". */ +bool Engine::state_slots_of(uint64_t seq, std::vector* out) const { + const KVManager& kv = ranks_[0]->kv; + out->assign((size_t)kv.n_groups(), -1); + bool any = false; + for (int32_t g = 0; g < kv.n_groups(); ++g) { + const KVGroupPlan* p = kv.plan(g); + if (!p || !p->stateful()) continue; + const int32_t s = kv.state_slot(seq, g); + if (s < 0) return false; /* the sequence is gone, or holds no state to copy */ + (*out)[(size_t)g] = s; + any = true; + } + return any; +} + +/* ------------------------------------------------------------------ the HTTP frontend */ +/* WHAT IS WIRED AND WHAT IS NOT, stated rather than discovered at runtime. `/v1/completions`, + * `/v1/chat/completions`, `/v1/models`, `/metrics` and `/health` are live. `/v1/embeddings` is + * 501 (no embedding head in the container), and so are image, video and audio content parts + * unless the program declared an encoder that accepts them (MEDIA, below). + * + * THE CHAT ENDPOINT IS 501 ONLY WHEN THE MODEL HAS NO TEMPLATE, and that distinction is the whole + * reason `chat_bridge` is conditional below. A container that carries a chat template gets the + * full path: the template's grammar and lazy triggers reach the sampler, and the reply parser the + * auto-parser derives from that same template comes back out through IChatTemplate::apply bound + * to the request that asked for it. A container without one gets an endpoint that says so, + * because a chat template guessed is a prompt format guessed, and the failure mode of guessing is + * fluent text in the wrong shape. */ +/* WHAT /server_info SAYS ABOUT THE ENGINE. + * + * The server cannot derive any of this: it holds interfaces and knows nothing about devices, + * containers or placement. Rather than growing ServerOptions a field per fact, the engine renders + * the object it owns and the server splices it in verbatim. + * + * IT IS THE OPERATOR'S FIRST QUESTION, asked of a process that is already running: which model, + * on how many cards, with how much KV, drafting how deeply, over which wire. All of it is printed + * at startup too -- and a startup log is on a machine, in a file, from a process that may have + * been restarted since. */ +std::string Engine::engine_info() const { + nlohmann::ordered_json e; + e["arch"] = meta_.arch_id ? meta_.arch_id : ""; + e["quant"] = meta_.quant ? meta_.quant : ""; + e["n_layers"] = meta_.n_layers; + e["n_embd"] = meta_.n_embd; + e["n_vocab"] = meta_.n_vocab; + e["n_ctx_train"] = meta_.n_ctx_train; + e["container"] = cfg_.model; + + e["tensor_parallel"] = cfg_.tp; + e["tp_wire"] = cfg_.tp > 1 ? (cfg_.tp_wire_exact ? "exact" : "wht6") : "n/a"; + e["tp_wire_min_kb"] = cfg_.tp_wire_exact ? 0 : cfg_.tp_wire_min_kb; + e["max_num_batched_tokens"] = cfg_.max_tok; + e["placement"] = cfg_.placement; + e["prefix_cache"] = cfg_.prefix_cache; + e["checkpoint_slots"] = cfg_.checkpoint_slots; + e["deterministic"] = cfg_.deterministic; + + nlohmann::ordered_json devs = nlohmann::ordered_json::array(); + for (const auto& r : ranks_) { + RadDeviceProps p{}; + if (rad_dev_props(r->device, &p) < 0) continue; + nlohmann::ordered_json d; + d["rank"] = r->index; + d["device"] = r->device; + d["name"] = p.name; + d["arch"] = p.arch; + d["vram_bytes"] = p.vram_bytes; + d["vram_free"] = p.vram_free; + devs.push_back(std::move(d)); + } + e["devices"] = std::move(devs); + + /* Rank 0's, and every rank declares the same graph -- see the miss report in + * engine_bringup.cpp for why that is relied on rather than assumed. */ + const Program& p0 = ranks_[0]->program; + e["ops"] = (int64_t)p0.ops.size() - 1; + e["weights"] = (int64_t)p0.weights.size() - 1; + + nlohmann::ordered_json kvs = nlohmann::ordered_json::array(); + const KVManager& kv = ranks_[0]->kv; + for (int32_t g = 0; g < kv.n_groups(); ++g) { + const KVGroupPlan* pl = kv.plan(g); + /* Group 0 is the "no KV group" sentinel every program carries so that a handle of zero is + * absent rather than valid. It has no layers and no pool, and reporting it would be + * reporting the absence of a thing. */ + if (!pl || pl->name.empty() || pl->n_layers <= 0) continue; + nlohmann::ordered_json k; + k["name"] = pl->name; + k["kind"] = pl->kind == RAD_KV_FULL ? "full" + : pl->kind == RAD_KV_WINDOW ? "window" + : pl->kind == RAD_KV_LINEAR ? "linear" + : pl->kind == RAD_KV_CONV ? "conv" : "none"; + k["n_layers"] = pl->n_layers; + k["bytes"] = pl->pool_bytes; + if (pl->paged()) { + k["block_size"] = pl->block_size; + k["blocks"] = pl->n_blocks; + k["tokens"] = pl->n_blocks * pl->block_size; + } else { + k["states"] = pl->n_seq_states(); + } + kvs.push_back(std::move(k)); + } + e["kv_groups"] = std::move(kvs); + + nlohmann::ordered_json sp; + if (drafter_.kind == RAD_DRAFT_NONE) { + sp["enabled"] = false; + } else { + sp["enabled"] = true; + sp["drafter"] = drafter_name_; + sp["kind"] = drafter_.kind == RAD_DRAFT_BLOCK ? "block" : "serial"; + sp["depth"] = drafter_.depth; + } + e["speculation"] = std::move(sp); + return e.dump(); +} + + +/* ------------------------------------------------------------------ a clean stop + * + * SIGINT AND SIGTERM ARE HANDLED, so a serving process has a way to end other than being killed + * where it stands. Unhandled, `~Engine` never runs: `--profile-ops` collects a table nobody + * prints, the placement banner is unreachable by construction, and an in-flight request is cut + * rather than drained. + * + * A WATCHER THREAD AND NOT THE HANDLER ITSELF. `Server::stop` takes locks, joins threads and + * drains a graveyard; none of that is async-signal-safe, and calling it from a handler is the + * deadlock that only shows up under load. The handler does the one thing it may -- store to a + * lock-free atomic -- and this thread does the work. A second signal is left to the default + * disposition, so an operator who has decided not to wait still gets an immediate kill. + */ +namespace { +std::atomic g_signalled{false}; +void on_signal(int) { g_signalled.store(true, std::memory_order_relaxed); } + +/* ================================================================== sampling defaults */ +/* WHAT A REQUEST THAT SENDS NO SAMPLER SETTINGS IS SERVED WITH. + * + * The reading and the range checks belong to core/gen_config.h, which carries the argument for + * why any of this exists. What is here is the ORDER, and the container lookup, which is the one + * part that reads the model's metadata: + * + * --temp / --top-k / --top-p / --min-p an operator overriding, field by field, and last + * --generation-config PATH a generation_config.json named outright + * .generation.json one placed beside the container + * the model's `generation.*` metadata generation_config.json, as the container or the + * checkpoint carries it + * SamplingParams' own defaults the untruncated floor + * + * Each source is consulted only if the one above it said nothing at all, so a deployment that + * names a file gets that file's sampler and not a blend of it with the container's. */ +SamplingParams resolve_sampling_defaults(const RadModelMeta& meta, bool container, + const Config& cfg) { + GenSampling g; + std::string src; + + if (!cfg.generation_config.empty() && + gen_sampling_from_file(cfg.generation_config, /*required=*/true, &g)) + src = cfg.generation_config; + + if (!g.any()) { + const std::string side = gen_sidecar_path(cfg.model); + if (gen_sampling_from_file(side, /*required=*/false, &g)) src = side; + } + if (!g.any()) { + auto get = [&meta](const char* field) { + return rad_meta_gets(&meta, (std::string("generation.") + field).c_str(), nullptr); + }; + if (gen_sampling_from_kv(get, &g)) src = container ? "the container" : "the checkpoint"; + } + + SamplingParams sp = g.onto(SamplingParams{}); + + std::string over; + if (cfg.sample_temp >= 0.0f) { sp.temp = cfg.sample_temp; over += " --temp"; } + if (cfg.sample_top_p >= 0.0f) { sp.top_p = cfg.sample_top_p; over += " --top-p"; } + if (cfg.sample_min_p >= 0.0f) { sp.min_p = cfg.sample_min_p; over += " --min-p"; } + if (cfg.sample_top_k >= 0) { sp.top_k = cfg.sample_top_k; over += " --top-k"; } + + const std::string from = src.empty() ? (over.empty() ? "nothing stated it" : "the command line") + : src; + RAD_INFO("sampling defaults for requests that send none: %s (from %s%s%s)", + GenSampling::describe(sp).c_str(), from.c_str(), + over.empty() || src.empty() ? "" : ", overridden by", over.c_str()); + if (src.empty() && over.empty()) + RAD_WARN("this checkpoint states no sampling of its own and none was given, so a request " + "that sends no sampler fields is served with the whole vocabulary live at " + "temperature 1 -- which ends a reply early often enough to notice. Pass " + "--generation-config, or put the checkpoint's generation_config.json beside the " + "container as %s.", gen_sidecar_path(cfg.model).c_str()); + return sp; +} +} /* namespace */ +int Engine::run_server() { + /* The rank-0 sampler comes along so admission can refuse a request whose sampling stage this + * build has no kernel for, by name and at the door (IScheduler::admit). The tiers come along + * because they are where a stored conversation is RECORDED, and that is passed whether or not + * any tier can move anything: with the caps at zero the object still holds the session table, + * and withholding it on that ground would leave the sessions view reporting an empty server. */ + server::SchedulerBridge sched_bridge(&sched_, ranks_.empty() ? nullptr : &ranks_[0]->sampler, + ranks_.empty() ? nullptr : &ranks_[0]->tiers); + server::TokenizerBridge tok_bridge(vocab_); + server::ChatTemplateBridge chat_bridge; + server::GrammarBridge grammar_bridge(vocab_view_.get()); + + /* THE SNAPSHOT OF WHAT ONLY THE ENGINE CAN SEE, and there is ONE of it. The live view + * (spec §16) and the web dashboard are two renderers of the same numbers, so they are given + * the same function rather than each reaching into the engine on its own -- two readers is + * two chances to disagree about what the engine was doing. + * + * Called from whichever thread is drawing, and it must not be able to slow the engine: it + * reads the scheduler's published copy (Scheduler::publish), the driver's VRAM counter + * through a descriptor opened here, and rank 0's plan, which is immutable after start(). + * + * THE CARDS' FIXED FACTS ARE READ ONCE, HERE, on the engine thread before serving. The props + * call enters the device runtime -- device properties, a device switch, a free-memory query, + * a peer walk -- and is meant for startup; it also opens the counter dev_vram_used reads. */ + std::vector card_facts; + for (const auto& r : ranks_) { + RadDeviceProps pr{}; + if (rad_dev_props(r->device, &pr) < 0) continue; + server::CardStat c; + c.index = r->device; + c.name = pr.name; + c.vram_total = pr.vram_bytes; + card_facts.push_back(std::move(c)); + } + server::LiveView::Source snap = [this, &sched_bridge, card_facts](server::LiveSnapshot& s) { + server::snapshot_from(sched_bridge.metrics(), &s); + s.model = meta_.name && *meta_.name ? meta_.name : "radiance"; + + s.cards.clear(); + for (const server::CardStat& f : card_facts) { + /* vram_used is sampled per call rather than cached: it is the number that moves, and + * it is the one an operator watching for a leak is watching. A card whose counter + * cannot be read is left out rather than drawn empty. Utilisation, power and + * temperature stay 0 -- "not sampled" -- because the device layer does not expose + * them and a plausible invented number is worse than a blank. */ + int64_t used = 0; + if (dev_vram_used(f.index, &used) != RAD_OK) continue; + server::CardStat c = f; + c.vram_used = used; + s.cards.push_back(std::move(c)); + } + + /* THE EXPERT PLANE, from rank 0's placement plan. A dense model has no expert units, so + * this stays empty and both renderers omit the panel -- which is why it is filled + * unconditionally rather than behind a "is this MoE" test the engine would have to + * invent. When there are experts, this is the picture the heat engine is judged by. */ + s.experts = server::ExpertPlane{}; + if (!ranks_.empty()) { + const Plan& p = ranks_[0]->plan; + /* Read ONCE for both halves of this panel: the same struct answers "what did the + * mover do to the experts" and "what did it put on the link", and two reads is two + * chances for the two halves of one picture to disagree. */ + const MoverStats ms = ranks_[0]->mover.stats(); + int32_t n_layer = 0, n_expert = 0; + for (const MoveUnit& mu : p.units) + if (mu.expert >= 0) { + n_layer = std::max(n_layer, mu.layer + 1); + n_expert = std::max(n_expert, mu.expert + 1); + } + if (n_layer > 0 && n_expert > 0) { + s.experts.n_layers = n_layer; + s.experts.n_experts = n_expert; + s.experts.tier.assign((size_t)n_layer * (size_t)n_expert, (uint8_t)Tier::VRAM); + /* THE LIVE TIER WHERE THERE IS ONE, and the plan's otherwise. The plan is where a + * unit STARTED; once the heat engine runs, the picture this panel exists to show + * is the one that moves, and reading the plan would draw a frozen plane under an + * engine doing nothing but change it. HeatEngine::tier is a plain vector + * read and the writes are made by the dispatch thread at a step boundary, so a + * draw racing one gets the value from either side of a single store. */ + const HeatEngine& heat = ranks_[0]->heat; + const bool live_tier = heat.enabled(); + s.experts.heat_enabled = live_tier; + s.experts.layer_units.assign((size_t)n_layer, 0); + s.experts.layer_resident.assign((size_t)n_layer, 0); + for (size_t u = 0; u < p.units.size(); ++u) { + const MoveUnit& mu = p.units[u]; + if (mu.expert < 0 || mu.layer < 0) continue; + const Tier t = live_tier ? heat.tier((int32_t)u) : mu.tier; + s.experts.tier[(size_t)mu.layer * (size_t)n_expert + (size_t)mu.expert] + = (uint8_t)t; + /* RESIDENCY IS COUNTED OVER THE UNITS, NOT OVER THE PLANE. The plane is a + * rectangle and a model need not fill it -- a draft head's expert count can + * differ from the trunk's -- so tallying cells would count + * (layer, expert) pairs that were never placed as VRAM-resident, which is the + * one direction the number must not be wrong in. */ + const int ti = (int)t >= 0 && (int)t < kTierCount ? (int)t : (int)Tier::SSD; + s.experts.units[ti]++; + s.experts.bytes[ti] += mu.bytes; + s.experts.n_units++; + s.experts.total_bytes += mu.bytes; + if (mu.movable) s.experts.movable++; + s.experts.layer_units[(size_t)mu.layer]++; + if (t == Tier::VRAM) s.experts.layer_resident[(size_t)mu.layer]++; + } + s.experts.promotions = (int64_t)ms.promotions; + s.experts.demotions = (int64_t)ms.demotions; + s.experts.no_record = (int64_t)ms.no_record; + s.experts.starved_slab = (int64_t)ms.starved_slab; + s.experts.starved_pool = (int64_t)ms.starved_pool; + s.experts.quarantined = (int64_t)ms.quarantined; + s.experts.stage_layers = (int64_t)ms.stage_layers; + s.experts.staged_units = (int64_t)ms.staged_units; + s.experts.staged_bytes = (int64_t)ms.staged_bytes; + s.experts.stage_overflow = (int64_t)ms.stage_overflow; + s.experts.flex_bytes = ranks_[0]->mover.flex_used_bytes(); + s.experts.flex_capacity = ranks_[0]->mover.flex_offered_bytes(); + /* THE HEAT ENGINE'S OWN TALLY, which answers a different question from the + * mover's. The mover counts bytes that went; these count decisions -- how many + * dispatches proposed nothing and why, and whether a promotion was of a unit + * never promoted before (investment) or one just demoted (pure loss). */ + const HeatStats hs = heat.stats(); + s.experts.dispatches = (int64_t)hs.dispatches; + s.experts.refused = (int64_t)hs.refused; + s.experts.no_candidate = (int64_t)hs.no_candidate; + s.experts.distinct_promoted = (int64_t)hs.distinct_promoted; + s.experts.readmits = (int64_t)hs.readmits; + /* AND WHETHER THE PLACEMENT IS ACTUALLY PAYING. Residency is a property of the + * plan; the hit rate is a property of the TRAFFIC, and a plan holding 80% of the + * units can still miss on most tokens if the hot ones are the ones outside. */ + s.experts.routed = (int64_t)hs.routed; + s.experts.routed_resident = (int64_t)hs.routed_resident; + + } + + /* THE LINK, and the two things that share it. + * + * THE COLLECTIVE IS ONE RANK'S AND THE MOVES ARE EVERY RANK'S, which is why the two + * halves of this panel are summed differently. The ranks are symmetric in the + * all-reduce -- each pushes the same message -- so rank 0's count IS the machine's and + * summing it would double it. A promotion, a demotion and a streamed expert are the + * opposite: each rank holds its own shard of the plane and pulls its own bytes over + * its own link, so the machine's traffic is the sum and rank 0 alone is a half of it + * at --tp 2. Reading one rank for all of them would put the move and stream rows at + * 1/world of the truth while the all-reduce beside them stayed right, which is the + * worse of the two errors: the SHARES would be wrong, and the shares are the whole + * point of the panel. + * + * `world` is published so the reader can still recover a per-card figure, which is the + * one to hold against a single link's ceiling. */ + s.passes.present = true; + for (const auto& rk : ranks_) { + const Ctx::PassCounts pc = rk->ctx.pass_counts(); + s.passes.played += pc.played; + s.passes.recorded += pc.recorded; + s.passes.audited += pc.audited; + s.passes.issued_unkeyed += pc.issued_unkeyed; + s.passes.issued_refused += pc.issued_refused; + s.passes.issued_first += pc.issued_first; + s.passes.dispatched += pc.dispatched; + s.passes.unordered += pc.unordered; + } + + s.link.present = true; + s.link.world = (int)ranks_.size(); + s.link.ar_calls = ranks_[0]->ctx.ar_calls(); + s.link.ar_bytes = ranks_[0]->ctx.ar_bytes(); + s.link.h2d_bytes = s.link.d2h_bytes = s.link.ssd_reads = 0; + s.link.ssd_bytes = s.link.prefetched = s.link.prefetch_bytes = 0; + s.link.stream_bytes = s.link.staged_bytes = 0; + for (const auto& rk : ranks_) { + const MoverStats rms = rk->mover.stats(); + s.link.h2d_bytes += (int64_t)rms.h2d_bytes; + s.link.d2h_bytes += (int64_t)rms.d2h_bytes; + s.link.ssd_reads += (int64_t)rms.ssd_reads; + s.link.ssd_bytes += (int64_t)rms.ssd_bytes; + s.link.prefetched += (int64_t)rms.prefetched; + s.link.prefetch_bytes += (int64_t)rms.prefetch_bytes; + s.link.staged_bytes += (int64_t)rms.staged_bytes; + if (rk->heat.enabled()) s.link.stream_bytes += (int64_t)rk->heat.stats().stream_bytes; + } + } + }; + + server::Deps d{}; + d.sched = &sched_bridge; + d.tok = &tok_bridge; + d.grammar = &grammar_bridge; + d.live = snap; + + /* load_from_vocab warns on its own when the template is missing or will not compile; all we + * decide here is whether the endpoint exists. The reply format is the architecture plugin's + * when it declares one, and the template's otherwise. */ + const RadChatFormat* declared_format = rad_tools_chat_format(plugins_, meta_); + if (vocab_ && !vocab_->chat_template().empty() && + chat_bridge.init(*vocab_, declared_format, plugins_.arch_plugin) >= 0 && + chat_bridge.ready()) { + d.chat = &chat_bridge; + } else { + RAD_WARN("no chat template in this container; /v1/chat/completions will answer 501 and " + "/v1/completions is the endpoint to use"); + } + + server::ServerOptions o{}; + o.model_id = meta_.name && *meta_.name ? meta_.name : "radiance"; + o.host = cfg_.host; + o.port = cfg_.port; + o.api_key = cfg_.api_key; + o.max_seqs = cfg_.max_seqs; + o.max_ctx = cfg_.max_ctx ? cfg_.max_ctx : meta_.n_ctx_train; + o.default_reasoning_effort = cfg_.reasoning_effort; + o.default_sampling = resolve_sampling_defaults(meta_, file_ != nullptr, cfg_); + o.engine_info = engine_info(); + /* Per request, not once: the dump carries OpInfo::issued, which only becomes true once the + * run phase has run. See ServerOptions::graph_json. */ + o.graph_json = [this] { return dump_graph_json(ranks_[0]->program); }; + + /* MEDIA, WHEN THE PROGRAM DECLARED AN ENCODER. The processor reads its geometry from the + * container and the encoder states the one it was built for; the two meet at the patch width + * and the merge, and a disagreement is refused here rather than discovered as garbage rows. */ + std::unique_ptr mm_proc; + std::unique_ptr mm_bridge; + const RadEncoderDecl& encd = ranks_[0]->program.encoder; + if (encd.modalities != 0) { + mm::VisionConfig vc; + std::string why; + if (vc.from_meta(meta_, &why) < 0) { + RAD_ERR("the '%s' encoder has no processor: %s", ranks_[0]->program.encoder_name.c_str(), + why.c_str()); + return RAD_E_INVAL; + } + vc.max_patches = encd.max_patches; + if (vc.patch_dim() != encd.patch_dim || (int64_t)vc.merge * vc.merge != encd.merge) { + RAD_ERR("the container's processor cuts %lld-element patches merged %lld to a row; the " + "'%s' encoder takes %lld-element patches merged %lld", (long long)vc.patch_dim(), + (long long)vc.merge * vc.merge, ranks_[0]->program.encoder_name.c_str(), + (long long)encd.patch_dim, (long long)encd.merge); + return RAD_E_INVAL; + } + mm_proc = std::make_unique(); + RAD_TRY(mm_proc->init(vc, [&tok_bridge](const std::string& t) { + return tok_bridge.encode(t, /*add_special=*/false, /*parse_special=*/false); + })); + mm_bridge = std::make_unique(mm_proc.get(), encd.modalities); + d.mm = mm_bridge.get(); + o.allow_image = (encd.modalities & RAD_MM_IMAGE) != 0; + o.allow_video = (encd.modalities & RAD_MM_VIDEO) != 0; + if (!mm::decoder_available()) + RAD_WARN("media: the '%s' encoder is loaded but this build has no media decoder " + "(RAD_WITH_FFMPEG), so every media part will be refused", + ranks_[0]->program.encoder_name.c_str()); + else + RAD_INFO("media: %s%s through '%s'; an image resizes to at most %lld pixels (%lld " + "patches a pass), a video to %lld pixels over all its frames", + o.allow_image ? "images" : "", o.allow_video ? " and video" : "", + ranks_[0]->program.encoder_name.c_str(), + (long long)mm_proc->config().image_max_pixels, (long long)encd.max_patches, + (long long)mm_proc->config().video_max_pixels); + } + + server::Server srv(d, o); + RAD_INFO("serving on http://%s:%d (/v1/completions%s)%s", o.host.c_str(), o.port, + d.chat ? "; /v1/chat/completions with tools and reasoning" : "; chat is 501", + o.api_key.empty() ? "" : " -- a bearer key is required"); + + /* THE LIVE VIEW (spec §16), constructed here and nowhere else. + * + * `core/server/liveview.{h,cpp}` is the console's view of a running engine, and the + * throughput heartbeat the server otherwise has no form of: nothing here logs a request, + * and everything else the engine prints happens at startup, so a loop that stalls looks + * exactly like a loop with nothing to do. + * + * Off by default, because §16 opens with "everything below is off by default". Redirected, it + * prints one greppable key=value line per interval and no escape sequences at all -- which is + * the property that makes it usable under nohup, and the reason the renderer is chosen once by + * isatty() rather than per draw. + * + * The snapshot function is the only part the engine owns: LiveView holds no data and reads no + * device. Held by value in this scope so its thread is joined before Deps goes out of it. */ + std::unique_ptr live; + if (cfg_.live_view) { + live = std::make_unique(snap); + live->start(); + } + + struct sigaction sa {}; + sa.sa_handler = on_signal; + sigemptyset(&sa.sa_mask); + sa.sa_flags = SA_RESETHAND; /* a second one takes the default disposition and kills */ + sigaction(SIGINT, &sa, nullptr); + sigaction(SIGTERM, &sa, nullptr); + + std::atomic watching{true}; + std::thread watcher([&] { + while (watching.load(std::memory_order_relaxed)) { + if (g_signalled.load(std::memory_order_relaxed)) { + RAD_INFO("stopping: draining in-flight requests"); + srv.stop(); + return; + } + /* THE STEP LOOP HAS DIED, so nothing will ever run another step. Every request it + * held has already been failed and answered (Engine::fail_loop); what is left is to + * stop taking new ones, which a transport left up would accept into a queue nobody + * drains. */ + if (loop_status_.load(std::memory_order_acquire) < 0) { + RAD_ERR("stopping: the step loop failed with %s", + rad_strerror(loop_status_.load(std::memory_order_acquire))); + srv.stop(); + return; + } + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } + }); + + const int rc = srv.run(); + /* The loop tests `watching` FIRST, so clearing it ends the watcher WITHOUT a second stop: a + * normal return from run() has already torn the transport down. It costs one sleep interval + * to join, which is the price of not polling a condition variable nobody else waits on. */ + watching.store(false, std::memory_order_relaxed); + watcher.join(); + if (live) live->stop(); + return rc; +} + +} /* namespace rad */ diff --git a/core/engine.h b/core/engine.h new file mode 100644 index 00000000..b4296eb2 --- /dev/null +++ b/core/engine.h @@ -0,0 +1,332 @@ +/* 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 +#include +#include +#include +#include +#include + +namespace rad { + +class SSDTier; +class Kld; +struct TierPump; +struct TierJob; +struct StepSlot; + +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> 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 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 pump_; + std::vector 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 file_; + std::unique_ptr ckpt_; + std::unique_ptr ckpt_src_; + /* What rad_weight_encoding is answered from: the container's entries or the checkpoint's + * tensors. */ + 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 meta_kv_k_, meta_kv_v_; + std::vector 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(); + 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 reqs; /* the requests that wanted a row, in row order */ + std::vector first_row; /* [n_seq] that entry's first row, or -1 */ + /* HOW MANY OF THE STEP'S LOGITS ROWS THE SAMPLER READS: the first ones. RadBatch::n_out + * counts the KL mode's scored rows after them too (Request::score). */ + int32_t n_rows = 0; + std::vector rows; /* [n_out] the device's answer, copied back */ + int32_t* rb = nullptr; /* the pinned readback collect_issue filled */ + std::vector lg; /* the first row's logits, at -vv */ + std::vector token; /* [n_seq] */ + std::vector accepted; /* [n_seq] */ + std::vector 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 vocab_; + std::unique_ptr vocab_view_; + + /* The chunk geometry, resolved ONCE here and handed to both consumers. The prefix cache needs + * the checkpoint interval at configure time and the scheduler needs the whole geometry at + * init; resolving it independently in each is how the cache ends up testing the operator's raw + * interval against positions the scheduler chose with the rounded one. */ + ChunkGeometry geo_; + + /* One scheduler for every rank: one decision per step, one batch, shared by pointer. */ + Scheduler sched_; + std::unique_ptr kv_iface_; + std::unique_ptr pc_iface_; + + /* The release point. Width is tp + 1 -- the scheduler thread is on both sides of it. */ + std::unique_ptr barrier_; + std::atomic step_batch_{nullptr}; + /* WHAT A RELEASE ASKS THE RANKS TO ISSUE: the forward pass and its sampler (kIssueAll), the + * forward pass alone (kIssueModel) -- the next step's, issued before this one is read back -- + * or that pass's sampler alone (kIssueSampler), once the host has committed what the sampler + * stages from. Every release sets it: one left over from the release before tells a draft + * pass to issue nothing but its sampler. */ + enum { kIssueAll = 0, kIssueModel = 1, kIssueSampler = 2 }; + std::atomic issue_what_{kIssueAll}; + std::atomic step_status_{RAD_OK}; + std::atomic stopping_{false}; + /* WHY THE STEP LOOP ENDED, when it ended on an error; RAD_OK while it runs or after a clean + * stop. Written once, by fail_loop(); read by the server watcher to take the HTTP side down + * and by serve() to return it. */ + std::atomic loop_status_{RAD_OK}; + int fail_loop(int st); + + /* THE SAMPLER'S HOST WORK RUNS UNDER THE MODEL, NOT IN FRONT OF IT. + * + * Staging a step's sampler parameters -- and with a grammar, walking a whole-vocabulary mask + * for every position in the speculative window -- is pure host work: every upload in the chain + * is issued by Sampler::run on the rank thread, so build_step touches no stream and nothing + * the ranks read until they are told to sample. Run BEFORE the release it sits in front of a + * device with nothing to do, and every microsecond of it is added to the step. + * + * So the ranks are released to enqueue the model first, and the scheduler stages the sampler + * while they do. The ranks then wait here for it before enqueueing the sampler chain -- which + * the device cannot reach until the whole forward pass has run, and that pass is the time the + * walk hides inside. This is a one-shot gate per step, reset while the ranks are parked at the + * release, so there is no window in which a rank can read a stale ready flag. */ + 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 ckpt_slots_; + bool state_slots_of(uint64_t seq, std::vector* 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 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 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 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&& 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 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; + 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_; + std::vector kld_host_; + std::vector 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 */ diff --git a/core/engine_bringup.cpp b/core/engine_bringup.cpp new file mode 100644 index 00000000..ee0361a4 --- /dev/null +++ b/core/engine_bringup.cpp @@ -0,0 +1,2846 @@ +/* engine_bringup.cpp -- everything the Engine does ONCE, in the order it does it. + * + * Devices, the container's metadata, the plugins, declare, the placement plan, the weights, the + * KV pools, the ranks' threads, the vocabulary. Each numbered section is one component doing its + * own job; this file is the order they happen in and nothing else. + * + * Kept apart from engine.cpp because none of it runs again: the step loop next door is on the hot + * path and shares nothing with this but the Engine's fields. See engine_priv.h. + */ +#include "engine_priv.h" + +#include "build/startup.h" +#include "build/rad_build.h" +#include "device/device.h" +#include "device/directio.h" +#include "format/radfile.h" +#include "format/share.h" +#include "rad_plugin.h" +#include "mem/vram_budget.h" +#include "runtime/arena.h" +#include "sample/gbnf.h" +#include "sched/scheduler.h" +#include "text/tokenizer.h" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rad { + +/* ================================================================== the miss report */ +/* WHAT DID NOT RESOLVE, in the three shapes the three answers want. + * + * A DEVICE miss WITH NO HOST KERNEL EITHER is a hole. The band exists, a request can land in it, + * and the step that does fails at ISSUE rather than here -- declare completes either way -- so + * every one gets a line of its own carrying the geometry and the constraint that refused it. + * + * A DEVICE miss whose op DID resolve on the host is not a hole at all. The planner puts that op's + * arithmetic on the host and its weights in the container's mapping, which is the whole of how + * `embed_lookup_q` serves a table too large to copy into VRAM. Reporting that as fatal produces + * an error nobody believes, and an error nobody believes is how a real one goes unread. + * + * A HOST miss removes ONE placement option for ONE op, and for a kernel library written for a GPU + * it is the ordinary case rather than news: most ops have no host implementation and never will. + * One line for all of them. + * + * The distinction is the whole point of this function. Printed alike, a large model at tp2 opens + * with thousands of lines of `E` that are all host misses, and a real device hole is invisible + * among them. */ +struct MissReport { + std::vector device; /* one line each; fatal at issue */ + std::string host; /* one line, or empty */ + /* Device bands whose op DOES have a host kernel. Not a hole: the planner runs such an op on + * the host and pins its weights there (Tier::Mapped), which is the whole of how a table too + * large to copy into VRAM is served. Reported apart because calling it fatal is a lie an + * operator has to learn to ignore -- and an error nobody believes is how a real one goes + * unread. */ + std::string host_only; + + bool operator==(const MissReport& o) const { + return device == o.device && host == o.host && host_only == o.host_only; + } +}; + +static MissReport miss_report(const Program& p) { + MissReport r; + std::vector host_ops; /* in first-seen order */ + std::map host_spans; /* op -> "M <= 64, M in (64, 512]" */ + + /* (op, band) pairs the HOST could not serve either. A device miss that is in this set is a + * hole; one that is not has a host kernel standing behind it. */ + std::set> no_host; + for (const Program::Miss& m : p.misses) + if (m.domain == RAD_DOMAIN_HOST) no_host.emplace(m.op, m.span); + + std::vector host_only_ops; + for (const Program::Miss& m : p.misses) { + if (m.domain != RAD_DOMAIN_HOST) { + if (no_host.count(std::make_pair(m.op, m.span))) r.device.push_back(m.line()); + else if (std::find(host_only_ops.begin(), host_only_ops.end(), m.op) == + host_only_ops.end()) host_only_ops.push_back(m.op); + continue; + } + auto it = host_spans.find(m.op); + if (it == host_spans.end()) { + host_ops.push_back(m.op); + host_spans.emplace(m.op, m.span); + } else if (it->second.find(m.span) == std::string::npos) { + it->second += ", " + m.span; + } + } + if (!host_only_ops.empty()) { + std::string names; + for (size_t i = 0; i < host_only_ops.size(); ++i) + names += (i ? ", " : "") + host_only_ops[i]; + r.host_only = fmt("host-only ops: %s resolved a host kernel and no device one, so the " + "planner places %s arithmetic on the host and its weights in the " + "container's mapping. Not a hole.", + names.c_str(), host_only_ops.size() == 1 ? "that op's" : "those ops'"); + } + if (host_ops.empty()) return r; + + /* THE OP NAMES, ALL OF THEM UNTIL IT GETS SILLY, and not the bands: a reader who wants the + * bands wants --debug-graph, and the bands are what would make this report thousands of lines + * long. The names are what a reader can act on -- each one is a reference kernel somebody could + * write -- and a short list is not enough to act on: whole-model host execution needs EVERY op + * covered, so the op behind "and 1 more" is the one that stops the run and the one the line + * does not name. Sixteen is past the point where the answer is a list rather than a shape. */ + std::string names; + const size_t k_named = 16; + for (size_t i = 0; i < host_ops.size() && i < k_named; ++i) + names += (i ? ", " : "") + host_ops[i]; + if (host_ops.size() > k_named) + names += fmt(", and %zu more", host_ops.size() - k_named); + + r.host = fmt("host-site execution: %zu of %zu declared ops have no host kernel (%s). Their " + "weights may still be tiered to host or SSD -- only the arithmetic is pinned to " + "the device. --debug-graph lists the bands.", + host_ops.size(), p.ops.size() - 1, names.c_str()); + return r; +} + +/* ================================================================== 1. devices */ +/* A HIP device is not necessarily a discrete GPU. A host with an integrated GPU reports it as a + * device of its own, claiming a slice of system RAM as VRAM, and a --tp that lands a rank on one + * runs slowly and wrongly with a failure that looks like a kernel bug. So the engine uses the + * discrete cards when there are any -- integrated graphics only when it is all there is, which is + * an APU machine -- and of those the ones sharing the first one's arch, and prints only what that + * choice DID, rather than reprinting the backend's inventory. Which devices the backend shows at + * all is the runtime's to say: ROCR_VISIBLE_DEVICES and HIP_VISIBLE_DEVICES pick them. */ +static int usable_devices(std::vector* out, std::string* inventory, std::string* note) { + const int n = rad_dev_count(); + if (n <= 0) return RAD_E_DEVICE; + + struct D { int i; std::string arch; bool igpu; }; + std::vector all; + bool any_discrete = false; + std::string inv; + for (int i = 0; i < n; ++i) { + RadDeviceProps p{}; + if (rad_dev_props(i, &p) < 0) continue; + const bool igpu = dev_integrated(i); + inv += fmt("%s%d:%s%s", i ? " " : "", i, p.arch, igpu ? "(integrated)" : ""); + all.push_back({ i, p.arch, igpu }); + any_discrete |= !igpu; + } + + std::string want; /* the arch of the first device taken -- the ranks must all match */ + std::string use, skip; + for (const D& d : all) { + const bool take = (!any_discrete || !d.igpu) && (want.empty() || want == d.arch); + if (take && want.empty()) want = d.arch; + std::string& into = take ? use : skip; + into += fmt("%s%d:%s", into.empty() ? "" : " ", d.i, d.arch.c_str()); + if (take) out->push_back(d.i); + } + *inventory = fmt("%s backend, %d device(s) [%s]", device_backend_name(), n, inv.c_str()); + + /* THE BACKEND ALREADY PRINTED THAT INVENTORY (core/device/dispatch.cpp), so repeating it here + * would only cost a reader two lines that say the same thing in different capitalisation. + * What is the engine's to say is which of them it will USE -- and that is news only when the + * arch filter dropped one, so on a uniform machine this stays empty and nothing is + * printed. */ + *note = skip.empty() + ? std::string() + : fmt("using %zu of %d [%s], ignoring [%s]: integrated graphics beside a discrete card, " + "or a different architecture from the first card used, and a rank placed on one " + "runs slowly and wrongly. ROCR_VISIBLE_DEVICES chooses the devices explicitly", + out->size(), n, use.c_str(), skip.c_str()); + return out->empty() ? RAD_E_DEVICE : RAD_OK; +} + +/* ================================================================== 2. metadata */ +/* The model's metadata ONLY -- architecture id, dimensions, quantisation, vocab. Not the weights: + * which weights exist is the architecture plugin's answer, not the container's, and reading them + * before declare would be reading them before we know what they are for. */ +namespace { + +/* A CONTAINER IS A FILE THAT SAYS SO: its first four bytes are the magic. Anything else -- + * a checkpoint directory, a .safetensors, an index, a .gguf -- is a checkpoint. A .rad that is not + * one is still opened as a container, so its own reader names what is wrong with it. */ +bool is_container(const std::string& path) { + if (path.size() > 4 && path.compare(path.size() - 4, 4, ".rad") == 0) return true; + FILE* f = std::fopen(path.c_str(), "rb"); + if (!f) return false; + uint32_t magic = 0; + const bool got = std::fread(&magic, 4, 1, f) == 1; + std::fclose(f); + return got && magic == RAD_MAGIC; +} + +} /* namespace */ + +WeightSourceFn Engine::sources() const { + if (file_) return rad_container_sources(*file_); + return ckpt_src_ ? ckpt_src_->fn() : WeightSourceFn{}; +} + +int Engine::read_metadata() { + if (!is_container(cfg_.model)) return read_checkpoint_metadata(); + file_ = std::make_unique(); + RAD_TRY(file_->open(cfg_.model.c_str())); + + const RadFileHeader& h = file_->header(); + meta_ = RadModelMeta{}; + meta_.arch_id = file_->str(h.arch_id); + meta_.name = file_->str(h.model_name); + meta_.quant = file_->str(h.quant); + + auto geti = [&](const char* k, int64_t d) { int64_t v = d; file_->get_i(k, &v); return v; }; + auto getf = [&](const char* k, double d) { double v = d; file_->get_f(k, &v); return (float)v; }; + + /* THE KEYS ARE RadModelMeta'S OWN FIELD NAMES, because that is what rad-convert writes and + * what rad-kbench and rad-tune read. Reading GGUF's spellings instead -- `block_count`, + * `embedding_length`, `attention.head_count` -- yields zero for every dimension, since no + * writer in this project produces them; declare then refuses with "invalid argument" while + * rad-info prints the correct shape off the same file. + * + * The GGUF names are NOT accepted as a fallback. A container carries these because + * rad-convert normalises whatever it read -- safetensors or GGUF -- into RadModelMeta before + * writing, so a file that lacks them is a file no version of this project wrote, and reading + * it as if the absent keys were zeros turns a bad container into a wrong model instead of a + * refusal. */ + meta_.n_layers = geti("n_layers", 0); + meta_.n_embd = geti("n_embd", 0); + meta_.n_head = geti("n_head", 0); + meta_.n_head_kv = geti("n_head_kv", 0); + /* Read head_dim; do NOT derive it. A model may declare a head_dim that is not n_embd/n_head, + * and a derived one then makes every downstream shape silently wrong + * (docs/ARCHITECTURES.md). */ + meta_.head_dim = geti("head_dim", 0); + meta_.n_ff = geti("n_ff", 0); + meta_.n_vocab = geti("n_vocab", 0); + meta_.n_ctx_train = geti("n_ctx_train", 0); + meta_.n_expert = geti("n_expert", 0); + meta_.n_expert_used = geti("n_expert_used", 0); + meta_.n_expert_shared = geti("n_expert_shared", 0); + meta_.rms_eps = getf("rms_eps", 1e-6); + meta_.rope_theta = getf("rope_theta", 10000.0); + meta_.rope_scale = getf("rope_scale", 1.0); + + /* A container that says nothing about its own shape is refused HERE, by name, rather than at + * declare as an "invalid argument" from a plugin that was handed zeros. */ + if (meta_.n_layers <= 0 || meta_.n_embd <= 0 || meta_.n_head <= 0 || meta_.n_vocab <= 0) { + RAD_ERR("%s carries no model dimensions (n_layers=%lld n_embd=%lld n_head=%lld " + "n_vocab=%lld). A .rad written by rad-convert always does; rad-info prints what " + "this one holds.", cfg_.model.c_str(), (long long)meta_.n_layers, + (long long)meta_.n_embd, (long long)meta_.n_head, (long long)meta_.n_vocab); + return RAD_E_FORMAT; + } + + /* Everything the struct does not name, verbatim, for the plugin to read. The vectors own the + * storage because RadModelMeta holds bare pointers. */ + meta_kv_k_.clear(); meta_kv_v_.clear(); + for (int64_t i = 0; i < file_->meta_count(); ++i) { + const RadFileKV& kv = file_->meta_at(i); + meta_kv_k_.push_back(file_->str(kv.key)); + switch (kv.type) { + case RAD_P_INT: meta_kv_v_.push_back(fmt("%lld", (long long)kv.v.i)); break; + case RAD_KV_F64: meta_kv_v_.push_back(fmt("%.17g", kv.v.f)); break; + default: meta_kv_v_.push_back(file_->str(kv.v.s)); break; + } + } + meta_kv_kp_.clear(); meta_kv_vp_.clear(); + for (auto& s : meta_kv_k_) meta_kv_kp_.push_back(s.c_str()); + for (auto& s : meta_kv_v_) meta_kv_vp_.push_back(s.c_str()); + meta_.n_kv = (int)meta_kv_kp_.size(); + meta_.kv_key = meta_kv_kp_.data(); + meta_.kv_val = meta_kv_vp_.data(); + + RAD_INFO("model: %s arch=%s quant=%s %lld layers %lld ctx", + meta_.name && *meta_.name ? meta_.name : "(unnamed)", + meta_.arch_id, meta_.quant && *meta_.quant ? meta_.quant : "bf16", + (long long)meta_.n_layers, (long long)meta_.n_ctx_train); + return RAD_OK; +} + +/* A CHECKPOINT SERVED DIRECTLY (spec §4.3): its config.json -- or the GGUF header -- is the + * metadata, read the way rad-convert reads it, and its tensors are the weights. Only an encoding + * served as it stands is answered to declare (CheckpointSources), so a checkpoint whose served + * form needs quantisation is refused by name after declare, with the container as the remedy. */ +int Engine::read_checkpoint_metadata() { + ckpt_ = std::make_unique(); + RAD_TRY(ckpt_->open(cfg_.model)); + ckpt_src_ = std::make_unique(*ckpt_); + const MetaOwn& mo = ckpt_->meta(); + meta_ = mo.m; + if (!meta_.name || !*meta_.name) meta_.name = meta_.arch_id; + if (meta_.n_layers <= 0 || meta_.n_embd <= 0 || meta_.n_head <= 0 || meta_.n_vocab <= 0) { + RAD_ERR("%s: the checkpoint's configuration states no model dimensions (n_layers=%lld " + "n_embd=%lld n_head=%lld n_vocab=%lld)", cfg_.model.c_str(), + (long long)meta_.n_layers, (long long)meta_.n_embd, (long long)meta_.n_head, + (long long)meta_.n_vocab); + return RAD_E_FORMAT; + } + meta_kv_k_ = mo.keys; + meta_kv_v_ = mo.vals; + meta_kv_kp_.clear(); meta_kv_vp_.clear(); + for (auto& k : meta_kv_k_) meta_kv_kp_.push_back(k.c_str()); + for (auto& v : meta_kv_v_) meta_kv_vp_.push_back(v.c_str()); + meta_.n_kv = (int)meta_kv_kp_.size(); + meta_.kv_key = meta_kv_kp_.data(); + meta_.kv_val = meta_kv_vp_.data(); + RAD_INFO("model: %s arch=%s quant=%s %lld layers %lld ctx (checkpoint, %zu tensors, " + "served as it stands)", meta_.name, meta_.arch_id, + meta_.quant && *meta_.quant ? meta_.quant : "bf16", (long long)meta_.n_layers, + (long long)meta_.n_ctx_train, ckpt_->tensors().size()); + return RAD_OK; +} + +/* ================================================================== 3 + 4. plugins, declare */ +int Engine::load_plugins() { + int s = rad_tools_load_plugins(cfg_.radiance_home, cfg_.kernel_hierarchy, + meta_.arch_id, meta_.quant ? meta_.quant : "", &plugins_); + if (s < 0) { + /* rad_tools_load_plugins has said why -- a plugin refused, or no architecture plugin for + * this model -- each by name. What it does not know is that this was the engine's start. */ + RAD_ERR("the plugins under %s did not load (above)", cfg_.radiance_home.c_str()); + return s; + } + + const Plugin* ap = rad_tools_registry().plugin(plugins_.arch_plugin); + arch_step_ = ap ? ap->arch_step : nullptr; + return RAD_OK; +} + +RadBuildCtx Engine::build_ctx(int rank, int64_t max_tok) const { + RadBuildCtx bc{}; + bc.rank = rank; + bc.world_size = cfg_.tp; + bc.max_tok = max_tok; + bc.max_seqs = cfg_.max_seqs; + bc.max_ctx = cfg_.max_ctx ? cfg_.max_ctx : meta_.n_ctx_train; + bc.max_spec = cfg_.n_spec; + bc.tp_wire_lossy = cfg_.tp_wire_exact ? 0 : 1; + /* One answer to "is the cache fp8", for every architecture. The engine always states it; + * RAD_DT_INVALID stays meaningful in the ABI for an out-of-tree caller that leaves the field + * zero, and means the plugin's own default. */ + bc.kv_dtype = cfg_.kv_cache_dtype == "fp8" ? RAD_F8E4M3 : RAD_BF16; + bc.tp_wire_min_bytes = cfg_.tp_wire_min_kb * 1024; + bc.scope = ""; + bc.max_enc_patches = cfg_.mm_max_patches > 0 ? cfg_.mm_max_patches : 0; + /* A row at every token of the step and the sampler's row a sequence before them + * (core/kld.h); the KL mode has no speculation, so a sequence samples one. */ + bc.max_out_rows = cfg_.kld() ? max_tok + cfg_.max_seqs : 0; + return bc; +} + +int Engine::declare() { + /* Declare runs ONCE PER RANK, with rank and world_size in RadBuildCtx, and the plugin declares + * dimensions ALREADY DIVIDED. The core does not reason about sharding propagation and does not + * insert collectives -- a sharding inference pass is a compiler pass whose failure mode is a + * model that produces fluent wrong text on a rank count nobody tested (spec §9). + * + * EVERY RANK DECLARES AT THE SAME TIME, ON ITS OWN THREAD. That is a requirement and not a + * speed-up. Kernel init() runs from here (registry.h says so), and a collective's init is a + * RENDEZVOUS: libr4d's all-reduce publishes this rank's peer scratch pointer and then WAITS + * for every other rank to publish before it can enable peer access. A serial loop never gets + * a second rank there, so the first one times out after 60 seconds and --tp 2 fails startup + * with `ar_oneshot_2rank_exact ... called in the wrong phase`. Registry::select() and + * init_instance() are already behind one mutex for exactly this, and the arch plugin's + * per-rank state is indexed by ctx->rank. + * + * The device is bound per thread because the backend's current device is thread-local and a + * collective's init ALLOCATES on it -- unbound, both ranks would hand each other pointers into + * card 0 and the reduce would read its own scratch twice. */ + /* Resolved HERE and not at argument parsing: it is the PLUGIN that says how deep this + * container's drafter goes, and the plugin is not selected until the container is open. Every + * consumer of `n_spec` -- buffer sizing, the kernel bands, the scheduler's window -- runs + * after this line. The core reads no drafter configuration of its own; rad_arch_probe is the + * whole of what it knows. */ + /* THE KL MODE MEASURES THE TRUNK (core/kld.h). A drafter adds passes that write no scored + * row, and a prefix hit would start a document past positions the reference holds, so both + * are off -- and an explicit depth is refused rather than dropped, because the operator asked + * for something this run will not do. The tower stays off the card: the corpus is text. */ + if (cfg_.kld()) { + if (cfg_.n_spec > 0) { + RAD_ERR("--num-speculative-tokens %d: the KL mode scores the trunk's own rows and " + "drafts nothing; leave it at auto or 0", cfg_.n_spec); + return RAD_E_INVAL; + } + cfg_.n_spec = 0; + cfg_.prefix_cache = false; + if (cfg_.mm_max_patches < 0) cfg_.mm_max_patches = 0; + } + if (cfg_.n_spec < 0) { + RadArchProbe pb{}; + (void)rad_tools_probe(plugins_, meta_, &pb); + cfg_.n_spec = pb.draft_depth > 0 ? pb.draft_depth : 0; + if (cfg_.n_spec > 0) + RAD_INFO("speculation: depth %d, this drafter's own operating point " + "(--num-speculative-tokens N overrides it)", cfg_.n_spec); + else + RAD_INFO("speculation: off -- this container carries no draft head"); + } + /* THE ENCODER'S PASS SIZE, resolved the same way and for the same reason: whether there is a + * tower to size is a property of the model file. A container says so (`radiance.encoder`, + * written when its weights went in); a checkpoint served directly is the release itself, so a + * vision_config is a tower whose weights are in it. 16384 patches is a 2048 x 2048 image, the + * largest one pass takes; the reference processor allows sixteen times that area, which would + * need an activation region sixteen times as large on every card for one picture. */ + if (cfg_.mm_max_patches < 0) { + const char* enc = rad_meta_gets(&meta_, "radiance.encoder", ""); + const bool tower = rad_meta_geti(&meta_, "vision_config.patch_size", 0) > 0; + cfg_.mm_max_patches = (enc && *enc) || (!file_ && tower) ? 16384 : 0; + if (cfg_.mm_max_patches == 0 && tower) + RAD_INFO("media: off -- the checkpoint has a vision tower but this container was " + "converted without its weights; convert again to serve images and video"); + } + + std::vector st(ranks_.size(), RAD_OK); + std::vector th; + th.reserve(ranks_.size()); + for (auto& rp : ranks_) { + Rank* r = rp.get(); + th.emplace_back([this, r, &st] { + const int ri = r->index; + LogRank lr(ri); + if (rad_dev_set(r->device) < 0) { + RAD_ERR("rank %d: could not bind device %d to declare on", ri, r->device); + st[(size_t)ri] = RAD_E_DEVICE; + return; + } + const RadBuildCtx bc = build_ctx(ri, cfg_.max_tok); + st[(size_t)ri] = rad_tools_declare(plugins_, meta_, bc, &r->program, + [this, ri](RadBuilder* bb, int64_t lw) { + return declare_sampler(ri, bb, lw); + }, + nullptr, sources()); + }); + } + if (cfg_.tp > 1 && !cfg_.tp_wire_exact) + RAD_WARN("tp wire: LOSSY (--tp-wire wht6) above %lld KiB a message. A cross-rank " + "all-reduce at or over that size carries a Walsh-Hadamard-rotated 6-bit payload " + "instead of bf16, so this process does not compute the same function the exact " + "wire does; smaller messages -- which is every decode step -- are still exact.", + (long long)cfg_.tp_wire_min_kb); + + for (auto& t : th) t.join(); + + /* This phase ALWAYS completes: if anything failed to resolve, the FULL list is reported at + * the end rather than the first failure at the top (spec §1 step 4). Reported after the join + * and in rank order -- two ranks printing their lists concurrently interleaves them into one + * that reads like neither. + * + * ONCE FOR EVERY RANK THAT AGREES, which is normally all of them: each rank declares the same + * model against the same registry, so N ranks produce N identical copies of the same list. A + * rank whose report differs is itself worth seeing, and gets its own. */ + { + std::vector rep; + for (auto& r : ranks_) rep.push_back(miss_report(r->program)); + bool same = true; + for (size_t i = 1; i < rep.size(); ++i) if (!(rep[i] == rep[0])) same = false; + + for (size_t i = 0; i < rep.size(); ++i) { + if (same && i > 0) break; + const std::string who = same && rep.size() > 1 ? fmt("all %zu ranks", rep.size()) + : fmt("rank %d", ranks_[i]->index); + if (!rep[i].device.empty()) { + RAD_ERR("%s: %zu device band(s) resolved to no kernel -- a request that lands in " + "one of them cannot run:", who.c_str(), rep[i].device.size()); + for (const std::string& l : rep[i].device) RAD_ERR(" %s", l.c_str()); + } + if (!rep[i].host_only.empty()) RAD_INFO("%s", rep[i].host_only.c_str()); + if (!rep[i].host.empty()) RAD_INFO("%s", rep[i].host.c_str()); + } + } + /* A CHECKPOINT WEIGHT THAT IS NOT SERVED AS IT STANDS was declared as plain and nothing can + * load it: every one is named, with the remedy, whatever declare made of the rest. */ + if (ckpt_src_) { + const std::vector no = ckpt_src_->refused(); + if (!no.empty()) { + RAD_ERR("%zu weight(s) of %s are not in a form the engine serves as it stands -- " + "nothing is quantised at load. Convert the checkpoint to a container with a " + "recipe that says what they become (rad-convert --recipe):", no.size(), + cfg_.model.c_str()); + for (size_t i = 0; i < no.size() && i < 16; ++i) RAD_ERR(" %s", no[i].c_str()); + if (no.size() > 16) RAD_ERR(" ... and %zu more", no.size() - 16); + return RAD_E_UNSUPPORTED; + } + } + for (size_t i = 0; i < st.size(); ++i) if (st[i] < 0) return st[i]; + RAD_INFO("declare: %zu ops, %zu weights, %zu buffers, %zu KV groups", + ranks_[0]->program.ops.size() - 1, ranks_[0]->program.weights.size() - 1, + ranks_[0]->program.buffers.size() - 1, ranks_[0]->program.kv_groups.size()); + + /* IS THERE A DRAFT HEAD, AND WHAT SHAPE IS IT? The plugin declared it (rad_declare_drafter) + * or it did not, and that is the whole of the question. There is no flag to read, no metadata + * key to re-read and no second place for the two to disagree. + * + * Sniffing it out instead -- scanning the declared weights for known draft-head names, then + * re-reading the metadata keys the plugin already read to build the head -- would put a list + * of model names in the core, and a third party's drafter could not then exist without + * editing this function. */ + const Program& p0 = ranks_[0]->program; + drafter_ = p0.drafter; + drafter_name_ = p0.drafter_name; + drafter_.name = drafter_name_.c_str(); + if (cfg_.n_spec <= 0) drafter_ = RadDrafterDecl{}; + if (drafter_.kind != RAD_DRAFT_NONE) { + /* The proposal buffer is a HANDLE the plugin passed, not a name this looked up. Zero is + * legal and means the sampler's token buffer -- a head whose logits go through the + * ordinary sampler chain, which the bf16 MTP head does and the 2-bit draft head does + * not. */ + RAD_INFO("speculation: %s", + drafter_.kind == RAD_DRAFT_BLOCK + ? fmt("'%s' proposes %d token(s) in ONE block pass over %lld row(s) (mask id %d, " + "window %lld); prompt lookup fills in for any sequence it declines", + drafter_.name, drafter_.depth, (long long)drafter_.block, + (int)drafter_.mask_token, (long long)drafter_.window).c_str() + : fmt("'%s' drafts %d token(s) a step in %d serial pass(es); prompt lookup fills " + "in for any sequence it declines", + drafter_.name, drafter_.depth, drafter_.depth).c_str()); + } else if (cfg_.n_spec > 0) { + RAD_INFO("speculation: prompt lookup only -- this container declares no draft head"); + } + probe_arena_levels(); + return RAD_OK; +} + +/* THE ACTIVATION ARENA'S SMALLER LEVELS, sized by the plugin itself. + * + * Every activation is declared for the largest step, and a decode step is a few dozen rows of the + * 2048 a prefill chunk carries: most of the arena sits unread for as long as nothing prefills. The + * plugin is asked to declare again at a smaller step (RadBuildCtx::shape_probe) -- its own shape + * rules are the only ones that know how each buffer scales, so no rule here second-guesses them -- + * and each answer that describes the same buffers with only their rows smaller becomes a level: + * the same fixed region, the transients packed lower, and the arena above them free while the + * steps are that small. + * + * THE SMALLEST LEVEL IS 256 ROWS AT LEAST. A kernel that computes whole tiles may write the + * padding rows of its last one; at the real size those land inside the buffer because the chunk is + * a multiple of every tile, and a level is held to the same property so that padding never reaches + * the next buffer or the memory past the level's end. Each level above is four times the one + * below, up to the chunk. + * + * A refusal costs a level and nothing else: the arena is lent from the levels that were accepted, + * or not at all. */ +void Engine::probe_arena_levels() { + for (auto& r : ranks_) r->arena_levels.clear(); + RadArchProbe pb{}; + (void)rad_tools_probe(plugins_, meta_, &pb); + if (!pb.shape_probe_ok) { + RAD_INFO("activation arena: not lent -- the '%s' plugin does not declare at a smaller step " + "size (RadArchProbe::shape_probe_ok)", plugins_.arch_plugin.c_str()); + return; + } + int64_t lo = 1; + const int64_t rows_min = cfg_.max_seqs * (1 + std::max(cfg_.n_spec, 0)); + while (lo < rows_min) lo <<= 1; + lo = std::max(lo, 256); + std::vector want; + for (int64_t R = lo; R < cfg_.max_tok; R *= 4) want.push_back(R); + + /* One sizing declare a (level, rank), all of them side by side: a sizing declare selects and + * initialises nothing, so they share no state, and each is a whole declare of the model. */ + const size_t nl = want.size(), nr = ranks_.size(); + std::vector got(nl * nr); + std::vector why(nl * nr); + std::vector ok(nl * nr, 0); + { + std::vector th; + th.reserve(nl * nr); + for (size_t l = 0; l < nl; ++l) + for (size_t i = 0; i < nr; ++i) + th.emplace_back([this, &want, &got, &why, &ok, l, i, nr] { + Rank& r = *ranks_[i]; + LogRank lr(r.index); + const size_t k = l * nr + i; + if (rad_dev_set(r.device) < 0) { + why[k] = fmt("could not bind device %d", r.device); + return; + } + RadBuildCtx bc = build_ctx(r.index, want[l]); + bc.shape_probe = 1; + Program probe; + const int st = rad_tools_declare(plugins_, meta_, bc, &probe, + [this, &r](RadBuilder* bb, int64_t lw) { + return declare_sampler(r.index, bb, lw, + true); + }, + &r.program, sources()); + if (st < 0) why[k] = fmt("the sizing declare failed: %s", rad_strerror(st)); + else if (plan_level(r.program, probe, want[l], &got[k], &why[k]) >= 0) + ok[k] = 1; + }); + for (auto& t : th) t.join(); + } + + std::string said; + for (size_t l = 0; l < nl; ++l) { + const int64_t R = want[l]; + size_t bad = nr; + for (size_t i = 0; i < nr && bad == nr; ++i) if (!ok[l * nr + i]) bad = i; + if (bad < nr) { + RAD_WARN("activation arena: no level for %lld-token steps on rank %d -- %s", + (long long)R, ranks_[bad]->index, why[l * nr + bad].c_str()); + continue; + } + for (size_t i = 0; i < nr; ++i) + ranks_[i]->arena_levels.push_back(std::move(got[l * nr + i])); + said += fmt("%s%lld tokens use %s", said.empty() ? "" : ", ", (long long)R, + humanb(ranks_[0]->arena_levels.back().end).c_str()); + } + if (!said.empty()) + RAD_INFO("activation arena: %s of %s (the fixed region is %s); the rest is lent to the " + "expert slab while the steps are that small", said.c_str(), + humanb(ranks_[0]->program.arena_bytes).c_str(), + humanb(ranks_[0]->program.arena_fixed_bytes).c_str()); +} + +/* ================================================================== 5. plan */ +int Engine::plan() { + /* THE BUDGET IS RESOLVED ONCE, FOR EVERY RANK, BEFORE ANY RANK ALLOCATES. + * + * It has to happen here and not inside the per-rank loop below for two reasons. One card's + * answer is not another's -- the fold in vram_budget_resolve takes the smallest capacity and + * the largest program so that one split fits every card it is applied to -- and the answer is + * written back into Config, which the loop then reads. Doing it per rank would let rank 1 + * re-resolve against a card rank 0 has already filled. + * + * Every input is available by now and not before: declare() has run, so the buffer plan exists + * and the arena can be sized; every kernel plugin's init has run, so the code objects are + * resident and the free-VRAM reading is the steady-state one; and the KV groups are declared, + * so a full cache's cost is computable. */ + { + std::vector facts; + facts.reserve(ranks_.size()); + const int64_t ctx = cfg_.max_ctx ? cfg_.max_ctx : meta_.n_ctx_train; + for (auto& r : ranks_) { + RAD_TRY(rad_dev_set(r->device)); + RadDeviceProps props{}; + rad_dev_props(r->device, &props); + VramFacts f{}; + f.capacity = props.vram_bytes; + f.free = props.vram_free; + /* AN EIGHTH OF THE HOST'S MEMORY STAYS THE HOST'S on integrated graphics. The card's + * free figure is already bounded by what the host has available (core/device/hip.cpp); + * this is the margin the rest of the machine keeps on top of that, because a budget + * that spends every available byte leaves the operating system to reclaim its page + * cache and then to kill something. */ + if (dev_integrated(r->device)) { + const long pages = sysconf(_SC_PHYS_PAGES), page = sysconf(_SC_PAGE_SIZE); + if (pages > 0 && page > 0) f.host_reserve = (int64_t)pages * page / 8; + } + arena_plan_bytes(r->program, nullptr, &f.arena); + /* WHAT THE WEIGHTS WOULD COST, split into the floor and the elastic plane -- see + * weight_footprint in core/place/planner.h. Per RANK, which under tensor parallel is + * already this card's even share of the static weights: declare ran once per rank + * with every dimension divided. */ + WeightFootprint wf; + weight_footprint(r->program, &wf); + f.statics = wf.statics; + f.experts = wf.experts; + /* THE STAGING REGION IS SIZED ONLY WHERE THE ARENA LENDS ITS TOP: with no smaller level + * nothing gives the region back to the slab at decode, and a deterministic plan moves + * nothing, so neither can stage or recover what a region would cost. */ + if (!r->arena_levels.empty() && !cfg_.deterministic) f.expert_layer_max = wf.expert_layer_max; + /* A THROWAWAY MANAGER, because the question is what the groups WOULD cost and the + * real one is configured against a pool that does not exist yet. plan_groups touches + * no memory and no pool; it is the half of configure() that is pure arithmetic on the + * declaration, split out for exactly this caller. */ + KVManager probe; + if (probe.plan_groups(r->program.kv_groups, cfg_) == RAD_OK) + f.kv_ceiling = probe.ceiling(ctx); + facts.push_back(f); + } + VramBudget vb; + RAD_TRY(vram_budget_resolve(cfg_, facts, &vb)); + if (!vb.report.empty()) RAD_INFO("%s", vb.report.c_str()); + /* The staging region the budget took out of the experts, above everything the buffer plan + * placed -- so it is at the top of the arena, the part the smaller levels lend. */ + if (vb.stage > 0) + for (auto& r : ranks_) { + int64_t dev = 0; + arena_plan_bytes(r->program, &dev, nullptr); + r->program.arena_stage_off = align_up(dev, RAD_ALIGN_UNIT); + r->program.arena_stage_bytes = vb.stage; + r->program.arena_bytes = r->program.arena_stage_off + vb.stage; + } + } + + for (auto& r : ranks_) { + LogRank lr(r->index); + /* THE MAIN THREAD RUNS EVERY RANK'S STARTUP, one rank after another, and every allocator + * reachable from here takes the CURRENT device -- rad_dev_alloc has no device argument. + * Unbound, rank 1's pools, its weights and its KV cache all land on card 0. That fits by + * accident at tp 1 and is silently wrong above it, so each phase binds the rank it is + * working on before it allocates anything for it. */ + RAD_TRY(rad_dev_set(r->device)); + RadDeviceProps props{}; + rad_dev_props(r->device, &props); + + /* Every pool is budgeted explicitly. No profiling pass, no utilisation fraction, no + * inference about what the workload will be (spec §6). Pools refuses by name and by how + * much rather than shrinking anything. */ + int s = r->pools.configure(cfg_, props.vram_bytes); + RAD_INFO("pools:\n%s", r->pools.fit_report().c_str()); + if (s < 0) return s; + + /* Under tensor parallel the placement unit is a SHARD of a weight, so each rank plans + * against its own card's budget (spec §5.3). */ + PlannerInput in{}; + in.program = &r->program; + in.config = &cfg_; + in.rank = r->index; + in.world_size = cfg_.tp; + if (file_ && file_->header().prof_count) { + in.profile = file_->profile(); + in.n_profile = (int64_t)file_->header().prof_count; + } + in.container = file_ != nullptr; + Planner planner(in); + s = planner.plan(&r->plan); + if (cfg_.debug_placement || s < 0) + fputs(r->plan.report(r->program).c_str(), stderr); + if (s < 0) return s; + } + return RAD_OK; +} + +/* ================================================================== 6. load */ +/* Weights are mapped and staged according to the plan. The mover has already reserved every slot + * and published the address each weight will live at, so this is a fill: for every declared + * weight, find its entry in the container and copy THIS RANK'S SHARD of it into place. + * + * The container holds whole weights unless it was converted pre-sharded, and the plugin declared + * dimensions ALREADY DIVIDED (spec §9) -- so the slicing happens here, and it is the only place + * in the engine that knows a weight is a piece of a larger one. Row sharding is a contiguous + * range of dim 0. Column sharding is not contiguous and needs a 2D copy, which is exactly why + * the two are different enum values rather than a bool. */ +/* ONE RUN OF CONTAINER BYTES, AND WHERE THEY GO. Emitted by the walk below, consumed by the + * sweep; `ny == 1` with `span == wb` is one contiguous range, and everything else is a column + * share, whose pieces are `wb` bytes every `sp`. A run with `stage >= 0` fills that staged + * weight's input at `dst` bytes in rather than landing where the weight lives. */ +struct LoadRun { + int64_t foff; /* first container byte the run reads */ + int64_t span; /* container bytes it covers, its own internal gaps included */ + uint8_t* dst; /* the destination, or the offset into the staged input */ + int64_t wb; /* bytes in one contiguous piece */ + int64_t sp; /* container bytes from the start of one piece to the next */ + int64_t ny; /* how many pieces */ + int32_t rank; /* which rank's stream carries the copy */ + int32_t dev; /* the destination is device memory; 0 is a host pool and a plain memcpy */ + int32_t stage; /* the staged weight it fills, or -1 */ +}; + +/* ================================================================== the relayout pool + * + * A WEIGHT THE LOADER HAS TO REARRANGE (spec §4.3): the resolved kernel stores something other + * than the container's canonical planes -- a fragment order, a scale carried in each row's tail -- + * or the declaration widens a bf16 plane to f32. Its share of the planes is read out of the sweep + * into host memory of its own, and when the last byte of it has arrived a worker produces the + * stored form: straight into its host pool, or, for VRAM, into memory of its own and up through + * that worker's pinned bounce buffers. + * + * IT HAS TO KEEP PACE WITH THE DISK, because Qwen3.8-27B-FP8 rearranges 24 GiB of its 29 at every + * load and a single thread scattering bytes into fragment order runs at a fraction of 7 GB/s. So + * it is a pool, and the sweep only reads: the copies out of its windows -- into a staged input, + * or into a host pool slot -- are the pool's too, taken before any relayout, because a window + * cannot be read into again until they are done. On the sweep thread those copies, and the first + * touch of every fresh input, would run in series with the reads. + * + * AND IT HOLDS A BOUNDED AMOUNT, because a staged input is a copy of the weight in host memory and + * a model is larger than that memory. A new input waits for room while there is finished work + * that will free some -- and only then: a weight still arriving cannot be relaid, so waiting on + * it would wait forever. Past the bound with nothing finished, the input is taken anyway. */ +struct StagedWeight { + const Program* prog = nullptr; + size_t wi = 0; + int device = 0; + uint8_t* dst = nullptr; /* where the stored form goes */ + bool dev = false; /* ...in device memory */ + int64_t in_bytes = 0; + int64_t plane_off[RAD_ENC_MAX_PLANES] = {0}; + int64_t remaining = 0; /* bytes the sweep has yet to deliver */ + bool reserved = false; /* its input counts against the pool's budget */ + uint8_t* in = nullptr; /* its input: in the pool's region, or its own allocation */ + bool own = false; /* ...its own, because the region had no hole that size */ + /* A checkpoint's weight has no sweep: the worker fills its input itself, from the mapped + * tensors, before it lays it out -- so the reads run on every worker at once. */ + std::function fill; +}; + +class RelayoutPool { +public: + explicit RelayoutPool(std::vector& items) + : items_(items), once_(new std::once_flag[items.size()]) {} + ~RelayoutPool() { + finish(); + for (StagedWeight& s : items_) if (s.own) delete[] s.in; + if (region_) ::munmap(region_, (size_t)budget_); + } + + /* THE INPUTS SHARE ONE REGION THE SIZE OF THE BUDGET, made once and handed out again as each + * weight is done with it. Memory made fresh for every input is a page fault every 4 KiB of + * it, and over a model's worth of weights those faults are most of the load's CPU time; a + * region the workers keep reusing faults once. An input with no hole its size -- larger than + * the budget, or the region too cut up -- gets an allocation of its own. */ + void start(int threads, int64_t budget) { + budget_ = budget; + void* p = ::mmap(nullptr, (size_t)budget_, PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (p != MAP_FAILED) { + region_ = (uint8_t*)p; + ::madvise(p, (size_t)budget_, MADV_HUGEPAGE); + holes_[0] = budget_; + } + int devs = 1; + for (const StagedWeight& w : items_) if (w.dev && w.device + 1 > devs) devs = w.device + 1; + uplinks_.reset(new Uplink[(size_t)devs]); + n_uplinks_ = devs; + for (int t = 0; t < threads; ++t) threads_.emplace_back([this] { worker(); }); + } + + /* The sweep thread: room for a staged weight's input, taken the first time a run reaches it. + * ROOM AND NOT MEMORY: the allocation is input()'s, on a worker. An allocation this size is + * an mmap, which waits on every munmap and fault the workers are making in the same address + * space -- milliseconds an input, and on the sweep thread that is a second of a load. */ + void reserve(int i) { + StagedWeight& s = items_[(size_t)i]; + if (s.reserved) return; + std::unique_lock lk(mu_); + room_.wait(lk, [&] { return held_ + s.in_bytes <= budget_ || pending_ == 0 || failed_; }); + held_ += s.in_bytes; + if (held_ > peak_) peak_ = held_; + s.reserved = true; + } + + /* `n` more bytes of it are in -- from whichever worker copied them, so under the lock. */ + void arrived(int i, int64_t n) { + std::lock_guard lk(mu_); + StagedWeight& s = items_[(size_t)i]; + s.remaining -= n; + if (s.remaining > 0) return; + pending_ += s.in_bytes; + queue_.push_back(i); + work_.notify_one(); + } + + /* A COPY OUT OF A SWEEP WINDOW: the part of run `q` that lies in file range [j0, j1), out of + * window `slot`, whose first byte is file offset `w0`. A staged run lands in its weight's + * input, which the sweep has made room for with reserve() first; any other run is a host + * destination. */ + struct Copy { const uint8_t* win; int64_t w0, j0, j1; LoadRun q; int slot; }; + + /* The sweep thread: how many windows it reads into. */ + void windows(int n) { + std::lock_guard lk(mu_); + out_.assign((size_t)n, 0); + } + void copy(const Copy& c) { + std::lock_guard lk(mu_); + ++out_[(size_t)c.slot]; + copies_.push_back(c); + work_.notify_one(); + } + /* The sweep thread: until no copy out of window `slot` is outstanding. A failed pool still + * retires its copies, so this returns either way. */ + void drain(int slot) { + std::unique_lock lk(mu_); + drained_.wait(lk, [&] { return out_[(size_t)slot] == 0; }); + } + + int finish() { + { + std::lock_guard lk(mu_); + done_ = true; + } + work_.notify_all(); + for (std::thread& t : threads_) t.join(); + threads_.clear(); + for (int d = 0; d < n_uplinks_; ++d) + if (uplinks_[(size_t)d].st) { + rad_dev_set(d); + rad_stream_destroy(uplinks_[(size_t)d].st); + uplinks_[(size_t)d].st = nullptr; + } + return status_; + } + + bool failed() const { return failed_; } + int64_t peak() const { return peak_; } + +private: + /* ONE STREAM A CARD FOR EVERY WORKER'S COPIES. A stream is a hardware queue of its own on + * this backend, and a stream a worker a card made some twenty queues a card, which the card + * time-slices: the workers spent three quarters of a Flash-Next load waiting on their copies. + * One link copy fills the link by itself, so one queue a card loses nothing; the workers take + * turns putting their copies on it. */ + struct Uplink { + std::mutex mu; + RadStream st = nullptr; + }; + + /* A worker's way onto a card: a ring of pinned slots. A weight that fits one is laid out + * straight into it, and a larger one goes up a slot's worth at a time; each slot is waited + * for when the ring comes back round to it, not after every copy. */ + struct Bounce { + static constexpr int kSlots = 8; + static constexpr int64_t kSlot = 4ll << 20; + explicit Bounce(Uplink* up) : up_(up) {} + Uplink* up_; + void* buf = nullptr; + /* THE RELAYOUT'S OUTPUT for a weight larger than a slot, kept from one weight to the next + * up to kKeep -- the same page faults as the inputs' region saves, and a worker's own. */ + static constexpr int64_t kKeep = 256ll << 20; + std::unique_ptr out; + int64_t out_cap = 0; + /* An event a device, since an event belongs to the device it was made on; `live` is the + * device the slot's last copy went to. */ + struct Slot { std::vector ev; int live = -1; }; + Slot slot[kSlots]; + int next = 0; + ~Bounce() { + (void)flush(); + for (Slot& s : slot) + for (size_t d = 0; d < s.ev.size(); ++d) + if (s.ev[d]) { rad_dev_set((int)d); rad_event_destroy(s.ev[d]); } + if (buf) rad_dev_free(buf, RAD_MEM_HOST_PINNED); + } + /* The next slot, once the copy made out of it last time round has run. */ + int acquire(uint8_t** p) { + if (!buf) { + buf = rad_dev_alloc(kSlots * kSlot, RAD_MEM_HOST_PINNED); + if (!buf) return RAD_E_NOMEM; + } + Slot& s = slot[next]; + if (s.live >= 0) { + RAD_TRY(rad_event_sync(s.ev[(size_t)s.live])); + s.live = -1; + } + *p = (uint8_t*)buf + next * kSlot; + return RAD_OK; + } + /* The first `n` bytes of the slot acquire() handed out, up to `dst` on `device`. */ + int send(uint8_t* dst, int64_t n, int device) { + Slot& s = slot[next]; + RAD_TRY(rad_dev_set(device)); + if (s.ev.size() <= (size_t)device) s.ev.resize((size_t)device + 1, nullptr); + if (!s.ev[(size_t)device]) RAD_TRY(rad_event_create(&s.ev[(size_t)device])); + Uplink& u = up_[device]; + { + std::lock_guard lk(u.mu); + if (!u.st) RAD_TRY(rad_stream_create(&u.st, 0)); + RAD_TRY(rad_memcpy_async(dst, (uint8_t*)buf + next * kSlot, n, u.st)); + RAD_TRY(rad_event_record(s.ev[(size_t)device], u.st)); + } + s.live = device; + next = (next + 1) % kSlots; + return RAD_OK; + } + int upload(uint8_t* dst, const uint8_t* src, int64_t n, int device) { + for (int64_t off = 0; off < n;) { + const int64_t c = n - off < kSlot ? n - off : kSlot; + uint8_t* p = nullptr; + RAD_TRY(acquire(&p)); + std::memcpy(p, src + off, (size_t)c); + RAD_TRY(send(dst + off, c, device)); + off += c; + } + return RAD_OK; + } + /* Every copy this worker made has landed. */ + int flush() { + int st = RAD_OK; + for (Slot& s : slot) + if (s.live >= 0) { + const int w = rad_event_sync(s.ev[(size_t)s.live]); + if (w < 0 && st == RAD_OK) st = w; + s.live = -1; + } + return st; + } + }; + + void worker() { + Bounce b(uplinks_.get()); + for (;;) { + int i = -1; + Copy c{}; + bool cp = false; + { + std::unique_lock lk(mu_); + work_.wait(lk, [&] { return !copies_.empty() || !queue_.empty() || done_; }); + if (!copies_.empty()) { + c = copies_.front(); + copies_.pop_front(); + cp = true; + } else if (!queue_.empty()) { + i = queue_.front(); + queue_.pop_front(); + } else { + break; + } + } + if (cp) { + if (!failed_) take(c); + std::lock_guard lk(mu_); + --out_[(size_t)c.slot]; + drained_.notify_all(); + continue; + } + StagedWeight& s = items_[(size_t)i]; + if (!failed_) input(i); + const int st = failed_ ? RAD_E_STATE : run(s, b); + if (s.own) { delete[] s.in; s.in = nullptr; s.own = false; } + std::lock_guard lk(mu_); + if (s.in) give_back(s.in - region_, align_up(s.in_bytes, kHole)); + s.in = nullptr; + held_ -= s.in_bytes; + pending_ -= s.in_bytes; + if (st < 0 && !failed_) { failed_ = true; status_ = st; } + room_.notify_all(); + } + /* Its copies are still in flight: finish() returns once every worker's have landed. */ + const int fs = b.flush(); + std::lock_guard lk(mu_); + if (fs < 0 && !failed_) { failed_ = true; status_ = fs; } + } + + /* A staged weight's input, made by the first worker that needs it: the first copy into it, or + * the job that fills it from a checkpoint. The first hole that holds it. */ + uint8_t* input(int i) { + StagedWeight& s = items_[(size_t)i]; + std::call_once(once_[(size_t)i], [&] { + const int64_t n = align_up(s.in_bytes, kHole); + { + std::lock_guard lk(mu_); + for (auto it = holes_.begin(); it != holes_.end(); ++it) { + if (it->second < n) continue; + s.in = region_ + it->first; + if (it->second > n) holes_[it->first + n] = it->second - n; + holes_.erase(it); + return; + } + } + s.in = new uint8_t[(size_t)s.in_bytes]; + s.own = true; + }); + return s.in; + } + + /* Under the lock: [off, off + n) of the region is free again, merged with the holes either + * side of it. */ + void give_back(int64_t off, int64_t n) { + auto next = holes_.lower_bound(off); + if (next != holes_.end() && off + n == next->first) { + n += next->second; + next = holes_.erase(next); + } + if (next != holes_.begin()) { + auto prev = std::prev(next); + if (prev->first + prev->second == off) { prev->second += n; return; } + } + holes_[off] = n; + } + + /* One piece after another of the run, each the part of it the job's range holds: dense in + * the destination, a row of a column share at a time. */ + void take(const Copy& c) { + const LoadRun& q = c.q; + uint8_t* base = q.stage >= 0 ? input(q.stage) + (intptr_t)q.dst : q.dst; + int64_t got = 0; + for (int64_t y = c.j0 > q.foff && q.sp > 0 ? (c.j0 - q.foff) / q.sp : 0; y < q.ny; ++y) { + const int64_t ps = q.foff + y * q.sp; + if (ps >= c.j1) break; + const int64_t lo = ps > c.j0 ? ps : c.j0; + const int64_t hi = ps + q.wb < c.j1 ? ps + q.wb : c.j1; + if (hi <= lo) continue; + std::memcpy(base + y * q.wb + (lo - ps), c.win + (lo - c.w0), (size_t)(hi - lo)); + got += hi - lo; + } + if (q.stage >= 0 && got) arrived(q.stage, got); + } + + int run(StagedWeight& s, Bounce& b) { + const WeightInfo& w = s.prog->weights[s.wi]; + if (s.fill) { + const int fs = s.fill(s.in); + if (fs < 0) return fs; + } + /* STORED AS IT IS, which only a weight with no sweep reaches: its share goes up as read. */ + if (w.identity && !w.widen) { + const int64_t n = w.stored_bytes; + if (!s.dev) { std::memcpy(s.dst, s.in, (size_t)n); return RAD_OK; } + const int us = b.upload(s.dst, s.in, n, s.device); + if (us < 0) RAD_ERR("load: '%s': the upload to device %d failed: %s", w.name.c_str(), + s.device, rad_strerror(us)); + return us; + } + RadTensor pt[RAD_ENC_MAX_PLANES]; + weight_planes(w, pt); + for (int k = 0; k < w.n_sel; ++k) pt[k].data = s.in + s.plane_off[k]; + const int64_t n = w.stored_bytes; + std::unique_ptr tmp; + uint8_t* out = s.dst; + /* A weight that fits a slot is laid out in pinned memory the copy reads directly. */ + const bool in_slot = s.dev && n <= Bounce::kSlot; + if (in_slot) { + RAD_TRY(b.acquire(&out)); + } else if (s.dev && n > Bounce::kKeep) { + tmp.reset(new uint8_t[(size_t)n]); + out = tmp.get(); + } else if (s.dev) { + if (b.out_cap < n) { b.out.reset(new uint8_t[(size_t)n]); b.out_cap = n; } + out = b.out.get(); + } + + int st = RAD_OK; + const char* who = "the loader"; + if (w.widen) { + /* EXACT: every bf16 and f16 value is an f32. */ + const int64_t cnt = w.sel_rows[0] * w.sel_cols[0]; + if (cnt * 4 != n) st = RAD_E_SHAPE; + else for (int64_t e = 0; e < cnt; ++e) ((float*)out)[e] = rad_load_f32(pt[0].data, pt[0].dtype, e); + } else { + const Resolved& r = s.prog->ops[(size_t)w.lay_op].bands[(size_t)w.lay_band].dom[w.lay_dom]; + const RadKernelInfo* ki = r.row->info; + who = ki->name; + st = ki->relayout ? ki->relayout(r.geom.params(), r.geom.n_params(), w.lay_operand, + &w.enc, w.sel, pt, w.n_sel, out, n) + : RAD_E_UNSUPPORTED; + } + if (st < 0) { + char e[256]; + rad_enc_format(&w.enc, e, sizeof e); + RAD_ERR("load: %s could not produce '%s' (%s) from %s: %s", who, w.name.c_str(), + w.layout_tag.empty() ? "widened" : w.layout_tag.c_str(), e, rad_strerror(st)); + return st; + } + if (s.dev) { + st = in_slot ? b.send(s.dst, n, s.device) : b.upload(s.dst, out, n, s.device); + if (st < 0) RAD_ERR("load: '%s': the upload to device %d failed: %s", w.name.c_str(), + s.device, rad_strerror(st)); + } + return st; + } + + std::vector& items_; + std::unique_ptr once_; /* one an item: its input is made once */ + std::unique_ptr uplinks_; /* indexed by device */ + int n_uplinks_ = 0; + static constexpr int64_t kHole = 4096; /* every input starts on a page of its own */ + uint8_t* region_ = nullptr; + std::map holes_; /* the region's free ranges, offset -> bytes */ + std::vector threads_; + std::mutex mu_; + std::condition_variable work_, room_, drained_; + std::deque queue_; + std::deque copies_; + std::vector out_; /* copies outstanding out of each sweep window */ + int64_t budget_ = 0, held_ = 0, pending_ = 0, peak_ = 0; + bool done_ = false; + std::atomic failed_{false}; + int status_ = RAD_OK; +}; + +/* THE ONE PASS OVER THE CONTAINER, SERVING EVERY RANK. + * + * The runs arrive in declaration order, grouped by rank. Sorted by FILE OFFSET they become a + * single front-to-back sweep: read a window, hand it to every rank that asked for a piece of it, + * move on. That is three separate wins over reading per rank as the walk goes: + * + * - the file is read ONCE. A weight every rank wants -- every replicated weight, which is + * gigabytes on a large container -- would otherwise be read once per rank. + * - the reads are SEQUENTIAL. A declaration-order access pattern reads at a fraction of an + * NVMe disk's sequential rate; one thread reading front to back reaches it, and more threads + * do not help -- provided the reads go around the page cache. A buffered pread is the kernel + * copying every byte out of the cache into the window on this one thread, and that copy, + * not the disk, sets the rate: about two thirds of it alone, and half once the relayout + * pool's copies share the memory system. O_DIRECT lands the disk's DMA in the window itself. + * - the copies OVERLAP the reads. A ring of pinned windows, an event a rank on each: the read + * that fills one window runs while the copies out of the others are in flight -- the DMAs to + * the cards, and the pool's memcpys to host memory. Serialising them costs about a fifth of + * the load rate; waiting on the stream instead of on the event costs the same, because the + * stream also holds the copies this read was supposed to hide under. + * + * Host pinned memory is portable across devices in one process, so ONE window feeds every card: + * copying each window to all of them still runs at the disk's rate rather than the link's. */ +static int sweep_container(RadFile* file, std::vector& runs, + const std::vector& devices, RelayoutPool* pool, + int64_t* read_out) { + *read_out = 0; + if (runs.empty()) return RAD_OK; + + /* By where the bytes ARE, which is the whole idea: after this the runs are a reading order + * and no longer a rank order. The tie-break on span keeps the order total, so two builds of + * the same load issue their copies in the same sequence. */ + std::sort(runs.begin(), runs.end(), [](const LoadRun& a, const LoadRun& b) { + if (a.foff != b.foff) return a.foff < b.foff; + return a.span > b.span; + }); + + /* What the sweep will actually read, for the progress line: the union of the runs, which is + * NOT the sum of them at --tp 2 and not the size of the file either -- the mapped tier is in + * neither. */ + int64_t want_bytes = 0; + { + int64_t hi = -1; + for (const LoadRun& q : runs) { + const int64_t a = q.foff, b = a + q.span; + if (a > hi) { want_bytes += b - a; hi = b; } + else if (b > hi) { want_bytes += b - hi; hi = b; } + } + } + + int64_t window = 64 << 20; + if (const char* e = getenv("RADIANCE_LOAD_WINDOW_MIB")) { + const long long v = atoll(e); + if (v > 0) window = (int64_t)v << 20; + } + /* A window WIDE ENOUGH to hold one piece of a strided run, whatever the widest is. The + * slicing below is correct at any window -- a piece cut by a chunk boundary is copied in the + * two halves it falls in -- but a window narrower than a piece turns every piece into two + * copies instead of one 2D copy for a whole row group at a time. Nothing in this tree comes + * near 64 MiB in a piece: a column shard's piece is one row group of one rank's columns. */ + int64_t widest = 0; + for (const LoadRun& q : runs) if (q.ny > 1 && q.wb > widest) widest = q.wb; + if (widest > window) window = align_up(widest, 4096); + + /* READ THROUGH A GAP RATHER THAN BREAK THE STREAM FOR IT, up to a point. On an NVMe disk a + * megabyte of sequential read costs about what starting a fresh read costs, so bytes nobody + * asked for are cheaper than the break until there are a few million of them. The gaps that + * matter are whole tiers -- a mapped n-gram table is tens of gigabytes of one -- and those + * are nowhere near this bound, so the choice only ever costs a little and saves a lot. */ + const int64_t kGap = 4 << 20; + + /* SIX WINDOWS, because the host copies out of one are a worker's memcpy and not a DMA: a + * window a staged weight's piece sits in is free only when a worker has taken it, and the + * ring is how far the read may run ahead of them. Pieces are cut at kPiece so one window's + * worth spreads over several workers. */ + constexpr int kWin = 6; + constexpr int64_t kPiece = 8 << 20; + constexpr int64_t kBlk = DirectFile::alignment(); + DirectFile dio; + const size_t nr = devices.size(); + std::vector st(nr, nullptr); + std::vector ev(kWin * nr, nullptr); + std::vector live(kWin * nr, 0), touched(nr, 0); + void* buf[kWin] = {}; + pool->windows(kWin); + int64_t read_bytes = 0; + double read_s = 0; /* of the sweep's wall time, how much was the disk itself */ + + const int rc = [&]() -> int { + for (size_t k = 0; k < nr; ++k) { + /* A stream and an event both belong to the device that was current when they were + * made, and recording one on the other's stream is an error rather than a slow path. + * The COPIES need no such bind: a stream carries its own device. */ + RAD_TRY(rad_dev_set(devices[k])); + RAD_TRY(rad_stream_create(&st[k], 0)); + for (int b = 0; b < kWin; ++b) RAD_TRY(rad_event_create(&ev[(size_t)b * nr + k])); + } + /* O_DIRECT WANTS THE OFFSET, THE LENGTH AND THE BUFFER BLOCK-ALIGNED, and a chunk is + * wherever its runs put it: a window is read from the block below the chunk to the block + * above it, so it is two blocks wider than the chunk can be. A filesystem that refuses + * O_DIRECT is read through the cache instead, at the cache's rate. */ + RAD_TRY(dio.open(file->path(), RAD_DIO_READ | RAD_DIO_ALLOW_BUFFERED)); + for (int b = 0; b < kWin; ++b) { + buf[b] = rad_dev_alloc(window + 2 * kBlk, RAD_MEM_HOST_PINNED); + if (!buf[b]) { + RAD_ERR("load: no %s pinned staging window. The load needs %d of them; lower " + "RADIANCE_LOAD_WINDOW_MIB or free host memory.", + humanb(window).c_str(), kWin); + return RAD_E_NOMEM; + } + } + + int cur = 0; + + /* Read the chunk [c0, c1) into window `b`; `*at` is where its first byte landed. The + * blocks are whole up to the file's last full one, and a tail past that is the only read + * the bounce in DirectFile serves. Read buffered, the cache goes with the window: nothing + * comes back for a window the sweep has finished, and tens of gigabytes of dead pages + * turn into reclaim the reads then wait on. */ + const int64_t whole = file->size() / kBlk * kBlk; + auto fill = [&](int b, int64_t c0, int64_t c1, const uint8_t** at) -> int { + const auto t = std::chrono::steady_clock::now(); + const int64_t a0 = c0 / kBlk * kBlk; + const int64_t a1 = std::min(align_up(c1, kBlk), whole); + uint8_t* w = (uint8_t*)buf[b]; + if (a1 > a0) RAD_TRY(dio.read_at(w, a0, a1 - a0)); + if (c1 > a1) RAD_TRY(dio.read_at(w + (a1 - a0), a1, c1 - a1)); + read_s += std::chrono::duration(std::chrono::steady_clock::now() - t).count(); + read_bytes += c1 - c0; + if (!dio.direct()) file->drop_range(c0, c1 - c0); + *at = w + (c0 - a0); + return RAD_OK; + }; + + /* Hand one run the part of itself that lies in the staged chunk [c0, c1). + * + * A run is SLICED BY THE CHUNK rather than given a chunk of its own, and that is the + * whole reason the chunk is a file range and not a run. At --tp 2 a column-sharded weight + * is two runs over the same entry, half a row apart: served one run at a time the entry + * is read TWICE, so the sweep reads more bytes than the container holds; served as a + * range, both runs take their columns out of one read. + * + * The strided case keeps its 2D copy for every piece the chunk holds WHOLE, which is all + * of them but the two at the ends; a piece cut by a chunk boundary is the only thing that + * becomes a copy of its own. */ + auto one = [&](const LoadRun& q, uint8_t* dst, const uint8_t* src, int64_t len) -> int { + touched[(size_t)q.rank] = 1; + return rad_memcpy_async(dst, src, len, st[(size_t)q.rank]); + }; + auto many = [&](const LoadRun& q, uint8_t* dst, const uint8_t* src, int64_t n) -> int { + touched[(size_t)q.rank] = 1; + return rad_memcpy_2d_async(dst, q.wb, src, q.sp, q.wb, n, st[(size_t)q.rank]); + }; + auto issue = [&](const LoadRun& q, const uint8_t* win, int64_t c0, int64_t c1, + int slot) -> int { + /* A HOST DESTINATION IS A MEMCPY, and the pool's workers make it: a staged run into + * its weight's input, which tells the pool how much of it has arrived, and any other + * into its host pool slot. The sweep only reads. */ + if (q.stage >= 0 || !q.dev) { + if (pool->failed()) return RAD_E_STATE; + if (q.stage >= 0) pool->reserve(q.stage); + const int64_t a = q.foff > c0 ? q.foff : c0; + const int64_t z = q.foff + q.span < c1 ? q.foff + q.span : c1; + for (int64_t j0 = a; j0 < z; j0 += kPiece) + pool->copy({ win, c0, j0, j0 + kPiece < z ? j0 + kPiece : z, q, slot }); + return RAD_OK; + } + if (q.ny <= 1) { + const int64_t lo = q.foff > c0 ? q.foff : c0; + const int64_t hi = q.foff + q.wb < c1 ? q.foff + q.wb : c1; + if (hi <= lo) return RAD_OK; + return one(q, q.dst + (lo - q.foff), win + (lo - c0), hi - lo); + } + int64_t y = c0 > q.foff && q.sp > 0 ? (c0 - q.foff) / q.sp : 0; + while (y < q.ny) { + const int64_t ps = q.foff + y * q.sp; + if (ps >= c1) break; + const int64_t lo = ps > c0 ? ps : c0; + const int64_t hi = ps + q.wb < c1 ? ps + q.wb : c1; + if (hi <= lo) { ++y; continue; } + if (lo == ps && hi == ps + q.wb) { + int64_t n = 1; + while (y + n < q.ny && q.foff + (y + n) * q.sp + q.wb <= c1) ++n; + RAD_TRY(many(q, q.dst + y * q.wb, win + (ps - c0), n)); + y += n; + } else { + RAD_TRY(one(q, q.dst + y * q.wb + (lo - ps), win + (lo - c0), hi - lo)); + ++y; + } + } + return RAD_OK; + }; + /* The window about to be overwritten is still the source of the copies issued out of it + * a turn of the ring ago. Wait for THOSE, by event, and not for the stream: the stream + * also holds the other windows' copies, which are exactly what this read is meant to hide + * under. And for the pool's memcpys out of it. */ + auto acquire = [&](int b) -> int { + for (size_t k = 0; k < nr; ++k) + if (live[(size_t)b * nr + k]) { + RAD_TRY(rad_event_sync(ev[(size_t)b * nr + k])); + live[(size_t)b * nr + k] = 0; + } + pool->drain(b); + return RAD_OK; + }; + auto release = [&](int b) -> int { + for (size_t k = 0; k < nr; ++k) + if (touched[k]) { + RAD_TRY(rad_event_record(ev[(size_t)b * nr + k], st[k])); + live[(size_t)b * nr + k] = 1; + touched[k] = 0; + } + return RAD_OK; + }; + + const auto t0 = std::chrono::steady_clock::now(); + int64_t last_note = 0; + /* A LOAD THAT STOPS HAS TO SAY WHERE. This names a file offset, which `rad-info -v` turns + * back into a weight -- the only way to localise a stall inside the sweep. Coarse by + * default because the sweep is seconds long; RADIANCE_DEBUG_LOAD_EVERY_MIB=64 is the + * fine-grained trail. */ + int64_t kNoteEvery = 8LL << 30; + if (const char* e = getenv("RADIANCE_DEBUG_LOAD_EVERY_MIB")) { + const long long v = atoll(e); + if (v > 0) kNoteEvery = (int64_t)v << 20; + } + size_t i = 0; + while (i < runs.size()) { + /* THE GROUP IS A STRETCH OF FILE, NOT A RUN. Every run that chains to this one within + * kGap belongs to the same read stream, however many ranks and however many weights + * that is, and however far it reaches: a group larger than a window is read in + * windows, not abandoned to a path of its own. */ + const int64_t g0 = runs[i].foff; + int64_t g1 = g0 + runs[i].span; + size_t j = i + 1; + for (; j < runs.size(); ++j) { + if (runs[j].foff - g1 > kGap) break; + const int64_t end = runs[j].foff + runs[j].span; + if (end > g1) g1 = end; + } + + /* `lo` is the first run that has not finished. Sorted by offset, a run whose last + * byte is behind the chunk is behind it for good, so the scan never goes backwards + * and each run is looked at once per chunk it reaches into. */ + size_t lo = i; + for (int64_t c0 = g0; c0 < g1; ) { + const int64_t c1 = g1 < c0 + window ? g1 : c0 + window; + RAD_TRY(acquire(cur)); + const uint8_t* win = nullptr; + RAD_TRY(fill(cur, c0, c1, &win)); + while (lo < j && runs[lo].foff + runs[lo].span <= c0) ++lo; + for (size_t k = lo; k < j && runs[k].foff < c1; ++k) + RAD_TRY(issue(runs[k], win, c0, c1, cur)); + RAD_TRY(release(cur)); + cur = (cur + 1) % kWin; + c0 = c1; + + if (read_bytes - last_note >= kNoteEvery) { + last_note = read_bytes; + const double s = std::chrono::duration( + std::chrono::steady_clock::now() - t0).count(); + RAD_INFO("load: %s of %s read, %.1f GB/s, at container offset %lld", + humanb(read_bytes).c_str(), humanb(want_bytes).c_str(), + read_bytes / (s > 0 ? s : 1) / 1e9, (long long)c0); + } + } + i = j; + } + + /* The last host synchronisation before serving: after this the step path never waits on + * the host again (spec §5.4). */ + for (size_t k = 0; k < nr; ++k) RAD_TRY(rad_stream_sync(st[k])); + for (int b = 0; b < kWin; ++b) pool->drain(b); + + const double s = std::chrono::duration( + std::chrono::steady_clock::now() - t0).count(); + /* THE SPLIT IS THE DIAGNOSTIC. If the disk time is the whole of the wall time the sweep + * is at the drive's ceiling and there is nothing here to win; what is left over is the + * copies that did not hide under a read -- the host-tier memcpy, which is synchronous, + * and the per-run issue loop. */ + RAD_INFO("load: one pass over the container, %s read in %.1f s (%.1f GB/s) for %zu " + "rank(s); %.1f s of that was the disk (%.1f GB/s)", + humanb(read_bytes).c_str(), s, read_bytes / (s > 0 ? s : 1) / 1e9, nr, + read_s, read_bytes / (read_s > 0 ? read_s : 1) / 1e9); + return RAD_OK; + }(); + + /* AND THE PAGE CACHE GOES BACK. Weights that will never be read from the file again are cache + * the mapped tier cannot use: a mapped n-gram table is read from its mapping for the life of + * the process, and it is the one thing here that wants the cache. What this frees is worth + * more to the model than to the loader. */ + file->drop_blob_cache(); + /* NOT FREED UNDER A WORKER: a sweep that failed part-way may have left copies out of them. */ + for (int b = 0; b < kWin; ++b) pool->drain(b); + for (int b = 0; b < kWin; ++b) if (buf[b]) rad_dev_free(buf[b], RAD_MEM_HOST_PINNED); + for (size_t k = 0; k < ev.size(); ++k) if (ev[k]) rad_event_destroy(ev[k]); + for (size_t k = 0; k < nr; ++k) if (st[k]) rad_stream_destroy(st[k]); + *read_out = read_bytes; + return rc; +} + +/* One rank's share of a checkpoint weight's selected planes, read out of the mapped tensors into + * `in` at the offsets the pool laid out: whole rows as one read, a column share a block of rows at + * a time with the bytes it owns taken out of each. A whole plane declared under another shape (a + * reshape) is the same bytes, so it is read in the checkpoint's own rows. */ +static int fill_from_checkpoint(const CkptWeight& cw, const std::vector& shares, + const std::vector& sel, const std::vector& offs, + const std::string& name, uint8_t* in) { + std::vector rows; + std::string why; + for (size_t k = 0; k < shares.size(); ++k) { + const PlaneShare& sh = shares[k]; + const RadEncPlane& p = cw.enc.plane[sel[k]]; + int64_t pr = 0, pc = 0; + rad_enc_plane_dims(&p, cw.rows, cw.cols, &pr, &pc); + const int64_t crb = rad_enc_row_bytes(p.dtype, pc); + uint8_t* at = in + offs[k]; + for (const PlaneShare::Rect& q : sh.rects) { + if (q.byte0 == 0 && q.bytes == sh.row_bytes) { + const int64_t off = q.row0 * sh.row_bytes, n = q.rows * sh.row_bytes; + if (crb <= 0 || off % crb || n % crb) { + RAD_ERR("load: '%s': rows [%lld, %lld) of its '%s' plane do not fall on the " + "checkpoint's rows", name.c_str(), (long long)q.row0, + (long long)(q.row0 + q.rows), p.role); + return RAD_E_SHAPE; + } + if (ckpt_plane_rows(cw, sel[k], off / crb, n / crb, at, &why) != RAD_OK) { + RAD_ERR("load: '%s': %s", name.c_str(), why.c_str()); + return RAD_E_FORMAT; + } + at += n; + continue; + } + const int64_t step = std::max(1, (64ll << 20) / std::max(crb, 1)); + for (int64_t r0 = 0; r0 < q.rows; r0 += step) { + const int64_t nr = std::min(step, q.rows - r0); + rows.resize((size_t)(nr * crb)); + if (ckpt_plane_rows(cw, sel[k], q.row0 + r0, nr, rows.data(), &why) != RAD_OK) { + RAD_ERR("load: '%s': %s", name.c_str(), why.c_str()); + return RAD_E_FORMAT; + } + for (int64_t r = 0; r < nr; ++r) { + std::memcpy(at, rows.data() + r * crb + q.byte0, (size_t)q.bytes); + at += q.bytes; + } + } + } + } + return RAD_OK; +} + +int Engine::load_weights() { + int64_t total = 0, n_loaded = 0, n_missing = 0; + /* Counted apart from `n_loaded` because it is not a load: mapped weights are published where + * they already lie, and reporting their bytes as moved would credit the load with tens of + * gigabytes of work it did not do. */ + int64_t n_mapped = 0, mapped_bytes = 0; + + /* THE WALK AND THE READING ARE TWO PHASES. + * + * A loop over RANKS, each walking the whole weight list and reading as it goes, reads the + * container once per rank, in declaration order, one pread to a weight -- a fraction of the + * disk's sequential rate, and more bytes read than placed, because every replicated weight is + * read once per rank. + * + * So the walk below decides everything -- which rank wants which bytes, where they land, + * what has to be refused -- and writes it down without touching the disk. sweep_container + * then sorts what it wrote by file offset and reads the container once, front to back, + * handing each window to every rank that asked for a piece of it. */ + std::vector runs; + std::vector staged; + int64_t n_out = 0; /* destination overruns reported, capped */ + + /* ============================================================== the walk */ + for (auto& r : ranks_) { + LogRank lr(r->index); + /* Bound before anything is allocated for this rank: rad_dev_alloc has no device argument + * and takes whatever is current, so the mover's slabs would otherwise all land on card 0. + * See plan() for the same bind and the same reason. */ + RAD_TRY(rad_dev_set(r->device)); + + /* THE CONTAINER IS THE FILE TIER, and the mover has to be told so. `--weights-disk-tier` makes + * the planner place units on Tier::SSD, and a bare `MoverConfig{}` then dies in + * Mover::init with "the plan put weights on the file tier but no container path was + * given" -- after the plan has already been made. The mover reads THIS file with O_DIRECT + * rather than a copy of it: the weights are already + * here, RAD_ALIGN_UNIT-aligned (rad_format.h), which is DirectFile's alignment exactly, + * so a stage takes the no-bounce path. */ + MoverConfig mc{}; + mc.container_path = file_ ? cfg_.model : std::string(); + RAD_TRY(r->mover.init(r->program, r->plan, mc, &r->pools)); + /* WHAT THE MOVER TOOK, said before the first copy. The slabs are allocated in init, so by + * here the pool is as full as it will get -- the copy loop writes into slots that already + * exist and moves the cursor no further. A load that stops with the pool at zero free is + * a placement failure wearing a loader's costume, and this line is what tells the two + * apart from the outside. */ + RAD_INFO("load: rank %d, mover took %s, weights pool %s free of %s", r->index, + humanb(r->pools.weights().used()).c_str(), + humanb(r->pools.weights().avail()).c_str(), + humanb(r->pools.weights().used() + r->pools.weights().avail()).c_str()); + + /* THE POLICY HALF, BOUND TO THE SAME PLAN. It returns RAD_OK on a static plan and reports + * `enabled() == false`, which is a mode and not a failure -- all_vram and + * --deterministic both land there -- so there is nothing to branch on here. */ + RAD_TRY(r->heat.init(r->plan, HeatParams{})); + + /* A DESTINATION HAS TO LIE INSIDE THE POOL IT WAS CARVED FROM. A slot pointer that runs + * past the end of the weights pool is a write to device memory the process does not own, + * and on this driver that does not fault -- the copy is accepted, never completes, and + * the host thread spins inside the runtime with the copy engine idle and no I/O. It looks + * exactly like a hang, and it moves with --vram-weights-mib because a bigger pool is a + * later overrun. Cheap enough to check on every copy, and checked before any of them + * start rather than as each one is issued. */ + const uint8_t* wp_lo = (const uint8_t*)r->pools.weights().base(); + const uint8_t* wp_hi = wp_lo + r->pools.weights().bytes(); + auto dst_fits = [&](const void* p, int64_t len, const char* nm) { + const uint8_t* q = (const uint8_t*)p; + if (!wp_lo || (q >= wp_lo && q + len <= wp_hi)) return true; + if (++n_out <= 8) + RAD_ERR("rank %d: '%s' writes %lld bytes at %p, which is outside the %s weights " + "pool [%p, %p). The slot was carved from somewhere else, or past the end.", + r->index, nm, (long long)len, p, + humanb(r->pools.weights().bytes()).c_str(), (const void*)wp_lo, + (const void*)wp_hi); + return false; + }; + + /* AND THE SOURCE OF A SHARE HAS TO LIE INSIDE ITS PLANE. Every offset below is computed + * from the rank index, so rank 0 cannot exercise the arithmetic at all -- whatever the + * shape is, it reads from the start of the plane. An offset that runs off the end is a + * read of the wrong weight, or of nothing at all, so it is checked, not trusted. */ + const int64_t file_bytes = file_ ? file_->size() : 0; + + for (size_t i = 1; i < r->program.weights.size(); ++i) { + WeightInfo& w = r->program.weights[i]; + /* WHERE ITS PLANES ARE: a container entry, or the checkpoint tensors declare resolved + * it to. Either way the encoding and the logical shape the share is cut in. */ + const RadFileEntry* e = file_ ? file_->find(w.source) : nullptr; + const CkptWeight* cw = ckpt_src_ ? ckpt_src_->find(w.source) : nullptr; + if (!e && !cw) { + if (w.decl.optional) continue; + const std::string why = ckpt_src_ ? ckpt_src_->missing(w.source) : std::string(); + if (!why.empty()) + RAD_ERR("rank %d: '%s' was declared over '%s', and %s", r->index, + w.name.c_str(), w.source.c_str(), why.c_str()); + else + RAD_ERR("rank %d: '%s' was declared over '%s', which is not in %s", + r->index, w.name.c_str(), w.source.c_str(), cfg_.model.c_str()); + ++n_missing; + continue; + } + const RadEncoding& src_enc = e ? file_->encoding(*e) : cw->enc; + const uint32_t src_rank = e ? e->rank : cw->rank; + const int64_t* src_shape = e ? e->shape : cw->shape; + + /* THE ENCODING THE KERNELS WERE CHOSEN FOR IS THE ONE THE SOURCE HOLDS. Declare asked + * it (rad_weight_encoding) and every layout hook answered for that encoding, so a + * difference here is a declaration that was made against something else -- refused + * by name rather than relaid as if it were the same weight. */ + if (!rad_enc_equal(&src_enc, &w.enc)) { + char want[256], have[256]; + rad_enc_format(&w.enc, want, sizeof want); + rad_enc_format(&src_enc, have, sizeof have); + RAD_ERR("rank %d: '%s' was declared against '%s' as %s, and %s holds it as %s", + r->index, w.name.c_str(), w.source.c_str(), want, cfg_.model.c_str(), + have); + return RAD_E_FORMAT; + } + + /* THE PLANNER'S DECISION HAS TO LAND ON WeightInfo, and this is where it lands. + * + * WeightInfo::tier/site/slab_slot say "Filled by the planner (spec §5.3)" and the + * planner's own finish() says it is "the component that fills these three" -- but + * what it fills is Plan::weight[], a parallel array. Leaving the two apart is silent + * in both directions: + * + * - Ctx::bind_weights picks RAD_DOMAIN_HOST only when EVERY weight operand of an op + * has site == Site::Host. Left at the default Site::Device that test can never + * pass, so host-site execution is unreachable and the planner's whole + * "contiguous host runs" objective lands nowhere -- layer offload becomes dead + * code that still passes its tests. + * - a file-tier weight is skipped below on `tier == Tier::SSD` read off the PLAN, + * so the two spellings of the same fact would disagree right here. + * + * file_offset is the same story one layer down: Mover::stage reads it to pread the + * container, and left unset every SSD stage reads offset 0 -- the file header -- for + * every weight. It is the selected plane's, and only a weight read where it lies ever + * uses it (weight_file_direct). + * + * Set before the residency lookup, not after: a file-tier weight has no address yet + * and takes the `continue` below, and it is precisely the one that needs the offset. */ + w.tier = r->plan.weight[i].tier; + w.site = r->plan.weight[i].site; + w.slab_slot = r->plan.weight[i].slab_slot; + w.file_offset = e ? file_->plane(*e, w.sel[0]).offset : 0; + const bool direct = weight_file_direct(w, cfg_.tp); + if ((w.tier == Tier::Mapped || w.tier == Tier::SSD) && (!direct || !e)) { + RAD_ERR("rank %d: '%s' was placed on the %s tier, which reads the container where " + "it lies, and its stored form is not the container's (%s)", r->index, + w.name.c_str(), tier_name(w.tier), + w.widen ? "widened at load" : w.identity ? "a shard of it" + : w.layout_tag.c_str()); + return RAD_E_STATE; + } + + /* THE MAPPED TIER IS A PUBLISH AND NOT A LOAD. The bytes are already at a host + * address -- the container is mmapped and stays mapped for the life of the engine + * (core/format/radfile.cpp) -- so there is nothing to copy and no pool to copy into. + * This is the only weight class the load phase does not move, and the sweep below + * never reads a byte of it -- which on a container with a large mapped table is most + * of the file. + * + * IT HAS TO GO THROUGH THE RESIDENCY TABLE and not only onto WeightInfo::ptr, because + * Ctx::resolve_weight reads the table whenever a mover exists and would otherwise + * find the null the mover published for a unit with no slab class. */ + if (w.tier == Tier::Mapped) { + const RadFilePlane& p0 = file_->plane(*e, w.sel[0]); + const int64_t n = (int64_t)p0.bytes; + if (n != w.stored_bytes) { + RAD_ERR("'%s': the container's '%s' plane has %lld bytes, the declaration " + "wants %lld", w.name.c_str(), file_->encoding(*e).plane[w.sel[0]].role, + (long long)n, (long long)w.stored_bytes); + return RAD_E_FORMAT; + } + w.ptr = (void*)file_->data(p0); + w.host_ptr = w.ptr; + /* NO READAHEAD ON A MAPPED WEIGHT. What reads one is a host kernel gathering rows + * out of it, and the only reason a weight is on this tier at all is that it is far + * too big to be resident -- so a fault is a real read from the file and the pages + * around it are pages nobody asked for. Linux's default 128 KiB readahead turns a + * row of a few hundred bytes into 32 pages of I/O, and at a dozen rows a token + * that is megabytes read to use kilobytes. MADV_RANDOM is the whole of the + * correction and it is per range, so the rest of the container keeps the + * sequential behaviour the load pass wants. + * + * IT SHOWS NOTHING ON A WARM PAGE CACHE. When the hot part of the table is + * already resident the serving process reads nothing from disk and the advice + * changes no timing at all; the regime it protects -- a table genuinely colder + * than RAM -- is the regime this tier exists for, and it costs one syscall at + * load. What shows its effect is a cold cache and a byte counter, not a + * stopwatch. */ + posix_madvise(w.ptr, (size_t)n, POSIX_MADV_RANDOM); + r->mover.publish_mapped((rad_weight)i, w.ptr); + ++n_mapped; + mapped_bytes += n; + continue; + } + + const WeightSlot* slot = r->mover.residency()->lookup((rad_weight)i); + if (!slot || !slot->ptr) { + /* A file-tier unit has no address until the mover stages it, which is correct and + * not an error: RAD_ACCESS_RARE weights are read on demand (spec §5.2). */ + if (w.tier == Tier::SSD) continue; + RAD_ERR("rank %d: '%s' has no address after mover init", r->index, w.name.c_str()); + return RAD_E_STATE; + } + + /* THE ADDRESS HAS TO LAND ON WeightInfo, not only in the residency table. In the + * all-in-VRAM case Ctx is built with a NULL residency -- the mover never runs, so + * there is nothing to look up per issue -- and `Ctx::resolve_weight` collapses to + * `WeightInfo::ptr` (core/runtime/issue.cpp says exactly that). Leaving it null + * leaves every weight in the program unbound at issue, which the run phase reports as + * "weight 'x' has no pointer at issue: the load phase never bound it" -- the load + * having copied the whole model into addresses nothing afterwards can name. + * `generation` is not bumped because `bind_weights` runs for the first time after + * this, in Ctx::init. */ + w.ptr = slot->ptr; + + /* HOST-POOL DESTINATIONS STAY A memcpy. The host pool is pinned and device-mapped + * (core/mem/pools.cpp), so the copy engine CAN write it, and the synchronous + * host-tier memcpy is most of what separates this sweep from the disk's own rate -- + * which makes putting those copies on the stream look as though it would hide them + * under the next read. It does not: an async host-to-host copy is not a DMA on this + * stack, it is the same memcpy with a stream in front of it. */ + const bool dev = w.tier == Tier::VRAM; + if (dev && !dst_fits(slot->ptr, w.stored_bytes, w.name.c_str())) return RAD_E_STATE; + + /* THIS RANK'S SHARE OF THE SELECTED PLANES, cut on the canonical form where a ROW + * shard is rows of every plane and a COL shard is columns -- each on the plane's own + * block boundary, and refused where a block or a byte would be split. */ + PlaneShare sh[RAD_ENC_MAX_PLANES]; + std::string why; + if (weight_share(w, src_enc, src_rank, src_shape, cfg_.tp, r->index, sh, &why) != + RAD_OK) { + RAD_ERR("rank %d: '%s' at --tp %d: %s", r->index, w.name.c_str(), cfg_.tp, + why.c_str()); + return RAD_E_SHAPE; + } + + /* FROM A CHECKPOINT, every weight is staged and its worker reads it: there is no + * sweep to deliver it, and the stored form is whatever the pool makes of the share -- + * as it is, widened, or relaid. */ + if (!e) { + StagedWeight sw; + sw.prog = &r->program; + sw.wi = i; + sw.device = r->device; + sw.dst = (uint8_t*)slot->ptr; + sw.dev = dev; + int64_t in_bytes = 0; + for (int k = 0; k < w.n_sel; ++k) { + sw.plane_off[k] = in_bytes; + in_bytes += align_up(sh[k].dense_bytes(), 64); + sw.remaining += sh[k].dense_bytes(); + total += sh[k].dense_bytes(); + } + sw.in_bytes = in_bytes; + if (w.identity && !w.widen && sh[0].dense_bytes() != w.stored_bytes) { + RAD_ERR("rank %d: '%s': this rank's share is %lld bytes and the slot %lld", + r->index, w.name.c_str(), (long long)sh[0].dense_bytes(), + (long long)w.stored_bytes); + return RAD_E_FORMAT; + } + std::vector shares(sh, sh + w.n_sel); + std::vector sel(w.sel, w.sel + w.n_sel); + std::vector offs(sw.plane_off, sw.plane_off + w.n_sel); + const std::string name = w.name; + sw.fill = [cw, shares, sel, offs, name](uint8_t* in) -> int { + return fill_from_checkpoint(*cw, shares, sel, offs, name, in); + }; + staged.push_back(std::move(sw)); + ++n_loaded; + continue; + } + + /* STORED AS IT IS: the share goes from the file to the slot. Otherwise it is staged + * whole for the relayout pool, plane after plane, and the pool writes the slot. */ + int32_t stage = -1; + int64_t in_bytes = 0; + if (!w.identity || w.widen) { + stage = (int32_t)staged.size(); + staged.emplace_back(); + StagedWeight& sw = staged.back(); + sw.prog = &r->program; + sw.wi = i; + sw.device = r->device; + sw.dst = (uint8_t*)slot->ptr; + sw.dev = dev; + for (int k = 0; k < w.n_sel; ++k) { + sw.plane_off[k] = in_bytes; + in_bytes += align_up(sh[k].dense_bytes(), 64); + } + sw.in_bytes = in_bytes; + sw.remaining = 0; + for (int k = 0; k < w.n_sel; ++k) sw.remaining += sh[k].dense_bytes(); + } else if (sh[0].dense_bytes() != w.stored_bytes) { + RAD_ERR("rank %d: '%s': this rank's share is %lld bytes and the slot %lld", + r->index, w.name.c_str(), (long long)sh[0].dense_bytes(), + (long long)w.stored_bytes); + return RAD_E_FORMAT; + } + for (int k = 0; k < w.n_sel; ++k) { + const RadFilePlane& pk = file_->plane(*e, w.sel[k]); + int64_t doff = stage >= 0 ? staged[(size_t)stage].plane_off[k] : 0; + for (const PlaneShare::Rect& q : sh[k].rects) { + const int64_t foff = (int64_t)pk.offset + q.row0 * sh[k].row_bytes + q.byte0; + const int64_t len = (q.rows - 1) * sh[k].row_bytes + q.bytes; + if (q.rows <= 0) continue; + if (foff < 0 || foff + len > file_bytes || + foff + len > (int64_t)(pk.offset + pk.bytes)) { + RAD_ERR("rank %d: '%s' would read [%lld, %lld), outside its '%s' plane " + "[%llu, %llu)", r->index, w.name.c_str(), (long long)foff, + (long long)(foff + len), file_->encoding(*e).plane[w.sel[k]].role, + (unsigned long long)pk.offset, + (unsigned long long)(pk.offset + pk.bytes)); + return RAD_E_FORMAT; + } + uint8_t* dst = stage >= 0 ? (uint8_t*)(intptr_t)doff : (uint8_t*)slot->ptr + doff; + const bool dense = q.byte0 == 0 && q.bytes == sh[k].row_bytes; + if (dense) + runs.push_back(LoadRun{ foff, q.rows * q.bytes, dst, q.rows * q.bytes, + q.rows * q.bytes, 1, r->index, + stage >= 0 ? 0 : (dev ? 1 : 0), stage }); + else + runs.push_back(LoadRun{ foff, len, dst, q.bytes, sh[k].row_bytes, q.rows, + r->index, stage >= 0 ? 0 : (dev ? 1 : 0), stage }); + total += q.rows * q.bytes; + doff += q.rows * q.bytes; + } + } + ++n_loaded; + } + } + + if (n_missing) { + RAD_ERR("%lld declared weights are absent from the container. Reported whole rather than " + "first-failure-at-the-top; the model cannot run.", (long long)n_missing); + return RAD_E_NOTFOUND; + } + + /* ============================================================== the sweep */ + std::vector devices; + devices.reserve(ranks_.size()); + for (auto& r : ranks_) devices.push_back(r->device); + int64_t read_bytes = 0; + int64_t staged_bytes = 0; + for (const StagedWeight& sw : staged) staged_bytes += sw.in_bytes; + RelayoutPool pool(staged); + const unsigned hw = std::thread::hardware_concurrency(); + /* Started whatever is staged: a host pool slot is filled by the same workers. */ + const int workers = (int)std::max(2u, std::min(16u, hw > 2 ? hw - 2 : 2u)); + pool.start(workers, std::max(4ll << 30, 0)); + const auto rt0 = std::chrono::steady_clock::now(); + int sw_st = RAD_OK; + if (file_) { + sw_st = sweep_container(file_.get(), runs, devices, &pool, &read_bytes); + } else { + /* every weight to the workers, in declaration order, as fast as the budget lets them in */ + for (size_t k = 0; k < staged.size() && !pool.failed(); ++k) { + const int64_t n = staged[k].remaining; + pool.reserve((int)k); + pool.arrived((int)k, n); + read_bytes += n; + } + } + const int pool_st = pool.finish(); + RAD_TRY(sw_st); + RAD_TRY(pool_st); + if (!staged.empty() && file_) + RAD_INFO("load: %zu weight(s), %s of planes, rearranged for their kernels by %d worker(s) " + "behind the read, %s held at most; done %.1f s after the read began", + staged.size(), humanb(staged_bytes).c_str(), workers, humanb(pool.peak()).c_str(), + std::chrono::duration(std::chrono::steady_clock::now() - rt0).count()); + else if (!staged.empty()) + RAD_INFO("load: %zu weight(s), %s, read out of the checkpoint and laid out for their " + "kernels by %d worker(s), %s held at most, in %.1f s", staged.size(), + humanb(staged_bytes).c_str(), workers, humanb(pool.peak()).c_str(), + std::chrono::duration(std::chrono::steady_clock::now() - rt0).count()); + + RAD_INFO("load: %lld weights, %s placed from %s of %s read", (long long)n_loaded, + humanb(total).c_str(), humanb(read_bytes).c_str(), + file_ ? "container" : "checkpoint"); + if (n_mapped) + /* THE BYTES ARE SHARED BETWEEN RANKS and the counters are not: every rank maps the same + * file, so at --tp 2 this counts one mapped table twice. Said rather than halved, + * because what the number IS is the sum of the mappings -- and an operator reading it as + * memory would size a box for twice what the model needs. */ + RAD_INFO("load: %lld weight(s), %s, read in place from the container's mapping -- not " + "copied and charged to no pool%s", (long long)n_mapped, + humanb(mapped_bytes).c_str(), + cfg_.tp > 1 ? " (summed over ranks, which map the same file: the resident bytes " + "are that divided by --tp)" : ""); + return RAD_OK; +} + +/* ================================================================== 6b. KV pools */ +/* The block manager owns every KV group's memory -- paged attention caches, the GDN recurrent + * states and the conv windows alike -- because two allocators disagreeing about what a sequence + * owns is not a leak but the bug where a freed sequence's state slot is handed to the next + * request while the first is still reading it (spec §7.2). + * + * This runs after load, not before, because it takes what the weight pool LEFT. It has to be + * before Ctx::init: a Ctx built without these bindings resolves every RAD_OPK_KV operand to null, + * and the first attention kernel of the first step dereferences it. */ +int Engine::configure_kv() { + /* THE ANCHOR IS A PROPERTY OF THE POOL, SO THE POOL'S OWNER TURNS IT ON. libr4d's recurrent + * update can keep one committed state a sequence and replay the accepted prefix onto it out + * of a scratch slot, instead of writing a full state per candidate token -- 2 slots a + * sequence against 1 + n_spec, which at a realistic depth is several times less. It is off by + * default because it is NOT PAGED: it assumes a sequence's state stays in the slot it was + * given, which is true of radiance's linear pool and is not true of vLLM's, and the two + * callers share the kernel. Set before any kernel runs; libr4d reads it once. + * + * The engine's half of the bargain is KVGroupPlan::state_copies (core/mem/kv.cpp): two slots + * a sequence, both zeroed on admission, named by a state_index row wide enough to reach + * them. Without speculation there is nothing to defer and the plain path is both correct and + * one slot cheaper. */ + /* Overwrite 0, so an operator can still set it -- but the two settings are NOT both runnable at + * every depth. Per-candidate indexing needs `1 + n_spec` distinct slots and this pool has two, + * so at a draft depth above one it gives several candidate tokens the same slot: a partially + * accepted step then resumes from a state one or more tokens too far along, silently, in a + * cache nothing reads back. The arch declares `state_form` on the op from the same condition + * below, and libr4d refuses the form that disagrees with the declaration -- so an override that + * would corrupt is a selection error naming the kernel and the geometry, rather than a + * generation that drifts. */ + if (cfg_.n_spec > 0) setenv("RADIANCE_GDN_ANCHOR", "1", 0); + /* Resolved once, for the cache below and for Scheduler::init later. Resolving it separately in + * each is how the two come to disagree, and the interval is the field where that shows. */ + RAD_TRY(chunk_geometry_resolve(ranks_[0]->program, cfg_, &geo_)); + for (auto& r : ranks_) { + LogRank lr(r->index); + RAD_TRY(rad_dev_set(r->device)); /* allocates on the CURRENT device; see plan() */ + RAD_TRY(r->kv.configure(r->program.kv_groups, cfg_, r->pools.kv())); + /* THE ONE CASE WHERE THE CACHE CANNOT GIVE ANYTHING BACK, said once and named. Every + * caller is written against the elastic contract and runs unchanged here -- the pool + * simply holds its whole carve -- so nothing fails, and the only symptom is an expert + * plane that never grows and a split that stays where --expert-vs-cache-ratio put it. + * That is worth a line, because it is indistinguishable from a working run in every + * counter this engine reports. */ + if (r->index == 0 && !r->pools.kv().elastic()) + RAD_WARN("this device has no virtual memory management, so the KV cache holds its " + "whole carve and the expert slab has nothing to grow into. The split stays " + "where --expert-vs-cache-ratio put it."); + if (cfg_.debug_placement) fputs(r->kv.report().c_str(), stderr); + RAD_TRY(r->prefix.configure(cfg_, &r->kv, geo_.checkpoint_interval)); + } + + /* ---------------- the idle session tiers (spec §7.3) ---------------- */ + /* AFTER the prefix cache, because the tiers are sized in units of ONE CACHE ENTRY and only the + * configured cache knows which groups an entry covers. No memory is committed unless an + * operator gave a tier a size: a tier of zero bytes holds nothing, so the two inactivity + * thresholds are ordinary defaults rather than a commitment of memory nobody asked to spend. + * + * CONFIGURED EVEN SO, because this object is also where a stored conversation is RECORDED, + * and that is not a tiering fact. A server with no --prefix-cache-host-mib holds its whole prefix + * cache in VRAM and holds it for exactly as long; skipping the configure would leave the + * sessions view reading an unconfigured object and reporting an empty server, on every + * deployment that has not opted into demotion. What the flags gate is the MOVER, below. */ + { + const bool tier_asked = cfg_.prefix_cache_host_mib > 0 || cfg_.prefix_cache_disk_mib > 0; + const std::vector& cg = ranks_[0]->prefix.cached_groups(); + int64_t entry_bytes = 0; + for (int32_t g : cg) { + const KVGroupPlan* p = ranks_[0]->kv.plan(g); + if (p && p->paged()) entry_bytes += p->bytes_per_block; + } + /* ONE SLOT HOLDS EVERY RANK'S SHARD. An entry under tensor parallelism is n_ranks + * pieces of KV that are not interchangeable, so the unit the tiers store and budget + * in is the whole thing; each rank writes only its own window of it. */ + const int64_t slot_bytes = entry_bytes * (int64_t)ranks_.size(); + + /* ---- how the tier is split between the two halves of a session ---- + * + * ON THIS BUILD A RESTORED HYBRID SESSION WITH NO SNAPSHOT REUSES NOTHING AT ALL. The + * scheduler clamps its reuse to the last reachable checkpoint and says why: RadBatch + * carries one query length for every KV group, so the linear layers cannot be replayed + * over a longer range than the attention layers, and the correct answer is to recompute + * from the checkpoint (core/sched/scheduler.cpp, admit_one). A session whose blocks came + * back and whose state did not therefore gets a hit of ZERO -- the blocks are not a + * partial win, they are unusable -- and the snapshot store is not a nice-to-have beside + * the block store, it is the thing that decides whether any of this works. + * + * So the split is DERIVED, from the session the operator sized the server for. At + * --max-model-len M a session costs + * + * blocks (M / block_size) * slot_bytes + * snapshots (log2(M / interval) + 1) * ck_slot_bytes [geometric backoff] + * + * and splitting the cap in that ratio makes both halves hold the same NUMBER OF SESSIONS, + * which is the only sense in which they can be balanced. The ratio is strongly length + * dependent -- snapshots want 22% of the tier at 200K and more than half at 32K, because + * the retained set grows logarithmically while the blocks grow linearly -- which is + * exactly why a single fixed fraction is the wrong shape. + * + * Two thirds is the ceiling. Not because the arithmetic asks for one, but because the + * clamp above is a property of THIS build rather than of the design, and a tier with + * almost no room for blocks would be badly sized the day it is lifted. */ + const int64_t ck_slot_bytes = ranks_[0]->kv.checkpoint_bytes() * (int64_t)ranks_.size(); + int64_t ck_host_cap = 0, ck_disk_slots = 0; + if (ck_slot_bytes > 0) { + const int64_t bs = ranks_[0]->prefix.block_size(); + const int64_t iv = ranks_[0]->prefix.checkpoint_interval(); + /* The session the server was sized for: --max-model-len, or the training context + * when it is unset -- the same reading the declare and the KV pool take. */ + const int64_t mlen = std::max( + 1, cfg_.max_ctx > 0 ? cfg_.max_ctx : meta_.n_ctx_train); + int64_t retained = 1; + for (int64_t n = (iv > 0 ? mlen / iv : 0); n > 1; n >>= 1) ++retained; + const int64_t sess_blocks = bs > 0 ? (mlen / bs) * slot_bytes : slot_bytes; + const int64_t sess_snaps = retained * ck_slot_bytes; + const int64_t denom = sess_blocks + sess_snaps; + const int64_t host_cap = cfg_.prefix_cache_host_mib << 20; + const int64_t disk_cap = cfg_.prefix_cache_disk_mib << 20; + const int64_t host_ck = std::min(host_cap * 2 / 3, denom > 0 ? host_cap / denom * sess_snaps + + host_cap % denom * sess_snaps / denom + : 0); + const int64_t disk_ck = std::min(disk_cap * 2 / 3, denom > 0 ? disk_cap / denom * sess_snaps + + disk_cap % denom * sess_snaps / denom + : 0); + ck_host_cap = (host_ck / ck_slot_bytes) * ck_slot_bytes; + ck_disk_slots = disk_ck / ck_slot_bytes; + /* One of each where there is room for one at all: a tier that holds a session's blocks + * and not one snapshot holds nothing usable. */ + if (ck_host_cap == 0 && host_cap >= ck_slot_bytes * 2) ck_host_cap = ck_slot_bytes; + if (ck_disk_slots == 0 && disk_cap >= ck_slot_bytes * 2) ck_disk_slots = 1; + } + if (cg.empty() || entry_bytes <= 0) { + /* Said only to an operator who asked for a tier. With no flag there is nothing to + * report: a cache that indexes no paged group stores no blocks to begin with. */ + if (tier_asked) + RAD_WARN("kv tiers: the prefix cache indexes no paged group, so there is nothing " + "to move. --prefix-cache-host-mib and --prefix-cache-disk-mib do nothing here."); + } else { + if (cfg_.prefix_cache_disk_mib > 0) { + if (cfg_.prefix_cache_dir.empty()) { + RAD_WARN("kv tiers: --prefix-cache-disk-mib needs --prefix-cache-dir to say WHERE. " + "The disk tier is off."); + } else { + SSDTierConfig sc; + sc.dir = cfg_.prefix_cache_dir; + sc.block_payload = slot_bytes; + sc.block_tokens = ranks_[0]->prefix.block_size(); + sc.ckpt_payload = ck_slot_bytes; + sc.n_ckpt_slots = ck_disk_slots; + sc.n_block_slots = ((cfg_.prefix_cache_disk_mib << 20) + - ck_disk_slots * ck_slot_bytes) / slot_bytes; + /* THE FINGERPRINT IS WHAT MAKES A PERSISTED STORE SAFE. A cached block is only + * meaningful under the container and layout that produced it; read back under + * another, it is a lossless function of somebody else's weights. */ + /* THE FINGERPRINT IS WHAT MAKES A PERSISTED STORE SAFE, and it is built from + * everything a cached block's bytes actually depend on. Read back under a + * different container, layout or KV width, a block is a lossless function of + * somebody else's weights -- fluent, confident and wrong. There is no cheaper + * check than refusing the whole store, because a block carries no evidence of + * what produced it beyond the tokens it was keyed by. */ + { + const std::string id = + std::string(meta_.name ? meta_.name : "") + "|" + + std::string(meta_.arch_id ? meta_.arch_id : "") + "|" + + std::to_string(meta_.n_layers) + "|" + + std::to_string(ranks_[0]->prefix.block_size()) + "|" + + std::to_string(slot_bytes) + "|" + std::to_string(ck_slot_bytes) + "|" + + cfg_.kv_cache_dtype + "|" + + std::to_string((long long)ranks_.size()) + "|" + RAD_VERSION; + uint64_t h = 1469598103934665603ull; + for (char c : id) { h ^= (unsigned char)c; h *= 1099511628211ull; } + sc.fingerprint = h; + } + sc.persistent = true; + kv_disk_ = std::make_unique(); + RAD_INFO("%s", SSDTier::disclosure(sc.dir).c_str()); + if (kv_disk_->open(sc) != RAD_OK) { + RAD_WARN("kv tiers: the disk tier at %s would not open; it is off.", + sc.dir.c_str()); + kv_disk_.reset(); + } + } + } + IdleTiers::Config tc; + tc.host_cap_bytes = cfg_.prefix_cache_host_mib << 20; + tc.disk_cap_bytes = kv_disk_ ? (cfg_.prefix_cache_disk_mib << 20) : 0; + tc.entry_bytes = slot_bytes; + tc.ckpt_bytes = ck_slot_bytes; + tc.ckpt_cap_bytes = ck_host_cap; + tc.ckpt_disk_slots = kv_disk_ ? ck_disk_slots : 0; + + /* THE POLICY IS RANK 0'S AND THE TRANSFER IS EVERY RANK'S. A session is not sharded -- + * it is a conversation -- so one decision is taken about it; but each rank holds its + * own shard of every block and gathers out of its own pool, so each rank moves its own + * bytes when that decision is taken. */ + IdleTiers& T = ranks_[0]->tiers; + RAD_TRY(T.configure(tc, kv_disk_.get())); + T.set_model(meta_.name && meta_.name[0] ? meta_.name : "(unnamed)"); + if (T.any_on()) { + /* HOW MUCH A PASS MOVES, SIZED IN BYTES AND NOT IN ENTRIES. A cache entry is one + * block per cached group, and that is 29 KiB on a 4-token-block hybrid and four + * times more on a 16-token one -- so a fixed entry count means a fixed batch on + * one model and a quarter of one on another. At a fixed 64 entries a 200K session + * on a 4-token-block hybrid takes about thirteen minutes to leave VRAM, which is + * most of the way to the disk threshold: a tier that works and is too slow to be + * worth having. + * + * 16 MiB of device staging a rank, which is about a millisecond of PCIe a pass + * and 0.02 ms a step of the VRAM it costs. The batch is one gather per (group, + * layer) however many entries are in it, so the launches are the same either + * way -- this buys the copies, which are what there are thousands of. */ + const int max_batch = (int)std::min( + 4096, std::max(64, (16ll << 20) / entry_bytes)); + /* A COPY OUT IS FOUR STAGING BATCHES, about 64 MiB a rank. It shares the transfer + * stream with the expert mover, so what it queues is what a promotion issued + * behind it waits for -- a few milliseconds of link at this size -- and the next + * copy goes out on the tick after this one lands, so a long conversation still + * leaves at the rate the link carries it. + * + * A RESTORE IS A WHOLE CHAIN, as long as the longest context this server takes. */ + const int64_t max_copy = 4ll * max_batch; + const int64_t bs = std::max(1, ranks_[0]->prefix.block_size()); + const int64_t max_chain = + (std::max(1, cfg_.max_ctx > 0 ? cfg_.max_ctx : meta_.n_ctx_train) + + bs - 1) / bs + 1; + bool all = true; + for (auto& r : ranks_) { + /* ON THAT RANK'S DEVICE. rad_dev_alloc takes the CURRENT device, and the + * staging buffer TierExec builds on its first pass is this rank's. The device + * is recorded in configure() and re-selected there, but selecting it here too + * keeps the rule that a rank is configured on its own card in one place: a + * gather reading a pointer that belongs to another card fails as a plain + * device error with nothing to say it was an addressing mistake. + * + * AND THE STREAM IS THE MOVER'S. See Mover::transfer_stream -- a fourth + * hardware queue costs an RDNA4 card 65% of its decode step. */ + RAD_TRY(rad_dev_set(r->device)); + if (r->tierx.configure(&rad_tools_registry(), &r->kv, &T, kv_disk_.get(), cg, + max_batch, max_copy, max_chain, + /*leader=*/&r == &ranks_[0], + r->device, + (int64_t)(&r - &ranks_[0]) * entry_bytes, + (int64_t)(&r - &ranks_[0]) * ranks_[0]->kv.checkpoint_bytes(), + /*shared=*/r->mover.transfer_stream()) + != RAD_OK) { + all = false; + break; + } + } + RAD_TRY(rad_dev_set(ranks_[0]->device)); + if (!all) { + /* THE MOVER IS OFF AND THE BOOKKEEPING IS NOT. close() forgets the entry and + * snapshot sizes with everything else, and those are what a session's + * reported size is computed from, so the object is re-configured for the + * caps it can still honour -- none. */ + T.close(); + kv_disk_.reset(); + tc.host_cap_bytes = tc.disk_cap_bytes = 0; + tc.ckpt_cap_bytes = tc.ckpt_disk_slots = 0; + RAD_TRY(T.configure(tc, nullptr)); + } else { + /* The tiers can lose an entry without the cache asking: a capacity drop, or a + * promotion that failed. The cache has to hear about it or it will go on + * serving block ids that are not its own any more. */ + T.set_drop_sink([this](const BlockHash& h) { + ranks_[0]->prefix.drop_offdevice(h); + }); + /* And the linear half on its own. The snapshot store is far smaller than the + * block store, so it overflows first and by itself; an index entry left + * behind would be a checkpoint the cache goes on offering whose bytes nobody + * holds, which is the recurrent-state form of the same corruption. */ + T.set_snapshot_drop_sink([this](const BlockHash& h) { + ranks_[0]->prefix.drop_snapshot(h); + }); + /* THE DISK HALF GETS A THREAD, and a plan holds about 512 MiB of it -- a + * fraction of a second of the store's write rate, so the disk copies keep up + * with the host copies in a handful of plans rather than one entry a second. */ + pump_ = std::make_unique(); + pump_->max_copy = max_copy; + pump_->slow_budget = (int)std::min( + 1 << 20, std::max(64, (512ll << 20) / std::max(1, slot_bytes))); + if (kv_disk_) pump_->io.start(&ranks_[0]->tierx); + RAD_INFO("%s", ranks_[0]->tierx.report().c_str()); + } + } + /* ATTACHED WHETHER OR NOT ANYTHING MOVES. A null `tiers_` is the whole of the cache's + * "off" path, and it turns off the session record along with the demotion it was + * written for -- so detached, a server with no tier flag would publish no conversations + * at all and the sessions view would have nothing to draw. With the caps at zero every + * call the cache makes here is a record of what it is holding and nothing is ever + * moved. */ + ranks_[0]->prefix.set_tiers(&T); + /* AND SAID EITHER WAY. configure() builds this line whether the tiers are on or off; + * printed only when they are on, a server that never moves a session would say + * nothing about it at all -- leaving "why is the KV pool full with one conversation + * open" with no answer in the log and a flag nobody knew was unset. */ + RAD_INFO("%s", T.report().c_str()); + } + } + + RAD_INFO("kv: %s", ranks_[0]->kv.report().c_str()); + /* PrefixCache::configure builds a report saying whether it is on, which groups it covers and + * which it had to skip, and this is where it is printed: unprinted, "why is cached_tokens + * always zero" has no answer short of reading the source. It is one line at startup and names + * the two things + * that silently turn caching off for a hybrid model: a windowed group cannot be served a + * prefix, and a linear model with no checkpoint interval replays from zero. */ + RAD_INFO("%s", ranks_[0]->prefix.report().c_str()); + + /* CAN THE POOL ACTUALLY HOLD A MAX-LENGTH SEQUENCE? The context limit and the KV pool are set + * by two unrelated flags, and this is where they are compared. Uncompared, a server started + * with a context its cache cannot cover accepts the request at the door and refuses it at + * admission seconds later, with a message about blocks rather than about the flag that was + * wrong. A WINDOW group is exempt: its per-sequence cost is the window, not the context, which is + * the whole point of it. Only paged groups can run out this way; a linear group is O(1) in + * context and is sized per sequence. */ + { + const int64_t want = cfg_.max_ctx ? cfg_.max_ctx : meta_.n_ctx_train; + const KVManager& kv = ranks_[0]->kv; + for (int32_t g = 0; g < kv.n_groups(); ++g) { + const KVGroupPlan* p = kv.plan(g); + if (!p || !p->paged() || p->window_blocks > 0) continue; + const int64_t cap = p->n_blocks * p->block_size; + if (cap >= want) continue; + /* THIS ONE IS A REAL LIMIT AND NOT A BACKING RATIO. How much of the worst case + * (every sequence at max_ctx at once) the pool backs is a provisioning choice and + * well under half is normal for one-shot traffic. (It is NOT harmless for + * multi-turn: prefix caching keeps a finished sequence's blocks so the next turn + * can reuse them, so a pool that backs fewer live SESSIONS than it admits makes + * every turn re-prefill. That is a provisioning choice too, and the budget line + * in vram_budget.cpp says it.) What is never acceptable is a pool that cannot + * hold ONE max-length sequence: + * that request is accepted by the API and can never complete, whatever the load. */ + RAD_WARN("kv group '%s' holds %lld tokens but the context limit is %lld: ONE request " + "longer than %lld tokens is accepted by the API and then refused as too " + "large to ever fit -- this is a hard limit, not a backing ratio. Raise " + "--expert-vs-cache-ratio toward the cache (about %lld MiB more for the whole " + "context), halve the cost a token with --kv-cache-dtype fp8, or lower " + "--max-model-len to %lld.", + p->name.c_str(), (long long)cap, (long long)want, (long long)cap, + (long long)(((want - cap) / p->block_size * p->bytes_per_block) >> 20), + (long long)cap); + } + } + return RAD_OK; +} + +/* The group pools, as the run phase addresses them. The operand names an ABSOLUTE model layer and + * the pool holds only the layers bound to this group, so the binding carries the POSITION of each + * absolute layer within the group -- a group covering layers 3,7,...,63 is sixteen caches and layer + * 7 is the second, not the fifth, and subtracting the first bound layer says the fifth. */ +static void bind_kv_pools(const Program& p, const KVManager& kv, std::vector* out) { + out->assign(p.kv_groups.size(), KVPoolBinding{}); + for (size_t g = 0; g < p.kv_groups.size(); ++g) { + const KVGroupPlan* gp = kv.plan((int32_t)g); + if (!gp) continue; + KVPoolBinding& b = (*out)[g]; + b.base = gp->base; + b.layer_stride = gp->layer_stride(); + b.bytes = gp->pool_bytes; + b.dtype = p.kv_groups[g].decl.dtype; + + /* The position of every bound layer, indexed by its absolute number. */ + const std::vector& ls = p.kv_groups[g].layers; + int32_t hi = -1; + for (int32_t l : ls) if (l > hi) hi = l; + b.layer_slot.assign((size_t)(hi + 1), -1); + for (size_t i = 0; i < ls.size(); ++i) b.layer_slot[(size_t)ls[i]] = (int32_t)i; + + /* The shape of ONE layer's cache, in the layout libref/ref_ops.h states for the whole + * project. Composed here because this is the only place that holds both halves of it: the + * plugin's declaration (heads, head_dim, state_dim, conv_width) and the block manager's + * decisions (block_size, n_blocks, n_states, conv_slots). A kernel cannot derive the conv + * window's depth or the slot count from any op parameter, so a flat span makes every shim + * that needs the structure refuse. */ + const RadKVGroupDecl& d = p.kv_groups[g].decl; + switch (gp->kind) { + case RAD_KV_FULL: + case RAD_KV_WINDOW: + b.rank = 4; + b.shape[0] = gp->n_blocks; + b.shape[1] = d.n_head_kv; + b.shape[2] = gp->block_size; + b.shape[3] = 2 * d.head_dim; + break; + case RAD_KV_LINEAR: + b.rank = 4; + b.shape[0] = gp->n_states; + b.shape[1] = d.n_head_kv; + b.shape[2] = d.state_dim[0]; + b.shape[3] = d.state_dim[1]; + break; + case RAD_KV_CONV: + b.rank = 3; + b.shape[0] = gp->n_states; + b.shape[1] = d.n_head_kv * d.head_dim; + b.shape[2] = gp->conv_slots; + break; + default: + b.rank = 0; /* the null sentinel at handle 0; nothing issues against it */ + break; + } + } +} + +/* ================================================================== start */ +int Engine::start() { + std::vector devs; + std::string inventory; + std::string devnote; + /* Rank tags on the log from here down, so the pools, the planner, the mover and the sampler + * are each attributed to the card they are about. At tp 1 there is nothing to disambiguate. */ + log_rank_tags(cfg_.tp > 1); + + int s = usable_devices(&devs, &inventory, &devnote); + if (!devnote.empty()) RAD_WARN("device: %s", devnote.c_str()); + if (s < 0) { RAD_ERR("no usable device"); return s; } + + if ((int)devs.size() < cfg_.tp) { + RAD_ERR("--tp %d needs %d devices of one architecture; %zu are usable [%s]", + cfg_.tp, cfg_.tp, devs.size(), inventory.c_str()); + return RAD_E_DEVICE; + } + + RAD_TRY(read_metadata()); + RAD_TRY(load_vocab()); + /* The cards are chosen, so a kernel library's device code is checked against the ones the + * ranks will run on and not against whichever device the backend happens to list first. */ + rad_tools_registry().set_code_device(devs[0]); + RAD_TRY(load_plugins()); + + ranks_.clear(); + for (int i = 0; i < cfg_.tp; ++i) { + auto r = std::make_unique(); + r->index = i; + r->device = devs[i]; + ranks_.push_back(std::move(r)); + } + + RAD_TRY(declare()); + + /* --debug-graph stops here on purpose: everything it prints is known between declare and + * plan, and a graph dump that first has to fit the model in VRAM is a graph dump you cannot + * run on the machine where the model does not fit. */ + if (cfg_.debug_graph) return RAD_OK; + + /* Before anything is placed or mapped. A container whose ops resolve to the reference + * implementation is a container that will serve at reference speed, and that is a decision the + * operator makes rather than one the engine discovers three minutes into a load. */ + RAD_TRY(rad_gate_reference_kernels(ranks_[0]->program, cfg_.accept_reference_kernels, "serve")); + + RAD_TRY(plan()); + RAD_TRY(load_weights()); + RAD_TRY(configure_kv()); + + for (auto& r : ranks_) { + LogRank lr(r->index); + RAD_TRY(rad_dev_set(r->device)); /* allocates on the CURRENT device; see plan() */ + CtxDesc d{}; + d.program = &r->program; + d.rank = r->index; + d.world_size = cfg_.tp; + d.device = r->device; + /* Null in the all-in-VRAM case: the degenerate one where the planner assigned everything + * to tier 0 and the mover never runs, and lookup collapses to WeightInfo::ptr. */ + d.residency = r->plan.strategy == Strategy::AllVram ? nullptr : r->mover.residency(); + d.arch_step = arch_step_; + d.profile_ops = cfg_.profile_ops; + bind_kv_pools(r->program, r->kv, &d.kv); + RAD_TRY(r->ctx.init(d)); + + /* THE MOVER NEEDS THE COMPUTE STREAM. + * + * Every transfer is ordered against the kernels that read the slot it targets, through an + * event recorded on the compute stream once per dispatch (Mover::record_gate). With no + * stream bound that function returns RAD_E_STATE, so a mover asked to move anything + * refuses. The bind belongs here rather than in load_weights: Ctx owns the stream and does + * not create it until init(), and the load runs on its own copy stream. + * + * Not under `if (d.residency)`: a plan can be static and still stage a file-tier weight + * on demand, and a mover that is bound but idle costs one pointer. */ + RAD_TRY(r->mover.bind_compute_stream(r->ctx.stream())); + + /* THE PREFILL STAGER, where the budget made room for it: a step larger than every smaller + * arena level is the only one that finds the region unlent, so that is the smallest pass + * it arms for. */ + if (r->program.arena_stage_bytes > 0 && r->plan.dynamic && !r->arena_levels.empty()) { + int64_t top_level = 0; + for (const ArenaLevel& lv : r->arena_levels) top_level = std::max(top_level, lv.rows); + RAD_TRY(r->stager.init(r->program, r->plan, &r->mover, + (char*)r->ctx.arena_base() + r->program.arena_stage_off, + r->program.arena_stage_bytes, top_level + 1)); + if (r->stager.enabled() && r->index == 0) + RAD_INFO("prefill staging: two %s buffers at the top of the arena; a step of " + "more than %lld tokens copies the next of %zu routed layers' pooled " + "experts onto the card while the one before it runs", + humanb(r->stager.buffer_bytes()).c_str(), (long long)top_level, + r->stager.n_layers()); + } + /* THE FILE STAGER, wherever the plan put a routed expert on the file tier -- static plan + * or dynamic, since a file-tier unit has no other address. */ + RAD_TRY(r->fstager.init(r->program, r->plan, &r->mover)); + if (r->fstager.enabled() && r->index == 0) + RAD_INFO("file stager: %zu routed layers hold experts read from the container; each " + "pass reads a layer's (up to %s) into one of two VRAM buffers before its " + "first expert op, so every step is paced by the drive", + r->fstager.n_layers(), humanb(r->plan.file_layer_max).c_str()); + if (r->stager.enabled() && r->fstager.enabled()) { + r->stagers.set(&r->stager, &r->fstager); + r->ctx.set_stager(&r->stagers); + } else if (r->stager.enabled()) { + r->ctx.set_stager(&r->stager); + } else if (r->fstager.enabled()) { + r->ctx.set_stager(&r->fstager); + } + + /* RADIANCE_HOST_DOMAIN puts EVERY op on the host domain, which is how you run the whole + * model on libref. The oracle the entire correctness story leans on is a per-op + * one -- it compares one kernel against ref on the operands the device handed it -- and + * that can never answer "is the GRAPH right", because both sides read the same graph. A + * whole forward pass on the reference implementation can, and it is the only thing that + * can be diffed against another engine's. + * + * The site is a per-op property already (spec §5.1) and set_op_domain refuses by name + * where a band has no host kernel, so this is the existing seam and not a new one. It + * belongs with HIP_VISIBLE_DEVICES=-1, which drops the backend to host so the arena is + * host memory a host kernel may dereference; without that this asks ref to read VRAM. */ + if (std::getenv("RADIANCE_HOST_DOMAIN")) { + if (!device_is_host()) + RAD_WARN("RADIANCE_HOST_DOMAIN on the %s backend: the arena is device memory and " + "a host kernel cannot read it. Set HIP_VISIBLE_DEVICES=-1 as well.", + device_backend_name()); + int moved = 0; + for (size_t i = 1; i < r->program.ops.size(); ++i) { + const int st = r->ctx.set_op_domain((rad_op)i, RAD_DOMAIN_HOST); + if (st < 0) return st; + ++moved; + } + RAD_WARN("RADIANCE_HOST_DOMAIN: %d op(s) on the host. This is the reference " + "implementation running the whole model, and it is as slow as that sounds.", + moved); + } + } + /* ---- THE LOAN: the cache's idle blocks, lent to the expert slab in place ---------------- + * + * Here and not earlier because it needs both halves: the cache's carve fixes the addresses and + * the mover's compute stream is what a recall drains. Every rank lends its own pool's strips -- + * the same geometry on every card -- and only a plan that moves units borrows at all. + * + * A STRIP IS ONE LAYER'S STRIPE OF ONE LENDABLE GROUP, top down, because that is how the cache + * lends: the top blocks of a group are the top of every layer's stripe at once. */ + for (auto& r : ranks_) { + if (!r->heat.enabled()) continue; + RAD_TRY(rad_dev_set(r->device)); + std::vector strips; + for (const KVGroupPlan& p : r->kv.plans()) { + if (!r->kv.lendable(p.index) || !p.base) continue; + const int64_t lbpb = p.layer_bytes_per_block(), stripe = p.layer_stride(); + for (int64_t L = 0; L < p.n_layers; ++L) { + LoanStrip st; + st.top = (char*)p.base + L * stripe + p.n_blocks * lbpb; + st.bytes = p.n_blocks * lbpb; + st.unit_bytes = lbpb; + st.unit_tokens = p.block_size; + strips.push_back(st); + } + } + RAD_TRY(r->mover.lend_from(Mover::kLendKV, strips)); + if (r->mover.flex_capacity() > 0) lending_ = true; + } + (void)rad_dev_set(ranks_[0]->device); + + /* ---- AND THE TOP OF THE ACTIVATION ARENA, lent while the steps are small ---------------- + * + * One stretch a rank: from the end of the full plan's transients down to the end of the + * smallest level's, less a guard. A level lends everything above its own end and guard, so the + * loan is stated in bytes from the top -- the measure every level can say in one number. Each + * rank lends its own arena, whose plan may differ from rank 0's by the buffers only one rank + * declares, so each rank's amounts are its own. + * + * THE GUARD is a mebibyte between a level's highest buffer and the lent memory: what a kernel + * writes past the rows it was given lands there rather than in an expert's weights, which + * would stay corrupt for as long as the unit stayed resident. */ + arena_rows_.clear(); + if (!ranks_.empty() && !ranks_[0]->arena_levels.empty() && ranks_[0]->heat.enabled()) { + static constexpr int64_t kGuard = 1ll << 20; + bool ok = true; + for (auto& r : ranks_) { + RAD_TRY(rad_dev_set(r->device)); + r->arena_lent.assign(1, 0); + const Program& P = r->program; + const int64_t top = P.arena_bytes; + for (const ArenaLevel& lv : r->arena_levels) { + if (r->ctx.add_level(lv.rows, lv.offset, lv.decl) < 0) { ok = false; break; } + const int64_t edge = (lv.end + kGuard + RAD_ALIGN_UNIT - 1) / + RAD_ALIGN_UNIT * RAD_ALIGN_UNIT; + r->arena_lent.push_back(top > edge ? top - edge : 0); + } + if (!ok) break; + int64_t most = 0; + for (int64_t b : r->arena_lent) most = std::max(most, b); + if (most <= 0) continue; + LoanStrip st; + st.top = (char*)r->ctx.arena_base() + top; + st.bytes = most; + st.unit_bytes = 1; + st.unit_tokens = 1; + RAD_TRY(r->mover.lend_from(Mover::kLendArena, { st })); + } + (void)rad_dev_set(ranks_[0]->device); + if (ok) { + arena_rows_.push_back(cfg_.max_tok); + for (const ArenaLevel& lv : ranks_[0]->arena_levels) arena_rows_.push_back(lv.rows); + std::string lv; + for (size_t k = 1; k < arena_rows_.size(); ++k) + lv += fmt("%s%s while steps are at most %lld tokens", + k > 1 ? ", " : "", humanb(ranks_[0]->arena_lent[k]).c_str(), + (long long)arena_rows_[k]); + RAD_INFO("activation arena: lends %s", lv.c_str()); + } else { + RAD_WARN("activation arena: a level would not bind; nothing is lent"); + for (auto& r : ranks_) r->arena_lent.clear(); + } + } + /* A RECALL THAT CANNOT WAIT. When a request needs more of the cache than it kept in hand, rank + * 0's cache calls this from the scheduler, between dispatches, with every rank thread parked: + * each rank's slab is drained to the loan the cache can still afford before the blocks are + * handed out, and every follower's mark moves with rank 0's at once rather than at the next + * step's build -- a tier restore on a follower picks the id rank 0 just chose. */ + if (lending_) + ranks_[0]->kv.set_reclaim([this](int64_t tokens) -> int { + int st = RAD_OK; + for (auto& r : ranks_) { + if (rad_dev_set(r->device) < 0) { st = RAD_E_DEVICE; break; } + st = r->mover.reclaim(Mover::kLendKV, tokens, &r->heat); + if (st < 0) break; + } + if (st >= 0) + for (size_t i = 1; i < ranks_.size(); ++i) { + KVManager& f = ranks_[i]->kv; + if (tokens < f.loan_tokens()) (void)f.set_loan(tokens); + } + (void)rad_dev_set(ranks_[0]->device); + return st; + }); + + /* WHAT THE CORE SPENT, beside what the card says was spent. The two differ by exactly the + * allocations the core does not make: the driver's context, its code objects, and any kernel + * plugin that calls hipMalloc for itself. Naming the difference is the only way to tell a + * budget that is wrong from a plugin that is spending behind it. */ + { + int64_t dev_bytes = 0, dev_count = 0; + rad_dev_alloc_totals(RAD_MEM_DEVICE, &dev_bytes, &dev_count); + int64_t pooled = 0; + for (auto& r : ranks_) + pooled += r->pools.weights().bytes() + r->pools.kv().bytes(); + RAD_INFO("device allocations: %lld totalling %s, of which %s is the two pools -- the rest " + "is the activation arena and the step staging. Anything on the card past this is " + "the driver or a kernel plugin's own hipMalloc, which this cannot see.", + (long long)dev_count, humanb(dev_bytes).c_str(), humanb(pooled).c_str()); + } + + RAD_TRY(step_state_init()); + + /* ---- THE BUDGET, CHECKED AGAINST THE CARD IT WAS SPENT ON ---------------------------------- + * + * Everything above this line allocated: the two pools, the activation arena, the step batch + * staging, the weight tables a grouped GEMM walks. What is left on the card should now be + * --gpu-headroom-mib and nothing else, and this is the only place that can say whether it is. + * + * Both directions are worth a line. TOO LITTLE means the terms the resolver could not compute + * -- anything still allocated lazily, and whatever the driver took after the reading -- ate + * into the memory the operator asked to keep, and the next thing to allocate on this card is + * whatever fails. TOO MUCH means the budget left VRAM on the floor, which on a model whose + * experts do not fit is milliseconds of decode step for every unspent GiB -- the exact + * failure this resolver exists to remove. + * + * A slack of one arena is tolerated silently: MiB rounding and a kernel plugin's own + * workspaces live in there, and naming a number this close to right would be noise. */ + /* DOES A DECOMMIT GIVE THE CARD BACK? The checkpoint slots are the one part of the KV pool + * backed on demand, and releasing a freed slot's pages is only worth a driver call where the + * card actually gets them back. That is a claim about the driver rather than about the API, + * so it is measured here, once, on a range nothing else owns: commit it, read the card, + * decommit it, read again. tools/vmemprobe.cpp asks the same question in more detail, and on + * ROCm 7.2 / gfx1201 the answer is no -- hipMemUnmap returns nothing, and a reservation is + * charged for its high-water commit until hipMemAddressFree. + * + * The expert slab does not depend on the answer. It borrows the cache's idle blocks at the + * addresses the cache already owns, so no page ever changes hands (Engine::loan_tick). */ + if (!ranks_.empty() && VMem::supported()) { + VMem v; + const int64_t g = VMem::granularity(); + const int64_t n = std::max(64ll << 20, g > 0 ? g * 16 : 0); + RadDeviceProps a{}, b{}; + release_frees_card_ = false; + if (rad_dev_set(ranks_[0]->device) >= 0 && v.reserve(n) >= 0 && v.commit(0, n) >= 0 && + rad_dev_props(ranks_[0]->device, &a) >= 0 && v.decommit(0, n) >= 0 && + rad_dev_props(ranks_[0]->device, &b) >= 0) + release_frees_card_ = (b.vram_free - a.vram_free) > n / 2; + for (auto& r : ranks_) r->kv.set_release_frees_card(release_frees_card_); + if (!release_frees_card_) + RAD_INFO("this driver does not return decommitted VRAM to the card (%s unmapped, the " + "free counter did not move), so a freed checkpoint slot keeps its pages. The " + "expert slab is unaffected: it borrows the cache's idle blocks in place.", + humanb(n).c_str()); + } + + /* A CHECKPOINT SLOT IS BACKED ON EVERY CARD BEFORE ITS ID IS HANDED OUT, AND NEVER INTO THE + * HEADROOM. Rank 0's free list hands the ids out and every rank writes its shard of a snapshot + * into the same slot of its own pool; backing a slot on one card and meeting a refusal on the + * other at the snapshot copy would stop the engine mid-serve. See + * KVManager::set_checkpoint_floor for why the floor is the headroom. */ + if (!ranks_.empty()) { + const int64_t keep = std::max(cfg_.gpu_headroom_mib, 0) * (1ll << 20); + for (auto& r : ranks_) { + const int dev = r->device; + r->kv.set_checkpoint_floor([dev](int64_t* free_now) -> int { + RadDeviceProps p{}; + RAD_TRY(rad_dev_props(dev, &p)); + *free_now = p.vram_free; + return RAD_OK; + }, keep); + } + std::vector peers; + for (size_t i = 1; i < ranks_.size(); ++i) peers.push_back(&ranks_[i]->kv); + ranks_[0]->kv.set_checkpoint_peers(std::move(peers)); + } + /* AND ON A DRIVER THAT KEEPS WHAT IT MAPS, BACKED NOW. A slot backed later would cost the card + * exactly what it costs now and could never be given back, so waiting would only move the + * region's cost out of the reading below and into the middle of serving -- where the budget's + * misses (allocations made after it was resolved) may already have taken part of it. Backed + * here, the reading includes the slots, and a slot the cards have no room for is withdrawn + * here and said so. */ + if (!release_frees_card_ && !ranks_.empty() && ranks_[0]->kv.free_checkpoint_slots() > 0) { + KVManager& lead = ranks_[0]->kv; + const int64_t asked = lead.free_checkpoint_slots(); + int64_t gone = 0; + RAD_TRY(lead.back_free_checkpoints(&gone)); + if (gone > 0) { + const int64_t stride = lead.checkpoint_stride(); + const int64_t keep = std::max(cfg_.gpu_headroom_mib, 0) * (1ll << 20); + int64_t short_by = 0; + for (auto& r : ranks_) { + RadDeviceProps p{}; + if (rad_dev_props(r->device, &p) < 0) continue; + short_by = std::max(short_by, gone * stride - (p.vram_free - keep)); + } + RAD_WARN("checkpoint slots: %lld of %lld backed (%s each), %lld withdrawn -- one more " + "would take a card under the %s --gpu-headroom-mib, the room a kernel's first " + "launch allocates from. The prefix cache holds %lld linear-state snapshots on " + "the card and its retention policy decides which. The budget counted all " + "%lld; the card is %s short of them, which is allocations made after the " + "budget was resolved.", + (long long)(asked - gone), (long long)asked, humanb(stride).c_str(), + (long long)gone, humanb(keep).c_str(), (long long)(asked - gone), + (long long)asked, humanb(short_by).c_str()); + } + } + + for (auto& r : ranks_) { + LogRank lr(r->index); + RadDeviceProps props{}; + if (rad_dev_props(r->device, &props) < 0 || props.vram_bytes <= 0) continue; + + const int64_t MiB = 1024 * 1024; + const int64_t want = std::max(cfg_.gpu_headroom_mib, 0) * MiB; + const int64_t got = props.vram_free; + if (got < want) { + /* WHAT THIS SHORTFALL THREATENS is whatever allocates after startup: a kernel's code + * object, loaded on its FIRST launch, and a spilling kernel's scratch, sized on its + * first launch by the whole grid. Neither is knowable when the budget is resolved, and + * running out for either is a fault inside the HIP runtime rather than an error. */ + RAD_WARN("card %d settled at %s free against the %s --gpu-headroom-mib asked to keep. " + "The difference is allocations made after the budget was resolved, and it is " + "the room a kernel's first launch allocates from. Raise --gpu-headroom-mib by " + "at least %s so the budget is resolved against the right number.", + r->device, humanb(got).c_str(), humanb(want).c_str(), + humanb(want - got).c_str()); + } + else if (got > want + 256 * MiB) { + /* AND "TOO MUCH" IS ONLY A FAULT WHERE SOMEBODY STATED THE BUDGET. Where the resolver + * made the split, what is left is left because neither pool could address another + * byte -- a small dense model already at the largest context its cache can hold + * leaves most of the card -- and vram_budget.cpp printed it on the `unusable` line. + * Warning here would contradict that receipt and send the reader looking for a flag + * to set. */ + if (cfg_.vram_budget_derived) + RAD_INFO("card %d settled at %s free against the %s --gpu-headroom-mib asked to " + "keep. The split accounted for it: neither pool could address another " + "byte, which is the `unusable` line of the VRAM budget above.", + r->device, humanb(got).c_str(), humanb(want).c_str()); + else + RAD_WARN("card %d settled at %s free against the %s --gpu-headroom-mib asked to " + "keep, so %s is unused. On a model that does not fit in VRAM every unused " + "GiB is weight that has to be moved instead of read, and that is decode " + "step time.", + r->device, humanb(got).c_str(), humanb(want).c_str(), + humanb(got - want).c_str()); + } else + RAD_INFO("card %d settled at %s free, against the %s --gpu-headroom-mib asked to keep", + r->device, humanb(got).c_str(), humanb(want).c_str()); + } + return RAD_OK; +} + +const Program& Engine::program() const { return ranks_[0]->program; } + +/* ================================================================== dump */ +/* The answer to "it is unclear what even runs" (spec §16). It is a first-class mode rather than a + * side effect of a verbose flag, because that is the complaint this project exists to answer. */ +int Engine::dump() { + Program& p = ranks_[0]->program; + fputs(dump_graph_str(p, nullptr).c_str(), stdout); + if (cfg_.debug_selection) fputs(rad_tools_registry().selection_table().c_str(), stdout); + /* A HOST miss is not a failure -- see miss_report(). The exit code answers "is there a + * hole a request can fall into", and a host miss is not one. NOR IS A DEVICE MISS WHOSE OP + * HAS A HOST KERNEL: the planner places that op on the host and pins its weights in the + * container's mapping, which is how a table too large to copy into VRAM is served at all. A + * hole is a band NEITHER domain resolved. */ + std::set> no_host; + for (const Program::Miss& m : p.misses) + if (m.domain == RAD_DOMAIN_HOST) no_host.emplace(m.op, m.span); + for (const Program::Miss& m : p.misses) + if (m.domain != RAD_DOMAIN_HOST && no_host.count(std::make_pair(m.op, m.span))) + return RAD_E_NOKERNEL; + return RAD_OK; +} + +/* ================================================================== 6c. the vocabulary */ +/* The sampler needs three facts about a token plus the ability to tokenise a short literal; the + * text frontend has a whole Vocab. vocab_view.h says core/text implements the view over the real + * vocabulary; core/text does not, so the adapter is here, where the two are wired together and + * nowhere else. It belongs in core/text the moment a second caller wants it. */ +namespace { +class RealVocabView final : public VocabView { +public: + int init(std::shared_ptr v) { + v_ = std::move(v); + RAD_TRY(tok_.init(v_)); + /* token_piece returns a reference, so the pieces have to outlive the call. Building them + * once costs one pass over the vocabulary and saves a string construction per candidate + * token per grammar step, which is host work on the step path. + * + * piece(), NOT Vocab::text(). text() is the vocab's OWN encoding -- for a byte-level BPE + * that is the GPT-2 mapped alphabet, where a space is 'Ġ' (U+0120) and a newline is 'Ċ'. + * piece() runs the declared decoder chain, which is what actually reaches the output + * stream, and vocab_view.h asks for exactly that. Handing the grammar the mapped form + * makes mask and accept consistently wrong, so nothing throws: every token containing a + * space or a newline is simply forbidden by every grammar. render_special is TRUE + * because the alternative gives a control token an empty piece, and an empty piece + * consumes nothing and so satisfies any grammar position. */ + pieces_.resize((size_t)v_->n_tokens()); + for (int32_t i = 0; i < v_->n_tokens(); ++i) + pieces_[(size_t)i] = tok_.piece(i, /*render_special=*/true); + return RAD_OK; + } + int32_t n_tokens() const override { return v_ ? v_->n_tokens() : 0; } + const std::string& token_piece(int32_t id) const override { + static const std::string kEmpty; + return (id >= 0 && (size_t)id < pieces_.size()) ? pieces_[(size_t)id] : kEmpty; + } + bool is_eog(int32_t id) const override { return v_ && v_->is_eog(id); } + int tokenize(const std::string& s, std::vector* out) const override { + return out ? tok_.encode(s, *out, /*add_special=*/false, /*parse_special=*/false) + : RAD_E_INVAL; + } + int tokenize_special(const std::string& s, std::vector* out) const override { + return out ? tok_.encode(s, *out, /*add_special=*/false, /*parse_special=*/true) + : RAD_E_INVAL; + } +private: + std::shared_ptr v_; + Tokenizer tok_; + std::vector pieces_; +}; +} /* namespace */ + +/* The container carries the vocabulary and nothing else is consulted. A .rad without one cannot + * serve text, and says so here rather than at the first request (spec §4.1, §12). */ +int Engine::load_vocab() { + VocabBuild vb; + if (file_) { + VocabSection vs = file_->vocab(); + if (!vs) { + RAD_ERR("%s carries no vocabulary section. A safetensors checkpoint has none of its " + "own, so rad-convert needs --tokenizer tokenizer.json.", cfg_.model.c_str()); + return RAD_E_FORMAT; + } + RAD_TRY(vocab_deserialize(file_->base(), (uint64_t)file_->size(), vs.h, vb)); + } else if (ckpt_->is_gguf()) { + /* GGUF names its pre-tokeniser and the chain is reconstructed from the name, or refused + * where it cannot be -- a container converted with --tokenizer bakes the declared one. */ + RAD_TRY(vocab_from_gguf(ckpt_->gguf(), vb)); + } else { + /* beside config.json, with tokenizer_config.json and chat_template.jinja */ + const std::string tj = ckpt_->dir() + "/tokenizer.json"; + if (parse_tokenizer_json(tj.c_str(), vb) < 0) { + RAD_ERR("%s: no readable tokenizer.json beside the checkpoint", cfg_.model.c_str()); + return RAD_E_FORMAT; + } + } + + auto v = std::make_shared(); + RAD_TRY(v->load(std::move(vb))); + vocab_ = v; + + auto view = std::make_unique(); + RAD_TRY(view->init(vocab_)); + vocab_view_ = std::move(view); + + RAD_INFO("vocab: %d tokens, bos=%d eos=%d%s", vocab_->n_tokens(), vocab_->bos(), vocab_->eos(), + vocab_->chat_template().empty() ? ", no chat template" : ""); + + /* THE GRAMMAR ENGINE'S VOCABULARY INDEX, built here rather than by the first request that + * carries a grammar -- a tool-calling template gives nearly every agent request one -- so + * that request's admission pays only for its own grammar. */ + GbnfVocabInfo gi; + const int gs = gbnf_prepare_vocab(vocab_view_.get(), &gi); + if (gs < 0) { + RAD_ERR("gbnf: the vocabulary index could not be built: %s", rad_strerror(gs)); + return gs; + } + RAD_INFO("gbnf: vocabulary index built in %.0f ms, %s", gi.build_ms, + humanb((int64_t)gi.bytes).c_str()); + return RAD_OK; +} + +} /* namespace rad */ diff --git a/core/engine_draft.cpp b/core/engine_draft.cpp new file mode 100644 index 00000000..09bb306f --- /dev/null +++ b/core/engine_draft.cpp @@ -0,0 +1,461 @@ +/* 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 +#include +#include +#include +#include +#include +#include + +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 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(rad_dev_alloc(slot_bytes, RAD_MEM_DEVICE)); + rk->n_eog = (int32_t)eog.size(); + rk->eog = static_cast( + rad_dev_alloc(std::max(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(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(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(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: 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; + 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 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= 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 */ diff --git a/core/engine_kld.cpp b/core/engine_kld.cpp new file mode 100644 index 00000000..7c0f19b8 --- /dev/null +++ b/core/engine_kld.cpp @@ -0,0 +1,174 @@ +/* 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 +#include +#include +#include + +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( + 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(); + 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> sinks(n); + std::vector> reqs(n); + for (size_t d = 0; d < n; ++d) { + sinks[d] = std::make_unique(64); + auto r = std::make_unique(); + 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 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(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(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 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(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 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 */ diff --git a/core/engine_mm.cpp b/core/engine_mm.cpp new file mode 100644 index 00000000..30c7ad43 --- /dev/null +++ b/core/engine_mm.cpp @@ -0,0 +1,132 @@ +/* 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 +#include + +namespace rad { + +int Engine::run_encodes() { + std::vector> 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= 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 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(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(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(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 */ diff --git a/core/engine_priv.h b/core/engine_priv.h new file mode 100644 index 00000000..6c18c8b9 --- /dev/null +++ b/core/engine_priv.h @@ -0,0 +1,116 @@ +/* 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 heat_seen; + /* One sweep's histograms, found before any is credited; kept so a sweep allocates nothing. */ + struct HeatRow { int layer; int bank; const int32_t* h; }; + std::vector heat_rows; + /* WHY A LAYER'S HISTOGRAM WENT UNCREDITED, which the credited total cannot separate on its + * own. A histogram is skipped either because its copy has not landed yet or because the bank + * still holds a step already credited, and those are different faults: the first says the host + * ran ahead of the device and the sample was lost, the second says the layer did not route. + * Without the split, a placement engine starved of evidence reads exactly like a model whose + * layers are idle. */ + 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 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 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 copy; + std::vector 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 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 */ diff --git a/core/engine_probe.cpp b/core/engine_probe.cpp new file mode 100644 index 00000000..9d906e0a --- /dev/null +++ b/core/engine_probe.cpp @@ -0,0 +1,268 @@ +/* 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 +#include +#include +#include +#include +#include +#include + +namespace rad { + +/* ================================================================== the buffer probe + * + * RADIANCE_DUMP_BUF names declared buffers, comma separated, and every step prints the first row + * of each: its mean, its largest magnitude and its first four elements. RADIANCE_DUMP_HEAD= + * adds the first n elements verbatim (integers included) and RADIANCE_DUMP_TOPK= the k largest. + * + * 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& 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=` 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(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=` 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> 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(row > 0 ? row : wi.stored_bytes, dump_cap()); + std::vector raw((size_t)n); + if (n <= 0 || rad_memcpy_async(raw.data(), ptr, n, ctx.stream()) < 0) continue; + rad_stream_sync(ctx.stream()); + dump_row(step, phase, wi.name.c_str(), wi.decl.dtype, raw); + goto next; + } + + 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(row, dump_cap()); + std::vector raw((size_t)n); + if (rad_memcpy_async(raw.data(), ptr, n, ctx.stream()) < 0) continue; + rad_stream_sync(ctx.stream()); + + dump_row(step, phase, b.name.c_str(), b.decl.dtype, raw); + break; + } + next:; + } +} + +} /* namespace rad */ diff --git a/core/format/checkpoint.cpp b/core/format/checkpoint.cpp new file mode 100644 index 00000000..08bcc526 --- /dev/null +++ b/core/format/checkpoint.cpp @@ -0,0 +1,887 @@ +/* checkpoint.cpp -- see checkpoint.h. */ +#include "checkpoint.h" +#include "rad_plugin.h" + +#include + +#include +#include +#include +#include +#include + +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() ? "1" : "0"); + else if (v.is_number_integer()) out->kv(key, fmt("%lld", (long long)v.get())); + else if (v.is_number()) out->kv(key, fmt("%.17g", v.get())); + else if (v.is_string()) out->kv(key, v.get()); + else if (v.is_array()) { + /* An array of scalars becomes a space-separated string: mrope_section "11 11 10", + * layer_types "linear_attention full_attention ...". A plugin splits it. Arrays of + * objects are not flattened -- nothing in a config uses one for a dimension. */ + 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()); + else if (e.is_number()) s += fmt("%.17g", e.get()); + else if (e.is_string()) s += e.get(); + 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 `.` 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 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()); + 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* out) { + std::unordered_map 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 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 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 */ + +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 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 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 inner; /* each piece's elements per outer index */ + int64_t total_inner = 0; + int n = 0; + void init(const std::vector& 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 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(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& 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 */ diff --git a/core/format/checkpoint.h b/core/format/checkpoint.h new file mode 100644 index 00000000..29d2139f --- /dev/null +++ b/core/format/checkpoint.h @@ -0,0 +1,159 @@ +/* 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 +#include +#include +#include +#include + +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 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 keys, vals; + std::vector 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& 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> shards_; + std::vector tensors_; + std::unordered_map index_; + std::deque 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 pieces; /* the codes, in concatenation order */ + std::vector 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); + +/* 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 */ diff --git a/core/format/encoding.cpp b/core/format/encoding.cpp new file mode 100644 index 00000000..d057efbd --- /dev/null +++ b/core/format/encoding.cpp @@ -0,0 +1,414 @@ +/* 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 +#include +#include +#include +#include +#include + +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 g_decoders; +} // namespace + +void enc_add_decoder(RadQuantDecodeFn fn) { + if (!fn) return; + std::lock_guard lk(g_dec_mu); + g_decoders.push_back(fn); +} + +void enc_remove_decoder(RadQuantDecodeFn fn) { + std::lock_guard 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 fns; + { + std::lock_guard 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 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 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; + } + 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 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 */ diff --git a/core/format/encoding.h b/core/format/encoding.h new file mode 100644 index 00000000..3f3e57a1 --- /dev/null +++ b/core/format/encoding.h @@ -0,0 +1,88 @@ +/* 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 + +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; 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 */ diff --git a/core/format/imatrix.cpp b/core/format/imatrix.cpp new file mode 100644 index 00000000..e5754e75 --- /dev/null +++ b/core/format/imatrix.cpp @@ -0,0 +1,417 @@ +/* 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 +#include +#include +#include +#include +#include + +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 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 dims; uint32_t type; uint64_t off; }; + std::vector 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 `.in_sum2` with `.counts`. Insertion order defines entries() order, so a + * report over the file reads in the order the collector wrote it. `held` is how many floats + * each half actually spans in the file, parallel to entries_, for the extent checks below. */ + std::unordered_map by_base; + struct Held { uint64_t sum2 = 0, counts = 0; }; + std::vector 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 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* 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 */ diff --git a/core/format/imatrix.h b/core/format/imatrix.h new file mode 100644 index 00000000..490d5d4b --- /dev/null +++ b/core/format/imatrix.h @@ -0,0 +1,97 @@ +/* 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 `.in_sum2` (f32 [cols] or [cols,n_expert]) + * and `.counts` (f32 [1] or [1,n_expert]), plus `imatrix.chunk_count`, + * `imatrix.chunk_size` and `imatrix.datasets` in the KV block. Per-expert data is a + * second dimension, which the legacy format could not express at all. + * + * 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 +#include +#include + +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& 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* 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> owned_; + std::vector entries_; + std::unordered_map index_; +}; + +} /* namespace rad */ diff --git a/core/format/machine_key.cpp b/core/format/machine_key.cpp new file mode 100644 index 00000000..b0de43fa --- /dev/null +++ b/core/format/machine_key.cpp @@ -0,0 +1,45 @@ +/* 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 + +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 */ diff --git a/core/format/radfile.cpp b/core/format/radfile.cpp new file mode 100644 index 00000000..24ee0055 --- /dev/null +++ b/core/format/radfile.cpp @@ -0,0 +1,1351 @@ +/* radfile.cpp -- the .rad reader and writer. + * + * Two halves of one decision. Everything the reader assumes on the hot path, the writer proves + * while writing and the reader re-proves at open. The pair is in one file so a change to the + * layout cannot land on only one side. + */ +#include "radfile.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__linux__) +#include +#endif + +namespace rad { + +std::string rad_unit_name(int32_t layer, int32_t expert) { + if (layer < 0) return "model"; + if (expert < 0) return fmt("layer %d", layer); + return fmt("layer %d expert %d", layer, expert); +} + +/* ================================================================== reader */ + +RadFile::~RadFile() { close(); } + +void RadFile::close() { + if (base_) ::munmap(base_, (size_t)size_); + if (fd_ >= 0) ::close(fd_); + base_ = nullptr; size_ = 0; fd_ = -1; + hdr_ = nullptr; meta_ = nullptr; dir_ = nullptr; planes_ = nullptr; encs_ = nullptr; + prof_ = nullptr; + vocab_ = VocabSection{}; + groups_.clear(); + by_name_.clear(); + path_.clear(); +} + +int RadFile::read_at(void* dst, int64_t bytes, int64_t off) const { + if (fd_ < 0) { RAD_ERR("read_at on a closed container"); return RAD_E_STATE; } + if (off < 0 || bytes < 0 || off + bytes > size_) { + RAD_ERR("read_at [%lld, %lld) is outside the %lld-byte container", + (long long)off, (long long)(off + bytes), (long long)size_); + return RAD_E_FORMAT; + } + uint8_t* p = (uint8_t*)dst; + while (bytes > 0) { + const ssize_t got = ::pread(fd_, p, (size_t)bytes, (off_t)off); + if (got < 0) { + if (errno == EINTR) continue; + RAD_ERR("%s: pread at %lld: %s", path_.c_str(), (long long)off, std::strerror(errno)); + return RAD_E_IO; + } + if (got == 0) { + RAD_ERR("%s: pread at %lld returned 0 with %lld bytes still wanted", + path_.c_str(), (long long)off, (long long)bytes); + return RAD_E_IO; + } + p += got; off += got; bytes -= got; + } + return RAD_OK; +} + +void RadFile::drop_blob_cache() const { + + if (!base_ || !hdr_ || fd_ < 0) return; + const int64_t tables = (int64_t)hdr_->data_off < size_ ? (int64_t)hdr_->data_off : size_; + if (tables >= size_) return; + /* The process's mapping first, then the cache behind it: a page still mapped here is one the + * kernel has to unmap before it can drop it, and doing it in the other order leaves the + * fadvise with nothing to free. */ + ::madvise(base_ + tables, (size_t)(size_ - tables), MADV_DONTNEED); + ::posix_fadvise(fd_, (off_t)tables, (off_t)(size_ - tables), POSIX_FADV_DONTNEED); +} + +/* Advisory, and deliberately NOT paired with an madvise: the load reads with pread and never + * maps these pages, so there is nothing of ours to unmap -- and the one region that IS read + * through the mapping, the n-gram table on Tier::Mapped, is never handed to this. */ +void RadFile::drop_range(int64_t off, int64_t bytes) const { + + if (fd_ < 0 || bytes <= 0) return; + ::posix_fadvise(fd_, (off_t)off, (off_t)bytes, POSIX_FADV_DONTNEED); +} + +int RadFile::open(const char* path) { + + close(); + if (!path || !*path) return RAD_E_INVAL; + path_ = path; + + fd_ = ::open(path, O_RDONLY | O_CLOEXEC); + if (fd_ < 0) { RAD_ERR("%s: %s", path, std::strerror(errno)); return RAD_E_IO; } + + struct stat st{}; + if (::fstat(fd_, &st) != 0) { RAD_ERR("%s: %s", path, std::strerror(errno)); close(); return RAD_E_IO; } + size_ = (int64_t)st.st_size; + if (size_ < (int64_t)sizeof(RadFileHeader)) { + RAD_ERR("%s: %lld bytes is shorter than a .rad header (%zu)", path, + (long long)size_, sizeof(RadFileHeader)); + close(); + return RAD_E_FORMAT; + } + + void* m = ::mmap(nullptr, (size_t)size_, PROT_READ, MAP_PRIVATE, fd_, 0); + if (m == MAP_FAILED) { RAD_ERR("%s: mmap: %s", path, std::strerror(errno)); close(); return RAD_E_IO; } + base_ = (uint8_t*)m; + + int s = validate(); + if (s < 0) { close(); return s; } + + /* THE TABLES ARE WANTED NOW; THE BLOB IS READ ONCE, FRONT TO BACK. + * + * THE ADVICE IS DELIBERATELY ASYMMETRIC AND MUST STAY THAT WAY. + * + * MADV_WILLNEED over the whole file asks the kernel to pull every byte into the page cache. + * That is right for a container that fits in RAM and ruinous for one that does not: it becomes + * a readahead storm that evicts the pages it just read and never settles, and the weight load + * collapses to a small fraction of disk bandwidth with the host thread spinning inside + * hipMemcpyAsync waiting on a copy engine starved for source pages. The tables are small and + * read immediately and in full, so they keep WILLNEED; the blob gets NO advice at all. + * + * MADV_SEQUENTIAL is the obvious replacement for the blob and is worse than silence: it widens + * the readahead window and drops pages behind the read pointer, and the load is not one + * stream. It reads a layer's gate_up experts, then that layer's down experts, then the + * scales -- three cursors over three regions -- so "behind" for one of them is "just about to + * be read" for another, and every page is fetched, dropped, and fetched again. Default + * readahead is what this copy loop is fastest under. + * + * The Tier::Mapped weights re-advise their own range MADV_RANDOM once the planner has spoken + * (engine_bringup.cpp); a later madvise over a sub-range wins for that sub-range, so leaving + * the blob unadvised here does not take that away. */ + const int64_t tables = (int64_t)hdr_->data_off < size_ ? (int64_t)hdr_->data_off : size_; + ::madvise(base_, (size_t)tables, MADV_WILLNEED); + /* A container extended in place (RadWriter::begin_append) keeps its tables PAST the blob; + * they are wanted now just the same. */ + const int64_t blob_end = (int64_t)(hdr_->data_off + hdr_->data_bytes); + if ((int64_t)hdr_->str_off >= blob_end && blob_end < size_) + ::madvise(base_ + (blob_end & ~(int64_t)(RAD_ALIGN_UNIT - 1)), + (size_t)(size_ - (blob_end & ~(int64_t)(RAD_ALIGN_UNIT - 1))), MADV_WILLNEED); + s = index_experts(); + if (s < 0) { close(); return s; } + + by_name_.reserve((size_t)hdr_->dir_count * 2); + for (int64_t i = 0; i < (int64_t)hdr_->dir_count; ++i) + by_name_.emplace(std::string_view(str(dir_[i].name)), i); + + return RAD_OK; +} + +/* Every offset and count in the header is attacker-shaped input until this function has run. + * Nothing below this point re-checks, so nothing below this point may be reached without it. */ +int RadFile::validate() { + hdr_ = (const RadFileHeader*)base_; + + if (hdr_->magic != RAD_MAGIC) { + RAD_ERR("%s: not a .rad container (magic %08x, expected %08x)", + path_.c_str(), hdr_->magic, RAD_MAGIC); + return RAD_E_FORMAT; + } + if (hdr_->version != RAD_FORMAT_VER) { + RAD_ERR("%s: .rad version %u, and this build reads only %u, which holds encodings rather " + "than kernel layouts -- convert it again with rad-convert", path_.c_str(), + hdr_->version, RAD_FORMAT_VER); + return RAD_E_FORMAT; + } + if ((int64_t)hdr_->file_bytes > size_) { + RAD_ERR("%s: header claims %llu bytes, the file is %lld -- truncated", + path_.c_str(), (unsigned long long)hdr_->file_bytes, (long long)size_); + return RAD_E_FORMAT; + } + + const uint64_t n = (uint64_t)size_; + auto span_ok = [&](uint64_t off, uint64_t bytes) { + return bytes == 0 ? off <= n : (off <= n && bytes <= n - off); + }; + /* A TABLE IS CHECKED BY ITS COUNT, NEVER BY count * sizeof. Every count in the header is + * uint64 and attacker-shaped, so the product wraps: meta_count = 0x0AAAAAAAAAAAAAAB times + * 24 bytes is 8, span_ok passes, and the loop below -- which iterates meta_count, not the + * byte span -- walks 7.6e17 rows off the end of the mapping. Divide into the space that is + * left instead, where nothing can wrap. */ + auto span_n = [&](uint64_t off, uint64_t count, uint64_t elem) { + if (count == 0) return off <= n; + return off <= n && count <= (n - off) / elem; + }; + auto need = [&](bool ok, const char* what) { + if (!ok) RAD_ERR("%s: %s lies outside the %lld-byte file", path_.c_str(), what, + (long long)size_); + return ok; + }; + + if (!need(span_ok(hdr_->str_off, hdr_->str_bytes), "the string blob")) return RAD_E_FORMAT; + if (hdr_->str_bytes == 0 || base_[hdr_->str_off + hdr_->str_bytes - 1] != 0) { + RAD_ERR("%s: the string blob is empty or its last byte is not NUL, so a string offset " + "near its end would read off the end of the mapping", path_.c_str()); + return RAD_E_FORMAT; + } + str_bytes_ = hdr_->str_bytes; + + if (!need(span_n(hdr_->meta_off, hdr_->meta_count, sizeof(RadFileKV)), "the metadata table")) + return RAD_E_FORMAT; + if (!need(span_n(hdr_->dir_off, hdr_->dir_count, sizeof(RadFileEntry)), + "the weight directory")) return RAD_E_FORMAT; + if (!need(span_n(hdr_->plane_off, hdr_->plane_count, sizeof(RadFilePlane)), + "the plane table")) return RAD_E_FORMAT; + if (!need(span_n(hdr_->enc_off, hdr_->enc_count, sizeof(RadEncoding)), + "the encoding table")) return RAD_E_FORMAT; + if (!need(span_n(hdr_->prof_off, hdr_->prof_count, sizeof(RadFileProfile)), + "the expert profile")) return RAD_E_FORMAT; + if (!need(span_ok(hdr_->vocab_off, hdr_->vocab_bytes), "the vocab section")) return RAD_E_FORMAT; + if (!need(span_ok(hdr_->data_off, hdr_->data_bytes), "the data blob")) return RAD_E_FORMAT; + + if (hdr_->data_bytes && (hdr_->data_off % RAD_ALIGN_POOL) != 0) { + RAD_ERR("%s: the data blob starts at %llu, which is not %u-aligned -- it could not be " + "mapped with huge pages", path_.c_str(), + (unsigned long long)hdr_->data_off, RAD_ALIGN_POOL); + return RAD_E_FORMAT; + } + + meta_ = (const RadFileKV*)(base_ + hdr_->meta_off); + dir_ = (const RadFileEntry*)(base_ + hdr_->dir_off); + planes_ = (const RadFilePlane*)(base_ + hdr_->plane_off); + encs_ = (const RadEncoding*)(base_ + hdr_->enc_off); + prof_ = (const RadFileProfile*)(base_ + hdr_->prof_off); + + auto str_ok = [&](rad_stroff o) { return o < str_bytes_; }; + + if (!str_ok(hdr_->arch_id) || !str_ok(hdr_->model_name) || !str_ok(hdr_->quant) || + !str_ok(hdr_->recipe) || + !str_ok(hdr_->created_by)) { + RAD_ERR("%s: a header string offset points outside the string blob", path_.c_str()); + return RAD_E_FORMAT; + } + + for (uint64_t i = 0; i < hdr_->meta_count; ++i) { + if (!str_ok(meta_[i].key) || + (meta_[i].type == RAD_P_STR && !str_ok(meta_[i].v.s))) { + RAD_ERR("%s: metadata row %llu has a string offset outside the string blob", + path_.c_str(), (unsigned long long)i); + return RAD_E_FORMAT; + } + } + + /* An encoding the core cannot read is refused here, by its index, rather than handed to a + * kernel's layout hook as if it meant something: rad_enc_valid() is the whole contract of the + * struct -- roles, chains, plane kinds and core dtypes. */ + for (uint64_t i = 0; i < hdr_->enc_count; ++i) { + RadEncoding e; + std::memcpy(&e, &encs_[i], sizeof e); + if (e.scheme[RAD_ENC_STR - 1] || e.transform[RAD_ENC_STR - 1] || !rad_enc_valid(&e)) { + RAD_ERR("%s: encoding %llu is not one the core can read", path_.c_str(), + (unsigned long long)i); + return RAD_E_FORMAT; + } + for (int k = 0; k < e.n_planes; ++k) + if (e.plane[k].role[RAD_ENC_STR - 1]) { + RAD_ERR("%s: encoding %llu's plane %d has an unterminated role", path_.c_str(), + (unsigned long long)i, k); + return RAD_E_FORMAT; + } + } + + for (uint64_t i = 0; i < hdr_->dir_count; ++i) { + const RadFileEntry& e = dir_[i]; + if (!str_ok(e.name) || !str_ok(e.quantizer) || !str_ok(e.options)) { + RAD_ERR("%s: directory row %llu has a string offset outside the string blob", + path_.c_str(), (unsigned long long)i); + return RAD_E_FORMAT; + } + if (e.rank == 0 || e.rank > RAD_MAX_RANK) { + RAD_ERR("%s: '%s' has rank %u; the ABI allows 1..%d", path_.c_str(), str(e.name), + e.rank, RAD_MAX_RANK); + return RAD_E_FORMAT; + } + for (uint32_t d = 0; d < e.rank; ++d) + if (e.shape[d] <= 0) { + RAD_ERR("%s: '%s' has extent %lld in dim %u", path_.c_str(), str(e.name), + (long long)e.shape[d], d); + return RAD_E_FORMAT; + } + if (!span_ok(e.offset, e.bytes)) { + RAD_ERR("%s: '%s' spans [%llu, %llu) which is outside the %lld-byte file -- truncated", + path_.c_str(), str(e.name), (unsigned long long)e.offset, + (unsigned long long)(e.offset + e.bytes), (long long)size_); + return RAD_E_FORMAT; + } + if (e.bytes && (e.offset % RAD_ALIGN_UNIT) != 0) { + RAD_ERR("%s: '%s' starts at %llu, not %u-aligned -- a transfer of it would straddle " + "a page boundary needlessly", path_.c_str(), str(e.name), + (unsigned long long)e.offset, RAD_ALIGN_UNIT); + return RAD_E_FORMAT; + } + if (e.enc >= hdr_->enc_count) { + RAD_ERR("%s: '%s' names encoding %u of %llu", path_.c_str(), str(e.name), e.enc, + (unsigned long long)hdr_->enc_count); + return RAD_E_FORMAT; + } + const RadEncoding& enc = encs_[e.enc]; + if (e.n_planes != (uint32_t)enc.n_planes || e.plane_first > hdr_->plane_count || + e.n_planes > hdr_->plane_count - e.plane_first) { + RAD_ERR("%s: '%s' names %u planes from %llu of %llu for an encoding of %d", + path_.c_str(), str(e.name), e.n_planes, (unsigned long long)e.plane_first, + (unsigned long long)hdr_->plane_count, enc.n_planes); + return RAD_E_FORMAT; + } + /* EVERY PLANE IS EXACTLY ITS ENCODING'S SIZE AND INSIDE ITS ENTRY. That is what lets a + * reader slice a plane by arithmetic and a mover treat the entry as one span. */ + int64_t rows = 0, cols = 0; + rad_enc_view(e.rank, e.shape, &rows, &cols); + for (uint32_t k = 0; k < e.n_planes; ++k) { + const RadFilePlane& p = planes_[e.plane_first + k]; + const int64_t want = rad_enc_plane_bytes(&enc.plane[k], rows, cols); + if ((int64_t)p.bytes != want || p.offset % RAD_ALIGN_SUB != 0 || p.offset < e.offset || + p.offset - e.offset > e.bytes || p.bytes > e.bytes - (p.offset - e.offset)) { + RAD_ERR("%s: '%s' plane %u ('%s') is %llu bytes at %llu; its encoding over " + "[%lld, %lld] makes it %lld, %u-aligned inside [%llu, %llu)", + path_.c_str(), str(e.name), k, enc.plane[k].role, + (unsigned long long)p.bytes, (unsigned long long)p.offset, + (long long)rows, (long long)cols, (long long)want, RAD_ALIGN_SUB, + (unsigned long long)e.offset, (unsigned long long)(e.offset + e.bytes)); + return RAD_E_FORMAT; + } + } + } + + /* ---------------------------------------------------------------- vocab */ + if (hdr_->vocab_bytes >= sizeof(RadVocabHeader)) { + /* THE SECTION IS READ IN PLACE through typed pointers, so the header and every array have + * to sit on their element's alignment, which is where the writer puts them. A file that + * does not is damaged, and reading it anyway is a misaligned load for every field. */ + if (hdr_->vocab_off % alignof(RadVocabHeader) != 0) { + RAD_ERR("%s: the vocab section starts at %llu, which is not %zu-aligned", path_.c_str(), + (unsigned long long)hdr_->vocab_off, alignof(RadVocabHeader)); + return RAD_E_FORMAT; + } + const RadVocabHeader* v = (const RadVocabHeader*)(base_ + hdr_->vocab_off); + /* Offset 0 means the array is absent -- an optional one (scores are unigram-only, types + * default to normal) simply is not written. Nothing real can live at file offset 0, so + * the sentinel is unambiguous. */ + auto arr_ok = [&](uint64_t off, uint64_t bytes, size_t align) { + return bytes == 0 || off == 0 || + (off >= hdr_->vocab_off && + off - hdr_->vocab_off <= hdr_->vocab_bytes && + bytes <= hdr_->vocab_bytes - (off - hdr_->vocab_off) && + off % align == 0); + }; + const uint64_t nt = v->n_tokens, nm = v->n_merges, ns = v->n_steps; + if (!arr_ok(v->tok_text_off, nt * sizeof(rad_stroff), alignof(rad_stroff)) || + !arr_ok(v->tok_score_off, nt * sizeof(float), alignof(float)) || + !arr_ok(v->tok_type_off, nt, 1) || + !arr_ok(v->merge_off, nm * 2 * sizeof(uint32_t), alignof(uint32_t)) || + !arr_ok(v->step_off, ns * sizeof(RadVocabStep), alignof(RadVocabStep))) { + RAD_ERR("%s: the vocab section's arrays do not fit inside it, or one is not aligned " + "to its element", path_.c_str()); + return RAD_E_FORMAT; + } + vocab_.h = v; + vocab_.tok_text = (nt && v->tok_text_off) ? (const rad_stroff*)(base_ + v->tok_text_off) : nullptr; + vocab_.tok_score = (nt && v->tok_score_off) ? (const float*)(base_ + v->tok_score_off) : nullptr; + vocab_.tok_type = (nt && v->tok_type_off) ? (const uint8_t*)(base_ + v->tok_type_off) : nullptr; + vocab_.merges = (nm && v->merge_off) ? (const uint32_t*)(base_ + v->merge_off) : nullptr; + vocab_.steps = (ns && v->step_off) ? (const RadVocabStep*)(base_ + v->step_off) : nullptr; + + if (vocab_.tok_text) + for (uint64_t i = 0; i < nt; ++i) + if (!str_ok(vocab_.tok_text[i])) { + RAD_ERR("%s: vocab token %llu points outside the string blob", path_.c_str(), + (unsigned long long)i); + return RAD_E_FORMAT; + } + if (vocab_.steps) + for (uint64_t i = 0; i < ns; ++i) + if (!str_ok(vocab_.steps[i].arg0) || !str_ok(vocab_.steps[i].arg1)) { + RAD_ERR("%s: vocab step %llu points outside the string blob", path_.c_str(), + (unsigned long long)i); + return RAD_E_FORMAT; + } + if (vocab_.merges) + for (uint64_t i = 0; i < nm * 2; ++i) + if (vocab_.merges[i] >= nt) { + RAD_ERR("%s: merge %llu names token %u of %llu", path_.c_str(), + (unsigned long long)(i / 2), vocab_.merges[i], (unsigned long long)nt); + return RAD_E_FORMAT; + } + if (!str_ok(v->chat_template)) { + RAD_ERR("%s: the chat template offset is outside the string blob", path_.c_str()); + return RAD_E_FORMAT; + } + } else if (hdr_->vocab_bytes != 0) { + RAD_ERR("%s: the vocab section is %llu bytes, shorter than its own header (%zu)", + path_.c_str(), (unsigned long long)hdr_->vocab_bytes, sizeof(RadVocabHeader)); + return RAD_E_FORMAT; + } + + return RAD_OK; +} + +/* Re-derive the fixed stride and refuse a container that does not have one. + * + * This is where the format's central claim is checked. `base + id * stride` is what the mover and + * the expert kernels do on the critical path, and they do it without a bounds test, so the claim + * has to be true before anything is handed a pointer. A file whose experts within a layer differ + * in shape or format is REFUSED here rather than read with a table walk: reading it slowly would + * quietly return exactly the property the format exists to provide. */ +int RadFile::index_experts() { + const int64_t n = (int64_t)hdr_->dir_count; + int64_t i = 0; + std::vector seen_layers; + + while (i < n) { + if (dir_[i].expert < 0) { ++i; continue; } + + const int32_t layer = dir_[i].layer; + if (std::find(seen_layers.begin(), seen_layers.end(), layer) != seen_layers.end()) { + RAD_ERR("%s: layer %d's experts are not contiguous in the directory, so no single " + "stride addresses them", path_.c_str(), layer); + return RAD_E_FORMAT; + } + seen_layers.push_back(layer); + + ExpertGroup g; + g.layer = layer; + g.first_index = i; + + /* Expert 0 establishes the shape of every expert in this layer. */ + int64_t j = i; + while (j < n && dir_[j].layer == layer && dir_[j].expert == 0) ++j; + g.n_slot = (int32_t)(j - i); + if (g.n_slot <= 0 || g.n_slot > 8) { + RAD_ERR("%s: layer %d expert 0 has %d slots; the directory supports 1..8", + path_.c_str(), layer, g.n_slot); + return RAD_E_FORMAT; + } + g.base = dir_[i].offset; + + uint64_t unit_end = g.base; + for (int32_t s = 0; s < g.n_slot; ++s) { + const RadFileEntry& e = dir_[i + s]; + if (e.slot != s) { + RAD_ERR("%s: layer %d expert 0's slots are %d at position %d -- the directory must " + "list them 0..n-1 in order", path_.c_str(), layer, e.slot, s); + return RAD_E_FORMAT; + } + if (e.offset < g.base) { + RAD_ERR("%s: layer %d expert 0 slot %d is before the expert's base", path_.c_str(), + layer, s); + return RAD_E_FORMAT; + } + g.slot_off[s] = e.offset - g.base; + g.slot_bytes[s] = e.bytes; + unit_end = std::max(unit_end, e.offset + e.bytes); + } + g.unit_bytes = unit_end - g.base; + + /* Every further expert must agree, byte for byte, with expert 0's internal layout, and + * must sit exactly one stride further along. */ + int32_t e_id = 1; + while (j < n && dir_[j].layer == layer && dir_[j].expert >= 0) { + if (dir_[j].expert != e_id) { + RAD_ERR("%s: layer %d's experts are listed out of order (expected %d, found %d)", + path_.c_str(), layer, e_id, dir_[j].expert); + return RAD_E_FORMAT; + } + const uint64_t ebase = dir_[j].offset; + if (e_id == 1) g.stride = ebase - g.base; + if (ebase != g.base + (uint64_t)e_id * g.stride) { + RAD_ERR("%s: layer %d expert %d starts at %llu, but base + %d*%llu is %llu -- the " + "layer has no fixed stride and cannot be addressed by arithmetic", + path_.c_str(), layer, e_id, (unsigned long long)ebase, e_id, + (unsigned long long)g.stride, + (unsigned long long)(g.base + (uint64_t)e_id * g.stride)); + return RAD_E_FORMAT; + } + for (int32_t s = 0; s < g.n_slot; ++s) { + if (j + s >= n || dir_[j + s].expert != e_id || dir_[j + s].slot != s) { + RAD_ERR("%s: layer %d expert %d does not have the same %d slots expert 0 has", + path_.c_str(), layer, e_id, g.n_slot); + return RAD_E_FORMAT; + } + const RadFileEntry& e = dir_[j + s]; + if (e.offset - ebase != g.slot_off[s] || e.bytes != g.slot_bytes[s]) { + RAD_ERR("%s: layer %d expert %d slot %d is at +%llu/%llu bytes where expert 0 " + "is at +%llu/%llu -- experts in a layer must share a shape and format", + path_.c_str(), layer, e_id, s, + (unsigned long long)(e.offset - ebase), (unsigned long long)e.bytes, + (unsigned long long)g.slot_off[s], (unsigned long long)g.slot_bytes[s]); + return RAD_E_FORMAT; + } + } + j += g.n_slot; + ++e_id; + } + g.n_expert = e_id; + if (g.n_expert == 1) g.stride = align_up((int64_t)g.unit_bytes, RAD_ALIGN_UNIT); + + groups_.push_back(g); + i = j; + } + return RAD_OK; +} + +const RadFileEntry* RadFile::find(std::string_view name) const { + auto it = by_name_.find(name); + return it == by_name_.end() ? nullptr : &dir_[it->second]; +} + +const RadFile::ExpertGroup* RadFile::group_for_layer(int32_t layer) const { + for (const auto& g : groups_) if (g.layer == layer) return &g; + return nullptr; +} + +bool RadFile::get_i(const char* key, int64_t* out) const { + for (uint64_t i = 0; i < hdr_->meta_count; ++i) + if (meta_[i].type == RAD_P_INT && std::strcmp(str(meta_[i].key), key) == 0) { + if (out) *out = meta_[i].v.i; + return true; + } + return false; +} + +bool RadFile::get_f(const char* key, double* out) const { + for (uint64_t i = 0; i < hdr_->meta_count; ++i) + if (std::strcmp(str(meta_[i].key), key) == 0) { + if (meta_[i].type == RAD_KV_F64) { if (out) *out = meta_[i].v.f; return true; } + if (meta_[i].type == RAD_P_INT) { if (out) *out = (double)meta_[i].v.i; return true; } + } + return false; +} + +const char* RadFile::get_s(const char* key, const char* dflt) const { + for (uint64_t i = 0; i < hdr_->meta_count; ++i) + if (meta_[i].type == RAD_P_STR && std::strcmp(str(meta_[i].key), key) == 0) + return str(meta_[i].v.s); + return dflt; +} + +/* ================================================================== writer */ + +RadWriter::~RadWriter() { if (began_) abort(); } + +int RadWriter::begin(const char* path) { + if (began_) return RAD_E_STATE; + if (!path || !*path) return RAD_E_INVAL; + + path_ = path; + spill_path_ = path_ + ".blob.tmp"; + sealed_ = late_ = false; + + fd_out_ = ::open(path_.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); + if (fd_out_ < 0) { RAD_ERR("%s: %s", path_.c_str(), std::strerror(errno)); return RAD_E_IO; } + + /* The data blob is spilled beside the target and spliced in at finish(). The tables in front + * of it cannot be sized until every weight has been added, and the blob is the model -- a + * 1.5 GB checkpoint is not going to be staged in RAM so the header can be back-patched. */ + fd_spill_ = ::open(spill_path_.c_str(), O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); + spill_base_ = 0; + if (fd_spill_ < 0) { + RAD_ERR("%s: %s", spill_path_.c_str(), std::strerror(errno)); + ::close(fd_out_); fd_out_ = -1; + return RAD_E_IO; + } + + began_ = true; + return RAD_OK; +} + +void RadWriter::abort() { + if (append_) { + /* The file is the caller's container, not ours to unlink: put its header back -- a no-op + * unless finish_append() failed inside that last write -- and cut the tail off. */ + if (fd_out_ >= 0) { + (void)!::pwrite(fd_out_, &old_hdr_, sizeof old_hdr_, 0); + (void)!::ftruncate(fd_out_, (off_t)old_size_); + ::close(fd_out_); + } + if (fd_spill_ >= 0) ::close(fd_spill_); + fd_out_ = fd_spill_ = -1; + began_ = append_ = false; + return; + } + if (fd_out_ >= 0) ::close(fd_out_); + if (fd_spill_ >= 0) ::close(fd_spill_); + if (!path_.empty()) ::unlink(path_.c_str()); + if (!spill_path_.empty()) ::unlink(spill_path_.c_str()); + fd_out_ = fd_spill_ = -1; + began_ = false; +} + +/* ------------------------------------------------------------------ append in place */ + +/* The processes other than this one that hold the file open or mapped. /proc//fd for an open + * descriptor and /proc//maps for a mapping whose descriptor was closed; a process this user + * cannot inspect is not counted, which is the same reach the caller has over that process. */ +static std::vector other_users(dev_t dev, ino_t ino) { + std::vector who; + DIR* d = ::opendir("/proc"); + if (!d) return who; + const long me = (long)::getpid(); + while (dirent* e = ::readdir(d)) { + char* end = nullptr; + const long pid = std::strtol(e->d_name, &end, 10); + if (!end || *end || pid <= 0 || pid == me) continue; + bool hit = false; + char dir[64]; + std::snprintf(dir, sizeof dir, "/proc/%ld/fd", pid); + if (DIR* f = ::opendir(dir)) { + while (dirent* x = ::readdir(f)) { + if (x->d_name[0] == '.') continue; + char link[384]; + std::snprintf(link, sizeof link, "%s/%s", dir, x->d_name); + struct stat st{}; + if (::stat(link, &st) == 0 && st.st_dev == dev && st.st_ino == ino) { + hit = true; + break; + } + } + ::closedir(f); + } + if (!hit) { + char maps[64]; + std::snprintf(maps, sizeof maps, "/proc/%ld/maps", pid); + if (FILE* m = std::fopen(maps, "r")) { + char line[4096]; + while (!hit && std::fgets(line, sizeof line, m)) { + unsigned maj = 0, mnr = 0; + unsigned long long inode = 0; + if (std::sscanf(line, "%*s %*s %*s %x:%x %llu", &maj, &mnr, &inode) == 3 && + inode == (unsigned long long)ino && maj == major(dev) && mnr == minor(dev)) + hit = true; + } + std::fclose(m); + } + } + if (hit) who.push_back(pid); + } + ::closedir(d); + return who; +} + +int RadWriter::begin_append(const char* path, const RadFile& old) { + if (began_) return RAD_E_STATE; + if (!path || !*path || !old.is_open()) return RAD_E_INVAL; + path_ = path; + spill_path_.clear(); + + fd_out_ = ::open(path, O_RDWR | O_CLOEXEC); + if (fd_out_ < 0) { RAD_ERR("%s: %s", path, std::strerror(errno)); return RAD_E_IO; } + struct stat st{}; + if (::fstat(fd_out_, &st) != 0) { + RAD_ERR("%s: %s", path, std::strerror(errno)); + ::close(fd_out_); fd_out_ = -1; + return RAD_E_IO; + } + /* The file `old` describes, unchanged since it was read: its header, byte for byte, and its + * length. Anything else and the directory being carried over names somebody else's bytes. */ + if (::pread(fd_out_, &old_hdr_, sizeof old_hdr_, 0) != (ssize_t)sizeof old_hdr_ || + std::memcmp(&old_hdr_, &old.header(), sizeof old_hdr_) != 0 || + (int64_t)st.st_size != old.size()) { + RAD_ERR("%s: not the container that was read, or it changed since", path); + ::close(fd_out_); fd_out_ = -1; + return RAD_E_STATE; + } + const std::vector who = other_users(st.st_dev, st.st_ino); + if (!who.empty()) { + RAD_ERR("%s is open in %zu other process(es), pid %ld first -- a running engine reads its " + "header through its mapping, and extending the file rewrites that header. Stop " + "it first.", path, who.size(), who[0]); + ::close(fd_out_); fd_out_ = -1; + return RAD_E_STATE; + } + + old_size_ = (int64_t)st.st_size; + old_data_off_ = old_hdr_.data_off; + append_base_ = (old_size_ + (int64_t)RAD_ALIGN_POOL - 1) / RAD_ALIGN_POOL * RAD_ALIGN_POOL; + fd_spill_ = ::dup(fd_out_); + spill_base_ = append_base_; + if (fd_spill_ < 0) { + RAD_ERR("%s: %s", path, std::strerror(errno)); + if (fd_spill_ >= 0) ::close(fd_spill_); + ::close(fd_out_); + fd_out_ = fd_spill_ = -1; + return RAD_E_IO; + } + append_ = true; + began_ = true; + return RAD_OK; +} + +int64_t RadWriter::add_existing(const Weight& w, const RadFile& old, const RadFileEntry& e) { + if (!began_ || !append_) return RAD_E_STATE; + /* The bytes and the encoding are the old entry's; what the entry SAYS about where it came from + * and which unit it moves with is the caller's, as a fresh write would record it. */ + RadFileEntry n = e; + n.name = intern(w.name); + n.quantizer = intern(w.quantizer); + n.options = intern(w.options); + n.enc = intern_encoding(old.encoding(e)); + n.layer = w.layer; + n.expert = w.expert; + n.slot = w.slot; + n.plane_first = (uint64_t)planes_.size(); + for (uint32_t k = 0; k < e.n_planes; ++k) { + planes_.push_back(old.plane(e, (int)k)); + written_.push_back((int64_t)old.plane(e, (int)k).bytes); + } + dir_.push_back(n); + dir_abs_.push_back(1); + return (int64_t)dir_.size() - 1; +} + +uint32_t RadWriter::intern_encoding(const RadEncoding& e) { + /* Zeroed before it is copied in, so the padding and the unused plane slots of a table row + * are zeros and two converts of one checkpoint compare equal byte for byte -- and compared + * in that form, so stray bytes in a caller's unused slots do not make a second row. */ + RadEncoding c; + std::memset(&c, 0, sizeof c); + std::memcpy(c.scheme, e.scheme, sizeof c.scheme); + std::memcpy(c.transform, e.transform, sizeof c.transform); + c.n_planes = e.n_planes; + for (int k = 0; k < e.n_planes && k < RAD_ENC_MAX_PLANES; ++k) c.plane[k] = e.plane[k]; + for (size_t i = 0; i < encs_.size(); ++i) + if (rad_enc_equal(&encs_[i], &c)) return (uint32_t)i; + encs_.push_back(c); + return (uint32_t)(encs_.size() - 1); +} + +rad_stroff RadWriter::intern(std::string_view s) { + if (s.empty()) return 0; + std::string key(s); + auto it = strmap_.find(key); + if (it != strmap_.end()) return it->second; + if (sealed_) late_ = true; + rad_stroff off = (rad_stroff)strblob_.size(); + strblob_.append(key); + strblob_.push_back('\0'); + strmap_.emplace(std::move(key), off); + return off; +} + +void RadWriter::meta_i(std::string_view k, int64_t v) { + if (sealed_) late_ = true; + RadFileKV kv{}; kv.key = intern(k); kv.type = RAD_P_INT; kv.v.i = v; meta_.push_back(kv); +} +void RadWriter::meta_f(std::string_view k, double v) { + if (sealed_) late_ = true; + RadFileKV kv{}; kv.key = intern(k); kv.type = RAD_KV_F64; kv.v.f = v; meta_.push_back(kv); +} +void RadWriter::meta_s(std::string_view k, std::string_view v) { + if (sealed_) late_ = true; + RadFileKV kv{}; kv.key = intern(k); kv.type = RAD_P_STR; kv.v.s = intern(v); meta_.push_back(kv); +} + +void RadWriter::add_profile(int32_t layer, int32_t expert, float share) { + if (sealed_) late_ = true; + RadFileProfile p{}; p.layer = layer; p.expert = expert; p.share = share; + prof_.push_back(p); +} + +/* Movement-unit bookkeeping. A unit is one (layer, expert) pair for a routed expert -- its + * gate/up/down are adjacent because the unit of transfer is an expert, not a tensor -- and one + * weight for everything else. */ +int RadWriter::check_unit_invariant(const Weight& w, uint64_t off, uint64_t bytes) { + const bool new_unit = (w.layer != cur_layer_ || w.expert != cur_expert_); + if (new_unit) { cur_layer_ = w.layer; cur_expert_ = w.expert; } + + if (w.expert < 0) { grp_layer_ = -2; return RAD_OK; } + + if (w.layer != grp_layer_) { + if (w.expert != 0) { + RAD_ERR("'%s': layer %d's experts start at %d. A layer's experts must be written " + "0..n-1 consecutively or the layer has no fixed stride.", + w.name.c_str(), w.layer, w.expert); + return RAD_E_INVAL; + } + grp_layer_ = w.layer; + grp_n_expert_ = 0; + grp_n_slot_ = 0; + grp_slot_seen_ = 0; + grp_first_off_ = off; + grp_expert_off_ = off; + grp_stride_ = 0; + grp_slot_bytes_.clear(); + } + + if (new_unit) { + if (w.expert != grp_n_expert_) { + RAD_ERR("'%s': layer %d expert %d follows expert %d. Experts must be written in " + "order.", w.name.c_str(), w.layer, w.expert, grp_n_expert_ - 1); + return RAD_E_INVAL; + } + if (grp_n_expert_ == 1) grp_stride_ = off - grp_first_off_; + if (grp_n_expert_ >= 1 && + off != grp_first_off_ + (uint64_t)grp_n_expert_ * grp_stride_) { + RAD_ERR("'%s': layer %d expert %d landed at %llu, not base + %d*%llu. The experts in " + "a layer differ in size, so the layer has no fixed stride.", + w.name.c_str(), w.layer, w.expert, (unsigned long long)off, + grp_n_expert_, (unsigned long long)grp_stride_); + return RAD_E_INVAL; + } + if (grp_n_expert_ == 1) grp_n_slot_ = grp_slot_seen_; + if (grp_n_expert_ >= 1 && grp_slot_seen_ != grp_n_slot_) { + RAD_ERR("'%s': layer %d expert %d has %d slots where expert 0 has %d.", + w.name.c_str(), w.layer, grp_n_expert_ - 1, grp_slot_seen_, grp_n_slot_); + return RAD_E_INVAL; + } + grp_expert_off_ = off; + grp_slot_seen_ = 0; + ++grp_n_expert_; + } + + if (w.slot != grp_slot_seen_) { + RAD_ERR("'%s': layer %d expert %d slot %d follows slot %d. Slots must be written 0..n-1.", + w.name.c_str(), w.layer, w.expert, w.slot, grp_slot_seen_ - 1); + return RAD_E_INVAL; + } + + /* Expert 0 defines the shape of a unit; every later expert must match it slot for slot. The + * offset arithmetic above cannot catch a size mismatch on its own: an oversized expert still + * lands at the right base, and only the NEXT one is displaced -- so an oversized LAST expert + * passes every offset check and leaves a container whose base + id*stride runs off the end of + * the group. Refusing here means the writer stops while the operator still has the checkpoint + * open and can fix the manifest. */ + if (grp_n_expert_ == 1) { + grp_slot_bytes_.push_back(bytes); + } else if ((size_t)w.slot < grp_slot_bytes_.size() && grp_slot_bytes_[(size_t)w.slot] != bytes) { + RAD_ERR("'%s': layer %d expert %d slot %d is %llu bytes where expert 0's is %llu. The " + "experts in a layer differ in size, so the layer has no fixed stride.", + w.name.c_str(), w.layer, w.expert, w.slot, (unsigned long long)bytes, + (unsigned long long)grp_slot_bytes_[(size_t)w.slot]); + return RAD_E_INVAL; + } + + ++grp_slot_seen_; + return RAD_OK; +} + +int64_t RadWriter::add_weight(const Weight& w) { + if (!began_ || sealed_) return RAD_E_STATE; + if (w.name.empty() || w.rank == 0 || w.rank > RAD_MAX_RANK) return RAD_E_INVAL; + if (!rad_enc_valid(&w.enc)) { + RAD_ERR("'%s': its encoding is not one the core can read", w.name.c_str()); + return RAD_E_INVAL; + } + for (uint32_t d = 0; d < w.rank; ++d) + if (w.shape[d] <= 0) { + RAD_ERR("'%s': extent %lld in dim %u", w.name.c_str(), (long long)w.shape[d], d); + return RAD_E_INVAL; + } + if (append_ && w.expert >= 0) { + RAD_ERR("'%s' is layer %d's expert %d, and a container extended in place cannot take a " + "new expert: a layer's experts sit at a fixed stride from each other, and one " + "written past the end joins no layer. Convert to a new file instead.", + w.name.c_str(), w.layer, w.expert); + return RAD_E_INVAL; + } + + /* Every entry starts on a movement-unit boundary. That costs up to 4 KiB of padding per + * matrix -- tens of megabytes on a large MoE -- and buys a transfer that never straddles a + * page needlessly. Its planes follow at RAD_ALIGN_SUB, a cacheline on the architectures in + * scope: SoA, so a code plane stays dense and a scale plane is its own stream. */ + int64_t rows = 0, cols = 0; + rad_enc_view(w.rank, w.shape, &rows, &cols); + const uint64_t off = (uint64_t)align_up(blob_bytes_, RAD_ALIGN_UNIT); + uint64_t end = off; + RadFileEntry e{}; + e.plane_first = (uint64_t)planes_.size(); + for (int k = 0; k < w.enc.n_planes; ++k) { + const int64_t bytes = rad_enc_plane_bytes(&w.enc.plane[k], rows, cols); + if (bytes <= 0) { + RAD_ERR("'%s': plane %d ('%s') of its encoding has no size over [%lld, %lld]", + w.name.c_str(), k, w.enc.plane[k].role, (long long)rows, (long long)cols); + planes_.resize((size_t)e.plane_first); + written_.resize((size_t)e.plane_first); + return RAD_E_INVAL; + } + RadFilePlane p{}; + p.offset = (uint64_t)align_up((int64_t)end, RAD_ALIGN_SUB); + p.bytes = (uint64_t)bytes; + end = p.offset + p.bytes; + planes_.push_back(p); + written_.push_back(0); + } + const int st = check_unit_invariant(w, off, end - off); + if (st < 0) { + planes_.resize((size_t)e.plane_first); + written_.resize((size_t)e.plane_first); + return st; + } + + e.name = intern(w.name); + e.quantizer = intern(w.quantizer); + e.options = intern(w.options); + e.enc = intern_encoding(w.enc); + e.rank = w.rank; + for (uint32_t i = 0; i < RAD_MAX_RANK; ++i) e.shape[i] = i < w.rank ? w.shape[i] : 0; + e.layer = w.layer; + e.expert = w.expert; + e.slot = w.slot; + e.n_planes = (uint32_t)w.enc.n_planes; + e.offset = off; /* blob-relative; finish() adds data_off */ + e.bytes = end - off; + blob_bytes_ = (int64_t)end; + + dir_.push_back(e); + dir_abs_.push_back(0); + return (int64_t)dir_.size() - 1; +} + +int64_t RadWriter::add_weight(const Weight& w, const void* const* planes) { + const int64_t idx = add_weight(w); + if (idx < 0) return idx; + for (int k = 0; k < w.enc.n_planes; ++k) + RAD_TRY(write_plane(idx, k, 0, planes[k], plane_bytes(idx, k))); + return idx; +} + +int64_t RadWriter::plane_bytes(int64_t idx, int k) const { + if (idx < 0 || idx >= (int64_t)dir_.size() || k < 0 || (uint32_t)k >= dir_[idx].n_planes) + return RAD_E_INVAL; + return (int64_t)planes_[dir_[idx].plane_first + (uint64_t)k].bytes; +} + +int RadWriter::write_plane(int64_t idx, int k, int64_t off, const void* data, int64_t bytes) { + if (!began_) return RAD_E_STATE; + if (idx < 0 || idx >= (int64_t)dir_.size() || dir_abs_[(size_t)idx] || k < 0 || + (uint32_t)k >= dir_[idx].n_planes) + return RAD_E_INVAL; + const size_t pi = (size_t)(dir_[idx].plane_first + (uint64_t)k); + const RadFilePlane& p = planes_[pi]; + if (off < 0 || bytes < 0 || (uint64_t)off > p.bytes || (uint64_t)bytes > p.bytes - (uint64_t)off || + (bytes > 0 && !data)) { + RAD_ERR("weight %lld plane %d: %lld bytes at %lld do not fit its %llu", (long long)idx, k, + (long long)bytes, (long long)off, (unsigned long long)p.bytes); + return RAD_E_INVAL; + } + const uint8_t* q = (const uint8_t*)data; + int64_t at = spill_base_ + (int64_t)p.offset + off, n = bytes; + while (n > 0) { + const ssize_t w = ::pwrite(fd_spill_, q, (size_t)n, (off_t)at); + if (w < 0) { + if (errno == EINTR) continue; + RAD_ERR("%s: %s", append_ ? path_.c_str() : spill_path_.c_str(), std::strerror(errno)); + return RAD_E_IO; + } + q += w; n -= w; at += w; + } + written_[pi] += bytes; + return RAD_OK; +} + +/* EVERY RESERVED BYTE WAS WRITTEN. A plane left short is a hole of zeros the reader cannot tell + * from codes -- a quantiser that returned early, a block loop with an off-by-one -- so the file is + * refused here, naming the weight, rather than written. Counted, not tracked by range: writes that + * overlapped would pass, and no producer here writes a byte twice. */ +int RadWriter::check_complete() const { + for (size_t i = 0; i < dir_.size(); ++i) { + if (dir_abs_[i]) continue; + for (uint32_t k = 0; k < dir_[i].n_planes; ++k) { + const size_t pi = (size_t)(dir_[i].plane_first + k); + if (written_[pi] != (int64_t)planes_[pi].bytes) { + RAD_ERR("'%s' plane %u: %lld of its %llu bytes were written", + strblob_.c_str() + dir_[i].name, k, (long long)written_[pi], + (unsigned long long)planes_[pi].bytes); + return RAD_E_STATE; + } + } + } + return RAD_OK; +} + +int RadWriter::set_vocab_section(const void* blob, int64_t bytes) { + if (!began_ || sealed_) return RAD_E_STATE; + if (!blob || bytes < (int64_t)sizeof(RadVocabHeader)) { + RAD_ERR("the vocab section is %lld bytes, shorter than its own header (%zu)", + (long long)bytes, sizeof(RadVocabHeader)); + return RAD_E_INVAL; + } + /* Sanity, here rather than at open: the reader would refuse this file, and a converter that + * writes a file its own reader refuses has wasted an hour of somebody's time. */ + const RadVocabHeader* h = (const RadVocabHeader*)blob; + auto fits = [&](uint64_t off, uint64_t n) { + return n == 0 || (off <= (uint64_t)bytes && n <= (uint64_t)bytes - off); + }; + if (!fits(h->tok_text_off, (uint64_t)h->n_tokens * sizeof(rad_stroff)) || + !fits(h->tok_score_off, h->tok_score_off ? (uint64_t)h->n_tokens * sizeof(float) : 0) || + !fits(h->tok_type_off, h->tok_type_off ? h->n_tokens : 0) || + !fits(h->merge_off, (uint64_t)h->n_merges * 2 * sizeof(uint32_t)) || + !fits(h->step_off, (uint64_t)h->n_steps * sizeof(RadVocabStep))) { + RAD_ERR("the vocab section's arrays do not fit inside its %lld bytes. Its offsets must be " + "SECTION-RELATIVE -- serialise with a section_file_off of 0 and let finish() " + "rebase them.", (long long)bytes); + return RAD_E_INVAL; + } + + vocab_blob_.assign((const uint8_t*)blob, (const uint8_t*)blob + bytes); + have_vocab_ = true; + return RAD_OK; +} + +/* ------------------------------------------------------------------ finish */ +static int write_all(int fd, const void* p, int64_t n) { + const uint8_t* q = (const uint8_t*)p; + while (n > 0) { + ssize_t w = ::write(fd, q, (size_t)n); + if (w < 0) { if (errno == EINTR) continue; return RAD_E_IO; } + q += w; n -= w; + } + return RAD_OK; +} + +static int pwrite_all(int fd, const void* p, int64_t n, int64_t at) { + const uint8_t* q = (const uint8_t*)p; + while (n > 0) { + ssize_t w = ::pwrite(fd, q, (size_t)n, (off_t)at); + if (w < 0) { if (errno == EINTR) continue; return RAD_E_IO; } + q += w; n -= w; at += w; + } + return RAD_OK; +} + +static int pad_file(int fd, int64_t n) { + static const uint8_t zero[65536] = {0}; + while (n > 0) { + int64_t c = std::min(n, (int64_t)sizeof zero); + RAD_TRY(write_all(fd, zero, c)); + n -= c; + } + return RAD_OK; +} + +/* Sections in header order, 8-aligned, then the blob at a 2 MiB boundary so the mapping can use + * huge pages. Interns the header's own strings, so it is the last thing that may. */ +void RadWriter::layout(RadFileHeader* hp) { + int64_t off = (int64_t)sizeof(RadFileHeader); + auto place8 = [&](int64_t bytes) { + off = align_up(off, 8); + int64_t at = off; + off += bytes; + return at; + }; + + RadFileHeader& h = *hp; + h = RadFileHeader{}; + h.magic = RAD_MAGIC; + h.version = RAD_FORMAT_VER; + h.arch_id = intern(arch_); + h.model_name = intern(model_); + h.quant = intern(quant_); + h.recipe = intern(recipe_); + h.created_by = intern(created_by_); + + /* Interning is done: everything after this point only reads the blob. */ + h.str_off = (uint64_t)place8((int64_t)strblob_.size()); + h.str_bytes = strblob_.size(); + h.meta_off = (uint64_t)place8((int64_t)(meta_.size() * sizeof(RadFileKV))); + h.meta_count = meta_.size(); + h.dir_off = (uint64_t)place8((int64_t)(dir_.size() * sizeof(RadFileEntry))); + h.dir_count = dir_.size(); + h.plane_off = (uint64_t)place8((int64_t)(planes_.size() * sizeof(RadFilePlane))); + h.plane_count= planes_.size(); + h.enc_off = (uint64_t)place8((int64_t)(encs_.size() * sizeof(RadEncoding))); + h.enc_count = encs_.size(); + h.vocab_off = (uint64_t)place8((int64_t)vocab_blob_.size()); + h.vocab_bytes= have_vocab_ ? vocab_blob_.size() : 0; + h.prof_off = (uint64_t)place8((int64_t)(prof_.size() * sizeof(RadFileProfile))); + h.prof_count = prof_.size(); + + h.data_off = (uint64_t)align_up(off, RAD_ALIGN_POOL); + h.data_bytes = (uint64_t)blob_bytes_; + h.file_bytes = h.data_off + h.data_bytes; +} + +int RadWriter::seal() { + if (!began_ || append_ || sealed_) return RAD_E_STATE; + for (int64_t n : written_) + if (n) { + RAD_ERR("%s: seal() after a plane was written; the blob is already in the spill", + path_.c_str()); + return RAD_E_STATE; + } + layout(&hdr_); + const int fd = ::dup(fd_out_); + if (fd < 0) { RAD_ERR("%s: %s", path_.c_str(), std::strerror(errno)); return RAD_E_IO; } + ::close(fd_spill_); + ::unlink(spill_path_.c_str()); + spill_path_.clear(); + fd_spill_ = fd; + spill_base_ = (int64_t)hdr_.data_off; + sealed_ = true; + return RAD_OK; +} + +int RadWriter::finish() { + if (!began_) return RAD_E_STATE; + if (late_) { + RAD_ERR("%s: a table changed after seal() fixed the layout", path_.c_str()); + abort(); + return RAD_E_STATE; + } + if (check_complete() < 0) { abort(); return RAD_E_STATE; } + if (append_) return finish_append(); + + RadFileHeader h{}; + if (sealed_) h = hdr_; + else layout(&h); + + /* Blob-relative to absolute. Both tables were built with offsets into the spill file, which + * is exactly the blob, so one add each. data_off is 2 MiB-aligned and every entry was already + * 4 KiB-aligned inside the blob, so the alignments survive the shift. */ + for (auto& e : dir_) e.offset += h.data_off; + for (auto& p : planes_) p.offset += h.data_off; + if (have_vocab_) { + auto* vh = (RadVocabHeader*)vocab_blob_.data(); + if (vh->tok_text_off) vh->tok_text_off += h.vocab_off; + if (vh->tok_score_off) vh->tok_score_off += h.vocab_off; + if (vh->tok_type_off) vh->tok_type_off += h.vocab_off; + if (vh->merge_off) vh->merge_off += h.vocab_off; + if (vh->step_off) vh->step_off += h.vocab_off; + } + + int st = RAD_OK; + int64_t at = 0; + auto emit = [&](const void* p, int64_t bytes, int64_t want_at) { + if (st < 0) return; + if (want_at > at) { st = pad_file(fd_out_, want_at - at); if (st < 0) return; at = want_at; } + st = write_all(fd_out_, p, bytes); + at += bytes; + }; + + emit(&h, (int64_t)sizeof h, 0); + emit(strblob_.data(), (int64_t)strblob_.size(), (int64_t)h.str_off); + emit(meta_.data(), (int64_t)(meta_.size() * sizeof(RadFileKV)), (int64_t)h.meta_off); + emit(dir_.data(), (int64_t)(dir_.size() * sizeof(RadFileEntry)), (int64_t)h.dir_off); + emit(planes_.data(), (int64_t)(planes_.size() * sizeof(RadFilePlane)), (int64_t)h.plane_off); + emit(encs_.data(), (int64_t)(encs_.size() * sizeof(RadEncoding)), (int64_t)h.enc_off); + if (have_vocab_) emit(vocab_blob_.data(), (int64_t)vocab_blob_.size(), (int64_t)h.vocab_off); + emit(prof_.data(), (int64_t)(prof_.size() * sizeof(RadFileProfile)), (int64_t)h.prof_off); + if (st < 0) { RAD_ERR("%s: %s", path_.c_str(), std::strerror(errno)); abort(); return st; } + + if (at < (int64_t)h.data_off) { + st = pad_file(fd_out_, (int64_t)h.data_off - at); + if (st < 0) { RAD_ERR("%s: %s", path_.c_str(), std::strerror(errno)); abort(); return st; } + at = (int64_t)h.data_off; + } + + /* SEALED, THE BLOB IS ALREADY HERE: every plane went to its final offset. The length is set + * explicitly because the blob's tail may be alignment the planes never wrote. */ + if (sealed_) { + if (::ftruncate(fd_out_, (off_t)h.file_bytes) != 0 || ::fsync(fd_out_) != 0) + RAD_ERR("%s: %s", path_.c_str(), std::strerror(errno)); + ::close(fd_out_); fd_out_ = -1; + ::close(fd_spill_); fd_spill_ = -1; + began_ = false; + return RAD_OK; + } + + /* Splice the spill in. copy_file_range stays in the kernel and reflinks on a filesystem that + * can, which on btrfs/xfs makes a 1.5 GB blob nearly free; the read/write fallback is there + * because tmpfs and older kernels cannot. The spill is exactly the blob's length: every + * reserved byte was written, and the last of them is the last plane's last byte. */ + if (::lseek(fd_spill_, 0, SEEK_SET) < 0) { + RAD_ERR("%s: %s", spill_path_.c_str(), std::strerror(errno)); abort(); return RAD_E_IO; + } + /* ============================== THE SPILL IS FREED AS IT IS COPIED ============================== + * + * A naive splice needs TWICE THE CONTAINER free, because the spill stays whole until the copy + * finishes and is only then unlinked. At container sizes in the hundreds of gigabytes that is + * the difference between a convert that fits on the disk and one that runs for half an hour, + * writes every weight, and then dies on the splice with ENOSPC. + * + * Punching a hole in the spill behind the copy gives the blocks back to the filesystem + * IMMEDIATELY, so the peak is one container plus a grain rather than two containers. ext4, + * xfs and btrfs all support it; where it is not supported fallocate fails and the copy + * proceeds exactly as it would without this. It is not an optimisation of the copy -- the + * bytes still move -- it is a bound on peak disk use. */ + int64_t left = blob_bytes_; + int64_t done = 0, punched = 0; + auto punch_behind = [&](bool final_grain) { +#if defined(__linux__) && defined(FALLOC_FL_PUNCH_HOLE) + /* 256 MiB at a time: enough that the syscall is noise against the copy, small enough that + * the residual peak overhead is negligible beside the container itself. */ + const int64_t grain = 256ll << 20; + const int64_t len = done - punched; + if (len <= 0 || (!final_grain && len < grain)) return; + if (::fallocate(fd_spill_, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, + (off_t)punched, (off_t)len) == 0) punched = done; +#else + (void)final_grain; +#endif + }; + +#if defined(__linux__) && defined(SYS_copy_file_range) + while (left > 0) { + /* AN EXPLICIT INPUT OFFSET, so the punch below knows where the copy has reached and the + * read() fallback can pick up from the same place. */ + loff_t oi = (loff_t)done; + ssize_t n = (ssize_t)syscall(SYS_copy_file_range, fd_spill_, &oi, + fd_out_, (loff_t*)nullptr, (size_t)left, 0u); + if (n <= 0) break; + left -= n; + done += n; + punch_behind(false); + } +#endif + if (left > 0) { + if (::lseek(fd_spill_, (off_t)done, SEEK_SET) < 0) { + RAD_ERR("%s: %s", spill_path_.c_str(), std::strerror(errno)); abort(); return RAD_E_IO; + } + std::vector buf(1 << 20); + while (left > 0) { + ssize_t r = ::read(fd_spill_, buf.data(), (size_t)std::min(left, (int64_t)buf.size())); + if (r < 0) { if (errno == EINTR) continue; RAD_ERR("%s: %s", spill_path_.c_str(), + std::strerror(errno)); abort(); return RAD_E_IO; } + if (r == 0) { RAD_ERR("%s: short read splicing the data blob", spill_path_.c_str()); + abort(); return RAD_E_IO; } + st = write_all(fd_out_, buf.data(), r); + if (st < 0) { RAD_ERR("%s: %s", path_.c_str(), std::strerror(errno)); abort(); return st; } + left -= r; + done += r; + punch_behind(false); + } + } + punch_behind(true); + + if (::fsync(fd_out_) != 0) { RAD_ERR("%s: fsync: %s", path_.c_str(), std::strerror(errno)); } + ::close(fd_out_); fd_out_ = -1; + ::close(fd_spill_); fd_spill_ = -1; + ::unlink(spill_path_.c_str()); + began_ = false; + return RAD_OK; +} + +/* The new weights are already past the old end (write_plane() put them there); what is left is the + * tables and, last, the header. */ +int RadWriter::finish_append() { + blob_bytes_ = align_up(blob_bytes_, RAD_ALIGN_UNIT); + const int64_t blob_end = append_base_ + blob_bytes_; + + int64_t off = blob_end; + auto place8 = [&](int64_t bytes) { + off = align_up(off, 8); + int64_t at = off; + off += bytes; + return at; + }; + + RadFileHeader h{}; + h.magic = RAD_MAGIC; + h.version = RAD_FORMAT_VER; + h.arch_id = intern(arch_); + h.model_name = intern(model_); + h.quant = intern(quant_); + h.recipe = intern(recipe_); + h.created_by = intern(created_by_); + + h.str_off = (uint64_t)place8((int64_t)strblob_.size()); + h.str_bytes = strblob_.size(); + h.meta_off = (uint64_t)place8((int64_t)(meta_.size() * sizeof(RadFileKV))); + h.meta_count = meta_.size(); + h.dir_off = (uint64_t)place8((int64_t)(dir_.size() * sizeof(RadFileEntry))); + h.dir_count = dir_.size(); + h.plane_off = (uint64_t)place8((int64_t)(planes_.size() * sizeof(RadFilePlane))); + h.plane_count= planes_.size(); + h.enc_off = (uint64_t)place8((int64_t)(encs_.size() * sizeof(RadEncoding))); + h.enc_count = encs_.size(); + h.vocab_off = (uint64_t)place8((int64_t)vocab_blob_.size()); + h.vocab_bytes= have_vocab_ ? vocab_blob_.size() : 0; + h.prof_off = (uint64_t)place8((int64_t)(prof_.size() * sizeof(RadFileProfile))); + h.prof_count = prof_.size(); + + /* The blob is the old one and the new weights after it: one span, still pool-aligned at its + * start, with the old tail's padding inside it. */ + h.data_off = old_data_off_; + h.data_bytes = (uint64_t)(blob_end - (int64_t)old_data_off_); + h.file_bytes = (uint64_t)off; + + for (size_t i = 0; i < dir_.size(); ++i) + if (!dir_abs_[i]) dir_[i].offset += (uint64_t)append_base_; + for (size_t i = 0; i < dir_.size(); ++i) + if (!dir_abs_[i]) + for (uint32_t k = 0; k < dir_[i].n_planes; ++k) + planes_[dir_[i].plane_first + k].offset += (uint64_t)append_base_; + if (have_vocab_) { + auto* vh = (RadVocabHeader*)vocab_blob_.data(); + if (vh->tok_text_off) vh->tok_text_off += h.vocab_off; + if (vh->tok_score_off) vh->tok_score_off += h.vocab_off; + if (vh->tok_type_off) vh->tok_type_off += h.vocab_off; + if (vh->merge_off) vh->merge_off += h.vocab_off; + if (vh->step_off) vh->step_off += h.vocab_off; + } + + int st = RAD_OK; + auto put = [&](const void* p, int64_t bytes, uint64_t at) { + if (st >= 0 && bytes > 0) st = pwrite_all(fd_out_, p, bytes, (int64_t)at); + }; + put(strblob_.data(), (int64_t)strblob_.size(), h.str_off); + put(meta_.data(), (int64_t)(meta_.size() * sizeof(RadFileKV)), h.meta_off); + put(dir_.data(), (int64_t)(dir_.size() * sizeof(RadFileEntry)), h.dir_off); + put(planes_.data(), (int64_t)(planes_.size() * sizeof(RadFilePlane)), h.plane_off); + put(encs_.data(), (int64_t)(encs_.size() * sizeof(RadEncoding)), h.enc_off); + if (have_vocab_) put(vocab_blob_.data(), (int64_t)vocab_blob_.size(), h.vocab_off); + put(prof_.data(), (int64_t)(prof_.size() * sizeof(RadFileProfile)), h.prof_off); + if (st >= 0 && ::ftruncate(fd_out_, (off_t)off) != 0) st = RAD_E_IO; + /* Everything the new header names is durable before the header names it. */ + if (st >= 0 && ::fsync(fd_out_) != 0) st = RAD_E_IO; + if (st < 0) { RAD_ERR("%s: %s", path_.c_str(), std::strerror(errno)); abort(); return st; } + + /* The way back: the old header and the old length. The old tables are still where that + * header points, so writing it back and truncating restores the file byte for byte. */ + { + const std::string bak = path_ + ".pre-append"; + const std::string tmp = bak + ".tmp"; + const int fb = ::open(tmp.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); + const int64_t len = old_size_; + if (fb < 0 || write_all(fb, &old_hdr_, sizeof old_hdr_) < 0 || + write_all(fb, &len, sizeof len) < 0 || ::fsync(fb) != 0) { + RAD_ERR("%s: %s", tmp.c_str(), std::strerror(errno)); + if (fb >= 0) ::close(fb); + abort(); + return RAD_E_IO; + } + ::close(fb); + if (::rename(tmp.c_str(), bak.c_str()) != 0) { + RAD_ERR("%s: %s", bak.c_str(), std::strerror(errno)); + abort(); + return RAD_E_IO; + } + } + + if (pwrite_all(fd_out_, &h, (int64_t)sizeof h, 0) < 0 || ::fsync(fd_out_) != 0) { + RAD_ERR("%s: writing the header: %s", path_.c_str(), std::strerror(errno)); + abort(); + return RAD_E_IO; + } + ::close(fd_out_); fd_out_ = -1; + ::close(fd_spill_); fd_spill_ = -1; + began_ = append_ = false; + return RAD_OK; +} + +} /* namespace rad */ diff --git a/core/format/radfile.h b/core/format/radfile.h new file mode 100644 index 00000000..7020b261 --- /dev/null +++ b/core/format/radfile.h @@ -0,0 +1,373 @@ +/* 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 +#include +#include +#include +#include + +namespace rad { + +/* ================================================================== vocab */ +/* The MUTABLE side of the vocab -- VocabBuild, the tokenizer.json interpreter and the serialiser + * that turns one into a RadVocabHeader -- belongs to core/text, because interpreting a declared + * normaliser chain is that component's whole job (spec §12). What belongs here is the container's + * half of the contract, and it is two things: + * + * 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 groups_; + std::unordered_map 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 + * `.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 dir_abs_; + + std::string arch_, model_, quant_, recipe_, created_by_; + + std::string strblob_{std::string(1, '\0')}; + std::unordered_map strmap_; + std::vector meta_; + std::vector dir_; + std::vector planes_; + std::vector written_; /* parallel to planes_ */ + std::vector encs_; + std::vector prof_; + + /* The vocab section, assembled in memory and appended verbatim. */ + std::vector 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 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 */ diff --git a/core/format/recipe.cpp b/core/format/recipe.cpp new file mode 100644 index 00000000..92218728 --- /dev/null +++ b/core/format/recipe.cpp @@ -0,0 +1,172 @@ +/* recipe.cpp -- see recipe.h. */ +#include "recipe.h" + +#include +#include +#include + +namespace rad { + +std::string RecipeRule::options_text() const { + std::vector> 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 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 */ diff --git a/core/format/recipe.h b/core/format/recipe.h new file mode 100644 index 00000000..bef90067 --- /dev/null +++ b/core/format/recipe.h @@ -0,0 +1,55 @@ +/* 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 +#include +#include + +namespace rad { + +struct RecipeRule { + std::string pattern, quantizer; + std::vector> options; /* in the order written */ + std::string origin; /* "file:12" or "--quant" */ + + /* The options as one canonical string, `key=value` comma-separated and sorted by key: what a + * container entry records and what --reuse compares, however the rule spelled them. */ + 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& 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 rules_; +}; + +} /* namespace rad */ diff --git a/core/format/safetensors.cpp b/core/format/safetensors.cpp new file mode 100644 index 00000000..ea8b8c9b --- /dev/null +++ b/core/format/safetensors.cpp @@ -0,0 +1,373 @@ +/* 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 +#include +#include +#include +#include +#include +#include +#include + +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* 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 */ diff --git a/core/format/safetensors.h b/core/format/safetensors.h new file mode 100644 index 00000000..f9096264 --- /dev/null +++ b/core/format/safetensors.h @@ -0,0 +1,67 @@ +/* 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 +#include +#include + +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 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& 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 tensors_; + std::unordered_map index_; +}; + +/* model.safetensors.index.json -> { tensor name: shard filename }. A single-file checkpoint has + * no index; the caller falls back to opening model.safetensors directly. */ +int st_load_index(const std::string& index_path, + std::unordered_map* out); + +} /* namespace rad */ diff --git a/core/format/share.cpp b/core/format/share.cpp new file mode 100644 index 00000000..dad88708 --- /dev/null +++ b/core/format/share.cpp @@ -0,0 +1,162 @@ +/* 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 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 */ diff --git a/core/format/share.h b/core/format/share.h new file mode 100644 index 00000000..53672495 --- /dev/null +++ b/core/format/share.h @@ -0,0 +1,40 @@ +/* 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 +#include + +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 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 */ diff --git a/core/format/tunecache.cpp b/core/format/tunecache.cpp new file mode 100644 index 00000000..94baa036 --- /dev/null +++ b/core/format/tunecache.cpp @@ -0,0 +1,267 @@ +/* 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 +#include +#include +#include +#include +#include +#include +#include + +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 split_ws_only(std::string_view s) { + std::vector 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 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>& c) { + std::vector 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> TuneCache::parse_choice(std::string_view s) { + std::vector> 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 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 */ diff --git a/core/format/tunecache.h b/core/format/tunecache.h new file mode 100644 index 00000000..60a69ffc --- /dev/null +++ b/core/format/tunecache.h @@ -0,0 +1,112 @@ +/* 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/.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 ` must equal the reader's own key + * `#...` comment, ignored + * otherwise ` ` + * + * 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 +#include +#include +#include + +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& 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>& 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> 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 rows_; + std::unordered_map index_; +}; + +/* The machine half of the key. Derived from the device layer, so it changes when the card does. + * Lives beside the cache and not inside it, because the cache is pure file I/O and testable + * without a device. */ +std::string rad_machine_key(); + +} /* namespace rad */ diff --git a/core/gen_config.cpp b/core/gen_config.cpp new file mode 100644 index 00000000..7764b126 --- /dev/null +++ b/core/gen_config.cpp @@ -0,0 +1,118 @@ +/* gen_config.cpp -- reading a checkpoint's own sampling. The header carries the argument. */ +#include "gen_config.h" + +#include "rad_internal.h" + +#include + +#include +#include +#include +#include + +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()) { out->temp = 0.0f; return true; } + + it = j.find("temperature"); + if (it != j.end() && it->is_number()) take("temperature", src, it->get(), 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(), 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(), 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(); + /* -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(f)), std::istreambuf_iterator()); + return gen_sampling_parse(text, path.c_str(), out); +} + +bool gen_sampling_from_kv(const std::function& get, GenSampling* out) { + /* REBUILT AS JSON RATHER THAN PARSED FIELD BY FIELD, so that a value written by rad-convert + * and a value read out of the original file go through exactly one set of range checks and + * one reading of `do_sample`. Two parsers for one schema is how the two come to disagree. */ + 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 */ diff --git a/core/gen_config.h b/core/gen_config.h new file mode 100644 index 00000000..1977d72f --- /dev/null +++ b/core/gen_config.h @@ -0,0 +1,73 @@ +/* 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 +#include + +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& get, GenSampling* out); + +/* `.rad` -> `.generation.json`. + * + * THE SIDECAR EXISTS BECAUSE A CONTAINER CANNOT BE EDITED. Metadata lives ahead of the weight + * data, so adding a key to a converted model means rewriting every byte of it, and a container + * that carries no `generation.*` metadata reads its sampling from nowhere. A file beside it is + * the one way to correct such a container without converting the weights a second time. */ +std::string gen_sidecar_path(const std::string& model_path); + +} /* namespace rad */ diff --git a/core/kld.cpp b/core/kld.cpp new file mode 100644 index 00000000..ba9f1647 --- /dev/null +++ b/core/kld.cpp @@ -0,0 +1,600 @@ +/* kld.cpp -- see kld.h. */ +#include "kld.h" + +#include "rad_internal.h" +#include "rad_plugin.h" +#include "text/tokenizer.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +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(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(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(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(h > 2 ? h - 2 : 1, 1, 32); +} + +/* The q-quantile by linear interpolation between order statistics, numpy's default. */ +double quantile(const std::vector& 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 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& 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::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 Kld::tokens(size_t d) const { + const Doc& doc = docs_[d]; + return std::vector(tokens_.begin() + doc.off, tokens_.begin() + doc.off + doc.n); +} + +int Kld::open(const Config& cfg, std::shared_ptr 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& 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& 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 ids; + RAD_TRY(tok.encode(j["prompt"].get(), 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(); + d.score_from = jd.at("score_from").get(); + d.row0 = jd.at("row0").get(); + 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& spans, const std::vector& shards) { + std::vector 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 next{0}; + auto work = [&] { + std::vector 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)worker_count(), jobs.size()); + std::vector 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& sh, std::vector& f16) { + float m = -std::numeric_limits::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& sh, std::vector& f16) { + float m = -std::numeric_limits::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& docs) { + std::vector 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 all(docs_.size()); + std::map> 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 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 */ diff --git a/core/kld.h b/core/kld.h new file mode 100644 index 00000000..3be7d3eb --- /dev/null +++ b/core/kld.h @@ -0,0 +1,140 @@ +/* kld.h -- the KL divergence of this model against a recorded reference, at every scored position + * of a fixed corpus. + * + * TWO RUNS, ONE YARDSTICK. `--kld-record DIR` runs the corpus through the model that defines the + * answer -- the bf16 checkpoint -- and writes its log-probabilities over the whole vocabulary at + * every scored position, once. `--kld-ref DIR` runs a candidate over the same tokens and compares + * its own logits against what DIR holds, row by row, so a candidate costs one prefill of the + * corpus and the reference is never computed again. + * + * WHAT IS REPORTED is the distribution of the per-position KL(P_ref || Q_candidate): its mean, + * median, 99th, 99.9th and 99.99th percentiles and maximum, the top-1 agreement (the candidate's + * argmax is the reference's), and both models' perplexity on the corpus's own next tokens. The + * tail is the point: a quantised model whose mean KL is small can still be confidently wrong at + * one position in ten thousand, and that is the position a user sees. + * + * THE WHOLE VOCABULARY, NOT A TOP-K. A KL over a truncated support is a lower bound that is + * tightest where it matters least: a peaked distribution keeps its mass in the top few tokens and + * a flat one -- the high-KL tail -- does not. + * + * THE REFERENCE FILES (DIR): + * kld.json the manifest: the model, the corpus, every document's source, token count, first + * scored position and first row. Written LAST, so a run that dies leaves a + * directory that no --kld-ref will read. + * tokens.i32 every document's tokens, concatenated: a candidate is scored on the tokens the + * reference saw, not on a re-tokenisation that could differ. + * logp.f16 [rows, n_vocab] log-probabilities, f16. Near log p = 0 an f16 has its finest + * resolution, and the tail tokens it rounds coarsely carry almost no mass. + * top.bin [rows, kKldTop] {int32 id, f32 log p}: the most likely tokens exactly, which is + * where the KL of a confident position lives and where f16 would cost ~1e-4 nats. + * rows.f32 [rows, 2] the reference's own next-token NLL and entropy. + * + * Document d scores positions [score_from, n - 1): the logits at p predict token p + 1, and the + * last token predicts nothing in the corpus. Its row r is row0 + p - score_from. + */ +#pragma once +#include "rad_core.h" + +#include +#include +#include +#include +#include + +namespace rad { + +class Vocab; + +/* One scoring entry's rows of a step: request `id`'s prompt positions [pos0, pos0 + n) are rows + * [row0, row0 + n) of the block the engine copied back. */ +struct KldSpan { + uint64_t id = 0; + int64_t pos0 = 0; + int64_t n = 0; + int64_t row0 = 0; +}; + +/* One rank's part of that block: its rows of `width` f32 logits, the vocabulary from `vocab0`. */ +struct KldShard { + const float* rows = nullptr; + int64_t vocab0 = 0; + int64_t width = 0; +}; + +/* The exact head kept beside every f16 row. */ +static constexpr int kKldTop = 16; + +class Kld { +public: + Kld(); + ~Kld(); + + /* Reads the corpus and creates DIR (record), or reads DIR's manifest and opens its rows (ref). + * `model` names this run's model in the manifest and the report. */ + int open(const Config& cfg, std::shared_ptr vocab, int64_t n_vocab, + const std::string& model); + + /* The two halves of open() for documents already tokenised, which is what a test drives: + * add_doc() each document, then record_into() creates DIR. score_against() is the ref mode + * whole. */ + int add_doc(const std::string& source, const std::vector& ids, int64_t score_from); + int record_into(const std::string& dir, int64_t n_vocab, const std::string& model); + int score_against(const std::string& dir, const std::string& out, int64_t n_vocab, + const std::string& model); + + size_t n_docs() const { return docs_.size(); } + /* Document d's tokens, and the request id the engine submits it under: d + 1. */ + std::vector tokens(size_t d) const; + int64_t n_rows() const { return n_rows_; } + int64_t rows_done() const { return done_n_.load(std::memory_order_relaxed); } + + /* A step's scored rows. Rows outside a document's scored range are skipped; a row seen twice + * -- a document re-prefilled after preemption -- is simply computed again. Blocks until every + * row is written (record) or scored (ref): the engine reuses the block at the next step. */ + int score(const std::vector& spans, const std::vector& shards); + + /* Record: checks every row was written and writes the manifest. Ref: the report, printed and, + * with --kld-out, written. */ + int finish(); + +private: + struct Doc { + std::string source; + int64_t off = 0; /* into tokens_ */ + int64_t n = 0; + int64_t score_from = 0; + int64_t row0 = 0; + int64_t rows() const { return n - 1 - score_from; } + }; + struct Job { + int64_t row; /* the reference's row */ + int64_t at; /* the row in the copied block */ + int32_t next; /* the corpus's next token */ + }; + + int load_corpus(const Config& cfg, const std::shared_ptr& vocab); + int load_ref(const std::string& dir); + void size_rows(); + void record_row(const Job& j, const std::vector& sh, std::vector& f16); + void score_row(const Job& j, const std::vector& sh, std::vector& f16); + int report(); + + bool record_ = false; + std::string dir_, out_, model_, ref_model_, corpus_; + uint64_t corpus_hash_ = 0; + int64_t n_vocab_ = 0; + std::vector tokens_; + std::vector docs_; + int64_t n_rows_ = 0; + int fd_logp_ = -1, fd_top_ = -1, fd_rows_ = -1; + + /* Per reference row. `seen_` marks a row written or scored; the rest is the ref mode's. */ + std::vector seen_; + std::atomic done_n_{0}; + std::vector kl_, nll_q_, nll_p_; + std::vector top1_; + std::atomic io_err_{0}; + float f16_lut_[65536]; +}; + +} /* namespace rad */ diff --git a/core/main.cpp b/core/main.cpp new file mode 100644 index 00000000..5bf05377 --- /dev/null +++ b/core/main.cpp @@ -0,0 +1,19 @@ +/* main.cpp -- the entry point. Everything it does is in engine.h's comment; this file only turns + * a command line into that sequence and a status into an exit code. + */ +#include "engine.h" + +int main(int argc, char** argv) { + rad::Config cfg; + int s = rad::config_parse(argc, argv, &cfg); + if (s == 1) { rad::config_usage(argv[0]); return 0; } + if (s < 0) { rad::config_usage(argv[0]); return 2; } + + rad::Engine engine(std::move(cfg)); + + s = engine.start(); + if (s < 0) return 1; /* start() already said what and why */ + + if (engine.config().debug_graph) return engine.dump(); + return engine.serve() < 0 ? 1 : 0; +} diff --git a/core/mem/kv.cpp b/core/mem/kv.cpp new file mode 100644 index 00000000..e74c4874 --- /dev/null +++ b/core/mem/kv.cpp @@ -0,0 +1,1529 @@ +/* kv.cpp -- see kv.h. */ +#include "mem/kv.h" + +#include +#include + +namespace rad { + +const std::vector KVManager::kNoBlocks; + +/* ------------------------------------------------------------------ group sizing */ + +static int64_t ceil_div(int64_t a, int64_t b) { return b > 0 ? (a + b - 1) / b : 0; } + +BundleComparison compare_bundling(const std::vector& bundles) { + BundleComparison c; + c.bundles = bundles; + if (bundles.empty()) return c; + + auto groups = [&](int64_t g) { + int64_t n = 0; for (int64_t b : bundles) n += ceil_div(b, g); return n; + }; + auto slots = [&](int64_t g) { + int64_t n = 0; for (int64_t b : bundles) n += ceil_div(b, g) * g; return n; + }; + + const int64_t lo = *std::min_element(bundles.begin(), bundles.end()); + const int64_t hi = *std::max_element(bundles.begin(), bundles.end()); + + /* vLLM's rule, transcribed: the smallest bundle, escaping to the largest when they are within + * 1.5x (gpt-oss-20b + eagle is 12 sw + 13 full, and padding to (13,13) beats (12,24)). */ + c.stock_group_size = (hi * 2 < lo * 3) ? hi : lo; + c.stock_groups = groups(c.stock_group_size); + c.stock_slots = slots(c.stock_group_size); + + /* The least-waste answer under the same scheme: least slots, tie-broken on fewer groups, under + * a hard cap of the stock group count -- without the cap, size 1 always wins on padding and + * drowns the scheduler in per-group bookkeeping. */ + const int64_t cap = c.stock_groups; + int64_t best = c.stock_group_size; + for (int64_t g = 1; g <= hi; ++g) { + if (groups(g) > cap) continue; + if (std::pair{slots(g), groups(g)} < + std::pair{slots(best), groups(best)}) best = g; + } + c.patched_group_size = best; + c.patched_groups = groups(best); + c.patched_slots = slots(best); + + /* Ours. One group per state kind, each with its own pool, so there is nothing to pad up to. */ + c.our_groups = (int64_t)bundles.size(); + c.our_slots = 0; for (int64_t b : bundles) c.our_slots += b; + return c; +} + +std::string BundleComparison::report() const { + std::string b; + for (size_t i = 0; i < bundles.size(); ++i) + b += fmt("%s%lld", i ? "/" : "", (long long)bundles[i]); + return fmt("KV layer bundles %s (%lld real layers)\n" + " vLLM stock size %2lld -> %2lld groups, %3lld slots (%lld padding)\n" + " least-waste size %2lld -> %2lld groups, %3lld slots (%lld padding)\n" + " radiance per state kind, own pool -> %2lld groups, %3lld slots (0 padding)\n", + b.c_str(), (long long)our_slots, + (long long)stock_group_size, (long long)stock_groups, (long long)stock_slots, + (long long)(stock_slots - our_slots), + (long long)patched_group_size, (long long)patched_groups, (long long)patched_slots, + (long long)(patched_slots - our_slots), + (long long)our_groups, (long long)our_slots); +} + +/* ------------------------------------------------------------------ configure */ + +static const char* kv_kind_name(int k) { + switch (k) { + case RAD_KV_FULL: return "full"; + case RAD_KV_WINDOW: return "window"; + case RAD_KV_LINEAR: return "linear"; + case RAD_KV_CONV: return "conv"; + default: return "?"; + } +} + +/* THE PLAN AND THE CARVE ARE SEPARATE BECAUSE THE BUDGET IS DECIDED FROM THE PLAN. + * + * Every per-group size here -- the page, the per-sequence state, the fixed floor -- is a function + * of the declaration and the run configuration alone, and NONE of it depends on how many bytes the + * pool ends up with. That matters because core/mem/vram_budget.cpp has to know what a full KV + * cache would cost BEFORE the pools are allocated: a share larger than the contexts the cache can + * address is VRAM that nothing will ever touch, left out of the weight plane for nothing. So the + * budget resolver plans the groups, asks ceiling() what they could use, and caps the share there. + * Splitting the function is what makes that one code path instead of two that have to agree. + * + * plan_groups() fills plans_ and fixed_; carve() spends a pool against them; configure() is both, + * which is what the engine calls. */ +int KVManager::configure(const std::vector& groups, const Config& cfg, + Pool& kv_pool) { + RAD_TRY(plan_groups(groups, cfg)); + return carve(kv_pool); +} + +int KVManager::plan_groups(const std::vector& groups, const Config& cfg) { + /* The snapshot count is the operator's, through --checkpoint-slots. Nothing here derives it. */ + const int64_t budget_ckpts = cfg.checkpoint_slots > 0 ? cfg.checkpoint_slots : 0; + + forget(); + max_seqs_ = cfg.max_seqs > 0 ? cfg.max_seqs : 1; + max_ctx_ = cfg.max_ctx > 0 ? cfg.max_ctx : 0; + max_tok_ = cfg.max_tok > 0 ? cfg.max_tok : 0; + + if (groups.empty()) { + RAD_ERR("KV manager: no KV groups were declared; the architecture plugin declares at " + "least one (spec §7.2)"); + return RAD_E_INVAL; + } + + std::vector bundles; + for (size_t i = 0; i < groups.size(); ++i) { + /* HANDLE 0 IS THE NULL GROUP. The builder reserves slot 0 of every handle table so that a + * zero handle means "none" (rad_builder.cpp), and every loop there starts at 1. A loop + * here that starts at 0 without this case refuses the sentinel by name -- "no layers are + * bound to it" -- on every real model. + * + * The placeholder is PUSHED rather than skipped, because plan() indexes plans_ by the + * handle. A default-constructed plan is inert everywhere it is walked: 0 blocks and 0 + * states give empty free lists, and a sequence holds nothing in it. */ + if (i == 0) { + KVGroupPlan null_plan; + null_plan.index = 0; + null_plan.name = "(none)"; + /* NOT RAD_KV_FULL, which is what a zero-initialised kind would be: -1 makes both + * paged() and stateful() false, so every loop that switches on the kind skips it + * instead of taking the paged branch and dividing by a zero block size. */ + null_plan.kind = -1; + plans_.push_back(std::move(null_plan)); + /* NOT in `bundles`: that list feeds the layer-bundling comparison report, and a zero + * entry would report a group with no layers as the smallest real one. */ + continue; + } + const KVGroupInfo& g = groups[i]; + KVGroupPlan p; + p.index = (int32_t)i; + p.name = g.name.empty() ? fmt("kv%zu", i) : g.name; + p.kind = g.decl.kind; + p.n_layers = (int64_t)g.layers.size(); + + if (p.n_layers <= 0) { + RAD_ERR("KV group '%s': no layers are bound to it. rad_bind_layer_kv() is what tells " + "the block manager how many state instances a sequence owns; without it the " + "group's page size is a guess and this component does not guess.", + p.name.c_str()); + return RAD_E_INVAL; + } + const int64_t elt = rad_dtype_bytes(g.decl.dtype, 1); + if (elt <= 0) { + RAD_ERR("KV group '%s': dtype %u has no core-known size", p.name.c_str(), g.decl.dtype); + return RAD_E_DTYPE; + } + bundles.push_back(p.n_layers); + + if (p.kind == RAD_KV_FULL || p.kind == RAD_KV_WINDOW) { + p.block_size = g.block_size; + if (p.block_size <= 0) { + RAD_ERR("KV group '%s': block size is 0. It comes off the resolved attention " + "kernel's constraints at declare, never from a core constant (spec §7.2) " + "-- so a 0 here means the attention op for this group did not resolve.", + p.name.c_str()); + return RAD_E_NOKERNEL; + } + /* One page covers every layer bound to the group. That is where the zero-padding + * property lives: there is no uniform page size across groups to round up to. */ + p.bytes_per_block = g.bytes_per_block > 0 + ? g.bytes_per_block + : p.block_size * g.decl.n_head_kv * g.decl.head_dim * elt * 2 * p.n_layers; + if (p.bytes_per_block <= 0) { + RAD_ERR("KV group '%s': page size computes to 0 (n_head_kv=%lld head_dim=%lld)", + p.name.c_str(), (long long)g.decl.n_head_kv, (long long)g.decl.head_dim); + return RAD_E_INVAL; + } + if (p.kind == RAD_KV_WINDOW) { + if (g.decl.window <= 0) { + RAD_ERR("KV group '%s': RAD_KV_WINDOW with window 0", p.name.c_str()); + return RAD_E_INVAL; + } + /* +1 because a window that is not block-aligned straddles one extra block. */ + p.window_blocks = ceil_div(g.decl.window, p.block_size) + 1; + } + } else if (p.kind == RAD_KV_LINEAR || p.kind == RAD_KV_CONV) { + if (p.kind == RAD_KV_CONV) { + /* A rolling window of conv_width-1 + n_spec entries, so a speculative rejection is + * a change of read offset rather than a recompute (spec §10). The engine's + * contract is that the kernel pair supports that; the manager's job is to make the + * slot big enough for it. */ + p.conv_slots = (g.decl.conv_width > 0 ? g.decl.conv_width - 1 : 0) + + (cfg.n_spec > 0 ? cfg.n_spec : 0); + if (p.conv_slots <= 0) { + RAD_ERR("KV group '%s': conv_width %lld with n_spec %d gives 0 slots", + p.name.c_str(), (long long)g.decl.conv_width, cfg.n_spec); + return RAD_E_INVAL; + } + p.bytes_per_state = g.bytes_per_state > 0 + ? g.bytes_per_state + : p.conv_slots * g.decl.n_head_kv * g.decl.head_dim * elt * p.n_layers; + } else { + p.bytes_per_state = g.bytes_per_state > 0 + ? g.bytes_per_state + : g.decl.n_head_kv * g.decl.state_dim[0] * g.decl.state_dim[1] * elt + * p.n_layers; + /* SPECULATION HAS NOWHERE TO PUT WHAT IT CANNOT COMMIT YET. A verify step runs + * 1 + n_spec tokens through the recurrence before anyone knows which survive, so + * on a rejection the state has folded in tokens the model never emitted -- fluent + * output that drifts, which nothing would report. + * + * The obvious fix is one state per candidate, which is what the plain reading of + * gdn_recurrent_update's state_index asks for. It is also gigabytes a SEQUENCE on a + * real model, tens of gigabytes at a serving concurrency, which no engine can pay. + * The one libr4d implements instead keeps ONE committed state and, beside it, the + * handful of numbers each token's rank-1 update needs -- its normalised k, its v, + * its decay and its beta. That block is RU_TMAX * (4*head_k + head_v + 8) floats a + * head against head_v * head_k for the state, so it fits inside a second slot; the + * next step replays the accepted prefix onto the anchor out of it and starts from a + * state that carries exactly the tokens that survived. + * + * Two slots a sequence, and the second is scratch the kernel owns. The engine's + * side of the bargain is that both are ZEROED when the slot is handed out (a zero + * factor replays as the identity, which is what the first step after a prefill + * needs) and that state_index is wide enough to name them. */ + p.state_copies = cfg.n_spec > 0 ? 2 : 1; + } + if (p.bytes_per_state <= 0) { + RAD_ERR("KV group '%s': per-sequence state computes to 0", p.name.c_str()); + return RAD_E_INVAL; + } + /* Exactly one slot per concurrent sequence, times whatever the kernel needs beside + * it. Not a heuristic: a sequence owns exactly one recurrent state, so max_seqs is + * the count of LOGICAL states, full stop. */ + p.n_states = max_seqs_ * p.state_copies; + } else { + RAD_ERR("KV group '%s': unknown kind %d", p.name.c_str(), p.kind); + return RAD_E_INVAL; + } + plans_.push_back(std::move(p)); + } + bundling_ = compare_bundling(bundles); + + /* ---- fixed costs first: they are not negotiable and they are not per-token ---- */ + checkpoint_bytes_ = 0; + for (const auto& p : plans_) if (p.stateful()) checkpoint_bytes_ += p.bytes_per_state; + + /* EVERY RESERVATION IS PADDED TO RAD_ALIGN_UNIT AND THE BUDGET HAS TO SAY SO. Summing the + * fixed costs as raw bytes leaves the paged split free to spend the difference, and the plan + * then reports a fit that the last reservation does not get. + * + * It takes an awkward size to show: a state or checkpoint whose byte count sits just past an + * alignment boundary pushes most of a unit of padding into every following reservation, so the + * shortfall grows with the slot count while each individual number still looks right. + * + * Padded per RESERVATION and not once at the end, because that is how the pool spends it: one + * align_up per reserve() call, whatever the bytes. */ + int64_t fixed = 0; + for (const auto& p : plans_) + if (p.stateful()) fixed += align_up(p.bytes_per_state * p.n_states, RAD_ALIGN_UNIT); + /* A SLOT IS ELASTIC ONLY WHEN A SNAPSHOT IS WORTH A GRANULE, and the stride follows from + * that. Committing and releasing a slot on its own needs the stride to be a whole number of + * granules: a commit rounds outward and a release rounds inward, so a straddling stride + * would leave every slot's last partial granule backed for the life of the process and let + * one slot's commit back part of its neighbour. + * + * That rounding is free on a linear-attention model, where a snapshot is a sizeable fraction + * of a gigabyte. It is not free on a small one: a 16 KiB snapshot rounded to a 2 MiB granule + * is 128x the address space to manage a charge that was never worth managing. Below a + * granule the slots stay in the eagerly committed region, where they cost what they say + * they cost and nothing reclaims them because there is nothing to reclaim. */ + const int64_t granule = Pool::granule(); + ck_elastic_ = granule > 0 && checkpoint_bytes_ >= granule; + ck_stride_ = align_up(checkpoint_bytes_, ck_align()); + /* AND THE PAD IN FRONT OF THE REGION IS PART OF ITS COST. The slots are reserved LAST, after + * every group, and on a ck_align() boundary -- so the region starts up to one alignment unit + * past wherever the groups happened to end. Where that is cannot be known here, because the + * paged split below is what decides it, so the whole unit is reserved rather than the exact + * pad: it is at most one commit granule against a pool measured in gigabytes, and the + * alternative is a budget the LAST slot falls off the end of -- a refusal at load on some + * models and not others, depending on where the groups happened to end. */ + const int64_t ck_pad = budget_ckpts > 0 ? ck_align() : 0; + const int64_t ck_total = budget_ckpts * ck_stride_ + ck_pad; + fixed += ck_total; + /* And one unit a paged group, for the same reason: a page size that is not a multiple of the + * alignment pads too, and the carve below hands the groups everything that is left. */ + for (const auto& p : plans_) if (p.paged()) fixed += RAD_ALIGN_UNIT; + + fixed_ = fixed; + ck_total_ = ck_total; + ckpts_ = budget_ckpts; + return RAD_OK; +} + +/* WHAT A FULL CACHE WOULD COST, in bytes, for `ctx` tokens on every one of max_seqs sequences. + * The paged groups are the only elastic term; a windowed group cannot address past its window and + * is capped there, which is the same cap carve() applies and for the same reason. Anything above + * this number is memory the block manager can never hand out, and it is the whole reason + * plan_groups() is callable on its own: the budget resolver asks this before a pool exists. */ +int64_t KVManager::ceiling(int64_t ctx) const { + if (ctx <= 0) return 0; + int64_t need = fixed_; + for (const auto& p : plans_) { + if (!p.paged() || p.block_size <= 0) continue; + int64_t blocks = max_seqs_ * ((ctx + p.block_size - 1) / p.block_size); + if (p.kind == RAD_KV_WINDOW && p.window_blocks > 0) + blocks = std::min(blocks, max_seqs_ * p.window_blocks); + need += blocks * p.bytes_per_block; + } + return need; +} + +/* EVERY VECTOR THE CARVE FILLS IS PARALLEL TO plans_, AND THEY ARE NOT FILLED AT THE SAME POINT IN + * IT. The block state is sized after the split is decided and the backing is taken after that, so + * a carve that returns part way through leaves a manager whose plan table answers every guard and + * whose block state is empty behind it. The entry points then index one vector having checked + * another -- reserve_block is a bounds check against plans_ and a read of free_usable_ -- and the + * read is out of bounds rather than a refusal. + * + * A refused carve is a configuration the operator is told about and the caller aborts on, so the + * cost of this is not that the engine runs badly afterwards; it is that reaching the abort goes + * through undefined behaviour, and a tier restoring blocks on the way there is one call away from + * a segmentation fault instead of a return code. Putting the two back in agreement by emptying + * both is one place, and it holds for every entry point rather than the ones anybody remembered. */ +int KVManager::carve(Pool& kv_pool) { + const int rc = carve_into(kv_pool); + if (rc < 0) forget(); + return rc; +} + +void KVManager::forget() { + plans_.clear(); free_blocks_.clear(); refcount_.clear(); free_states_.clear(); + live_.clear(); free_usable_.clear(); bucket_blocks_.clear(); held_hist_.clear(); + chunk_blocks_.clear(); short_peak_.clear(); + pool_ = nullptr; + clears_.clear(); + seqs_.clear(); pending_.clear(); ck_slot_base_.clear(); ck_free_.clear(); + ck_stride_ = ck_region_off_ = 0; + ck_elastic_ = false; + ck_high_water_ = 0; + ck_backed_ = 0; + configured_ = false; + report_.clear(); +} + +int KVManager::carve_into(Pool& kv_pool) { + /* The pool is whatever the operator stated or the resolver derived; nothing here re-decides + * it. What this does decide is how the groups share it, which is arithmetic, not policy. */ + const int64_t budget_bytes = kv_pool.avail(); + const int64_t budget_ckpts = ckpts_; + const int64_t fixed = fixed_; + const int64_t ck_total = ck_total_; + pool_base_ = kv_pool.base(); + pool_ = &kv_pool; + + if (fixed >= budget_bytes) { + RAD_ERR("vram_kv does not fit its fixed costs:\n" + " linear/conv state %10s (%lld sequences)\n" + " checkpoints %10s (%lld x %s)\n" + " ------------------------------\n" + " fixed %10s\n" + " --vram-kv-mib %10s\n" + " SHORT BY %10s\n" + "Lower --max-seqs or the checkpoint slot count, or raise --vram-kv-mib. " + "The engine will not shrink one of them for you (spec §6).", + humanb(fixed - ck_total).c_str(), (long long)max_seqs_, + humanb(ck_total).c_str(), (long long)budget_ckpts, + humanb(ck_stride_).c_str(), + humanb(fixed).c_str(), humanb(budget_bytes).c_str(), + humanb(fixed - budget_bytes + 1).c_str()); + return RAD_E_NOMEM; + } + + /* ---- the paged split. Not a policy: size the groups to exhaust at the same total token + * count. Any other split strands memory in whichever group outlasts the others, and a + * long-context server would then run out of full-attention blocks with a window pool still + * half empty. ---- */ + int64_t remaining = budget_bytes - fixed; + std::vector open; + for (auto& p : plans_) if (p.paged()) open.push_back(p.index); + + int64_t tokens = 0; + while (!open.empty()) { + double cost = 0; + for (int32_t i : open) + cost += (double)plans_[i].bytes_per_block / (double)plans_[i].block_size; + if (cost <= 0) break; + tokens = (int64_t)((double)remaining / cost); + + /* A windowed group cannot use more than window_blocks per sequence; anything past that + * is memory nobody will ever address. Cap it and give the bytes back to the others. */ + int32_t capped = -1; + for (int32_t i : open) { + const auto& p = plans_[i]; + if (p.kind != RAD_KV_WINDOW) continue; + if (tokens / p.block_size > max_seqs_ * p.window_blocks) { capped = i; break; } + } + if (capped < 0) break; + plans_[capped].n_blocks = max_seqs_ * plans_[capped].window_blocks; + remaining -= plans_[capped].n_blocks * plans_[capped].bytes_per_block; + open.erase(std::find(open.begin(), open.end(), capped)); + } + for (int32_t i : open) plans_[i].n_blocks = tokens / plans_[i].block_size; + + for (auto& p : plans_) { + if (!p.paged()) continue; + if (p.n_blocks <= 0) { + RAD_ERR("KV group '%s': a %s KV pool leaves 0 blocks (%s a page) after the fixed " + "linear/conv costs of %s. Raise --vram-kv-mib, lower --expert-vs-cache-ratio, " + "or lower --max-seqs.", + p.name.c_str(), humanb(budget_bytes).c_str(), + humanb(p.bytes_per_block).c_str(), humanb(fixed).c_str()); + return RAD_E_NOMEM; + } + } + + /* ---- carve. Every reservation comes from the KV pool and only from the KV pool: the mover + * works inside the weight slab and cannot reach this (spec §6). ---- */ + int64_t paged_taken = 0; + for (auto& p : plans_) { + int64_t bytes = p.paged() ? p.n_blocks * p.bytes_per_block + : p.n_states * p.bytes_per_state; + if (p.paged()) paged_taken += bytes; + int64_t off = 0; + void* ptr = kv_pool.reserve(p.name, bytes, RAD_ALIGN_UNIT, &off); + if (!ptr && !kv_pool.accounting_only()) { + RAD_ERR("KV group '%s': %s did not fit the KV pool", p.name.c_str(), + humanb(bytes).c_str()); + return RAD_E_NOMEM; + } + p.base = ptr; + p.pool_offset = off; + p.pool_bytes = bytes; + } + /* --checkpoint-slots on a model with no recurrent state buys nothing, and allocating zero-byte + * slots for it would leave the operator's flag looking honoured. Ignore it and say so. */ + if (budget_ckpts > 0 && checkpoint_bytes_ <= 0) + RAD_WARN("--checkpoint-slots %lld ignored: this model declares no linear-attention state, " + "so there is nothing to snapshot", (long long)budget_ckpts); + for (int64_t i = 0; checkpoint_bytes_ > 0 && i < budget_ckpts; ++i) { + int64_t off = 0; + if (!kv_pool.reserve("linear checkpoint", ck_stride_, ck_align(), &off) + && !kv_pool.accounting_only()) { + /* The arithmetic that is supposed to make this impossible, printed next to the + * failure: `fixed` reserved budget_ckpts * checkpoint_bytes_ up front, so a checkpoint + * that does not fit means the paged carve above spent more than `remaining`. */ + RAD_ERR("linear checkpoint slot %lld (%lld B) did not fit the KV pool: %lld B of " + "%lld B left after the paged groups took %lld B against a %lld B share", + (long long)i, (long long)checkpoint_bytes_, + (long long)kv_pool.avail(), (long long)budget_bytes, + (long long)paged_taken, (long long)(budget_bytes - fixed)); + return RAD_E_NOMEM; + } + if (i == 0) ck_region_off_ = off; + ck_slot_base_.push_back(off); + ck_free_.push_back((int32_t)i); + } + std::reverse(ck_free_.begin(), ck_free_.end()); /* pop_back hands out slot 0 first */ + + /* ---- free lists ---- */ + free_blocks_.resize(plans_.size()); + refcount_.resize(plans_.size()); + cached_.resize(plans_.size()); + cache_only_.assign(plans_.size(), 0); + free_states_.resize(plans_.size()); + for (size_t i = 0; i < plans_.size(); ++i) { + const auto& p = plans_[i]; + if (p.paged()) { + refcount_[i].assign((size_t)p.n_blocks, 0); + cached_[i].assign((size_t)p.n_blocks, 0); + /* ASCENDING, WHICH IS ALREADY A MIN-HEAP. A sorted run satisfies the heap property, + * so the list starts valid and hands out block 0 first. See the loan block in kv.h + * for why the lowest free id is the one to hand out. */ + free_blocks_[i].resize((size_t)p.n_blocks); + for (int64_t b = 0; b < p.n_blocks; ++b) free_blocks_[i][(size_t)b] = (int32_t)b; + } else { + /* Only the LOGICAL slots are allocatable. Copy k of slot s is s + k * n_seq_states + * and is never handed out on its own -- it belongs to whoever holds s. */ + const int64_t n_alloc = p.n_seq_states(); + free_states_[i].resize((size_t)n_alloc); + for (int64_t s = 0; s < n_alloc; ++s) + free_states_[i][(size_t)s] = (int32_t)(n_alloc - 1 - s); + } + } + + /* ---- backing ---- + * + * EVERYTHING THE CARVE TOOK IS BACKED BEFORE ANYTHING RUNS, and the paged groups stay backed + * for the life of the process: a pool on a device with virtual memory management is exactly + * one without it, the same bytes in the same places at the same addresses. The loan moves + * which blocks the cache hands out and never what is mapped, so it needs no driver call and + * cannot leave an address the free list names with nothing behind it. + * + * The fixed part -- recurrent state and conv slots -- is never released. It is sized per + * sequence rather than per token, so there is no idle fraction of it to give back, and a + * state slot cannot be re-created on demand the way a page can. + * + * CHECKPOINT SLOTS ARE NOT PART OF THAT. They are a CACHE -- the retention policy creates and + * retires them all run, and a slot nobody has taken holds nothing that has to survive -- so + * backing them all here would make --checkpoint-slots a standing VRAM charge whether or not a + * snapshot exists. On a linear-attention model a slot is a sizeable fraction of a gigabyte, + * and on a card whose experts do not fit that charge is decode step time. The region is left + * unbacked and each slot is committed as it is handed out, which makes the flag a cap. */ + if (pool_ && pool_->elastic()) { + /* EVERYTHING EXCEPT THE CHECKPOINT REGION. The slots are reserved last, so the + * second range is empty and this is a prefix -- written as a hole anyway, because + * "commit everything below the slots" is the rule and "the slots are at the end" is a + * detail of the carve above that nothing here should depend on. A prefix that stopped at + * a region in the MIDDLE would leave every group past it addressable and unbacked, and + * the paged groups are live from the first step: a fault at a valid-looking address on + * the first write, which is the worst shape this class of bug has. + * + * Both edges are granule-aligned by construction (the slot reserve asks for ck_align() + * and the stride is a whole number of granules), so neither commit rounds outward into + * the region. That alignment is the whole reason it can be skipped at all. */ + const int64_t used = pool_->used(); + const int64_t hole_off = ck_elastic_ && !ck_slot_base_.empty() ? ck_region_off_ : used; + const int64_t hole_end = ck_elastic_ && !ck_slot_base_.empty() + ? ck_slot_base_.back() + ck_stride_ + : used; + int rc = pool_->commit(0, hole_off); + if (rc >= 0 && used > hole_end) rc = pool_->commit(hole_end, used - hole_end); + if (rc < 0) { + RAD_ERR("KV pool: the carve reserved %s of address space and the card would not back " + "it", humanb(used - (hole_end - hole_off)).c_str()); + return rc; + } + } + live_.assign(plans_.size(), 0); + free_usable_.assign(plans_.size(), 0); + bucket_blocks_.assign(plans_.size(), 1); + chunk_blocks_.assign(plans_.size(), 0); + short_peak_.assign(plans_.size(), 0); + held_hist_.assign(plans_.size(), {}); + for (size_t i = 0; i < plans_.size(); ++i) { + const auto& p = plans_[i]; + if (!p.paged()) continue; + live_[i] = p.n_blocks; + free_usable_[i] = p.n_blocks; + /* THE BUFFER FLOOR IS ONE STEP'S WORTH OF THIS GROUP. A step batches at most max_tok + * tokens across every sequence in it, so a buffer this size means a prefill asks the + * driver for memory once a chunk at worst and a decode step essentially never. Clamped to + * the carve, since a group too small to hold one chunk has no floor to speak of. */ + const int64_t chunk = blocks_for(p.index, max_tok_); + chunk_blocks_[i] = std::min(chunk > 0 ? chunk : 1, p.n_blocks); + /* A FEW THOUSAND BUCKETS, whatever the carve. The histogram answers "how high does + * anything still hold" for the loan, and a bucket is the resolution of that answer: at + * this size the loan stops within a fraction of a percent of the carve of the highest + * held block, and the walk that finds it is a few thousand counters. */ + bucket_blocks_[i] = std::max(1, ceil_div(p.n_blocks, 4096)); + held_hist_[i].assign((size_t)ceil_div(p.n_blocks, bucket_blocks_[i]), 0); + } + + configured_ = true; + report_ = bundling_.report(); + for (const auto& p : plans_) { + if (p.paged()) + report_ += fmt(" %-14s %-6s %3lld layers block %4lld tok page %8s " + "%7lld blocks = %9s (%lld tokens)\n", + p.name.c_str(), kv_kind_name(p.kind), (long long)p.n_layers, + (long long)p.block_size, humanb(p.bytes_per_block).c_str(), + (long long)p.n_blocks, humanb(p.pool_bytes).c_str(), + (long long)(p.n_blocks * p.block_size)); + else + report_ += fmt(" %-14s %-6s %3lld layers state %8s %7lld slots = %9s\n", + p.name.c_str(), kv_kind_name(p.kind), (long long)p.n_layers, + humanb(p.bytes_per_state).c_str(), + (long long)p.n_states, humanb(p.pool_bytes).c_str()); + } + /* WHERE EACH GROUP STARTS, SO A FAULT ADDRESS CAN BE PLACED. A GPU memory fault names an + * address and nothing else, and without this the only way to tell "kv_attn layer 7" from + * "checkpoint slot 3" is to reconstruct the carve by hand from the sizes above. One line. */ + report_ += fmt(" pool at %p, %s; groups at +%lld..+%lld, checkpoints at +%lld\n", + pool_base_, humanb(pool_ ? pool_->bytes() : 0).c_str(), + (long long)(plans_.size() > 1 ? plans_[1].pool_offset : 0), + (long long)(plans_.empty() ? 0 : plans_.back().pool_offset + + plans_.back().pool_bytes), + (long long)(ck_slot_base_.empty() ? 0 : ck_slot_base_.front())); + if (checkpoint_bytes_ > 0) + report_ += fmt( +" %-14s %-6s %lld slots x %s = %s%s\n", "checkpoints", "linear", + (long long)ck_slot_base_.size(), humanb(ck_stride_).c_str(), + humanb((int64_t)ck_slot_base_.size() * ck_stride_).c_str(), + ck_elastic_ ? " (address space; backed as slots are taken)" : ""); + return RAD_OK; +} + +std::string KVManager::report() const { return report_; } + +const KVGroupPlan* KVManager::plan(int32_t g) const { + return (g >= 0 && g < (int32_t)plans_.size()) ? &plans_[(size_t)g] : nullptr; +} + +/* ------------------------------------------------------------------ free lists */ + +/* THE LOWEST FREE BLOCK, NOT THE ONE FREED MOST RECENTLY. A stack hands back the id released + * last, which after a busy period is the high block the loan wants -- so the highest held block + * never falls and nothing can be lent. A min-heap keeps the held blocks packed at the bottom, + * which is what leaves the top free to lend. + * + * It also makes the live gate free. The smallest free id is below live_ whenever ANY free id is, + * so a pool with backed free blocks finds one at the top of the heap and never scans for it. + * + * Entries whose block is no longer free are skipped rather than removed: reserve_specific_block + * takes one block out of the middle, and erasing from a heap costs a rebuild. A stale entry is + * consumed by the one pop that meets it. */ +int KVManager::grab_block(int32_t g, int32_t* out) { + auto& fl = free_blocks_[(size_t)g]; + /* AN EMPTY POOL THAT HAS LENT BLOCKS TAKES THEM BACK HERE, on the path that needed the block, + * because this is the moment the memory is worth more to the cache than to the slab holding + * it. ensure() recalls in one call for the whole request; this is the fallback for the callers + * that take one block at a time, and it takes back a buffer's worth so that a sequence built + * block by block does not recall per block. */ + if (free_usable_[(size_t)g] <= 0) (void)grow_for(g, 1); + if (free_usable_[(size_t)g] <= 0) return RAD_E_FULL; + while (!fl.empty()) { + std::pop_heap(fl.begin(), fl.end(), std::greater()); + const int32_t b = fl.back(); + fl.pop_back(); + if (refcount_[(size_t)g][(size_t)b] != 0) continue; /* stale: taken out of the middle */ + /* AND NEVER PAST THE LIVE MARK. An id above it addresses a page this pool never mapped, + * and the first thing to read it is a kernel -- a GPU memory fault with nothing to say + * which block or which group. The count and the heap are two structures and this is the + * one place they are required to agree, so it is the one place worth asking. */ + if (b >= live_[(size_t)g]) { + RAD_ERR("KV group '%s': the free list offered block %d with the live mark at %lld and " + "%lld usable -- the count and the heap have gone out of step", + plans_[(size_t)g].name.c_str(), (int)b, (long long)live_[(size_t)g], + (long long)free_usable_[(size_t)g]); + return RAD_E_STATE; + } + refcount_[(size_t)g][(size_t)b] = 1; + --free_usable_[(size_t)g]; + note_held(g, b, +1); + *out = b; + return RAD_OK; + } + return RAD_E_FULL; +} + +void KVManager::drop_block(int32_t g, int32_t b) { + auto& rc = refcount_[(size_t)g][(size_t)b]; + if (rc <= 0) { RAD_ERR("KV group %d: double free of block %d", g, b); return; } + if (cached_[(size_t)g][(size_t)b]) { + if (rc == 2) ++cache_only_[(size_t)g]; + else if (rc == 1) { --cache_only_[(size_t)g]; cached_[(size_t)g][(size_t)b] = 0; } + } + if (--rc != 0) return; + auto& fl = free_blocks_[(size_t)g]; + fl.push_back(b); + std::push_heap(fl.begin(), fl.end(), std::greater()); + ++free_usable_[(size_t)g]; + note_held(g, b, -1); +} + +void KVManager::add_ref(size_t g, int32_t b) { + auto& rc = refcount_[g][(size_t)b]; + if (rc == 1 && cached_[g][(size_t)b]) --cache_only_[g]; + ++rc; +} + +/* The held count per bucket, which is the only thing a loan needs to know: the highest bucket + * anything still holds is where the loan has to stop. Maintained here rather than scanned on demand + * because a scan of every refcount is not affordable between steps, and a stale answer would lend + * a block out from under a live sequence. */ +void KVManager::note_held(int32_t g, int32_t b, int delta) { + auto& h = held_hist_[(size_t)g]; + if (h.empty()) return; + const int64_t bucket = (int64_t)b / bucket_blocks_[(size_t)g]; + if (bucket >= 0 && bucket < (int64_t)h.size()) h[(size_t)bucket] += delta; +} + +int KVManager::grab_state(int32_t g, int32_t* out) { + auto& fl = free_states_[(size_t)g]; + if (fl.empty()) return RAD_E_FULL; + *out = fl.back(); fl.pop_back(); + /* The slot arrives dirty -- see StateClear in kv.h. Recorded rather than zeroed because this + * runs on the scheduler thread and the pool is device memory. EVERY COPY IS CLEARED, not + * just the state: the second one holds a kernel's replay scratch, and a zero there is what + * makes the first step after a prefill replay nothing (KVGroupPlan::state_copies). */ + const KVGroupPlan* p = plan(g); + const int64_t copies = p ? p->state_copies : 1, span = p ? p->n_seq_states() : 0; + for (int64_t k = 0; k < (copies > 0 ? copies : 1); ++k) + clears_.push_back(StateClear{ g, (int32_t)(*out + k * span) }); + return RAD_OK; +} + +void KVManager::drop_state(int32_t g, int32_t s) { + if (s >= 0) free_states_[(size_t)g].push_back(s); +} + +/* WHAT CAN BE HANDED OUT, WHICH IS NOT THE LENGTH OF THE FREE LIST. The list holds every id the + * carve created; a cache lending the top of its range still has those ids in it and a slab's + * weights behind them, and a stale entry left by reserve_specific_block is in there too. The + * counter is the answer to the only question anybody asks -- how many more blocks can this group + * give out right now -- and it is maintained wherever that number changes. */ +int64_t KVManager::free_blocks(int32_t g) const { + return (g >= 0 && g < (int32_t)free_usable_.size()) ? free_usable_[(size_t)g] : 0; +} +int64_t KVManager::held_blocks(int32_t g) const { + if (g < 0 || g >= (int32_t)live_.size()) return 0; + const int64_t held = live_[(size_t)g] - free_usable_[(size_t)g]; + return held > 0 ? held : 0; +} +/* THE CARVE, not the backing. This is the number every block id is addressed against and the one + * the scheduler's capacity arithmetic means; live_blocks() is what has VRAM behind it. */ +int64_t KVManager::total_blocks(int32_t g) const { + const KVGroupPlan* p = plan(g); return p ? p->n_blocks : 0; +} +int64_t KVManager::live_blocks(int32_t g) const { + return (g >= 0 && g < (int32_t)live_.size()) ? live_[(size_t)g] : 0; +} + +int64_t KVManager::committed_bytes() const { return pool_ ? pool_->committed() : 0; } + +/* ONE PREFILL CHUNK, OR THE LARGEST RECENT SHORTFALL. The floor is what a single step can consume + * -- past it a chunked prefill would recall the loan on every chunk -- and the trend term is what + * says the last few seconds asked for more than that. `short_peak_` decays in spare_tokens(), so a + * server that has gone quiet settles back to the floor and lends the difference to the expert + * plane. */ +int64_t KVManager::buf_blocks(size_t i) const { + if (i >= plans_.size()) return 0; + const int64_t floor_b = i < chunk_blocks_.size() ? chunk_blocks_[i] : 0; + const int64_t peak = i < short_peak_.size() ? short_peak_[i] : 0; + return peak > floor_b ? peak : floor_b; +} + +int64_t KVManager::buffer_bytes() const { + int64_t b = 0; + for (size_t i = 0; i < plans_.size(); ++i) + if (plans_[i].paged()) b += buf_blocks(i) * plans_[i].bytes_per_block; + return b; +} + +int64_t KVManager::ck_reserve_bytes() const { + if (!ck_elastic_ || ck_stride_ <= 0) return 0; + /* Counted from what is BACKED and not from the free list, because a rank that is not the one + * holding the free list still backs the slots it writes, and its reserve has to cover them. */ + const int64_t want = std::min(ckpts_, ck_high_water_ + 1); + return want > ck_backed_ ? (want - ck_backed_) * ck_stride_ : 0; +} + +bool KVManager::ck_backed(int32_t slot) const { + if (slot < 0 || slot >= (int32_t)ck_slot_base_.size()) return false; + if (!ck_elastic_ || !pool_ || !pool_->elastic() || ck_stride_ <= 0) return true; + return pool_->is_committed(ck_slot_base_[(size_t)slot], ck_stride_); +} + +int KVManager::ck_room(int32_t slot) const { + if (slot < 0 || slot >= (int32_t)ck_slot_base_.size()) return RAD_E_INVAL; + if (ck_backed(slot) || !ck_free_bytes_ || ck_keep_free_ <= 0) return RAD_OK; + int64_t free_now = 0; + RAD_TRY(ck_free_bytes_(&free_now)); + return free_now - ck_stride_ >= ck_keep_free_ ? RAD_OK : RAD_E_FULL; +} + +int KVManager::ck_commit(int32_t slot) { + if (slot < 0 || slot >= (int32_t)ck_slot_base_.size()) return RAD_E_INVAL; + if (ck_backed(slot)) return RAD_OK; + if (pool_->commit(ck_slot_base_[(size_t)slot], ck_stride_) < 0) return RAD_E_FULL; + if (++ck_backed_ > ck_high_water_) ck_high_water_ = ck_backed_; + return RAD_OK; +} + +int KVManager::back_checkpoint(int32_t slot) { + RAD_TRY(ck_room(slot)); + return ck_commit(slot); +} + +/* EVERY CARD'S ANSWER BEFORE ANY CARD'S PAGES. Asking first means a slot one card refuses costs + * the others nothing: on a driver that keeps what it maps, pages committed for a slot that is then + * not handed out would be charged to that card for the life of the process. */ +int KVManager::ck_back_everywhere(int32_t slot) { + RAD_TRY(ck_room(slot)); + for (KVManager* p : ck_peers_) RAD_TRY(p->ck_room(slot)); + RAD_TRY(ck_commit(slot)); + for (KVManager* p : ck_peers_) RAD_TRY(p->ck_commit(slot)); + return RAD_OK; +} + +int KVManager::back_free_checkpoints(int64_t* withdrawn) { + std::vector keep; + keep.reserve(ck_free_.size()); + int64_t gone = 0; + for (const int32_t s : ck_free_) { + const int rc = ck_back_everywhere(s); + if (rc == RAD_E_FULL) { ++gone; continue; } + if (rc < 0) return rc; + keep.push_back(s); + } + ck_free_.swap(keep); + if (withdrawn) *withdrawn = gone; + return RAD_OK; +} + +int64_t KVManager::ck_align() const { + if (!ck_elastic_) return (int64_t)RAD_ALIGN_UNIT; + const int64_t g = Pool::granule(); + return g > (int64_t)RAD_ALIGN_UNIT ? g : (int64_t)RAD_ALIGN_UNIT; +} + +/* WHAT THE GROUP CAN STILL HAND OUT, WHICH IS NOT WHAT IT HAS BELOW THE MARK. A lent block is + * still carved, still addressed and still the operator's budget -- it is one recall away, and the + * recall happens on the path that needs it. So every admission decision is made against this + * number and not against the mark, and a cache that is lending admits exactly what one that is + * not would. + * + * Deciding on the mark instead would be a livelock: a 200K-token prefill asks for its blocks in + * one call, a cache that had lent everything above its idle size would refuse, and the thing that + * brings the loan back is demand it just refused. */ +int64_t KVManager::available_blocks(int32_t g) const { + const KVGroupPlan* p = plan(g); + if (!p || !p->paged()) return 0; + const int64_t lent = p->n_blocks - live_blocks(g); + return free_blocks(g) + (lent > 0 ? lent : 0); +} + +bool KVManager::lendable(int32_t g) const { + const KVGroupPlan* p = plan(g); + return p && p->kind == RAD_KV_FULL && p->n_blocks > 0 && p->block_size > 0 && + p->bytes_per_block > 0; +} + +int64_t KVManager::lent_blocks(size_t i, int64_t tokens) const { + const KVGroupPlan& p = plans_[i]; + if (!lendable(p.index) || tokens <= 0) return 0; + const int64_t b = tokens / p.block_size; + return b < p.n_blocks ? b : p.n_blocks; +} + +int64_t KVManager::held_top(size_t i) const { + const auto& h = held_hist_[i]; + for (size_t b = h.size(); b-- > 0;) + if (h[b] > 0) return std::min(((int64_t)b + 1) * bucket_blocks_[i], plans_[i].n_blocks); + return 0; +} + +/* Take back enough of the loan that `blocks` more can be handed out. Unbounded: this is a request + * that has already been admitted, and the alternative to serving it is refusing a request the + * budget says fits. It takes back the shortfall PLUS the buffer, so a sequence that grows a block + * at a time does not come back here for every block. */ +int KVManager::grow_for(int32_t g, int64_t blocks) { + if (g < 0 || g >= (int32_t)plans_.size()) return RAD_E_INVAL; + const KVGroupPlan& p = plans_[(size_t)g]; + if (!p.paged()) return RAD_OK; + const int64_t short_by = blocks - free_usable_[(size_t)g]; + if (short_by <= 0) return RAD_OK; + + /* WHAT WAS ASKED FOR AND WAS NOT THERE, which is the one honest measure of how big the buffer + * should have been. Recorded before the recall rounds it up, and never from the recall + * itself -- the recall already contains the buffer, so feeding it back would size the buffer + * from its own last value. */ + if ((size_t)g < short_peak_.size() && short_by > short_peak_[(size_t)g]) + short_peak_[(size_t)g] = short_by; + + if (!lendable(g) || loan_ <= 0 || live_[(size_t)g] >= p.n_blocks) return RAD_E_FULL; + int64_t live = live_[(size_t)g] + short_by + buf_blocks((size_t)g); + if (live > p.n_blocks) live = p.n_blocks; + /* The loan that leaves this group `live` blocks, in the unit every group shares. It can only + * shrink: a shortfall in one group is never a reason to lend more of another. */ + int64_t keep = (p.n_blocks - live) * p.block_size; + if (keep > loan_) keep = loan_; + if (reclaim_) { + const int rc = reclaim_(keep); + if (rc < 0) { + RAD_ERR("KV group '%s': a request needs %lld more blocks and the expert slab could not " + "give back the loan past %lld tokens: %s", p.name.c_str(), + (long long)short_by, (long long)keep, rad_strerror(rc)); + return rc; + } + } + RAD_TRY(set_loan(keep)); + return free_usable_[(size_t)g] >= blocks ? RAD_OK : RAD_E_FULL; +} + +int64_t KVManager::spare_tokens() { + int64_t spare = -1; + for (size_t i = 0; i < plans_.size(); ++i) { + /* THE BURST IS FORGOTTEN A LITTLE ON EVERY PASS. Without a decay the buffer would be the + * high-water mark of the whole run, so one 200K admission would pin its own worth of VRAM + * for as long as the process lived -- the opposite of the point. An eighth a tick is a + * half-life of about half a second and a return to the floor in a few, which is slower + * than a burst arrives and faster than a workload changes. */ + if (i < short_peak_.size()) short_peak_[i] -= short_peak_[i] / 8; + if (!lendable(plans_[i].index)) continue; + const KVGroupPlan& p = plans_[i]; + int64_t keep = held_top(i) + buf_blocks(i); + if (keep > p.n_blocks) keep = p.n_blocks; + const int64_t t = (p.n_blocks - keep) * p.block_size; + if (spare < 0 || t < spare) spare = t; + } + return spare > 0 ? spare : 0; +} + +int KVManager::set_loan(int64_t tokens) { + if (tokens < 0) tokens = 0; + /* CHECKED WHOLE BEFORE ANYTHING MOVES, so a refused loan leaves every group where it was. */ + for (size_t i = 0; i < plans_.size(); ++i) { + if (!lendable(plans_[i].index)) continue; + const int64_t live = plans_[i].n_blocks - lent_blocks(i, tokens); + if (live < live_[i] && held_top(i) > live) { + RAD_ERR("KV group '%s': asked to lend down to block %lld with a block held at or above " + "%lld", plans_[i].name.c_str(), (long long)live, + (long long)(held_top(i) - bucket_blocks_[i])); + return RAD_E_STATE; + } + } + for (size_t i = 0; i < plans_.size(); ++i) { + if (!lendable(plans_[i].index)) continue; + const int64_t live = plans_[i].n_blocks - lent_blocks(i, tokens); + /* THE FREE COUNT MOVES WITH THE MARK, NOT THE LIST. Every id the carve created stays in + * the heap; what changes is how many of them may be handed out. The ids between the two + * marks are all free -- nothing is held above the lower of them -- so the count moves by + * exactly the distance. */ + free_usable_[i] += live - live_[i]; + live_[i] = live; + } + loan_ = tokens; + return RAD_OK; +} + +int KVManager::follow(const KVManager& leader) { + if (leader.loan_ == loan_) return RAD_OK; + for (size_t i = 0; i < plans_.size() && i < leader.plans_.size(); ++i) { + if (!lendable(plans_[i].index)) continue; + const int64_t live = plans_[i].n_blocks - lent_blocks(i, leader.loan_); + free_usable_[i] += live - live_[i]; + live_[i] = live; + } + loan_ = leader.loan_; + return RAD_OK; +} +int64_t KVManager::free_states(int32_t g) const { + return (g >= 0 && g < (int32_t)free_states_.size()) ? (int64_t)free_states_[(size_t)g].size() : 0; +} + +/* ONE GROUP'S SHARE OF THE CARD, AND WHAT IS HELD OF IT. Paged and stateful groups are counted by + * the objects they actually hand out, because those are the only ones whose occupancy is tracked: + * `pool_bytes` may exceed the product for a group whose pool was rounded up when it was carved, + * and the rounding is capacity nothing can be allocated from rather than capacity in use. */ +int64_t KVManager::pool_bytes(int32_t g) const { + const KVGroupPlan* p = plan(g); + if (!p) return 0; + /* THE PART THE CACHE KEEPS, because this figure is answering "how much of the card is the KV + * cache". A group whose top blocks are lent still addresses them and still reports them in + * total_blocks(), but the expert slab is holding weights in them, and the slab reports those + * bytes as its own (Mover::flex_used_bytes); counting them here as well would count them twice. */ + if (p->paged()) return live_blocks(g) * p->bytes_per_block; + if (p->stateful()) return p->n_states * p->bytes_per_state; + return 0; +} + +int64_t KVManager::pool_bytes_carved(int32_t g) const { + const KVGroupPlan* p = plan(g); + if (!p) return 0; + if (p->paged()) return p->n_blocks * p->bytes_per_block; + if (p->stateful()) return p->n_states * p->bytes_per_state; + return 0; +} + +int64_t KVManager::pool_bytes_used(int32_t g) const { + const KVGroupPlan* p = plan(g); + if (!p) return 0; + if (p->paged()) return (live_blocks(g) - free_blocks(g)) * p->bytes_per_block; + /* IN LOGICAL SLOTS, THEN SCALED. The free list holds only logical slots -- copy k of slot s + * belongs to whoever holds s and is never handed out alone -- while n_states counts every + * copy, so subtracting one from the other reads a speculating deployment's idle pool as + * half full. */ + if (p->stateful()) { + const int64_t copies = p->state_copies > 0 ? p->state_copies : 1; + return (p->n_seq_states() - free_states(g)) * copies * p->bytes_per_state; + } + return 0; +} + +int64_t KVManager::blocks_for(int32_t g, int64_t n_tokens) const { + const KVGroupPlan* p = plan(g); + if (!p || !p->paged() || n_tokens <= 0) return 0; + int64_t n = ceil_div(n_tokens, p->block_size); + if (p->kind == RAD_KV_WINDOW) n = std::min(n, p->window_blocks); + return n; +} + +bool KVManager::can_ever_fit(int64_t n_tokens) const { + for (const auto& p : plans_) { + /* Both kinds NAMED, not "paged or else". The null group at handle 0 is neither, so an + * `else` branch that assumed stateful would refuse every sequence: it holds no states. */ + if (p.paged()) { if (blocks_for(p.index, n_tokens) > p.n_blocks) return false; } + else if (p.stateful()) { if (p.n_states < 1) return false; } + } + return true; +} + +/* ------------------------------------------------------------------ sequences */ + +KVManager::Seq* KVManager::find(uint64_t s) { + auto it = seqs_.find(s); return it == seqs_.end() ? nullptr : &it->second; +} +const KVManager::Seq* KVManager::find(uint64_t s) const { + auto it = seqs_.find(s); return it == seqs_.end() ? nullptr : &it->second; +} +bool KVManager::has_sequence(uint64_t s) const { return find(s) != nullptr; } + +int KVManager::add_sequence(uint64_t id) { + if (!configured_) return RAD_E_STATE; + if (seqs_.count(id)) return RAD_E_DUPLICATE; + Seq s; + s.id = id; + s.blocks.resize(plans_.size()); + s.first_block_pos.assign(plans_.size(), 0); + s.state.assign(plans_.size(), -1); + s.dirty_from.assign(plans_.size(), 0); + seqs_.emplace(id, std::move(s)); + return RAD_OK; +} + +void KVManager::free_sequence(uint64_t id) { + Seq* s = find(id); + if (!s) return; + for (size_t g = 0; g < plans_.size(); ++g) { + for (int32_t b : s->blocks[g]) drop_block((int32_t)g, b); + s->blocks[g].clear(); + if (s->state[g] >= 0) { drop_state((int32_t)g, s->state[g]); s->state[g] = -1; } + } + seqs_.erase(id); + ++seq_frees_; +} + +int KVManager::preempt(uint64_t id) { + Seq* s = find(id); + if (!s) return RAD_E_NOTFOUND; + for (size_t g = 0; g < plans_.size(); ++g) { + for (int32_t b : s->blocks[g]) drop_block((int32_t)g, b); + s->blocks[g].clear(); + s->first_block_pos[g] = 0; + s->dirty_from[g] = 0; + /* The recurrent state goes too. A GDN state that was not snapshotted cannot be resumed, + * so a preempted sequence replays from its last checkpoint or from zero -- which is what + * "preemption by recompute" means for a linear layer (spec §7.1). */ + if (s->state[g] >= 0) { drop_state((int32_t)g, s->state[g]); s->state[g] = -1; } + } + s->n_tokens = 0; + ++seq_frees_; + return RAD_OK; +} + +/* ------------------------------------------------------------------ rollback (spec §10) */ +/* The other direction from `ensure`, and deliberately NOT `preempt`. A verify wrote KV for + * 1 + n_spec positions; the sampler accepted a prefix; the rest must go back to the free list. + * The sequence keeps its state slots and its window base -- see kv.h for why touching the + * stateful groups here would be actively wrong. */ +int KVManager::rollback(uint64_t id, int64_t n_tokens) { + Seq* s = find(id); + if (!s) return RAD_E_NOTFOUND; + if (n_tokens < 0) return RAD_E_INVAL; + /* Monotone in the other direction is `ensure`'s job. Saying RAD_OK rather than refusing keeps + * "every draft token was accepted" -- the good case -- off a special path in the caller. */ + if (n_tokens >= s->n_tokens) return RAD_OK; + + for (size_t g = 0; g < plans_.size(); ++g) { + const auto& p = plans_[g]; + if (!p.paged()) continue; + int64_t first = s->first_block_pos[g] / p.block_size; + int64_t want = ceil_div(n_tokens, p.block_size) - first; + if (want < 0) { + /* Below what a WINDOW group still retains, which needs n_spec to exceed the whole + * window. Drop everything and rebase rather than index a block table from a negative + * offset -- the KV for those positions was recycled and is not coming back. */ + want = 0; + s->first_block_pos[g] = (n_tokens / p.block_size) * p.block_size; + s->dirty_from[g] = 0; + } + while ((int64_t)s->blocks[g].size() > want) { + drop_block((int32_t)g, s->blocks[g].back()); + s->blocks[g].pop_back(); + } + s->dirty_from[g] = std::min(s->dirty_from[g], (int64_t)s->blocks[g].size()); + } + s->n_tokens = n_tokens; + return RAD_OK; +} + +int64_t KVManager::first_block_pos(uint64_t id, int32_t g) const { + const Seq* s = find(id); + if (!s || g < 0 || g >= (int32_t)s->first_block_pos.size()) return 0; + return s->first_block_pos[(size_t)g]; +} + +int64_t KVManager::seq_tokens(uint64_t id) const { const Seq* s = find(id); return s ? s->n_tokens : 0; } + +int64_t KVManager::take_table_changes(uint64_t id, int32_t g) const { + const Seq* s = find(id); + if (!s || g < 0 || g >= (int32_t)s->dirty_from.size()) return 0; + const int64_t d = s->dirty_from[(size_t)g]; + s->dirty_from[(size_t)g] = kNoDirty; + return d; +} + +const std::vector& KVManager::block_table(uint64_t id, int32_t g) const { + const Seq* s = find(id); + if (!s || g < 0 || g >= (int32_t)s->blocks.size()) return kNoBlocks; + return s->blocks[(size_t)g]; +} + +int32_t KVManager::state_slot(uint64_t id, int32_t g) const { + const Seq* s = find(id); + if (!s || g < 0 || g >= (int32_t)s->state.size()) return -1; + return s->state[(size_t)g]; +} + +/* The tiers' restore path. grab_block is private because every ordinary caller reaches a block + * through a sequence; a restore has none yet -- it has bytes and needs somewhere to put them + * before the prefix cache re-indexes them and takes the reference. */ +int KVManager::reserve_block(int32_t g, int32_t* out) { + if (!out) return RAD_E_INVAL; + *out = -1; + if (g < 0 || g >= (int32_t)plans_.size()) return RAD_E_INVAL; + if (!plans_[(size_t)g].paged()) return RAD_E_INVAL; + if (free_usable_[(size_t)g] <= 0) return RAD_E_FULL; + return grab_block(g, out) == RAD_OK && *out >= 0 ? RAD_OK : RAD_E_FULL; +} + +int64_t KVManager::reserve_blocks(int32_t g, int64_t n, std::vector* out) { + if (!out || n <= 0) return 0; + if (g < 0 || g >= (int32_t)plans_.size() || !plans_[(size_t)g].paged()) return 0; + if (free_usable_[(size_t)g] < n) (void)grow_for(g, n); + int64_t got = 0; + while (got < n && free_usable_[(size_t)g] > 0) { + int32_t b = -1; + if (grab_block(g, &b) != RAD_OK || b < 0) break; + out->push_back(b); + ++got; + } + return got; +} + +/* TAKE ONE PARTICULAR BLOCK, for the tiers' restore under tensor parallelism. Block ids are + * SHARED ACROSS RANKS -- RadBatch carries one block table and every rank indexes its own shard of + * the pool with it -- so a restore cannot let each rank pick its own. Rank 0 decides and the + * others take the same id here. + * + * It refuses rather than substituting when the id is not free, because a rank quietly restoring + * into a different block than its peers is the shape of bug that produces correct-looking output + * on one card and garbage on another. */ +int KVManager::reserve_specific_block(int32_t g, int32_t b) { + if (g < 0 || g >= (int32_t)plans_.size() || !plans_[(size_t)g].paged()) return RAD_E_INVAL; + if (b < 0 || b >= plans_[(size_t)g].n_blocks) return RAD_E_INVAL; + /* PAST THE LIVE MARK IS A REFUSAL. A block above live_ is lent to the expert slab, and + * restoring into one would overwrite the weights a kernel is reading out of it. Rank 0 chooses + * from what it can hand out, so every rank can; a rank that could not is a rank whose loan is + * deeper than its peers', and taking that block silently would be the garbled-on-one-card bug + * this function already exists to prevent. */ + if (b >= live_[(size_t)g]) return RAD_E_STATE; + if (refcount_[(size_t)g][(size_t)b] != 0) return RAD_E_STATE; + /* The heap entry is LEFT BEHIND rather than erased -- erasing from a heap costs a rebuild, + * and grab_block skips an entry whose block is no longer free. */ + refcount_[(size_t)g][(size_t)b] = 1; + --free_usable_[(size_t)g]; + note_held(g, b, +1); + return RAD_OK; +} + +int KVManager::retain_block(int32_t g, int32_t b) { + if (g < 0 || g >= (int32_t)refcount_.size()) return RAD_E_INVAL; + if (b < 0 || b >= (int32_t)refcount_[(size_t)g].size()) return RAD_E_INVAL; + if (refcount_[(size_t)g][(size_t)b] <= 0) { + RAD_ERR("KV group %d: retain of free block %d -- the cache is naming a block it does not " + "hold, which would serve one sequence another's context", g, b); + return RAD_E_STATE; + } + add_ref((size_t)g, b); + cached_[(size_t)g][(size_t)b] = 1; /* at two or more: shared, so not counted */ + return RAD_OK; +} + +void KVManager::cache_reserved_block(int32_t g, int32_t b) { + if (g < 0 || g >= (int32_t)refcount_.size()) return; + if (b < 0 || b >= (int32_t)refcount_[(size_t)g].size()) return; + if (refcount_[(size_t)g][(size_t)b] <= 0) return; + uint8_t& mark = cached_[(size_t)g][(size_t)b]; + if (!mark) { mark = 1; if (refcount_[(size_t)g][(size_t)b] == 1) ++cache_only_[(size_t)g]; } +} + +/* A MARKED BLOCK'S RELEASE IS THE CACHE'S. The cache holds the only marked reference, and the + * other callers -- a restore giving back what it reserved -- release blocks the cache was never + * handed. So the mark goes with the release, and a block a sequence still holds stops counting + * as the cache's. */ +void KVManager::release_block(int32_t g, int32_t b) { + if (g < 0 || g >= (int32_t)refcount_.size()) return; + if (b < 0 || b >= (int32_t)refcount_[(size_t)g].size()) return; + uint8_t& mark = cached_[(size_t)g][(size_t)b]; + if (mark && refcount_[(size_t)g][(size_t)b] > 1) mark = 0; + drop_block(g, b); +} + +int64_t KVManager::cache_only_blocks(int32_t g) const { + if (g < 0 || g >= (int32_t)cache_only_.size()) return 0; + return cache_only_[(size_t)g]; +} + +int32_t KVManager::block_refcount(int32_t g, int32_t b) const { + if (g < 0 || g >= (int32_t)refcount_.size()) return 0; + if (b < 0 || b >= (int32_t)refcount_[(size_t)g].size()) return 0; + return refcount_[(size_t)g][(size_t)b]; +} + +std::vector KVManager::take_pending_copies() { + std::vector out; + out.swap(pending_); + return out; +} + +/* ------------------------------------------------------------------ ensure */ + +int KVManager::ensure(uint64_t id, int64_t n_tokens) { + Seq* s = find(id); + if (!s) return RAD_E_NOTFOUND; + if (n_tokens <= s->n_tokens) return RAD_OK; + + /* Pass 0: recycle whatever the window has slid past. This only frees, so it cannot fail, and + * doing it first means the availability check below sees the memory it releases. */ + for (size_t g = 0; g < plans_.size(); ++g) { + const auto& p = plans_[g]; + if (p.kind != RAD_KV_WINDOW) continue; + int64_t want_end = ceil_div(n_tokens, p.block_size); + int64_t first = s->first_block_pos[g] / p.block_size; + int64_t target = std::max(first, want_end - p.window_blocks); + while (first < target && !s->blocks[g].empty()) { + drop_block((int32_t)g, s->blocks[g].front()); + s->blocks[g].erase(s->blocks[g].begin()); + s->dirty_from[g] = 0; + ++first; + } + if (s->blocks[g].empty()) first = target; /* nothing held: rebase to the window */ + s->first_block_pos[g] = first * p.block_size; + } + + /* Pass 1: can every group serve this? Check before touching anything, so a group that runs + * out does not leave the sequence half-extended and the caller unable to say what it owns. */ + std::vector need(plans_.size(), 0); + int64_t cow = 0; + for (size_t g = 0; g < plans_.size(); ++g) { + const auto& p = plans_[g]; + if (p.paged()) { + int64_t first = s->first_block_pos[g] / p.block_size; + int64_t want = ceil_div(n_tokens, p.block_size) - first; + need[g] = want - (int64_t)s->blocks[g].size(); + if (need[g] < 0) need[g] = 0; + /* Copy-on-write: the partially filled block is the only one a write can reach, and if + * somebody else holds it we must not write through. One extra block, per group. */ + if (s->n_tokens > 0 && s->n_tokens % p.block_size != 0) { + int64_t bi = s->n_tokens / p.block_size - first; + if (bi >= 0 && bi < (int64_t)s->blocks[g].size() + && refcount_[g][(size_t)s->blocks[g][(size_t)bi]] > 1) { need[g] += 1; ++cow; } + } + if (need[g] > available_blocks((int32_t)g)) return RAD_E_FULL; + RAD_TRY(grow_for((int32_t)g, need[g])); + } else if (p.stateful() && s->state[g] < 0) { + if (free_states_[g].empty()) return RAD_E_FULL; + } + } + (void)cow; + + /* Pass 2: commit. Nothing below can fail. */ + for (size_t g = 0; g < plans_.size(); ++g) { + const auto& p = plans_[g]; + if (p.paged()) { + int64_t first = s->first_block_pos[g] / p.block_size; + if (s->n_tokens > 0 && s->n_tokens % p.block_size != 0) { + int64_t bi = s->n_tokens / p.block_size - first; + if (bi >= 0 && bi < (int64_t)s->blocks[g].size()) { + int32_t old = s->blocks[g][(size_t)bi]; + if (refcount_[g][(size_t)old] > 1) { + int32_t fresh = -1; + grab_block((int32_t)g, &fresh); + s->blocks[g][(size_t)bi] = fresh; + s->dirty_from[g] = std::min(s->dirty_from[g], bi); + drop_block((int32_t)g, old); + pending_.push_back({(int32_t)g, old, fresh}); + } + } + } + int64_t want = ceil_div(n_tokens, p.block_size) - first; + if ((int64_t)s->blocks[g].size() < want) + s->dirty_from[g] = std::min(s->dirty_from[g], + (int64_t)s->blocks[g].size()); + while ((int64_t)s->blocks[g].size() < want) { + int32_t b = -1; + grab_block((int32_t)g, &b); + s->blocks[g].push_back(b); + } + } else if (p.stateful() && s->state[g] < 0) { + grab_state((int32_t)g, &s->state[g]); + } + } + s->n_tokens = n_tokens; + return RAD_OK; +} + +/* ------------------------------------------------------------------ adopt / fork */ + +int KVManager::adopt(uint64_t id, int32_t g, const std::vector& blocks, int64_t n_tokens) { + Seq* s = find(id); + if (!s) return RAD_E_NOTFOUND; + const KVGroupPlan* p = plan(g); + if (!p || !p->paged()) return RAD_E_INVAL; + /* A partial block is never shared: the next token written into it would corrupt whoever else + * holds it, and the copy-on-write that would prevent that is pure cost on a block the cache + * cannot serve to anyone else either. Whole blocks only. */ + if (n_tokens % p->block_size != 0) return RAD_E_INVAL; + if ((int64_t)blocks.size() != n_tokens / p->block_size) return RAD_E_INVAL; + if (!s->blocks[(size_t)g].empty()) return RAD_E_STATE; + if (s->n_tokens != 0 && s->n_tokens != n_tokens) return RAD_E_INVAL; + + for (int32_t b : blocks) { + if (b < 0 || b >= p->n_blocks) return RAD_E_INVAL; + add_ref((size_t)g, b); + } + s->blocks[(size_t)g] = blocks; + s->dirty_from[(size_t)g] = 0; + s->n_tokens = n_tokens; + return RAD_OK; +} + +int KVManager::fork(uint64_t parent, uint64_t child) { + Seq* pa = find(parent); + if (!pa) return RAD_E_NOTFOUND; + if (seqs_.count(child)) return RAD_E_DUPLICATE; + + /* Pass 1: the child needs its own state slot in every stateful group before anything is + * shared. A recurrent state is one object and not a chain -- there is no "share the first N + * tokens of a GDN state" -- so a fork of a linear-attention model costs a whole slot, and the + * caller restores into it from a checkpoint (spec §7.3). */ + for (size_t g = 0; g < plans_.size(); ++g) + if (plans_[g].stateful() && free_states_[g].empty()) return RAD_E_FULL; + + int st = add_sequence(child); + if (st < 0) return st; + Seq* ch = find(child); + ch->n_tokens = pa->n_tokens; + for (size_t g = 0; g < plans_.size(); ++g) { + if (plans_[g].paged()) { + ch->blocks[g] = pa->blocks[g]; + ch->first_block_pos[g] = pa->first_block_pos[g]; + for (int32_t b : ch->blocks[g]) add_ref(g, b); + } else { + grab_state((int32_t)g, &ch->state[g]); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ make_room */ + +int KVManager::make_room(uint64_t id, int64_t n_tokens, + const std::vector& victims, + std::vector* preempted) { + /* If it could not fit an empty pool, preempting the whole server would not help. Fail it here + * rather than freeing every other sequence and then deadlocking on it (spec §17). */ + if (!can_ever_fit(n_tokens)) { + RAD_WARN("request %llu wants %lld tokens, which exceeds the whole KV pool. Failing it " + "rather than preempting the server for a request that still would not fit.", + (unsigned long long)id, (long long)n_tokens); + return RAD_E_FULL; + } + Seq* s = find(id); + if (!s) return RAD_E_NOTFOUND; + + auto fits = [&]() { + for (size_t g = 0; g < plans_.size(); ++g) { + const auto& p = plans_[g]; + if (p.paged()) { + int64_t first = s->first_block_pos[g] / p.block_size; + int64_t want = ceil_div(n_tokens, p.block_size) - first; + if (p.kind == RAD_KV_WINDOW) want = std::min(want, p.window_blocks); + int64_t extra = want - (int64_t)s->blocks[g].size() + 1; /* +1 for a COW copy */ + if (extra > available_blocks((int32_t)g)) return false; + } else if (p.stateful() && s->state[g] < 0 && free_states_[g].empty()) return false; + } + return true; + }; + + if (fits()) return RAD_OK; + for (uint64_t v : victims) { + if (v == id) continue; + if (preempt(v) == RAD_OK && preempted) preempted->push_back(v); + if (fits()) return RAD_OK; + } + return fits() ? RAD_OK : RAD_E_FULL; +} + +/* ------------------------------------------------------------------ checkpoints */ + +/* A SLOT IS BACKED WHEN IT IS HANDED OUT, NOT WHEN IT IS CARVED. --checkpoint-slots states how + * many snapshots the server may hold at once; what it costs the card is how many it is holding. + * + * THE CARD REFUSING IS A FULL POOL AND NOT AN ERROR. The slot stays in the free list and the + * caller sees RAD_E_FULL, which is the answer it already handles -- the retention policy runs and + * the allocation is retried. Anything else would turn a card that is momentarily busy into a + * failed request. */ +int KVManager::alloc_checkpoint(int32_t* slot_out) { + if (ck_free_.empty()) return RAD_E_FULL; + /* A SLOT EVERY CARD HAS BACKED ALREADY, WHERE ONE IS FREE: it costs no commit and no reading + * of the card, and a card at its floor still has every slot it backed before. Otherwise the + * top of the free list, backed on every card or not handed out at all. */ + size_t at = ck_free_.size() - 1; + for (size_t i = ck_free_.size(); i-- > 0;) { + const int32_t s = ck_free_[i]; + bool all = ck_backed(s); + for (const KVManager* p : ck_peers_) all = all && p->ck_backed(s); + if (all) { at = i; break; } + } + const int32_t slot = ck_free_[at]; + const int rc = ck_back_everywhere(slot); + if (rc < 0) return rc; + ck_free_.erase(ck_free_.begin() + (std::ptrdiff_t)at); + *slot_out = slot; + return RAD_OK; +} + +void KVManager::free_checkpoint(int32_t slot) { + if (slot < 0 || slot >= (int32_t)ck_slot_base_.size()) return; + for (int32_t f : ck_free_) if (f == slot) return; /* double free: refuse, do not corrupt */ + ck_free_.push_back(slot); + /* AFTER the free list, so a release the driver refuses still leaves the slot allocatable: the + * next commit of the same range is idempotent and the bytes are correct either way. */ + /* AND ONLY WHERE A RELEASE IS WORTH MAKING. See set_release_frees_card: on a driver that does + * not return decommitted VRAM, unmapping these pages buys the card nothing and costs a commit + * on the next allocation of the slot. It is not merely wasted work: the range is unmapped + * while the slot id goes straight back on the free list, so anything still addressing it + * reads a page that is no longer there. */ + if (ck_elastic_ && release_frees_card_ && pool_ && pool_->elastic() && ck_stride_ > 0) { + const int64_t off = ck_slot_base_[(size_t)slot]; + if (pool_->is_committed(off, ck_stride_) && ck_backed_ > 0) --ck_backed_; + (void)pool_->decommit(off, ck_stride_); + } +} + +void* KVManager::checkpoint_ptr(int32_t slot) const { + if (!pool_base_ || slot < 0 || slot >= (int32_t)ck_slot_base_.size()) return nullptr; + return (char*)pool_base_ + ck_slot_base_[(size_t)slot]; +} + +/* One walk, both directions. Keeping save and restore as a single traversal is deliberate: the + * blob has no header and no self-description, so the only thing that makes it readable is that + * exactly one piece of code decides its order. Two functions that agreed today would be two + * functions that could stop agreeing. */ +int KVManager::checkpoint_copy(const int32_t* state_slots, int n_slots, int32_t ck_slot, + bool save, RadStream s) { + /* THIS RANK'S PAGES, BEFORE THIS RANK'S COPY. alloc_checkpoint backed the slot on every rank + * before it handed the id out, so this finds it backed; a refusal here is a slot that did not + * come from there. See KVManager::back_checkpoint. */ + RAD_TRY(back_checkpoint(ck_slot)); + char* ck = (char*)checkpoint_ptr(ck_slot); + if (!ck) return RAD_E_INVAL; + if (!state_slots || n_slots < (int)plans_.size()) return RAD_E_INVAL; + + int64_t off = 0; + for (size_t g = 0; g < plans_.size(); ++g) { + const KVGroupPlan& p = plans_[g]; + if (!p.stateful()) continue; + const int32_t slot = state_slots[g]; + if (slot < 0) return RAD_E_STATE; /* no state to save, or none to restore into */ + const int64_t nbytes = p.layer_bytes_per_state(); + for (int64_t l = 0; l < p.n_layers; ++l) { + void* st = state_ptr((int32_t)g, (int32_t)l, slot); + if (!st) return RAD_E_STATE; + if (off + nbytes > checkpoint_bytes_) { + RAD_ERR("checkpoint slot %d holds %lld bytes and this sequence's linear state " + "needs more than that; configure() sized it from the same plans, so the " + "two have gone out of step", (int)ck_slot, (long long)checkpoint_bytes_); + return RAD_E_STATE; + } + RAD_TRY(save ? rad_memcpy_async(ck + off, st, nbytes, s) + : rad_memcpy_async(st, ck + off, nbytes, s)); + off += nbytes; + } + } + return RAD_OK; +} + +int KVManager::checkpoint_save(const int32_t* slots, int n, int32_t ck, RadStream s) { + return checkpoint_copy(slots, n, ck, /*save=*/true, s); +} +int KVManager::checkpoint_restore(const int32_t* slots, int n, int32_t ck, RadStream s) { + return checkpoint_copy(slots, n, ck, /*save=*/false, s); +} + +/* HOW MANY COLUMNS A SEQUENCE'S state_index ROW HAS. One per physical copy would be the obvious + * answer and it is not the one libr4d wants: its anchor scheme was written against a PAGED state + * cache, where the page a sequence's state lives in moves by -1, 0 or +1 from step to step, so it + * names each copy THREE times and picks the column at run time out of a marker it stamped into + * the scratch. Radiance's linear pool does not page -- a slot is a slot for the life of the + * sequence -- so the three columns naming a copy all name the SAME slot and the marker steers a + * read that lands in the same place whatever it says. + * + * Three columns a copy, therefore, and column j names copy j * copies / width. */ +int64_t KVManager::state_index_width(int32_t g) const { + const KVGroupPlan* p = plan(g); + if (!p || !p->stateful()) return 0; + return p->state_copies > 1 ? p->state_copies * 3 : 1; +} + +int KVManager::state_index_row(uint64_t seq, int32_t g, int32_t* out, int max) const { + const int64_t w = state_index_width(g); + if (w <= 0 || !out || max <= 0) return 0; + const KVGroupPlan* p = plan(g); + const int32_t base = state_slot(seq, g); + const int64_t span = p ? p->n_seq_states() : 0, copies = p ? p->state_copies : 1; + const int n = (int)(w < (int64_t)max ? w : (int64_t)max); + for (int j = 0; j < n; ++j) { + /* A sequence with no slot has none of its copies either: -1 all the way across, which is + * the pad every kernel already tests for. */ + out[j] = base < 0 ? -1 : (int32_t)(base + (int64_t)j * copies / w * span); + } + return n; +} + +void* KVManager::state_ptr(int32_t g, int32_t layer, int32_t s) const { + const KVGroupPlan* p = plan(g); + if (!p || !p->base || s < 0 || s >= p->n_states) return nullptr; + if (layer < 0 || layer >= p->n_layers) return nullptr; + return (char*)p->base + (int64_t)layer * p->layer_stride() + + (int64_t)s * p->layer_bytes_per_state(); +} + +} /* namespace rad */ diff --git a/core/mem/kv.h b/core/mem/kv.h new file mode 100644 index 00000000..b05244ed --- /dev/null +++ b/core/mem/kv.h @@ -0,0 +1,623 @@ +/* kv.h -- the KV block manager (spec §7.2). + * + * Paged, per KV group, each group with its OWN block geometry, its own pool and its own slot + * mapping. Block size comes from KVGroupInfo::block_size, which the build component took off the + * resolved attention kernel's constraints -- never a core constant. A core that picked its own + * block size would be a core that has to be edited when a kernel changes. + * + * Hybrid models are the normal case, not an extension. Four state kinds: + * + * RAD_KV_FULL paged, per-token, growing + * RAD_KV_WINDOW paged, per-token, bounded by the window -- blocks below the window are recycled + * RAD_KV_LINEAR per-sequence, FIXED size: the GDN recurrent state + * RAD_KV_CONV per-sequence, FIXED size: a rolling window of conv_width-1 + n_spec entries + * + * The last two are not paged the same way, and they are allocated, mapped and freed BY THIS + * MANAGER anyway, because otherwise two allocators disagree about what a sequence owns. That + * disagreement is not a memory leak, it is a correctness bug: the scheduler frees a sequence and + * one of the two allocators keeps handing its state slot to the next request. + */ +#pragma once +#include "mem/pools.h" +#include "rad_core.h" + +#include +#include +#include +#include + +namespace rad { + +/* ------------------------------------------------------------------ group sizing */ +/* vLLM slices a hybrid model's layers into equal-sized groups and PADS each bundle up to a + * multiple of that size -- and a padding layer is allocated real memory. On a 48 linear / 16 full + * / 5 drafter model its rule ("group size = the smallest bundle") picks 5, which divides neither + * 48 nor 16, so it allocates 15 groups x 5 = 75 slots for 69 real layers, and rounds the + * per-request requirement up once per group -- fifteen round-ups on every request, which is where + * most of the loss actually is. Replacing that rule with a least-waste search recovers a + * substantial fraction of the KV tokens at a byte-identical budget. + * + * Radiance does not need the search, because it does not have the constraint the search works + * around. A KV group here is one state kind with one geometry and ITS OWN POOL (spec §7.2), so + * there is no uniform page size to pad up to and no reason to subdivide a bundle: every state + * kind is exactly one group covering exactly its own layers. Padding is structurally zero and the + * group count is structurally minimal. + * + * This struct exists so `--debug-placement` can print that claim next to what vLLM would have + * done, and so the test can assert it rather than trusting the comment. */ +struct BundleComparison { + std::vector bundles; /* layers per state kind, as declared */ + int64_t stock_group_size = 0; /* vLLM's rule: the smallest bundle (with the 1.5x escape) */ + int64_t stock_groups = 0; + int64_t stock_slots = 0; /* allocated layer-slots, padding included */ + int64_t patched_group_size = 0; /* the least-waste group size for the same rule */ + int64_t patched_groups = 0; + int64_t patched_slots = 0; + int64_t our_groups = 0; /* == bundles.size() */ + int64_t our_slots = 0; /* == sum(bundles); padding is zero by construction */ + std::string report() const; +}; +BundleComparison compare_bundling(const std::vector& bundles); + +/* ------------------------------------------------------------------ per-group plan */ +struct KVGroupPlan { + int32_t index = -1; /* position in Program::kv_groups */ + std::string name; + int kind = RAD_KV_FULL; + int64_t n_layers = 0; + + int64_t block_size = 0; /* tokens per block, from the resolved kernel */ + int64_t bytes_per_block = 0; /* covers EVERY layer bound to the group -- see the note + * on bundling above: one page, one bundle, no padding */ + int64_t bytes_per_state = 0; /* LINEAR/CONV: per sequence, every layer */ + int64_t conv_slots = 0; /* CONV: conv_width - 1 + n_spec */ + int64_t window_blocks = 0; /* WINDOW: the per-sequence block cap */ + + int64_t n_blocks = 0; /* paged groups: blocks carved from the pool */ + int64_t n_states = 0; /* LINEAR/CONV: n_seq_states * state_copies */ + /* HOW MANY PHYSICAL SLOTS ONE LOGICAL STATE COSTS. One, normally: a sequence owns a state. + * Under speculation a linear kernel needs somewhere to put what it cannot commit yet -- it + * has run 1 + n_spec tokens through the recurrence before anyone knows which survive -- and + * the scheme libr4d uses keeps the committed state in one slot and the per-token replay + * factors in a second, then folds the accepted prefix in at the start of the next step. Two + * slots a sequence, not 1 + n_spec: the factors are a few hundred floats a head against a + * 128x128 state, so they fit inside a slot with room to spare and the pool grows by 2x + * rather than by 9x. Copy k of logical slot s is the physical slot s + k * n_seq_states. */ + int64_t state_copies = 1; + int64_t n_seq_states() const { return state_copies > 0 ? n_states / state_copies : n_states; } + int64_t pool_offset = 0; + int64_t pool_bytes = 0; + void* base = nullptr; + + bool paged() const { return kind == RAD_KV_FULL || kind == RAD_KV_WINDOW; } + bool stateful() const { return kind == RAD_KV_LINEAR || kind == RAD_KV_CONV; } + + /* THE POOL IS LAYER-MAJOR, and that is not a free choice -- the ABI already made it. A + * RAD_OPK_KV operand carries the LAYER as its offset and the core resolves it as + * `base + layer * layer_stride` (RadOperand in rad_runtime.h, KVPoolBinding in + * core/runtime/ctx.h), because an attention kernel takes ONE base pointer for the layer it is + * running and indexes inside it with the block table and the slot mapping. Interleaving the + * layers inside a block would mean every kernel needed the layer count and the bundle stride + * as well, to reach the same bytes. + * + * So layer i owns [base + i*layer_stride, + layer_stride): n_blocks blocks of + * `bytes_per_block / n_layers` for a paged group, n_states states of + * `bytes_per_state / n_layers` for a stateful one. The totals are identical either way, which + * is why sizing does not care and addressing does. */ + int64_t layer_bytes_per_block() const { + return n_layers > 0 ? bytes_per_block / n_layers : bytes_per_block; + } + int64_t layer_bytes_per_state() const { + return n_layers > 0 ? bytes_per_state / n_layers : bytes_per_state; + } + int64_t layer_stride() const { + return paged() ? n_blocks * layer_bytes_per_block() : n_states * layer_bytes_per_state(); + } +}; + +/* A copy the caller must execute on its copy stream before the destination block is read. The + * manager does not issue device copies itself: it has no stream, and a memcpy on the step path is + * a synchronisation the engine spends its whole design avoiding (spec §5.4). */ +struct BlockCopy { + int32_t group = -1; + int32_t src_block = -1; + int32_t dst_block = -1; +}; + +/* A STATE SLOT THAT STILL HOLDS THE PREVIOUS TENANT'S HISTORY. The manager names the work and the + * engine issues it, for the same reason BlockCopy exists: no stream here, and a synchronisation on + * the step path is what this design spends itself avoiding (spec §5.4). + * + * WHY A RECURRENT SLOT HAS TO BE CLEARED AND A PAGED ONE DOES NOT. A paged sequence reads only the + * blocks its own block table names, so a recycled block is unreachable until it is written. A + * recurrent sequence has no table: `gdn_chunk_scan` reads `h0` out of the slot and there is no + * operand in its schema that says "this sequence has none". An uncleared slot IS the last + * sequence's entire compressed history, so the second request a server answers silently continues + * the first: the same prompt gives a different distribution on a fresh process than it does after + * another request has run. + * + * The conv group carries `has_init` and does not need this. It is cleared anyway: two rules about + * one pool is how one of them rots. */ +struct StateClear { + int32_t group = -1; + int32_t slot = -1; +}; + +/* ------------------------------------------------------------------ manager */ +class KVManager { +public: + /* Sizes every group out of one pool and refuses, by name and by how much, if the fixed costs + * alone do not fit. The split between the paged groups is not a policy: they are sized to + * exhaust at the same total token count, and any other split strands memory in whichever + * group outlasts the others. + * + * Both budgets come from the operator and neither is derived here: the byte budget is whatever + * `kv_pool` still has (which is --vram-kv-mib), and the linear-snapshot count is + * Config::checkpoint_slots (--checkpoint-slots). A checkpoint is ~96 MiB on a Qwen3-Next and + * 64 of them is 6 GiB, so how many to retain is a budget decision and therefore not this + * component's to make (spec §6, §7.3). */ + int configure(const std::vector& groups, const Config& cfg, Pool& kv_pool); + + /* configure(), split at the seam the budget resolver needs. plan_groups() sizes every group + * from the declaration and the run configuration -- no pool, no bytes -- and ceiling() then + * says what a FULL cache for `ctx` tokens on max_seqs sequences would cost. Pools are + * allocated before carve() runs, so a derived --vram-kv-mib has to be decided from these two + * and nothing else (core/mem/vram_budget.cpp). carve() spends the pool it is given. */ + int plan_groups(const std::vector& groups, const Config& cfg); + int64_t ceiling(int64_t ctx) const; + int carve(Pool& kv_pool); + + const std::vector& plans() const { return plans_; } + const KVGroupPlan* plan(int32_t group) const; + int32_t n_groups() const { return (int32_t)plans_.size(); } + const BundleComparison& bundling() const { return bundling_; } + std::string report() const; + + /* ---------------- sequences ---------------- */ + int add_sequence(uint64_t seq); + bool has_sequence(uint64_t seq) const; + void free_sequence(uint64_t seq); + /* HOW MANY TIMES A SEQUENCE HAS LET GO OF ITS BLOCKS -- freed or preempted -- over the life of + * the manager. A block's reference count falls for no other reason the prefix cache cannot + * see, so this is what tells it a block it found shared may no longer be. */ + uint64_t seq_frees() const { return seq_frees_; } + + /* Grow the sequence's mapping to cover `n_tokens` in every group. Unshares a shared partial + * block first (copy-on-write) and appends the copy request to the pending list. + * RAD_E_FULL when a group's free list is empty -- the caller preempts and retries. */ + int ensure(uint64_t seq, int64_t n_tokens); + + /* Adopt blocks a prefix-cache hit found. `n_tokens` must be a whole multiple of the group's + * block size: a partial block is never shared, because the next token written into it would + * corrupt the cache entry. Bumps each block's refcount. */ + int adopt(uint64_t seq, int32_t group, const std::vector& blocks, int64_t n_tokens); + + /* Fork: the child shares every WHOLE block of the parent and gets its own copy of the + * partial one on first write (copy-on-write, spec §7.3). Stateful groups cannot be shared -- + * a recurrent state is one object, not a chain -- so the child gets its own slot and the + * caller must snapshot-restore into it. */ + int fork(uint64_t parent, uint64_t child); + + std::vector take_pending_copies(); + + /* The prefix cache's handle on a block. It holds a reference on every block it indexes, and + * that reference is the invariant that makes a hit safe: a block named by the cache is never + * in the free list, so it can never be handed to another sequence underneath a cache entry. + * Nothing else in the engine may call these -- the block table is the manager's property. */ + /* TAKE A FREE BLOCK, with no sequence attached to it yet. The idle-session tiers need this + * and nothing else does: a restore has bytes to put somewhere before any sequence has asked + * for them, and the prefix cache takes the reference afterwards. Every other caller reaches + * blocks through a sequence, which is why grab_block itself stays private -- this is the one + * documented way to hold a block that no Seq owns, and the holder is responsible for + * release_block if the restore then fails. */ + int reserve_block(int32_t group, int32_t* out); + /* THE SAME FOR A WHOLE CHAIN AT ONCE: up to `n` blocks appended to `out`, and how many. The + * loan is recalled for all of them before the first is taken, because a restore is sized + * before it starts and one recall a block would drain the slab a buffer at a time -- the + * reserve above stops at whatever the cache kept in hand. */ + int64_t reserve_blocks(int32_t group, int64_t n, std::vector* out); + /* The same, for a block another rank already chose. See the definition. */ + int reserve_specific_block(int32_t group, int32_t block); + /* The cache's reference on a block a sequence already holds. The block is marked as the + * cache's for cache_only_blocks(). */ + int retain_block(int32_t group, int32_t block); + /* A reserved block's reference handed to the cache as it stands: marked, not counted again. */ + void cache_reserved_block(int32_t group, int32_t block); + /* Lets go of the cache's reference on a marked block and of a reservation's on any other. */ + void release_block(int32_t group, int32_t block); + int32_t block_refcount(int32_t group, int32_t block) const; + /* BLOCKS ONLY THE CACHE HOLDS: marked, and at a reference count of one. This is what an + * eviction would give back, and what a dashboard reports as cache rather than as context. + * Kept current at every reference-count change so that reading it costs nothing: the figure + * is read while the scheduler's lock is held, and a walk of the cache to compute it would + * stall the step for as long as it ran. */ + int64_t cache_only_blocks(int32_t group) const; + + const std::vector& block_table(uint64_t seq, int32_t group) const; + int32_t state_slot(uint64_t seq, int32_t group) const; + int state_index_row(uint64_t seq, int32_t group, int32_t* out, int max) const; + int64_t state_index_width(int32_t group) const; + + /* Slots handed to a sequence since the last drain, oldest first. The engine zeroes each on the + * compute stream before the step that first reads it and then calls clear_state_clears(). */ + const std::vector& state_clears() const { return clears_; } + void clear_state_clears() { clears_.clear(); } + int64_t seq_tokens(uint64_t seq) const; + + /* ---------------- accounting ---------------- */ + int64_t free_blocks(int32_t g) const; + + /* HOW MANY BLOCKS OF A GROUP ANYTHING IS HOLDING. free_blocks() is what may be handed out + * RIGHT NOW, which while the cache is lending is bounded by the live mark and not by the + * carve, so `carve - free` counts every lent block as occupied -- an idle server reading 97% + * full. The occupancy question wants this instead: a lent block is neither held nor + * unavailable, because the loan is recalled on demand up to the carve. */ + int64_t held_blocks(int32_t g) const; + + int64_t total_blocks(int32_t group) const; + int64_t free_states(int32_t group) const; + + /* THE POOL IN BYTES, WHICH IS THE ONLY UNIT THE GROUPS CAN BE ADDED IN. Blocks cannot be: + * a paged group and a stateful one count different objects, and two paged groups share ONE + * token axis -- a token of context takes a slot in each of them -- so summing either measure + * reports a pool several times the size of the one the card holds. Bytes are disjoint VRAM + * and add up. + * + * The used figure is what is HELD rather than what is reachable: a block a sequence owns and + * a block only the prefix cache still references both count, because both are VRAM the next + * request cannot be given. A block stops counting the moment it reaches the free list, + * whether it got there because its sequence ended, because the cache evicted it, or because + * the idle tiers copied it to host memory and released it. */ + int64_t pool_bytes(int32_t group) const; + int64_t pool_bytes_used(int32_t group) const; + /* THE CARVE, which the cache may not be keeping. pool_bytes() is what the cache keeps for + * itself right now; this is what the operator budget gave it to address, and the difference + * between them is what it has lent to the expert slab. */ + int64_t pool_bytes_carved(int32_t group) const; + int64_t blocks_for(int32_t group, int64_t n_tokens) const; + + /* Could a sequence of this length EVER fit, in an empty pool? If not, preempting the whole + * server would not help and the request is failed immediately rather than the engine + * deadlocking on it (spec §17). */ + bool can_ever_fit(int64_t n_tokens) const; + + /* ---------------- the loan ---------------- + * + * THE PAGED GROUPS LEND THE EXPERT SLAB WHAT NOTHING HOLDS, AT THE ADDRESSES THEY ALREADY + * OWN. The carve decides every address once and backs all of it before anything runs, and + * nothing here ever unmaps it. What moves is only how many of a group's blocks the cache may + * hand out: the blocks above that mark, in every layer's stripe, are where the slab keeps + * expert units -- units the MoE GEMM would otherwise read across the link on every step that + * routes to them. No memory is allocated or released in either direction, so no driver call + * is made and what the card reports free never changes. + * + * THE LOAN IS STATED IN TOKENS, counted down from the top of the carve. The FULL groups are + * sized to run out at the same total token count (carve()), so one number is the same depth + * in each of them: a loan of T tokens is the top floor(T / block_size) blocks of every FULL + * group. A WINDOW group is sized per sequence rather than on that axis and is never lent. + * + * A BLOCK IS NOT LENT WHILE ANYTHING HOLDS IT, and a held block is a block a sequence owns OR + * one the prefix cache still indexes. So a loan cannot evict anything: it is a claim on what + * is free. Everything that makes a block free -- a sequence ending, an eviction, an idle-tier + * demotion to host memory or disk -- makes it lendable, and the min-heap free list is what + * keeps the free blocks at the top, where a loan can reach them. + * + * THE BUFFER IS DERIVED AND NOT STATED. It is the free blocks the cache keeps in hand so that + * a request finds room without a recall, and the right size for it is a property of the + * workload rather than a number an operator can know: one prefill chunk -- the most KV a + * single step can consume -- or the largest recent shortfall, whichever is larger. The second + * term decays, so an idle server settles at the floor and a ramping one has the buffer + * leading the ramp. */ + int64_t buffer_bytes() const; + + /* Is this group lent from? The FULL paged groups, and only those. */ + bool lendable(int32_t group) const; + + /* HOW MUCH THE CACHE CAN LEND RIGHT NOW, in tokens: the smallest distance, over the lendable + * groups, from the top of the carve down to the highest block anything holds plus the buffer. + * Rank 0 only -- a follower's held history is empty. Also where the buffer's trend term + * decays, so it is called once per arbiter tick. */ + int64_t spare_tokens(); + + /* LEND `tokens` FROM THE TOP, or take back what a smaller number no longer covers. Lending + * past a held block is refused (RAD_E_STATE): the arbiter asked for more than spare_tokens() + * said there was. Taking back is always allowed here, and it is the caller's to make true -- + * the slab must have left those blocks before this runs. */ + int set_loan(int64_t tokens); + int64_t loan_tokens() const { return loan_; } + + /* WHO GIVES IT BACK WHEN A REQUEST CANNOT WAIT. A request that needs more blocks than the + * cache kept in hand calls this with the loan it can still afford, and the owner of the + * slabs drains them to it before returning -- so admission is decided against the whole + * carve, exactly as it would be with nothing lent. Without one, what is lent is not + * recalled and the request is refused (RAD_E_FULL). */ + void set_reclaim(std::function f) { reclaim_ = std::move(f); } + + /* WHETHER A DECOMMIT ACTUALLY GIVES THE CARD BACK, for the checkpoint region, which is the one + * part of the pool still backed on demand. Measured once at bringup rather than assumed, + * because it is a property of the driver: where it is false a freed checkpoint slot keeps its + * pages, since unmapping them would cost driver calls and return nothing. */ + void set_release_frees_card(bool yes) { release_frees_card_ = yes; } + + /* MATCH A LEADER'S LOAN, FOR A RANK THAT DOES NOT KNOW WHAT IT IS HOLDING. + * + * Block ids are SHARED ACROSS RANKS -- RadBatch carries one block table and every rank indexes + * its own shard of the pool with it -- and only rank 0's KVManager tracks sequences. So a + * follower takes its mark from the leader instead of computing one: its own slab occupies the + * same blocks of its own pool, and an id the leader hands out below the mark has to be one the + * follower's slab has left too. */ + int follow(const KVManager& leader); + + /* HOW MANY OF A GROUP'S BLOCKS THE CACHE MAY HAND OUT: the carve less what is lent. */ + int64_t live_blocks(int32_t group) const; + int64_t committed_bytes() const; + + /* HOW MUCH OF THE CHECKPOINT REGION MUST STAY AVAILABLE, in bytes, counting only what is not + * committed already. The number is the HIGH WATER MARK PLUS ONE rather than the whole cap: + * the cap is what the operator allows and the high water is what this workload takes, and + * holding one slot past it means the allocation that would advance it always has room. */ + int64_t ck_reserve_bytes() const; + + /* BACK THIS RANK'S COPY OF A SLOT, AND SAY SO IF THE CARD WILL NOT. + * + * A slot's LIFETIME is decided once: rank 0's PrefixCache owns the free list and every other + * rank takes the id it is handed. Its BACKING is per rank, because every rank writes its own + * shard of the snapshot into the same offset of its OWN pool. alloc_checkpoint backs the slot + * on every rank before it hands the id out (set_checkpoint_peers), so on the paths that use a + * slot this is a check that finds it backed. Called before EVERY access rather than once: + * idempotence is what makes that safe, and a commit of a range already committed is a no-op. + * + * RAD_E_FULL when the commit would take the card under its floor (set_checkpoint_floor). */ + int back_checkpoint(int32_t slot); + + /* THE CARD'S FLOOR FOR A CHECKPOINT SLOT'S PAGES: the card is read before a slot is backed, + * and a slot that would leave it under `keep_free` bytes is refused as a full pool. + * + * The budget counts the whole checkpoint region as the cache's, but the region is backed as + * slots are taken, and until then its bytes read as free. The allocations nobody sizes in + * advance -- a kernel's code object and a spilling kernel's scratch, both made on the + * kernel's first launch -- are made out of that same free memory. A slot that took the last + * of it would leave the next first launch nothing, which is a fault inside the HIP runtime + * and not an error. A refused slot is a snapshot fewer on the card, which the retention + * policy answers and the host tier covers. + * + * `free_bytes` reads the card's free memory into its argument: the engine reads the device, a + * test reads a simulated card, and no floor is set on a backend with no card. */ + using FreeBytes = std::function; + void set_checkpoint_floor(FreeBytes free_bytes, int64_t keep_free) { + ck_free_bytes_ = std::move(free_bytes); + ck_keep_free_ = keep_free; + } + + /* THE OTHER RANKS' MANAGERS, given to the one whose free list hands the ids out. Every rank + * writes its shard of a snapshot into the same slot of its own pool, so a slot is backed on + * every card or handed out on none: a card that cannot back it is a full pool at allocation, + * which the prefix cache answers by retiring a snapshot, rather than a failed copy after the + * step that produced the state, which stops the engine. */ + void set_checkpoint_peers(std::vector peers) { ck_peers_ = std::move(peers); } + + /* BACK EVERY FREE SLOT NOW, ON EVERY RANK, and withdraw the ones the cards have no room for. + * For a driver that never takes a mapping's pages back (set_release_frees_card(false)): a + * slot backed later costs exactly what it costs now, and backing it now puts the region's + * cost on the card before serving starts, where the startup reading shows it. A withdrawn + * slot is never handed out. `withdrawn` counts them; RAD_E_FULL is not returned. */ + int back_free_checkpoints(int64_t* withdrawn); + + int64_t checkpoint_stride() const { return ck_stride_; } + + /* ---------------- preemption by recompute (spec §7.1, §17) ---------------- */ + /* Free the sequence's blocks and take it back to zero tokens. Its state slots are freed too: a + * recurrent state that is not snapshotted cannot be resumed, so a preempted sequence replays + * from its last checkpoint or from zero. + * + * IT DOES NOT MARK ANYTHING, and carries no "needs re-prefill" flag. The scheduler's own + * `r.n_computed = 0` (preempt_back) is what drives the replay, and a second piece of state + * saying the same thing is a second thing to keep true. seq_tokens() == 0 is the reading, and + * it cannot drift. */ + int preempt(uint64_t seq); + + /* ---------------- speculative rejection (spec §10) ---------------- */ + /* Bring the sequence back to `n_tokens` and return the paged blocks past it. A verify writes + * KV for 1 + n_spec positions and the sampler accepts a prefix of them, so the rest has to go + * back; `ensure` is monotone and cannot express it. + * + * PAGED GROUPS ONLY, and that is the whole point. The linear state and the conv window have + * already absorbed the rejected tokens and are NOT recomputed: libr4d keeps the conv cache as + * a rolling window of conv_width-1 + n_spec entries and reads at the slot the last accepted + * token left, so a rejection there is a change of read offset that the kernels perform + * themselves (core/sample/accept.h). Freeing a state slot here would destroy the state that + * offset points into. + * + * Rolling back is not preemption: the sequence keeps its state slots and its window base. + * Without this the pool leaks one block per rejected block-crossing, which is a slow leak and + * therefore the worst kind. */ + int rollback(uint64_t seq, int64_t n_tokens); + + /* The absolute token position that block_table(seq, group)[0] covers. Zero for a FULL group; + * non-zero for a WINDOW group, whose blocks below the window have been recycled. The step + * batch's slot mapping is (pos - first_block_pos) / block_size, and without the offset every + * sliding-window sequence writes its KV to the wrong slot the moment it passes its window. */ + int64_t first_block_pos(uint64_t seq, int32_t group) const; + + /* THE ENTRIES OF A SEQUENCE'S TABLE THAT CHANGED since the last call: every entry below the + * returned index is what it was then, and kNoDirty says none changed. The call clears the + * mark, so it has exactly one reader -- the batch builder, which stages only the changed tail + * of a table the device already holds. A sequence it has not seen answers 0. */ + int64_t take_table_changes(uint64_t seq, int32_t group) const; + static constexpr int64_t kNoDirty = INT64_MAX; + + /* Free victims, in the order given, until `seq` can be extended to `n_tokens`. + * RAD_OK room was made; *preempted lists who paid for it + * RAD_E_FULL even an empty pool cannot serve it -- fail the request, do not retry + * The caller supplies the victim order because priority is the scheduler's business, not the + * allocator's. */ + int make_room(uint64_t seq, int64_t n_tokens, + const std::vector& victims, + std::vector* preempted); + + /* ---------------- linear-state checkpoints (spec §7.3) ---------------- */ + int64_t checkpoint_bytes() const { return checkpoint_bytes_; } + int64_t checkpoint_slots() const { return (int64_t)ck_slot_base_.size(); } + int64_t free_checkpoint_slots() const { return (int64_t)ck_free_.size(); } + int alloc_checkpoint(int32_t* slot_out); + void free_checkpoint(int32_t slot); + void* checkpoint_ptr(int32_t slot) const; + + /* SNAPSHOT AND RESUME A SEQUENCE'S WHOLE LINEAR STATE. This is what makes a prefix hit legal + * on a hybrid model: the attention half of a hit is carried by the adopted blocks, and the + * recurrent half is carried by these two calls and by nothing else. Without them a hit + * resumes every recurrent layer from whatever the slot last held -- which reads as fluent + * text, so it is not a failure anyone notices without a determinism check. + * + * The pool is LAYER-MAJOR and a sequence's state is therefore strided, not contiguous, so the + * blob is a gather: for every stateful group, in `plans()` order, for every layer, its + * `layer_bytes_per_state()` bytes. Both directions walk that identically, which is the whole + * requirement -- a checkpoint is only ever read back by this same build. + * + * COPY 0 ONLY. A speculating sequence owns `state_copies` physical slots and the committed + * state is copy 0 (KVGroupPlan); the replay factors in the others describe tokens that have + * not been accepted and mean nothing to a later reader. + * + * Enqueued on `s`, not synchronous: the save has to follow the step that produced the state + * and the restore has to precede the step that consumes it, and both are ordered by the + * stream rather than by waiting. RAD_E_INVAL on a bad slot or an unknown sequence. */ + int checkpoint_save(const int32_t* state_slots, int n_slots, int32_t ck_slot, RadStream s); + int checkpoint_restore(const int32_t* state_slots, int n_slots, int32_t ck_slot, RadStream s); + + /* Byte address of a state slot, for the slot-mapping builder. Null when the pool has no + * host-visible base (a device pool), which is the normal case -- the offset is what the step + * batch actually carries. */ + void* state_ptr(int32_t group, int32_t layer, int32_t slot) const; + +private: + /* carve() is the wrapper and carve_into() is the work, so that a carve which returns part way + * through cannot leave plans_ answering guards for block state that was never sized. forget() + * empties both together and is what plan_groups() starts from. */ + int carve_into(Pool& kv_pool); + void forget(); + + /* One traversal serving both checkpoint directions; see checkpoint_save. */ + int checkpoint_copy(const int32_t* state_slots, int n_slots, int32_t ck_slot, bool save, + RadStream s); + + struct Seq { + uint64_t id = 0; + int64_t n_tokens = 0; + std::vector> blocks; /* per group */ + std::vector first_block_pos; /* WINDOW: token pos of blocks[0] */ + std::vector state; /* per group, -1 when not stateful */ + /* Per group, the lowest table entry written since the batch builder last staged this + * sequence: everything below it is unchanged. An append or a truncation lowers it to + * where it touched; anything that shifts or replaces entries lowers it to zero; kNoDirty + * is nothing. Mutable because reading it is what clears it -- take_table_changes. */ + mutable std::vector dirty_from; + }; + + int grab_block(int32_t g, int32_t* out); + void drop_block(int32_t g, int32_t b); + /* Every increment of a held block's reference count, so the cache-only count follows it. */ + void add_ref(size_t g, int32_t b); + int grab_state(int32_t g, int32_t* out); + void drop_state(int32_t g, int32_t s); + Seq* find(uint64_t seq); + const Seq* find(uint64_t seq) const; + + std::vector plans_; + std::vector> free_blocks_; /* per group */ + std::vector> refcount_; /* per group, per block */ + /* Per group, per block: the prefix cache holds one of the references. A free block is never + * marked. `cache_only_` is, per group, how many marked blocks are at a count of one. */ + std::vector> cached_; + std::vector cache_only_; + std::vector> free_states_; /* per group */ + std::unordered_map seqs_; + std::vector pending_; + + std::vector ck_slot_base_; /* pool offsets of the checkpoint slots */ + std::vector ck_free_; + int64_t checkpoint_bytes_ = 0; + std::vector clears_; /* grabbed slots the engine must zero */ + void* pool_base_ = nullptr; + BundleComparison bundling_; + std::string report_; + int64_t max_seqs_ = 0; + int64_t max_ctx_ = 0; + int64_t max_tok_ = 0; /* --max-num-batched-tokens; the buffer floor is one of these */ + /* plan_groups() computes these; carve() spends against them and ceiling() reports on them. */ + int64_t fixed_ = 0; /* the non-negotiable floor: states, conv slots, checkpoints, padding */ + int64_t ck_total_ = 0; /* the checkpoint part of fixed_, named for the refusal message */ + int64_t ckpts_ = 0; /* --checkpoint-slots, as plan_groups() resolved it */ + /* THE SLOT STRIDE AND WHERE THE SLOTS BEGIN. The stride is checkpoint_bytes_ rounded up to a + * whole number of commit granules, so a slot can be backed and released without touching a + * neighbour; the offset is where the eager startup commit stops, because everything from + * there up is backed as it is handed out. Zero on a model with no linear state. */ + bool release_frees_card_ = true; + bool ck_elastic_ = false; + int64_t ck_high_water_ = 0; + int64_t ck_backed_ = 0; + int64_t ck_stride_ = 0; + int64_t ck_region_off_ = 0; + FreeBytes ck_free_bytes_; /* set_checkpoint_floor */ + int64_t ck_keep_free_ = 0; + std::vector ck_peers_; + /* RAD_OK when this rank has the slot backed or room above the floor to back it. */ + int ck_room(int32_t slot) const; + bool ck_backed(int32_t slot) const; + /* The commit itself, with no floor: callers have asked ck_room on every rank first. */ + int ck_commit(int32_t slot); + /* ck_room on every rank, then ck_commit on every rank. */ + int ck_back_everywhere(int32_t slot); + /* What a checkpoint slot is aligned and sized to. RAD_ALIGN_UNIT on a device with no virtual + * memory management, where nothing is released and the stride is only padding. */ + int64_t ck_align() const; + + /* ---- the loan. See the public block for what this is and why a block that anything holds + * is never lent. ---- + * + * `live_` is how many of a group's blocks the cache may hand out -- the carve less the loan -- + * and it gates the free list rather than the carve: every id the carve created is in + * `free_blocks_`, and an id at or above live_ is simply not handed out. THAT IS WHY THE FREE + * LIST IS A MIN-HEAP. Handing out the lowest free id keeps the held blocks packed at the + * bottom of the pool, so the top is what drains and the top is the only part a loan can + * reach; a stack would hand back the id freed most recently, which after a busy period is + * exactly the high block the loan wants. The heap also makes the gate free: the smallest free + * id is below live_ whenever any free id is, so no scan is needed to find one. + * + * `held_hist_` counts held blocks per bucket, so "what is the highest bucket anything still + * holds" is a walk of a few thousand counters instead of a scan of every refcount. It is what + * decides how far a loan may reach, and it is maintained on the allocation path because a + * scan there is not affordable and a stale answer would lend a block out from under a live + * sequence. */ + /* THE BUFFER, PER GROUP, IN BLOCKS. `chunk_blocks_` is the floor -- one prefill chunk, fixed + * at plan time; `short_peak_` is the largest shortfall the admission path has met recently, + * raised by grow_for and decayed by every spare_tokens() so it forgets a burst in a few + * seconds. + * + * THE SHORTFALL IS THE SIGNAL AND THE RECALL IS NOT. grow_for recalls the shortfall PLUS the + * buffer; feeding that back would be a buffer that sizes itself from its own last value and + * climbs until it is the carve. What is recorded is what was asked for and not there. */ + std::vector chunk_blocks_; + std::vector short_peak_; + Pool* pool_ = nullptr; + int64_t loan_ = 0; /* tokens lent from the top of every lendable group */ + uint64_t seq_frees_ = 0; + std::function reclaim_; + std::vector live_; /* per group: blocks the cache may hand out */ + std::vector free_usable_; /* per group: free ids below live_ */ + std::vector bucket_blocks_; /* per group: blocks one held_hist_ bucket covers */ + std::vector> held_hist_; /* per group, per bucket: held blocks */ + + int64_t available_blocks(int32_t g) const; + /* The buffer this group wants in hand, in blocks. See buffer_bytes(). */ + int64_t buf_blocks(size_t i) const; + /* One past the highest block anything holds, to a bucket. */ + int64_t held_top(size_t i) const; + /* The blocks a loan of `tokens` takes off the top of group i. */ + int64_t lent_blocks(size_t i, int64_t tokens) const; + int grow_for(int32_t g, int64_t blocks); + void note_held(int32_t g, int32_t b, int delta); + bool configured_ = false; + static const std::vector kNoBlocks; +}; + +} /* namespace rad */ diff --git a/core/mem/kvtier.cpp b/core/mem/kvtier.cpp new file mode 100644 index 00000000..6d0f3131 --- /dev/null +++ b/core/mem/kvtier.cpp @@ -0,0 +1,1389 @@ +#include "mem/kvtier.h" + +#include "mem/sstier.h" +#include "rad_internal.h" + +#include +#include +#include + +namespace rad { + +const char* kv_tier_name(KVTier t) { + switch (t) { + case KVTier::Device: return "device"; + case KVTier::Host: return "host"; + case KVTier::Disk: return "disk"; + } + return "?"; +} + +/* ------------------------------------------------------------------ HostArena */ + +HostArena::~HostArena() { close(); } + +int HostArena::open(int64_t slot_bytes, int64_t cap_bytes) { + close(); + if (slot_bytes <= 0 || cap_bytes < slot_bytes) return RAD_E_INVAL; + const int64_t n = cap_bytes / slot_bytes; + /* PINNED, and the allocation is refused rather than downgraded. A pageable host buffer on + * this path does not fail, it just collapses -- an async copy to pageable memory serialises + * against the stream and the whole point of moving instead of dropping is gone. Better to + * start without the tier and say so than to run it at a tenth of the rate it was budgeted at. */ + base_ = rad_dev_alloc(n * slot_bytes, RAD_MEM_HOST_PINNED); + if (!base_) return RAD_E_NOMEM; + slot_bytes_ = slot_bytes; + used_ = 0; + cap_slots_ = n; + cursor_ = 0; + bits_.assign((size_t)((n + 63) / 64), 0ull); + return RAD_OK; +} + +void HostArena::close() { + if (base_) rad_dev_free(base_, RAD_MEM_HOST_PINNED); + base_ = nullptr; + slot_bytes_ = 0; + used_ = 0; + cap_slots_ = 0; + cursor_ = 0; + bits_.clear(); +} + +int32_t HostArena::alloc() { + int32_t got = 0; + return alloc_run(1, &got); +} + +/* THE FIRST FREE RUN AT OR AFTER THE CURSOR, wrapping once. A whole word of used slots is skipped + * in one compare, so a nearly full arena costs a scan of its bitmap -- a few thousand words at the + * sizes an operator gives this -- and an arena with room costs nothing. The cursor makes + * consecutive calls hand out consecutive slots, which is what lets a batch be one copy a run. */ +int32_t HostArena::alloc_run(int32_t want, int32_t* got) { + *got = 0; + if (want <= 0 || !base_ || full()) return -1; + int64_t s = -1; + for (int pass = 0; pass < 2 && s < 0; ++pass) { + const int64_t lo = pass == 0 ? cursor_ : 0; + const int64_t hi = pass == 0 ? cap_slots_ : cursor_; + for (int64_t i = lo; i < hi;) { + const uint64_t w = bits_[(size_t)(i >> 6)]; + if ((i & 63) == 0 && w == ~0ull) { i += 64; continue; } + if (!is_used(i)) { s = i; break; } + ++i; + } + } + if (s < 0) return -1; + int64_t n = 0; + while (n < want && s + n < cap_slots_ && !is_used(s + n)) { + bits_[(size_t)((s + n) >> 6)] |= 1ull << ((s + n) & 63); + ++n; + } + used_ += n; + cursor_ = s + n >= cap_slots_ ? 0 : s + n; + *got = (int32_t)n; + return (int32_t)s; +} + +void HostArena::free(int32_t slot) { + if (slot < 0 || slot >= cap_slots_) return; + /* A slot that is already free is refused rather than counted twice: the used count is what the + * sessions view reports and what `full` answers, and a negative one hides the next leak. */ + if (!is_used(slot)) return; + bits_[(size_t)(slot >> 6)] &= ~(1ull << (slot & 63)); + --used_; +} + +void* HostArena::at(int32_t slot) const { + if (!base_ || slot < 0 || slot >= cap_slots_) return nullptr; + return (char*)base_ + (int64_t)slot * slot_bytes_; +} + +/* ------------------------------------------------------------------ IdleTiers */ + +int IdleTiers::configure(const Config& c, SSDTier* disk) { + std::lock_guard lk(mu_); + reset(); + cfg_ = c; + disk_ = disk; + + /* THE SNAPSHOT STORE IS CARVED OUT OF THE TIER, NOT ADDED TO IT. engine_bringup decides how + * much; what matters here is that the block arena is opened against what is left, so the two + * together never exceed what --prefix-cache-host-mib asked for. */ + if (cfg_.ckpt_bytes > 0 && cfg_.ckpt_cap_bytes >= cfg_.ckpt_bytes && cfg_.host_cap_bytes > 0) { + if (ck_arena_.open(cfg_.ckpt_bytes, cfg_.ckpt_cap_bytes) != RAD_OK) { + RAD_WARN("kv tiers: no pinned host memory for %s of linear-state snapshots; a hybrid " + "session's blocks will tier and its recurrent state will not", + humanb(cfg_.ckpt_cap_bytes).c_str()); + cfg_.ckpt_cap_bytes = 0; + } else { + cfg_.host_cap_bytes -= ck_arena_.cap_bytes(); + } + } else { + cfg_.ckpt_cap_bytes = 0; + } + + if (cfg_.host_cap_bytes > 0 && cfg_.entry_bytes > 0) { + const int st = arena_.open(cfg_.entry_bytes, cfg_.host_cap_bytes); + if (st != RAD_OK) { + RAD_WARN("kv tiers: no pinned host memory for %s, the host tier is off", + humanb(cfg_.host_cap_bytes).c_str()); + cfg_.host_cap_bytes = 0; + /* The snapshot store rides on the host tier: nothing reaches disk except through it, + * so a snapshot arena under no block arena would fill once and never drain. */ + ck_arena_.close(); + cfg_.ckpt_cap_bytes = 0; + } + } else { + cfg_.host_cap_bytes = 0; + ck_arena_.close(); + cfg_.ckpt_cap_bytes = 0; + } + if (!disk_ || !disk_->enabled()) cfg_.disk_cap_bytes = 0; + + /* A disk tier under no host tier is legal and it is not a mistake: the path to disk runs + * through host memory, so with no host tier nothing ever reaches disk, and saying so at + * startup is cheaper than an operator reading a disk tier's zero counters for an afternoon. */ + if (!host_on() && disk_on()) + RAD_WARN("kv tiers: --prefix-cache-disk-mib is set but --prefix-cache-host-mib is not, and the " + "path to disk runs through host memory -- nothing will be written"); + + char buf[512]; + if (!any_on()) { + report_ = "kv tiers: off (no --prefix-cache-host-mib), so a finished conversation's KV stays " + "in VRAM until the cache evicts it under pressure -- it is never copied to host " + "memory, and what the pool is holding is mostly cache rather than live requests"; + } else { + std::snprintf(buf, sizeof buf, + "kv tiers: a finished conversation's KV is copied to host memory at once " + "(%s, %lld entries) and its VRAM is given up when the expert loan or a " + "request wants it; %s. One entry is %s", + humanb(arena_.cap_bytes()).c_str(), (long long)arena_.capacity(), + disk_on() ? ("every host copy is written on to disk (" + + humanb(cfg_.disk_cap_bytes) + ") and its slot is given up " + "when another entry needs it").c_str() + : "no disk tier, so a full host tier drops its oldest entries", + humanb(cfg_.entry_bytes).c_str()); + report_ = buf; + /* SAID EVEN WHEN IT IS ZERO, on a model that has recurrent state. A hybrid server whose + * snapshots do not tier looks identical from every block counter there is, and the + * difference it makes is a full linear replay of the transcript on what the hit rate will + * happily report as a hit. */ + if (cfg_.ckpt_bytes > 0) { + std::snprintf(buf, sizeof buf, + "\nkv tiers: a session's linear state moves with its blocks -- %lld " + "snapshot(s) of %s in host memory, %lld on disk", + (long long)ck_arena_.capacity(), humanb(cfg_.ckpt_bytes).c_str(), + (long long)cfg_.ckpt_disk_slots); + report_ += buf; + if (!ckpt_on()) + report_ += " -- NONE, so an idle hybrid session comes back needing a full " + "linear replay; give --prefix-cache-host-mib more room"; + } + } + return RAD_OK; +} + +void IdleTiers::close() { + std::lock_guard lk(mu_); + reset(); +} + +/* The body of close(), for the caller that already holds the lock. */ +void IdleTiers::reset() { + recs_.clear(); + sessions_.clear(); + roots_.clear(); + host_lru_.clear(); + disk_lru_.clear(); + wb_q_.clear(); + dk_q_.clear(); + clean_q_.clear(); + ck_frees_.clear(); + starved_ = 0; + wb_stuck_ = false; + arena_.close(); + ck_arena_.close(); + disk_ = nullptr; + cfg_ = Config{}; + report_.clear(); +} + +std::string IdleTiers::report() const { return report_; } + +void IdleTiers::unlist(Rec& r) { + if (!r.listed) return; + list_for(r.tier).erase(r.it); + r.listed = false; +} + +/* ONLY A RECORD WHOSE BYTES ARE ONLY OFF THE CARD. A device record -- clean or not -- is ordered by + * the prefix cache's own LRU, and a second ordering of the same entries is the two-owner shape the + * header's one-record rule exists to rule out. */ +void IdleTiers::relist(const BlockHash& key, Rec& r) { + if (r.pending || r.tier == KVTier::Device || r.listed) return; + std::list& l = list_for(r.tier); + l.push_back(key); + r.it = std::prev(l.end()); + r.listed = true; +} + +bool IdleTiers::wants_copy(const Rec& r) const { + if (r.pending || r.doomed) return false; + const bool blocks = host_on() && r.tier == KVTier::Device && r.host_slot < 0 && !r.on_disk && + !r.blocks.empty(); + return blocks || wants_ck_copy(r); +} + +bool IdleTiers::wants_ck_copy(const Rec& r) const { + /* A snapshot on a disk record stays where it is: the record's blocks are already past the + * host tier, and the device slot it still holds is reachable the moment they come back. */ + return ckpt_on() && r.ck_dev >= 0 && r.ck_host < 0 && !r.ck_on_disk && !r.ck_skip && + r.tier != KVTier::Disk; +} + +bool IdleTiers::wants_disk(const Rec& r) const { + if (!disk_on() || r.doomed) return false; + const bool blocks = r.host_slot >= 0 && !r.on_disk && r.disk_src < 0; + const bool snap = cfg_.ckpt_disk_slots > 0 && r.ck_host >= 0 && !r.ck_on_disk && + r.ck_disk_src < 0; + return blocks || snap; +} + +void IdleTiers::queue_copy(const BlockHash& key, Rec& r) { + if (r.queued || !wants_copy(r)) return; + wb_q_.push_back(key); + r.queued = true; +} + +void IdleTiers::queue_disk(const BlockHash& key, Rec& r) { + if (r.disk_q || !wants_disk(r)) return; + dk_q_.push_back(key); + r.disk_q = true; +} + +void IdleTiers::give_slot(int32_t slot) { + if (slot < 0) return; + arena_.free(slot); + wb_stuck_ = false; +} + +void IdleTiers::free_host(Rec& r) { + if (r.host_slot < 0) return; + if (r.host_slot != r.disk_src) give_slot(r.host_slot); + r.host_slot = -1; +} + +void IdleTiers::free_ck_host(Rec& r) { + if (r.ck_host < 0) return; + if (r.ck_host != r.ck_disk_src) ck_arena_.free(r.ck_host); + r.ck_host = -1; +} + +/* THE ONE PLACE `on_disk` CHANGES, because the disk figure in the occupancy view is kept beside it + * rather than counted, and an entry landing on disk is also what unblocks a stuck write-back. */ +void IdleTiers::set_on_disk(Rec& r, bool v) { + if (r.on_disk == v) return; + r.on_disk = v; + stats_.disk_bytes += v ? cfg_.entry_bytes : -cfg_.entry_bytes; + if (v) wb_stuck_ = false; +} + +void IdleTiers::queue_clean(const BlockHash& key, Rec& r) { + if (r.clean_q) return; + clean_q_.push_back(key); + r.clean_q = true; +} + +/* EVERYTHING THIS RECORD HOLDS OFF THE CARD, both halves. The blocks' arena slot and the + * snapshot's are different arenas with different slot sizes; SSDTier owns its own slots either way + * and reclaims them by LRU, so there is nothing to give back for a disk-resident record. + * + * A snapshot still in its device slot is the CACHE'S, not this object's: the cache retires device + * snapshots by its own retention policy and the slot is still correct and indexed. Only a snapshot + * that exists nowhere but here is lost with the record, and only that loss is announced -- the + * cache learns about a lost ENTRY from set_drop_sink at the sites that erase one, and this is also + * called from forget(), where the cache is the caller and already knows. */ +void IdleTiers::release_storage(const BlockHash& key, Rec& r) { + free_host(r); + set_on_disk(r, false); + const bool lost_ck = r.ck_dev < 0 && (r.ck_host >= 0 || r.ck_on_disk); + free_ck_host(r); + r.ck_on_disk = false; + if (lost_ck) { ++stats_.ck_drops; if (on_ck_drop_) on_ck_drop_(key); } +} + +/* ------------------------------------------------------------------ the linear half */ + +void IdleTiers::note_snapshot(const BlockHash& key, int32_t dev_slot, int64_t pos) { + if (dev_slot < 0) return; + std::lock_guard lk(mu_); + Rec& r = recs_[key]; + /* A FRESH DEVICE SNAPSHOT REPLACES WHATEVER COPY THERE WAS, never joins it. The host copy + * described the state as it was last written; the slot now holds it as it was just written, + * and a record that called the two the same bytes would restore the older one. The copy goes + * and the snapshot is queued for a new one. + * + * Never while a copy is outstanding, for the same reason: report() owns the slot the job was + * handed and frees it when it sees the record's device slot has changed under it. */ + if (!r.pending) free_ck_host(r); + r.ck_on_disk = false; + r.ck_dev = dev_slot; + r.ck_pos = pos; + r.ck_skip = false; + /* COPIED ONCE ITS RECORD IS PUBLISHED, like the blocks: note_used queues it then. A request + * commits its checkpoints as its prefill passes them, so copying each at commit would send the + * shallow ones across first, one at a time, while the tip does not exist yet -- and the tip is + * the one the next turn resumes from. Published together, they are planned together, and the + * plan takes the deepest first. A record the request had already published takes a new + * commit at once. */ + if (r.tier != KVTier::Device || !r.blocks.empty()) queue_copy(key, r); +} + +bool IdleTiers::release_snapshot(const BlockHash& key) { + std::lock_guard lk(mu_); + auto it = recs_.find(key); + if (it == recs_.end()) return false; + Rec& r = it->second; + /* A COPY IS READING THE DEVICE SLOT. The record forgets the snapshot now -- the cache no longer + * has it -- but the slot itself is held until the copy reports, because freeing it here lets + * the pool decommit a page an asynchronous transfer is still reading. */ + if (r.ck_reading && r.ck_dev >= 0) { + r.ck_free_after = r.ck_dev; + r.ck_dev = -1; + free_ck_host(r); + r.ck_on_disk = false; + return true; + } + /* The host copy is the record's to free unless a job is carrying it: a pending host or disk + * record is being restored out of that very slot, and report() gives it back. A pending device + * record is a copy of its blocks, whose snapshot half -- if it has one -- is the record's own. */ + if (!r.pending || r.tier == KVTier::Device) free_ck_host(r); + r.ck_on_disk = false; + r.ck_dev = -1; + /* A RECORD THAT ONLY EVER EXISTED FOR THE SNAPSHOT GOES WITH IT. note_snapshot creates one at + * commit time, which is mid-request and long before the chain is published; a request that + * never publishes -- a rebased block table, a cancel before the first whole block -- would + * otherwise leave a record with no blocks, no storage and no way to be reached again. */ + if (!r.pending && r.tier == KVTier::Device && r.blocks.empty() && r.host_slot < 0) + recs_.erase(it); + return false; +} + +void IdleTiers::take_checkpoint_frees(std::vector* out) { + std::lock_guard lk(mu_); + out->insert(out->end(), ck_frees_.begin(), ck_frees_.end()); + ck_frees_.clear(); +} + +bool IdleTiers::snapshot_reading(const BlockHash& key) const { + std::lock_guard lk(mu_); + auto it = recs_.find(key); + return it != recs_.end() && it->second.ck_reading; +} + +int32_t IdleTiers::evict_snapshot_slot(bool lossless) { + /* EVERY RECORD HOLDING A SNAPSHOT'S HOST COPY IS A CANDIDATE, on the lists or not. A session + * still in VRAM holds its snapshots' host copies from the moment they land, and a search that + * looked only at the off-device lists would not see them: the first snapshot to land would keep + * the slot and every later one -- the running session's own tip among them -- would be refused + * for good. The arena is a few slots deep, so the walk is over the records, once, and only + * when a copy has found the arena full. + * + * THREE PRICES, cheapest first. A copy the disk store also holds costs nothing. A copy of a + * snapshot still in its device slot costs that slot its backing: the checkpoint pool can no + * longer detach it, only retire it, and a restore that needs a device slot can no longer take + * it. A copy that is the snapshot's only one costs the state. A restore takes only the first + * kind -- anything else trades one session's state for another's. + * + * THE TIP IS THE ONE WORTH KEEPING, so within a price the earliest POSITION loses: within a + * session that is exactly "not the tip", which is the one position an appending conversation + * will ask for and the one that makes its replay short. Across sessions it is a choice between + * snapshots that are equally not tips, and the older one goes. + * + * The slot is returned to the caller rather than freed, because the caller is about to + * allocate one: going through the free list would be the same slot and two more operations. */ + Rec* best = nullptr; + const BlockHash* best_key = nullptr; + int best_price = 3; + const uint64_t now = rad_mono_ns(); + for (auto& kv : recs_) { + Rec& r = kv.second; + if (r.pending || r.doomed || r.ck_host < 0 || r.ck_host == r.ck_disk_src || + held_by_fetch(r, now)) + continue; + const int price = r.ck_on_disk ? 0 : r.ck_dev >= 0 ? 1 : 2; + if (lossless && price > 0) continue; + if (best && (price > best_price || + (price == best_price && + (r.ck_pos > best->ck_pos || + (r.ck_pos == best->ck_pos && r.used_ns >= best->used_ns))))) + continue; + best = &r; + best_key = &kv.first; + best_price = price; + } + if (!best) return -1; + Rec& r = *best; + const int32_t s = r.ck_host; + r.ck_host = -1; + if (best_price == 2) { + ++stats_.ck_drops; + if (on_ck_drop_) on_ck_drop_(*best_key); + } else if (best_price == 1) { + /* Still in its device slot and nowhere else off the card: its index entry is as good as + * it was, and it is not queued for another copy (Rec::ck_skip). */ + r.ck_skip = true; + } + return s; +} + +/* ------------------------------------------------------------------ the cache's notices */ + +void IdleTiers::note_used(const BlockHash& key, const std::vector& blocks, uint64_t now_ns) { + if (!any_on()) return; + std::lock_guard lk(mu_); + Rec& r = recs_[key]; + r.used_ns = now_ns; + if (r.tier == KVTier::Device && !r.pending) r.blocks = blocks; + /* A record only moves to the back of its list when it is IN one. A device record is a + * timestamp and nothing else, which is what keeps this cheap enough to sit on the publish + * path -- the hash insert is the whole cost. */ + if (r.listed) { + list_for(r.tier).erase(r.it); + r.listed = false; + relist(key, r); + } + queue_copy(key, r); +} + +void IdleTiers::note_hits(const BlockHash* keys, int64_t n, uint64_t now_ns) { + if (!any_on() || !keys || n <= 0) return; + std::lock_guard lk(mu_); + for (int64_t i = 0; i < n; ++i) { + auto it = recs_.find(keys[i]); + if (it == recs_.end()) continue; + Rec& r = it->second; + r.used_ns = now_ns; + if (r.listed) { + list_for(r.tier).erase(r.it); + r.listed = false; + relist(keys[i], r); + } + } +} + +void IdleTiers::rebound(const BlockHash& key, const std::vector& blocks, uint64_t now_ns) { + if (!any_on()) return; + std::lock_guard lk(mu_); + Rec& r = recs_[key]; + if (r.pending) return; + unlist(r); + release_storage(key, r); + r.tier = KVTier::Device; + r.blocks = blocks; + r.used_ns = now_ns; + queue_copy(key, r); +} + +bool IdleTiers::doomed(const BlockHash& key) const { + std::lock_guard lk(mu_); + auto it = recs_.find(key); + return it == recs_.end() || it->second.doomed; +} + +IdleTiers::Stats IdleTiers::stats() const { + std::lock_guard lk(mu_); + Stats s = stats_; + /* What the block arena holds, clean copies included: counted off the arena rather than kept + * beside it, because every path that takes or returns a slot would otherwise have to remember + * to move a second number. */ + s.host_bytes = arena_.used_slots() * cfg_.entry_bytes; + return s; +} + +void IdleTiers::forget(const BlockHash& key) { + std::lock_guard lk(mu_); + /* AND EVERY CONVERSATION THAT STARTED HERE. This is the only notice the cache gives that an + * entry is gone for good, and a chain whose first block has gone cannot be hit at any length + * -- a prefix hit starts at position zero. Leaving the row behind would report blocks the + * pool has already handed to somebody else as this session's, and would hold its whole chain + * in memory for a conversation that can never come back. */ + auto ro = roots_.find(key); + if (ro != roots_.end()) { + const std::vector ids = ro->second; /* drop_session rewrites the list */ + for (uint64_t id : ids) drop_session(id); + } + auto it = recs_.find(key); + if (it == recs_.end()) return; + Rec& r = it->second; + if (r.pending) { + /* The engine is mid-transfer against this record. Erasing it now is exactly the + * use-after-free the one-record rule exists to prevent, so mark it and let report() + * finish the job and clean up. */ + r.doomed = true; + return; + } + unlist(r); + release_storage(key, r); + recs_.erase(it); +} + +KVTier IdleTiers::tier_of(const BlockHash& key) const { + std::lock_guard lk(mu_); + auto it = recs_.find(key); + return it == recs_.end() ? KVTier::Device : it->second.tier; +} + +bool IdleTiers::resident_off_device(const BlockHash& key) const { + std::lock_guard lk(mu_); + auto it = recs_.find(key); + if (it == recs_.end()) return false; + return !it->second.pending && it->second.tier != KVTier::Device; +} + +/* ------------------------------------------------------------------ copy on idle */ + +bool IdleTiers::writeback_waiting() const { + std::lock_guard lk(mu_); + /* NOT WHILE NOTHING CAN MOVE. An arena full of copies the disk does not hold yet has nothing + * to give up, so a plan would pop the queue, find no slot and put it back, every tick, until + * a slot is freed or a disk copy lands -- which is what ends the wait. */ + if (wb_stuck_ && arena_.full()) return false; + return !wb_q_.empty() && (host_on() || ckpt_on()); +} + +bool IdleTiers::disk_waiting() const { + std::lock_guard lk(mu_); + return !dk_q_.empty(); +} + +int64_t IdleTiers::make_room(int64_t n) { + std::lock_guard lk(mu_); + return make_room_locked(n); +} + +/* A READ NO REQUEST CLAIMS IS HELD THIS LONG. A request is admitted on the step after its read lands, + * which is milliseconds; this only bounds what one that went away -- cancelled while it waited -- + * keeps out of reach of everybody else. */ +static constexpr uint64_t kFetchHoldNs = 10ull * 1000000000ull; + +bool IdleTiers::held_by_fetch(const Rec& r, uint64_t now_ns) const { + return r.keep || (r.fetched_ns != 0 && now_ns - r.fetched_ns < kFetchHoldNs); +} + +int64_t IdleTiers::make_room_locked(int64_t n) { + if (!disk_on() || n <= 0) return 0; + const uint64_t now = rad_mono_ns(); + int64_t freed = 0; + /* HOST RECORDS FIRST, oldest first: nothing is in VRAM to use them, and they become disk + * records. The walk skips the ones whose disk copy has not landed, which are the newest -- + * the writes go out in the order the copies landed -- so it stops close to the front. */ + for (auto it = host_lru_.begin(); it != host_lru_.end() && freed < n;) { + const BlockHash key = *it; + ++it; + auto ri = recs_.find(key); + if (ri == recs_.end()) continue; + Rec& r = ri->second; + if (r.pending || !r.on_disk || r.host_slot < 0 || r.host_slot == r.disk_src || + held_by_fetch(r, now)) + continue; + unlist(r); + free_host(r); + r.tier = KVTier::Disk; + relist(key, r); + ++freed; + } + /* THEN THE HOST COPIES OF CLEAN VRAM ENTRIES, oldest first. The VRAM copy stays and stays + * clean -- its disk copy is what lets it go now. These are on no list (a device record is + * ordered by the cache), so they are found by a walk, which only a full arena of them pays. */ + if (freed < n) { + std::vector> c; + for (auto& kv : recs_) { + Rec& r = kv.second; + if (r.tier == KVTier::Device && !r.pending && r.on_disk && r.host_slot >= 0 && + r.host_slot != r.disk_src && !held_by_fetch(r, now)) + c.emplace_back(r.used_ns, &r); + } + const size_t k = std::min(c.size(), (size_t)(n - freed)); + std::partial_sort(c.begin(), c.begin() + (long)k, c.end(), + [](const auto& a, const auto& b) { return a.first < b.first; }); + for (size_t i = 0; i < k; ++i) { free_host(*c[i].second); ++freed; } + } + stats_.host_freed += freed; + return freed; +} + +bool IdleTiers::starved() const { + std::lock_guard lk(mu_); + return starved_ > 0; +} + +void IdleTiers::plan_writeback(int64_t max_entries, std::vector* out) { + if (!host_on() || max_entries <= 0) return; + std::lock_guard lk(mu_); + /* A SEPARATE, MUCH SMALLER BUDGET FOR SNAPSHOTS, because they are not the same size of thing. + * A block entry is tens of kilobytes; a snapshot on a production hybrid is a hundred megabytes + * or more. Copying a session's whole retained set in one pass would queue most of a second of + * link time ahead of whatever the transfer stream is asked for next. */ + int ck_budget = 2; + std::vector later; /* wanted only a snapshot the budget could not take */ + std::vector ck_jobs; /* jobs whose record wants its snapshot copied too */ + size_t first = out->size(); + while (!wb_q_.empty() && (int64_t)(out->size() - first) < max_entries) { + const BlockHash key = wb_q_.front(); + wb_q_.pop_front(); + auto it = recs_.find(key); + if (it == recs_.end()) continue; + Rec& r = it->second; + r.queued = false; + if (!wants_copy(r)) continue; + TierJob j; + j.kind = TierJob::Kind::WriteBack; + j.key = key; + j.bytes = cfg_.entry_bytes; + if (r.tier == KVTier::Device && r.host_slot < 0 && !r.on_disk) j.blocks = r.blocks; + if (wants_ck_copy(r)) { + j.ck_pos = r.ck_pos; + ck_jobs.push_back(out->size()); + } + out->push_back(std::move(j)); + } + + /* THE SNAPSHOT BUDGET GOES TO THE DEEPEST FIRST. A session commits its checkpoints in order, + * so the queue holds its shallow ones ahead of its tip -- and the tip is the one its next turn + * resumes from. Taken in queue order, the shallow ones would fill a snapshot arena a few slots + * deep and the tip would be refused for good. Across sessions a position says nothing, and the + * order among them is the queue's, which is as arbitrary as any. */ + std::stable_sort(ck_jobs.begin(), ck_jobs.end(), + [out](size_t a, size_t b) { return (*out)[a].ck_pos > (*out)[b].ck_pos; }); + for (size_t idx : ck_jobs) { + TierJob& j = (*out)[idx]; + if (ck_budget <= 0) continue; /* a later pass; the record is queued again */ + Rec& r = recs_[j.key]; + int32_t cs = ck_arena_.alloc(); + if (cs < 0) cs = evict_snapshot_slot(/*lossless=*/false); + if (cs >= 0) { + j.ck_dev = r.ck_dev; + j.ck_host = cs; + j.ck_bytes = cfg_.ckpt_bytes; + --ck_budget; + } else { + /* Nowhere to put it, and nothing to evict: this snapshot goes without a copy until a + * new commit replaces it. Waiting would retry it every pass for the same answer. */ + ++stats_.ck_starved; + r.ck_skip = true; + } + } + for (size_t i = first; i < out->size();) { + const TierJob& j = (*out)[i]; + if (j.blocks.empty() && j.ck_host < 0) { + later.push_back(j.key); + out->erase(out->begin() + (long)i); + continue; + } + ++i; + } + + /* THE HOST SLOTS, AS RUNS. Taken for the whole batch at once so that entries planned together + * sit together in the arena and each run crosses the link as one copy. A batch the arena + * cannot hold is cut where the arena ran out: the entries past that point keep only their + * snapshot half, or go back to the front of the queue, and the maintenance plan is told how + * many copies were refused so it can make that much room. */ + int64_t want = 0; + for (size_t i = first; i < out->size(); ++i) if (!(*out)[i].blocks.empty()) ++want; + if (want > arena_.free_slots()) make_room_locked(want - arena_.free_slots()); + std::vector slots; + slots.reserve((size_t)want); + while ((int64_t)slots.size() < want) { + int32_t got = 0; + const int32_t s = arena_.alloc_run((int32_t)(want - (int64_t)slots.size()), &got); + if (s < 0) break; + for (int32_t k = 0; k < got; ++k) slots.push_back(s + k); + } + size_t next = 0; + std::vector refused; + for (size_t i = first; i < out->size();) { + TierJob& j = (*out)[i]; + if (!j.blocks.empty()) { + if (next < slots.size()) { + j.host_slot = slots[next++]; + } else { + ++starved_; + j.blocks.clear(); + if (j.ck_host < 0) { + refused.push_back(j.key); + out->erase(out->begin() + (long)i); + continue; + } + } + } + ++i; + } + if (want > 0 && slots.empty()) wb_stuck_ = true; + for (size_t i = first; i < out->size(); ++i) { + const TierJob& j = (*out)[i]; + Rec& r = recs_[j.key]; + unlist(r); + r.pending = true; + r.ck_reading = j.ck_host >= 0; + } + /* Back where they were: the refused ones at the front, in order, so the oldest conversation is + * still the first copied once there is room; the snapshot-only ones at the back, since the + * budget and not the arena is what held them. */ + for (auto it = refused.rbegin(); it != refused.rend(); ++it) { + auto ri = recs_.find(*it); + if (ri == recs_.end() || ri->second.queued) continue; + wb_q_.push_front(*it); + ri->second.queued = true; + } + for (const BlockHash& k : later) { + auto ri = recs_.find(k); + if (ri != recs_.end()) queue_copy(k, ri->second); + } +} + +void IdleTiers::take_clean(std::vector* out) { + std::lock_guard lk(mu_); + for (const BlockHash& k : clean_q_) { + auto it = recs_.find(k); + if (it == recs_.end()) continue; + it->second.clean_q = false; + out->push_back(k); + } + clean_q_.clear(); +} + +bool IdleTiers::droppable(const BlockHash& key) const { + std::lock_guard lk(mu_); + auto it = recs_.find(key); + if (it == recs_.end()) return false; + const Rec& r = it->second; + return !r.pending && !r.doomed && r.tier == KVTier::Device && (r.host_slot >= 0 || r.on_disk); +} + +void IdleTiers::drop_commit(const BlockHash& key) { + std::lock_guard lk(mu_); + auto it = recs_.find(key); + if (it == recs_.end()) return; + Rec& r = it->second; + if (r.tier != KVTier::Device) return; + r.tier = r.host_slot >= 0 ? KVTier::Host : KVTier::Disk; + ++stats_.dropped; + wb_stuck_ = false; /* with no disk tier, a host record is what a capacity drop takes */ + relist(key, r); +} + +bool IdleTiers::snapshot_backed(const BlockHash& key) const { + std::lock_guard lk(mu_); + auto it = recs_.find(key); + if (it == recs_.end()) return false; + const Rec& r = it->second; + return !r.pending && !r.doomed && !r.ck_reading && r.ck_dev >= 0 && + (r.ck_host >= 0 || r.ck_on_disk); +} + +void IdleTiers::snapshot_detached(const BlockHash& key) { + std::lock_guard lk(mu_); + auto it = recs_.find(key); + if (it == recs_.end()) return; + it->second.ck_dev = -1; +} + +/* ------------------------------------------------------------------ the slow half */ + +void IdleTiers::plan(int budget, std::vector* out) { + if (!any_on() || budget <= 0) return; + std::lock_guard lk(mu_); + /* ---- disk copies, in the order the host copies landed ---------------------------------- */ + /* ONE SNAPSHOT BUDGET FOR THE WAY TO DISK, apart from the blocks'. A snapshot is a hundred + * megabytes or more and the disk store copies it twice on the way out (an aligned bounce, then + * the write), so a plan that sent a session's whole retained set at once would hold the IO + * thread for most of a second. A record whose snapshot the budget left behind still sends its + * blocks, and goes to the back of the queue for the rest. */ + int ck_disk_budget = 2; + int n = 0; + std::vector later; + while (disk_on() && !dk_q_.empty() && n < budget) { + const BlockHash key = dk_q_.front(); + dk_q_.pop_front(); + auto ri = recs_.find(key); + if (ri == recs_.end()) continue; + Rec& r = ri->second; + if (!r.disk_q) continue; + r.disk_q = false; + if (!wants_disk(r)) continue; + TierJob j; + j.kind = TierJob::Kind::ToDisk; + j.key = key; + j.bytes = cfg_.entry_bytes; + if (r.host_slot >= 0 && !r.on_disk && r.disk_src < 0) { + j.host_slot = r.host_slot; + r.disk_src = r.host_slot; + } + if (cfg_.ckpt_disk_slots > 0 && r.ck_host >= 0 && !r.ck_on_disk && r.ck_disk_src < 0) { + if (ck_disk_budget > 0) { + j.ck_host = r.ck_host; + j.ck_pos = r.ck_pos; + j.ck_bytes = cfg_.ckpt_bytes; + r.ck_disk_src = r.ck_host; + --ck_disk_budget; + } else { + later.push_back(key); + } + } + if (j.host_slot < 0 && j.ck_host < 0) continue; + out->push_back(std::move(j)); + ++n; + } + for (const BlockHash& k : later) { + auto ri = recs_.find(k); + if (ri != recs_.end()) queue_disk(k, ri->second); + } + + /* ---- capacity, with no disk tier: oldest first ----------------------------------------- */ + /* HOW MANY, AND NOT "UNTIL THERE IS ROOM". A queued drop does not free its slot until the + * engine reports it, so a loop that tested the arena would queue a drop for every entry on the + * list and empty the whole tier to make room for one. The copies refused since the last plan + * say how much room was wanted; this frees exactly that much. With a disk tier the room comes + * from make_room instead, for nothing, once the disk copies above have landed. */ + const int64_t want = starved_; + starved_ = 0; + if (disk_on()) return; + int n_cap = 0; + for (int64_t k = 0; k < want && n_cap < budget; ) { + if (host_lru_.empty()) break; + auto ri = recs_.find(host_lru_.front()); + if (ri == recs_.end()) { host_lru_.pop_front(); continue; } + Rec& r = ri->second; + TierJob j; + j.kind = TierJob::Kind::DropHost; + j.key = ri->first; + j.host_slot = r.host_slot; + j.bytes = cfg_.entry_bytes; + j.ck_host = r.ck_host; + unlist(r); + r.pending = true; + out->push_back(std::move(j)); + ++k; + ++n_cap; + } +} + +bool IdleTiers::plan_promote(const BlockHash& key, TierJob* out) { + std::lock_guard lk(mu_); + auto it = recs_.find(key); + if (it == recs_.end()) return false; + Rec& r = it->second; + if (r.pending || r.doomed || r.tier != KVTier::Host) return false; + + *out = TierJob{}; + out->kind = TierJob::Kind::ToDevice; + out->key = key; + out->host_slot = r.host_slot; + out->bytes = cfg_.entry_bytes; + /* THE STATE COMES BACK WITH THE BLOCKS OR THE PROMOTION IS HALF A PROMOTION. `ck_dev` is an + * output: the engine allocates the device slot, because only it holds a KVManager, and fills + * it before this record is told the move succeeded. A snapshot still in its device slot needs + * nothing -- the cache's index entry for it was never detached. */ + out->ck_dev = -1; + out->ck_host = r.ck_host; + out->ck_pos = r.ck_pos; + out->ck_want = r.ck_dev < 0 && (r.ck_host >= 0 || r.ck_on_disk); + out->ck_bytes = cfg_.ckpt_bytes; + if (r.fetched_ns) ++stats_.disk_hits; else ++stats_.host_hits; + unlist(r); + r.pending = true; + return true; +} + +bool IdleTiers::plan_fetch(const std::vector& chain, std::vector* out, + uint64_t now_ns) { + if (!disk_on() || chain.empty()) return false; + std::lock_guard lk(mu_); + bool wait = false; + std::vector recs(chain.size(), nullptr); + std::vector need; /* chain positions whose blocks are only on disk */ + size_t deep = chain.size(); /* the deepest record a restore wants a snapshot for */ + for (size_t i = 0; i < chain.size(); ++i) { + auto it = recs_.find(chain[i]); + if (it == recs_.end()) continue; + Rec& r = it->second; + if (r.fetching) { wait = true; continue; } + if (r.pending || r.doomed || r.tier == KVTier::Device) continue; + recs[i] = &r; + if (r.tier == KVTier::Disk) need.push_back(i); + if (r.ck_dev < 0 && (r.ck_host >= 0 || r.ck_on_disk)) deep = i; + } + const bool ck_read = deep < chain.size() && recs[deep]->ck_host < 0 && + cfg_.ckpt_disk_slots > 0 && ck_arena_.enabled(); + if (need.empty() && !ck_read) return wait; + + /* THE ROOM, OUT OF EVERYTHING BUT THIS CHAIN. What the disk also holds goes for nothing + * (make_room); the chain's own host copies are what the restore is about to read, and giving + * one up to read another would only move the gap. */ + for (Rec* r : recs) if (r) r->keep = true; + std::vector slots; + if (!need.empty()) { + const int64_t want = (int64_t)need.size(); + if (want > arena_.free_slots()) make_room_locked(want - arena_.free_slots()); + slots.reserve((size_t)want); + while ((int64_t)slots.size() < want) { + int32_t got = 0; + const int32_t s = arena_.alloc_run((int32_t)(want - (int64_t)slots.size()), &got); + if (s < 0) break; + for (int32_t k = 0; k < got; ++k) slots.push_back(s + k); + } + } + int32_t ck_slot = -1; + if (ck_read) { + ck_slot = ck_arena_.alloc(); + if (ck_slot < 0) ck_slot = evict_snapshot_slot(/*lossless=*/true); + } + for (Rec* r : recs) if (r) r->keep = false; + + /* IN CHAIN ORDER, AND CUT WHERE THE SLOTS RAN OUT: a hit needs a contiguous prefix, so an entry + * read past a gap would be read for nothing. */ + const size_t first = out->size(); + for (size_t k = 0; k < slots.size(); ++k) { + TierJob j; + j.kind = TierJob::Kind::ToHost; + j.key = chain[need[k]]; + j.host_slot = slots[k]; + j.bytes = cfg_.entry_bytes; + out->push_back(std::move(j)); + } + if (ck_slot >= 0) { + /* Only a snapshot the restore will reach: every disk entry at or before it has a slot. */ + const bool reached = slots.size() == need.size() || need[slots.size()] > deep; + if (!reached) { + ck_arena_.free(ck_slot); + } else { + TierJob* j = nullptr; + for (size_t k = first; k < out->size(); ++k) + if ((*out)[k].key == chain[deep]) { j = &(*out)[k]; break; } + if (!j) { + out->push_back(TierJob{}); + j = &out->back(); + j->kind = TierJob::Kind::ToHost; + j->key = chain[deep]; + j->bytes = cfg_.entry_bytes; + } + j->ck_host = ck_slot; + j->ck_pos = recs[deep]->ck_pos; + j->ck_bytes = cfg_.ckpt_bytes; + } + } + for (size_t k = first; k < out->size(); ++k) { + Rec& r = recs_[(*out)[k].key]; + unlist(r); + r.pending = true; + r.fetching = true; + r.used_ns = now_ns; + } + return wait || out->size() > first; +} + +void IdleTiers::report(const TierJob& job, bool ok, uint64_t now_ns) { + std::lock_guard lk(mu_); + auto it = recs_.find(job.key); + + /* A DISK WRITE IS NOT A PENDING JOB, so it is settled before anything below touches the + * record's pending state -- which may belong to a restore running beside it. The slots it + * read are the record's, unless the record gave them up (or went) while the write was out: + * then the write's report is what frees them. */ + if (job.kind == TierJob::Kind::ToDisk) { + if (!ok) ++stats_.failures; + Rec* r = it == recs_.end() ? nullptr : &it->second; + if (job.host_slot >= 0) { + if (r && r->disk_src == job.host_slot) r->disk_src = -1; + if (!r || r->host_slot != job.host_slot) give_slot(job.host_slot); + else if (ok) { set_on_disk(*r, true); ++stats_.to_disk; } + } + if (job.ck_host >= 0) { + if (r && r->ck_disk_src == job.ck_host) r->ck_disk_src = -1; + if (!r || r->ck_host != job.ck_host) ck_arena_.free(job.ck_host); + else if (ok && job.ck_ok) { r->ck_on_disk = true; ++stats_.ck_to_disk; } + } + /* A write that failed is not tried again: a store that refused it once will refuse the + * next, and the entry stays host-only, which is what it was before. */ + return; + } + + if (it == recs_.end()) { + /* Nothing names the slots a copy was handed but the job itself. */ + if (job.kind == TierJob::Kind::WriteBack) { + give_slot(job.host_slot); + ck_arena_.free(job.ck_host); + } + return; + } + Rec& r = it->second; + r.pending = false; + r.fetching = false; + const bool was_reading = r.ck_reading; + r.ck_reading = false; + /* A promotion the chain was cut before, or a read that never ran, is not a failure: nothing + * was tried. */ + const bool may_skip = job.kind == TierJob::Kind::ToDevice || job.kind == TierJob::Kind::ToHost; + if (!ok && (!may_skip || job.started)) ++stats_.failures; + + /* A device slot the cache let go of while this copy read it is free to go now. */ + if (was_reading && r.ck_free_after >= 0) { + ck_frees_.push_back(r.ck_free_after); + r.ck_free_after = -1; + } + + /* A record that was forgotten mid-transfer is finished off here and nowhere else. Doing it at + * the top, before the per-kind handling, means no branch below has to remember to check. */ + if (r.doomed) { + /* THE JOB'S SLOTS AND THE RECORD'S ARE NOT THE SAME SLOTS on every path. A copy's host + * slots were the job's until it reported, and a promotion out of disk ran through a join + * slot the record never owned; freeing only the record's would leak those, and freeing + * the job's as well where they ARE the record's would return one slot twice. */ + if (job.host_slot >= 0 && job.host_slot != r.host_slot) give_slot(job.host_slot); + if (job.ck_host >= 0 && job.ck_host != r.ck_host) ck_arena_.free(job.ck_host); + release_storage(job.key, r); + recs_.erase(it); + return; + } + + switch (job.kind) { + case TierJob::Kind::WriteBack: { + if (job.host_slot >= 0) { + if (ok && r.tier == KVTier::Device && r.host_slot < 0) { + r.host_slot = job.host_slot; + ++stats_.to_host; + } else { + give_slot(job.host_slot); + } + } + if (job.ck_host >= 0) { + /* THE SNAPSHOT IS KEPT ONLY IF IT IS STILL THE ONE THAT WAS COPIED. A new commit + * at this key, or a release by the cache, moved the record's device slot while the + * copy ran, and the bytes that landed describe a state nobody holds any more. */ + if (ok && job.ck_ok && r.ck_dev == job.ck_dev && r.ck_host < 0) { + r.ck_host = job.ck_host; + ++stats_.ck_to_host; + } else { + ck_arena_.free(job.ck_host); + } + } + relist(job.key, r); + /* Clean now: the cache is asked whether the VRAM copy can go. */ + if (r.tier == KVTier::Device && r.host_slot >= 0) queue_clean(job.key, r); + /* A copy that failed, or a snapshot the budget left behind, is tried again. */ + queue_copy(job.key, r); + /* And what landed goes on to disk. */ + queue_disk(job.key, r); + return; + } + + case TierJob::Kind::ToDevice: + if (ok) { + r.tier = KVTier::Device; + r.blocks = job.blocks; + /* THE HOST COPY IS KEPT, which is what makes the entry clean the moment it lands: + * its VRAM copy can go again at no cost, and the next copy this conversation needs + * is only of the tokens its next turn adds. A disk entry keeps the slot it was + * read into for the same reason -- it holds exactly the entry's bytes -- and keeps + * its disk copy, which is what lets that slot go again for nothing. */ + r.host_slot = job.host_slot; + /* THE CLOCK RESTARTS: the entry came back because a request is about to hit it. */ + if (now_ns) r.used_ns = now_ns; + r.fetched_ns = 0; + if (job.ck_dev >= 0) { + r.ck_dev = job.ck_dev; + r.ck_host = job.ck_host; + ++stats_.ck_promoted; + } else if (job.ck_want && job.ck_host >= 0 && job.ck_ok) { + /* THE BLOCKS CAME BACK AND THE STATE DID NOT -- no device slot was free for it. + * This turn replays its linear layers from an older checkpoint or from zero, + * but the host copy is intact and is KEPT: the cache's entry for it stays + * detached, and the next time the blocks leave VRAM and come back the snapshot + * comes with them. Dropping it here would make one full slot pool cost the + * session its state for good. */ + r.ck_host = job.ck_host; + } else if (job.ck_want && job.ck_ok && r.ck_on_disk) { + /* No host slot to read the state through, and every one the arena holds is + * some other session's only copy. It stays on disk, reachable next time. */ + } else if (job.ck_want) { + /* The host copy itself could not be read -- from disk, or it was never there. + * There is nothing left to offer and the cache has to hear so. */ + if (job.ck_host >= 0 && job.ck_host != r.ck_host) ck_arena_.free(job.ck_host); + free_ck_host(r); + r.ck_on_disk = false; + ++stats_.ck_drops; + if (on_ck_drop_) on_ck_drop_(job.key); + } + ++stats_.promoted; + queue_clean(job.key, r); + queue_disk(job.key, r); + return; + } + if (!job.started) { + /* NEVER STARTED: the reservation ran out before this entry, and nothing about it + * was touched. It stays exactly where it was. */ + relist(job.key, r); + return; + } + /* A FAILED PROMOTION DROPS THE ENTRY, AND THE CACHE MUST HEAR ABOUT IT. Every other + * failure here can leave the record where it was, because nothing was consumed. This + * one cannot: the scatter may have written some layers and not others, so the blocks + * hold a mixture and the cached tensors are no longer a function of the tokens. A miss + * is always safe and this is the only way to guarantee one -- but the prefix cache + * still holds an entry naming blocks that are not ours any more, and left alone it + * would serve them. */ + if (job.host_slot >= 0 && job.host_slot != r.host_slot) give_slot(job.host_slot); + if (job.ck_host >= 0 && job.ck_host != r.ck_host) ck_arena_.free(job.ck_host); + { + const bool had_ck = r.ck_on_disk || r.ck_host >= 0 || job.ck_want; + free_host(r); + set_on_disk(r, false); + free_ck_host(r); + recs_.erase(it); + if (had_ck) { ++stats_.ck_drops; if (on_ck_drop_) on_ck_drop_(job.key); } + } + if (on_drop_) on_drop_(job.key); + return; + + case TierJob::Kind::DropHost: + give_slot(job.host_slot); + ++stats_.host_drops; + if (job.ck_host >= 0) { ck_arena_.free(job.ck_host); ++stats_.ck_drops; } + recs_.erase(it); + if (on_drop_) on_drop_(job.key); + return; + + case TierJob::Kind::ToHost: { + if (!job.started) { + /* NEVER READ: the slots go back and the record is where it was, on disk. */ + give_slot(job.host_slot); + if (job.ck_host >= 0) ck_arena_.free(job.ck_host); + relist(job.key, r); + return; + } + if (!ok) { + /* THE STORE NO LONGER HOLDS WHAT THE RECORD SAYS IT DOES -- its own eviction does + * not tell the tiers, and a slot that fails its verify is dropped by the read. The + * record claims bytes nobody has, so it goes, and the cache has to hear so. */ + give_slot(job.host_slot); + if (job.ck_host >= 0) ck_arena_.free(job.ck_host); + const bool had_ck = r.ck_dev < 0 && (r.ck_on_disk || r.ck_host >= 0); + free_host(r); + set_on_disk(r, false); + free_ck_host(r); + recs_.erase(it); + if (had_ck) { ++stats_.ck_drops; if (on_ck_drop_) on_ck_drop_(job.key); } + if (on_drop_) on_drop_(job.key); + return; + } + if (job.host_slot >= 0) { + r.host_slot = job.host_slot; + r.tier = KVTier::Host; + ++stats_.fetched; + } + if (job.ck_host >= 0) { + if (job.ck_ok && r.ck_host < 0 && r.ck_dev < 0) { + r.ck_host = job.ck_host; + ++stats_.ck_fetched; + } else { + ck_arena_.free(job.ck_host); + if (!job.ck_ok && r.ck_dev < 0 && r.ck_host < 0 && r.ck_on_disk) { + /* The snapshot store lost it; the blocks are still good. */ + r.ck_on_disk = false; + ++stats_.ck_drops; + if (on_ck_drop_) on_ck_drop_(job.key); + } + } + } + r.fetched_ns = now_ns ? now_ns : rad_mono_ns(); + relist(job.key, r); + return; + } + + case TierJob::Kind::ToDisk: + return; /* settled above */ + } +} + + +/* ------------------------------------------------------------------ the session view */ + +/* A PREFIX RELATION IS WHAT MAKES TWO CHAINS THE SAME CONVERSATION. The blocks are content + * addressed, so turn N's chain is byte for byte turn N-1's with more on the end; anything that + * diverges anywhere is a different transcript from that point on, however much of a system prompt + * it shares. */ +static bool chain_extends(const std::vector& shorter, + const std::vector& longer) { + if (shorter.size() > longer.size()) return false; + for (size_t i = 0; i < shorter.size(); ++i) if (shorter[i] != longer[i]) return false; + return true; +} + +void IdleTiers::note_session(uint64_t id, const std::vector& chain, int64_t n_tokens, + uint64_t now_ns) { + if (chain.empty()) return; + std::lock_guard lk(mu_); + + /* A SESSION IS A LEAF OF THE PREFIX TRIE, and that is what decides every case here. The turns + * of one conversation arrive under different ids -- the id is the request's, and a + * conversation is a new request every turn -- so without this the table grows a row a turn, + * each holding its own copy of a chain that is a prefix of the next one's and none of them + * ever revisited. Candidates are the sessions sharing this root, which is a handful at most. + * + * A CHAIN THIS ONE EXTENDS HAS STOPPED BEING A LEAF, so it is absorbed: its blocks are the + * first blocks of this one, byte for byte, because the chain is content addressed. + * + * A CHAIN THAT EXTENDS THIS ONE MEANS THIS ONE IS NOT A LEAF EITHER. That happens when a + * preempted request re-prefills and republishes SHORTER than the conversation it belongs to; + * recording it would shrink the row to less than the pool is holding, and there may be + * several conversations below it -- two clients past the same system prompt -- with nothing + * to say which of them republished. So the most recent of them is touched and no row is + * added, which is the one answer that is wrong about nothing. */ + uint64_t first_seen = 0; + bool absorbed = false; + std::vector& at_root = roots_[chain[0]]; + for (size_t i = 0; i < at_root.size();) { + auto it = sessions_.find(at_root[i]); + if (it == sessions_.end()) { at_root.erase(at_root.begin() + (long)i); continue; } + if (!chain_extends(it->second.chain, chain)) { ++i; continue; } + if (first_seen == 0 || it->second.first_seen_ns < first_seen) + first_seen = it->second.first_seen_ns; + sessions_.erase(it); + at_root.erase(at_root.begin() + (long)i); + absorbed = true; + } + + if (!absorbed) { + Session* newest = nullptr; + for (uint64_t sid : at_root) { + auto it = sessions_.find(sid); + if (it == sessions_.end() || !chain_extends(chain, it->second.chain)) continue; + if (!newest || it->second.last_used_ns > newest->last_used_ns) newest = &it->second; + } + if (newest) { newest->last_used_ns = now_ns; return; } + } + + Session& s = sessions_[id]; + s.last_used_ns = now_ns; + s.n_tokens = n_tokens; + s.first_seen_ns = first_seen ? first_seen : now_ns; + s.chain = chain; + at_root.push_back(id); +} + +void IdleTiers::drop_session(uint64_t id) { + auto it = sessions_.find(id); + if (it == sessions_.end()) return; + if (!it->second.chain.empty()) { + auto ri = roots_.find(it->second.chain[0]); + if (ri != roots_.end()) { + std::vector& v = ri->second; + v.erase(std::remove(v.begin(), v.end(), id), v.end()); + if (v.empty()) roots_.erase(ri); + } + } + sessions_.erase(it); +} + +void IdleTiers::forget_session(uint64_t id) { + std::lock_guard lk(mu_); + drop_session(id); +} + +std::vector IdleTiers::sessions(Occupancy* occ) const { + /* The view's hold on the lock, a slice at a time (YieldingMutex). */ + struct Slice { + YieldingMutex& m; + explicit Slice(YieldingMutex& mu) : m(mu) { m.lock_after_others(); } + ~Slice() { m.unlock(); } + }; + /* Records a slice visits: a few microseconds of hash lookups, the most an engine-side taker + * arriving mid-slice waits. */ + constexpr size_t kSliceRecords = 64; + + std::vector out; + { + Slice lk(mu_); + out.reserve(sessions_.size()); + for (const auto& kv : sessions_) { + SessionInfo si; + si.id = kv.first; + si.model = model_; + si.n_tokens = kv.second.n_tokens; + si.first_seen_ns = kv.second.first_seen_ns; + si.last_used_ns = kv.second.last_used_ns; + si.bytes = (int64_t)kv.second.chain.size() * cfg_.entry_bytes; + out.push_back(std::move(si)); + } + } + /* SNAPSHOTS ON DISK, each once. Nothing keeps a running count of them -- a host snapshot has + * an arena slot to count and a disk one has only a flag on its record -- and this walk visits + * every record a stored conversation reaches, so it counts them here. They are sparse, one + * per checkpoint interval, so the set stays small beside the walk that fills it. */ + std::unordered_set disk_snaps; + size_t kept = 0; + for (size_t k = 0; k < out.size(); ++k) { + SessionInfo& si = out[k]; + /* The histogram is computed here and stored nowhere. A session's blocks move one tier at + * a time under a bounded plan, so a second copy of this would be stale between the pass + * that moves the first block and the pass that moves the last -- which is exactly the + * window an operator is looking at the page during. The session is found again at every + * slice: between slices it may have been absorbed into a longer one or dropped, and a + * row that is gone is left out. */ + bool gone = false; + for (size_t at = 0;;) { + Slice lk(mu_); + const auto it = sessions_.find(si.id); + if (it == sessions_.end()) { gone = true; break; } + const std::vector& chain = it->second.chain; + const size_t end = std::min(chain.size(), at + kSliceRecords); + for (; at < end; ++at) { + const BlockHash& h = chain[at]; + auto ri = recs_.find(h); + if (ri == recs_.end()) { ++si.on_device; continue; } + const Rec& rr = ri->second; + if (rr.pending) si.moving = true; + switch (rr.tier) { + case KVTier::Device: ++si.on_device; break; + case KVTier::Host: ++si.on_host; break; + case KVTier::Disk: ++si.on_disk; break; + } + /* THE LINEAR HALF, COUNTED WHERE ITS BYTES ACTUALLY ARE and not where the blocks + * are. They normally agree, because a snapshot moves with the record it belongs + * to; when they do not -- a snapshot that could not be placed and stayed on the + * device -- the page says so rather than averaging the two into something neither + * is. */ + const bool ck = rr.ck_dev >= 0 || rr.ck_host >= 0 || rr.ck_on_disk; + if (rr.ck_dev >= 0) { ++si.snapshots; ++si.snap_device; } + else if (rr.ck_host >= 0) { ++si.snapshots; ++si.snap_host; } + else if (rr.ck_on_disk) { ++si.snapshots; ++si.snap_disk; } + if (rr.ck_on_disk && occ) disk_snaps.insert(h); + if (ck && rr.ck_pos > si.resume_tokens) si.resume_tokens = rr.ck_pos; + } + if (at >= chain.size()) break; + } + if (gone) continue; + si.snap_bytes = si.snapshots * cfg_.ckpt_bytes; + if (kept != k) out[kept] = std::move(si); + ++kept; + } + out.resize(kept); + std::sort(out.begin(), out.end(), + [](const SessionInfo& a, const SessionInfo& b) { + return a.last_used_ns > b.last_used_ns; + }); + if (occ) { + Slice lk(mu_); + occ->host_bytes = arena_.used_slots() * cfg_.entry_bytes + + ck_arena_.used_slots() * cfg_.ckpt_bytes; + occ->disk_bytes = stats_.disk_bytes + (int64_t)disk_snaps.size() * cfg_.ckpt_bytes; + /* The cap the operator gave, which the snapshot store was carved out of -- the same scope + * as `host_bytes` above, which counts both arenas. */ + occ->host_cap_bytes = host_on() ? cfg_.host_cap_bytes + ck_arena_.cap_bytes() : 0; + occ->disk_cap_bytes = disk_on() ? cfg_.disk_cap_bytes : 0; + } + return out; +} +} /* namespace rad */ diff --git a/core/mem/kvtier.h b/core/mem/kvtier.h new file mode 100644 index 00000000..bcb7194b --- /dev/null +++ b/core/mem/kvtier.h @@ -0,0 +1,691 @@ +/* kvtier.h -- where a finished conversation's KV is kept once VRAM has a better use for it + * (spec §7.3). + * + * The prefix cache holds a KV reference on every block it indexes, so a finished turn's context + * survives into the next one. That is the whole value of it, and it is also the whole cost: those + * blocks are the most valuable thing in the pool while the session is live and the least valuable + * thing in it once the session stops -- and on a card whose experts do not fit, VRAM holding an + * idle conversation is VRAM every decode step pays for across the link. + * + * ============================== COPY ON IDLE, FREE ON DEMAND ==================================== + * + * An entry is COPIED to host memory as soon as the request that published it finishes, and its + * VRAM copy is kept. From then on the entry is CLEAN: the pool and the host hold the same bytes, + * so giving the VRAM copy up costs nothing at all -- no transfer, no wait, only the cache's + * reference -- and it is given up the moment something wants the memory: the expert slab's loan, + * or an allocation the free list cannot serve. A conversation that comes back before either + * happens resumes from VRAM for free; one that comes back after is restored from its host copy, + * and KEEPS that copy, so the turn after it copies only the tokens that turn added. + * + * published --(copy, at once)--> clean on device --(memory wanted)--> host + * ^ | + * +------------(a hit restores)------+ + * host copy --(copy to disk, at once)--> clean on host --(a slot wanted)--> disk + * + * THE DISK TIER IS A COPY TOO, by the same argument one level down. Every host copy is written to + * the disk store in the background as soon as it lands, and keeps its host slot. Once the write + * has landed the host slot is as free to give up as a clean entry's VRAM: when a copy or a + * restore needs a slot and the arena is full, the oldest entries the disk also holds give theirs + * up, which is bookkeeping and nothing else. Moving an entry to disk only when its slot is wanted + * would put a write on the path of whatever wanted it -- a restore out of disk needs a host slot to + * read through, and an arena full of host-only entries has no slot to give it at all. + * + * THERE IS NO IDLE THRESHOLD ON THE WAY OUT OF VRAM, and that is the point of the design rather + * than an omission. A threshold is a guess at when an entry stops being worth its VRAM, made in + * seconds by an operator; a clean entry answers the question itself, because keeping it costs + * nothing until the memory is wanted and releasing it costs nothing once it is. + * + * WHY MOVING BEATS DROPPING, stated once so the costs can be argued about in the right units: + * dropping a 200K-token prefix costs a re-prefill, which is minutes. Restoring it costs a copy + * over PCIe, which is a fraction of a second. The two are not the same order of magnitude. + * + * ============================== THIS OBJECT MOVES NO BYTES ====================================== + * + * It decides WHAT should move and hands the work out as a list of TierJob. The engine executes + * them on its transfer stream and reports back. That split is not decoration: `KVManager` already + * works this way (BlockCopy, take_pending_copies) for the same reason -- core/mem has no stream, + * and a synchronisation on the step path is what this design spends itself avoiding (spec §5.4). + * A second mechanism for moving KV bytes would be a second place to get the pool's addressing + * wrong. + * + * ============================== THE ADDRESSING, WHICH IS THE TRAP ============================== + * + * THE POOL IS LAYER-MAJOR (core/mem/kv.h). Layer i of a paged group owns + * `[base + i*layer_stride, + layer_stride)`, and inside that a block is + * `block_index * layer_bytes_per_block()`. A logical block is therefore NOT a contiguous extent: + * it is `n_layers` fragments, one per layer, and on a production model a fragment is a few hundred + * bytes. `base + block * bytes_per_block` addresses something else entirely -- roughly `n_layers` + * consecutive blocks OF LAYER ZERO -- and a tier built on it moves other sequences' data and + * restores a jumble. Corrupt KV does not read as babble; it reads as fluent, deterministic, + * plausible, wrong text, and nothing short of a byte comparison against a known-good run finds it. + * + * So the unit of transfer here is not a block. It is A LAYER'S WORTH OF MANY BLOCKS, which is the + * shape the pool is already in: within one layer the group's blocks are dense rows of + * `layer_bytes_per_block()` each, so packing an arbitrary set of them is exactly `gather_rows` + * and restoring them is exactly `scatter_rows`. One launch per (group, layer) per batch, however + * many entries the batch holds. + * + * ============================== ONE RECORD, ONE TIER, ONE LIST ================================== + * + * An entry that can live in either of two tiers must not be on BOTH tiers' LRU lists: each tier's + * eviction path then invalidates references the other holds, and every such pair is a + * use-after-free. The rule here is that a key has exactly one Rec, + * a Rec is in exactly one tier, and a Rec is in at most that tier's list. A CLEAN device record + * is on no list: the copy it keeps off the card is what lets the VRAM copy go, and the tiers' + * lists are for entries no longer in VRAM. A Rec with a transfer through the pool outstanding is + * `pending` and is in no list either: it cannot be chosen as a victim, cannot be planned again, + * and cannot be erased until the engine reports the job finished or failed. A disk write is not + * such a transfer -- it reads host memory and nothing else -- and holds only the slots it reads. + */ +#pragma once +#include "mem/kv.h" +#include "mem/prefix.h" +#include "rad_core.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rad { + +class SSDTier; + +enum class KVTier : uint8_t { Device = 0, Host = 1, Disk = 2 }; +const char* kv_tier_name(KVTier t); + +/* What the engine is being asked to do. One job is one entry moving one step. The block ids are + * carried in the job rather than looked up when it runs, because the whole point of `pending` is + * that nothing may touch the record in between. */ +struct TierJob { + enum class Kind : uint8_t { + WriteBack, /* gather_rows out of the pool into a host slot; the entry stays in VRAM */ + ToDisk, /* a host slot written to the disk store; the host copy is kept */ + ToDevice, /* allocate blocks, scatter_rows in; the host copy is kept */ + DropHost, /* no disk tier and the arena is full: this record's bytes go */ + ToHost, /* the disk store read into a host slot, ahead of the restore that wants it */ + }; + Kind kind = Kind::WriteBack; + BlockHash key; + /* Per cached group, in PrefixCache::cached_groups() order. For a write-back these are the + * blocks to read -- EMPTY when only the snapshot is being copied, because the blocks already + * have their host copy; for a promotion they are filled in by the engine with the blocks it + * allocated. */ + std::vector blocks; + int32_t host_slot = -1; + int64_t bytes = 0; + + /* ---- the linear half, on a hybrid model ---- + * + * A session's recurrent state lives in a CHECKPOINT SLOT rather than in blocks: one contiguous + * KVManager::checkpoint_bytes() extent, which is why nothing here needs a gather. The snapshot + * belonging to this entry moves with it, so a restored hybrid session gets its attention hit + * AND its state back, instead of an attention hit and a full linear replay from token zero. + * + * `ck_dev` is the device slot: where the bytes are read from on the way out, and where the + * engine put them on the way in -- it is an OUTPUT of a promotion, exactly as `blocks` is. */ + int32_t ck_dev = -1; + int32_t ck_host = -1; /* a slot in the snapshot arena, not the block arena */ + int64_t ck_pos = 0; /* the token position, which the disk store verifies on the way back */ + bool ck_want = false; /* a promotion should bring the snapshot back too */ + /* DID THE SNAPSHOT HALF SUCCEED. Separate from the job's own result because the two halves + * fail for different reasons and are repaired differently: a snapshot that could not be copied + * has not been damaged, it is still sitting correct and committed in its device slot and a + * later pass reaches it again for free, so the blocks may as well carry on without it. + * + * A snapshot that is DROPPED is another matter, and it is worth being exact about the cost + * because it is not what it looks like. On this build the scheduler clamps a hybrid session's + * reuse to the last LINEAR CHECKPOINT it can reach, not to the attention hit -- RadBatch + * carries one query length for every KV group, so the linear layers cannot be replayed over a + * longer range than the attention ones (core/sched/scheduler.cpp, admit_one). A session whose + * blocks came back and whose state did not therefore reuses NOTHING. The blocks are not a + * partial win; they are unusable until some checkpoint under them survives. */ + int64_t ck_bytes = 0; + bool ck_ok = true; + /* A PROMOTION THAT WAS NEVER STARTED, as opposed to one that failed part of the way through. + * A restore reserves every block before it moves a byte, and a chain that did not fit is cut + * where the reservation ran out: the entries past that point were not touched, their host + * copies are exactly what they were, and they stay on the host tier. Only an entry whose + * scatter may have run is dropped on failure. A read off disk that never ran -- its batch + * could not be handed to the thread -- is the same: the record stays on disk. */ + bool started = false; +}; + +/* ------------------------------------------------------------------ the host arena */ +/* Pinned, because every byte of it is a PCIe transfer endpoint and a pageable one collapses: the + * driver stages an async copy to pageable memory through its own buffer and, on some paths, + * synchronises. Slot-allocated at one + * fixed size rather than malloc'd per entry: every entry in a given model holds exactly one block + * per cached group, so the size is a property of the geometry and a bitmap is the whole allocator. + * + * RUNS, BECAUSE A TRANSFER IS PER RUN. A 4-token block makes a 200K-token conversation fifty + * thousand entries, and a copy per entry is fifty thousand driver calls on the engine thread -- + * the call rate, not the link, is then what a restore costs. Entries written together are given + * consecutive slots wherever the arena has them, so a batch crosses the link as one strided copy + * a run. */ +class HostArena { +public: + ~HostArena(); + int open(int64_t slot_bytes, int64_t cap_bytes); + void close(); + bool enabled() const { return base_ != nullptr; } + + int64_t slot_bytes() const { return slot_bytes_; } + /* Fixed when the arena is opened. Stored rather than counted from the bitmap, because an + * HTTP thread reads it for the sessions view while the engine thread allocates and frees. */ + int64_t capacity() const { return cap_slots_; } + int64_t used_slots() const { return used_; } + int64_t cap_bytes() const { return slot_bytes_ * capacity(); } + int64_t free_slots() const { return cap_slots_ - used_; } + + /* -1 when the arena is full. The caller evicts and retries; this does not choose victims, + * because the LRU that would choose them lives in IdleTiers and an allocator that reached + * into it would give each record two owners. */ + bool full() const { return used_ >= cap_slots_; } + int32_t alloc(); + /* UP TO `want` CONSECUTIVE SLOTS, the first free run at or after the cursor. `*got` is how + * many; the caller asks again for the rest. -1 when the arena is full. */ + int32_t alloc_run(int32_t want, int32_t* got); + void free(int32_t slot); + void* at(int32_t slot) const; + +private: + bool is_used(int64_t s) const { return (bits_[(size_t)(s >> 6)] >> (s & 63)) & 1ull; } + void* base_ = nullptr; + int64_t slot_bytes_ = 0; + int64_t used_ = 0; + int64_t cap_slots_ = 0; + int64_t cursor_ = 0; + std::vector bits_; +}; + +/* ------------------------------------------------------------------ the policy */ +class IdleTiers { +public: + struct Config { + int64_t host_cap_bytes = 0; /* 0 is off */ + int64_t disk_cap_bytes = 0; + int64_t entry_bytes = 0; /* one entry: sum over cached groups of bytes_per_block */ + /* ---- the linear half ---- + * `ckpt_bytes` is ONE SNAPSHOT, every rank's shard of it, laid out exactly like + * `entry_bytes`. `ckpt_cap_bytes` is carved out of the tier the operator sized rather than + * added to it: a snapshot store is host memory like any other and a tier that quietly + * allocated past its stated cap would be the one thing --prefix-cache-host-mib is for. Zero + * for either means snapshots do not tier, and the blocks still do. */ + int64_t ckpt_bytes = 0; + int64_t ckpt_cap_bytes = 0; /* host; part of host_cap_bytes, not additional to it */ + int64_t ckpt_disk_slots = 0; /* how many the disk store was opened for */ + }; + + int configure(const Config& c, SSDTier* disk); + void close(); + bool host_on() const { return cfg_.host_cap_bytes > 0 && arena_.enabled(); } + bool disk_on() const { return cfg_.disk_cap_bytes > 0 && disk_ != nullptr; } + bool any_on() const { return host_on() || disk_on(); } + std::string report() const; + + /* Called by PrefixCache whenever an entry is inserted. The blocks come with it because a copy + * needs them and the map is the only place they would otherwise be read from -- at which point + * the tiers would hold a second copy of the cache's own bookkeeping and the two could + * disagree. A record with no host copy is queued for one here: publishing is the moment a + * request has stopped writing the entry, which is the moment it can be copied. */ + void note_used(const BlockHash& key, const std::vector& blocks, uint64_t now_ns); + /* THE HIT HALF OF THAT, for a lookup that matched `n` blocks of a chain. Only the idle clock + * moves: a hit carries no new block ids, and it creates no record for an entry the tiers were + * never told about. One lock for the whole chain, since a long prefix is thousands of blocks. */ + void note_hits(const BlockHash* keys, int64_t n, uint64_t now_ns); + /* The entry is gone from the cache for good -- evicted, or its blocks released. Any tier + * storage it held is returned. A record with work outstanding is marked instead of erased and + * is cleaned up when the job reports. */ + void forget(const BlockHash& key); + /* AN OFF-DEVICE ENTRY WAS RECOMPUTED. A request that could not reach the tier copy -- a + * restore that did not fit, a chain past the point a promotion was cut -- computes the same + * tokens again and publishes them, and the cache takes those blocks as the entry's device + * copy. The tier copy goes: two copies of one entry computed by two different batches agree + * only to the rounding the batch shape allows, and a record that called them the same bytes + * would restore the older one over a pool that holds the newer. The record is a fresh device + * record, queued for a copy of its own. */ + void rebound(const BlockHash& key, const std::vector& blocks, uint64_t now_ns); + + /* WHERE IS IT. Device for anything this object has never been told about, which is the right + * answer: an entry the cache holds and the tiers have not touched is in the pool. */ + KVTier tier_of(const BlockHash& key) const; + bool resident_off_device(const BlockHash& key) const; + + /* ---------------- copy on idle ---------------- + * + * The records waiting for a host copy, up to `max_entries`, as WriteBack jobs with their host + * slots already allocated. Oldest first, so a conversation that went idle before another is + * copied before it. A record whose snapshot is still only on the device is included even when + * its blocks already have their copy, with `blocks` empty -- the snapshot is the half a hybrid + * session cannot resume without, and it becomes copyable later than the blocks (a checkpoint + * is committed on its own clock). + * + * Every record named by a returned job is `pending` until report() is called for it. An arena + * too full to take the batch first gives up the host slots of the oldest entries the disk also + * holds (make_room); what is still short stays queued, and with no disk tier the next + * maintenance plan drops that many of the oldest host-only entries. */ + void plan_writeback(int64_t max_entries, std::vector* out); + bool writeback_waiting() const; + /* Has the arena refused a copy since the last maintenance plan? That plan is then due now. */ + bool starved() const; + + /* THE VRAM COPIES THAT CAN GO, as the entries that became clean since the last call. The + * cache decides whether each one actually goes -- a block a running sequence also holds would + * free nothing -- and reports what it did through drop_commit. A key handed out here and not + * dropped is the cache's to ask about again. */ + void take_clean(std::vector* out); + /* Can this entry's blocks leave VRAM for nothing, right now: a copy off the card has landed -- + * in host memory or on disk -- and no job is out on the record. */ + bool droppable(const BlockHash& key) const; + /* The cache released the blocks. The record is now a host record with its copy, on the host + * tier's list like any other -- or a disk record, when its host slot was already given up. + * + * ITS SNAPSHOT STAYS WHERE IT IS. A snapshot's device slot is not memory anything else can + * use -- the expert slab borrows blocks, never checkpoint slots -- so taking it off the device + * along with the blocks would buy nothing and put the session's recurrent state at the mercy + * of a host arena a few snapshots deep, shared by every conversation. The slot goes when the + * checkpoint pool itself needs it (snapshot_backed). */ + void drop_commit(const BlockHash& key); + + /* ---------------- the snapshots' own pressure ---------------- + * + * The checkpoint pool is --checkpoint-slots deep for the whole server, and when it is full the + * cache retires the least recently used snapshot to make room. One whose bytes the tiers also + * hold need not be lost: the cache DETACHES it instead -- the slot goes back, the index entry + * stays, and the next restore of the session brings the state back with the blocks. True when + * this key's device snapshot has a finished copy off the card that nothing is still writing. */ + bool snapshot_backed(const BlockHash& key) const; + /* The cache gave the device slot back; the copy off the card is now the snapshot. */ + void snapshot_detached(const BlockHash& key); + + /* ---------------- the slow half ---------------- + * + * The host copies waiting for their disk copy, in the order they landed, as ToDisk jobs -- + * blocks and snapshot halves together where both are waiting. A ToDisk job does NOT make its + * record pending: it only reads the host slots it names, which a restore may read at the same + * time, and a slot the record gives up while the write is out is freed when the write reports + * rather than under it. With no disk tier, the copies the arena refused since the last plan + * are made room for by dropping that many of the oldest host-only entries. `budget` bounds + * one plan so the IO a pass asks for is bounded too. */ + void plan(int budget, std::vector* out); + /* Is a host copy waiting for its disk copy? The slow half is then due now rather than on its + * once-a-second clock: an entry the disk does not hold yet is one whose host slot cannot be + * given up for nothing. */ + bool disk_waiting() const; + + /* ROOM IN THE ARENA, FOR NOTHING. Up to `n` host slots of entries the disk also holds, given + * up oldest first: host records first -- they become disk records -- and then the host copies + * of clean VRAM entries, which stay clean through their disk copy. Nothing is written; an + * entry whose disk copy has not landed is not a candidate. Returns how many were freed. */ + int64_t make_room(int64_t n); + + /* ---------------- reading a chain back off disk, before its request runs ---------------- + * + * A RESTORE COPIES HOST MEMORY TO THE DEVICE AND NOTHING ELSE. It runs inside the scheduler's + * step, and a disk read there -- thousands of entries for a long conversation -- would hold + * every other request's next token for as long as the reads take. So the disk half of a chain + * is read into host slots on the IO thread first, as ToHost jobs, while the request that wants + * it waits outside admission and everything else keeps running; the restore then finds the + * chain in host memory. + * + * `chain` is every key a prompt's prefix matched, in order. True when the request must wait: + * a read for one of its entries was planned now, into `out`, or is already out. False when + * none of the chain is on disk, or none of what is can be given a slot -- a chain larger than + * the arena comes back as far as the arena holds, and the rest is prefilled. + * + * The chain's deepest snapshot that is only on disk is read with it, into the snapshot arena, + * because that is the state the hit resumes from (TierExec::issue_restore). Every record named + * is `pending` until the read reports, and what a read brought in is not given up to make + * room for anybody else until the request has had the step it needs to claim it. */ + bool plan_fetch(const std::vector& chain, std::vector* out, + uint64_t now_ns); + + /* A promotion, asked for by a lookup that hit off-device. Returns false when the entry is not + * in host memory -- a disk entry is read in by plan_fetch first -- or already has work + * outstanding. */ + bool plan_promote(const BlockHash& key, TierJob* out); + + /* The engine finished (or failed) a job. On failure the record returns to the state it was in + * with its storage intact, EXCEPT for a failed ToDevice that had started, which cannot leave a + * half-scattered pool behind and so drops the entry -- and a disk read that failed is marked + * started for that reason too: the store no longer holds what the record says it does. A + * successful ToDevice restarts the record's clock at `now_ns` when one is given: the promotion + * happened because something is about to use it. */ + void report(const TierJob& job, bool ok, uint64_t now_ns = 0); + + /* WAS THIS KEY FORGOTTEN WHILE ITS JOB WAS OUT -- or is it not known at all. The engine asks + * before acting on a finished job's blocks: an entry the cache evicted mid-transfer had its + * references released by the eviction, and anything done in its name afterwards would be done + * to blocks somebody else now holds. */ + bool doomed(const BlockHash& key) const; + + /* ============================ WHEN THE BYTES ARE GONE, SO IS THE ENTRY ==================== + * + * A record erased while its bytes are OFF-DEVICE -- a capacity drop, or a promotion that + * failed -- leaves the prefix cache holding an entry whose block ids the pool has already + * given to somebody else. `resident_off_device` then answers false, because there is no + * record any more, and the cache would serve those ids as an ordinary hit: one conversation + * gets another's context, as fluent and plausible text. + * + * So the tiers tell the cache, at every site that erases an off-device record, and the cache + * drops the entry WITHOUT releasing blocks -- there are none of its own left to release. */ + void set_drop_sink(std::function f) { on_drop_ = std::move(f); } + + /* ---------------- the linear half of an idle session ---------------- + * + * Told by PrefixCache::commit_checkpoint, for the same reason note_used carries the block ids: + * a copy has to know what to move and the cache's index is the only place it is written down. + * `dev_slot` is a KVManager checkpoint slot and `pos` the token position the disk store + * verifies a read against. + * + * A record may hear this BEFORE it hears note_used -- a checkpoint is committed mid-request + * and the chain is published when the request closes -- so this creates the record if it has + * to. The snapshot is queued for a copy when the record is published, or at once when it + * already was. */ + void note_snapshot(const BlockHash& key, int32_t dev_slot, int64_t pos); + /* The cache is done with the snapshot at `key`: return whatever tier storage holds it. The + * record's BLOCKS are untouched -- the two halves are retired by different policies on + * different clocks, and a snapshot the retention policy drops says nothing about the prefix. + * + * TRUE WHEN A COPY IS STILL READING THE DEVICE SLOT, and then the slot is NOT the caller's to + * free: an asynchronous copy out of a slot the pool has decommitted reads a page that is no + * longer there, which is a device fault rather than a stale byte. The tiers keep the slot and + * hand it back through `take_checkpoint_frees` once the copy has reported. */ + bool release_snapshot(const BlockHash& key); + /* Device checkpoint slots whose release waited on a copy, now safe to free. */ + void take_checkpoint_frees(std::vector* out); + /* Is a copy reading this key's device snapshot right now? A save into that slot would tear it. */ + bool snapshot_reading(const BlockHash& key) const; + /* THE TIERS LOST A SNAPSHOT BUT KEPT THE BLOCKS. The snapshot store is far smaller than the + * block store (a snapshot is thousands of blocks' worth of bytes) so it overflows first and on + * its own, and the cache has to stop offering an index entry whose bytes nobody holds. Wired + * to PrefixCache::drop_snapshot; separate from set_drop_sink because losing half an entry and + * losing all of it are different events with different repairs. */ + void set_snapshot_drop_sink(std::function f) { on_ck_drop_ = std::move(f); } + bool ckpt_on() const { return ck_arena_.enabled(); } + int64_t ckpt_bytes() const { return cfg_.ckpt_bytes; } + HostArena& ckpt_arena() { return ck_arena_; } + const HostArena& ckpt_arena() const { return ck_arena_; } + int64_t ckpt_disk_slots() const { return cfg_.ckpt_disk_slots; } + + /* ---------------- the session view ---------------- + * + * WHAT A SESSION IS HERE, because it is not what the cache is keyed by. The cache is keyed by + * BLOCK, and a 200K-token conversation is twelve thousand of them -- an enumeration nobody can + * read and not what anyone means by "session". A session is one PUBLISHED CHAIN: the blocks + * one request inserted, named by its tip. That is exactly the leaf of the prefix trie, so two + * conversations sharing a system prompt are two sessions and the shared blocks belong to both. + * + * THE SIZES THEREFORE OVERLAP AND THE TOTAL IS NOT A SUM. Sharing is the point of the cache; + * a view that hid it would make a server look like it was storing several times what it is. + * Anything reporting these numbers says so. + * + * The model name is carried rather than looked up because the disk tier outlives the process: + * a store written by one container and read back under another is refused by fingerprint, and + * the name is what turns that refusal into something an operator can act on. */ + struct SessionInfo { + uint64_t id = 0; + std::string model; + int64_t n_tokens = 0; + int64_t bytes = 0; + uint64_t first_seen_ns = 0; + uint64_t last_used_ns = 0; + int64_t on_device = 0, on_host = 0, on_disk = 0; /* blocks, by tier */ + /* LINEAR STATE, on a hybrid model. Counted separately from blocks because it is a + * different resource with a different scarcity: a snapshot is thousands of blocks' worth + * of bytes and there are only --checkpoint-slots of them on the device. A session showing + * blocks on disk and no snapshot anywhere is one that will come back and re-run every + * recurrent layer over its whole transcript, which is not what "restored" should mean. */ + int64_t snapshots = 0; /* this session holds, any tier */ + int64_t snap_device = 0, snap_host = 0, snap_disk = 0; + int64_t snap_bytes = 0; + /* WHAT A RETURN REUSES: the token position of the deepest snapshot on the chain, in any + * tier. On a hybrid model the scheduler clamps a hit to the last linear checkpoint it can + * reach, so this -- not n_tokens and not the blocks -- is the prefix the next turn skips, + * and n_tokens minus it is what that turn prefills. Zero with no snapshot anywhere. */ + int64_t resume_tokens = 0; + bool moving = false; /* a job is outstanding */ + }; + /* WHAT THE TIERS OFF THE CARD ARE HOLDING, blocks and snapshots together, each counted once. + * The per-session figures cannot be summed into this: sessions sharing a prefix share its + * blocks and its snapshots. Caps are what the operator configured, snapshots included. A + * clean entry's host copy is counted: it occupies the arena whether or not the VRAM copy has + * gone yet. */ + struct Occupancy { + int64_t host_bytes = 0, disk_bytes = 0; + int64_t host_cap_bytes = 0, disk_cap_bytes = 0; + }; + /* Publish one request's chain. Called from PrefixCache::insert, which is the only place that + * knows a chain was completed rather than merely touched. + * + * KEPT WHETHER OR NOT ANY TIER IS ON, because what it records is not a tiering fact. A server + * with no --prefix-cache-host-mib still stores conversations -- it stores them all in VRAM, which + * is the case the table most wants to show -- and gating the record on the mover would make + * the view report an empty server to every operator who has not opted into tiering. + * + * ONE CONVERSATION IS ONE ROW, and the rule that makes it one is the trie: a session is a + * LEAF, so a chain that a later turn extends has stopped being one and is absorbed into it. + * Each turn publishes the chain it grew under its own request id, so without that the table + * is a row per turn -- a table nobody can read, holding a copy of every prefix of the + * transcript for as long as the newest. */ + void note_session(uint64_t id, const std::vector& chain, int64_t n_tokens, + uint64_t now_ns); + void set_model(const std::string& m) { model_ = m; } + /* Newest activity first. Recomputes each session's tier histogram from the records, so it is + * a view and never a second copy of the truth. The walk takes the lock in slices and lets + * every other taker go first between them (YieldingMutex), so rows read at different slices + * may describe moments a few microseconds apart. */ + std::vector sessions(Occupancy* occ = nullptr) const; + void forget_session(uint64_t id); + + struct Stats { + /* `to_host` is entries COPIED to host memory; `dropped` is entries whose VRAM copy was + * then given up. They are different events: a copy is link traffic and a drop is VRAM + * handed to something else, and a conversation that returns before anything wants its + * VRAM is copied and never dropped. */ + int64_t to_host = 0, dropped = 0, to_disk = 0, promoted = 0; + /* `host_freed` is host slots given up because the disk holds the entry -- the host tier's + * counterpart of `dropped`; `host_drops` is entries lost with no disk tier to hold them. */ + int64_t host_freed = 0, host_drops = 0, failures = 0; + int64_t host_bytes = 0, disk_bytes = 0; + int64_t host_hits = 0, disk_hits = 0; + /* Entries and snapshots read off disk into host memory ahead of a restore. */ + int64_t fetched = 0, ck_fetched = 0; + /* SNAPSHOTS MOVED, counted apart from blocks. A hybrid session can move its whole chain + * off the device and still replay every linear layer from zero on the way back, and no + * block counter can tell the two apart -- these are the numbers that can. */ + int64_t ck_to_host = 0, ck_to_disk = 0, ck_promoted = 0, ck_drops = 0, ck_starved = 0; + }; + /* A copy, taken under the lock: an HTTP thread reads these while the engine thread moves + * records. */ + Stats stats() const; + HostArena& arena() { return arena_; } + /* The size of ONE SLOT, which under tensor parallelism holds every rank's shard. */ + int64_t entry_bytes() const { return cfg_.entry_bytes; } + +private: + struct Rec { + KVTier tier = KVTier::Device; + uint64_t used_ns = 0; + /* THE HOST COPY. On a device record it is a copy that makes the record clean; on a host + * record it is where the bytes are read from. -1 on a disk record always. */ + int32_t host_slot = -1; + /* THE DISK STORE HOLDS THESE BYTES, written from the host copy. What makes the host slot + * free to give up, and a device record with no host copy clean. The store evicts on its own + * and does not say so; a read that finds the entry gone drops it (report). */ + bool on_disk = false; + /* The host slot a disk write is reading right now, -1 when none. A slot given up while + * this names it is freed when the write reports, not under it. */ + int32_t disk_src = -1; + bool disk_q = false; /* in dk_q_: waiting for a disk copy */ + bool pending = false; + bool fetching = false; /* the pending job is a read off disk (plan_fetch) */ + bool doomed = false; /* forget() arrived while pending */ + bool queued = false; /* in wb_q_: waiting for a copy */ + bool clean_q = false; /* in clean_q_: a drop the cache has not been asked about */ + bool listed = false; /* on host_lru_ or disk_lru_; `it` is valid */ + std::vector blocks; + /* ---- the linear half ---- + * `ck_dev` is the snapshot's device slot, `ck_host` its host copy and `ck_on_disk` the + * disk store's. A clean device snapshot has both of the first two; a snapshot that has + * left the device has no `ck_dev`. All clear when the record carries no snapshot, which is + * the common case -- one block in every (interval / block_size) is a checkpoint position. */ + int32_t ck_dev = -1; + int32_t ck_host = -1; + bool ck_on_disk = false; + int64_t ck_pos = 0; + /* A COPY IS READING `ck_dev` RIGHT NOW: set when a write-back takes the snapshot, cleared + * when it reports. The one moment the device slot is not the cache's to free. */ + bool ck_reading = false; + /* THIS SNAPSHOT WILL NOT BE COPIED AGAIN: its copy was refused for want of room, or taken + * back to make room for another. The snapshot store is a few slots deep for the whole + * server, and a snapshot still in its device slot re-queued the moment its copy was + * evicted would evict the next one's, and so on -- every pass copying a hundred megabytes + * a rank to throw another hundred away. Cleared when a new commit replaces the state. */ + bool ck_skip = false; + /* A device slot the cache let go of while a copy was reading it. See release_snapshot. */ + int32_t ck_free_after = -1; + /* The snapshot host slot a disk write is reading, as `disk_src` is for the blocks. */ + int32_t ck_disk_src = -1; + /* WHEN A READ OFF DISK BROUGHT THIS RECORD IN, 0 when none did or its restore has run. + * Until the request that asked for it has been admitted the slots are its and not the + * arena's to give up: two conversations waiting on reads into a full arena would + * otherwise each evict what the other had read, and neither would ever be restored. Held + * for kFetchHoldNs at most, which bounds what a request that went away can pin. */ + uint64_t fetched_ns = 0; + /* Set only while plan_fetch makes room: this record is part of the chain being read, and + * giving its slot up to read another part of the same chain would be no progress. */ + bool keep = false; + std::list::iterator it; + }; + + /* Does this record want a copy it does not have yet? The blocks when they are in VRAM with no + * copy off the card; the snapshot when it is in a device slot with no copy off the card and + * the snapshot store exists at all. */ + bool wants_copy(const Rec& r) const; + /* The snapshot half of that on its own. */ + bool wants_ck_copy(const Rec& r) const; + /* And a disk copy: a host copy of either half that the disk does not hold yet. */ + bool wants_disk(const Rec& r) const; + void queue_copy(const BlockHash& key, Rec& r); + void queue_clean(const BlockHash& key, Rec& r); + void queue_disk(const BlockHash& key, Rec& r); + /* GIVE UP A HOST SLOT, the record's or a finished job's. Every block-arena free goes through + * `give_slot`, because a freed slot is what unblocks a write-back that found the arena full. + * `free_host` / `free_ck_host` are the record's own: a slot a disk write is reading is left + * for that write's report to free. */ + void give_slot(int32_t slot); + void free_host(Rec& r); + void free_ck_host(Rec& r); + void set_on_disk(Rec& r, bool v); + int64_t make_room_locked(int64_t n); + /* May this record's host copies be given up to make room right now? Not while a read put + * them there for a request that has not claimed them yet, nor while the chain being read + * includes it. */ + bool held_by_fetch(const Rec& r, uint64_t now_ns) const; + void unlist(Rec& r); + void relist(const BlockHash& key, Rec& r); + std::list& list_for(KVTier t) { return t == KVTier::Host ? host_lru_ : disk_lru_; } + void release_storage(const BlockHash& key, Rec& r); + /* Take a snapshot arena slot from the record whose host copy is cheapest to lose, and tell the + * cache if that was the snapshot's only copy. NO SECOND LIST: the records are walked, which + * keeps the header's "one record, one tier, one list" rule intact. `lossless` takes only a + * snapshot the disk also holds. + * Returns -1 when there is none to take. */ + int32_t evict_snapshot_slot(bool lossless); + + struct Session { + int64_t n_tokens = 0; + uint64_t first_seen_ns = 0; + uint64_t last_used_ns = 0; + std::vector chain; + }; + + /* Erase one row and its root index entry together. */ + void drop_session(uint64_t id); + /* The body of close(), for a caller that already holds the lock. */ + void reset(); + + /* TWO THREADS REACH THIS OBJECT. The engine loop owns every mutation -- the cache publishes a + * chain from the scheduler's close path, the maintenance pass moves records -- and an HTTP + * thread drawing the sessions view walks the same containers through sessions(). An + * unordered_map rehashed under an iterator is a crash rather than a stale number, so the + * state the view reads is held under this and every mutator takes it. + * + * NOT A BOTTLENECK, and it is worth saying where the cost lands: the per-block calls on the + * publish path (note_used) take it once each, uncontended, against a hash insert they were + * already paying for. No method here calls another that takes it, which is what keeps a plain + * mutex sufficient; the drop sinks are called while it is held and reach into the prefix + * cache, which never calls back. + * + * AND THE VIEW'S WALK MUST NOT DELAY THE ENGINE. It visits every block of every stored + * conversation, which is far longer than any engine-side hold, and the engine takes this lock + * every step. So the walk takes it for a slice of records at a time and, between slices, + * waits until nobody else is waiting for it: an engine-side taker that arrives during a slice + * waits for that slice and never for the walk. A plain mutex cannot promise that, because + * the walker re-locking the moment it unlocks can win against a woken waiter every time. */ + struct YieldingMutex { + std::mutex m; + std::atomic waiting{0}; + void lock() { + waiting.fetch_add(1, std::memory_order_relaxed); + m.lock(); + waiting.fetch_sub(1, std::memory_order_relaxed); + } + void unlock() { m.unlock(); } + /* The view's: taken only while no other taker is waiting. */ + void lock_after_others() { + for (;;) { + while (waiting.load(std::memory_order_relaxed) > 0) std::this_thread::yield(); + m.lock(); + if (waiting.load(std::memory_order_relaxed) == 0) return; + m.unlock(); + } + } + }; + mutable YieldingMutex mu_; + + Config cfg_; + SSDTier* disk_ = nullptr; + HostArena arena_; + HostArena ck_arena_; /* snapshots; a different slot size, so a different arena */ + std::unordered_map recs_; + std::list host_lru_, disk_lru_; /* front = oldest */ + /* THE WORK QUEUES, in the order the work arrived. Each holds a key at most once -- the Rec's + * flag says whether it is in -- and a key whose record changed under it is skipped when it is + * reached rather than searched for, so both stay a push and a pop. */ + std::deque wb_q_; /* records wanting a host copy */ + std::deque dk_q_; /* records wanting a disk copy, in the order they landed */ + std::vector clean_q_; /* records whose VRAM copy may now go */ + std::vector ck_frees_; /* device checkpoint slots a finished copy released */ + /* COPIES THE ARENA REFUSED since the last maintenance plan, which is what that plan frees + * room for. A count and not a list: any host-only entry makes room for any copy. */ + int64_t starved_ = 0; + /* A WRITE-BACK FOUND THE ARENA FULL AND NOTHING TO GIVE UP. Waiting again changes nothing until + * a slot is freed or an entry's disk copy lands, so the copy is not planned until one does -- + * otherwise every tick pops the queue, finds no slot and puts it back. */ + bool wb_stuck_ = false; + std::unordered_map sessions_; + /* THE DEATH SIGNAL FOR A ROW, and the reason the table is bounded. A published chain is only + * ever reachable from position zero, so the moment the cache evicts its FIRST block the + * conversation cannot be hit at any length and the row describes blocks that are not there. + * The cache announces every eviction through forget(), which is the only notice this object + * gets, so the root is indexed and the row goes with it. Several sessions share a root when + * they share a system prompt and all of them are unreachable together, which is why the value + * is a list. */ + std::unordered_map, BlockHashHash> roots_; + std::string model_; + std::function on_drop_; + std::function on_ck_drop_; + Stats stats_; + std::string report_; +}; + +} /* namespace rad */ diff --git a/core/mem/pools.cpp b/core/mem/pools.cpp new file mode 100644 index 00000000..168359a3 --- /dev/null +++ b/core/mem/pools.cpp @@ -0,0 +1,314 @@ +/* pools.cpp -- see pools.h. Every refusal in here names what did not fit and by how much. */ +#include "mem/pools.h" + +#include +#include +#include + +namespace rad { + +/* ------------------------------------------------------------------ allocators */ + +namespace { + +class DeviceAllocator final : public MemAllocator { +public: + void* alloc(int64_t bytes, int kind) override { return rad_dev_alloc(bytes, kind); } + void free(void* p, int kind) override { rad_dev_free(p, kind); } + const char* name() const override { return "device"; } +}; + +/* aligned_alloc, at the pool alignment. Used by the no-ROCm build and by the tests. A pool's base + * is 2 MiB-aligned either way, because the .rad's pool alignment is 2 MiB and huge-page mappable + * (spec §4.1) and a slab whose base is not aligned makes every fixed-stride slot inside it + * misaligned as well. */ +class MallocAllocator final : public MemAllocator { +public: + void* alloc(int64_t bytes, int kind) override { + (void)kind; + if (bytes <= 0) return nullptr; + int64_t n = align_up(bytes, (int64_t)RAD_ALIGN_POOL); + void* p = ::aligned_alloc((size_t)RAD_ALIGN_POOL, (size_t)n); + return p; + } + void free(void* p, int kind) override { (void)kind; ::free(p); } + const char* name() const override { return "malloc"; } +}; + +} /* namespace */ + +MemAllocator& rad_device_allocator() { static DeviceAllocator a; return a; } +MemAllocator& rad_malloc_allocator() { static MallocAllocator a; return a; } + +/* ------------------------------------------------------------------ Shortfall */ + +std::string Shortfall::str() const { + return fmt("%s: %s wanted %s, %s available -- short by %s", + pool.c_str(), what.c_str(), humanb(wanted).c_str(), + humanb(available).c_str(), humanb(missing()).c_str()); +} + +/* ------------------------------------------------------------------ Pool */ + +Pool::~Pool() { release(); } + +void Pool::release() { + /* ELASTIC FIRST, because an elastic pool has no allocator-owned base: vm_ owns the address + * range and the pages in it, and handing that pointer to MemAllocator::free would be a free + * of memory the allocator never handed out. */ + if (elastic_) { + vm_.release(); + elastic_ = false; + } else if (base_ && alloc_) { + alloc_->free(base_, kind_); + } + base_ = nullptr; + bytes_ = used_ = 0; +} + +int Pool::init(std::string_view nm, int64_t bytes, int kind, MemAllocator* a, bool accounting) { + release(); + name_ = std::string(nm); + bytes_ = bytes; + used_ = 0; + kind_ = kind; + accounting_ = accounting; + alloc_ = a; + shortfalls_.clear(); + res_.clear(); + if (accounting_ || bytes_ <= 0) return RAD_OK; + + base_ = a->alloc(bytes_, kind); + if (!base_) { + /* Refuse; do not retry smaller. An engine that quietly re-optimises the split is an + * engine whose benchmarks do not reproduce (spec §6). */ + shortfalls_.push_back({name_, "backing allocation", bytes_, 0}); + bytes_ = 0; + return RAD_E_NOMEM; + } + return RAD_OK; +} + +void* Pool::reserve(std::string_view what, int64_t bytes, int64_t align, int64_t* off_out) { + if (bytes < 0 || align <= 0) return nullptr; + int64_t off = align_up(used_, align); + if (off + bytes > bytes_) { + shortfalls_.push_back({name_, std::string(what), bytes, bytes_ - off}); + return nullptr; + } + used_ = off + bytes; + res_.push_back({std::string(what), off, bytes}); + if (off_out) *off_out = off; + if (accounting_) return nullptr; /* headroom: accounted, never touched */ + return (char*)base_ + off; +} + +/* ------------------------------------------------------------------ elastic */ + +int64_t Pool::granule() { return VMem::granularity(); } + +int Pool::init_elastic(std::string_view nm, int64_t bytes, int kind, MemAllocator* a) { + /* WITHOUT VIRTUAL MEMORY MANAGEMENT THIS IS init(). The caller does not branch: it commits + * what it wants, the commits succeed against memory that was already there, and the pool + * holds its maximum for the whole run. That is worse than elastic and identical to a fixed + * pool, which is the right shape for a fallback. */ + if (!VMem::supported() || kind != RAD_MEM_DEVICE) + return init(nm, bytes, kind, a, /*accounting=*/false); + + release(); + name_ = std::string(nm); + bytes_ = bytes; + used_ = 0; + kind_ = kind; + accounting_ = false; + alloc_ = a; + shortfalls_.clear(); + res_.clear(); + if (bytes_ <= 0) return RAD_OK; + + const int rc = vm_.reserve(bytes_, RAD_ALIGN_POOL); + if (rc < 0) { + /* Refuse; do not retry smaller. An address range is not memory -- a reservation that + * fails on a 64-bit card is a bug and not a budget, and quietly halving it would hide the + * bug behind a pool that cannot grow to what the operator asked for. */ + shortfalls_.push_back({ name_, "address reservation", bytes_, 0 }); + bytes_ = 0; + return rc; + } + base_ = vm_.base(); + /* THE RANGE ROUNDS UP AND THE BUDGET DOES NOT. vm_.size() is the reservation rounded to a + * whole granule, which is a fact about the driver and not a licence to spend more than the + * split allowed. Taking it as the budget lets a pool grow into the headroom by up to a + * granule and, worse, GRANT a reservation the budget should have refused -- the same quiet + * re-optimisation of the split that init() refuses to make when its allocation fails. + * + * The rounded tail stays addressable, and that is what it is for: the last reservation can + * end mid-granule and its commit rounds outward into a range that is really reserved. */ + elastic_ = true; + return RAD_OK; +} + +int Pool::commit(int64_t off, int64_t bytes) { + if (!elastic_) { + /* A fixed pool is backed everywhere inside it and nowhere outside it, and saying so is + * what keeps a caller written against the elastic contract correct here. */ + return (off >= 0 && bytes >= 0 && off + bytes <= bytes_) ? RAD_OK : RAD_E_INVAL; + } + return vm_.commit(off, bytes); +} + +int Pool::decommit(int64_t off, int64_t bytes) { + if (!elastic_) return RAD_OK; /* nothing to give back, and that is not an error */ + return vm_.decommit(off, bytes); +} + +bool Pool::is_committed(int64_t off, int64_t bytes) const { + if (!elastic_) return off >= 0 && bytes >= 0 && off + bytes <= bytes_; + return vm_.is_committed(off, bytes); +} + +std::string Pool::report() const { + std::string s = fmt("%-14s %10s budget, %10s used, %10s free%s\n", + name_.c_str(), humanb(bytes_).c_str(), humanb(used_).c_str(), + humanb(avail()).c_str(), accounting_ ? " (accounted, not allocated)" : ""); + for (const auto& r : res_) + s += fmt(" %-24s %10s @ +%lld\n", r.what.c_str(), humanb(r.bytes).c_str(), + (long long)r.off); + for (const auto& f : shortfalls_) s += " REFUSED " + f.str() + "\n"; + return s; +} + +/* ------------------------------------------------------------------ Pools */ + +int Pools::configure(const Config& cfg, int64_t vram_capacity, + MemAllocator* device, MemAllocator* host) { + configured_ = false; + fit_report_.clear(); + + if (!device) device = &rad_device_allocator(); + if (!host) host = device; + + const int64_t MiB = 1024 * 1024; + const int64_t w = cfg.vram_weights_mib * MiB; + const int64_t kv = cfg.vram_kv_mib * MiB; + const int64_t hp = cfg.host_pool_mib * MiB; + + /* THE BUDGETS ARE RESOLVED BEFORE THIS RUNS AND THIS DOES NOT RE-DECIDE THEM. Either the + * operator stated them or core/mem/vram_budget.cpp derived them from the card, the measured + * driver residency and the computed arena -- and either way they arrive here as two numbers + * with a report behind them. Either way this component refuses rather than shrinking + * anything: an engine that quietly re-optimises a split is an engine whose + * benchmarks do not reproduce (spec §6). A zero here means the resolver was never called, + * which is a wiring bug and gets named as one. */ + std::string missing; + if (cfg.vram_weights_mib <= 0) missing += " vram_weights resolved to 0 MiB\n"; + if (cfg.vram_kv_mib <= 0) missing += " vram_kv resolved to 0 MiB\n"; + if (!missing.empty()) { + fit_report_ = "VRAM pool budgets are empty -- state --vram-weights-mib / --vram-kv-mib, or " + "let the card be split by --gpu-headroom-mib and --expert-vs-cache-ratio:\n" + + missing; + RAD_ERR("%s", fit_report_.c_str()); + return RAD_E_INVAL; + } + + const int64_t want = w + kv; + if (vram_capacity > 0 && want > vram_capacity) { + /* Name every pool and the total overage. Refuse rather than shrinking any of them. */ + fit_report_ = fmt( + "VRAM budgets do not fit:\n" + " vram_weights %10s\n" + " vram_kv %10s\n" + " ------------------------\n" + " total %10s\n" + " card total %10s\n" + " OVER BY %10s\n" + "Lower --vram-weights-mib / --vram-kv-mib, or raise --gpu-headroom-mib and let " + "--expert-vs-cache-ratio split what is left. The split is yours to make; the engine " + "will not make it for you (spec §6).\n", + humanb(w).c_str(), humanb(kv).c_str(), + humanb(want).c_str(), humanb(vram_capacity).c_str(), + humanb(want - vram_capacity).c_str()); + RAD_ERR("%s", fit_report_.c_str()); + return RAD_E_NOMEM; + } + + /* THE SLACK IS NAMED, because nothing else will name it -- and after the resolver ran there + * should be almost none. `vram_capacity` is totalGlobalMem: it is not the free VRAM and it is + * not the sum of the budgets. What is left over here is the driver's residency, the activation + * arena, --gpu-headroom-mib, and whatever MiB rounding could not place; vram_budget.cpp's + * report breaks that down term by term. A budget a couple of GiB under the card is that much + * of the expert plane streaming from host memory instead, which costs real prefill throughput + * on a model whose experts do not fit. + * + * THIS IS FOR A STATED BUDGET AND ONLY FOR ONE. A size threshold cannot tell the two apart: a + * small dense model whose cache is already at the largest context it can address leaves many + * GiB that NOTHING can spend, and warning there would tell the operator to leave unset the + * very flags they already left unset. Where the resolver made the split it has already printed + * every term including the unusable one, and there is nothing to add. */ + if (vram_capacity > 0 && !cfg.vram_budget_derived) { + const int64_t slack = vram_capacity - want; + if (slack >= 1024 * MiB) + RAD_WARN("VRAM budgets total %s of the card's %s, so %s is neither budgeted nor " + "accounted. The driver's context, the activation arena and " + "--gpu-headroom-mib come out of it; anything past those is throughput on the " + "floor. Leave --vram-weights-mib / --vram-kv-mib unset to have the card split " + "automatically.", + humanb(want).c_str(), humanb(vram_capacity).c_str(), humanb(slack).c_str()); + } + + int st = RAD_OK; + int s; + /* Order matters only for the diagnostic: allocate the two big ones first so a failure names + * the one that actually could not be served. */ + if ((s = weights_.init("vram_weights", w, RAD_MEM_DEVICE, device, false)) < 0) st = s; + /* THE KV POOL IS THE ELASTIC ONE, ALWAYS, AND THERE IS NO OTHER MODE. Its budget is still the + * budget: elasticity does not change how much of the card the cache may address, it changes + * whether the part it is not addressing has VRAM behind it. What the cache releases is what + * the expert plane can promote into, so the split between them stops being a guess made once + * at startup and becomes the two pools' actual demand. + * + * THERE IS NO FLAG, BECAUSE A FLAG IS THE WRONG SHAPE FOR IT. A fixed pool holds every block + * it was carved for whether or not a single token is in it, and an expert plane that does not + * fit streams weights over the link for the whole run to pay for cache nobody is using. There + * is no deployment that wants that. A device with no virtual memory management goes through + * the same call -- init_elastic() allocates the range whole there, which is fixed-pool + * behaviour under a contract the callers already meet. */ + if ((s = kv_.init_elastic("vram_kv", kv, RAD_MEM_DEVICE, device)) < 0) st = s; + /* MAPPED, NOT MERELY PINNED, AND THE DIFFERENCE IS A WHOLE TIER. + * + * This one pool serves two jobs: the mover's staging buffers and O_DIRECT landing zone, which + * want pinned memory so a transfer is a DMA with no driver bounce -- and the ZERO-COPY + * execution site, row three of spec §5.1's table, where the bytes stay in host memory and the + * kernel reads them over the link as it computes. The second needs the allocation to be + * addressable FROM A KERNEL, and hipHostMallocDefault does not make it so. + * + * Getting it wrong is silent and total: Mover::init asks rad_dev_device_ptr for the pool's + * base as the card sees it, an unmapped allocation answers null, and the fallback is the host + * pointer -- so `assign_expert_tiered`, which routes EVERY pooled expert to + * Site::DeviceZeroCopy, would hand a kernel a pointer it cannot dereference. There would be no + * hybrid tier, only a plan that says there is one. + * + * Mapped memory is still pinned, so job one is unaffected; hipHostMallocMapped is strictly the + * larger promise. On the host backend all four kinds are the same aligned pages. */ + if ((s = host_ .init("host_pool", hp, RAD_MEM_HOST_MAPPED, host, false)) < 0) st = s; + + fit_report_ = weights_.report(); + fit_report_ += kv_.report(); + fit_report_ += host_.report(); + + if (st < 0) { + RAD_ERR("pool allocation refused:\n%s", fit_report_.c_str()); + return st; + } + configured_ = true; + return RAD_OK; +} + +std::vector Pools::shortfalls() const { + std::vector out; + for (const Pool* p : { &weights_, &kv_, &host_ }) + for (const auto& f : p->shortfalls()) out.push_back(f); + return out; +} + +} /* namespace rad */ diff --git a/core/mem/pools.h b/core/mem/pools.h new file mode 100644 index 00000000..9bf9288e --- /dev/null +++ b/core/mem/pools.h @@ -0,0 +1,199 @@ +/* pools.h -- explicit pool budgets (spec §6). + * + * Every pool is budgeted EXPLICITLY. No profiling pass, no utilisation fraction, no inference + * about what the workload will be. The trade between KV blocks and resident weights is real and + * workload-dependent -- a long-context low-concurrency server and a short-context high-concurrency + * one want opposite splits -- but it is the operator's to make. An engine that quietly + * re-optimises the split is an engine whose benchmarks do not reproduce. + * + * Two properties this file exists to make STRUCTURAL rather than conventional: + * + * 1. A Pool holds a base, a size and a cursor, and has no pointer to any other Pool. There is + * no allocate-from-wherever call anywhere in this header. Therefore no code path exists + * along which the mover's expert promotion (spec §5.4) can reach a KV block: the mover is + * handed Pools::weights() and it is not possible to reach Pools::kv() from it. That is the + * whole reason the weight slab is a fixed budget. + * + * 2. A reservation that does not fit returns null and RECORDS the shortfall by name and by how + * much. It never falls through to another pool, never shrinks an earlier reservation, and + * never silently rounds the request down. The engine refuses to start instead. + */ +#pragma once +#include "rad_core.h" + +#include "../device/device.h" + +#include +#include +#include + +namespace rad { + +/* ------------------------------------------------------------------ the allocator seam */ +/* Everything here goes through an allocator object rather than calling rad_dev_alloc directly. + * The host backend is the primary development target and not a fallback + * (docs/IMPLEMENTATION.md), and a pool test that cannot run without ROCm is a pool test that does + * not run. The device allocator is the default; the malloc one is what the no-device build and + * the tests use. */ +class MemAllocator { +public: + virtual ~MemAllocator() = default; + virtual void* alloc(int64_t bytes, int kind) = 0; /* kind is RAD_MEM_* */ + virtual void free(void* p, int kind) = 0; + virtual const char* name() const = 0; +}; + +MemAllocator& rad_device_allocator(); /* rad_dev_alloc / rad_dev_free */ +MemAllocator& rad_malloc_allocator(); /* aligned_alloc; host-only builds and tests */ + +/* ------------------------------------------------------------------ shortfalls */ +/* What did not fit, by name and by how much. Every refusal in this component produces one of + * these rather than a bare RAD_E_NOMEM, because "it returned -6" is not a diagnosis. */ +struct Shortfall { + std::string pool; /* which budget: "vram_weights", "vram_kv", ... */ + std::string what; /* what was being reserved when it ran out */ + int64_t wanted = 0; + int64_t available = 0; + int64_t missing() const { return wanted - available; } + std::string str() const; +}; + +/* ------------------------------------------------------------------ Pool */ +/* One reservation, made once, that never grows, never shrinks and never borrows. + * + * `accounting_only` pools hold no memory: the headroom budget is memory we promise NOT to touch, + * for activations and the arena (spec §6). The arena owner still reserves against it, so an arena + * that would exceed the headroom refuses at startup by name instead of succeeding here and + * failing the first prefill on the device. */ +class Pool { +public: + Pool() = default; + ~Pool(); + Pool(const Pool&) = delete; + Pool& operator=(const Pool&) = delete; + + const char* name() const { return name_.c_str(); } + int64_t bytes() const { return bytes_; } + int64_t used() const { return used_; } + int64_t avail() const { return bytes_ - used_; } + void* base() const { return base_; } + int kind() const { return kind_; } + bool accounting_only() const { return accounting_; } + + /* Carve `bytes` at `align`. Returns the pointer (null for an accounting-only pool, which + * still tracks the cursor), or null with a recorded shortfall if it does not fit. + * `off_out`, when given, receives the byte offset from base -- which is what a slab of + * fixed-stride slots actually wants, since the offset survives a base that is a device + * pointer nobody may dereference on the host. */ + void* reserve(std::string_view what, int64_t bytes, int64_t align, int64_t* off_out = nullptr); + + /* True when nothing was refused. Checked once, at the end of startup, so the report names + * every failure rather than the first one at the top (spec §3.1's rule, applied here). */ + bool ok() const { return shortfalls_.empty(); } + + /* ---- elastic pools ---------------------------------------------------------------------- + * + * An elastic pool reserves its ADDRESS RANGE whole and backs only the part somebody has asked + * for. Every offset reserve() hands out is final from the first call, so a slab stride or a + * layer stride computed against the full range stays correct while the physical memory behind + * the unused part goes back to the card for another pool to take. That is the only way two + * pools on one card can trade: the addresses cannot move, so the pages have to. + * + * The two pools this exists for are the KV cache and the expert slab, and the trade is not + * symmetric. A KV block holds a sequence's state and can only be given back once nothing + * holds it; an expert slot holds a COPY of a weight that also lives in the host pool or the + * container, so it can be given back whenever the mover can spare it. That asymmetry is the + * policy's, not this file's -- what is here is the mechanism and the refusal. + * + * A pool is elastic only where the device layer has virtual memory management (VMem in + * core/device/device.h). Where it does not, init_elastic() allocates the whole range exactly + * as init() does and commit()/decommit() are no-ops that succeed: a caller written for an + * elastic pool runs unchanged against a fixed one, holding the maximum it was reserved. That + * is the degradation spec §6 allows, because the pool is still one explicit budget -- it is + * simply one that cannot give anything back. */ + bool elastic() const { return elastic_; } + int64_t committed() const { return elastic_ ? vm_.committed() : bytes_; } + + /* Back [off, off+bytes) so a kernel may touch it. Rounds OUTWARD to the commit granule, so + * what was asked for is certainly backed, and is idempotent: a pool growing to n asks for + * [0, n) every time n changes and pays only for the part that is new. */ + int commit(int64_t off, int64_t bytes); + + /* Hand the pages back. Rounds INWARD, so a granule holding one byte the caller still wants + * stays -- a caller that shrinks to exactly the boundary it is holding is therefore safe, and + * one that shrinks between boundaries simply keeps a granule it will use next time. */ + int decommit(int64_t off, int64_t bytes); + + bool is_committed(int64_t off, int64_t bytes) const; + + /* The commit quantum, so a caller can pick grow steps that do not strand a fraction of one in + * every stripe. 0 when the pool is not elastic. */ + static int64_t granule(); + + const std::vector& shortfalls() const { return shortfalls_; } + + std::string report() const; + +private: + /* Reserve the address range and back nothing. `bytes` is the MAXIMUM the pool may ever hold + * and is what reserve() carves against; what it costs the card is committed(). Falls back to + * a whole allocation where the device layer has no virtual memory management. */ + int init_elastic(std::string_view nm, int64_t bytes, int kind, MemAllocator* a); + + friend class Pools; + int init(std::string_view nm, int64_t bytes, int kind, MemAllocator* a, bool accounting); + void release(); + + std::string name_; + int64_t bytes_ = 0; + int64_t used_ = 0; + void* base_ = nullptr; + int kind_ = RAD_MEM_DEVICE; + bool accounting_ = false; + bool elastic_ = false; + VMem vm_; + MemAllocator* alloc_ = nullptr; + std::vector shortfalls_; + struct Res { std::string what; int64_t off, bytes; }; + std::vector res_; +}; + +/* ------------------------------------------------------------------ Pools */ +class Pools { +public: + /* `vram_capacity` is what the device reports free. Pass 0 to skip the capacity check, which + * is what the host backend wants -- it has no meaningful answer and inventing one would be + * exactly the inference §6 forbids. + * + * Refuses, by name and by how much, rather than shrinking anything: + * - if the operator did not state the weight and KV budgets at all; + * - if weights + kv exceeds the card; + * - if a pool's backing allocation fails. + */ + int configure(const Config& cfg, int64_t vram_capacity, + MemAllocator* device = nullptr, MemAllocator* host = nullptr); + + Pool& weights() { return weights_; } + Pool& kv() { return kv_; } + Pool& host_pinned() { return host_; } + + const Pool& weights() const { return weights_; } + const Pool& kv() const { return kv_; } + const Pool& host_pinned() const { return host_; } + + bool configured() const { return configured_; } + + /* The line the engine prints at startup and the reason it refuses. Always populated, even on + * success, because the placement report wants the pool totals (spec §16). */ + const std::string& fit_report() const { return fit_report_; } + + /* Every shortfall from every pool, gathered. */ + std::vector shortfalls() const; + +private: + Pool weights_, kv_, host_; + std::string fit_report_; + bool configured_ = false; +}; + +} /* namespace rad */ diff --git a/core/mem/prefix.cpp b/core/mem/prefix.cpp new file mode 100644 index 00000000..290a0650 --- /dev/null +++ b/core/mem/prefix.cpp @@ -0,0 +1,869 @@ +/* prefix.cpp -- see prefix.h. */ +#include "mem/prefix.h" + +#include "mem/kvtier.h" + +#include +#include + +namespace rad { + +/* ------------------------------------------------------------------ hashing */ +/* A 128-bit chained mix rather than a cryptographic hash. A prefix cache whose store is on disk, + * shared and long-lived is usually keyed by SHA-256, because a cheap hash's collision would serve + * one caller another caller's context. We get the same guarantee more cheaply: every entry keeps + * its BLOCK'S TOKEN IDS and compares them on a hit, so a collision is a miss rather than a wrong + * answer, and the hash only has to be good enough to keep the bucket chains short. The SSD tier, + * which is such a store, carries the token ids into the slot header for the same reason + * (sstier.h). + * + * splitmix64's finaliser, which is a full 64-bit bijection -- so folding one token cannot lose the + * bits of the previous one, which is the failure mode of a plain multiply-xor chain. */ +static inline uint64_t mix64(uint64_t x) { + x += 0x9e3779b97f4a7c15ull; + x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9ull; + x = (x ^ (x >> 27)) * 0x94d049bb133111ebull; + return x ^ (x >> 31); +} + +std::string BlockHash::str() const { return fmt("%016llx%016llx", (unsigned long long)hi, + (unsigned long long)lo); } + +uint64_t mm_content_hash(const void* embedding, int64_t bytes) { + const uint8_t* p = (const uint8_t*)embedding; + uint64_t h = 0xcbf29ce484222325ull ^ mix64((uint64_t)bytes); + int64_t i = 0; + for (; i + 8 <= bytes; i += 8) { + uint64_t w; std::memcpy(&w, p + i, 8); + h = mix64(h ^ w); + } + uint64_t tail = 0; + for (int64_t k = 0; i + k < bytes; ++k) tail |= (uint64_t)p[i + k] << (8 * k); + return mix64(h ^ tail); +} + +BlockHash chain_block_hash(const BlockHash& parent, const int32_t* toks, int32_t n, + const MMContentKey* mm, int32_t n_mm, int64_t block_begin) { + /* The parent seeds both lanes. That is the whole chained-hash property: a block with identical + * tokens under a different prefix lands somewhere else, so a block in the middle of another + * conversation cannot be served here. */ + BlockHash h; + h.hi = mix64(parent.hi ^ 0x243f6a8885a308d3ull); + h.lo = mix64(parent.lo ^ 0x13198a2e03707344ull); + h.hi = mix64(h.hi ^ (uint64_t)block_begin); + + for (int32_t i = 0; i < n; ++i) { + uint64_t t = (uint64_t)(uint32_t)toks[i]; + h.lo = mix64(h.lo ^ t); + h.hi = mix64(h.hi + h.lo + t); + } + + /* Multimodal spans that overlap this block, folded by CONTENT plus the overlap offsets, so the + * same image at the same position hashes the same and a different image never aliases behind + * the identical placeholder token ids (spec §11). */ + const int64_t lo_pos = block_begin, hi_pos = block_begin + n; + for (int32_t i = 0; i < n_mm; ++i) { + const MMContentKey& m = mm[i]; + if (m.tok_end <= lo_pos || m.tok_begin >= hi_pos) continue; + h.lo = mix64(h.lo ^ m.hash); + h.hi = mix64(h.hi ^ mix64(m.hash + (uint64_t)(m.tok_begin - lo_pos) * 1000003ull + + (uint64_t)(m.tok_end - lo_pos))); + } + /* Never let a block hash to zero: a zeroed BlockHash is the chain root and must be unique. */ + if (!h.valid()) h.lo = 1; + return h; +} + +/* ------------------------------------------------------------------ retention policies */ + +void GeometricBackoff::select(const std::vector& pos, std::vector* keep) const { + keep->clear(); + if (pos.empty()) return; + const int64_t tip = (int64_t)pos.size() - 1; + std::vector mark(pos.size(), 0); + mark[(size_t)tip] = 1; /* THE TIP IS ALWAYS KEPT */ + for (int64_t d = 1; tip - d >= 0; d *= 2) mark[(size_t)(tip - d)] = 1; + for (size_t i = 0; i < pos.size(); ++i) if (mark[i]) keep->push_back(pos[i]); +} + +void KeepTipOnly::select(const std::vector& pos, std::vector* keep) const { + keep->clear(); + if (!pos.empty()) keep->push_back(pos.back()); +} + +void KeepAll::select(const std::vector& pos, std::vector* keep) const { + *keep = pos; +} + +/* ------------------------------------------------------------------ configure */ + +int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_interval) { + kv_ = kv; + enabled_ = false; + has_linear_ = false; + block_size_ = 0; + interval_ = 0; + groups_.clear(); + map_.clear(); lru_.clear(); + ck_by_prefix_.clear(); ck_by_session_.clear(); + /* THE POLICY COMES FROM THE CONFIG, and set_policy() overrides it -- which is the order a + * test wants and the order an operator wants. The three names are checked in config_parse, so + * an unknown one cannot reach here and silently become the default. */ + if (cfg.checkpoint_policy == "tip-only") policy_ = std::make_unique(); + else if (cfg.checkpoint_policy == "keep-all") policy_ = std::make_unique(); + else policy_ = std::make_unique(); + report_.clear(); + + if (!kv) return RAD_E_INVAL; + if (!cfg.prefix_cache) { + report_ = "prefix cache: disabled by --no-prefix-cache\n"; + return RAD_OK; + } + + /* The cache's granularity is the block size of the first FULL-attention group, because that is + * the group whose content a prefix hit actually reuses. A paged group with a different block + * size cannot be indexed at that granularity and is named in the report rather than silently + * skipped -- a group that quietly stops being prefix-cached is a hit-rate regression nobody + * can attribute. */ + for (const auto& p : kv->plans()) { + if (p.kind == RAD_KV_FULL && block_size_ == 0) block_size_ = p.block_size; + if (p.stateful()) has_linear_ = true; + } + if (block_size_ == 0) { + for (const auto& p : kv->plans()) if (p.paged()) { block_size_ = p.block_size; break; } + } + if (block_size_ <= 0) { + report_ = "prefix cache: no paged KV group to cache; disabled\n"; + RAD_WARN("%s", report_.c_str()); + return RAD_OK; + } + std::string skipped; + for (const auto& p : kv->plans()) { + if (!p.paged()) continue; + /* A WINDOW GROUP CANNOT BE SERVED A PREFIX. Its blocks below the window are recycled, so + * the block list a hit hands over does not describe it -- adopt() would take a prefix's + * worth of blocks into a table the manager only ever grows to window_blocks, and the slot + * mapping is computed against a first_block_pos that a hit does not set. The group is + * simply not prefix-cached, which is correct and costs the sequences that hit a drafter + * or a windowed layer whose cache starts where the hit ended. */ + if (p.kind == RAD_KV_WINDOW) { + skipped += fmt(" group '%s' is windowed (%lld blocks) -- NOT cached, a hit's blocks " + "do not describe a cache whose floor moves\n", + p.name.c_str(), (long long)p.window_blocks); + continue; + } + if (p.block_size == block_size_) groups_.push_back(p.index); + else skipped += fmt(" group '%s' block %lld != cache granularity %lld -- NOT cached\n", + p.name.c_str(), (long long)p.block_size, (long long)block_size_); + } + + interval_ = checkpoint_interval; + if (has_linear_) { + if (interval_ <= 0) { + RAD_ERR("checkpoint_interval is %lld but the model has linear-attention state. A " + "0 interval means no checkpoint is ever written and every hit replays the " + "linear layers from zero.", (long long)interval_); + return RAD_E_INVAL; + } + if (interval_ % block_size_ != 0) { + /* A checkpoint that does not land on an attention block boundary can never be found: + * the lookup identifies a checkpoint by the chained hash at its position, and that + * hash only exists at block boundaries. vLLM's answer is to inflate the block to the + * interval, which is what costs it attention hit rate on every short prompt. Ours is + * to refuse the misconfiguration by name. */ + RAD_ERR("the checkpoint interval resolves to %lld (from --checkpoint-interval %lld, " + "rounded up to the chunk quantum) and that is not a multiple of the attention " + "block size %lld. The linear checkpoint is found by the chained block hash at " + "its position, and that hash exists only on a block boundary, so this interval " + "would never produce a single hit (spec §7.3).", + (long long)interval_, (long long)cfg.checkpoint_interval, + (long long)block_size_); + return RAD_E_INVAL; + } + } + + enabled_ = true; + report_ = fmt("prefix cache: %zu paged group(s) at %lld-token blocks; linear checkpoints " + "every %lld tokens (%s x %s), retention '%s'\n", + groups_.size(), (long long)block_size_, + (long long)(has_linear_ ? interval_ : 0), + humanb(kv->checkpoint_bytes()).c_str(), + fmt("%lld slots", (long long)kv->checkpoint_slots()).c_str(), + policy_->name()); + report_ += skipped; + return RAD_OK; +} + +void PrefixCache::set_policy(std::unique_ptr p) { + if (p) policy_ = std::move(p); +} + +std::string PrefixCache::report() const { return report_; } + +/* ------------------------------------------------------------------ full attention */ + +std::vector PrefixCache::chain_all(const std::vector& tokens, + const std::vector& mm, + int64_t n_blocks) const { + std::vector hs; + hs.reserve((size_t)n_blocks); + BlockHash parent; + for (int64_t b = 0; b < n_blocks; ++b) { + parent = chain_block_hash(parent, tokens.data() + b * block_size_, (int32_t)block_size_, + mm.data(), (int32_t)mm.size(), b * block_size_); + hs.push_back(parent); + } + return hs; +} + +void PrefixCache::touch(const BlockHash& h) const { + auto it = map_.find(h); + if (it == map_.end() || !it->second.in_lru) return; + lru_.splice(lru_.end(), lru_, it->second.lru); +} + +CacheHit PrefixCache::lookup(const std::vector& tokens, + const std::vector& mm, + std::vector>* blocks_out) const { + CacheHit hit; + if (blocks_out) { blocks_out->assign(groups_.size(), {}); } + if (!enabled_ || tokens.empty()) return hit; + ++stats_.lookups; + + const int64_t n_full = (int64_t)tokens.size() / block_size_; + std::vector hs = chain_all(tokens, mm, n_full); + + int64_t matched = 0; + for (; matched < n_full; ++matched) { + auto it = map_.find(hs[(size_t)matched]); + if (it == map_.end()) break; + /* AN ENTRY THE TIERS HOLD IS NOT A HIT, and this is the guard that makes demotion safe at + * all. Moving an entry off the device releases its KV blocks; the map keeps the entry so + * the bytes can be found again, but its `blocks` now name blocks the pool has given to + * somebody else. Serving them would hand one conversation another's context -- exactly + * the failure the token compare below exists to rule out, arrived at from the other side. + * + * The prefix simply stops here. The caller may promote and ask again (see + * restorable_from), and until it does the answer is an honest shorter hit. An entry with + * a promotion still out on it stops the prefix too: its ids are the ones it left with. */ + if (!it->second.in_lru) break; + /* Compare the token ids, not just the hash. A 128-bit collision is improbable; serving one + * conversation's context to another is not a failure anybody would ever diagnose, so it is + * made impossible rather than unlikely. */ + const int32_t* src = tokens.data() + matched * block_size_; + if ((int64_t)it->second.tokens.size() != block_size_ || + std::memcmp(it->second.tokens.data(), src, (size_t)block_size_ * sizeof(int32_t)) != 0) + break; + } + + /* At least one token must remain for the step to compute a logit from. A full hit is backed + * off by one block rather than being handed to a caller that would then schedule a zero-token + * forward pass. */ + if (matched * block_size_ >= (int64_t)tokens.size() && matched > 0) --matched; + + for (int64_t b = 0; b < matched; ++b) { + touch(hs[(size_t)b]); + if (!blocks_out) continue; + const Entry& e = map_.find(hs[(size_t)b])->second; + for (size_t g = 0; g < groups_.size(); ++g) + (*blocks_out)[g].push_back(e.blocks[g]); + } + /* A HIT IS A USE, and the tiers' idle clock has to hear about it: it is what decides when an + * entry leaves the device, and without this it runs from when the chain was published, so a + * prefix hit on every turn -- or one just promoted back for this very lookup -- would read as + * idle and be demoted from under the request using it. */ + if (tiers_ && matched > 0) tiers_->note_hits(hs.data(), matched, rad_mono_ns()); + hit.n_attn_tokens = (int32_t)(matched * block_size_); + stats_.block_hits += matched; + stats_.block_misses += n_full - matched; + + /* ---- the split: how far the LINEAR state can be reused ---- + * The attention blocks are reusable up to n_attn_tokens. The recurrent state is only reusable + * at a checkpoint, so walk back to the last checkpoint boundary at or below n_attn_tokens and + * look it up by the chained hash there. The gap between the two is replayed through the linear + * layers only -- the attention layers for those tokens are already in the cache. */ + if (!has_linear_) { + /* No recurrent state means nothing to replay: the whole attention hit is directly usable. */ + hit.n_linear_tokens = hit.n_attn_tokens; + return hit; + } + for (int64_t p = (hit.n_attn_tokens / interval_) * interval_; p > 0; p -= interval_) { + const BlockHash& h = hs[(size_t)(p / block_size_ - 1)]; + auto it = ck_by_prefix_.find(h); + if (it == ck_by_prefix_.end() || !it->second.valid) continue; + hit.n_linear_tokens = (int32_t)p; + hit.checkpoint_slot = it->second.slot; + it->second.used = ++clock_; + handed_.push_back(h); + ++stats_.ckpt_hits; + return hit; + } + ++stats_.ckpt_misses; + return hit; +} + +int PrefixCache::insert(uint64_t session, + const std::vector& tokens, + const std::vector& mm, + const std::vector>& blocks, + int64_t n_tokens) { + if (!enabled_) return RAD_OK; + if (blocks.size() != groups_.size()) return RAD_E_INVAL; + if (n_tokens > (int64_t)tokens.size()) return RAD_E_INVAL; + + const int64_t n_full = n_tokens / block_size_; + if (n_full <= 0) return RAD_OK; + for (const auto& bt : blocks) if ((int64_t)bt.size() < n_full) return RAD_E_INVAL; + + std::vector hs = chain_all(tokens, mm, n_full); + const uint64_t now = rad_mono_ns(); + for (int64_t b = 0; b < n_full; ++b) { + const BlockHash& h = hs[(size_t)b]; + auto it = map_.find(h); + if (it != map_.end() && it->second.in_lru) { touch(h); continue; } + if (it != map_.end()) { + /* AN ENTRY WHOSE ONLY COPY IS OFF THE CARD, AND THIS REQUEST JUST COMPUTED IT AGAIN -- + * a restore that did not fit, or a chain cut short. The request's blocks become the + * entry's device copy and the tier copy is let go (IdleTiers::rebound says why). One + * with a promotion still out on it is left alone: its record is the transfer's. */ + if (!tiers_ || !tiers_->resident_off_device(h)) continue; + std::vector mine(groups_.size(), -1); + size_t held = 0; + for (; held < groups_.size(); ++held) { + const int32_t blk = blocks[held][(size_t)b]; + if (kv_->retain_block(groups_[held], blk) < 0) break; + mine[held] = blk; + } + if (held != groups_.size()) { + for (size_t g = 0; g < held; ++g) kv_->release_block(groups_[g], mine[g]); + return RAD_E_STATE; + } + Entry& e = it->second; + e.blocks = std::move(mine); + lru_.push_back(h); + e.lru = std::prev(lru_.end()); + e.in_lru = true; + tiers_->rebound(h, e.blocks, now); + continue; + } + + Entry e; + e.blocks.assign(groups_.size(), -1); + size_t held = 0; + for (; held < groups_.size(); ++held) { + int32_t blk = blocks[held][(size_t)b]; + if (kv_->retain_block(groups_[held], blk) < 0) break; + e.blocks[held] = blk; + } + if (held != groups_.size()) { + /* Unwind exactly what was taken. A half-referenced entry leaks a block forever, and a + * released block that was never retained frees one out from under a live sequence -- + * both are silent and neither is diagnosable later. */ + for (size_t g = 0; g < held; ++g) kv_->release_block(groups_[g], e.blocks[g]); + return RAD_E_STATE; + } + e.tokens.assign(tokens.begin() + b * block_size_, + tokens.begin() + (b + 1) * block_size_); + lru_.push_back(h); + e.lru = std::prev(lru_.end()); + e.in_lru = true; + map_.emplace(h, std::move(e)); + } + + /* THE TIERS LEARN THE CHAIN HERE AND NOWHERE ELSE. insert() is the one call that knows a chain + * was COMPLETED rather than merely touched -- which is what a session is -- and it is also the + * only place every entry's block ids are in hand at once. + * + * AND THE IDS COME OUT OF THE MAP, NOT OUT OF `blocks`. The two are the same for an entry this + * call just created and DIFFERENT for one that already existed, because the loop above keeps + * the entry the cache already holds and lets this request's own copy of those blocks go. Both + * block tables describe the same tokens, but only the cache's is REFERENCED: the other belongs + * to a sequence that is about to be freed. + * + * Recording the wrong one is not a bookkeeping detail. The tiers demote what they were told, + * so they would gather out of blocks the pool had already handed to somebody else -- putting a + * stranger's KV in the tier under this prefix's key -- and then release a reference nobody + * took. It shows as a flood of "double free of block N" in the log and, once the entry is + * promoted back, as fluent text with one word changed. */ + if (tiers_) { + for (int64_t b = 0; b < n_full; ++b) { + auto it = map_.find(hs[(size_t)b]); + if (it == map_.end()) continue; + tiers_->note_used(hs[(size_t)b], it->second.blocks, now); + } + tiers_->note_session(session, hs, n_tokens, now); + } + return RAD_OK; +} + + +/* ------------------------------------------------------------------ idle session tiers */ + +std::vector PrefixCache::restorable_from(const std::vector& tokens, + const std::vector& mm, + std::vector* chain) const { + std::vector out; + if (chain) chain->clear(); + if (!enabled_ || !tiers_ || tokens.empty()) return out; + + const int64_t n_full = (int64_t)tokens.size() / block_size_; + std::vector hs = chain_all(tokens, mm, n_full); + + /* Walk exactly as lookup does, and keep walking past the point it stopped for as long as the + * chain holds. EVERY off-device block in it is collected, not just the first run of them. + * + * STOPPING AT THE FIRST RESIDENT BLOCK PAST A GAP, on the reasoning that "the run this call is + * about has ended", would be wrong, and the way it is wrong is worth stating because the + * symptom does not look like a caching bug at all. A hit needs the WHOLE prefix: + * restoring blocks 0..99 and stopping leaves block 200 off-device, so the hit ends at 200 and + * everything above it is re-prefilled -- and WHICH blocks are off-device at the moment this + * runs depends on how far the maintenance pass has got. The same prompt then gets a different + * hit length on each restore. + * + * That is not only a lost prefix. The hit length is what the scheduler chunks the remaining + * prefill against, so two restores that recovered different amounts run different GEMM shapes + * over the same tokens -- and greedy decoding is tie-level sensitive to that (§19). The + * session's answer moves between restores, intermittently, with nothing wrong in the KV at + * all. Restoring the whole chain makes the hit length a property of the prompt. */ + for (int64_t b = 0; b < n_full; ++b) { + auto it = map_.find(hs[(size_t)b]); + if (it == map_.end()) break; + const int32_t* src = tokens.data() + b * block_size_; + if ((int64_t)it->second.tokens.size() != block_size_ || + std::memcmp(it->second.tokens.data(), src, (size_t)block_size_ * sizeof(int32_t)) != 0) + break; + if (chain) chain->push_back(hs[(size_t)b]); + if (tiers_->resident_off_device(hs[(size_t)b])) out.push_back(hs[(size_t)b]); + } + return out; +} + +void PrefixCache::drop_offdevice(const BlockHash& key) { + auto it = map_.find(key); + if (it == map_.end()) return; + /* NO release_block HERE, and that is the whole point. The entry has been off-device since it + * was demoted; the ids in it name blocks the pool reassigned long ago, so releasing them + * would free somebody else's context and serving them would hand it over. */ + if (it->second.in_lru) lru_.erase(it->second.lru); + map_.erase(it); + ++stats_.evictions; + /* AND THE SNAPSHOT KEYED BY THE SAME HASH. The tiers moved the two halves together, so they + * lose them together; leaving the index entry behind would leave a snapshot marked off-device + * whose bytes nobody holds, waiting to be promoted by something that no longer exists. */ + drop_snapshot(key); +} + +int PrefixCache::rebind(const BlockHash& key, const std::vector& blocks) { + auto it = map_.find(key); + if (it == map_.end()) return RAD_E_NOTFOUND; + if (blocks.size() != groups_.size()) return RAD_E_SHAPE; + for (int32_t b : blocks) if (b < 0) return RAD_E_INVAL; + /* THE RESERVATION'S REFERENCE BECOMES THE CACHE'S. KVManager::reserve_block left each block at + * a refcount of one with no sequence attached; assigning them here is the handover, and the + * cache's ordinary release path frees them from now on. Retaining and then releasing to "make + * it explicit" would be a round trip to the same number and would only obscure which reference + * is which. */ + Entry& e = it->second; + e.blocks = blocks; + for (size_t g = 0; g < groups_.size(); ++g) kv_->cache_reserved_block(groups_[g], blocks[g]); + if (!e.in_lru) { + lru_.push_back(key); + e.lru = std::prev(lru_.end()); + e.in_lru = true; + } + return RAD_OK; +} + +int64_t PrefixCache::evict_lru(int64_t n) { + int64_t done = 0; + while (done < n && !lru_.empty()) { + const BlockHash h = lru_.front(); + lru_.pop_front(); + auto it = map_.find(h); + if (it == map_.end()) continue; + Entry& e = it->second; + e.in_lru = false; + /* Every entry on the list holds its blocks, whatever the tiers are doing with it: one on + * its way to a host copy still holds the cache's references until the copy reports, and + * the report finds it forgotten and keeps nothing. */ + for (size_t g = 0; g < groups_.size(); ++g) + kv_->release_block(groups_[g], e.blocks[g]); + if (tiers_) { + /* THE HOST COPY HAS LANDED: the entry leaves VRAM and stays in the index. */ + if (tiers_->droppable(h)) { + tiers_->drop_commit(h); + ++stats_.drops; + ++done; + continue; + } + tiers_->forget(h); + } + map_.erase(it); + ++done; + ++stats_.evictions; + } + return done; +} + +int64_t PrefixCache::drop_clean() { + if (!tiers_ || !kv_) return 0; + drop_scratch_.clear(); + tiers_->take_clean(&drop_scratch_); + const uint64_t frees = kv_->seq_frees(); + if (frees != frees_seen_) { + frees_seen_ = frees; + drop_scratch_.insert(drop_scratch_.end(), drop_wait_.begin(), drop_wait_.end()); + drop_wait_.clear(); + } + int64_t n = 0; + for (const BlockHash& h : drop_scratch_) { + auto it = map_.find(h); + if (it == map_.end()) continue; + Entry& e = it->second; + e.drop_wait = false; + if (!e.in_lru || !tiers_->droppable(h)) continue; + /* A BLOCK A RUNNING SEQUENCE ALSO HOLDS WOULD FREE NOTHING, and its entry would then be + * off-device in the index while its bytes sat in VRAM under somebody else's table -- the + * next lookup would restore a second copy beside them. */ + bool shared = false; + for (size_t g = 0; g < groups_.size() && !shared; ++g) + shared = kv_->block_refcount(groups_[g], e.blocks[g]) > 1; + if (shared) { + if (!e.drop_wait) { e.drop_wait = true; drop_wait_.push_back(h); } + continue; + } + for (size_t g = 0; g < groups_.size(); ++g) + kv_->release_block(groups_[g], e.blocks[g]); + lru_.erase(e.lru); + e.in_lru = false; + ++stats_.drops; + tiers_->drop_commit(h); + ++n; + } + return n; +} + +/* THE REFCOUNT IS WHAT SEPARATES A CACHE FROM A LEAK. A block the cache indexes and a running + * sequence is reading is not memory the cache could give back; a block only the cache references + * is exactly what the next eviction frees. Nothing else distinguishes them -- both are `used`, + * both are in the index -- so the count is the manager's: it marks the blocks the cache holds and + * keeps the number of marked blocks at a reference count of one current as the counts move. + * + * ONE GROUP, FOR THE REASON THE POOL'S OWN TOKEN FIGURES ARE ONE GROUP'S: the paged groups share + * a token axis and an entry is one block in each of them, so counting every group would multiply + * the answer by the group count. + * + * OFF-DEVICE ENTRIES COUNT FOR NOTHING. A demoted entry released its blocks, and the mark went + * with the release; its bytes are on the host or on disk and it is holding none of the card. */ +int64_t PrefixCache::unshared_tokens() const { + if (!kv_ || groups_.empty() || block_size_ <= 0) return 0; + return kv_->cache_only_blocks(groups_[0]) * block_size_; +} + +void PrefixCache::clear() { + for (auto& kv : map_) { + if (kv.second.in_lru) + for (size_t g = 0; g < groups_.size(); ++g) + kv_->release_block(groups_[g], kv.second.blocks[g]); + if (tiers_) tiers_->forget(kv.first); + ++stats_.evictions; + } + map_.clear(); + lru_.clear(); + drop_wait_.clear(); +} + +std::vector PrefixCache::lru_order() const { + return std::vector(lru_.begin(), lru_.end()); +} + +/* ------------------------------------------------------------------ checkpoints */ + +int64_t PrefixCache::next_checkpoint_after(int64_t pos) const { + if (interval_ <= 0) return -1; + if (pos < 0) pos = 0; + return (pos / interval_ + 1) * interval_; +} + +std::vector PrefixCache::checkpoints(uint64_t session) const { + std::vector out; + auto it = ck_by_session_.find(session); + if (it == ck_by_session_.end()) return out; + for (const BlockHash& h : it->second) { + auto e = ck_by_prefix_.find(h); + if (e != ck_by_prefix_.end()) out.push_back(e->second.pos); + } + std::sort(out.begin(), out.end()); + return out; +} + +int64_t PrefixCache::retain(uint64_t session) { + auto it = ck_by_session_.find(session); + if (it == ck_by_session_.end()) return 0; + + /* DEVICE-RESIDENT SNAPSHOTS ONLY. This policy exists to spend a fixed number of --checkpoint- + * slots well, and it runs when that pool is exhausted. A snapshot the idle tiers hold occupies + * none of it, so retiring one would free nothing here and would cost a session the state it + * was moved off the device precisely in order to keep. Tiered bytes are bounded by the tiers' + * own caps, oldest first, which is the right policy for the resource they actually spend. + * + * It stays in `kept` rather than being skipped, or the session index would forget it. */ + std::vector> all; + std::vector kept; + for (const BlockHash& h : it->second) { + auto e = ck_by_prefix_.find(h); + if (e == ck_by_prefix_.end()) continue; + if (e->second.off_device) { kept.push_back(h); continue; } + all.push_back({e->second.pos, h}); + } + std::sort(all.begin(), all.end(), + [](const auto& a, const auto& b) { return a.first < b.first; }); + + std::vector pos; + for (const auto& a : all) pos.push_back(a.first); + std::vector keep; + policy_->select(pos, &keep); + + int64_t freed = 0; + for (const auto& a : all) { + if (std::binary_search(keep.begin(), keep.end(), a.first)) { kept.push_back(a.second); continue; } + auto e = ck_by_prefix_.find(a.second); + if (e != ck_by_prefix_.end()) { + retire_ckpt(e); + ++freed; + ++stats_.ckpt_evictions; + } + } + /* ERASE THE SESSION WHEN NOTHING IS LEFT OF IT, and that is not tidiness. `session` is a + * REQUEST id, so without an eraser this map gains an entry for every request that ever writes + * a checkpoint: the vector empties, here and in the eviction below, and the key stays. The + * cost is not the bytes -- it is that the loop in reserve_checkpoint walks EVERY key on every + * allocation failure, which is the one path this cache exists to relieve. */ + if (kept.empty()) { ck_by_session_.erase(it); return freed; } + it->second = std::move(kept); + return freed; +} + +int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHash& prefix, + int32_t* slot_out) { + if (!enabled_ || !has_linear_) return RAD_E_UNSUPPORTED; + if (!slot_out) return RAD_E_INVAL; + if (interval_ <= 0 || pos <= 0 || pos % interval_ != 0) { + RAD_ERR("checkpoint at %lld is not on a %lld-token boundary; the scheduler splits chunks " + "at the interval precisely so this cannot happen (spec §7.3)", + (long long)pos, (long long)interval_); + return RAD_E_INVAL; + } + auto existing = ck_by_prefix_.find(prefix); + if (existing != ck_by_prefix_.end()) { + /* A SNAPSHOT THE TIERS HOLD IS NOT ONE THIS CALL CAN HAND BACK. Returning its -1 slot + * would look to the scheduler exactly like a refusal (it tests `cs >= 0`) and the chunk + * would silently stop checkpointing; handing back a slot that is not in the pool would be + * worse. The state is about to be recomputed anyway -- that is what a reservation at this + * prefix means -- so the tiered copy is retired and a fresh slot allocated below. */ + /* NOR ONE A COPY IS READING. The save that follows this reservation writes the slot on + * the compute stream while the copy reads it on the transfer stream, and the host would + * keep a snapshot that is half of each. A fresh slot costs one allocation. */ + if (!existing->second.off_device && + !(tiers_ && tiers_->snapshot_reading(prefix))) { + *slot_out = existing->second.slot; + return RAD_OK; + } + const uint64_t vs = existing->second.session; + retire_ckpt(existing); + auto sit = ck_by_session_.find(vs); + if (sit != ck_by_session_.end()) { + sit->second.erase(std::remove(sit->second.begin(), sit->second.end(), prefix), + sit->second.end()); + if (sit->second.empty()) ck_by_session_.erase(sit); + } + } + + int32_t slot = -1; + if (kv_->alloc_checkpoint(&slot) < 0) { + /* Budgeted retention: run the policy over every session before giving up. The tip of each + * session survives it by construction, because that is what an appending agent transcript + * needs (spec §7.3). + * + * Over a SNAPSHOT of the keys, because retain() erases a session it empties and a + * range-for over the map would be iterating a container it is erasing from. */ + std::vector sessions; + sessions.reserve(ck_by_session_.size()); + for (const auto& s : ck_by_session_) sessions.push_back(s.first); + for (uint64_t s : sessions) retain(s); + if (kv_->alloc_checkpoint(&slot) < 0) { + /* Still nothing. Drop the globally least-recently-used snapshot, PREFERRING a non-tip + * one -- but falling back to a tip rather than giving up. + * + * MAKING A TIP UNEVICTABLE OUTRIGHT WEDGES THE POOL PERMANENTLY. A session here is a + * REQUEST id (PCBinding passes r.id), and a finished request's checkpoints are meant + * to outlive it -- they are keyed by chained prefix hash, which is exactly how the + * next turn of an agent transcript finds them. So every request that writes a + * checkpoint leaves a tip behind and nothing ever retires one: after + * --checkpoint-slots such requests, every slot holds a dead session's tip and this + * would return RAD_E_FULL for the life of the process. The scheduler ignores the + * failure (scheduler.cpp: `>= 0 && cs >= 0`), so linear prefix caching would simply + * stop, with nothing in the log. + * + * Two passes rather than one comparison, because "prefer a non-tip" is a tier and not + * a tiebreak: the oldest tip must lose to the newest non-tip. */ + const Ckpt* victim = nullptr; + const Ckpt* tip_victim = nullptr; + for (const auto& kvp : ck_by_prefix_) { + /* A TIERED SNAPSHOT IS NOT A CANDIDATE, because evicting it frees nothing HERE. + * Its device slot went back to the pool when the tiers took the bytes, so picking + * it as the victim would retire a usable snapshot and then fail the retry anyway. */ + if (kvp.second.off_device) continue; + auto sit = ck_by_session_.find(kvp.second.session); + bool is_tip = false; + if (sit != ck_by_session_.end()) { + int64_t tip = -1; + for (const BlockHash& h : sit->second) { + auto e = ck_by_prefix_.find(h); + if (e != ck_by_prefix_.end()) tip = std::max(tip, e->second.pos); + } + is_tip = (kvp.second.pos == tip); + } + const Ckpt*& best = is_tip ? tip_victim : victim; + if (!best || kvp.second.used < best->used) best = &kvp.second; + } + if (!victim) victim = tip_victim; + if (!victim) return RAD_E_FULL; + BlockHash vh = victim->prefix; + uint64_t vs = victim->session; + /* A VICTIM THE TIERS HOLD A COPY OF IS DETACHED, NOT LOST. The slot goes back all the + * same; the index entry stays, and the session's next restore brings the state back + * with its blocks instead of replaying every recurrent layer from an older point. */ + if (tiers_ && tiers_->snapshot_backed(vh)) { + (void)detach_snapshot(vh); + tiers_->snapshot_detached(vh); + if (kv_->alloc_checkpoint(&slot) < 0) return RAD_E_FULL; + Ckpt c; + c.session = session; c.pos = pos; c.prefix = prefix; c.slot = slot; + c.used = ++clock_; + ck_by_prefix_.emplace(prefix, c); + ck_by_session_[session].push_back(prefix); + *slot_out = slot; + return RAD_OK; + } + retire_ckpt(ck_by_prefix_.find(vh)); + ++stats_.ckpt_evictions; + auto sit = ck_by_session_.find(vs); + if (sit != ck_by_session_.end()) { + sit->second.erase(std::remove(sit->second.begin(), sit->second.end(), vh), + sit->second.end()); + if (sit->second.empty()) ck_by_session_.erase(sit); + } + if (kv_->alloc_checkpoint(&slot) < 0) return RAD_E_FULL; + } + } + + Ckpt c; + c.session = session; c.pos = pos; c.prefix = prefix; c.slot = slot; c.used = ++clock_; + ck_by_prefix_.emplace(prefix, c); + ck_by_session_[session].push_back(prefix); + *slot_out = slot; + return RAD_OK; +} + +void PrefixCache::commit_checkpoint(const BlockHash& prefix) { + auto it = ck_by_prefix_.find(prefix); + if (it == ck_by_prefix_.end()) return; + it->second.valid = true; + /* THE TIERS LEARN THE SNAPSHOT HERE, for the same reason note_used tells them the block ids: + * a demotion has to know what to move and this index is the only place it is written down. + * Before the commit there is nothing to move -- the slot still holds the previous tenant's + * state -- so this is also the earliest moment at which telling them would be true. */ + if (tiers_) tiers_->note_snapshot(prefix, it->second.slot, it->second.pos); +} + + +/* ------------------------------------------------------------------ the linear half of a session */ + +void PrefixCache::retire_ckpt(std::unordered_map::iterator it) { + if (it == ck_by_prefix_.end()) return; + /* THE TIERS ARE ASKED FIRST, because they may be reading the slot: a copy to host memory in + * flight out of a slot the pool then decommits reads a page that is no longer mapped. When + * one is, the tiers keep the slot and hand it back once the copy has reported. */ + const bool held = tiers_ && tiers_->release_snapshot(it->first); + if (it->second.slot >= 0 && !held) kv_->free_checkpoint(it->second.slot); + /* TOLD EITHER WAY, AND NOT ONLY WHEN THE TIERS HOLD THE BYTES. They also remember a snapshot's + * DEVICE slot -- note_snapshot records it at commit, because a demotion has to know what to + * copy and this index is the only place it is written down. Freeing that slot here without + * saying so leaves the tiers naming a slot the pool has since given to another session, and + * the next demotion copies THAT session's recurrent state and restores it as this one's. The + * text that comes back is fluent, deterministic and about the wrong conversation, which is + * the exact failure the whole tier design is arranged to make impossible. + * + * Not reachable from the tiers' own drop sink, which erases the index entry through + * drop_snapshot instead -- so this never calls back into a record being erased. */ + ck_by_prefix_.erase(it); +} + +int PrefixCache::detach_snapshot(const BlockHash& key) { + auto it = ck_by_prefix_.find(key); + if (it == ck_by_prefix_.end()) return RAD_E_NOTFOUND; + if (it->second.off_device) return RAD_OK; /* already theirs */ + if (it->second.slot >= 0) kv_->free_checkpoint(it->second.slot); + it->second.slot = -1; + it->second.off_device = true; + /* NOT SERVABLE FROM HERE ON, which is the same state a reserved-but-unwritten snapshot is in + * and is handled by the same branch in lookup(). A hit that reaches this position simply walks + * back to an older checkpoint, or to none -- shorter, never wrong. */ + it->second.valid = false; + return RAD_OK; +} + +int PrefixCache::reattach_snapshot(const BlockHash& key, int32_t slot) { + auto it = ck_by_prefix_.find(key); + if (it == ck_by_prefix_.end()) return RAD_E_NOTFOUND; + if (slot < 0) return RAD_E_INVAL; + /* A SLOT THIS ENTRY DID NOT ASK FOR IS STILL ITS OWN. The promotion allocated it and filled it + * from the tier copy of THIS key's state, so the identity that matters -- which prefix the + * bytes describe -- is carried by the key and not by the slot number it happened to get. */ + it->second.slot = slot; + it->second.off_device = false; + it->second.valid = true; + it->second.used = ++clock_; + return RAD_OK; +} + +bool PrefixCache::free_checkpoint_for_restore() { + if (!tiers_) return false; + const Ckpt* victim = nullptr; + for (const auto& kvp : ck_by_prefix_) { + const Ckpt& c = kvp.second; + if (c.off_device || c.slot < 0 || !c.valid) continue; + if (victim && c.used >= victim->used) continue; + if (std::find(handed_.begin(), handed_.end(), kvp.first) != handed_.end()) continue; + if (!tiers_->snapshot_backed(kvp.first)) continue; + victim = &c; + } + if (!victim) return false; + const BlockHash vh = victim->prefix; + (void)detach_snapshot(vh); + tiers_->snapshot_detached(vh); + return true; +} + +void PrefixCache::drop_snapshot(const BlockHash& key) { + auto it = ck_by_prefix_.find(key); + if (it == ck_by_prefix_.end()) return; + const uint64_t session = it->second.session; + /* No release_snapshot on this path: the tiers are the caller and the bytes are already gone. + * Telling them to free what they just lost would double-free the arena slot. */ + if (it->second.slot >= 0) kv_->free_checkpoint(it->second.slot); + ck_by_prefix_.erase(it); + ++stats_.ckpt_evictions; + auto sit = ck_by_session_.find(session); + if (sit == ck_by_session_.end()) return; + sit->second.erase(std::remove(sit->second.begin(), sit->second.end(), key), sit->second.end()); + if (sit->second.empty()) ck_by_session_.erase(sit); +} + +int64_t PrefixCache::snapshots_off_device() const { + int64_t n = 0; + for (const auto& kvp : ck_by_prefix_) if (kvp.second.off_device) ++n; + return n; +} +} /* namespace rad */ diff --git a/core/mem/prefix.h b/core/mem/prefix.h new file mode 100644 index 00000000..e3e51d43 --- /dev/null +++ b/core/mem/prefix.h @@ -0,0 +1,407 @@ +/* prefix.h -- prefix caching (spec §7.3). TWO mechanisms, because full attention and linear + * attention cannot share one. + * + * FULL ATTENTION: content-hashed blocks with a CHAINED hash, so a block's identity includes its + * whole prefix. LRU eviction, copy-on-write on fork, and multimodal inputs hashed BY CONTENT -- + * an image is a cache hit, because the hash is taken over the EMBEDDING span rather than the + * image bytes. + * + * LINEAR ATTENTION: a state checkpoint. A GDN layer's recurrent state at position N depends on + * all of 0..N and is one fixed-size object per sequence -- 32 heads of 128x128 fp32 is 2 MiB a + * layer, roughly 96 MiB across the 48 linear layers of a Qwen3-Next. Snapshotting that per 16-token + * block is not affordable at any block count. We take vLLM's `--mamba-cache-mode align` mechanism + * and change two things: + * + * (a) THE CHECKPOINT INTERVAL IS DECOUPLED FROM THE ATTENTION BLOCK SIZE. vLLM inflates the + * attention block to match the mamba page -- 528 tokens for Qwen3.5, 2240 for the 35B-A3B -- + * and since prefix caching is block-granular, every prompt shorter than that gets a 0% hit + * rate on ATTENTION as well. We could not inflate the attention block even if we wanted to: + * §7.2 takes it from the resolved kernel and libr4d's paged attention is compiled for 16. + * So attention caches at 16-token granularity and Config::checkpoint_interval is a separate, + * much larger number. A hit landing BETWEEN checkpoints reuses the attention blocks and + * replays only the linear layers forward from the last checkpoint. That is what CacheHit's + * two token counts are: `n_attn_tokens` is free, `[n_linear_tokens, n_attn_tokens)` costs a + * linear-layers-only forward pass, and the rest is an ordinary prefill. + * + * (b) CHECKPOINTS ARE TAKEN DELIBERATELY, NOT OPPORTUNISTICALLY. vLLM writes one only when a + * scheduler step happens to end on a boundary, which is why a checkpoint landing in + * request-unique tokens silently drops caching to zero. Our scheduler owns chunk boundaries + * (spec §7.1) and splits a chunk AT the interval, so one is always written. The cost is an + * occasional short chunk; the benefit is that hit rate is a property of the workload rather + * than of scheduling luck. `next_checkpoint_after()` is what the scheduler splits on. + * + * ============================== WHAT IT COSTS TO HOLD, AND WHEN IT STOPS WORKING ============== + * + * The cache takes a KV REFERENCE on every block it indexes, so a finished sequence's blocks stay + * held for the next turn. That is the whole point -- and it means the pool's demand is the number + * of LIVE SESSIONS, not of running requests. Size it the other way and the failure is not graceful. + * + * THE THRESHOLD IS POOL UTILISATION, and it is a CLIFF rather than a slope. Below roughly 75% + * utilisation the cache is whole; by around 81% half of it is gone; once the sessions no longer + * fit at all the cache is not degraded but DEFEATED -- each turn evicts the prefixes the next turn + * wants, so every turn re-prefills its whole context and the hit rate is zero. The generated text + * is unaffected either way; the only difference is whether the prefixes still exist when the next + * turn asks for them, and that difference is one to two orders of magnitude of time to first + * token. Size the cache so live sessions fit with room to spare -- a context of T tokens occupies + * roughly 1.8 x T pool-tokens across the paged groups -- and keep --expert-vs-cache-ratio on the + * safe side of that. + * + * WHAT TO WATCH: `kv_util` (/stats, or vllm:kv_cache_usage_perc) is the predictor, and + * `radiance:prefix_cache_evictions_total` is the event -- the hit rate is neither, because it only + * falls once a prefix that would have been reused is already gone. + */ +#pragma once +#include "mem/kv.h" +#include "rad_core.h" + +#include +#include +#include +#include +#include +#include + +namespace rad { + +class IdleTiers; + +/* ------------------------------------------------------------------ block identity */ +/* 128 bits, chained. A block's identity includes its whole prefix, so two identical 16-token spans + * sitting at the same offset under different prefixes are DIFFERENT blocks and cannot be served + * for one another. That is the property; the width is only there to make an accidental collision + * improbable, and the stored token ids below make it impossible. */ +struct BlockHash { + uint64_t hi = 0, lo = 0; + bool operator==(const BlockHash& o) const { return hi == o.hi && lo == o.lo; } + bool operator!=(const BlockHash& o) const { return !(*this == o); } + bool valid() const { return hi != 0 || lo != 0; } + std::string str() const; +}; + +struct BlockHashHash { + size_t operator()(const BlockHash& h) const { return (size_t)(h.lo ^ (h.hi * 0x9e3779b97f4a7c15ull)); } +}; + +/* A multimodal span, keyed BY CONTENT. The placeholder token ids inside an image span are + * identical for every image, so hashing token ids alone would serve one request another's picture. + * The hash is taken over the ENCODER OUTPUT for the span -- the embedding bytes -- not over the + * image file, so a re-encode of the same picture at the same resolution hits even when the JPEG + * differs byte-for-byte, and two different pictures never alias (spec §7.3, §11). + * + * The cost, stated: a non-deterministic encoder produces different embedding bytes for the same + * image and therefore MISSES. A miss is the safe direction; the alternative -- hashing the image + * bytes -- gets a hit and the wrong embeddings when the preprocessing changes. */ +struct MMContentKey { + int32_t tok_begin = 0; /* [begin, end) in prompt-token coordinates */ + int32_t tok_end = 0; + uint64_t hash = 0; +}; +uint64_t mm_content_hash(const void* embedding, int64_t bytes); + +/* The chained hash of one block. `parent` is the previous block's hash (a zeroed BlockHash for + * block 0), `block_begin` is the block's first token position. */ +BlockHash chain_block_hash(const BlockHash& parent, const int32_t* toks, int32_t n, + const MMContentKey* mm, int32_t n_mm, int64_t block_begin); + +/* ------------------------------------------------------------------ the split lookup */ +struct CacheHit { + int32_t n_attn_tokens = 0; /* attention KV reused directly, always a whole block multiple */ + int32_t n_linear_tokens = 0; /* linear state reused; <= n_attn_tokens, a checkpoint multiple */ + int32_t checkpoint_slot = -1; /* the snapshot holding that state, -1 if none */ +}; + +/* ------------------------------------------------------------------ retention policy */ +/* Spec §19.1 records geometric backoff as a GUESS until there is a workload to measure. It is + * therefore a policy OBJECT and not an if-statement, so replacing it is writing a class rather + * than rewriting the cache. Two alternatives ship alongside it for exactly that reason. */ +class CheckpointPolicy { +public: + virtual ~CheckpointPolicy() = default; + virtual const char* name() const = 0; + /* `positions` ascending, one entry per checkpoint the session holds. Fill `keep` with the + * subset to retain. THE TIP -- positions.back() -- MUST ALWAYS BE KEPT, because an appending + * agent transcript is what this cache is for and the tip is the only thing it needs. */ + virtual void select(const std::vector& positions, std::vector* keep) const = 0; +}; + +/* Keep the tip, then 1x, 2x, 4x, 8x checkpoints back. Bounds the snapshot count at log(n) and the + * recompute at one interval-doubling, which is the trade §19.1 describes. Distances are counted in + * CHECKPOINTS rather than in tokens: the scheduler splits chunks at the interval so the spacing is + * uniform, and counting in checkpoints stays correct if it ever is not. */ +class GeometricBackoff final : public CheckpointPolicy { +public: + const char* name() const override { return "geometric-backoff"; } + void select(const std::vector& positions, std::vector* keep) const override; +}; + +/* The two obvious ends of the trade, kept so a measurement can be run against them. */ +class KeepTipOnly final : public CheckpointPolicy { +public: + const char* name() const override { return "tip-only"; } + void select(const std::vector& positions, std::vector* keep) const override; +}; +class KeepAll final : public CheckpointPolicy { +public: + const char* name() const override { return "keep-all"; } + void select(const std::vector& positions, std::vector* keep) const override; +}; + +/* ------------------------------------------------------------------ the cache */ +class PrefixCache { +public: + /* `kv` must already be configured: the cache holds a KV-manager reference on every block it + * indexes, which is the invariant that makes a hit safe -- a block in the map is never in the + * free list, so it can never be handed to another sequence underneath a cache entry. + * + * `checkpoint_interval` IS THE SCHEDULER'S RESOLVED INTERVAL, NOT cfg.checkpoint_interval. + * The two are different numbers: chunk_geometry_resolve rounds the operator's request UP to + * the chunk quantum so that "split at the interval" is always also a legal chunk split. If + * this cache read the raw config value while the scheduler split on the rounded one, every + * checkpoint would be refused by reserve_checkpoint -- with an error saying the scheduler + * splits at the interval precisely so this cannot happen -- and restore() would walk back in + * the wrong stride looking for snapshots nothing had written. It is a parameter rather than a + * config read so that there is one place the number comes from. */ + int configure(const Config& cfg, KVManager* kv, int64_t checkpoint_interval); + bool enabled() const { return enabled_; } + int64_t block_size() const { return block_size_; } + int64_t checkpoint_interval() const { return interval_; } + const std::vector& cached_groups() const { return groups_; } + std::string report() const; + + /* AFTER configure(), which installs the one Config::checkpoint_policy names. This is the + * in-process override -- a policy that is not one of the three, or one a test wants to + * substitute -- and calling it first would be undone. */ + void set_policy(std::unique_ptr p); + const CheckpointPolicy& policy() const { return *policy_; } + + /* ---------------- full attention ---------------- */ + /* Longest cached prefix, in whole blocks, plus the checkpoint that covers the linear state + * for a prefix of it. `blocks_out`, when given, receives the block ids per cached group, in + * cached_groups() order, ready for KVManager::adopt(). + * + * NEVER returns the whole prompt: at least one token must remain for the step to compute a + * logit from, so a full hit is backed off by one block. That is not a subtlety the caller + * should have to know. */ + CacheHit lookup(const std::vector& tokens, + const std::vector& mm, + std::vector>* blocks_out = nullptr) const; + + /* Publish the whole blocks a sequence just filled. `blocks[i]` is the block table of + * cached_groups()[i]. Takes a KV reference on every newly indexed block. */ + int insert(uint64_t session, + const std::vector& tokens, + const std::vector& mm, + const std::vector>& blocks, + int64_t n_tokens); + + /* Drop the least recently used entries, releasing their KV references. Returns how many were + * dropped. Blocks a live sequence still holds stay allocated -- releasing the cache's + * reference is not freeing the block. + * + * A CLEAN ENTRY IS RELEASED AND KEPT. With the idle tiers on, an entry whose host copy has + * landed loses nothing by leaving VRAM, so pressure on the pool moves it to the host tier + * instead of forgetting it: the next turn restores it rather than re-prefilling it. Only an + * entry with no host copy yet is lost. Either way the blocks go back to the pool. */ + int64_t evict_lru(int64_t n_entries); + /* GIVE UP EVERY VRAM COPY THAT CAN GO FOR NOTHING: the entries whose host copy has landed and + * that no running sequence is still reading. Called when the memory has a better use -- the + * expert slab's loan -- and returns how many entries left VRAM. An entry a sequence still + * holds would free nothing, so it is asked about again once a sequence has let go of blocks. */ + int64_t drop_clean(); + int64_t size() const { return (int64_t)map_.size(); } + /* How many entries hold blocks in the pool, as opposed to only a copy off the card. */ + int64_t resident() const { return (int64_t)lru_.size(); } + /* HOW MUCH OF THE POOL THIS CACHE IS HOLDING ON ITS OWN, in tokens of context. The entry + * count cannot answer that: an entry's blocks are SHARED with every live sequence that hit on + * them, and on a server carrying long conversations that is most of the index -- so an index + * size read as "memory the cache is keeping back" says a request reading its own context is + * the cache refusing to release it. What an eviction would actually free is the blocks + * nothing else references, which is what this counts. */ + int64_t unshared_tokens() const; + /* Forget every entry, in VRAM or off it, and give back whatever the tiers held for them. */ + void clear(); + /* Diagnostic: the LRU order, oldest first. */ + std::vector lru_order() const; + + /* ---------------- idle session tiers (core/mem/kvtier.h) ---------------- */ + /* Installed after configure() when the tiers are on. A null pointer is the whole of the "off" + * path: every call site below is guarded, and with no tiers the cache is a plain VRAM-only + * prefix cache. */ + void set_tiers(IdleTiers* t) { tiers_ = t; } + + /* THE CHAIN THIS PROMPT WOULD HIT IF THE TIERS GAVE IT BACK, in order, starting at the block + * `lookup` stopped on. The caller promotes them and asks again; an empty answer means the + * prefix stopped for an ordinary reason -- a miss, or a token compare -- and no amount of + * restoring would lengthen it. + * + * It is a separate call rather than something lookup does because lookup is const and has no + * device: a promotion allocates blocks and runs a scatter, which is the engine's to do + * between steps and not something a cache query may trigger under the caller. */ + /* `chain`, when given, receives every key the walk matched, wherever it is -- what the tiers + * need to see whether any of it is still being read off disk (IdleTiers::plan_fetch). */ + std::vector restorable_from(const std::vector& tokens, + const std::vector& mm, + std::vector* chain = nullptr) const; + + /* THE TIERS LOST THE BYTES. Erase the entry WITHOUT releasing blocks: an off-device entry + * owns none -- demotion released them -- and its recorded ids belong to whoever the pool gave + * them to since. Releasing those would free another sequence's block; leaving the entry in + * the map would serve them. Installed as IdleTiers::set_drop_sink. */ + void drop_offdevice(const BlockHash& key); + + /* A restore finished: the entry's blocks live at these ids now. The cache takes a reference on + * each, because the restore holds them only as raw reservations (KVManager::reserve_block) and + * this is where they become cache-held blocks with the usual invariant. */ + int rebind(const BlockHash& key, const std::vector& blocks); + + + /* ---------------- the linear half of an idle session ---------------- + * + * ON A HYBRID MODEL THE BLOCKS ARE ONLY HALF OF WHAT A SESSION NEEDS BACK. The other half is + * the recurrent state, and it lives in a CHECKPOINT SLOT: a device-resident object of + * KVManager::checkpoint_bytes(), of which there are --checkpoint-slots IN TOTAL for the whole + * server. Eight by default, against the six or seven a single 200K session retains under + * geometric backoff -- so a second session evicts the first's snapshots, tip included. + * + * Tiering the blocks and leaving the snapshot behind therefore gets the trade backwards: it + * frees the plentiful resource and holds on to the scarce one. And what the session loses is + * not part of its hit, it is ALL of it -- the scheduler clamps reuse to the last checkpoint a + * hit can reach, because RadBatch carries one query length for every KV group and the linear + * layers cannot be replayed over a longer range than the attention ones (core/sched/ + * scheduler.cpp, admit_one). A restored session with no reachable snapshot reuses zero tokens + * and re-prefills its whole transcript. The blocks without the state are not a partial win; + * they are unusable. + * + * So a snapshot moves with the blocks whose hash it is keyed by, and these calls are the + * cache's whole part in that. The bytes are the engine's to move. */ + + /* Its bytes are on another tier now: give the device slot back and stop offering it. The index + * entry STAYS, because that is what a promotion puts the snapshot back into, and an entry + * whose state is not in the pool is exactly the `valid` flag's existing meaning -- lookup + * already walks past one and falls back to an older position. */ + int detach_snapshot(const BlockHash& key); + /* And back again, into a slot the caller has already filled. */ + int reattach_snapshot(const BlockHash& key, int32_t slot); + /* A DEVICE CHECKPOINT SLOT FOR A RESTORE. The pool is --checkpoint-slots deep for the whole + * server, and it is full whenever as many sessions have run since; a session restored then + * would get its blocks back and replay every recurrent layer from an older point, because its + * state has nowhere to land. One slot is freed by detaching the least recently used snapshot + * the tiers hold a copy of -- which the next restore of THAT session brings back -- and never + * one whose only copy is the slot, and never one a lookup has handed out since the step began: + * that request reads the slot in this step's forward, and a restore writes it before the + * forward runs. True when a slot was freed. */ + bool free_checkpoint_for_restore(); + /* A step's admissions begin. The snapshots the last step's lookups handed out have been read + * by its forward, which committed before this step was planned. */ + void begin_step() { handed_.clear(); } + /* The tiers lost it -- a capacity drop, a failed promotion, or an entry they were told to + * forget. Erase the index entry; there is no device slot to give back. */ + void drop_snapshot(const BlockHash& key); + /* How many snapshots the index holds whose bytes the tiers have. Reported rather than derived + * because it is the number that says whether hybrid tiering is doing anything at all: a + * session can move its whole chain off the device and still be re-prefilling its linear + * layers from zero on every hit, and nothing else distinguishes the two. */ + int64_t snapshots_off_device() const; + /* ---------------- linear checkpoints ---------------- */ + /* The next position strictly after `pos` at which the scheduler must split a chunk so that a + * checkpoint lands on a boundary (spec §7.1, §7.3). */ + int64_t next_checkpoint_after(int64_t pos) const; + bool is_checkpoint(int64_t pos) const { return interval_ > 0 && pos > 0 && pos % interval_ == 0; } + + /* Reserve a snapshot slot for `session` at `pos`. Applies the retention policy when the slot + * pool is exhausted, never evicting a session tip. RAD_E_FULL when even that is not enough. */ + int reserve_checkpoint(uint64_t session, int64_t pos, const BlockHash& prefix, + int32_t* slot_out); + /* The state named by `prefix` is now IN its slot. Until this is called the reservation is only + * a promise and lookup() will not offer it -- see Ckpt::valid. */ + void commit_checkpoint(const BlockHash& prefix); + /* Every checkpoint of a session, ascending. */ + std::vector checkpoints(uint64_t session) const; + /* Apply the retention policy to one session now. Returns how many snapshots were released. + * A session left holding nothing is forgotten -- see the note at the definition for why that + * matters more than the bytes. */ + int64_t retain(uint64_t session); + + /* How many sessions the checkpoint index still knows about. Exposed because it is an + * INVARIANT rather than a statistic: a session is a request id, so this must track the + * sessions holding a live snapshot and not the number of requests the process has served. */ + int64_t sessions_tracked() const { return (int64_t)ck_by_session_.size(); } + + struct Stats { + int64_t lookups = 0, block_hits = 0, block_misses = 0; + int64_t ckpt_hits = 0, ckpt_misses = 0; + int64_t evictions = 0, ckpt_evictions = 0; + /* Entries whose VRAM copy was given up with their host copy kept. Not evictions: nothing + * was lost, and a counter that mixed the two would read a working tier as a thrashing + * cache. */ + int64_t drops = 0; + }; + const Stats& stats() const { return stats_; } + +private: + struct Entry { + std::vector blocks; /* one per cached group, in groups_ order */ + std::vector tokens; /* the block's token ids, compared on hit */ + /* ON THE LRU EXACTLY WHILE THE CACHE HOLDS THE BLOCKS. An entry whose bytes are only off + * the card owns no block, so it has nothing an eviction could free, and walking past it + * under pressure would erase the tier's copy to make room it never occupied. `lru` is + * valid only while this is set. */ + bool in_lru = false; + bool drop_wait = false; /* in drop_wait_: clean, but a sequence still reads it */ + std::list::iterator lru; + }; + struct Ckpt { + uint64_t session = 0; + int64_t pos = 0; + BlockHash prefix; + int32_t slot = -1; + uint64_t used = 0; + /* HAS THE STATE ACTUALLY BEEN WRITTEN INTO THE SLOT YET. reserve_checkpoint runs when the + * scheduler PLANS the chunk; the copy happens after the step that computes the state. A + * lookup between those two points would hand out a slot holding the previous tenant's + * history, which is the exact failure this whole mechanism exists to prevent. */ + bool valid = false; + /* ARE THE BYTES STILL IN THE POOL. The idle tiers move a snapshot along with the blocks + * it is keyed by, and `slot` is -1 for the whole time they hold it. Kept as its own flag + * rather than inferred from the slot so that the two reasons a snapshot cannot be served + * -- not written yet, and not here -- stay distinguishable in a debugger and in a report. */ + bool off_device = false; + }; + + std::vector chain_all(const std::vector& tokens, + const std::vector& mm, + int64_t n_blocks) const; + void touch(const BlockHash& h) const; + /* Retire one snapshot whatever tier holds its bytes: a device slot goes back to the pool, and + * tiered bytes go back to the tiers. One place, because three call sites that each remembered + * to check `off_device` would be three places to forget. The session index is the caller's, + * since every caller is already rebuilding or erasing it. */ + void retire_ckpt(std::unordered_map::iterator it); + + KVManager* kv_ = nullptr; + IdleTiers* tiers_ = nullptr; + bool enabled_ = false; + int64_t block_size_ = 0; + int64_t interval_ = 0; + std::vector groups_; /* paged groups this cache indexes */ + bool has_linear_ = false; + + mutable std::unordered_map map_; + mutable std::list lru_; /* front = oldest; resident entries only */ + /* CLEAN ENTRIES A SEQUENCE WAS STILL READING when drop_clean last looked, and the pool's count + * of freed sequences at that moment. Only a sequence letting go of blocks can make one of them + * droppable, so they are looked at again only when that count has moved. */ + std::vector drop_wait_; + std::vector drop_scratch_; + uint64_t frees_seen_ = 0; + mutable std::unordered_map ck_by_prefix_; + std::unordered_map> ck_by_session_; + /* Snapshots lookup handed out since begin_step: not a restore's to take (free_checkpoint_for_restore). */ + mutable std::vector handed_; + mutable uint64_t clock_ = 0; + std::unique_ptr policy_; + mutable Stats stats_; + std::string report_; +}; + +} /* namespace rad */ diff --git a/core/mem/sstier.cpp b/core/mem/sstier.cpp new file mode 100644 index 00000000..e3e01dad --- /dev/null +++ b/core/mem/sstier.cpp @@ -0,0 +1,536 @@ +/* sstier.cpp -- see sstier.h. IT HOLDS CONVERSATION CONTENT ON DISK, UNENCRYPTED. */ +#include "mem/sstier.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace rad { + +/* The device layer's alignment, not a second opinion about it: every slot, every header region and + * every staging buffer here is a multiple of it, which is what keeps every transfer on + * DirectFile's aligned fast path and its bounce buffer unallocated. */ +static constexpr int64_t kAlign = DirectFile::alignment(); + +static void* alloc_aligned(int64_t bytes) { + void* p = nullptr; + if (posix_memalign(&p, (size_t)kAlign, (size_t)align_up(bytes, kAlign)) != 0) return nullptr; + return p; +} +static constexpr uint32_t kMagicBlock = 0x4b4c4252u; /* "RBLK" */ +static constexpr uint32_t kMagicCkpt = 0x504b4352u; /* "RCKP" */ + +struct SSSlotHeader { + uint32_t magic; + uint32_t n_tokens; + uint64_t fingerprint; + uint64_t payload_bytes; + uint64_t key_hi, key_lo; + int64_t pos; /* checkpoint: the token position it restores to; 0 for a block */ + uint64_t reserved[3]; +}; + +/* ------------------------------------------------------------------ TokenBucket */ + +const char* ssd_consumer_name(SSDConsumer c) { + switch (c) { + case SSDConsumer::PrefixCache: return "prefix-cache"; + case SSDConsumer::WeightTier: return "weight-tier"; + default: return "?"; + } +} + +static int64_t now_ns() { + return std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()).count(); +} + +void TokenBucket::configure(int64_t bytes_per_sec, int64_t burst_bytes) { + std::lock_guard lk(mu_); + rate_ = bytes_per_sec > 0 ? bytes_per_sec : 0; + burst_ = burst_bytes > 0 ? burst_bytes : rate_; + tokens_ = (double)burst_; + last_ns_ = now_ns(); +} + +void TokenBucket::refill_locked() { + int64_t t = now_ns(); + double dt = (double)(t - last_ns_) * 1e-9; + last_ns_ = t; + tokens_ = std::min((double)burst_, tokens_ + dt * (double)rate_); +} + +bool TokenBucket::try_take(int64_t bytes, SSDConsumer who) { + std::lock_guard lk(mu_); + Use& u = use_[(int)who]; + if (rate_ <= 0) { u.bytes += bytes; ++u.grants; return true; } + refill_locked(); + if (tokens_ < (double)bytes) return false; + tokens_ -= (double)bytes; + u.bytes += bytes; + ++u.grants; + return true; +} + +void TokenBucket::take(int64_t bytes, SSDConsumer who) { + int64_t t0 = now_ns(); + bool waited = false; + for (;;) { + if (try_take(bytes, who)) break; + waited = true; + /* Sleep for the deficit rather than spinning. Coarse on purpose: this is a placeholder + * and a precise scheduler for a policy nobody has measured would be effort spent on the + * wrong thing (spec §19.5). */ + std::this_thread::sleep_for(std::chrono::microseconds(200)); + } + if (waited) { + std::lock_guard lk(mu_); + ++use_[(int)who].waits; + use_[(int)who].wait_us += (now_ns() - t0) / 1000; + } +} + +TokenBucket::Use TokenBucket::use(SSDConsumer c) const { + std::lock_guard lk(mu_); + return use_[(int)c]; +} + +std::string TokenBucket::report() const { + std::lock_guard lk(mu_); + std::string s = rate_ > 0 + ? fmt("SSD token bucket: %s/s, burst %s (PLACEHOLDER, spec §19.5)\n", + humanb(rate_).c_str(), humanb(burst_).c_str()) + : std::string("SSD token bucket: off (no measured rate to enforce, spec §19.5)\n"); + for (int i = 0; i < (int)SSDConsumer::N; ++i) + s += fmt(" %-14s %10s in %lld ops, %lld waits totalling %lld ms\n", + ssd_consumer_name((SSDConsumer)i), humanb(use_[i].bytes).c_str(), + (long long)use_[i].grants, (long long)use_[i].waits, + (long long)(use_[i].wait_us / 1000)); + return s; +} + +TokenBucket& rad_ssd_bucket() { static TokenBucket b; return b; } + +/* ------------------------------------------------------------------ SSDTier */ + +std::string SSDTier::disclosure(const std::string& dir) { + return fmt("SSD prefix tier active at %s.\n" + " It stores CONVERSATION CONTENT ON DISK, UNENCRYPTED: the cached KV blocks are a\n" + " lossless function of the prompt, and the prompt's token ids are written beside\n" + " them so a hit can be verified. Anything that persists across restarts says so\n" + " (spec §7.3). Put this directory on storage you are willing to treat as holding\n" + " the text itself.\n", dir.c_str()); +} + +SSDTier::~SSDTier() { close(); } + +static int64_t hdr_region_bytes(int64_t tok_bytes) { + return align_up((int64_t)sizeof(SSSlotHeader) + tok_bytes, kAlign); +} + +int SSDTier::open_store(Store& s, const std::string& path, int64_t payload, int64_t n_slots, + int64_t tok_bytes, bool allow_buffered) { + s.payload = payload; + s.hdr_bytes = hdr_region_bytes(tok_bytes); + s.slot_bytes = s.hdr_bytes + align_up(payload, kAlign); + if (n_slots <= 0) return RAD_OK; + + int flags = RAD_DIO_READ | RAD_DIO_WRITE | RAD_DIO_CREATE; + if (allow_buffered) flags |= RAD_DIO_ALLOW_BUFFERED; + RAD_TRY(s.file.open(path.c_str(), flags)); + + /* Size the store up front. DirectFile does not take a size hint and does not need one -- a + * write past the end extends the file -- but a store laid out in one ftruncate is one extent + * rather than N, which is the difference between a slot read being one seek and being several + * once the filesystem has interleaved somebody else's writes between ours. */ + if (::ftruncate(s.file.fd(), (off_t)(s.slot_bytes * n_slots)) != 0) + RAD_WARN("ftruncate %s to %s: %s -- the store will be extended by its writes instead", + path.c_str(), humanb(s.slot_bytes * n_slots).c_str(), strerror(errno)); + + s.slots.assign((size_t)n_slots, Slot{}); + s.freelist.resize((size_t)n_slots); + for (int64_t i = 0; i < n_slots; ++i) s.freelist[(size_t)i] = (int32_t)(n_slots - 1 - i); + s.stage = alloc_aligned(s.slot_bytes); + if (!s.stage) return RAD_E_NOMEM; + return RAD_OK; +} + +int SSDTier::open(const SSDTierConfig& cfg) { + close(); + cfg_ = cfg; + if (cfg.dir.empty()) { enabled_ = false; return RAD_OK; } + if (cfg.block_payload <= 0 && cfg.ckpt_payload <= 0) { + RAD_ERR("--prefix-cache-dir is set but neither a block payload nor a checkpoint payload was " + "given; there is nothing for the tier to store"); + return RAD_E_INVAL; + } + + /* The engine says so at startup. Not behind a verbosity flag. */ + RAD_WARN("%s", disclosure(cfg.dir).c_str()); + + if (::mkdir(cfg.dir.c_str(), 0700) != 0 && errno != EEXIST) { + RAD_ERR("cannot create %s: %s", cfg.dir.c_str(), strerror(errno)); + return RAD_E_IO; + } + + RAD_TRY(open_store(blocks_, cfg.dir + "/blocks.bin", cfg.block_payload, cfg.n_block_slots, + cfg.block_tokens * (int64_t)sizeof(uint32_t), cfg.allow_buffered)); + RAD_TRY(open_store(ckpts_, cfg.dir + "/ckpts.bin", cfg.ckpt_payload, cfg.n_ckpt_slots, + 0, cfg.allow_buffered)); + + enabled_ = true; + + if (cfg.persistent) { + /* Rebuild the index by scanning the slot headers rather than persisting a separate index + * file. One sequential pass at startup, and no way for an index to disagree with the data + * it names -- which is the failure a separate index file has and which produces exactly + * the "serves one caller another caller's context" outcome this tier verifies against. */ + const int64_t nb = scan_store(blocks_, kMagicBlock); + if (nb < 0) return (int)nb; + const int64_t nc = scan_store(ckpts_, kMagicCkpt); + if (nc < 0) return (int)nc; + RAD_INFO("SSD tier: recovered %lld block and %lld checkpoint slots from %s", + (long long)nb, (long long)nc, cfg.dir.c_str()); + } else { + /* Not persistent means the store must not outlive the process, and unlinking now rather + * than at exit means it also does not outlive a crash. The descriptors stay valid. */ + ::unlink((cfg.dir + "/blocks.bin").c_str()); + ::unlink((cfg.dir + "/ckpts.bin").c_str()); + } + + report_ = fmt("SSD tier %s: %lld block slots x %s, %lld checkpoint slots x %s, %s%s\n", + cfg.dir.c_str(), + (long long)cfg.n_block_slots, humanb(blocks_.slot_bytes).c_str(), + (long long)cfg.n_ckpt_slots, humanb(ckpts_.slot_bytes).c_str(), + blocks_.file.direct() ? "O_DIRECT" : "BUFFERED", + cfg.persistent ? ", persistent" : ", volatile"); + return RAD_OK; +} + +void SSDTier::close() { + for (Store* s : { &blocks_, &ckpts_ }) { + s->file.close(); + if (s->stage) { ::free(s->stage); s->stage = nullptr; } + s->slots.clear(); s->index.clear(); s->freelist.clear(); + } + enabled_ = false; +} + +std::string SSDTier::report() const { + std::string s = report_; + s += fmt(" %lld hits, %lld misses, %lld verify misses, %lld evictions; " + "%s read, %s written\n", + (long long)stats_.hits, (long long)stats_.misses, (long long)stats_.verify_misses, + (long long)stats_.evictions, humanb(stats_.bytes_read).c_str(), + humanb(stats_.bytes_written).c_str()); + s += rad_ssd_bucket().report(); + return s; +} + +void SSDTier::lru_unlink(Store& s, int32_t i) { + Slot& x = s.slots[(size_t)i]; + if (x.prev >= 0) s.slots[(size_t)x.prev].next = x.next; else s.lru_head = x.next; + if (x.next >= 0) s.slots[(size_t)x.next].prev = x.prev; else s.lru_tail = x.prev; + x.prev = x.next = -1; +} + +void SSDTier::lru_push(Store& s, int32_t i) { + Slot& x = s.slots[(size_t)i]; + x.prev = s.lru_tail; + x.next = -1; + if (s.lru_tail >= 0) s.slots[(size_t)s.lru_tail].next = i; else s.lru_head = i; + s.lru_tail = i; +} + +/* THE HEADERS ARE READ MANY AT A TIME. Each is one 4 KiB direct read at its own slot, so a single + * reader waits one device round trip a slot -- some tens of microseconds, over the millions of + * slots a store sized in hundreds of GiB holds, which is over a minute of every start. The device + * serves dozens of such reads at once at little more latency than one, so the scan keeps + * kScanDepth in flight: one thread each, over its own contiguous run of slots with its own staging + * page. The threads only record each slot's verdict in the slot itself; the index, the order and + * the free list are built afterwards in one descending pass, which is the order a single + * sequential reader would produce. */ +static constexpr int64_t kScanDepth = 64; + +int64_t SSDTier::scan_store(Store& s, uint32_t magic) { + if (s.slots.empty()) return 0; + s.index.clear(); + s.freelist.clear(); + s.lru_head = s.lru_tail = -1; + for (Slot& x : s.slots) { x.used = 0; x.prev = x.next = -1; } + + const int64_t n = (int64_t)s.slots.size(); + const int64_t nt = std::min(kScanDepth, n); + std::atomic nomem{false}; + std::vector th; + th.reserve((size_t)nt); + for (int64_t t = 0; t < nt; ++t) + th.emplace_back([&, t] { + void* stage = alloc_aligned(s.hdr_bytes); + if (!stage) { nomem.store(true); return; } + for (int64_t i = n * t / nt; i < n * (t + 1) / nt; ++i) { + if (s.file.read_at(stage, i * s.slot_bytes, s.hdr_bytes) < 0) continue; + const SSSlotHeader* h = (const SSSlotHeader*)stage; + if (h->magic != magic || h->fingerprint != cfg_.fingerprint + || h->payload_bytes != (uint64_t)s.payload) continue; + Slot& x = s.slots[(size_t)i]; + x.key.hi = h->key_hi; + x.key.lo = h->key_lo; + x.pos = h->pos; + x.used = 1; + } + std::free(stage); + }); + for (std::thread& x : th) x.join(); + if (nomem.load()) { + for (Slot& x : s.slots) x.used = 0; + RAD_ERR("SSD tier: no staging page for the header scan"); + return RAD_E_NOMEM; + } + + int64_t live = 0; + for (const Slot& x : s.slots) live += x.used; + s.index.reserve((size_t)live); + s.freelist.reserve((size_t)(n - live)); + for (int64_t i = n - 1; i >= 0; --i) { + if (!s.slots[(size_t)i].used) { s.freelist.push_back((int32_t)i); continue; } + lru_push(s, (int32_t)i); + s.index[s.slots[(size_t)i].key] = (int32_t)i; + } + return live; +} + +int SSDTier::claim(Store& s, const BlockHash& key, int32_t* out) { + auto it = s.index.find(key); + if (it != s.index.end()) { *out = it->second; return RAD_OK; } + if (!s.freelist.empty()) { *out = s.freelist.back(); s.freelist.pop_back(); return RAD_OK; } + + /* LRU. Evicting the DEEPEST entry first would be better -- a deeper block chains more tokens, + * is less shareable, and losing it only shortens the usable prefix, whereas losing a shallow + * one strands everything above it -- but depth is not a property this tier is told. Straight + * LRU until the caller carries depth in. */ + const int32_t victim = s.lru_head; + if (victim < 0) return RAD_E_FULL; + lru_unlink(s, victim); + s.index.erase(s.slots[(size_t)victim].key); + s.slots[(size_t)victim].used = 0; + ++stats_.evictions; + *out = victim; + return RAD_OK; +} + +int SSDTier::put(Store& s, uint32_t magic, const BlockHash& key, int64_t pos, + const int32_t* toks, int32_t n_toks, const void* payload, int64_t bytes) { + if (!enabled_ || s.slots.empty()) return RAD_E_UNSUPPORTED; + if (bytes != s.payload) return RAD_E_SHAPE; + if ((int64_t)sizeof(SSSlotHeader) + (int64_t)n_toks * 4 > s.hdr_bytes) return RAD_E_SHAPE; + + int32_t slot = -1; + RAD_TRY(claim(s, key, &slot)); + const int64_t base = (int64_t)slot * s.slot_bytes; + + std::memset(s.stage, 0, (size_t)s.slot_bytes); + SSSlotHeader* h = (SSSlotHeader*)s.stage; + h->magic = magic; + h->n_tokens = (uint32_t)n_toks; + h->fingerprint = cfg_.fingerprint; + h->payload_bytes = (uint64_t)bytes; + h->key_hi = key.hi; h->key_lo = key.lo; + h->pos = pos; + if (n_toks > 0) std::memcpy((char*)s.stage + sizeof(SSSlotHeader), toks, (size_t)n_toks * 4); + std::memcpy((char*)s.stage + s.hdr_bytes, payload, (size_t)bytes); + + rad_ssd_bucket().take(s.slot_bytes, SSDConsumer::PrefixCache); + + /* Payload first, header last. Written front to back, a short write would leave the header + * COMPLETE and the payload truncated, so the slot verifies and the engine loads whatever was + * in the file underneath it -- which is the worst failure this tier can have. + * + * A WRITE THAT FAILS GIVES THE SLOT BACK. claim() took it off the free list or out of the + * index, so returning here without that leaves a slot no list names and the store one slot + * smaller for good. Whatever the slot held before is no longer trustworthy either -- the + * payload may be half overwritten under a header that still verifies -- so the key comes out + * of the index and the header is cleared on a best-effort basis, which keeps a persistent + * store from indexing it again at the next start. */ + int wst = s.file.write_at((char*)s.stage + s.hdr_bytes, base + s.hdr_bytes, + s.slot_bytes - s.hdr_bytes); + if (wst >= 0) wst = s.file.write_at(s.stage, base, s.hdr_bytes); + if (wst < 0) { + auto it = s.index.find(key); + if (it != s.index.end() && it->second == slot) s.index.erase(it); + if (s.slots[(size_t)slot].used) lru_unlink(s, slot); + s.slots[(size_t)slot].used = 0; + s.freelist.push_back(slot); + std::memset(s.stage, 0, (size_t)s.hdr_bytes); + (void)s.file.write_at(s.stage, base, s.hdr_bytes); + return wst; + } + + if (s.slots[(size_t)slot].used) lru_unlink(s, slot); + s.slots[(size_t)slot].key = key; + s.slots[(size_t)slot].used = 1; + s.slots[(size_t)slot].pos = pos; + lru_push(s, slot); + s.index[key] = slot; + ++stats_.writes; + stats_.bytes_written += s.slot_bytes; + return RAD_OK; +} + +int SSDTier::get(Store& s, uint32_t magic, const BlockHash& key, int64_t pos, + const int32_t* toks, int32_t n_toks, void* payload, int64_t bytes) { + if (!enabled_ || s.slots.empty()) return RAD_E_UNSUPPORTED; + if (bytes != s.payload) return RAD_E_SHAPE; + auto it = s.index.find(key); + if (it == s.index.end()) { ++stats_.misses; return RAD_E_NOTFOUND; } + const int32_t slot = it->second; + const int64_t base = (int64_t)slot * s.slot_bytes; + + rad_ssd_bucket().take(s.slot_bytes, SSDConsumer::PrefixCache); + RAD_TRY(s.file.read_at(s.stage, base, s.slot_bytes)); + ++stats_.reads; + stats_.bytes_read += s.slot_bytes; + + if (!header_ok(s, s.stage, magic, key, pos, toks, n_toks, bytes)) { + /* Drop it rather than leaving it to fail every future probe: without this a single bad + * slot poisons its prefix permanently. */ + forget_slot(s, slot); + ++stats_.verify_misses; + return RAD_E_NOTFOUND; + } + std::memcpy(payload, (const char*)s.stage + s.hdr_bytes, (size_t)bytes); + lru_unlink(s, slot); + lru_push(s, slot); + ++stats_.hits; + return RAD_OK; +} + +/* Belt and braces on top of the index: verify the header AND the token ids. A store that survives + * a restart, a model change or a layout change would otherwise serve one caller another caller's + * context, and that is not a failure anybody would ever diagnose. */ +bool SSDTier::header_ok(const Store& s, const void* stage, uint32_t magic, const BlockHash& key, + int64_t pos, const int32_t* toks, int32_t n_toks, int64_t bytes) const { + (void)s; + const SSSlotHeader* h = (const SSSlotHeader*)stage; + bool ok = h->magic == magic && h->fingerprint == cfg_.fingerprint + && h->key_hi == key.hi && h->key_lo == key.lo + && h->payload_bytes == (uint64_t)bytes && h->pos == pos + && h->n_tokens == (uint32_t)n_toks; + if (ok && n_toks > 0) + ok = std::memcmp((const char*)stage + sizeof(SSSlotHeader), toks, (size_t)n_toks * 4) == 0; + return ok; +} + +void SSDTier::forget_slot(Store& s, int32_t slot) { + auto it = s.index.find(s.slots[(size_t)slot].key); + if (it != s.index.end() && it->second == slot) s.index.erase(it); + if (s.slots[(size_t)slot].used) lru_unlink(s, slot); + s.slots[(size_t)slot].used = 0; + s.freelist.push_back(slot); +} + +/* READS OUTSTANDING AT ONCE. An NVMe drive reading tens-of-kilobyte extents at random reaches its + * bandwidth only with many requests in flight; a thread each is the simplest way to have them, and + * every thread has an aligned staging buffer of its own. */ +static constexpr int kReaders = 16; + +int SSDTier::get_blocks(const BlockHash* keys, int64_t n, void* const* payloads, int64_t bytes, + char* ok) { + std::lock_guard lk(io_mu_); + Store& s = blocks_; + for (int64_t i = 0; i < n; ++i) ok[i] = 0; + if (!enabled_ || s.slots.empty()) return RAD_E_UNSUPPORTED; + if (bytes != s.payload) return RAD_E_SHAPE; + + std::vector slot((size_t)n, -1); + int64_t found = 0; + for (int64_t i = 0; i < n; ++i) { + auto it = s.index.find(keys[i]); + if (it == s.index.end()) { ++stats_.misses; continue; } + slot[(size_t)i] = it->second; + ++found; + } + if (found == 0) return RAD_OK; + + /* The reads, and nothing that touches the index or the order: those are settled after, on this + * thread. 1 read and verified, 2 read and not the key asked for, negative a failed read. */ + std::vector st((size_t)n, 0); + std::atomic next{0}; + auto reader = [&](void* stage) { + for (int64_t i; (i = next.fetch_add(1, std::memory_order_relaxed)) < n;) { + if (slot[(size_t)i] < 0) continue; + rad_ssd_bucket().take(s.slot_bytes, SSDConsumer::PrefixCache); + const int r = s.file.read_at(stage, (int64_t)slot[(size_t)i] * s.slot_bytes, + s.slot_bytes); + if (r < 0) { st[(size_t)i] = r; continue; } + if (!header_ok(s, stage, kMagicBlock, keys[i], 0, nullptr, 0, bytes)) { + st[(size_t)i] = 2; + continue; + } + std::memcpy(payloads[i], (const char*)stage + s.hdr_bytes, (size_t)bytes); + st[(size_t)i] = 1; + } + }; + const int nt = (int)std::min(kReaders, found); + std::vector stages; + for (int t = 1; t < nt; ++t) { + void* p = alloc_aligned(s.slot_bytes); + if (!p) break; + stages.push_back(p); + } + std::vector th; + th.reserve(stages.size()); + for (void* p : stages) th.emplace_back(reader, p); + reader(s.stage); + for (std::thread& t : th) t.join(); + for (void* p : stages) ::free(p); + + for (int64_t i = 0; i < n; ++i) { + const int32_t sl = slot[(size_t)i]; + if (sl < 0 || st[(size_t)i] < 0) continue; + ++stats_.reads; + stats_.bytes_read += s.slot_bytes; + if (st[(size_t)i] == 2) { + forget_slot(s, sl); + ++stats_.verify_misses; + continue; + } + lru_unlink(s, sl); + lru_push(s, sl); + ++stats_.hits; + ok[i] = 1; + } + return RAD_OK; +} + +/* ONE CALLER AT A TIME. Every call is the KV tiers' IO thread today, but a store is one staging + * buffer, one slot table and one index, and nothing about the interface says who may call it. */ +int SSDTier::put_block(const BlockHash& key, const int32_t* toks, int32_t n_toks, + const void* payload, int64_t bytes) { + std::lock_guard lk(io_mu_); + return put(blocks_, kMagicBlock, key, 0, toks, n_toks, payload, bytes); +} +int SSDTier::get_block(const BlockHash& key, const int32_t* toks, int32_t n_toks, + void* payload, int64_t bytes) { + std::lock_guard lk(io_mu_); + return get(blocks_, kMagicBlock, key, 0, toks, n_toks, payload, bytes); +} +int SSDTier::put_checkpoint(const BlockHash& key, int64_t pos, const void* payload, int64_t bytes) { + std::lock_guard lk(io_mu_); + return put(ckpts_, kMagicCkpt, key, pos, nullptr, 0, payload, bytes); +} +int SSDTier::get_checkpoint(const BlockHash& key, int64_t pos, void* payload, int64_t bytes) { + std::lock_guard lk(io_mu_); + return get(ckpts_, kMagicCkpt, key, pos, nullptr, 0, payload, bytes); +} + +} /* namespace rad */ diff --git a/core/mem/sstier.h b/core/mem/sstier.h new file mode 100644 index 00000000..ce55820c --- /dev/null +++ b/core/mem/sstier.h @@ -0,0 +1,181 @@ +/* sstier.h -- the optional SSD tier for served attention state and linear checkpoints alike, so + * an agent session does not re-prefill its whole transcript every turn (spec §7.3). + * + * ============================== IT HOLDS CONVERSATION CONTENT ON DISK, UNENCRYPTED ============== + * A KV block IS the prompt: the token ids are stored beside it so a hit can be verified, and the + * cached tensors are a lossless function of the text. Anything that persists it across restarts + * says so, and this engine says so at startup whenever --prefix-cache-dir is set. There is no + * encryption option, no obfuscation, and no claim of one; if the content is sensitive the + * directory must be on storage the operator is willing to treat as sensitive. + * ================================================================================================ + * + * O_DIRECT, same as the weight tier. Going through the page cache would evict the weight tier's own + * file mappings, which is paid for in decode and would never show up as a *cache* problem. O_DIRECT + * wants offsets, lengths and buffers all on the logical block size, so every slot and every + * sub-region here is a multiple of it and there is no unaligned tail to handle. + * + * Spec §19.5 records that prefix-cache and weight-tier contention on one SSD has NO PLAN. The + * TokenBucket below is a placeholder for a measured policy, and it is labelled as one: it is a + * shared byte budget between the two consumers, which at least makes the contention visible and + * boundable instead of invisible. What the right split is, or whether a rate limit is even the + * right shape of answer rather than a priority queue, is a measurement nobody has taken. + */ +#pragma once +#include "device/directio.h" +#include "mem/prefix.h" +#include "rad_core.h" + +#include +#include +#include +#include + +namespace rad { + +/* The O_DIRECT file is the device layer's rad::DirectFile (core/device/directio.h). Every extent + * this tier reads or writes is a whole slot or a whole aligned header region, so every transfer + * lands on its fast path and its bounce buffer is never allocated -- which is the property worth + * stating, since the bounce exists for callers reading a header or a file tail and one on this + * path would mean a slot geometry bug rather than a performance problem. */ + +/* ------------------------------------------------------------------ the shared rate limiter */ +enum class SSDConsumer { PrefixCache = 0, WeightTier = 1, N = 2 }; +const char* ssd_consumer_name(SSDConsumer c); + +/* PLACEHOLDER FOR A MEASURED POLICY (spec §19.5). + * + * Both the prefix cache and the weight tier want O_DIRECT bandwidth and under load they fight. A + * token bucket is the simplest thing that bounds the fight: one shared byte budget, refilled at a + * stated rate, drawn on by both. What it does NOT do is decide who should win, and that is the + * actual open question -- a weight-tier read blocks a layer that is about to execute, while a + * prefix-cache read only makes a prefill shorter, so a priority scheme is probably the right shape + * and a flat rate limit certainly is not. Replace this once there is a workload to measure + * against; the per-consumer counters exist so that measurement has something to read. */ +class TokenBucket { +public: + /* 0 bytes_per_sec disables the limiter entirely, which is the default: an unmeasured rate + * limit that throttles a machine nobody profiled is worse than none. */ + void configure(int64_t bytes_per_sec, int64_t burst_bytes); + bool enabled() const { return rate_ > 0; } + + bool try_take(int64_t bytes, SSDConsumer who); /* non-blocking */ + void take(int64_t bytes, SSDConsumer who); /* sleeps until the budget allows */ + + struct Use { int64_t bytes = 0; int64_t grants = 0; int64_t waits = 0; int64_t wait_us = 0; }; + Use use(SSDConsumer c) const; + std::string report() const; + +private: + void refill_locked(); + + mutable std::mutex mu_; + int64_t rate_ = 0; /* bytes per second */ + int64_t burst_ = 0; + double tokens_ = 0; + int64_t last_ns_ = 0; + Use use_[(int)SSDConsumer::N]; +}; + +/* The one bucket both consumers share. The weight tier (core/place/) draws on the same object; + * that is the entire point of it living here rather than inside either one. */ +TokenBucket& rad_ssd_bucket(); + +/* ------------------------------------------------------------------ the tier */ +struct SSDTierConfig { + std::string dir; /* Config::prefix_cache_dir */ + int64_t block_payload = 0; /* bytes one cached attention block occupies, all groups */ + int64_t block_tokens = 0; /* the attention block size, for the verify */ + int64_t ckpt_payload = 0; /* KVManager::checkpoint_bytes() */ + /* Slot counts are STATED, not derived from statvfs. A tier that sizes itself from the free + * space it happens to see at startup is a tier whose capacity changes when somebody untars + * something, and §6's rule is that budgets do not move on their own. */ + int64_t n_block_slots = 0; + int64_t n_ckpt_slots = 0; + uint64_t fingerprint = 0; /* model + layout identity; a mismatch invalidates the store */ + bool persistent = false; /* keep the files across restarts */ + /* Passes RAD_DIO_ALLOW_BUFFERED. Off by default: the device layer REFUSES a filesystem + * without O_DIRECT rather than downgrading it, because a silent buffered fallback costs the + * weight tier its own page cache and shows up only as a decode regression nobody can + * attribute. The flag is for tests, which run on whatever /tmp happens to be. */ + bool allow_buffered = false; +}; + +class SSDTier { +public: + ~SSDTier(); + int open(const SSDTierConfig& cfg); + void close(); + bool enabled() const { return enabled_; } + + /* The line the engine prints at startup when the flag is on. Not optional. */ + static std::string disclosure(const std::string& dir); + std::string report() const; + + /* Attention blocks. `toks` is the block's token ids: they are stored in the slot header and + * memcmp'd on the way back in, so a hash collision is a miss and never a wrong answer. */ + int put_block(const BlockHash& key, const int32_t* toks, int32_t n_toks, + const void* payload, int64_t bytes); + int get_block(const BlockHash& key, const int32_t* toks, int32_t n_toks, + void* payload, int64_t bytes); + /* MANY BLOCKS AT ONCE, READ IN PARALLEL. A conversation coming back off disk is thousands of + * entries of tens of kilobytes each, and read one at a time they keep the drive at a queue + * depth of one -- a fraction of what it delivers with dozens of reads outstanding. `ok[i]` is + * whether block i was found, read and verified into `payloads[i]`; one that was not is a miss + * exactly as get_block's would be. Blocks stored with no token ids only. */ + int get_blocks(const BlockHash* keys, int64_t n, void* const* payloads, int64_t bytes, + char* ok); + + /* Linear-state checkpoints. Keyed by the chained block hash at the checkpoint position, which + * is exactly what PrefixCache::reserve_checkpoint keys them by in VRAM. */ + int put_checkpoint(const BlockHash& key, int64_t pos, const void* payload, int64_t bytes); + int get_checkpoint(const BlockHash& key, int64_t pos, void* payload, int64_t bytes); + + struct Stats { + int64_t reads = 0, writes = 0, hits = 0, misses = 0, verify_misses = 0, evictions = 0; + int64_t bytes_read = 0, bytes_written = 0; + }; + const Stats& stats() const { return stats_; } + +private: + /* `prev`/`next` link the used slots from least to most recently used, so a full store finds + * the one to give up without a walk. A walk would be over every slot of a store sized in the + * millions, once per write, on the thread that has to keep up with the host tier's copies. */ + struct Slot { BlockHash key; int32_t used = 0; int64_t pos = 0; int32_t prev = -1, next = -1; }; + struct Store { + DirectFile file; + int64_t slot_bytes = 0; + int64_t hdr_bytes = 0; /* header + token ids, padded */ + int64_t payload = 0; + std::vector slots; + std::unordered_map index; + std::vector freelist; + int32_t lru_head = -1, lru_tail = -1; /* least and most recently used */ + void* stage = nullptr; + }; + /* A used slot leaves the order; a slot becomes the most recently used. */ + static void lru_unlink(Store& s, int32_t i); + static void lru_push(Store& s, int32_t i); + + int open_store(Store& s, const std::string& path, int64_t payload, int64_t n_slots, + int64_t tok_bytes, bool allow_buffered); + int64_t scan_store(Store& s, uint32_t magic); + int claim(Store& s, const BlockHash& key, int32_t* out); + int put(Store& s, uint32_t magic, const BlockHash& key, int64_t pos, + const int32_t* toks, int32_t n_toks, const void* payload, int64_t bytes); + int get(Store& s, uint32_t magic, const BlockHash& key, int64_t pos, + const int32_t* toks, int32_t n_toks, void* payload, int64_t bytes); + /* Is the slot read into `stage` the one asked for: this store, this model, this key. */ + bool header_ok(const Store& s, const void* stage, uint32_t magic, const BlockHash& key, + int64_t pos, const int32_t* toks, int32_t n_toks, int64_t bytes) const; + /* A slot whose bytes are not what the index says: out of the index and the order, and free. */ + static void forget_slot(Store& s, int32_t slot); + + SSDTierConfig cfg_; + std::mutex io_mu_; + Store blocks_, ckpts_; + bool enabled_ = false; + Stats stats_; + std::string report_; +}; + +} /* namespace rad */ diff --git a/core/mem/vram_budget.cpp b/core/mem/vram_budget.cpp new file mode 100644 index 00000000..07cb0ead --- /dev/null +++ b/core/mem/vram_budget.cpp @@ -0,0 +1,329 @@ +/* vram_budget.cpp -- see vram_budget.h for why a derived budget is not the §6 violation it looks + * like. This file is the arithmetic and the receipt. */ +#include "mem/vram_budget.h" + +#include +#include + +namespace rad { + +namespace { +constexpr int64_t kMiB = 1024 * 1024; + +/* DOWN, ALWAYS. The pools take MiB and multiply back up, so a budget rounded up is a budget that + * asks the card for more than the arithmetic said was there -- which fails at the allocation + * rather than here, with the driver's message instead of ours. */ +int64_t to_mib(int64_t bytes) { return bytes > 0 ? bytes / kMiB : 0; } + +/* UP, FOR THE ONE BUDGET THAT IS A FLOOR. The KV budget is a CAPACITY -- truncated, the cache + * addresses a few fewer tokens and nothing else changes. The weights budget is `statics + + * experts`, a figure the pool must COVER, and a byte short is a tensor with nowhere to land. An + * expert share pads the number enough to hide that; a dense model is budgeted its static + * footprint to the byte, and there the rounding direction decides whether it loads. The MiB this + * claims comes out of the headroom, which is what the headroom is for. */ +int64_t to_mib_up(int64_t bytes) { return bytes > 0 ? (bytes + kMiB - 1) / kMiB : 0; } +} /* namespace */ + +int vram_budget_resolve(Config& cfg, const std::vector& per_rank, VramBudget* out) { + VramBudget b; + if (per_rank.empty()) { if (out) *out = b; return RAD_OK; } + + /* THE SMALLEST CARD AND THE LARGEST PROGRAM, because one split is applied to every rank. Ranks + * of one deployment normally hold the same shard shapes and the same program, so these folds + * are no-ops -- they exist so that a mixed pair degrades to the card that binds instead of + * overcommitting the smaller one on the first allocation. */ + b.capacity = per_rank[0].capacity; + int64_t freeb = per_rank[0].free; + int64_t layer_max = 0; + for (const VramFacts& f : per_rank) { + b.capacity = std::min(b.capacity, f.capacity); + freeb = std::min(freeb, f.free); + b.arena = std::max(b.arena, f.arena); + b.kv_ceiling = std::max(b.kv_ceiling, f.kv_ceiling); + b.statics = std::max(b.statics, f.statics); + b.expert_ceiling = std::max(b.expert_ceiling, f.experts); + layer_max = std::max(layer_max, f.expert_layer_max); + } + b.headroom = std::max(cfg.gpu_headroom_mib, 0) * kMiB; + int64_t host_reserve = 0; + for (const VramFacts& f : per_rank) host_reserve = std::max(host_reserve, f.host_reserve); + const bool shared = host_reserve > b.headroom; + if (shared) b.headroom = host_reserve; + + /* A host backend has no VRAM to speak of and reports none; there is nothing here to resolve + * and inventing a capacity would be exactly the inference §6 forbids. */ + if (b.capacity <= 0) { + b.weights = cfg.vram_weights_mib * kMiB; + b.kv = cfg.vram_kv_mib * kMiB; + if (out) *out = b; + return RAD_OK; + } + + /* MEASURED, NOT ASSUMED, AND IT IS THE ONLY TERM THAT IS. Everything the driver and the loaded + * code objects already hold shows up here, including a desktop compositor on the same card -- + * which is a real configuration on a workstation and the reason this is a line in the report + * rather than a constant folded into the headroom. Read after declare(), so every kernel + * plugin's init has run and its code object is resident. */ + b.already_held = std::max(b.capacity - freeb, 0); + + const bool want_w = cfg.vram_weights_mib <= 0; + const bool want_kv = cfg.vram_kv_mib <= 0; + b.derived_weights = want_w; + b.derived_kv = want_kv; + + /* What is left after the terms nobody gets to spend. */ + int64_t fixed = b.already_held + b.headroom + b.arena; + if (!want_w) fixed += cfg.vram_weights_mib * kMiB; /* a stated pool is fixed too */ + if (!want_kv) fixed += cfg.vram_kv_mib * kMiB; + b.claimable = b.capacity - fixed; + + if (b.claimable < 0) { + b.report = fmt( + "VRAM does not cover the fixed costs before a single pool is sized:\n" + " card total %10s\n" + " already held %10s (driver context, code objects, anything else on the card)\n" + " --gpu-headroom-mib %10s\n" + " activation arena %10s (buffer plan + kernel scratch)\n" + "%s%s" + " ------------------------------\n" + " SHORT BY %10s\n" + "Lower --gpu-headroom-mib, lower --max-num-batched-tokens (the arena scales with it), " + "or free the card.\n", + humanb(b.capacity).c_str(), humanb(b.already_held).c_str(), + humanb(b.headroom).c_str(), humanb(b.arena).c_str(), + want_w ? "" : fmt(" --vram-weights-mib %10s (stated)\n", + humanb(cfg.vram_weights_mib * kMiB).c_str()).c_str(), + want_kv ? "" : fmt(" --vram-kv-mib %10s (stated)\n", + humanb(cfg.vram_kv_mib * kMiB).c_str()).c_str(), + humanb(-b.claimable).c_str()); + RAD_ERR("%s", b.report.c_str()); + if (out) *out = b; + return RAD_E_NOMEM; + } + + b.weights = want_w ? 0 : cfg.vram_weights_mib * kMiB; + b.kv = want_kv ? 0 : cfg.vram_kv_mib * kMiB; + + /* ---- the static weights come off the top ------------------------------------------------ + * + * They are a floor and not a share. Only a DERIVED weight budget pays them here: an operator + * who stated --vram-weights-mib has already decided what the weights get, and second-guessing + * that is the re-optimisation §6 forbids. */ + if (want_w) { + b.statics = std::min(b.statics, b.claimable); + if (b.statics >= b.claimable && b.claimable > 0) { + /* Not fatal: the planner will demote what does not fit and the model still serves, + * badly. Name it, because "why is this model 8x slower than it should be" has no other + * answer at startup. */ + RAD_WARN("the static (non-expert) weights alone want %s of the %s this card has to " + "give. Every expert will stream from host memory and the KV cache has " + "nothing left -- this model wants more VRAM, fewer ranks of it, or a smaller " + "--max-num-batched-tokens.", + humanb(b.statics).c_str(), humanb(b.claimable).c_str()); + } + } + b.elastic = want_w ? b.claimable - b.statics : b.claimable; + if (b.elastic < 0) b.elastic = 0; + + /* ---- and only what is left is what the ratio divides ------------------------------------- */ + if (want_w && want_kv) { + const double r = (cfg.expert_cache_ratio > 0.0 && cfg.expert_cache_ratio < 1.0) + ? cfg.expert_cache_ratio : 0.75; + int64_t kv = (int64_t)((double)b.elastic * (1.0 - r)); + int64_t exp = b.elastic - kv; + + /* BOTH SIDES ARE CAPPED AT WHAT THEY COULD USE, AND THE SLACK CROSSES OVER. A paged cache + * cannot address past max_seqs x max_ctx tokens and an expert plane that is entirely + * resident has no use for another byte -- so a share above either ceiling is memory + * nothing will ever touch. Cap, then hand the remainder to whichever side is still short, + * then stop: what neither can take is genuinely unusable and is reported as such rather + * than allocated into a pool that reports itself three quarters empty. */ + if (b.kv_ceiling > 0 && kv > b.kv_ceiling) kv = b.kv_ceiling; + /* ZERO EXPERTS IS A CEILING OF ZERO, NOT AN UNMEASURED ONE. weight_footprint() runs on + * every rank before this call, so expert_ceiling is always known -- and guarding this cap + * with `> 0` would read "dense" as "unlimited", handing a model with no experts at all a + * large expert budget against nothing to put in it while its cache goes short. + * kv_ceiling keeps its guard: that one IS genuinely unset when plan_groups fails. */ + if (exp > b.expert_ceiling) exp = b.expert_ceiling; + int64_t spare = b.elastic - kv - exp; + if (spare > 0 && b.expert_ceiling > exp) { + const int64_t take = std::min(spare, b.expert_ceiling - exp); + exp += take; spare -= take; + } + if (spare > 0 && b.kv_ceiling > kv) { + const int64_t take = std::min(spare, b.kv_ceiling - kv); + kv += take; spare -= take; + } + b.experts = exp; + b.kv = kv; + b.weights = b.statics + exp; + b.unusable = spare > 0 ? spare : 0; + } else if (want_kv) { + b.kv = b.kv_ceiling > 0 ? std::min(b.claimable, b.kv_ceiling) : b.claimable; + b.unusable = b.claimable - b.kv; + } else if (want_w) { + /* The KV pool was stated, so `claimable` is already net of it; the weights take the rest, + * still capped at what the model has to put there. */ + int64_t exp = b.elastic; + if (exp > b.expert_ceiling) { + b.unusable = exp - b.expert_ceiling; + exp = b.expert_ceiling; + } + b.experts = exp; + b.weights = b.statics + exp; + } + + /* ---- THE PREFILL STAGING REGION, out of the expert share --------------------------------- + * + * A prefill chunk routes to nearly every expert of every layer, so the part of each layer the + * budget leaves off the card is read across the link by the layer's GEMM -- on the critical + * path, at the link's rate, while the rest of the layer's work leaves the link idle. Two + * buffers of one layer's share of that let the next layer's copy run behind the current one + * (core/place/stager.h). They come out of the expert share because they exist only for the + * experts that do not fit, and they sit at the top of the activation arena, which every step + * smaller than the full plan lends back to the expert slab: a decode step keeps the residency + * they cost. + * + * The share is the budget's -- what the slab alone leaves off -- which is the most a step can + * see: the loans the KV cache and the smaller arena levels make only ever add residency. A + * layer whose pooled part is larger than a buffer stages what fits and streams the rest. */ + if (want_w && layer_max > 0 && b.expert_ceiling > b.experts && cfg.placement != "all_vram" && + cfg.placement != "layer_offload") { + const double f = (double)(b.expert_ceiling - b.experts) / (double)b.expert_ceiling; + const int64_t one = ((int64_t)std::ceil(f * (double)layer_max) + RAD_ALIGN_UNIT - 1) / + RAD_ALIGN_UNIT * RAD_ALIGN_UNIT; + if (2 * one < b.experts) { + b.stage = 2 * one; + b.experts -= b.stage; + b.weights = b.statics + b.experts; + } + } + + /* HOW MUCH OF THE ADVERTISED CONTEXT THE POOL BACKS, AND IT IS A PROVISIONING CHOICE RATHER + * THAN A SHORTFALL. + * + * A KV share under max_seqs x max_ctx is not a warning. The argument that it would be -- that + * the server accepts at the door what it cannot serve -- is wrong for a PAGED cache, and the + * difference is the whole of vLLM's block manager: a sequence holds only the blocks its tokens + * actually occupy (KVManager::ensure grows it by ceil_div(n_tokens, block_size) as it runs, + * drops them at completion, and returns RAD_E_FULL for the scheduler to preempt rather than + * failing the request). Every sequence reaching max_ctx at the same moment is the worst case, + * not the workload -- real loads run well under half backing -- and sizing for the worst case + * spends VRAM that a model whose experts do not fit would rather have for them. + * + * So it is reported and not warned about. What IS still checked, and belongs in the KV manager + * because it is a real limit rather than a ratio, is that ONE max-length sequence fits: a + * context no single request can complete is a configuration error however much slack the pool + * has (core/engine_bringup.cpp, configure_kv). */ + if (b.derived_kv && b.kv_ceiling > 0 && cfg.max_ctx > 0) + RAD_INFO("kv: the pool backs %.0f%% of the worst case (%lld sequences all at %lld tokens), " + "%.1f full-length sessions. That is concurrency at length before the scheduler " + "preempts, not a bound on any one request. WITH PREFIX CACHING a finished " + "sequence's blocks stay held so the next turn can reuse them, so the demand is " + "live SESSIONS and not running requests -- when they do not all fit, the cache " + "evicts prefixes the next turn wanted and that turn re-prefills its whole " + "context. --expert-vs-cache-ratio moves it.", + 100.0 * (double)b.kv / (double)b.kv_ceiling, + (long long)cfg.max_seqs, (long long)cfg.max_ctx, + (double)cfg.max_seqs * (double)b.kv / (double)b.kv_ceiling); + /* Rounding the floor up claims up to a MiB the split did not hand out. Take it back from the + * cache where the cache is ours to size -- a paged pool a MiB smaller addresses a handful + * fewer tokens and nothing else -- so the headroom stays whole. Where the KV budget was + * STATED it is not ours to shave and the MiB comes out of the headroom instead. */ + cfg.vram_budget_derived = want_w || want_kv; + cfg.vram_weights_mib = to_mib_up(b.weights); + const int64_t w_over = cfg.vram_weights_mib * kMiB - b.weights; + cfg.vram_kv_mib = want_kv ? to_mib(std::max(b.kv - w_over, 0)) : to_mib(b.kv); + + /* THE RECEIPT. Every term, in the order it was spent, so that a split anybody disagrees with + * can be argued about against numbers instead of re-derived from sysfs by hand. The unclaimed + * line is not padding: to_mib truncates, and what it drops is real VRAM that ends up beside + * the headroom. */ + const int64_t granted = cfg.vram_weights_mib * kMiB + cfg.vram_kv_mib * kMiB; + const int64_t unclaimed = b.capacity - b.already_held - b.arena - b.stage - granted; + const double ela = b.elastic > 0 ? (double)b.elastic : 1.0; + b.report = fmt( + "VRAM budget, per card:\n" + " card total %10s\n" + " already held %10s measured: driver context, code objects, anything else resident\n" + " activation arena %10s computed from the buffer plan\n" + " %-18s %10s %s\n" + " ------------------------------\n" + " claimable %10s\n" + " static weights %10s %s\n" + " ------------------------------\n" + " elastic %10s what --expert-vs-cache-ratio %.2f divides\n" + " experts %10s %.0f%% of it%s\n" + " kv cache %10s %.0f%% of it%s\n" + "%s" + "%s" + " ==============================\n" + " vram_weights %10s %s\n" + " vram_kv %10s %s\n" + " unclaimed %10s the headroom, the unusable above, and what MiB rounding\n" + " could not place\n", + humanb(b.capacity).c_str(), humanb(b.already_held).c_str(), humanb(b.arena).c_str(), + shared ? "left to the host" : "--gpu-headroom-mib", humanb(b.headroom).c_str(), + shared ? "integrated graphics: this memory is the host's; --vram-kv-mib states a pool " + "outright" + : "left unclaimed on purpose", + humanb(b.claimable).c_str(), + humanb(b.statics).c_str(), + b.derived_weights ? "off the top: every rank's own shard, and not a share of anything" + : "(not charged here -- --vram-weights-mib was stated)", + humanb(b.elastic).c_str(), + (cfg.expert_cache_ratio > 0.0 && cfg.expert_cache_ratio < 1.0) ? cfg.expert_cache_ratio + : 0.75, + humanb(b.experts).c_str(), 100.0 * (double)b.experts / ela, + b.expert_ceiling == 0 + ? " -- a dense model, so there is no expert plane for this share to fill and the\n" + " cache took everything it could address" + : (b.experts >= b.expert_ceiling) + ? " -- the whole expert plane is resident, so more would do nothing" : "", + humanb(b.kv).c_str(), 100.0 * (double)b.kv / ela, + (b.kv_ceiling > 0 && b.kv >= b.kv_ceiling) + ? fmt(" -- backs %lld sequences all at %lld tokens at once, which is the worst case and\n" + " more would be unusable", + (long long)cfg.max_seqs, (long long)cfg.max_ctx).c_str() + : (b.kv_ceiling > 0 + /* SAID AS A SESSION COUNT, because that is the number to compare against + * --max-num-seqs, and "28%" makes the reader do the arithmetic. + * + * AND IT NAMES SESSIONS, NOT RUNNING REQUESTS. "Paged blocks are held only + * while a sequence occupies them" stops being true once prefix caching takes a + * KV reference on every block it indexes: a finished sequence's blocks stay + * held so the next turn can reuse them. So the demand of a multi-turn workload + * is the number of LIVE SESSIONS, and counting running requests instead + * under-counts by exactly the thing that makes agent turns cheap. When the pool + * cannot hold them all, the cache evicts prefixes the next turn wants and that + * turn re-prefills its whole context (radiance:prefix_cache_evictions_total). */ + ? fmt(" -- %.0f%% backing of the %lld x %lld worst case: %.1f full-length\n" + " sessions. With prefix caching a " + "finished sequence's blocks stay held\n" + " for reuse, so the demand is LIVE " + "SESSIONS and not running requests", + 100.0 * (double)b.kv / (double)b.kv_ceiling, + (long long)cfg.max_seqs, (long long)cfg.max_ctx, + (double)cfg.max_seqs * (double)b.kv / (double)b.kv_ceiling).c_str() + : ""), + b.unusable > 0 + ? fmt(" unusable %10s neither side could take it: both are at their " + "ceiling\n", humanb(b.unusable).c_str()).c_str() + : "", + b.stage > 0 + ? fmt(" prefill staging %10s out of the experts: two buffers of one layer's " + "non-resident experts,\n" + " at the arena's top and lent back to the " + "slab while steps are small\n", humanb(b.stage).c_str()).c_str() + : "", + humanb(cfg.vram_weights_mib * kMiB).c_str(), + b.derived_weights ? "static + experts" : "stated by --vram-weights-mib", + humanb(cfg.vram_kv_mib * kMiB).c_str(), + b.derived_kv ? "the cache's share" : "stated by --vram-kv-mib", + humanb(unclaimed).c_str()); + + if (out) *out = b; + return RAD_OK; +} + +} /* namespace rad */ diff --git a/core/mem/vram_budget.h b/core/mem/vram_budget.h new file mode 100644 index 00000000..0273f7c9 --- /dev/null +++ b/core/mem/vram_budget.h @@ -0,0 +1,103 @@ +/* vram_budget.h -- how many bytes each VRAM pool gets, decided once and printed in full. + * + * ============================== WHY THIS IS NOT THE §6 VIOLATION IT LOOKS LIKE ============================== + * + * Spec §6 says the engine does not derive its budgets, and core/mem/pools.cpp still refuses to + * re-optimise a split the operator stated. The reason given there is exact and worth repeating: + * a budget derived from the FREE VRAM at startup is a benchmark that moves when somebody opens a + * window on the machine's desktop. + * + * What that argument forbids is inference. It does not forbid arithmetic on numbers that are all + * known, all printed, and all stable: + * + * capacity totalGlobalMem. A fixed property of the part. + * already held capacity - the free VRAM this process can see, MEASURED once, after every + * kernel plugin has initialised and its code objects are resident. This is the + * driver's context and the loaded code, and it is the one term that is observed + * rather than computed -- so it is printed on its own line, and a machine with a + * desktop on the card shows up in it instead of silently eating a pool. + * --gpu-headroom-mib what the operator wants left alone. Stated, defaulted to 96 MiB. + * arena the activation arena and the scratch beside it, computed from the buffer plan + * by arena_plan_bytes() -- the same call that later allocates it. + * + * What is left over is claimable, and it is spent in TWO STEPS, not one. + * + * THE STATIC WEIGHTS COME OFF THE TOP. Everything that is not an expert -- the attention + * projections, the norms, the embedding, the head -- has to be resident for the model to run at a + * sensible speed at all, and under tensor parallel each rank already holds its own even share of + * them (declare runs per rank with every dimension divided, spec §9). They are a FLOOR, not a + * share of anything: applying a ratio to the weights as a whole would let --expert-vs-cache-ratio + * 0.3 demote the attention projections to host memory to make room for a cache nothing will fill. + * If they do not fit, that is a refusal with the shortfall named. + * + * ONLY WHAT IS LEFT AFTER THAT IS DIVIDED, and that is the division the flag is named for: the + * expert plane against the KV cache, which is the one genuinely two-sided trade on this engine. A + * long-context low-concurrency server and a short-context high-concurrency one want opposite + * answers and neither is derivable. + * + * BOTH SIDES ARE THEN CAPPED AT WHAT THEY COULD USE, and whatever one side cannot take goes to the + * other rather than nowhere. A cache cannot address past max_seqs x max_ctx tokens + * (KVManager::ceiling), so a share larger than that ceiling is VRAM the cache can never fill and + * the expert plane could have held. And an expert plane that fits entirely in VRAM has no use for + * more; on a model that fits, the ratio stops meaning anything and that is correct. + * + * A stated --vram-weights-mib or --vram-kv-mib still wins outright and turns the whole of this + * off for that pool. The point is that the DEFAULT is a full card rather than a guess: VRAM left + * unbudgeted is VRAM no pool can use, and on a model whose experts do not fit, every unbudgeted + * GiB costs measurable decode time. + */ +#pragma once +#include "../rad_core.h" + +#include +#include + +namespace rad { + +/* One rank's card and program, as the resolver needs to see them. Every field is either read from + * the device or computed from the declared program; none of it is a policy. */ +struct VramFacts { + int64_t capacity = 0; /* RadDeviceProps::vram_bytes -- totalGlobalMem */ + int64_t free = 0; /* RadDeviceProps::vram_free, measured now */ + int64_t arena = 0; /* arena_plan_bytes() for this rank's program, total incl. scratch */ + int64_t kv_ceiling = 0; /* KVManager::ceiling(max_ctx) for this rank's declared groups */ + /* weight_footprint() for this rank, which under tensor parallel is already this card's even + * share: declare runs per rank with every dimension already divided. */ + int64_t statics = 0; /* non-expert weights -- the floor, not a share of anything */ + int64_t experts = 0; /* the elastic plane the ratio divides against the KV cache */ + int64_t expert_layer_max = 0; /* the most expert bytes one routed layer holds */ + /* Integrated graphics: what of the host's memory the card leaves to the host. Its device + * memory IS the host's, so an unclaimed MiB is the operating system's and every other + * process's to run in, not slack. 0 on a discrete card. */ + int64_t host_reserve = 0; +}; + +/* The resolved split, in bytes, beside every term it came from. Always filled, including when the + * operator stated the budgets -- the placement report and the pool report both want the totals. */ +struct VramBudget { + int64_t capacity = 0, already_held = 0, headroom = 0, arena = 0; + int64_t claimable = 0; /* after the four fixed terms above */ + int64_t statics = 0; /* off the top, before the ratio sees anything */ + int64_t elastic = 0; /* claimable - statics: what the ratio divides */ + int64_t kv_ceiling = 0, expert_ceiling = 0; + int64_t experts = 0, kv = 0; /* the two shares, each capped at its ceiling */ + int64_t unusable = 0; /* elastic neither side could take -- both were full */ + /* THE PREFILL STAGING REGION: two buffers, each one layer's share of the experts the budget + * leaves off the card, taken out of the expert share and appended to the top of the activation + * arena (core/place/stager.h). Zero when every expert is resident or the placement cannot move + * any. */ + int64_t stage = 0; + int64_t weights = 0; /* statics + experts: what vram_weights is set to */ + bool derived_weights = false, derived_kv = false; + std::string report; /* the block the engine prints at startup */ +}; + +/* Writes the answer into cfg.vram_weights_mib / cfg.vram_kv_mib -- ONE resolved number that every + * consumer downstream reads, so the planner, the KV manager and the pool report cannot disagree. + * Takes the SMALLEST capacity and free across ranks and the LARGEST arena, because a split has to + * fit on every card it is applied to. + * + * Refuses, by name and by how much, when the fixed terms alone exceed the card. */ +int vram_budget_resolve(Config& cfg, const std::vector& per_rank, VramBudget* out); + +} /* namespace rad */ diff --git a/core/mm/item.cpp b/core/mm/item.cpp new file mode 100644 index 00000000..740c2c39 --- /dev/null +++ b/core/mm/item.cpp @@ -0,0 +1,30 @@ +/* item.cpp -- the parts of an Item the step path uses, in a unit of their own. The batch builder + * links against this and nothing else in core/mm, so a test that fakes the device layer does not + * pull the processor -- and through its metadata reader, the real device layer -- in with it. */ +#include "mm/processor.h" + +namespace rad { +namespace mm { + +void Item::coords(int64_t first, int64_t count, int32_t* planes) const { + /* Merge-block order inverted: a patch's index within its segment is + * ((block_row * blocks_w + block_col) * merge + in_row) * merge + in_col. */ + const int64_t seg = (int64_t)grid_h * grid_w; + const int32_t merge = grid_h / rows_h; + const int64_t bw = grid_w / merge; + for (int64_t k = 0; k < count; ++k) { + const int64_t within = (first + k) % seg; + const int64_t in_col = within % merge; + const int64_t in_row = (within / merge) % merge; + const int64_t blk = within / (merge * merge); + const int64_t row = (blk / bw) * merge + in_row; + const int64_t col = (blk % bw) * merge + in_col; + planes[k] = (int32_t)row; + planes[count + k] = (int32_t)col; + planes[2 * count + k] = grid_h; + planes[3 * count + k] = grid_w; + } +} + +} /* namespace mm */ +} /* namespace rad */ diff --git a/core/mm/media.cpp b/core/mm/media.cpp new file mode 100644 index 00000000..2fa04d39 --- /dev/null +++ b/core/mm/media.cpp @@ -0,0 +1,366 @@ +/* media.cpp -- image and video decoding through libavformat / libavcodec / libswscale. */ +#include "mm/media.h" + +#include "rad_internal.h" + +#include +#include + +#ifdef RAD_HAVE_FFMPEG +extern "C" { +#include +#include +#include +#include +#include +} +#endif + +namespace rad { +namespace mm { + +#ifndef RAD_HAVE_FFMPEG + +bool decoder_available() { return false; } + +static int no_decoder(std::string* why) { + if (why) *why = "this build has no media decoder: it was configured without libavformat / " + "libavcodec / libswscale (RAD_WITH_FFMPEG)"; + return RAD_E_UNSUPPORTED; +} + +int decode_image(const uint8_t*, size_t, int64_t, Frame*, std::string* why) { + return no_decoder(why); +} +int decode_video(const uint8_t*, size_t, SampleFn, const void*, int64_t, Video*, + std::string* why) { + return no_decoder(why); +} + +#else + +bool decoder_available() { return true; } + +namespace { + +/* THE DEMUXERS A REQUEST MAY REACH, and nothing else. A container format that can name another + * file -- a playlist, a concat script, an image sequence pattern -- would otherwise let a request + * make the server open a path of its choosing, so the probe only ever considers these, and the + * protocol list below is empty so none of them can open anything either. */ +constexpr const char* kFormats = + "mov,mp4,m4a,3gp,3g2,mj2,matroska,webm,avi,mpegts,flv,ogg,gif,apng,image2pipe,png_pipe," + "jpeg_pipe,jpegls_pipe,jpegxl_pipe,webp_pipe,bmp_pipe,tiff_pipe,qoi_pipe,pgm_pipe,ppm_pipe," + "pbm_pipe,pam_pipe,gif_pipe,avif,heif"; + +struct MemIO { + const uint8_t* p = nullptr; + size_t n = 0; + size_t at = 0; +}; + +int mem_read(void* opaque, uint8_t* buf, int size) { + MemIO* m = static_cast(opaque); + const size_t left = m->n - m->at; + if (left == 0) return AVERROR_EOF; + const size_t k = std::min(left, (size_t)size); + std::memcpy(buf, m->p + m->at, k); + m->at += k; + return (int)k; +} + +int64_t mem_seek(void* opaque, int64_t off, int whence) { + MemIO* m = static_cast(opaque); + if (whence & AVSEEK_SIZE) return (int64_t)m->n; + int64_t base = 0; + switch (whence & ~AVSEEK_FORCE) { + case SEEK_SET: base = 0; break; + case SEEK_CUR: base = (int64_t)m->at; break; + case SEEK_END: base = (int64_t)m->n; break; + default: return AVERROR(EINVAL); + } + const int64_t to = base + off; + if (to < 0 || to > (int64_t)m->n) return AVERROR(EINVAL); + m->at = (size_t)to; + return to; +} + +std::string averr(int e) { + char b[AV_ERROR_MAX_STRING_SIZE] = {}; + av_strerror(e, b, sizeof b); + return b; +} + +/* One opened input over a memory buffer: the demuxer, its best video stream and a decoder for it. + * Every libav object is released in the destructor, so an early return anywhere leaks nothing. */ +struct Input { + MemIO io; + AVIOContext* avio = nullptr; + AVFormatContext* fmt = nullptr; + AVCodecContext* dec = nullptr; + int stream = -1; + + ~Input() { + if (dec) avcodec_free_context(&dec); + if (fmt) avformat_close_input(&fmt); + if (avio) { + av_freep(&avio->buffer); + avio_context_free(&avio); + } + } + + int open(const uint8_t* data, size_t n, bool want_decoder, std::string* why) { + io.p = data; io.n = n; io.at = 0; + constexpr int kBuf = 64 * 1024; + uint8_t* buf = static_cast(av_malloc(kBuf)); + if (!buf) { *why = "out of memory"; return RAD_E_NOMEM; } + avio = avio_alloc_context(buf, kBuf, 0, &io, mem_read, nullptr, mem_seek); + if (!avio) { av_free(buf); *why = "out of memory"; return RAD_E_NOMEM; } + fmt = avformat_alloc_context(); + if (!fmt) { *why = "out of memory"; return RAD_E_NOMEM; } + fmt->pb = avio; + fmt->flags |= AVFMT_FLAG_CUSTOM_IO; + AVDictionary* opts = nullptr; + av_dict_set(&opts, "format_whitelist", kFormats, 0); + av_dict_set(&opts, "protocol_whitelist", "", 0); + int e = avformat_open_input(&fmt, nullptr, nullptr, &opts); + av_dict_free(&opts); + if (e < 0) { + fmt = nullptr; /* freed by a failed open */ + *why = "not a recognised image or video format (" + averr(e) + ")"; + return RAD_E_INVAL; + } + e = avformat_find_stream_info(fmt, nullptr); + if (e < 0) { *why = "could not read the stream headers (" + averr(e) + ")"; return RAD_E_INVAL; } + const AVCodec* codec = nullptr; + stream = av_find_best_stream(fmt, AVMEDIA_TYPE_VIDEO, -1, -1, &codec, 0); + if (stream < 0 || !codec) { *why = "no picture in it: the media holds no video stream"; return RAD_E_INVAL; } + if (!want_decoder) return RAD_OK; + dec = avcodec_alloc_context3(codec); + if (!dec) { *why = "out of memory"; return RAD_E_NOMEM; } + e = avcodec_parameters_to_context(dec, fmt->streams[stream]->codecpar); + if (e < 0) { *why = "decoder setup failed (" + averr(e) + ")"; return RAD_E_INVAL; } + /* A few threads a decode: this runs on a server worker, one per request in flight, so + * handing each one every core would oversubscribe the machine the engine runs on. */ + dec->thread_count = 4; + e = avcodec_open2(dec, codec, nullptr); + if (e < 0) { *why = std::string("no decoder for ") + codec->name + " (" + averr(e) + ")"; return RAD_E_UNSUPPORTED; } + return RAD_OK; + } +}; + +/* One decoded frame to packed RGB24 at its own size. The YUV coefficients and range are the + * frame's own, so a BT.709 video and a full-range JPEG both come out with the colours they were + * encoded with; ACCURATE_RND and FULL_CHR_H_INT keep the conversion from truncating and from + * sampling chroma at half resolution. */ +int to_rgb(const AVFrame* f, SwsContext** sws, Frame* out, std::string* why) { + const AVPixelFormat src = (AVPixelFormat)f->format; + *sws = sws_getCachedContext(*sws, f->width, f->height, src, f->width, f->height, + AV_PIX_FMT_RGB24, + SWS_BICUBIC | SWS_ACCURATE_RND | SWS_FULL_CHR_H_INT, nullptr, + nullptr, nullptr); + if (!*sws) { *why = "no colour conversion from this pixel format"; return RAD_E_UNSUPPORTED; } + int cs = f->colorspace; + if (cs == AVCOL_SPC_UNSPECIFIED || cs == AVCOL_SPC_RGB) cs = AVCOL_SPC_BT470BG; + const int* coef = sws_getCoefficients(cs); + const int src_full = f->color_range == AVCOL_RANGE_JPEG || + src == AV_PIX_FMT_YUVJ420P || src == AV_PIX_FMT_YUVJ422P || + src == AV_PIX_FMT_YUVJ444P || src == AV_PIX_FMT_YUVJ440P; + sws_setColorspaceDetails(*sws, coef, src_full, sws_getCoefficients(SWS_CS_DEFAULT), 1, 0, + 1 << 16, 1 << 16); + out->w = f->width; + out->h = f->height; + out->rgb.resize((size_t)f->width * (size_t)f->height * 3); + uint8_t* dst[4] = { out->rgb.data(), nullptr, nullptr, nullptr }; + int dst_ls[4] = { f->width * 3, 0, 0, 0 }; + const int e = sws_scale(*sws, f->data, f->linesize, 0, f->height, dst, dst_ls); + if (e != f->height) { *why = "colour conversion failed"; return RAD_E_INVAL; } + return RAD_OK; +} + +/* THE DECODE LOOP, for both kinds: every frame in presentation order, `keep(i, frame)` told the + * index of each and whether to stop. + * + * AN EMPTY PACKET REPEATS THE FRAME BEFORE IT: it is how Ogg Theora stores a frame that does not + * change. Sent to a decoder, an empty packet would read as the end of the stream and the next one + * would be refused; it is passed to `keep` as another copy of the last frame instead, so the + * frame indices and the stream's length are the ones the frame count promised. */ +template +int decode_frames(Input& in, Keep&& keep, std::string* why) { + AVPacket* pkt = av_packet_alloc(); + AVFrame* frm = av_frame_alloc(); + AVFrame* last = av_frame_alloc(); + if (!pkt || !frm || !last) { + av_packet_free(&pkt); + av_frame_free(&frm); + av_frame_free(&last); + *why = "out of memory"; + return RAD_E_NOMEM; + } + int64_t idx = 0; + int st = RAD_OK; + bool done = false, flushing = false; + while (!done && st >= 0) { + if (!flushing) { + const int r = av_read_frame(in.fmt, pkt); + if (r == AVERROR_EOF) { + flushing = true; + avcodec_send_packet(in.dec, nullptr); + } else if (r < 0) { + *why = "demuxing failed (" + averr(r) + ")"; + st = RAD_E_INVAL; + break; + } else { + if (pkt->stream_index != in.stream) { av_packet_unref(pkt); continue; } + if (pkt->size == 0) { + av_packet_unref(pkt); + if (!last->buf[0]) continue; + const int k = keep(idx++, last); + if (k < 0) { st = k; break; } + if (k > 0) done = true; + continue; + } + const int s = avcodec_send_packet(in.dec, pkt); + av_packet_unref(pkt); + if (s < 0 && s != AVERROR(EAGAIN)) { + *why = "decoding failed (" + averr(s) + ")"; + st = RAD_E_INVAL; + break; + } + } + } + for (;;) { + const int r = avcodec_receive_frame(in.dec, frm); + if (r == AVERROR(EAGAIN)) break; + if (r == AVERROR_EOF) { done = true; break; } + if (r < 0) { + *why = "decoding failed (" + averr(r) + ")"; + st = RAD_E_INVAL; + break; + } + const int k = keep(idx++, frm); + av_frame_unref(last); + av_frame_move_ref(last, frm); + if (k < 0) { st = k; break; } + if (k > 0) { done = true; break; } + } + } + av_packet_free(&pkt); + av_frame_free(&frm); + av_frame_free(&last); + return st; +} + +} /* namespace */ + +int decode_image(const uint8_t* data, size_t n, int64_t max_pixels, Frame* out, std::string* why) { + std::string w; + if (!why) why = &w; + if (!data || n == 0) { *why = "empty"; return RAD_E_INVAL; } + Input in; + RAD_TRY(in.open(data, n, true, why)); + const AVCodecParameters* cp = in.fmt->streams[in.stream]->codecpar; + if (cp->width <= 0 || cp->height <= 0) { *why = "the image has no size"; return RAD_E_INVAL; } + if ((int64_t)cp->width * cp->height > max_pixels) { + *why = "the image is " + std::to_string(cp->width) + "x" + std::to_string(cp->height) + + ", over the server's " + std::to_string(max_pixels) + "-pixel limit for a source"; + return RAD_E_INVAL; + } + SwsContext* sws = nullptr; + bool got = false; + const int s = decode_frames(in, [&](int64_t, const AVFrame* f) -> int { + const int c = to_rgb(f, &sws, out, why); + if (c < 0) return c; + got = true; + return 1; + }, why); + sws_freeContext(sws); + if (s < 0) return s; + if (!got) { *why = "the image decoded to no frame"; return RAD_E_INVAL; } + return RAD_OK; +} + +int decode_video(const uint8_t* data, size_t n, SampleFn sample, const void* user, + int64_t max_pixels, Video* out, std::string* why) { + std::string w; + if (!why) why = &w; + if (!data || n == 0) { *why = "empty"; return RAD_E_INVAL; } + + /* THE FRAME COUNT FIRST, because which frames to keep depends on it. Many containers state it; + * those that do not are demuxed once without decoding, which counts packets -- one a frame for + * every codec a request is going to send -- at the cost of reading the bytes twice. */ + VideoInfo info; + { + Input probe; + RAD_TRY(probe.open(data, n, false, why)); + const AVStream* st = probe.fmt->streams[probe.stream]; + info.w = st->codecpar->width; + info.h = st->codecpar->height; + AVRational r = st->avg_frame_rate; + if (r.num <= 0 || r.den <= 0) r = st->r_frame_rate; + info.fps = (r.num > 0 && r.den > 0) ? av_q2d(r) : 0.0; + info.n_frames = st->nb_frames; + if (info.n_frames <= 0) { + AVPacket* pkt = av_packet_alloc(); + if (!pkt) { *why = "out of memory"; return RAD_E_NOMEM; } + int64_t c = 0; + while (av_read_frame(probe.fmt, pkt) >= 0) { + if (pkt->stream_index == probe.stream) ++c; + av_packet_unref(pkt); + } + av_packet_free(&pkt); + info.n_frames = c; + } + } + if (info.w <= 0 || info.h <= 0) { *why = "the video has no size"; return RAD_E_INVAL; } + if ((int64_t)info.w * info.h > max_pixels) { + *why = "the video is " + std::to_string(info.w) + "x" + std::to_string(info.h) + + ", over the server's " + std::to_string(max_pixels) + "-pixel limit for a frame"; + return RAD_E_INVAL; + } + if (info.n_frames <= 0) { *why = "the video holds no frames"; return RAD_E_INVAL; } + + out->info = info; + out->index = sample(info, user); + if (out->index.empty()) { *why = "no frames were sampled"; return RAD_E_INVAL; } + out->frames.assign(out->index.size(), Frame{}); + + Input in; + RAD_TRY(in.open(data, n, true, why)); + SwsContext* sws = nullptr; + size_t next = 0; + int64_t last_kept = -1; + const int s = decode_frames(in, [&](int64_t i, const AVFrame* f) -> int { + if ((int64_t)f->width * f->height > max_pixels) { + *why = "a frame is larger than the server's pixel limit"; + return RAD_E_INVAL; + } + /* The same frame may be sampled twice when the stream is shorter than its own header + * says; each slot that names this index takes a copy. */ + bool converted = false; + while (next < out->index.size() && out->index[next] == i) { + if (!converted) { + const int c = to_rgb(f, &sws, &out->frames[next], why); + if (c < 0) return c; + converted = true; + } else { + out->frames[next] = out->frames[next - 1]; + } + last_kept = (int64_t)next; + ++next; + } + return next >= out->index.size() ? 1 : 0; + }, why); + sws_freeContext(sws); + if (s < 0) return s; + if (last_kept < 0) { *why = "the video decoded to no frame"; return RAD_E_INVAL; } + /* A STREAM SHORTER THAN ITS HEADER leaves the last sampled indices unreached. They take the + * last frame that was decoded, which is what a reader that clamps an index past the end + * returns. */ + for (size_t k = next; k < out->index.size(); ++k) out->frames[k] = out->frames[(size_t)last_kept]; + return RAD_OK; +} + +#endif /* RAD_HAVE_FFMPEG */ + +} /* namespace mm */ +} /* namespace rad */ diff --git a/core/mm/media.h b/core/mm/media.h new file mode 100644 index 00000000..08aaa806 --- /dev/null +++ b/core/mm/media.h @@ -0,0 +1,60 @@ +/* media.h -- turning the bytes of an image or a video into RGB frames (spec §11). + * + * ONE DECODER FOR BOTH, and it is libavformat/libavcodec. An image is a one-frame stream to it, so + * PNG, JPEG, WebP, GIF, BMP and TIFF arrive through the same demuxer probe and the same decode loop + * a video takes, and there is one colour conversion (libswscale) rather than one per format. A + * build without the libraries has no decoder at all: every call here returns RAD_E_UNSUPPORTED + * with the reason, and the server refuses a media part by name rather than guessing at its bytes. + * + * THE BYTES COME FROM THE REQUEST, never from a URL. The server accepts `data:` URLs only, so + * nothing here opens a file or a network stream: the demuxer reads a memory buffer through its own + * I/O context, and the protocol whitelist is empty. + * + * WHAT A FRAME IS: packed 8-bit RGB, row-major, no padding. An alpha channel is DROPPED, not + * composited -- the reference processor converts with PIL's convert("RGB"), which does the same, + * so a transparent PNG reaches the encoder with the colours under its alpha. + */ +#pragma once +#include +#include +#include + +namespace rad { +namespace mm { + +struct Frame { + int32_t w = 0, h = 0; + std::vector rgb; /* [h, w, 3] */ +}; + +/* Is there a decoder in this build. */ +bool decoder_available(); + +/* The first frame of an image (or of anything with a video stream). Refuses more than + * `max_pixels` in the SOURCE, which is what bounds the memory a request can make the server + * allocate before any resize happens. */ +int decode_image(const uint8_t* data, size_t n, int64_t max_pixels, Frame* out, std::string* why); + +/* HOW A VIDEO IS SAMPLED, and it happens INSIDE the decode rather than after it: a minute of 1080p + * is 10 GB of RGB, so frames that are not sampled are never converted or kept. The choice of which + * frames is the processor's (it depends on the stream's length and rate, which only the decoder + * knows), so it is a callback: given the stream's frame count and rate, return the frame indices to + * keep, ascending. */ +struct VideoInfo { + int64_t n_frames = 0; /* frames in the stream; counted by demuxing when the header omits it */ + double fps = 0.0; /* the stream's average rate */ + int32_t w = 0, h = 0; +}; +typedef std::vector (*SampleFn)(const VideoInfo& info, const void* user); + +struct Video { + VideoInfo info; + std::vector index; /* the frame each of `frames` is */ + std::vector frames; +}; + +int decode_video(const uint8_t* data, size_t n, SampleFn sample, const void* user, + int64_t max_pixels, Video* out, std::string* why); + +} /* namespace mm */ +} /* namespace rad */ diff --git a/core/mm/processor.cpp b/core/mm/processor.cpp new file mode 100644 index 00000000..fab26f8d --- /dev/null +++ b/core/mm/processor.cpp @@ -0,0 +1,549 @@ +/* processor.cpp -- see processor.h. */ +#include "mm/processor.h" + +#include "rad_internal.h" +#include "rad_plugin.h" + +#include +#include +#include +#include +#include + +namespace rad { +namespace mm { + +/* ================================================================== configuration */ + +static bool read_triple(const RadModelMeta& m, const char* key, float out[3]) { + const char* v = rad_meta_gets(&m, key, nullptr); + if (!v || !*v) return false; + std::istringstream is(v); + float t[3]; + for (int i = 0; i < 3; ++i) + if (!(is >> t[i])) return false; + for (int i = 0; i < 3; ++i) out[i] = t[i]; + return true; +} + +int VisionConfig::from_meta(const RadModelMeta& m, std::string* why) { + patch = (int32_t)rad_meta_geti(&m, "vision_config.patch_size", 0); + temporal = (int32_t)rad_meta_geti(&m, "vision_config.temporal_patch_size", 0); + merge = (int32_t)rad_meta_geti(&m, "vision_config.spatial_merge_size", 0); + if (patch <= 0 || temporal <= 0 || merge <= 0) { + if (why) *why = "the container states no vision tower geometry (vision_config.patch_size, " + "temporal_patch_size, spatial_merge_size)"; + return RAD_E_NOTFOUND; + } + tok_image = (int32_t)rad_meta_geti(&m, "image_token_id", -1); + tok_video = (int32_t)rad_meta_geti(&m, "video_token_id", -1); + tok_start = (int32_t)rad_meta_geti(&m, "vision_start_token_id", -1); + tok_end = (int32_t)rad_meta_geti(&m, "vision_end_token_id", -1); + if (tok_image < 0 || tok_video < 0 || tok_start < 0 || tok_end < 0) { + if (why) *why = "the container states no media token ids (image_token_id, video_token_id, " + "vision_start_token_id, vision_end_token_id)"; + return RAD_E_NOTFOUND; + } + /* THE PROCESSOR-ONLY KEYS DEFAULT TO THE FAMILY'S VALUES. They come from the checkpoint's + * preprocessor configs, which a container may not carry; the numbers below are what the + * Qwen3.x checkpoints ship. */ + image_min_pixels = rad_meta_geti(&m, "preprocessor.size.shortest_edge", + rad_meta_geti(&m, "preprocessor.min_pixels", 65536)); + image_max_pixels = rad_meta_geti(&m, "preprocessor.size.longest_edge", + rad_meta_geti(&m, "preprocessor.max_pixels", 16777216)); + video_min_pixels = rad_meta_geti(&m, "video_preprocessor.size.shortest_edge", 4096); + video_max_pixels = rad_meta_geti(&m, "video_preprocessor.size.longest_edge", 25165824); + fps = rad_meta_getf(&m, "video_preprocessor.fps", 2.0); + min_frames = (int32_t)rad_meta_geti(&m, "video_preprocessor.min_frames", 4); + max_frames = (int32_t)rad_meta_geti(&m, "video_preprocessor.max_frames", 768); + max_frame_rows = (int32_t)rad_meta_geti(&m, "video_preprocessor.max_video_tokens", 768); + read_triple(m, "preprocessor.image_mean", mean); + read_triple(m, "preprocessor.image_std", stdv); + if (image_min_pixels <= 0 || image_max_pixels < image_min_pixels || video_min_pixels <= 0 || + video_max_pixels < video_min_pixels || !(fps > 0.0) || min_frames < 1 || + max_frames < min_frames) { + if (why) *why = "the container's preprocessor configuration is inconsistent"; + return RAD_E_INVAL; + } + for (int c = 0; c < 3; ++c) + if (!(stdv[c] > 0.0f)) { + if (why) *why = "preprocessor.image_std must be positive"; + return RAD_E_INVAL; + } + return RAD_OK; +} + +/* ================================================================== sizes and sampling */ + +/* Python's round(), which is round-half-to-even on the double -- the reference computes these in + * Python, and a size that lands on .5 rounds the way it does there. */ +static inline int64_t pyround(double x) { return (int64_t)std::nearbyint(x); } + +int smart_resize_image(int64_t h, int64_t w, int32_t factor, int64_t min_px, int64_t max_px, + int64_t* oh, int64_t* ow, std::string* why) { + if (h <= 0 || w <= 0) { if (why) *why = "the picture has no size"; return RAD_E_INVAL; } + if ((double)std::max(h, w) / (double)std::min(h, w) > 200.0) { + if (why) *why = "the picture's aspect ratio is over 200:1"; + return RAD_E_INVAL; + } + const double f = factor; + int64_t hb = pyround((double)h / f) * factor; + int64_t wb = pyround((double)w / f) * factor; + if (hb * wb > max_px) { + const double beta = std::sqrt((double)(h * w) / (double)max_px); + hb = std::max(factor, (int64_t)std::floor((double)h / beta / f) * factor); + wb = std::max(factor, (int64_t)std::floor((double)w / beta / f) * factor); + } else if (hb * wb < min_px) { + const double beta = std::sqrt((double)min_px / (double)(h * w)); + hb = (int64_t)std::ceil((double)h * beta / f) * factor; + wb = (int64_t)std::ceil((double)w * beta / f) * factor; + } + *oh = hb; + *ow = wb; + return RAD_OK; +} + +int smart_resize_video(int64_t t, int64_t h, int64_t w, int32_t tfactor, int32_t factor, + int64_t min_px, int64_t max_px, int64_t* oh, int64_t* ow, std::string* why) { + if (t < tfactor) { if (why) *why = "too few frames"; return RAD_E_INVAL; } + if (h < factor || w < factor) { + const double s = std::max((double)factor / (double)h, (double)factor / (double)w); + h = (int64_t)((double)h * s); + w = (int64_t)((double)w * s); + } + if (h <= 0 || w <= 0) { if (why) *why = "the video has no size"; return RAD_E_INVAL; } + if ((double)std::max(h, w) / (double)std::min(h, w) > 200.0) { + if (why) *why = "the video's aspect ratio is over 200:1"; + return RAD_E_INVAL; + } + const double f = factor; + int64_t hb = pyround((double)h / f) * factor; + int64_t wb = pyround((double)w / f) * factor; + const int64_t tb = pyround((double)t / (double)tfactor) * tfactor; + if (tb * hb * wb > max_px) { + const double beta = std::sqrt((double)(t * h * w) / (double)max_px); + hb = std::max(factor, (int64_t)std::floor((double)h / beta / f) * factor); + wb = std::max(factor, (int64_t)std::floor((double)w / beta / f) * factor); + } else if (tb * hb * wb < min_px) { + const double beta = std::sqrt((double)min_px / (double)(t * h * w)); + hb = (int64_t)std::ceil((double)h * beta / f) * factor; + wb = (int64_t)std::ceil((double)w * beta / f) * factor; + } + *oh = hb; + *ow = wb; + return RAD_OK; +} + +/* THE REFERENCE'S FRAME CHOICE: as many frames as `fps` gives over the clip's duration, clamped to + * [min_frames, max_frames] and to what the stream has, spread evenly over it -- numpy's linspace, + * rounded half-to-even. A stream that states no rate is taken at 24, as the reference does. */ +std::vector sample_frames(const VideoInfo& info, double fps, int32_t min_frames, + int32_t max_frames) { + const int64_t total = info.n_frames; + if (total <= 0) return {}; + const double vfps = info.fps > 0.0 ? info.fps : 24.0; + int64_t n = (int64_t)((double)total / vfps * fps); + n = std::min(std::max(n, min_frames), max_frames); + n = std::min(n, total); + std::vector idx((size_t)n); + if (n == 1) { idx[0] = 0; return idx; } + const double step = (double)(total - 1) / (double)(n - 1); + for (int64_t i = 0; i < n; ++i) idx[(size_t)i] = (int64_t)std::nearbyint((double)i * step); + idx[(size_t)n - 1] = total - 1; + return idx; +} + +/* ================================================================== the resample + * + * Pillow's ImagingResample for an 8-bit RGB image, transcribed: the coefficient table in double, + * normalised per output pixel and rounded to 22-bit fixed point; a horizontal pass over only the + * source rows the vertical pass will read, into an 8-bit intermediate; then the vertical pass. The + * rounding at the intermediate is part of the function -- a single-pass float resample is a + * different (and slightly better) function, and not the one the model was trained against. */ +namespace { + +constexpr int kPrec = 32 - 8 - 2; + +inline double bicubic(double x) { + constexpr double a = -0.5; + if (x < 0.0) x = -x; + if (x < 1.0) return ((a + 2.0) * x - (a + 3.0)) * x * x + 1.0; + if (x < 2.0) return (((x - 5.0) * x + 8.0) * x - 4.0) * a; + return 0.0; +} + +inline uint8_t clip8(int32_t v) { + const int32_t s = v >> kPrec; + return (uint8_t)(s < 0 ? 0 : (s > 255 ? 255 : s)); +} + +/* One axis: `bounds` gets (first, count) per output pixel and `kk` its fixed-point weights, `ksize` + * a row. */ +int coeffs(int32_t in_size, int32_t out_size, std::vector* bounds, + std::vector* kk) { + const double scale = (double)in_size / (double)out_size; + const double fscale = scale < 1.0 ? 1.0 : scale; + const double support = 2.0 * fscale; + const int ksize = (int)std::ceil(support) * 2 + 1; + std::vector k((size_t)ksize); + bounds->assign((size_t)out_size * 2, 0); + kk->assign((size_t)out_size * (size_t)ksize, 0); + for (int xx = 0; xx < out_size; ++xx) { + const double center = (xx + 0.5) * scale; + const double ss = 1.0 / fscale; + int xmin = (int)(center - support + 0.5); + if (xmin < 0) xmin = 0; + int xmax = (int)(center + support + 0.5); + if (xmax > in_size) xmax = in_size; + xmax -= xmin; + double ww = 0.0; + int x = 0; + for (; x < xmax; ++x) { + const double w = bicubic((x + xmin - center + 0.5) * ss); + k[(size_t)x] = w; + ww += w; + } + for (x = 0; x < xmax; ++x) + if (ww != 0.0) k[(size_t)x] /= ww; + for (; x < ksize; ++x) k[(size_t)x] = 0.0; + for (x = 0; x < ksize; ++x) { + const double v = k[(size_t)x]; + (*kk)[(size_t)xx * ksize + x] = v < 0 ? (int32_t)(-0.5 + v * (1 << kPrec)) + : (int32_t)(0.5 + v * (1 << kPrec)); + } + (*bounds)[(size_t)xx * 2] = xmin; + (*bounds)[(size_t)xx * 2 + 1] = xmax; + } + return ksize; +} + +} /* namespace */ + +void resize_bicubic(const Frame& in, int32_t w, int32_t h, Frame* out) { + if (in.w == w && in.h == h) { *out = in; return; } + std::vector bh, kh, bv, kv; + const int ksh = coeffs(in.w, w, &bh, &kh); + const int ksv = coeffs(in.h, h, &bv, &kv); + + /* The source rows the vertical pass reads, which is all the horizontal pass has to produce. */ + const int y_first = bv[0]; + const int y_last = bv[(size_t)h * 2 - 2] + bv[(size_t)h * 2 - 1]; + const bool need_h = w != in.w; + const bool need_v = h != in.h; + + Frame tmp; + const Frame* src = ∈ + if (need_h) { + const int rows = need_v ? y_last - y_first : in.h; + const int y0 = need_v ? y_first : 0; + tmp.w = w; + tmp.h = rows; + tmp.rgb.assign((size_t)w * rows * 3, 0); + for (int yy = 0; yy < rows; ++yy) { + const uint8_t* row = in.rgb.data() + (size_t)(yy + y0) * in.w * 3; + uint8_t* o = tmp.rgb.data() + (size_t)yy * w * 3; + for (int xx = 0; xx < w; ++xx) { + const int xmin = bh[(size_t)xx * 2], xmax = bh[(size_t)xx * 2 + 1]; + const int32_t* k = kh.data() + (size_t)xx * ksh; + int32_t s0 = 1 << (kPrec - 1), s1 = s0, s2 = s0; + for (int x = 0; x < xmax; ++x) { + const uint8_t* p = row + (size_t)(x + xmin) * 3; + s0 += p[0] * k[x]; + s1 += p[1] * k[x]; + s2 += p[2] * k[x]; + } + o[xx * 3 + 0] = clip8(s0); + o[xx * 3 + 1] = clip8(s1); + o[xx * 3 + 2] = clip8(s2); + } + } + src = &tmp; + } + if (!need_v) { *out = std::move(tmp); return; } + const int shift = need_h ? y_first : 0; + out->w = src->w; + out->h = h; + out->rgb.assign((size_t)src->w * h * 3, 0); + for (int yy = 0; yy < h; ++yy) { + const int ymin = bv[(size_t)yy * 2] - shift, ymax = bv[(size_t)yy * 2 + 1]; + const int32_t* k = kv.data() + (size_t)yy * ksv; + uint8_t* o = out->rgb.data() + (size_t)yy * src->w * 3; + for (int xx = 0; xx < src->w; ++xx) { + int32_t s0 = 1 << (kPrec - 1), s1 = s0, s2 = s0; + for (int y = 0; y < ymax; ++y) { + const uint8_t* p = src->rgb.data() + ((size_t)(y + ymin) * src->w + xx) * 3; + s0 += p[0] * k[y]; + s1 += p[1] * k[y]; + s2 += p[2] * k[y]; + } + o[xx * 3 + 0] = clip8(s0); + o[xx * 3 + 1] = clip8(s1); + o[xx * 3 + 2] = clip8(s2); + } + } +} + +/* ================================================================== patches */ + +namespace { + +inline uint64_t mix64(uint64_t x) { + x += 0x9e3779b97f4a7c15ull; + x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9ull; + x = (x ^ (x >> 27)) * 0x94d049bb133111ebull; + return x ^ (x >> 31); +} + +/* Two independent 64-bit lanes over the patch bytes and the grid. The prefix cache folds the key + * into a chained 128-bit block identity; a collision would serve one picture's cache for another, + * so both lanes are carried. */ +void content_key(const Item& it, uint64_t* hi, uint64_t* lo) { + uint64_t a = 0x6a09e667f3bcc908ull ^ mix64((uint64_t)it.grid_t << 42 ^ + (uint64_t)it.grid_h << 21 ^ (uint64_t)it.grid_w); + uint64_t b = 0xbb67ae8584caa73bull ^ mix64(it.kind == Kind::Image ? 1u : 2u); + const uint8_t* p = reinterpret_cast(it.pixels.data()); + const size_t n = it.pixels.size() * sizeof(uint16_t); + size_t i = 0; + for (; i + 16 <= n; i += 16) { + uint64_t w0, w1; + std::memcpy(&w0, p + i, 8); + std::memcpy(&w1, p + i + 8, 8); + a = mix64(a ^ w0) + w1; + b = mix64(b ^ w1) ^ w0; + } + for (; i < n; ++i) { a = mix64(a ^ p[i]); b = mix64(b + p[i]); } + *hi = mix64(a ^ (uint64_t)n); + *lo = mix64(b + (uint64_t)n); +} + +/* THE PATCH ROWS, in merge-block order, from `frames` (temporal * grid_t of them, already resized + * to grid_h * patch by grid_w * patch). Each row is (channel, frame, y, x), each value normalised + * as the reference does -- (x - 255 mean) / (255 std) in f32 -- and rounded to bf16. */ +void patchify(const VisionConfig& c, const std::vector& frames, Item* it) { + const int P = c.patch, T = c.temporal, M = c.merge; + const int gh = it->grid_h, gw = it->grid_w; + float m255[3], s255[3]; + for (int ch = 0; ch < 3; ++ch) { + /* torch.tensor(mean) * (1 / rescale_factor), in f32: the fused rescale's own constants. */ + m255[ch] = c.mean[ch] * (float)(1.0 / (1.0 / 255.0)); + s255[ch] = c.stdv[ch] * (float)(1.0 / (1.0 / 255.0)); + } + /* One lookup per (channel, byte): the normalisation is a function of the byte alone. */ + uint16_t lut[3][256]; + for (int ch = 0; ch < 3; ++ch) + for (int v = 0; v < 256; ++v) + lut[ch][v] = rad_f32_to_bf16(((float)v - m255[ch]) / s255[ch]); + + const int64_t dim = it->patch_dim; + it->pixels.assign((size_t)it->n_patch * (size_t)dim, 0); + uint16_t* dst = it->pixels.data(); + for (int g = 0; g < it->grid_t; ++g) + for (int bh = 0; bh < gh / M; ++bh) + for (int bw = 0; bw < gw / M; ++bw) + for (int mh = 0; mh < M; ++mh) + for (int mw = 0; mw < M; ++mw) { + const int py0 = (bh * M + mh) * P, px0 = (bw * M + mw) * P; + for (int ch = 0; ch < 3; ++ch) + for (int t = 0; t < T; ++t) { + const Frame& f = *frames[(size_t)(g * T + t)]; + for (int y = 0; y < P; ++y) { + const uint8_t* row = f.rgb.data() + + ((size_t)(py0 + y) * f.w + px0) * 3 + ch; + for (int x = 0; x < P; ++x) *dst++ = lut[ch][row[x * 3]]; + } + } + } +} + +void finish_item(const VisionConfig& c, Item* it) { + it->patch_dim = c.patch_dim(); + it->n_patch = (int64_t)it->grid_t * it->grid_h * it->grid_w; + it->rows_h = it->grid_h / c.merge; + it->rows_w = it->grid_w / c.merge; + it->seg_rows = it->rows_h * it->rows_w; + it->n_seg = it->grid_t; +} + +} /* namespace */ + +/* ================================================================== the processor */ + +int Processor::init(const VisionConfig& cfg, + std::function(const std::string&)> encode_text) { + if (cfg.patch <= 0 || cfg.temporal <= 0 || cfg.merge <= 0 || cfg.max_patches <= 0) + return RAD_E_INVAL; + cfg_ = cfg; + /* The largest image the encoder takes in one pass, in pixels: the band's ceiling comes down to + * it, so smart_resize itself keeps every image inside a pass. */ + const int64_t pass_px = cfg.max_patches * cfg.patch * cfg.patch; + if (cfg_.image_max_pixels > pass_px) cfg_.image_max_pixels = pass_px; + if (cfg_.image_min_pixels > cfg_.image_max_pixels) cfg_.image_min_pixels = cfg_.image_max_pixels; + if (cfg_.max_video_patches <= 0) + cfg_.max_video_patches = cfg_.video_max_pixels / ((int64_t)cfg.patch * cfg.patch); + encode_text_ = std::move(encode_text); + return RAD_OK; +} + +int Processor::image_from(const Frame& f, std::shared_ptr* out, std::string* why) const { + const VisionConfig& c = cfg_; + int64_t h = 0, w = 0; + RAD_TRY(smart_resize_image(f.h, f.w, c.factor(), c.image_min_pixels, c.image_max_pixels, + &h, &w, why)); + Frame r; + resize_bicubic(f, (int32_t)w, (int32_t)h, &r); + auto it = std::make_shared(); + it->kind = Kind::Image; + it->grid_t = 1; + it->grid_h = (int32_t)(h / c.patch); + it->grid_w = (int32_t)(w / c.patch); + finish_item(c, it.get()); + if (it->n_patch > c.max_patches) { + if (why) *why = "the image resizes to more patches than one encoder pass holds"; + return RAD_E_INVAL; + } + /* An image fills the temporal depth by repetition. */ + std::vector frames((size_t)c.temporal, &r); + patchify(c, frames, it.get()); + content_key(*it, &it->key_hi, &it->key_lo); + + it->expand.reserve((size_t)it->seg_rows + 2); + it->expand.push_back(c.tok_start); + it->seg_at.push_back(1); + it->expand.insert(it->expand.end(), (size_t)it->seg_rows, c.tok_image); + it->expand.push_back(c.tok_end); + *out = std::move(it); + return RAD_OK; +} + +int Processor::video_from(const Video& v, std::shared_ptr* out, std::string* why) const { + const VisionConfig& c = cfg_; + if (v.frames.empty()) { if (why) *why = "the video decoded to no frames"; return RAD_E_INVAL; } + /* The frames and their indices, padded to whole temporal groups by repeating the last. A clip + * shorter than one group is padded the same way, so a single-frame video is one group. */ + std::vector frames; + std::vector idx = v.index; + for (const Frame& f : v.frames) frames.push_back(&f); + while (frames.size() % (size_t)c.temporal != 0 || frames.size() < (size_t)c.temporal) { + frames.push_back(frames.back()); + idx.push_back(idx.back()); + } + const int64_t nf = (int64_t)v.frames.size() < c.temporal ? c.temporal + : (int64_t)v.frames.size(); + + /* THE PER-FRAME CAP: at most `max_frame_rows` output rows' worth of pixels a frame, and the + * video budget's even share, but never under the band's floor. */ + int64_t max_px = c.video_max_pixels; + if (c.max_frame_rows > 0) { + const int64_t f2 = (int64_t)c.factor() * c.factor(); + const int64_t cap = (int64_t)c.max_frame_rows * f2; + const int64_t share = c.video_max_pixels / nf; + const int64_t per = std::max(std::min(cap, share), + (int64_t)((double)c.video_min_pixels * 1.05)); + max_px = per * nf; + } + int64_t h = 0, w = 0; + RAD_TRY(smart_resize_video(nf, v.frames[0].h, v.frames[0].w, c.temporal, c.factor(), + c.video_min_pixels, max_px, &h, &w, why)); + + auto it = std::make_shared(); + it->kind = Kind::Video; + it->grid_t = (int32_t)(frames.size() / (size_t)c.temporal); + it->grid_h = (int32_t)(h / c.patch); + it->grid_w = (int32_t)(w / c.patch); + finish_item(c, it.get()); + if ((int64_t)it->grid_h * it->grid_w > c.max_patches) { + if (why) *why = "a video frame resizes to more patches than one encoder pass holds"; + return RAD_E_INVAL; + } + if (it->n_patch > c.max_video_patches) { + if (why) *why = "the video is over the server's patch budget for one video"; + return RAD_E_INVAL; + } + + /* Resize each distinct frame once; padding repeats share the resized copy. */ + std::vector resized(v.frames.size()); + for (size_t i = 0; i < v.frames.size(); ++i) + resize_bicubic(v.frames[i], (int32_t)w, (int32_t)h, &resized[i]); + std::vector rframes; + for (const Frame* f : frames) rframes.push_back(&resized[(size_t)(f - v.frames.data())]); + patchify(c, rframes, it.get()); + content_key(*it, &it->key_hi, &it->key_lo); + + /* THE TIMESTAMPED EXPANSION: per temporal group, "" then a run of pads between + * vision_start and vision_end, T being the mean of the group's first and last frame times. + * It stands for the template's whole <|vision_start|><|video_pad|><|vision_end|>, as the + * model's own processor wrote it (transformers 4.57, qwen-vl-utils). transformers 5.x swaps + * only the pad and leaves that outer pair around the frames -- two tokens the model was not + * trained with. */ + const double vfps = v.info.fps > 0.0 ? v.info.fps : 24.0; + for (int32_t g = 0; g < it->grid_t; ++g) { + const double t0 = (double)idx[(size_t)g * c.temporal] / vfps; + const double t1 = (double)idx[(size_t)g * c.temporal + c.temporal - 1] / vfps; + char ts[64]; + std::snprintf(ts, sizeof ts, "<%.1f seconds>", (t0 + t1) / 2.0); + const std::vector tt = encode_text_ ? encode_text_(ts) : std::vector{}; + if (tt.empty()) { + if (why) *why = "the tokenizer produced nothing for a video timestamp"; + return RAD_E_STATE; + } + it->expand.insert(it->expand.end(), tt.begin(), tt.end()); + it->expand.push_back(c.tok_start); + it->seg_at.push_back((int32_t)it->expand.size()); + it->expand.insert(it->expand.end(), (size_t)it->seg_rows, c.tok_video); + it->expand.push_back(c.tok_end); + } + *out = std::move(it); + return RAD_OK; +} + +int Processor::image(const uint8_t* bytes, size_t n, std::shared_ptr* out, + std::string* why) const { + Frame f; + RAD_TRY(decode_image(bytes, n, cfg_.max_source_pixels, &f, why)); + return image_from(f, out, why); +} + +namespace { +struct SampleArgs { double fps; int32_t lo, hi; }; +std::vector sample_cb(const VideoInfo& info, const void* user) { + const SampleArgs* a = static_cast(user); + return sample_frames(info, a->fps, a->lo, a->hi); +} +} /* namespace */ + +int Processor::video(const uint8_t* bytes, size_t n, std::shared_ptr* out, + std::string* why) const { + Video v; + const SampleArgs a{ cfg_.fps, cfg_.min_frames, cfg_.max_frames }; + RAD_TRY(decode_video(bytes, n, sample_cb, &a, cfg_.max_source_pixels, &v, why)); + return video_from(v, out, why); +} + +/* ================================================================== rotary layout */ + +void PromptMedia::layout() { + rope.runs.clear(); + int64_t pos = 0, tok = 0; + for (size_t pi = 0; pi < items.size(); ++pi) { + const Placed& p = items[pi]; + const Item& it = *p.item; + for (int32_t s = 0; s < it.n_seg; ++s) { + const int64_t run_tok = (int64_t)p.tok + it.seg_at[(size_t)s]; + pos += run_tok - tok; /* the text in front of the run counts up */ + RopeLayout::Run r; + r.tok = (int32_t)run_tok; + r.n = it.seg_rows; + r.w = it.rows_w; + r.base = (int32_t)pos; + pos += std::max(it.rows_h, it.rows_w); + tok = run_tok + it.seg_rows; + r.shift = (int32_t)(pos - tok); + r.item = (int32_t)pi; + r.row0 = s * it.seg_rows; + rope.runs.push_back(r); + } + } +} + +} /* namespace mm */ +} /* namespace rad */ diff --git a/core/mm/processor.h b/core/mm/processor.h new file mode 100644 index 00000000..a03d7e19 --- /dev/null +++ b/core/mm/processor.h @@ -0,0 +1,208 @@ +/* processor.h -- what an image or a video becomes before an encoder sees it (spec §11). + * + * THIS IS THE QWEN-VL PROCESSOR FAMILY (Qwen2-VL through Qwen3.x), and what is family-specific is + * the arithmetic, not the numbers: every size, rate and token id comes from the container, which + * carries the checkpoint's config.json and its two preprocessor configs (rad-convert writes them + * under `vision_config.*`, `preprocessor.*` and `video_preprocessor.*`). What the family fixes: + * + * - A picture is resized so both sides are multiples of patch * merge and its area falls in the + * configured band, keeping the aspect ratio (smart_resize), with PIL's antialiased bicubic. + * - It is cut into patch x patch squares, `temporal` frames deep -- an image is repeated to fill + * the depth -- in MERGE-BLOCK ORDER: the merge x merge patches that become one output row are + * consecutive. Each patch row is (channel, frame, y, x), normalised by the configured mean and + * deviation, in bf16. + * - The prompt gets ` pad*N ` where the template put the media, N + * being the encoder's output rows. A video gets one such run per temporal group, each after + * the text `` giving the group's time -- which is how the model knows when a frame + * is, since the groups share one temporal rotary component. + * - Rotary positions are three components (temporal, height, width): text counts up in all + * three; a media run holds its start in the first and adds its row and column to the other + * two; the text after it continues from start + max(rows, cols). (RopeLayout below.) + * + * The encoder's input is patches plus each patch's (row, col) in its segment and the segment's + * size, which is all a learned position table and a 2-D rotary embedding need; the processor + * produces those too, so the core stages them without knowing what they are for. + */ +#pragma once +#include "mm/media.h" + +#include +#include +#include +#include +#include + +struct RadModelMeta; + +namespace rad { +namespace mm { + +enum class Kind { Image, Video }; + +struct VisionConfig { + int32_t patch = 0, temporal = 0, merge = 0; + int64_t image_min_pixels = 0, image_max_pixels = 0; + int64_t video_min_pixels = 0, video_max_pixels = 0; + double fps = 2.0; + int32_t min_frames = 4, max_frames = 768; + /* The per-frame ceiling on a video's resolution, in output rows: a clip that samples few + * frames does not spend the whole video budget on near-native frames, so the cost of a video + * grows with its length (the reference processor's per-frame cap). 0 turns the cap off. */ + int32_t max_frame_rows = 768; + float mean[3] = { 0.5f, 0.5f, 0.5f }; + float stdv[3] = { 0.5f, 0.5f, 0.5f }; + int32_t tok_image = -1, tok_video = -1, tok_start = -1, tok_end = -1; + + /* THE DEPLOYMENT'S BOUNDS, not the checkpoint's. `max_patches` is the encoder's pass size: an + * image is one segment and a segment is never split, so no image may resize past it, and the + * image band's ceiling is lowered to fit. `max_source_pixels` bounds what the decoder is asked + * to hold before any resize. */ + int64_t max_patches = 0; + int64_t max_source_pixels = (int64_t)1 << 26; + /* A whole video's patch budget, across all its passes. */ + int64_t max_video_patches = 0; + + int64_t patch_dim() const { return 3LL * temporal * patch * patch; } + int32_t factor() const { return patch * merge; } + + /* Read from the container. Refuses a container that states no vision tower; the defaults for + * the processor-only keys are the family's, used only when the container omits them. */ + int from_meta(const RadModelMeta& m, std::string* why); +}; + +/* One media part after processing: its patches, its place in the prompt's token stream, and -- + * once the encoder has run -- its rows. Shared between the request that owns it and the engine + * thread that encodes it; the engine writes `embd` once and nothing reads it before then. */ +struct Item { + Kind kind = Kind::Image; + int32_t grid_t = 0, grid_h = 0, grid_w = 0; /* in patches; grid_t temporal groups */ + int64_t n_patch = 0; + int64_t patch_dim = 0; + std::vector pixels; /* [n_patch, patch_dim] bf16 */ + + /* The encoder's output: n_seg segments of seg_rows rows, one segment per temporal group. + * `rows_w` is a segment's width in output rows, which is where its rotary grid wraps. */ + int32_t n_seg = 0, seg_rows = 0, rows_w = 0, rows_h = 0; + int64_t n_rows() const { return (int64_t)n_seg * seg_rows; } + + /* THE TOKENS THAT REPLACE THE MEDIA MARKER, and where in them each segment's run of + * placeholders starts. Placeholders are the checkpoint's own pad ids, not an arbitrary one: + * an n-gram embedding hashes them like any other id. */ + std::vector expand; + std::vector seg_at; + + /* A CONTENT KEY over the patches and the grid. It is taken BEFORE the encoder runs, so a + * prefix-cache hit over this item skips the encoder as well as the prefill: the patches are + * what the encoder is a function of, and they already reflect every preprocessing choice. */ + uint64_t key_hi = 0, key_lo = 0; + + /* [n_rows, n_embd] bf16, written by the engine after the encoder pass. */ + std::vector embd; + bool encoded = false; + /* Handed to the engine's encoder queue and not yet encoded -- the scheduler's thread only. */ + bool queued = false; + + /* The (row, col, rows, cols) of each patch in its segment, for the encoder: component-major, + * four planes of `count` entries, patches [first, first + count). */ + void coords(int64_t first, int64_t count, int32_t* planes) const; +}; + +/* THE ROTARY LAYOUT OF ONE PROMPT: which tokens are media and where each run's grid sits. Built + * once when the prompt is tokenised; `at` is what the batch builder asks for every row of every + * pass, so it is a binary search over runs rather than an array the length of the prompt. */ +struct RopeLayout { + struct Run { + int32_t tok = 0; /* first placeholder token of the run */ + int32_t n = 0; /* its length: rows_h * rows_w */ + int32_t w = 0; /* its width in rows */ + int32_t base = 0; /* the rotary position of its first token */ + int32_t shift = 0; /* rotary minus token index for the text AFTER the run */ + int32_t item = 0; /* which of PromptMedia::items the run belongs to */ + int32_t row0 = 0; /* the item's encoder row that its first token takes */ + }; + std::vector runs; /* ascending */ + + bool empty() const { return runs.empty(); } + + /* The last run starting at or before token i, or null. Inline and dependency-free, because + * the batch builder asks it for every row of every pass. */ + const Run* last_at(int64_t i) const { + size_t lo = 0, hi = runs.size(); + while (lo < hi) { + const size_t mid = (lo + hi) / 2; + if ((int64_t)runs[mid].tok <= i) lo = mid + 1; else hi = mid; + } + return lo == 0 ? nullptr : &runs[lo - 1]; + } + /* (t, h, w) of token index i. Past the prompt, text continues from the last run's shift. */ + void at(int64_t i, int32_t out[3]) const { + const Run* r = last_at(i); + if (!r) { out[0] = out[1] = out[2] = (int32_t)i; return; } + const int64_t k = i - r->tok; + if (k < r->n) { + out[0] = r->base; + out[1] = r->base + (int32_t)(k / r->w); + out[2] = r->base + (int32_t)(k % r->w); + return; + } + out[0] = out[1] = out[2] = (int32_t)(i + r->shift); + } + /* Rotary minus index for text at or after token i -- the one number a decode row needs. */ + int32_t shift_at(int64_t i) const { + const Run* r = last_at(i); + return r ? r->shift : 0; + } + /* The run holding token i, or null when i is text. */ + const Run* run_at(int64_t i) const { + const Run* r = last_at(i); + return r && i - r->tok < r->n ? r : nullptr; + } +}; + +/* THE MEDIA A PROMPT CARRIES, in prompt order, with where each item's expansion begins. */ +struct Placed { + std::shared_ptr item; + int32_t tok = 0; /* index of item->expand[0] in the prompt */ +}; + +struct PromptMedia { + std::vector items; + RopeLayout rope; + /* Build `rope` from `items`, which must be placed and in prompt order. */ + void layout(); +}; + +class Processor { +public: + /* `encode_text` tokenises the timestamp text between a video's groups: plain text, no + * special tokens added and none parsed. */ + int init(const VisionConfig& cfg, std::function(const std::string&)> encode_text); + const VisionConfig& config() const { return cfg_; } + + int image(const uint8_t* bytes, size_t n, std::shared_ptr* out, std::string* why) const; + int video(const uint8_t* bytes, size_t n, std::shared_ptr* out, std::string* why) const; + + /* The pieces, exposed for the test suite: an already-decoded picture or frame list. */ + int image_from(const Frame& f, std::shared_ptr* out, std::string* why) const; + int video_from(const Video& v, std::shared_ptr* out, std::string* why) const; + +private: + VisionConfig cfg_{}; + std::function(const std::string&)> encode_text_; +}; + +/* smart_resize, the image form: (height, width) -> multiples of `factor` in [min, max] pixels. */ +int smart_resize_image(int64_t h, int64_t w, int32_t factor, int64_t min_px, int64_t max_px, + int64_t* oh, int64_t* ow, std::string* why); +/* ...and the video form, which counts the frames into the budget. */ +int smart_resize_video(int64_t t, int64_t h, int64_t w, int32_t tfactor, int32_t factor, + int64_t min_px, int64_t max_px, int64_t* oh, int64_t* ow, std::string* why); +/* Which frames a video keeps. */ +std::vector sample_frames(const VideoInfo& info, double fps, int32_t min_frames, + int32_t max_frames); +/* PIL's antialiased bicubic resample of packed RGB, bit for bit: fixed-point coefficients, a + * horizontal pass into an 8-bit intermediate and then a vertical one. */ +void resize_bicubic(const Frame& in, int32_t w, int32_t h, Frame* out); + +} /* namespace mm */ +} /* namespace rad */ diff --git a/core/place/heat.cpp b/core/place/heat.cpp new file mode 100644 index 00000000..9ee56410 --- /dev/null +++ b/core/place/heat.cpp @@ -0,0 +1,627 @@ +/* heat.cpp -- the heat engine's mechanics. See heat.h for why any of it is shaped this way. */ +#include "heat.h" + +#include +#include + +namespace rad { + +namespace { +/* The width of one observe() block: a layer's run of positions is a whole number of these, so + * every block has the same trip count and the compiler vectorizes it with no scalar remainder. */ +constexpr int32_t kLanes = 16; +/* What the movable units with no layer are padded to. */ +constexpr int32_t kBlock = 64; +} /* namespace */ + +int HeatEngine::init(const Plan& plan, const HeatParams& params) { + params_ = params; + stats_ = HeatStats{}; + + const size_t n = plan.units.size(); + tier_.assign(n, Tier::VRAM); + busy_.assign(n, 0u); + movable_.assign(n, 0u); + layer_of_.assign(n, -1); + bytes_.assign(n, 0); + ever_.assign(n, 0u); + + /* The movable units' slab classes, as dense indices -- see heat.h's `cls_`. */ + cls_.assign(n, -1); + { + std::vector dense; + for (size_t u = 0; u < n; ++u) { + const MoveUnit& mu = plan.units[u]; + if (!mu.movable) continue; + const int32_t k = mu.slab_class; + auto it = std::find(dense.begin(), dense.end(), k); + if (it == dense.end()) { dense.push_back(k); it = dense.end() - 1; } + cls_[u] = (int32_t)(it - dense.begin()); + } + n_cls_ = dense.empty() ? 1 : (int32_t)dense.size(); + } + n_hot_.assign((size_t)n_cls_, 0); + n_cold_.assign((size_t)n_cls_, 0); + m_of_.assign((size_t)n_cls_, 0); + + n_layer_ = 0; + for (const MoveUnit& mu : plan.units) n_layer_ = std::max(n_layer_, mu.layer + 1); + if (n_layer_ < 0) n_layer_ = 0; + res_count_.assign((size_t)n_layer_, 0); + + /* Each layer's units by expert id, and each slot's other movable units in plan order: a + * layer's, then (slot n_layer_) those with no layer. Two units naming one (layer, expert) + * leave the later one indexed by the expert -- the one a histogram credits -- and the + * earlier, if it can move, among the layer's others. */ + std::vector> by_expert((size_t)n_layer_); + std::vector> other((size_t)n_layer_ + 1); + int64_t movable = 0; + for (size_t u = 0; u < n; ++u) { + const MoveUnit& mu = plan.units[u]; + tier_[u] = mu.tier; + layer_of_[u] = mu.layer; + bytes_[u] = mu.bytes; + movable_[u] = mu.movable ? 1u : 0u; + if (mu.movable) ++movable; + if (mu.layer < 0) { + if (mu.movable) other[(size_t)n_layer_].push_back((int32_t)u); + continue; + } + if (mu.tier == Tier::VRAM) ++res_count_[(size_t)mu.layer]; + if (mu.expert >= 0) { + auto& row = by_expert[(size_t)mu.layer]; + if ((size_t)mu.expert >= row.size()) row.resize((size_t)mu.expert + 1, -1); + const int32_t was = row[(size_t)mu.expert]; + if (was >= 0 && movable_[(size_t)was]) other[(size_t)mu.layer].push_back(was); + row[(size_t)mu.expert] = (int32_t)u; + } else if (mu.movable) { + other[(size_t)mu.layer].push_back((int32_t)u); + } + } + + pos_.assign(n, -1); + unit_at_.clear(); + unit_at_.reserve(n + (size_t)(n_layer_ + 1) * kLanes + kBlock); + n_ex_.assign((size_t)n_layer_, 0); + slot_lo_.assign((size_t)n_layer_ + 2, 0); + auto place = [&](int32_t u) { + if (u >= 0) pos_[(size_t)u] = (int32_t)unit_at_.size(); + unit_at_.push_back(u); + }; + for (size_t s = 0; s <= (size_t)n_layer_; ++s) { + slot_lo_[s] = (int32_t)unit_at_.size(); + if (s < (size_t)n_layer_) { + for (int32_t u : by_expert[s]) place(u); + n_ex_[s] = (int32_t)by_expert[s].size(); + } + for (int32_t u : other[s]) place(u); + const int32_t to = s < (size_t)n_layer_ ? kLanes : kBlock; + while (unit_at_.size() % (size_t)to) place(-1); + } + slot_lo_[(size_t)n_layer_ + 1] = (int32_t)unit_at_.size(); + for (size_t u = 0; u < n; ++u) + if (pos_[u] < 0) place((int32_t)u); + + const size_t np = unit_at_.size(); + heat_.assign(np, 0.0f); + rank_as_.assign(np, 0u); + routed_as_.assign(np, 0u); + miss_bytes_.assign(np, 0); + for (size_t u = 0; u < n; ++u) set_place((int32_t)u); + + /* Each slot's lowest movable unit index, for step()'s tie test. */ + min_unit_.assign((size_t)n_layer_ + 1, INT32_MAX); + for (size_t sl = 0; sl <= (size_t)n_layer_; ++sl) + for (int32_t p = slot_lo_[sl]; p < slot_lo_[sl + 1]; ++p) { + const int32_t u = unit_at_[(size_t)p]; + if (u >= 0 && movable_[(size_t)u] && u < min_unit_[sl]) min_unit_[sl] = u; + } + + end_hot_.assign((size_t)n_layer_ + 1, 0.0f); + end_cold_.assign((size_t)n_layer_ + 1, 0.0f); + end_n_off_.assign((size_t)n_layer_ + 1, 0); + end_n_on_.assign((size_t)n_layer_ + 1, 0); + end_n_cold_.assign((size_t)n_layer_ + 1, 0); + end_ok_.assign((size_t)n_layer_ + 1, 0); + + /* Two ways to be off, and they are different facts worth different lines. A static plan is a + * mode the operator asked for; a plan with nothing movable is a model that does not need this + * engine -- the all-in-VRAM degenerate case, where the mover never runs either. */ + if (!plan.dynamic) { + enabled_ = false; + RAD_INFO("placement is static (--deterministic): the heat engine will not run, so " + "residency -- and therefore the summation order -- is fixed for the run"); + return RAD_OK; + } + if (movable == 0) { + enabled_ = false; + RAD_DEBUG("heat engine: nothing movable in this plan; every weight is statically placed"); + return RAD_OK; + } + enabled_ = true; + RAD_INFO("heat engine: %lld movable units, %d move%s a dispatch, " + "decay %.3f hysteresis %.2f min-gain %.2f", + (long long)movable, params_.moves_per_dispatch, + params_.moves_per_dispatch == 1 ? "" : "s", + (double)params_.decay, (double)params_.hysteresis, (double)params_.min_gain); + return RAD_OK; +} + + +void HeatEngine::observe_ids(int32_t layer, const int32_t* experts, const int32_t* counts, + int32_t n) { + if (!enabled_ || layer < 0 || layer >= n_layer_) return; + /* The histogram these name, dense, so both entry points are the one pass. */ + const int32_t n_ex = n_ex_[(size_t)layer]; + std::vector dense((size_t)n_ex, 0); + for (int32_t i = 0; i < n; ++i) { + const int32_t e = experts[i]; + if (e >= 0 && e < n_ex) dense[(size_t)e] += counts ? counts[i] : 1; + } + observe(layer, dense.data(), n_ex, 1.0f); +} + +/* DECAY EVERY POSITION, THEN CREDIT THE ROUTED ONES. Decay first, then credit: the other order + * gives THIS dispatch's experts a decayed count, which makes min_gain = 1.0 mean 1/decay + * activations rather than one -- the kind of off-by-a-constant that only ever shows up as a + * threshold that does not do what it says. + * + * THE DECAY IS THE ONLY WORK EVERY POSITION NEEDS, so it is the only dense pass: one multiply a + * float, vector code at any instruction set. A dispatch routes to a few dozen of a layer's + * hundreds of experts, and everything else -- the credit, the pricing, the layer's ends -- is a + * property of those, so it is done for those alone. `h * d` and then `+ c * w` round exactly as + * the one expression `h * d + c * w` does, so the heats are the same bits either way. + * + * A ROUTED EXPERT IS PRICED HERE TOO. A unit not in VRAM is not a stall -- the GEMM reads it + * where it lies -- but for every tier above VRAM that read crosses the link, and those are the + * bytes the mover exists to stop paying. Pricing them on the pass that credits the heat puts the + * hit rate and the streamed bytes beside the policy's decisions. + * + * THE LAYER'S ENDS FOLLOW FROM THE CREDITED EXPERTS WHEN THEY WERE VALID. A positive scale keeps + * every order, and rounding is monotone, so the hottest unit off the device decays to exactly + * `hot * d` and nothing uncredited passes it: the new hot end is that or a credited unit, whichever + * is larger. The coldest units on the device decay to exactly `cold * d` likewise, and a credit + * only raises a unit, so the cold end stands while any unit is left at it. The ends count the + * units AT the cold value -- equal heats decay to equal heats -- because the common cold end is + * a crowd: every resident unit no token has routed to yet sits at exactly zero. Only when the + * last of them is credited is the next coldest unknown here, and the layer is rebuilt from its + * positions. A tie decay creates is not counted, which can only rebuild a layer that did not need + * it. */ +void HeatEngine::observe(int32_t layer, const int32_t* counts, int32_t n_expert, float weight) { + if (!enabled_ || layer < 0 || layer >= n_layer_ || !counts) return; + if (!(weight > 0.0f)) weight = 1.0f; + /* Passes this histogram stands for -- see observe()'s contract. At least one, so a caller + * that does not set it still prices its reads. */ + const uint64_t passes = weight >= 1.0f ? (uint64_t)(weight + 0.5f) : 1u; + + const size_t l = (size_t)layer; + const int32_t lo = slot_lo_[l], len = slot_lo_[l + 1] - lo; + /* Past the histogram's last expert, and past the layer's, a position is credited nothing. */ + const int32_t n = std::max(0, std::min(n_expert, n_ex_[l])); + const float d = params_.decay; + + /* THE HISTOGRAM ARRIVES BY DMA, so none of it is in the cache: every line is a miss, and a + * scan that meets them one at a time pays one latency a line. Asked for all at once they + * overlap each other and the decay below -- and a caller sweeping layers asks earlier still + * (prefetch()), which makes this a no-op. */ + prefetch(counts, n); + + float* __restrict h = heat_.data() + lo; + for (int32_t j = 0; j < len; ++j) h[j] *= d; + + bool ends = end_ok_[l] != 0; + float hot = ends && end_n_off_[l] > 0 ? end_hot_[l] * d : -INFINITY; + const float cold = ends && end_n_on_[l] > 0 ? end_cold_[l] * d : INFINITY; + int32_t n_cold = ends ? end_n_cold_[l] : 0; + int32_t routed = 0, resident = 0; + int64_t miss = 0; + auto credit = [&](int32_t j) { + const int32_t c = counts[j]; + const size_t q = (size_t)(lo + j); + const float was = h[j]; + const float x = was + (float)c * weight; + h[j] = x; + routed += routed_as_[q] != 0; + resident += routed_as_[q] == 2; + miss += miss_bytes_[q]; + if (rank_as_[q] == 1) hot = std::max(hot, x); + else if (rank_as_[q] == 2 && was <= cold && --n_cold <= 0) ends = false; + }; + /* A dispatch routes to a few dozen of the layer's experts, so the credited ones are found a + * block at a time -- a mask of the positive counts is vector code -- and only its set bits are + * visited, in increasing order as a scan would meet them. */ + int32_t j0 = 0; + for (; j0 + kLanes <= n; j0 += kLanes) { + uint32_t m = 0; + for (int32_t j = 0; j < kLanes; ++j) m |= (uint32_t)(counts[j0 + j] > 0) << j; + for (; m; m &= m - 1) credit(j0 + __builtin_ctz(m)); + } + for (int32_t j = j0; j < n; ++j) + if (counts[j] > 0) credit(j); + + if (ends) { + end_hot_[l] = end_n_off_[l] ? hot : 0.0f; + end_cold_[l] = end_n_on_[l] ? cold : 0.0f; + end_n_cold_[l] = n_cold; + } else { + end_rebuild(l); + } + + stats_.routed += (uint64_t)routed * passes; + stats_.routed_resident += (uint64_t)resident * passes; + stats_.stream_bytes += (uint64_t)miss * passes; + ++stats_.dispatches; +} + +void HeatEngine::set_tier(int32_t unit, Tier t) { + if (unit < 0 || (size_t)unit >= tier_.size()) return; + const int32_t l = layer_of_[(size_t)unit]; + const Tier was = tier_[(size_t)unit]; + if (l >= 0) { + if (was == Tier::VRAM && t != Tier::VRAM) --res_count_[(size_t)l]; + else if (was != Tier::VRAM && t == Tier::VRAM) ++res_count_[(size_t)l]; + } + tier_[(size_t)unit] = t; + set_place(unit); + end_invalidate(unit); + + if (was != Tier::VRAM && t == Tier::VRAM) { + ++stats_.promotions; + if (ever_[(size_t)unit] & 2u) ++stats_.readmits; + if (!(ever_[(size_t)unit] & 1u)) { ++stats_.distinct_promoted; ever_[(size_t)unit] |= 1u; } + } else if (was == Tier::VRAM && t != Tier::VRAM) { + ++stats_.demotions; + ever_[(size_t)unit] |= 2u; + } +} + +void HeatEngine::set_busy(int32_t unit, bool busy) { + if (unit < 0 || (size_t)unit >= busy_.size()) return; + busy_[(size_t)unit] = busy ? 1u : 0u; + set_place(unit); + end_invalidate(unit); +} + +void HeatEngine::set_place(int32_t unit) { + const size_t u = (size_t)unit, p = (size_t)pos_[u]; + const bool vram = tier_[u] == Tier::VRAM; + rank_as_[p] = (!movable_[u] || busy_[u]) ? 0u : vram ? 2u : 1u; + routed_as_[p] = vram ? 2u : 1u; + miss_bytes_[p] = vram ? 0 : bytes_[u]; +} + +void HeatEngine::end_rebuild(size_t slot) { + float hot = 0.0f, cold = 0.0f; + int32_t n_off = 0, n_on = 0, n_cold = 0; + for (int32_t p = slot_lo_[slot], e = slot_lo_[slot + 1]; p < e; ++p) { + const uint8_t r = rank_as_[(size_t)p]; + if (!r) continue; + const float h = heat_[(size_t)p]; + if (r == 2) { + if (n_on++ == 0 || h < cold) { cold = h; n_cold = 1; } + else if (h == cold) ++n_cold; + } else { + if (n_off++ == 0 || h > hot) hot = h; + } + } + end_hot_[slot] = hot; + end_cold_[slot] = cold; + end_n_off_[slot] = n_off; + end_n_on_[slot] = n_on; + end_n_cold_[slot] = n_cold; + end_ok_[slot] = 1; +} + +void HeatEngine::abandon(const Swap& s) { + set_busy(s.promote, false); + set_busy(s.demote, false); +} + +/* THE ONE-PAIR PICK, kept as the definition of the ranking: the hottest movable unit off the device + * against the coldest one on it, ties broken toward the layer that most needs the slot, and the + * first unit in index order on a full tie. step() proposes exactly the pairs repeated calls to + * this would, from one pass. */ +bool HeatEngine::pick(Swap* out) const { + if (!enabled_ || !warm() || !out) return false; + + /* Each class's hottest unit off the device and coldest one on it: a swap stays in its class + * (heat.h's `cls_`). */ + std::vector hot((size_t)n_cls_, -1), cold((size_t)n_cls_, -1); + std::vector hot_h((size_t)n_cls_, 0.0f), cold_h((size_t)n_cls_, 0.0f); + std::vector hot_res((size_t)n_cls_, 0), cold_res((size_t)n_cls_, 0); + + for (size_t i = 0; i < movable_.size(); ++i) { + if (!movable_[i] || busy_[i]) continue; + const size_t c = (size_t)cls_[i]; + const int32_t l = layer_of_[i]; + const int32_t rc = l >= 0 ? res_count_[(size_t)l] : 0; + const float h = heat_[(size_t)pos_[i]]; + if (tier_[i] == Tier::VRAM) { + /* Colder wins; on an exact tie take from the layer holding the MOST resident units, + * which is the layer that can spare it. */ + if (cold[c] < 0 || h < cold_h[c] || (h == cold_h[c] && rc > cold_res[c])) { + cold[c] = (int32_t)i; cold_h[c] = h; cold_res[c] = rc; + } + } else { + /* Hotter wins; on an exact tie the layer with the FEWEST resident units wins, because + * that is the layer whose tokens are missing most often. Both halves of this are the + * same statement about where capacity should sit. + * + * Tier::SSD is a candidate here and Tier::HostPinned is too, deliberately: this + * engine promotes UP from wherever the unit is, and the mover knows which source that + * means. What it never does is push a unit DOWN to the file tier -- banishing + * something to disk is a bet that it will not be needed, paid at a full read every + * time the bet is wrong, and a frequency counter has no forward-looking confidence to + * justify one. Demotion targets the host pool, and only the planner assigns SSD. */ + if (hot[c] < 0 || h > hot_h[c] || (h == hot_h[c] && rc < hot_res[c])) { + hot[c] = (int32_t)i; hot_h[c] = h; hot_res[c] = rc; + } + } + } + + /* BOTH guards, and they answer different failures. The ratio stops a swap that trades one + * warm unit for another; the additive floor stops the degenerate case where the victim's heat + * is zero, which every ratio passes trivially and which describes most of the resident set + * right after warmup. Of the classes whose pair passes, the one with the hotter candidate. */ + int32_t best = -1; + for (int32_t c = 0; c < n_cls_; ++c) { + if (hot[(size_t)c] < 0 || cold[(size_t)c] < 0) continue; + if (hot_h[(size_t)c] < cold_h[(size_t)c] * params_.hysteresis + params_.min_gain) continue; + if (best < 0 || hot_h[(size_t)c] > hot_h[(size_t)best] || + (hot_h[(size_t)c] == hot_h[(size_t)best] && + (hot_res[(size_t)c] < hot_res[(size_t)best] || + (hot_res[(size_t)c] == hot_res[(size_t)best] && hot[(size_t)c] < hot[(size_t)best])))) + best = c; + } + if (best < 0) return false; + + out->promote = hot[(size_t)best]; + out->demote = cold[(size_t)best]; + return true; +} + +/* THE WHOLE DISPATCH'S PROPOSALS FROM ONE PASS. Marking a pair busy changes neither a unit's heat + * nor any layer's resident count, so the m-th pair repeated pick() calls would return is simply the + * m-th entry at each end of the same ranking. One pass keeps the `moves_per_dispatch` best of each + * end; the proposals, and the counters that say why the list stopped, are the ones the repeated + * picks produce. This runs before every pass a rank issues -- draft passes included, where the + * device waits for the issue -- so a scan per proposed move would be most of its cost. */ +namespace { +using Ranked = HeatRanked; +/* Hotter first, then the layer with fewer residents, then the lower index. */ +inline bool hotter(const Ranked& a, const Ranked& b) { + if (a.h != b.h) return a.h > b.h; + if (a.rc != b.rc) return a.rc < b.rc; + return a.unit < b.unit; +} +/* Colder first, then the layer with more residents, then the lower index. */ +inline bool colder(const Ranked& a, const Ranked& b) { + if (a.h != b.h) return a.h < b.h; + if (a.rc != b.rc) return a.rc > b.rc; + return a.unit < b.unit; +} +/* Insert into a sorted list of at most `k`, dropping what falls off the end. */ +template +inline void keep_best(Ranked* v, int* n, int k, const Ranked& x, Less less) { + if (*n == k && !less(x, v[k - 1])) return; + int i = *n < k ? (*n)++ : k - 1; + while (i > 0 && less(x, v[i - 1])) { v[i] = v[i - 1]; --i; } + v[i] = x; +} +} /* namespace */ + +int HeatEngine::step(std::vector* out) { + if (!out) return RAD_E_INVAL; + out->clear(); + if (!enabled_) return RAD_OK; + const int k = params_.moves_per_dispatch; + if (k <= 0) return RAD_OK; + + /* THE BEST PAIR FROM THE LAYERS' ENDS FIRST. If it fails the guard every pair does -- the + * ranking only gets colder at one end and warmer at the other -- and the dispatch proposes + * nothing, which is the verdict the full ranking below reaches, from one entry a layer. The + * ends also count the candidates at each end, which is all the stop reasons below need. */ + int64_t n_off = 0, n_on = 0; + float bar = 0.0f; + { + float hot_h = 0.0f, cold_h = 0.0f; + for (size_t l = 0; l < end_ok_.size(); ++l) { + if (!end_ok_[l]) end_rebuild(l); + if (end_n_off_[l] > 0 && (n_off == 0 || end_hot_[l] > hot_h)) hot_h = end_hot_[l]; + if (end_n_on_[l] > 0 && (n_on == 0 || end_cold_[l] < cold_h)) cold_h = end_cold_[l]; + n_off += end_n_off_[l]; + n_on += end_n_on_[l]; + } + if (!warm() || n_off == 0 || n_on == 0 || + hot_h < cold_h * params_.hysteresis + params_.min_gain) { + if (n_off > 0 && n_on > 0) ++stats_.refused; else ++stats_.no_candidate; + return RAD_OK; + } + bar = cold_h * params_.hysteresis + params_.min_gain; + } + + /* THE RANKING, over every movable position. A unit can only enter a full list by reaching + * its last entry's heat, so each block of positions is first screened against the two lists' + * last heats -- one compare a position, over contiguous floats -- and only what passes the + * screen meets the exact comparison, ties and all. The screen passes a tie, so it never drops + * a unit the comparison would keep; and the lists are a strict order's best k, so meeting the + * units in position order rather than unit order ends in the same lists. + * + * The hot end is screened against the guard as well. A unit colder than the coldest resident + * unit's bar fails the guard against every victim the cold list can hold, so it cannot be + * proposed, and the list it is kept out of only ever ends at the pair that fails. A layer's + * run is a whole number of kLanes blocks, so every block has the same trip count and the + * screen is vector code. + * + * A WHOLE LAYER IS SCREENED FIRST, BY ITS ENDS. Most resident units sit at exactly the cold + * end's heat -- zero, for every one no token has routed to lately -- and the position screen + * passes a tie, so it would send nearly every resident unit to the exact comparison only for + * the tie break to refuse it. The ends are that layer's hottest candidate off the device and + * coldest on it, so a layer whose hot end is below the hot list's bar and whose cold end + * cannot beat the cold list's last entry holds no unit either list would keep. On a tie the + * comparison falls to the layer's resident count, which every unit of the layer shares, and + * then to the unit index, which the layer's lowest bounds. */ + /* ONE PAIR OF LISTS A CLASS, because a swap stays inside its class (heat.h's `cls_`). The + * screens below take the loosest of the classes' thresholds, so a unit any class's list would + * keep still reaches the exact comparison; with one class they are that class's thresholds + * and the screen is exact. */ + const int nc = n_cls_; + rank_hot_.resize((size_t)(k * nc)); + rank_cold_.resize((size_t)(k * nc)); + Ranked* hot = rank_hot_.data(); + Ranked* cold = rank_cold_.data(); + int32_t* n_hot = n_hot_.data(); + int32_t* n_cold = n_cold_.data(); + for (int c = 0; c < nc; ++c) n_hot[c] = n_cold[c] = 0; + const int64_t n_pool = n_off, n_vram = n_on; + const float* hp = heat_.data(); + const uint8_t* ra = rank_as_.data(); + /* A hot unit reaches a list at the lowest last entry of a full list, and none below the guard; + * a cold one at the highest last entry, and any heat while some list is not full. */ + auto hot_bar = [&]() { + float t = INFINITY; + for (int c = 0; c < nc; ++c) t = std::min(t, n_hot[c] == k ? hot[c * k + k - 1].h : -INFINITY); + return std::max(t, bar); + }; + auto cold_bar = [&]() { + float t = -INFINITY; + for (int c = 0; c < nc; ++c) t = std::max(t, n_cold[c] == k ? cold[c * k + k - 1].h : INFINITY); + return t; + }; + uint8_t pass[kLanes]; + for (int32_t sl = 0; sl <= n_layer_; ++sl) { + const int32_t lo = slot_lo_[(size_t)sl], hi = slot_lo_[(size_t)sl + 1]; + if (lo >= hi) continue; + const float th0 = hot_bar(); + const bool some_hot = end_n_off_[(size_t)sl] > 0 && end_hot_[(size_t)sl] >= th0; + bool some_cold = end_n_on_[(size_t)sl] > 0; + if (some_cold && nc == 1 && n_cold[0] == k) { + const Ranked& last = cold[k - 1]; + const float c = end_cold_[(size_t)sl]; + const int32_t rc = sl < n_layer_ ? res_count_[(size_t)sl] : 0; + some_cold = c < last.h || + (c == last.h && (rc > last.rc || + (rc == last.rc && min_unit_[(size_t)sl] < last.unit))); + } else if (some_cold) { + some_cold = end_cold_[(size_t)sl] <= cold_bar(); + } + if (!some_hot && !some_cold) continue; + for (int32_t b = lo; b < hi; b += kLanes) { + const float th = hot_bar(); + const float tc = cold_bar(); + uint8_t any = 0; + for (int32_t j = 0; j < kLanes; ++j) { + const float h = hp[b + j]; + const uint8_t r = ra[b + j]; + pass[j] = (uint8_t)(((r == 1) & (h >= th)) | (((r == 2) & (h <= tc)) << 1)); + any |= pass[j]; + } + if (!any) continue; + for (int32_t j = 0; j < kLanes; ++j) { + if (!pass[j]) continue; + const int32_t u = unit_at_[(size_t)(b + j)]; + const int32_t l = layer_of_[(size_t)u]; + const int32_t c = cls_[(size_t)u]; + const Ranked r{ hp[b + j], l >= 0 ? res_count_[(size_t)l] : 0, u }; + if (pass[j] & 2) keep_best(cold + c * k, &n_cold[c], k, r, colder); + else keep_best(hot + c * k, &n_hot[c], k, r, hotter); + } + } + } + + /* The proposals: each class's m-th hottest against its m-th coldest, for as long as that + * passes the guard -- the ranking only gets colder at one end and warmer at the other, so the + * first pair that fails ends the class -- and at most `k` of them a class, taken across the + * classes hottest first, which is the order repeated pick() calls would return them in. */ + int32_t* m_of = m_of_.data(); + for (int c = 0; c < nc; ++c) m_of[c] = 0; + int made = 0; + bool short_of_budget = false; + for (;;) { + int best = -1; + for (int c = 0; c < nc; ++c) { + const int32_t m = m_of[c]; + if (m >= k) continue; + if (m >= n_hot[c] || m >= n_cold[c]) { short_of_budget = true; continue; } + const Ranked& h = hot[c * k + m]; + if (h.h < cold[c * k + m].h * params_.hysteresis + params_.min_gain) { + short_of_budget = true; + continue; + } + if (best < 0 || hotter(h, hot[best * k + m_of[best]])) best = c; + } + if (best < 0) break; + Swap s; + s.promote = hot[best * k + m_of[best]].unit; + s.demote = cold[best * k + m_of[best]].unit; + ++m_of[best]; + /* Marked busy on the way out: the caller owns the pair until it publishes or abandons. */ + set_busy(s.promote, true); + set_busy(s.demote, true); + out->push_back(s); + ++stats_.proposed; + ++made; + } + if (short_of_budget) { + /* Two ways to propose nothing more and they are different diagnoses. `refused` is the + * guard declining -- the healthy steady state. `no_candidate` is one end of the ranking + * being empty, which means either everything movable is resident or nothing is, and is a + * budget question rather than a policy one. The pairs already proposed are busy by now, + * so they are not counted at either end. */ + if (n_pool - made > 0 && n_vram - made > 0) ++stats_.refused; else ++stats_.no_candidate; + } + return RAD_OK; +} + + +std::string HeatEngine::report() const { + if (!enabled_) + return "heat engine: off (static placement); residency and therefore the summation " + "order are fixed for the run\n"; + + std::string s = fmt("heat engine: %llu dispatches, %llu swaps proposed, %llu promotions, " + "%llu demotions\n", + (unsigned long long)stats_.dispatches, + (unsigned long long)stats_.proposed, + (unsigned long long)stats_.promotions, + (unsigned long long)stats_.demotions); + s += fmt(" %llu dispatches declined on hysteresis, %llu found no candidate at one end\n", + (unsigned long long)stats_.refused, (unsigned long long)stats_.no_candidate); + /* The one line that says whether the traffic above was worth paying. A readmit is a unit this + * engine demoted and then fetched back: both directions of the link spent to return to where + * it started, on the link the zero-copy tier needs. High here means the guards are too + * loose -- and note that TIGHTENING min_gain to fix it costs more bytes, not fewer. */ + s += fmt(" %llu distinct units promoted, %llu readmits (%.0f%% of promotions were of " + "something already demoted)\n", + (unsigned long long)stats_.distinct_promoted, (unsigned long long)stats_.readmits, + stats_.promotions ? 100.0 * (double)stats_.readmits / (double)stats_.promotions : 0.0); + + /* The histogram this engine exists for. A global profile ranking leaves the per-layer + * resident count wherever it happens to fall; a layer starved of slots misses on nearly every + * token however good the ranking inside it is, which is how a hit rate lands below what + * choosing at random would give. Whether the engine repaired that is a question about this + * DISTRIBUTION, not about the mean. */ + if (!res_count_.empty()) { + int32_t lo = res_count_[0], hi = res_count_[0]; + double sum = 0; + for (int32_t v : res_count_) { lo = std::min(lo, v); hi = std::max(hi, v); sum += v; } + const double mean = sum / (double)res_count_.size(); + double var = 0; + for (int32_t v : res_count_) var += (v - mean) * (v - mean); + s += fmt(" resident units a layer: min %d max %d mean %.1f sd %.1f\n", (int)lo, (int)hi, + mean, std::sqrt(var / (double)res_count_.size())); + /* AND WHICH LAYERS, because min/max/sd cannot be joined to anything. A kernel trace can + * say which layers run longer than their neighbours; only this line can say whether those + * are the starved ones, and without it the two measurements sit in different files saying + * nothing to each other. One line, one number a layer, printed once at exit. */ + s += " per layer:"; + for (size_t i = 0; i < res_count_.size(); ++i) { + if (i % 12 == 0) s += fmt("\n L%-3zu ", i); + s += fmt("%5d", (int)res_count_[i]); + } + s += "\n"; + } + return s; +} + +} /* namespace rad */ diff --git a/core/place/heat.h b/core/place/heat.h new file mode 100644 index 00000000..72d773d4 --- /dev/null +++ b/core/place/heat.h @@ -0,0 +1,318 @@ +/* heat.h -- the heat engine: which conditional weight should be in VRAM, decided from what the + * router actually did. + * + * EXPERT OFFLOAD IS A PREDICTION PROBLEM. Layer offload is not -- declare enumerated the whole + * access sequence and the planner emits an exact prefetch schedule off it. Routing is + * data-dependent, so for RAD_ACCESS_CONDITIONAL weights there is no schedule to emit and the only + * thing left is a policy. This file is that policy and nothing else: it sees a tier per unit, a + * heat per unit and a dispatch count, and it answers one question -- "swap these two." + * + * Deliberately pure host code with no device call in it and no knowledge of slabs, streams or + * events. Everything about how the bytes get there is mover.cpp. That split is what lets the + * entire decision half be tested on a machine with no card, which is the only reason the + * hysteresis behaviour below is checkable at all. + * + * ---- WHAT IT COSTS TO BE ONE STEP BEHIND, HONESTLY ------------------------------------------- + * + * Routing is computed on device and never blocks the compute stream. The histogram is copied back + * asynchronously and this engine consumes it on the NEXT step (spec §5.5), so every placement + * decision is one step stale. + * + * For heat-based promotion that is irrelevant: a hot expert is hot across many steps, and a + * ranking built from the step before ranks almost exactly the same as one built from this step. + * The real cost is different and it is worth being blunt about, because it is what people expect + * this file to do and it does not: + * + * AN EXPERT THAT IS NOT RESIDENT THIS STEP CANNOT BE FETCHED IN TIME. It is served from + * wherever it is -- streamed out of the pinned pool over the link, or staged off the file tier. + * There is no last-moment rescue and there is no point adding one: the fetch would have to + * finish inside the gap between the router's output and the expert GEMM's first block, which + * is microseconds. + * + * Hit rate is therefore a property of the PLACEMENT POLICY, not of a rescue path. That is the + * trade, and what it buys is a run phase with no device round-trip in it. + * + * ---- WHY LFU-WITH-DECAY AND NOT SOMETHING CLEVERER -------------------------------------------- + * + * Replaying real routing traces against cache policies settles the shape of this. Runtime + * placement beats static profile placement by a wide margin, so it is worth building; LFU-with- + * decay and LRU score the same, so the decay constant is not where the wins are and this does not + * need to be subtle. Belady is a few points of hit rate above both -- but an oracle restricted to + * a disjoint sample of the future keeps most of that gap, so the remainder is knowledge of the + * realised future and is not reachable. Of what is left, no statistic of PAST USE captures any of + * it: an expert never selected has count zero, no age and no history, and most of the space is in + * that state. The router's own gate value does separate those cases, so a scorer built on it is + * the one direction here that measurement has not refuted. + */ +#pragma once +#include "planner.h" + +#include +#include + +namespace rad { + +struct HeatParams { + /* Applied to a layer's whole plane each time that layer is dispatched. Every layer is + * dispatched exactly once per forward, so all planes decay in lockstep and heats stay + * comparable ACROSS layers -- which the global ranking below depends on. + * + * 0.98 is a half-life of a few dozen dispatches: long enough to survive a paragraph, short + * enough to follow a change of subject. Nearby values are not distinguishable from each other + * above the run-to-run spread, which is what the offline replay predicts. */ + float decay = 0.98f; + + /* Promote only when the candidate beats the victim by this ratio. Without it the two ends of + * the ranking trade places on noise and the engine spends the whole link on churn that + * changes nothing. */ + float hysteresis = 1.25f; + + /* ...and the additive half of the same guard, in units of one activation. It is what stops a + * swap when the victim's heat is ZERO, where any ratio test passes trivially -- and right + * after warmup that describes most of the resident set, so without this the first dispatch + * would try to swap the entire cache. + * + * LINK TRAFFIC IS U-SHAPED IN THIS THRESHOLD. PAST THE BOTTOM OF THE CURVE, RAISING IT MOVES + * MORE BYTES, NOT FEWER -- so do not "fix" it by tightening the bar to save traffic. The + * economics look one-directional -- a promotion costs an H2D plus a D2H and only pays if the + * expert is selected again -- and they are not, because A PROMOTION DECLINED COMES BACK AS A + * MISS, and a miss is a shard streamed over the same link on the same budget. A tighter bar + * then gives up hit rate and buys no traffic back. + * + * The exchange rate behind the value: the two link directions share one budget, so + * a demotion costs about what a promotion does, and a swap therefore has to repay about 1.4 + * future hits rather than the 0.74 a half-price demotion would imply. */ + float min_gain = 1.5f; + + /* A BOUNDED MOVE BUDGET PER LAYER DISPATCH. The apparent risk is that a high budget makes the + * mover compete with the tier it is trying to shrink -- a promotion and a streamed miss are + * the same bytes over the same link. At this scale that does not bind: a larger budget pays + * even though it moves considerably more bytes, because converging sooner is worth more than + * the traffic costs. The benefit then SATURATES, and this sits where the knob stops mattering + * rather than at the largest value that still helps. Past that point the guard, not the + * budget, is what declines the extra opportunities -- so raising this alone is worth nothing + * until min_gain moves with it. + * + * IT IS A BUDGET PER SLAB CLASS. A rank holding an uneven slice of every expert has two expert + * classes -- the wider slice of one parity's experts and the narrower slice of the other's -- + * each about half a whole expert, and a budget shared between them would move half the bytes + * a dispatch that whole experts do: residency would converge half as fast, and a fresh server + * would run about 2% slower for its first minute. Per class, the two together move about as + * many whole experts as one class of whole experts does. */ + int moves_per_dispatch = 8; + + /* Dispatches to watch before moving anything, and it is 0 because THE GUARD ALREADY DOES THIS + * JOB. min_gain means a promotion needs `hot >= cold*hysteresis + 1.5`, and against a + * zero-heat victim that is two tokens agreeing in one dispatch -- evidence, not noise, + * whatever the dispatch count is. A warmup only postpones convergence. */ + int warmup_dispatches = 0; +}; + +/* A swap is returned as a PAIR even though the mover issues two independent transfers, because + * the DECISION is a comparison between them: promoting without the matching demotion would grow + * the resident set past the slab. */ +struct Swap { + int32_t promote = -1; /* unit index */ + int32_t demote = -1; +}; + +/* One movable unit as step() ranks it: its heat, its layer's resident count, its index. */ +struct HeatRanked { float h; int32_t rc; int32_t unit; }; + +struct HeatStats { + uint64_t dispatches = 0; + uint64_t proposed = 0, promotions = 0, demotions = 0; + /* Why a dispatch did NOT move anything, which is the diagnostic that matters once the engine + * looks idle. `refused` is the guard declining -- the healthy steady state, and the number + * that should dominate once the hot set has settled. */ + uint64_t refused = 0, no_candidate = 0; + /* Is the churn PROGRESS or THRASH? The same total move count means two opposite things. If + * every promotion is of a unit never promoted before, the engine is still discovering the + * working set and the traffic is an investment. If it keeps re-admitting units it demoted a + * moment ago, the traffic is pure loss: both directions of the link spent to arrive back + * where it started. `readmits` is the second case counted directly, and it is the number that + * decides whether the guards are set right. */ + uint64_t distinct_promoted = 0, readmits = 0; + /* WHAT THE ROUTER ASKED FOR, AND WHETHER IT WAS THERE. Counted on the histogram this engine + * already walks, so it is one compare per routed expert and no second pass. + * + * A miss is not an error and nothing stalls on it: the GEMM reads that expert's weights from + * whatever tier holds them, which for a host-pinned unit means pulling them across the link + * on the critical path of the step. So `stream_bytes` is the OTHER traffic the mover's + * promotions were hiding -- a promotion is bytes spent once to stop paying this, and without + * both numbers beside each other there is no way to say whether the policy is winning. + * + * Weighted by the histogram's `weight`, because a draft head's histogram stands for several + * routing passes and each of them really did read its experts. The hit RATE is unaffected -- + * both counters scale together -- and the byte figure is right. + */ + uint64_t routed = 0, routed_resident = 0, stream_bytes = 0; +}; + +class HeatEngine { +public: + /* Binds to the plan. Returns RAD_OK even when the plan is static -- that is a mode, not a + * failure, and every caller would otherwise have to special-case it. `enabled()` says which. + * Under Config::deterministic the plan is static, this stays off, and step() proposes + * nothing for the whole run (spec §17). */ + int init(const Plan& plan, const HeatParams& params); + bool enabled() const { return enabled_; } + + /* ---- the input: last step's routing histogram ------------------------------------------ + * + * `counts[e]` is how many of the step's tokens routed to expert e of this layer. The credit + * is that count and not a flat 1.0: cost is per DISTINCT expert -- a dispatch reads an + * expert's weights once however many tokens chose it -- but the probability of needing it + * again is not. An expert several tokens chose is far likelier to be chosen again soon than + * one a single token chose, and most selections are single-token. Weighting by it moves no + * extra bytes; it only ranks better. */ + /* `weight` is how many of that layer's routing passes this histogram stands for -- see + * Ctx::last_histogram_reports. It is 1 for every layer of a non-speculative step and n_spec + * for a draft head, and it belongs on the CREDIT rather than the decay: the caller sweeps + * every layer exactly once a step, so the planes decay in lockstep and heats stay comparable + * across layers. Without it a single histogram silently stands for several passes' worth of + * activations and under-credits the experts a draft head routed to. */ + void observe(int32_t layer, const int32_t* counts, int32_t n_expert, float weight = 1.0f); + /* The same, sparse: distinct expert ids and their counts. `counts` may be null for one each. */ + void observe_ids(int32_t layer, const int32_t* experts, const int32_t* counts, int32_t n); + /* Starts the fetch of a histogram observe() will read: a row the card copied into host + * memory is a miss on every line, so a caller that knows its next rows asks for them early. */ + static void prefetch(const int32_t* counts, int32_t n_expert) { + for (int32_t j = 0; j < n_expert; j += 64 / (int32_t)sizeof(int32_t)) + __builtin_prefetch(counts + j); + } + + /* ---- the tier map, written by the MOVER when a move PUBLISHES, not when it is issued ---- + * + * Between issue and publish both copies of the bytes are valid and the dispatch still reads + * the old one, so this engine must agree with dispatch about where a unit is or it will pick + * the same one twice. `set_busy` is what excludes an in-flight unit instead. */ + void set_tier(int32_t unit, Tier t); + void set_busy(int32_t unit, bool busy); + Tier tier(int32_t unit) const { return tier_[(size_t)unit]; } + bool busy(int32_t unit) const { return busy_[(size_t)unit] != 0; } + + /* The best swap available, or false when the guards refuse. */ + bool pick(Swap* out) const; + + /* One layer dispatch's worth of proposals, at most `moves_per_dispatch` of them a class. + * + * CONTRACT: every unit named in the result is marked busy on the way out. The caller must + * either issue the transfer -- in which case set_tier() on publish and set_busy(false) after + * the quarantine -- or call abandon() for both halves. A proposal that is silently dropped + * leaves the pair busy forever and the engine goes quiet with no counter to say why. */ + int step(std::vector* out); + void abandon(const Swap& s); + + float heat(int32_t unit) const { return heat_[(size_t)pos_[(size_t)unit]]; } + /* How many units of THIS unit's layer are resident. The tiebreak every residency decision + * needs: a global ranking with no layer term leaves some layers holding far more than others, + * and a layer starved of slots misses on nearly every token however good the ranking inside + * it is. `pick` uses it on an exact heat tie and so must anything else that chooses. */ + int32_t layer_residents(int32_t unit) const { + const int32_t l = (size_t)unit < layer_of_.size() ? layer_of_[(size_t)unit] : -1; + return l >= 0 && (size_t)l < res_count_.size() ? res_count_[(size_t)l] : 0; + } + const HeatStats& stats() const { return stats_; } + + /* The exit banner. The per-layer residency histogram at the end of it is the one number that + * says whether the engine did the thing it exists for: a global profile ranking leaves layers + * with wildly different resident counts, and a layer starved of slots misses on nearly every + * token however good the ranking inside it is. */ + std::string report() const; + +private: + HeatParams params_; + bool enabled_ = false; + int32_t n_layer_ = 0; + HeatStats stats_; + + /* THE HEAT, BY POSITION RATHER THAN BY UNIT. Each layer owns one run of positions, and the + * front of that run is indexed by EXPERT: expert e of layer l sits at slot_lo_[l] + e, whether + * or not the plan has a unit for it and whether or not that unit may move. Then the layer's + * other movable units, then padding to a whole number of lanes. After the layers come the + * movable units with no layer, padded to a whole screening block, and after them everything + * else. + * + * That lines a histogram up with the positions it credits. observe() walks counts[e] and the + * heat at slot_lo_[l] + e side by side, in fixed-width blocks the compiler turns into vector + * code, with no unit number looked up and no branch taken per expert. A position with no unit + * behind it is a hole: never a candidate, never priced, and its heat is read by nothing. + * `pos_` and `unit_at_` translate (-1 for a hole); everything outside the position arrays + * stays indexed by MoveUnit index so this file and the plan cannot disagree about what a + * number means. */ + std::vector heat_; /* by position */ + std::vector pos_; /* unit -> position */ + std::vector unit_at_; /* position -> unit, -1 for a hole */ + /* Per position, what step() ranks it as: 0 not a candidate (fixed, in flight, or a hole), 1 a + * candidate off the device, 2 a candidate on it. Kept by set_tier and set_busy. */ + std::vector rank_as_; + /* Per position, what a routed read of it costs: `routed_as_` is 0 for a hole, 1 off the device + * and 2 in VRAM, and `miss_bytes_` is the unit's bytes when it is off the device and 0 when it + * is not. Kept by set_tier, so pricing a histogram is arithmetic on the pass that credits it. */ + std::vector routed_as_; + std::vector miss_bytes_; + /* Slot s's positions are [slot_lo_[s], slot_lo_[s + 1]): layer s, and slot n_layer_ the + * movable units with no layer. Every movable unit is below slot_lo_[n_layer_ + 1], which is a + * whole number of screening blocks. The first n_ex_[l] positions of layer l are its experts. */ + std::vector slot_lo_; + std::vector n_ex_; + void set_place(int32_t unit); + /* Unit bytes, from the plan. Here so a miss can be priced where it is detected rather than + * joined back to the plan by every reader. */ + std::vector bytes_; + std::vector tier_; + std::vector busy_; + std::vector movable_; + std::vector layer_of_; + /* Bit 0: promoted before. Bit 1: demoted before. Two bits a unit, so the thrash question + * costs nothing on the dispatch path. */ + std::vector ever_; + + /* How many of each layer's units are resident. THE TIE-BREAK IS NOT COSMETIC: most resident + * units are cold, so `heat == 0.0f` exactly is the common case at both ends of the ranking, + * and whatever breaks that tie IS the policy for most of a run. Breaking it by index order + * strips the low-numbered layers first, which replaces the skew this engine exists to fix + * with a different one. So ties go to the layer that can most afford it: take the victim from + * the layer holding the MOST, promote into the one holding the FEWEST. */ + std::vector res_count_; + /* A SWAP STAYS INSIDE ONE SLAB CLASS. The promoted unit takes a slot of its own class and the + * demoted one frees a slot of its own, so a pair across two classes would drain one class's + * spare slots into the other's until promotions starve. A model has one expert class when + * every expert is the same size on a rank, and two when a rank holds an uneven slice of each + * expert's width (three 128-column blocks of one parity, two of the other). `cls_` is the + * unit's class as a dense index, -1 for a unit that cannot move. */ + std::vector cls_; + int32_t n_cls_ = 1; + /* step()'s two ends of the ranking, `moves_per_dispatch` entries a class, kept between calls + * so a dispatch allocates nothing. */ + std::vector rank_hot_, rank_cold_; + std::vector n_hot_, n_cold_, m_of_; + /* Per slot, its lowest movable unit index: the bound step()'s layer screen needs on a tie. */ + std::vector min_unit_; + + /* EACH LAYER'S TWO ENDS, so a dispatch that proposes nothing -- the guard declining the best + * pair, which is nearly every dispatch once the resident set has settled -- is decided from + * one entry a layer rather than a scan of every unit. Over the movable units not in flight: + * the hottest one off the device and the coldest one on it, and how many there are of each. + * Slot n_layer_ is the movable units with no layer. + * + * observe() recomputes a layer's ends on the pass that decays and credits it, where each is + * one more compare on a value already in a register. A change of tier or of being in flight + * invalidates the unit's layer, and an invalid entry is rebuilt from its positions when step() + * next reads it. */ + std::vector end_hot_, end_cold_; + std::vector end_n_off_, end_n_on_; + std::vector end_n_cold_; /* units on the device at exactly the cold end's heat */ + std::vector end_ok_; + void end_rebuild(size_t slot); + void end_invalidate(int32_t unit) { + if (end_ok_.empty()) return; + const int32_t l = (size_t)unit < layer_of_.size() ? layer_of_[(size_t)unit] : -1; + end_ok_[l >= 0 ? (size_t)l : (size_t)n_layer_] = 0; + } + + bool warm() const { return (int64_t)stats_.dispatches >= params_.warmup_dispatches; } +}; + +} /* namespace rad */ diff --git a/core/place/mover.cpp b/core/place/mover.cpp new file mode 100644 index 00000000..a0d4dd5b --- /dev/null +++ b/core/place/mover.cpp @@ -0,0 +1,1442 @@ +/* mover.cpp -- the mover's mechanics. See mover.h for why any of it is shaped this way. + * + * Everything here runs on the DISPATCH THREAD. The transfers are asynchronous -- their own + * stream, gated behind an event recorded after the layer's launches -- but every table edit is + * applied by this thread at a layer boundary, draining a queue of transfers that have landed. No + * mutex on the read side, because that side is the critical path of every layer, and no + * background thread mutating placement mid-layer, because placement would then depend on host + * timing and stop being reproducible. + */ +#include "mover.h" +#include "../device/device.h" + +#include +#include +#include +#include +#include +#include + +namespace rad { + +/* ------------------------------------------------------------------ the file tier */ +int FileTier::open(const std::string& path) { + /* No RAD_DIO_ALLOW_BUFFERED. The weight tier is read on the dispatch path in whole movement + * units; a silent buffered fallback turns it into a page-cache pump that is several times + * slower, evicts the container's own mapped pages, and looks like nothing at all in a + * profile. An operator who pointed the tier at tmpfs wants to be told, not accommodated. */ + const int rc = f_.open(path.c_str(), RAD_DIO_READ); + if (rc < 0) + RAD_ERR("file tier: cannot open %s with O_DIRECT. The tier needs a filesystem that " + "supports it -- tmpfs and some overlay mounts do not.", path.c_str()); + return rc; +} + +int FileTier::read(uint64_t offset, int64_t bytes, void* dst, int64_t dst_cap) { + if (!f_.is_open()) return RAD_E_STATE; + if (!dst || bytes <= 0) return RAD_E_INVAL; + /* The whole extent, rounded up: a movement unit's stride is already aligned, and reading the + * padding costs one block against a branch on the step path. */ + const int64_t want = direct_align(bytes); + if (want > dst_cap) { + RAD_ERR("file tier: a %s read needs a %s aligned buffer, the staging slot is %s", + humanb(bytes).c_str(), humanb(want).c_str(), humanb(dst_cap).c_str()); + return RAD_E_SCRATCH; + } + RAD_TRY(f_.read_at(dst, (int64_t)offset, want)); + ++reads_; + bytes_ += (uint64_t)bytes; + return RAD_OK; +} + +/* ------------------------------------------------------------------ residency */ +void Residency::init(const Program& prog, const Plan& plan) { + (void)plan; + slot_.assign(prog.weights.size(), WeightSlot{}); + noted_.assign(prog.weights.size(), 0); + changed_.clear(); + ++epoch_; +} + +/* The generation bump is the whole of the staleness protocol, and it is deliberately not a lock: + * at this instant BOTH copies of the bytes are valid -- the mover wrote a shadow slot and has not + * freed the old one -- so whichever side of this write a reader lands on names bytes that are + * correct. The quarantine is what makes that sentence stay true. + * + * Both writers bump. `publish` settles a slot whose transfer has landed; `begin_transfer` opens + * one, and it MUST bump too, because the run phase memoises its stream wait per generation and a + * new event at an old generation is a wait that never happens (residency_iface.h). */ +void Residency::publish(rad_weight w, void* ptr) { + if ((size_t)w >= slot_.size()) return; + slot_[w].ptr = ptr; + slot_[w].ready = nullptr; + ++slot_[w].generation; + ++epoch_; + note(w); +} + +void Residency::begin_transfer(rad_weight w, void* ptr, RadEvent ready) { + if ((size_t)w >= slot_.size()) return; + slot_[w].ptr = ptr; + slot_[w].ready = ready; + ++slot_[w].generation; + ++epoch_; + note(w); +} + +/* ------------------------------------------------------------------ the mover */ +Mover::~Mover() { + /* The stream first, drained. What it still holds are the gate waits and the move records + * that name the events below and the copies into and out of the memory below, so each of + * those goes only once nothing queued refers to it. */ + if (mover_) { + rad_stream_sync(mover_); + rad_stream_destroy(mover_); + } + for (Move& m : moves_) if (m.ev) rad_event_destroy(m.ev); + for (RadEvent e : lead_) if (e) rad_event_destroy(e); + for (RadEvent e : win_ev_) if (e) rad_event_destroy(e); + if (gate_) rad_event_destroy(gate_); + /* Only what this object allocated itself. A Pool reservation belongs to the Pool. */ + if (owns_memory_) { + for (ClassPools& c : pools_) { + if (c.slab_base) rad_dev_free(c.slab_base, RAD_MEM_DEVICE); + if (c.pool_base) rad_dev_free(c.pool_base, RAD_MEM_HOST_PINNED); + } + if (static_vram_) rad_dev_free(static_vram_, RAD_MEM_DEVICE); + if (stage_) rad_dev_free(stage_, RAD_MEM_HOST_PINNED); + if (file_vram_) rad_dev_free(file_vram_, RAD_MEM_DEVICE); + if (windows_) rad_dev_free(windows_, RAD_MEM_HOST_PINNED); + } + /* The pageable region is always ours: Pools has no pageable pool, because pageable host + * memory is not a device-visible budget and nothing else contends for it. */ + if (pageable_) rad_dev_free(pageable_, RAD_MEM_HOST); +} + +/* One place the mover asks for memory. Everything device-side and everything pinned comes out of + * the budgets the operator stated (spec §6); the fallback exists so the placement test can run + * without standing a whole Pools up, and it announces itself. */ +void* Mover::reserve(const char* what, int64_t bytes, int kind) { + if (bytes <= 0) return nullptr; + if (budget_) { + Pool& p = kind == RAD_MEM_DEVICE ? budget_->weights() : budget_->host_pinned(); + return p.reserve(what, bytes, RAD_ALIGN_UNIT); + } + owns_memory_ = true; + return rad_dev_alloc(bytes, kind); +} + +int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, Pools* budget) { + prog_ = &prog; + plan_ = &plan; + cfg_ = cfg; + budget_ = budget; + stats_ = MoverStats{}; + if (!budget_) + RAD_WARN("mover: no Pools handed over; allocating its slab and host pool directly. That " + "double-spends --vram-weights-mib against whatever else already reserved it, so " + "it is a test path and not a deployment."); + + unit_.assign(plan.units.size(), UnitState{}); + pools_.clear(); + pools_.resize(plan.classes.size()); + + /* ---- how many slots each class needs, counted before anything is allocated ------------- */ + std::vector n_slab(plan.classes.size(), 0), n_pool(plan.classes.size(), 0); + int64_t static_need = 0, pageable_need = 0; + for (size_t u = 0; u < plan.units.size(); ++u) { + const MoveUnit& mu = plan.units[u]; + UnitState& us = unit_[u]; + us.tier = mu.tier; + us.site = mu.site; + us.klass = mu.slab_class; + us.bytes = mu.bytes; + if (mu.slab_class < 0) continue; + const int64_t stride = plan.classes[(size_t)mu.slab_class].stride; + + if (mu.tier == Tier::VRAM && mu.slab_slot >= 0) { + n_slab[(size_t)mu.slab_class] = std::max(n_slab[(size_t)mu.slab_class], + (int64_t)mu.slab_slot + 1); + } else if (mu.tier == Tier::VRAM) { + us.static_off = align_up(static_need, RAD_ALIGN_UNIT); + static_need = us.static_off + mu.bytes; + } else if (mu.tier == Tier::HostPinned) { + us.pool_slot = n_pool[(size_t)mu.slab_class]++; + } else if (mu.tier == Tier::HostPageable) { + us.static_off = align_up(pageable_need, RAD_ALIGN_UNIT); + pageable_need = us.static_off + mu.bytes; + } + (void)stride; + } + + /* ---- allocate ------------------------------------------------------------------------- */ + int64_t total_shadow = 0; + for (size_t c = 0; c < plan.classes.size(); ++c) { + const SlabClass& sc = plan.classes[c]; + ClassPools& cp = pools_[c]; + cp.stride = sc.stride; + + /* Shadow slots sit PAST the resident ones, so a slot index is a slot index and the + * resident count is untouched by turning the engine on. Under a static plan the plan + * asked for none and the slab is exactly the resident set. */ + /* THE PLAN'S NUMBER, not a config cap. The planner reserved these out of + * --vram-weights-mib and the report told the operator how many; allocating a different + * count here would mean the mover works against one number while the operator was charged + * for another, and the direction that is wrong in is an overrun. */ + const int64_t shadow = plan.dynamic ? sc.n_shadow : 0; + /* Shadow slots and staging slots are both "slab slots that belong to no unit", and the + * mover takes them off one free list because at the point of use they are the same thing: + * somewhere to copy into that nothing is reading. They are budgeted separately by the + * planner because they are the price of two different features. */ + const int64_t slab_slots = n_slab[c] + shadow + sc.n_stage; + /* The flex slots are not here: their memory is the KV cache's and is not carved yet. + * lend_from() adds them once it is. */ + cp.n_fixed = slab_slots; + cp.n_work = shadow + sc.n_stage; + cp.slab.init(slab_slots, sc.stride); + if (slab_slots > 0) { + /* Tail padding: a kernel that assembles a packed code window from a wide read + * legitimately reads a few bytes past the last slot's data. Inside the slab that + * lands in a neighbour; at the end it runs off the allocation and faults the card. */ + cp.slab_base = reserve(sc.name.c_str(), slab_slots * sc.stride + RAD_ALIGN_UNIT, + RAD_MEM_DEVICE); + if (!cp.slab_base) { + RAD_ERR("mover: no VRAM for the '%s' slab: %lld slots of %s", + sc.name.c_str(), (long long)slab_slots, humanb(sc.stride).c_str()); + return RAD_E_NOMEM; + } + } + for (int64_t s = n_slab[c]; s < slab_slots; ++s) cp.slab.add_free(s); + total_shadow += shadow + sc.n_stage; + + cp.pool.init(n_pool[c], sc.stride); + if (n_pool[c] > 0) { + cp.pool_base = reserve(sc.name.c_str(), n_pool[c] * sc.stride, RAD_MEM_HOST_PINNED); + if (!cp.pool_base) { + RAD_ERR("mover: no pinned host memory for the '%s' pool: %lld slots of %s", + sc.name.c_str(), (long long)n_pool[c], humanb(sc.stride).c_str()); + return RAD_E_NOMEM; + } + /* The pool's base as the CARD sees it. On a unified backend this is the host address + * itself, but going through the device layer is what makes that a checked fact + * rather than an assumption -- and without it a zero-copy expert is a bounce-buffer + * memcpy and there is no hybrid tier at all. */ + cp.pool_dev = rad_dev_device_ptr(cp.pool_base); + /* AND A FAILURE HERE IS NAMED RATHER THAN PAPERED OVER. Falling back silently to the + * host pointer hands a kernel an address it cannot dereference -- so a zero-copy + * expert would fault, or read whatever the backend happens to map there. + * + * It is not refused HERE because this is not where the consequence lands: a unit with + * no pool address gets a null base from unit_base(), republish() publishes the null, + * and the load phase already refuses by name on the first weight that needs one. That + * is the right place -- a pool nothing zero-copies out of is not an error. This line + * is what turns that refusal from "no address after mover init" into a cause. */ + if (!cp.pool_dev) { + RAD_WARN("mover: the '%s' host pool did not resolve to a device address; the " + "zero-copy tier cannot be served out of it. In a deployment the pool is " + "RAD_MEM_HOST_MAPPED (core/mem/pools.cpp) and this does not fire; where " + "it does, the pool is ordinary host memory and a kernel handed this " + "address would fault.", sc.name.c_str()); + cp.pool_dev = cp.pool_base; + } + } + /* The pool free list starts EMPTY: every pooled unit occupies its slot. The engine primes + * off the shadow slab slots, runs ahead by at most that many, and settles into + * alternating pairs -- a promotion frees a pool slot, which is what a demotion needs. */ + + /* AND NOTHING HERE IS MEMSET. A fresh pool holds garbage until the load phase writes it, + * which is correct -- a weight is read only after it is loaded -- and zeroing it would be + * a full pass over the host tier for no information. It is also the one asymmetry between + * the two device backends: rad_memset_async on RAD_MEM_HOST refuses on a real card + * (pageable memory the GPU has never been shown) and quietly succeeds on the host backend, + * so a memset added here passes in tests and fails on a card. If a host buffer ever + * genuinely needs clearing, clear it with std::memset on the host. */ + } + + if (static_need > 0) { + static_vram_ = reserve("static weights", static_need, RAD_MEM_DEVICE); + if (!static_vram_) { + /* THE ARITHMETIC, not just the refusal: the slab is reserved first and takes its + * shadow and staging slots with it, so "no VRAM" here means the budget covered the + * resident set and not the fixed weights beside it. An operator cannot act on the + * sentence without the two numbers. */ + if (budget_) + RAD_ERR("mover: the weight budget is %s and the slab already took %s of it, " + "leaving %s", + humanb(budget_->weights().bytes()).c_str(), + humanb(budget_->weights().used()).c_str(), + humanb(budget_->weights().avail()).c_str()); + RAD_ERR("mover: no VRAM for the %s of statically placed weights", + humanb(static_need).c_str()); + return RAD_E_NOMEM; + } + static_bytes_ = static_need; + } + if (pageable_need > 0) { + pageable_ = rad_dev_alloc(pageable_need, RAD_MEM_HOST); + if (!pageable_) return RAD_E_NOMEM; + pageable_bytes_ = pageable_need; + } + + /* ---- the file tier -------------------------------------------------------------------- */ + bool want_file = false; + for (const MoveUnit& mu : plan.units) if (mu.tier == Tier::SSD) want_file = true; + if (want_file) { + if (cfg_.container_path.empty()) { + RAD_ERR("mover: the plan put weights on the file tier but no container path was " + "given; a file-tier unit with nowhere to read from is an error, not a slow " + "path"); + return RAD_E_INVAL; + } + RAD_TRY(file_.open(cfg_.container_path)); + /* THE WIDEST UNIT THAT IS ACTUALLY ON THE FILE TIER, not the widest class in the plan. + * + * A staging slot only ever receives a unit read from the container, so sizing it off every + * class charges the host pool for classes that are never staged. The widest class is + * typically the embedding table -- its own class, gigabytes wide, and resident in VRAM for + * the whole run -- so sizing on it reserves several times that in pinned memory to receive + * a weight that never arrives, and the file tier is then refused for want of memory it + * did not need. */ + int64_t widest = 0; + for (const MoveUnit& mu : plan.units) { + if (mu.tier != Tier::SSD || mu.slab_class < 0) continue; + widest = std::max(widest, plan.classes[(size_t)mu.slab_class].stride); + } + stage_stride_ = FileTier::direct_align(widest); + if (cfg_.stage_slots > 0 && stage_stride_ > 0) { + stage_ = reserve("file-tier staging", (int64_t)cfg_.stage_slots * stage_stride_, RAD_MEM_HOST_PINNED); + if (!stage_) { + RAD_ERR("mover: no pinned memory for the file tier's %d staging slots of %s", + cfg_.stage_slots, humanb(stage_stride_).c_str()); + return RAD_E_NOMEM; + } + } + } + + /* ---- the file stager's buffers --------------------------------------------------------- + * + * Exactly what the plan charged: the two VRAM buffers out of the weight budget and the read + * windows out of the host pool's file-staging reserve. Allocated only when a routed unit is + * actually on the file tier, which is when the plan sized them. */ + if (plan.file_stage_vram > 0) { + if (!file_.ok()) { + RAD_ERR("mover: the plan reads routed experts from the container and the file tier " + "did not open"); + return RAD_E_STATE; + } + file_vram_ = (char*)reserve("file-tier layer buffers", plan.file_stage_vram, RAD_MEM_DEVICE); + if (!file_vram_) { + RAD_ERR("mover: no VRAM for the two %s buffers a routed layer is read into from the " + "container", humanb(plan.file_layer_max).c_str()); + return RAD_E_NOMEM; + } + /* Two halves of what was charged, each at least the largest layer and aligned, so the + * tail pad the plan added stays past the second buffer's end. */ + file_buf_bytes_ = (plan.file_stage_vram - RAD_ALIGN_UNIT) / 2 / RAD_ALIGN_UNIT * RAD_ALIGN_UNIT; + if (file_buf_bytes_ < plan.file_layer_max) return RAD_E_STATE; + if (plan.file_windows < (int64_t)RAD_PLACE_FILE_WINDOWS * RAD_PLACE_FILE_WINDOW_BYTES) { + RAD_ERR("mover: the plan reads routed experts from the container but reserved no read " + "windows for them"); + return RAD_E_STATE; + } + windows_ = (char*)reserve("file-tier read windows", + (int64_t)RAD_PLACE_FILE_WINDOWS * RAD_PLACE_FILE_WINDOW_BYTES, + RAD_MEM_HOST_PINNED); + if (!windows_) { + RAD_ERR("mover: no pinned memory for the file tier's %d read windows of %s", + RAD_PLACE_FILE_WINDOWS, humanb(RAD_PLACE_FILE_WINDOW_BYTES).c_str()); + return RAD_E_NOMEM; + } + n_windows_ = RAD_PLACE_FILE_WINDOWS; + } + + /* ---- streams, events, move records ------------------------------------------------------ */ + RAD_TRY(rad_stream_create(&mover_, /*high_priority=*/0)); + /* EVERY EVENT HERE IS LOCAL. They order the mover's queue against this card's compute queue + * and tell the host WHEN a slot is free; the bytes they order are read by this card's kernels + * and never by the host through them. A copy out to host memory carries the system scope on + * its own packets. */ + RAD_TRY(rad_event_create_local(&gate_)); + /* A window's event is waited on by the HOST, before the window is read into again. */ + win_ev_.assign((size_t)n_windows_, nullptr); + win_rec_.assign((size_t)n_windows_, 0); + for (RadEvent& e : win_ev_) RAD_TRY(rad_event_create_as(&e, RAD_EVENT_LOCAL | RAD_EVENT_HOST_WAIT)); + + const int lead = std::max(1, cfg_.max_lead_dispatches); + lead_.assign((size_t)lead + 1, nullptr); + for (RadEvent& e : lead_) RAD_TRY(rad_event_create_as(&e, RAD_EVENT_LOCAL | RAD_EVENT_HOST_WAIT)); + + /* TWO records per shadow slot, not one. A promotion holds a slab slot for its whole life, so + * there can never be more promotions in flight than there are shadows -- but a swap is two + * transfers, and the matching demotion needs a record of its own or the pair can never be in + * flight together and the engine never issues a demotion at all. That failure is silent: it + * shows up as `no_record` where the real symptom is a resident set that only ever grows. + * The floor is what makes a one-shadow plan still able to hold a swap. */ + const int64_t n_records = std::max(2 * total_shadow, 4); + moves_.assign((size_t)n_records, Move{}); + for (Move& m : moves_) RAD_TRY(rad_event_create_local(&m.ev)); + + /* ---- publish the initial addresses ------------------------------------------------------ */ + res_.init(prog, plan); + for (int32_t u = 0; u < (int32_t)plan.units.size(); ++u) { + unit_[(size_t)u].slab_slot = plan.units[(size_t)u].slab_slot; + republish(u); + } + + RAD_INFO("mover: %lld slab slots (%lld shadow), %lld pinned pool slots, %s static vram%s", + (long long)[&] { int64_t n = 0; for (auto& c : pools_) n += c.slab.size(); return n; }(), + (long long)total_shadow, + (long long)[&] { int64_t n = 0; for (auto& c : pools_) n += c.pool.size(); return n; }(), + humanb(static_bytes_).c_str(), file_.ok() ? ", file tier open" : ""); + /* The pageable host region is allocated here and charged to no budget -- Pools has no + * pageable pool because the memory is not device-visible and nothing else contends for it. + * That makes the receipt the only place it is ever named. */ + if (pageable_bytes_ > 0) + RAD_INFO("mover: %s of pageable host memory for the units no tier could hold", + humanb(pageable_bytes_).c_str()); + return RAD_OK; +} + +int Mover::bind_compute_stream(RadStream s) { + if (!s) return RAD_E_INVAL; + compute_ = s; + return RAD_OK; +} + +void* Mover::unit_base(int32_t unit) const { + if (unit < 0 || (size_t)unit >= unit_.size()) return nullptr; + const UnitState& us = unit_[(size_t)unit]; + if (us.klass < 0) return nullptr; + const ClassPools& cp = pools_[(size_t)us.klass]; + if (us.slab_slot >= 0 && (cp.is_flex(us.slab_slot) || cp.slab_base)) + return cp.slot_ptr(us.slab_slot); + if (us.tier == Tier::VRAM && us.static_off >= 0 && static_vram_) + return (char*)static_vram_ + us.static_off; + if (us.tier == Tier::HostPinned && us.pool_slot >= 0 && cp.pool_dev) + return (char*)cp.pool_dev + us.pool_slot * cp.stride; + if (us.tier == Tier::HostPageable && us.static_off >= 0 && pageable_) + return (char*)pageable_ + us.static_off; + /* A file-tier unit that is not staged has NO address, and saying so is the point: a kernel + * cannot read one off disk, so a caller that meets a null here must stage it or refuse. */ + return nullptr; +} + +void Mover::republish(int32_t unit) { + const MoveUnit& mu = plan_->units[(size_t)unit]; + char* base = (char*)unit_base(unit); + for (size_t i = 0; i < mu.weights.size(); ++i) + res_.publish(mu.weights[i], base ? base + mu.offset[i] : nullptr); +} + +/* Is a COPY INTO this unit's slot still in flight? The release path needs it: a slot whose + * staging copy has not landed cannot be given back, because the quarantine barrier is recorded on + * the COMPUTE stream and would say nothing about an H2D still in flight on the mover's. + * + * Copying and only Copying. "Any record that is not Free" is the same question asked too widely: + * a record past Copying has its bytes in place, and treating it as in-flight holds the slot for + * as long as the record takes to recycle rather than as long as the copy takes to land. */ +bool Mover::unit_in_flight(int32_t unit) const { + for (const Move& m : moves_) + if (m.state == Move::State::Copying && m.unit == unit) return true; + return false; +} + +int Mover::free_move_record() const { + const size_t n = moves_.size(); + for (size_t k = 0; k < n; ++k) { + const size_t i = (rec_cursor_ + k) % n; + if (moves_[i].state == Move::State::Free) { rec_cursor_ = (i + 1) % n; return (int)i; } + } + return -1; +} + +/* The ordering event, recorded ONCE PER DISPATCH and only when a move is actually going out. + * Everything the mover issues this dispatch waits on it, and it is downstream of every launch + * made up to now. Once per dispatch rather than once per move: re-recording per move is a dozen + * event records a layer restating one ordering constraint. */ +int Mover::record_gate() { + if (!compute_) { + RAD_ERR("mover: no compute stream bound; a transfer cannot be ordered against the " + "kernels that read the slot it targets"); + return RAD_E_STATE; + } + if (gate_dispatch_ == dispatch_) return RAD_OK; + RAD_TRY(rad_event_record(gate_, compute_)); + gate_dispatch_ = dispatch_; + return RAD_OK; +} + +int Mover::begin_dispatch(int dispatch, HeatEngine* heat) { + dispatch_ = dispatch; + ++stats_.dispatches; + RAD_TRY(retire(heat)); + + /* THE LEAD GATE. This is a host wait and it is NOT a transfer synchronisation: no transfer + * waits on the host and no host thread waits on a transfer. What it bounds is how far ahead + * of the cards this thread may queue work, and it exists because a freed slot returns to the + * free list only when its quarantine event signals -- and that event is on the compute + * stream. Let the host run and the stream carries a whole step, the recycle latency becomes + * that depth, and the mover finds no free slot to move into on almost every round. */ + if (compute_ && cfg_.max_lead_dispatches > 0) { + RadEvent old = lead_[(size_t)lead_next_]; + if (stats_.dispatches > (uint64_t)lead_.size()) RAD_TRY(rad_event_sync(old)); + RAD_TRY(rad_event_record(old, compute_)); + lead_next_ = (lead_next_ + 1) % (int)lead_.size(); + } + return RAD_OK; +} + +/* ---- the exact prefetch, which is the whole of layer offload's policy ------------------------- + * + * Declare enumerated every op with its weight operands in order, so the deadline for each staged + * unit is a fact and not a guess. WHEN to start is the supply question -- start as early as a + * slot is free, and stop at the first unit that cannot get one rather than skipping ahead, + * because the schedule is in deadline order and serving a later unit before an earlier one is how + * a prefetch turns into a cache. + */ +int Mover::prefetch_to_op(int32_t op_index) { + if (!plan_) return RAD_E_STATE; + + /* A backwards op index is the next step starting. The schedule is per step, so the cursor + * rewinds; nothing else has to know a step boundary happened. */ + if (op_index < last_op_) prefetch_cursor_ = 0; + last_op_ = op_index; + + /* RELEASE FIRST, so the slots this op finished with are available to the units it is about to + * need. A staged unit's slot goes back once its last_use_op is behind us: the declared order + * is what makes that safe, because a weight read outside [first_use_op, last_use_op] would + * contradict the order declare recorded. */ + for (int32_t u = 0; u < (int32_t)unit_.size(); ++u) { + const UnitState& us = unit_[(size_t)u]; + if (us.site != Site::DeviceStaged || us.slab_slot < 0) continue; + if (unit_in_flight(u)) continue; /* its copy has not landed; the slot is not ours yet */ + const MoveUnit& mu = plan_->units[(size_t)u]; + if (mu.last_use_op >= 0 && mu.last_use_op < op_index) release_slot(u); + } + + while (prefetch_cursor_ < (int32_t)plan_->prefetch.size()) { + const Plan::Prefetch& pf = plan_->prefetch[(size_t)prefetch_cursor_]; + UnitState& us = unit_[(size_t)pf.unit]; + if (us.slab_slot >= 0) { ++prefetch_cursor_; continue; } /* already in a slot */ + if (us.klass < 0) { ++prefetch_cursor_; continue; } + + const int64_t slot = pools_[(size_t)us.klass].slab.take(); + if (slot < 0) { ++stats_.starved_slab; break; } + const int rc = start_stage(pf.unit, slot); + if (rc < 0) { + pools_[(size_t)us.klass].slab.add_free(slot); + return rc; + } + ++prefetch_cursor_; + } + return RAD_OK; +} + +int Mover::start_stage(int32_t unit, int64_t slab_slot) { + const int rec = free_move_record(); + if (rec < 0) { ++stats_.no_record; return RAD_E_FULL; } + RAD_TRY(record_gate()); + + UnitState& us = unit_[(size_t)unit]; + ClassPools& cp = pools_[(size_t)us.klass]; + char* dst = cp.slot_ptr(slab_slot); + + const void* src = nullptr; + if (us.tier == Tier::HostPinned && us.pool_slot >= 0) + src = (char*)cp.pool_base + us.pool_slot * cp.stride; + else if (us.tier == Tier::HostPageable && us.static_off >= 0) + src = (char*)pageable_ + us.static_off; + else if (us.tier == Tier::SSD) { + /* The file tier's cliff, and it is a BLOCKING host read in the middle of a dispatch. It + * is counted so a run that leans on it is visible as a run to re-budget, not as a mystery + * in the throughput. */ + if (!file_.ok() || !stage_) return RAD_E_STATE; + char* stage = (char*)stage_ + (int64_t)stage_next_ * stage_stride_; + stage_next_ = (stage_next_ + 1) % std::max(1, cfg_.stage_slots); + /* WEIGHT BY WEIGHT, each from its own plane into its own place in the unit. A container + * entry is a logical weight's planes at 256-byte alignment and a unit lays its weights out + * at their declared alignment, so the two arrangements are not the same bytes and one + * read of the unit's span would put every weight after the first at the wrong offset. */ + const MoveUnit& mu = plan_->units[(size_t)unit]; + for (size_t k = 0; k < mu.weights.size(); ++k) { + const WeightInfo& w = prog_->weights[mu.weights[k]]; + RAD_TRY(file_.read(w.file_offset, w.stored_bytes, stage + mu.offset[k], + stage_stride_ - mu.offset[k])); + } + ++stats_.ssd_reads; + stats_.ssd_bytes += (uint64_t)us.bytes; + src = stage; + } + if (!src) return RAD_E_STATE; + + RAD_TRY(rad_event_wait(mover_, gate_)); + RAD_TRY(rad_memcpy_async(dst, src, us.bytes, mover_)); + RAD_TRY(rad_event_record(moves_[(size_t)rec].ev, mover_)); + + Move& m = moves_[(size_t)rec]; + m.state = Move::State::Copying; + m.kind = Move::Kind::Stage; + m.unit = unit; + m.slab_slot = slab_slot; + m.pool_slot = -1; + stats_.h2d_bytes += (uint64_t)us.bytes; + stats_.prefetch_bytes += (uint64_t)us.bytes; + ++stats_.prefetched; + + /* PUBLISH THE DESTINATION NOW, not at retire, and with the event. A staging copy is the one + * move whose destination the run phase will read: the old address (the pinned pool) stays + * valid for everything already issued, and everything issued from here on names the slab slot + * and is ordered behind `ev` on the compute stream. That stream wait is the only thing + * standing between a staged weight and a race, and it costs no host time. + * + * begin_transfer bumps the generation, which is what makes the run phase actually perform + * that wait rather than skipping it as already done. */ + us.slab_slot = slab_slot; + char* base = (char*)unit_base(unit); + const MoveUnit& mu = plan_->units[(size_t)unit]; + for (size_t i = 0; i < mu.weights.size(); ++i) + res_.begin_transfer(mu.weights[i], base + mu.offset[i], m.ev); + return RAD_OK; +} + +/* ---- staging within a pass (see mover.h) ---------------------------------------------------- */ +int Mover::stage_units(const std::vector& units, char* dst, int64_t cap, RadEvent after, + RadEvent done, std::vector* staged) { + if (!plan_ || !dst || !staged || !done) return RAD_E_INVAL; + staged->clear(); + std::vector at; + at.reserve(units.size()); + int64_t off = 0; + bool waited = false; + for (int32_t u : units) { + if (u < 0 || (size_t)u >= unit_.size()) return RAD_E_INVAL; + const UnitState& us = unit_[(size_t)u]; + if (us.tier != Tier::HostPinned || us.pool_slot < 0 || us.slab_slot >= 0 || us.klass < 0) + continue; + if (unit_in_flight(u)) continue; + const int64_t need = align_up(us.bytes, RAD_ALIGN_UNIT); + if (off + need > cap) { ++stats_.stage_overflow; continue; } + if (!waited) { + if (after) RAD_TRY(rad_event_wait(mover_, after)); + waited = true; + } + const ClassPools& cp = pools_[(size_t)us.klass]; + const char* src = (const char*)cp.pool_base + us.pool_slot * cp.stride; + RAD_TRY(rad_memcpy_async(dst + off, src, us.bytes, mover_)); + staged->push_back(u); + at.push_back(off); + stats_.h2d_bytes += (uint64_t)us.bytes; + stats_.staged_bytes += (uint64_t)us.bytes; + off += need; + } + if (staged->empty()) return RAD_OK; + RAD_TRY(rad_event_record(done, mover_)); + for (size_t k = 0; k < staged->size(); ++k) { + const MoveUnit& mu = plan_->units[(size_t)(*staged)[k]]; + for (size_t i = 0; i < mu.weights.size(); ++i) + res_.publish(mu.weights[i], dst + at[k] + mu.offset[i]); + } + ++stats_.stage_layers; + stats_.staged_units += (uint64_t)staged->size(); + return RAD_OK; +} + +void Mover::unstage_units(const std::vector& staged) { + for (int32_t u : staged) republish(u); +} + +/* ---- a routed layer read from the container (see mover.h) ---------------------------------- */ +namespace { + +/* One weight's bytes: where they are in the container and where they go. */ +struct FileExt { + int64_t foff = 0, bytes = 0; + char* dst = nullptr; +}; + +/* THE GAP A RUN READS THROUGH rather than starting another pread. The weights of one routed + * layer sit together in the container, each starting on RAD_ALIGN_UNIT, so between two that are + * both on the file tier there is either alignment padding or a run of units that are not -- a + * resident expert or a pooled one. Reading padding is free next to a second pread; reading a + * resident expert is a megabyte or ten the drive delivers for nothing. 256 KiB is above every + * padding and below every expert this engine serves. */ +constexpr int64_t kReadThrough = (int64_t)256 << 10; + +} /* namespace */ + +int Mover::stage_file_units(const std::vector& units, char* dst, int64_t cap, + RadEvent after, RadEvent done, std::vector* staged) { + if (!plan_ || !dst || !staged || !done) return RAD_E_INVAL; + staged->clear(); + if (!file_.ok() || !windows_ || n_windows_ <= 0) return RAD_E_STATE; + + /* The layout in `dst`, unit by unit in the order given, and every weight's extent. */ + std::vector ext; + std::vector at; + int64_t off = 0; + for (int32_t u : units) { + if (u < 0 || (size_t)u >= unit_.size()) return RAD_E_INVAL; + const UnitState& us = unit_[(size_t)u]; + if (us.tier != Tier::SSD || us.slab_slot >= 0 || us.klass < 0) continue; + const int64_t need = align_up(us.bytes, RAD_ALIGN_UNIT); + if (off + need > cap) { + RAD_ERR("file stager: a routed layer's file-tier units need more than the %s buffer " + "the plan sized for the largest one", humanb(cap).c_str()); + return RAD_E_SCRATCH; + } + const MoveUnit& mu = plan_->units[(size_t)u]; + for (size_t k = 0; k < mu.weights.size(); ++k) { + const WeightInfo& w = prog_->weights[mu.weights[k]]; + if (w.stored_bytes <= 0) continue; /* nothing to read, and nothing to place */ + ext.push_back(FileExt{ (int64_t)w.file_offset, w.stored_bytes, dst + off + mu.offset[k] }); + } + staged->push_back(u); + at.push_back(off); + off += need; + } + if (staged->empty()) return RAD_OK; + /* CONTAINER ORDER, so a window is one long run of the drive and not a seek per weight. */ + std::stable_sort(ext.begin(), ext.end(), + [](const FileExt& a, const FileExt& b) { return a.foff < b.foff; }); + + if (after) RAD_TRY(rad_event_wait(mover_, after)); + + const int64_t A = DirectFile::alignment(); + const int64_t W = RAD_PLACE_FILE_WINDOW_BYTES; + struct Seg { int64_t fs = 0, fe = 0, ws = 0; }; /* file [fs, fe) read to window offset ws */ + struct Cp { int64_t wo = 0, bytes = 0; char* dst = nullptr; }; + std::vector segs; + std::vector cps; + size_t i = 0; + int64_t piece = 0; /* bytes of ext[i] already placed */ + while (i < ext.size()) { + const int w = win_next_; + win_next_ = (win_next_ + 1) % n_windows_; + char* win = windows_ + (int64_t)w * W; + if (win_rec_[(size_t)w]) { + /* The window's copies from the round before must have left it. */ + const auto t0 = std::chrono::steady_clock::now(); + RAD_TRY(rad_event_sync(win_ev_[(size_t)w])); + stats_.file_wait_ns += (uint64_t)std::chrono::duration_cast( + std::chrono::steady_clock::now() - t0).count(); + win_rec_[(size_t)w] = 0; + } + + /* Pack the window: extend the current run while the next weight starts within the + * read-through gap of its end, start another run otherwise, and split a weight the window + * cannot finish across this window and the next. */ + segs.clear(); + cps.clear(); + while (i < ext.size()) { + const FileExt& e = ext[i]; + const int64_t fo = e.foff + piece, left = e.bytes - piece; + int64_t wo; + if (!segs.empty() && fo >= segs.back().fs && fo <= segs.back().fe + kReadThrough) { + wo = segs.back().ws + (fo - segs.back().fs); + } else { + const int64_t ws = segs.empty() + ? 0 : segs.back().ws + align_up(segs.back().fe - segs.back().fs, A); + const int64_t fs = fo / A * A; + wo = ws + (fo - fs); + if (wo >= W) break; + segs.push_back(Seg{ fs, fs, ws }); + } + const int64_t take = std::min(left, W - wo); + if (take <= 0) break; + Seg& s = segs.back(); + s.fe = std::max(s.fe, fo + take); + cps.push_back(Cp{ wo, take, e.dst + piece }); + piece += take; + if (piece == e.bytes) { ++i; piece = 0; } + if (take < left) break; /* the window is full */ + } + if (cps.empty()) return RAD_E_STATE; /* a window that takes nothing cannot end */ + + const auto t0 = std::chrono::steady_clock::now(); + for (const Seg& s : segs) { + RAD_TRY(file_.read((uint64_t)s.fs, s.fe - s.fs, win + s.ws, W - s.ws)); + ++stats_.file_preads; + } + stats_.file_read_ns += (uint64_t)std::chrono::duration_cast( + std::chrono::steady_clock::now() - t0).count(); + for (const Cp& c : cps) RAD_TRY(rad_memcpy_async(c.dst, win + c.wo, c.bytes, mover_)); + RAD_TRY(rad_event_record(win_ev_[(size_t)w], mover_)); + win_rec_[(size_t)w] = 1; + } + RAD_TRY(rad_event_record(done, mover_)); + + for (size_t k = 0; k < staged->size(); ++k) { + const int32_t u = (*staged)[k]; + const MoveUnit& mu = plan_->units[(size_t)u]; + for (size_t j = 0; j < mu.weights.size(); ++j) + res_.publish(mu.weights[j], dst + at[k] + mu.offset[j]); + stats_.file_bytes += (uint64_t)unit_[(size_t)u].bytes; + } + ++stats_.file_layers; + stats_.file_units += (uint64_t)staged->size(); + stats_.h2d_bytes += (uint64_t)off; + return RAD_OK; +} + +void Mover::release_slot(int32_t unit) { + const int rec = free_move_record(); + if (rec < 0) { ++stats_.no_record; return; } + UnitState& us = unit_[(size_t)unit]; + Move& m = moves_[(size_t)rec]; + m.state = Move::State::Published; /* nothing to copy; it is already "landed" */ + m.kind = Move::Kind::Release; + m.unit = unit; + m.slab_slot = us.slab_slot; + m.pool_slot = -1; + us.slab_slot = -1; + republish(unit); /* the pointer stops naming the slot before the barrier */ +} + +int Mover::issue(const Swap& s, HeatEngine* heat) { + if (!plan_ || !plan_->dynamic) return RAD_OK; + + auto one = [&](int32_t unit, bool promote) -> bool { + if (unit < 0) return false; + UnitState& us = unit_[(size_t)unit]; + if (us.klass < 0) return false; + ClassPools& cp = pools_[(size_t)us.klass]; + + /* A UNIT THAT KEPT ITS HOST COPY IS DROPPED, NOT DEMOTED: its pool slot still holds its + * bytes, so there is nothing to copy and no second pool slot to take. */ + if (!promote && us.pool_slot >= 0 && us.slab_slot >= 0) return drop(unit, heat) >= 0; + + if (promote) { + const int64_t slot = cp.slab.take(); + if (slot < 0) { ++stats_.starved_slab; return false; } + if (promote_to(unit, slot) < 0) { cp.slab.add_free(slot); return false; } + return true; + } + + const int rec = free_move_record(); + if (rec < 0) { ++stats_.no_record; return false; } + if (record_gate() < 0) return false; + Move& m = moves_[(size_t)rec]; + { + const int64_t g = cp.pool.take(); + if (g < 0) { ++stats_.starved_pool; return false; } + char* dst = (char*)cp.pool_base + g * cp.stride; + if (us.slab_slot < 0) { cp.pool.add_free(g); return false; } + const void* src = cp.slot_ptr(us.slab_slot); + /* D2H out of the slab. The slab layout IS the pool layout, so this is a straight copy + * with no transform -- and IT IS NOT FREE. It is tempting to read a demotion as + * running in the direction the zero-copy tier leaves idle and therefore as nearly + * free; it is not. The two costs are additive: the directions share one budget and a + * demotion costs about what a promotion does. That is the exchange rate heat.h's + * min_gain is tuned against. */ + if (rad_event_wait(mover_, gate_) < 0) { cp.pool.add_free(g); return false; } + if (rad_memcpy_async(dst, src, us.bytes, mover_) < 0) { + cp.pool.add_free(g); + return false; + } + (void)rad_event_record(m.ev, mover_); + m.kind = Move::Kind::Demote; + m.slab_slot = us.slab_slot; + m.pool_slot = g; + stats_.d2h_bytes += (uint64_t)us.bytes; + } + m.state = Move::State::Copying; + m.unit = unit; + return true; + }; + + const bool up = one(s.promote, true); + const bool down = one(s.demote, false); + /* A half-issued swap is legal and self-correcting: the two halves create each other's supply, + * so the missing one goes out on a later dispatch. What is NOT legal is leaving a unit busy + * that no move will ever publish -- the heat engine would never consider it again and would + * go quiet with no counter saying why. */ + if (heat) { + if (!up) heat->set_busy(s.promote, false); + if (!down) heat->set_busy(s.demote, false); + } + return (up || down) ? RAD_OK : RAD_E_FULL; +} + +/* ------------------------------------------------------------------ the loan */ +static char* align_down_ptr(char* p) { + const uintptr_t v = (uintptr_t)p; + return (char*)(v - v % (uintptr_t)RAD_ALIGN_UNIT); +} + +int Mover::lend_from(int lender, const std::vector& strips) { + if (!plan_ || !plan_->dynamic) return RAD_OK; /* a static plan never moves a unit */ + if (lender < 0 || lender >= kLenders) return RAD_E_INVAL; + for (const ClassPools& cp : pools_) + for (const ClassPools::Lent& l : cp.lent) + if (l.lender == lender) { + RAD_ERR("mover: lend_from called twice for one lender; its slots are carved once"); + return RAD_E_STATE; + } + + /* WHO GETS THE SLOTS. A class with units in the pinned pool that could be promoted, in + * proportion to their bytes -- and never more slots than it has such units, because a slot no + * unit can ever fill is VRAM lent to nothing. */ + const size_t nc = pools_.size(); + std::vector want(nc, 0), got(nc, 0); + for (size_t u = 0; u < unit_.size(); ++u) { + const UnitState& us = unit_[u]; + if (us.klass < 0 || us.tier != Tier::HostPinned || us.pool_slot < 0) continue; + if (!plan_->units[u].movable) continue; + ++want[(size_t)us.klass]; + } + std::vector weight(nc, 0.0); + for (size_t c = 0; c < nc; ++c) + weight[c] = pools_[c].stride > 0 ? (double)want[c] * (double)pools_[c].stride : 0.0; + + /* EVERY STRETCH, TOP DOWN. The classes take turns in proportion to their weight, so each + * stretch holds each class's share and the share does not depend on the order the stretches + * arrive in. */ + struct Cut { int64_t need; char* p; }; + std::vector> cuts(nc); + for (const LoanStrip& st : strips) { + if (!st.top || st.bytes <= (int64_t)RAD_ALIGN_UNIT || st.unit_bytes <= 0 || + st.unit_tokens <= 0) + continue; + char* const bottom = st.top - st.bytes; + /* THE TOP ALIGNMENT UNIT STAYS EMPTY. A kernel assembling a packed code window reads a + * few bytes past the end of the slot it was handed; inside the stretch that lands in the + * slot above, and above the top of the stretch is memory that is not the slab's -- the + * next layer's blocks, or at the end of the carve a region nothing may have mapped. */ + char* cur = align_down_ptr(st.top - RAD_ALIGN_UNIT); + for (;;) { + int best = -1; + double best_k = 0.0; + for (size_t c = 0; c < nc; ++c) { + if (weight[c] <= 0.0 || got[c] >= want[c]) continue; + if (cur - bottom < pools_[c].stride) continue; + if (align_down_ptr(cur - pools_[c].stride) < bottom) continue; + const double k = (double)(got[c] + 1) * (double)pools_[c].stride / weight[c]; + if (best < 0 || k < best_k) { best = (int)c; best_k = k; } + } + if (best < 0) break; + char* p = align_down_ptr(cur - pools_[(size_t)best].stride); + /* The loan that covers this slot reaches its lowest byte. */ + const int64_t depth = st.top - p; + const int64_t need = (depth + st.unit_bytes - 1) / st.unit_bytes * st.unit_tokens; + cuts[(size_t)best].push_back(Cut{ need, p }); + ++got[(size_t)best]; + cur = p; + } + } + + /* SMALLEST LOAN FIRST, so a loan of any size is a prefix of the slots and the one it gives + * back first is the deepest -- which is the one the owner wants back first. */ + int64_t n_new = 0, bytes_new = 0; + for (size_t c = 0; c < nc; ++c) { + if (cuts[c].empty()) continue; + ClassPools& cp = pools_[c]; + std::stable_sort(cuts[c].begin(), cuts[c].end(), + [](const Cut& x, const Cut& y) { return x.need < y.need; }); + ClassPools::Lent l; + l.lender = lender; + l.seg = cp.slab.add_segment((int64_t)cuts[c].size()); + l.first = cp.slab.seg_lo(l.seg); + /* THE SLOT NUMBER AND THE POINTER LIST AGREE BY CONSTRUCTION: segments are appended in the + * order their pointers are, so slot_ptr's `slot - n_fixed` indexes straight into them. */ + if (l.first != cp.n_fixed + (int64_t)cp.flex_ptr.size()) { + RAD_ERR("mover: a lent segment starts at slot %lld with %zu lent slots before it", + (long long)l.first, cp.flex_ptr.size()); + return RAD_E_STATE; + } + for (const Cut& k : cuts[c]) { cp.flex_ptr.push_back(k.p); l.need.push_back(k.need); } + cp.lent.push_back(std::move(l)); + n_new += (int64_t)cuts[c].size(); + bytes_new += (int64_t)cuts[c].size() * cp.stride; + } + if (n_new <= 0) return RAD_OK; + + /* A RECORD FOR EVERY SLOT THAT CAN BE LENT. A fill issues a promotion into every free slot + * at once and a recall drops every unit past the loan at once, and each of those is a record + * until its barrier clears; sized at the shadow count, the records -- not the link -- would + * decide how fast a loan is used. */ + const size_t had = moves_.size(); + moves_.resize(had + (size_t)n_new); + for (size_t i = had; i < moves_.size(); ++i) RAD_TRY(rad_event_create_local(&moves_[i].ev)); + + RAD_INFO("mover: %lld slots can be lent out of the %s (%s), filled as it lends them", + (long long)n_new, lender == kLendKV ? "KV cache" : "activation arena", + humanb(bytes_new).c_str()); + count_flex(); + return RAD_OK; +} + +int Mover::set_loan(int lender, int64_t amount) { + if (lender < 0 || lender >= kLenders) return RAD_E_INVAL; + loan_[lender] = amount > 0 ? amount : 0; + for (ClassPools& cp : pools_) + for (const ClassPools::Lent& l : cp.lent) { + if (l.lender != lender) continue; + const int64_t n = std::upper_bound(l.need.begin(), l.need.end(), loan_[lender]) - + l.need.begin(); + if (cp.slab.target(l.seg) != l.first + n) { + if (l.first + n < cp.slab.target(l.seg)) cp.strand_check = true; + cp.slab.set_target(l.seg, l.first + n); + } + } + count_flex(); + return RAD_OK; +} + +int64_t Mover::loan_held(int lender) const { + int64_t t = 0; + for (const ClassPools& cp : pools_) + for (const ClassPools::Lent& l : cp.lent) { + if (l.lender != lender) continue; + const int64_t top = cp.slab.top_held(l.seg); + if (top >= l.first) t = std::max(t, l.need[(size_t)(top - l.first)]); + } + return t; +} + +int64_t Mover::flex_capacity() const { + int64_t n = 0; + for (const ClassPools& cp : pools_) n += (int64_t)cp.flex_ptr.size() * cp.stride; + return n; +} + +int64_t Mover::loan_ceiling(int lender) const { + int64_t t = 0; + for (const ClassPools& cp : pools_) + for (const ClassPools::Lent& l : cp.lent) + if (l.lender == lender && !l.need.empty()) t = std::max(t, l.need.back()); + return t; +} + +void Mover::count_flex() { + int64_t used = 0, offered = 0; + for (const ClassPools& cp : pools_) { + if (cp.flex_ptr.empty()) continue; + used += cp.slab.held_from(cp.n_fixed) * cp.stride; + for (const ClassPools::Lent& l : cp.lent) + offered += (cp.slab.target(l.seg) - l.first) * cp.stride; + } + flex_used_.store(used, std::memory_order_relaxed); + flex_offered_.store(offered, std::memory_order_relaxed); +} + +int Mover::drop(int32_t unit, HeatEngine* heat) { + const int rec = free_move_record(); + if (rec < 0) { ++stats_.no_record; return RAD_E_FULL; } + UnitState& us = unit_[(size_t)unit]; + Move& m = moves_[(size_t)rec]; + m.state = Move::State::Published; /* nothing to copy: the host copy never went away */ + m.kind = Move::Kind::Drop; + m.unit = unit; + m.slab_slot = us.slab_slot; + m.pool_slot = -1; + us.slab_slot = -1; + us.tier = Tier::HostPinned; + us.site = Site::DeviceZeroCopy; + republish(unit); /* the pointer stops naming the slot before the barrier */ + ++stats_.demotions; + ++stats_.dropped; + if (heat) { + heat->set_tier(unit, Tier::HostPinned); + heat->set_busy(unit, true); + } + return RAD_OK; +} + +int Mover::promote_to(int32_t unit, int64_t slot) { + UnitState& us = unit_[(size_t)unit]; + ClassPools& cp = pools_[(size_t)us.klass]; + const int rec = free_move_record(); + if (rec < 0) { ++stats_.no_record; return RAD_E_FULL; } + RAD_TRY(record_gate()); + if (us.pool_slot < 0) return RAD_E_STATE; + const void* src = (const char*)cp.pool_base + us.pool_slot * cp.stride; + Move& m = moves_[(size_t)rec]; + RAD_TRY(rad_event_wait(mover_, gate_)); + RAD_TRY(rad_memcpy_async(cp.slot_ptr(slot), src, us.bytes, mover_)); + (void)rad_event_record(m.ev, mover_); + m.kind = Move::Kind::Promote; + m.slab_slot = slot; + /* INTO A LENT SLOT, THE HOST COPY STAYS. The loan can be recalled at any time and a unit that + * kept its pool slot goes back by a change of address; one that gave it up would need a pool + * slot and a copy across the link at the moment the cache is asking for its memory. The + * quarantine then has no pool slot to free. */ + m.pool_slot = cp.is_flex(slot) ? -1 : us.pool_slot; + m.state = Move::State::Copying; + m.unit = unit; + stats_.h2d_bytes += (uint64_t)us.bytes; + return RAD_OK; +} + +int Mover::fill(size_t klass, int64_t room, HeatEngine* heat) { + if (room <= 0) return RAD_OK; + struct Cand { float h; int32_t layer; int32_t unit; }; + std::vector cand; + for (int32_t u = 0; u < (int32_t)unit_.size(); ++u) { + const UnitState& us = unit_[(size_t)u]; + if (us.klass != (int32_t)klass || us.tier != Tier::HostPinned || us.pool_slot < 0) continue; + if (!plan_->units[(size_t)u].movable) continue; + if (heat && heat->busy(u)) continue; + cand.push_back(Cand{ heat ? heat->heat(u) : 0.0f, plan_->units[(size_t)u].layer, u }); + } + std::stable_sort(cand.begin(), cand.end(), [](const Cand& a, const Cand& b) { return a.h > b.h; }); + + /* HOTTEST FIRST, AND ON AN EXACT TIE THE LAYER HOLDING THE FEWEST RESIDENT UNITS -- the + * statement `pick` makes, and it has to keep holding as the batch lands. Every promotion here + * is issued before any of them retires, so the heat engine's own count does not move during + * the batch; it is counted here instead. Without that a fill of a cold slab, where every heat + * is zero, would put its whole batch into whichever layer was thinnest when it began. */ + std::unordered_map added; + int64_t issued = 0; + for (size_t i = 0; i < cand.size() && issued < room;) { + size_t j = i; + while (j < cand.size() && cand[j].h == cand[i].h) ++j; + std::map> by_layer; /* one heat, per layer */ + for (size_t k = j; k-- > i;) by_layer[cand[k].layer].push_back(cand[k].unit); + using Key = std::pair; /* (residents, layer) */ + std::priority_queue, std::greater> q; + for (auto& kv : by_layer) { + const int32_t rc = heat ? heat->layer_residents(kv.second.back()) : 0; + q.push({ rc + added[kv.first], kv.first }); + } + while (!q.empty() && issued < room) { + const Key k = q.top(); + q.pop(); + std::vector& us = by_layer[k.second]; + const int32_t u = us.back(); + us.pop_back(); + /* A LENT SLOT AND NEVER A WORKING ONE. The shadow and staging slots are what lets a + * swap happen at all, and a unit filled into one sits in the budgeted range where no + * loan can give it back -- the reserve would be gone for good the first time the loan + * shrank. */ + const int64_t slot = pools_[klass].slab.take_at_least(pools_[klass].n_fixed); + if (slot < 0) return RAD_OK; + if (heat) heat->set_busy(u, true); + if (promote_to(u, slot) < 0) { /* no record left: next time */ + pools_[klass].slab.add_free(slot); + if (heat) heat->set_busy(u, false); + return RAD_OK; + } + ++issued; + ++added[k.second]; + if (!us.empty()) q.push({ k.first + 1, k.second }); + } + i = j; + } + return RAD_OK; +} + +int Mover::balance(HeatEngine* heat) { + if (!plan_ || !plan_->dynamic) return RAD_OK; + + for (size_t c = 0; c < pools_.size(); ++c) { + ClassPools& cp = pools_[c]; + if (cp.flex_ptr.empty()) continue; + bool drained = false; + + /* ---- EMPTY WHAT THE LOAN NO LONGER COVERS, FIRST AND ALL OF IT. Each is a drop -- a + * change of address, with no copy -- so there is no link to ration it against, and the + * cache is waiting for these bytes. A unit still busy is on its way in; it goes on the + * next call, once its promotion has retired. The sweep is over every unit, so it runs + * only while a shrink may have stranded one (ClassPools::strand_check). */ + if (cp.strand_check) { + bool left = false; + for (int32_t u = 0; u < (int32_t)unit_.size(); ++u) { + const UnitState& us = unit_[(size_t)u]; + if (us.klass != (int32_t)c || us.slab_slot < 0 || cp.slab.covered(us.slab_slot)) continue; + /* Anything else still past the loan -- a promotion that has not retired, a staged + * unit -- becomes droppable later, so the sweep has to come back for it. */ + if (us.tier != Tier::VRAM || us.site != Site::Device || (heat && heat->busy(u))) { + left = true; + continue; + } + if (drop(u, heat) < 0) { left = true; break; } + drained = true; + } + cp.strand_check = left; + } + + /* ---- THE WORKING RESERVE. The shadow and staging slots have to stay free whatever the + * loan is, or the mover cannot turn over: a loan that shrank past units sitting in the + * slots that were serving as the reserve leaves the slab too full by that many, and the + * coldest lent units go -- drops, never copies. A slot already on its way back below the + * target counts as free, because it is, a barrier from now; draining against it again is + * how a slab empties itself. */ + int64_t pending = 0; + for (const Move& m : moves_) { + if (m.state == Move::State::Free || m.unit < 0 || m.slab_slot < 0) continue; + if (unit_[(size_t)m.unit].klass != (int32_t)c || !cp.slab.covered(m.slab_slot)) continue; + if (m.kind == Move::Kind::Drop || m.kind == Move::Kind::Demote || + m.kind == Move::Kind::Release) + ++pending; + } + int64_t short_by = cp.n_work - (cp.slab.n_free() + pending); + while (short_by > 0) { + int32_t victim = -1; + float coldest = 0.0f; + for (int32_t u = 0; u < (int32_t)unit_.size(); ++u) { + const UnitState& us = unit_[(size_t)u]; + if (us.klass != (int32_t)c || us.slab_slot < 0 || !cp.is_flex(us.slab_slot)) continue; + if (us.tier != Tier::VRAM || us.site != Site::Device || us.pool_slot < 0) continue; + if (heat && heat->busy(u)) continue; + const float h = heat ? heat->heat(u) : 0.0f; + if (victim < 0 || h < coldest) { victim = u; coldest = h; } + } + if (victim < 0 || drop(victim, heat) < 0) break; + drained = true; + --short_by; + } + /* AND WITH NO LENT UNIT LEFT TO DROP, THE COLDEST BUDGETED ONE GOES BACK TO THE POOL -- a + * real demotion, one a call. A swap can leave the free slots in the lent range, and a loan + * that then shrinks away takes them with it; the reserve has to be rebuilt out of the + * budgeted slots or the mover stops turning over. */ + if (short_by > 0) { + int32_t victim = -1; + float coldest = 0.0f; + for (int32_t u = 0; u < (int32_t)unit_.size(); ++u) { + const UnitState& us = unit_[(size_t)u]; + if (us.klass != (int32_t)c || us.slab_slot < 0 || cp.is_flex(us.slab_slot)) continue; + if (us.tier != Tier::VRAM || us.site != Site::Device || us.pool_slot >= 0) continue; + if (!plan_->units[(size_t)u].movable) continue; + if (heat && heat->busy(u)) continue; + const float h = heat ? heat->heat(u) : 0.0f; + if (victim < 0 || h < coldest) { victim = u; coldest = h; } + } + if (victim >= 0) { + if (heat) heat->set_busy(victim, true); + Swap s; + s.demote = victim; + if (issue(s, heat) >= 0) drained = true; + } + } + /* A drain and a fill in the same call fight: the fill would take the slots the drain is + * trying to hand back. */ + if (drained) continue; + + /* ---- THEN FILL, every free slot past the working reserve. */ + RAD_TRY(fill(c, cp.slab.n_free() - cp.n_work, heat)); + } + count_flex(); + return RAD_OK; +} + +int Mover::idle_tick(HeatEngine* heat) { + if (!plan_ || !plan_->dynamic) return RAD_OK; + RAD_TRY(retire(heat)); + return balance(heat); +} + +int Mover::reclaim(int lender, int64_t amount, HeatEngine* heat) { + RAD_TRY(set_loan(lender, amount)); + if (loan_held(lender) <= loan_[lender]) return RAD_OK; + if (!compute_ || !mover_) { + RAD_ERR("mover: a loan cannot be recalled with no compute stream bound; nothing orders " + "the kernels that may still read the slots"); + return RAD_E_STATE; + } + /* NO COPY IS STILL WRITING A SLOT: everything the mover issued has landed, and retiring it + * publishes the promotions that landed in slots about to be taken back. */ + RAD_TRY(rad_stream_sync(mover_)); + RAD_TRY(retire(heat)); + + /* EVERY UNIT PAST THE LOAN GOES BACK TO ITS HOST COPY, which is a change of address. */ + std::vector> freed; + for (int32_t u = 0; u < (int32_t)unit_.size(); ++u) { + UnitState& us = unit_[(size_t)u]; + if (us.klass < 0 || us.slab_slot < 0) continue; + const ClassPools& cp = pools_[(size_t)us.klass]; + if (!cp.is_flex(us.slab_slot) || cp.slab.covered(us.slab_slot)) continue; + if (us.pool_slot < 0) { + RAD_ERR("mover: unit %d sits in lent slot %lld with no host copy to go back to", + (int)u, (long long)us.slab_slot); + return RAD_E_STATE; + } + freed.push_back({ (size_t)us.klass, us.slab_slot }); + us.slab_slot = -1; + us.tier = Tier::HostPinned; + us.site = Site::DeviceZeroCopy; + republish(u); + ++stats_.demotions; + ++stats_.dropped; + if (heat) { + heat->set_tier(u, Tier::HostPinned); + heat->set_busy(u, false); + } + } + + /* AND NO KERNEL STILL NAMES ONE. The compute stream is the only reader of the slab -- the + * quarantine barrier rests on the same fact -- so once it has drained, nothing already issued + * can reach a slot past the loan, and everything issued from here reads the host copies. */ + RAD_TRY(rad_stream_sync(compute_)); + for (const auto& f : freed) pools_[f.first].slab.add_free(f.second); + + /* EVERY RECORD WAITING ON ONE OF THOSE SLOTS IS DONE WAITING: its barrier is behind the + * drain. A promotion's record has nothing to free -- its unit kept the pool slot -- and a + * drop's frees the slot it left. */ + for (Move& m : moves_) { + if (m.state == Move::State::Free || m.unit < 0 || m.slab_slot < 0) continue; + const int32_t klass = unit_[(size_t)m.unit].klass; + if (klass < 0) continue; + ClassPools& cp = pools_[(size_t)klass]; + if (!cp.is_flex(m.slab_slot) || cp.slab.covered(m.slab_slot)) continue; + if (m.kind == Move::Kind::Drop || m.kind == Move::Kind::Demote || + m.kind == Move::Kind::Release) + cp.slab.add_free(m.slab_slot); + if (heat && m.kind != Move::Kind::Stage && m.kind != Move::Kind::Release) + heat->set_busy(m.unit, false); + m.state = Move::State::Free; + m.unit = -1; + m.slab_slot = m.pool_slot = -1; + } + count_flex(); + if (loan_held(lender) > loan_[lender]) { + RAD_ERR("mover: recalled the %s loan to %lld and a slot at %lld is still held", + lender == kLendKV ? "KV" : "arena", (long long)loan_[lender], + (long long)loan_held(lender)); + return RAD_E_STATE; + } + return RAD_OK; +} + +int Mover::retire(HeatEngine* heat) { + for (Move& m : moves_) { + if (m.state != Move::State::Copying) continue; + const int q = rad_event_query(m.ev); + if (q < 0) return RAD_E_DEVICE; + if (q == 0) continue; + + UnitState& us = unit_[(size_t)m.unit]; + switch (m.kind) { + case Move::Kind::Promote: + us.slab_slot = m.slab_slot; + /* The source slot goes back on quarantine, not to us -- unless the destination + * was lent, in which case it is kept (see issue()). */ + if (m.pool_slot >= 0) us.pool_slot = -1; + us.tier = Tier::VRAM; + us.site = Site::Device; + ++stats_.promotions; + if (heat) heat->set_tier(m.unit, Tier::VRAM); + break; + case Move::Kind::Demote: + us.pool_slot = m.pool_slot; + us.slab_slot = -1; + us.tier = Tier::HostPinned; + /* Demoted, not exiled: the unit is now the zero-copy tier's, so the GEMM streams + * it out of the pinned pool as it computes. There is no third dispatch path. */ + us.site = Site::DeviceZeroCopy; + ++stats_.demotions; + if (heat) heat->set_tier(m.unit, Tier::HostPinned); + break; + case Move::Kind::Stage: + /* The destination was published at issue, with the event. All that is left is to + * clear the event: the copy has landed, so the wait is no longer needed and the + * common case -- a staged unit read many times before it is released -- costs no + * runtime call at all. No generation bump: the address did not change, and + * bumping would make the run phase re-wait on an event that has already + * signalled. */ + for (rad_weight w : plan_->units[(size_t)m.unit].weights) res_.settle(w); + /* ...AND STRAIGHT TO FREE, SKIPPING THE QUARANTINE. The barrier exists to protect + * a slot on its way back to the free list from kernels that still name it; a + * staging copy returns no slot -- the slot stays with the unit until a later + * Release hands it back, and THAT is the move the barrier belongs to. + * + * Sending a Stage through the quarantine anyway is not merely redundant, it + * stalls the prefetch: the record stays occupied for two more dispatches, and + * unit_in_flight() therefore keeps reporting the unit busy, which blocks the very + * Release that would recycle its slot. With a ring two deep that is the whole + * supply. Invisible on the host backend, where every copy lands within the + * dispatch that issued it; on a real card the copies take tens of microseconds + * and the pipeline simply stops turning over. */ + m.state = Move::State::Free; + m.unit = -1; + m.slab_slot = m.pool_slot = -1; + continue; + case Move::Kind::Release: + case Move::Kind::Drop: + break; + } + /* PUBLISH. Both copies of the bytes are valid at this instant -- the mover wrote a shadow + * slot and has not freed the source -- which is what makes this edit safe to make from + * this thread with nothing synchronised: whichever side of the write a reader lands on + * names bytes that are correct. */ + republish(m.unit); + m.state = Move::State::Published; + } + + /* QUARANTINE, and it is a SECOND pass on purpose. The slot being freed was named by kernels + * issued in earlier layers and those may still be running. Re-recording the move's event on + * the COMPUTE stream is the barrier: when it signals, every launch made before the publish + * has retired and the slot is safe to write. It has to sit downstream of the publish in + * stream order for that sentence to be true, which is why it cannot be folded into the loop + * above. A slot reused too early is not a crash -- it is fluent text with a new hash. */ + for (Move& m : moves_) { + if (m.state != Move::State::Published) continue; + if (!compute_) { + RAD_ERR("mover: no compute stream to quarantine the slot just freed by unit %d", + (int)m.unit); + return RAD_E_STATE; + } + RAD_TRY(rad_event_record(m.ev, compute_)); + m.state = Move::State::Quarantine; + ++stats_.quarantined; + } + + for (Move& m : moves_) { + if (m.state != Move::State::Quarantine) continue; + const int q = rad_event_query(m.ev); + if (q < 0) return RAD_E_DEVICE; + if (q == 0) continue; + + UnitState& us = unit_[(size_t)m.unit]; + ClassPools& cp = pools_[(size_t)us.klass]; + switch (m.kind) { + case Move::Kind::Promote: cp.pool.add_free(m.pool_slot); break; + case Move::Kind::Demote: cp.slab.add_free(m.slab_slot); break; + case Move::Kind::Release: cp.slab.add_free(m.slab_slot); break; + case Move::Kind::Drop: cp.slab.add_free(m.slab_slot); break; + case Move::Kind::Stage: break; /* never reaches here; freed as soon as it lands */ + } + if (heat && (m.kind == Move::Kind::Promote || m.kind == Move::Kind::Demote || + m.kind == Move::Kind::Drop)) + heat->set_busy(m.unit, false); + m.state = Move::State::Free; + m.unit = -1; + m.slab_slot = m.pool_slot = -1; + } + count_flex(); + return RAD_OK; +} + +std::string Mover::report() const { + const double gib = 1.0 / 1073741824.0; + std::string s = fmt("mover: %llu dispatches, %llu promotions, %llu demotions, %llu staged " + "(%.2f GiB h2d, %.2f GiB d2h)\n", + (unsigned long long)stats_.dispatches, + (unsigned long long)stats_.promotions, + (unsigned long long)stats_.demotions, + (unsigned long long)stats_.prefetched, + (double)stats_.h2d_bytes * gib, (double)stats_.d2h_bytes * gib); + /* Supply, not policy. These three are the difference between a mover at its budget and one + * that never got to spend it, and without them they look identical from the outside. */ + s += fmt(" %llu found no free move record, %llu starved of a slab slot, %llu of a pool " + "slot; %llu slots quarantined\n", + (unsigned long long)stats_.no_record, (unsigned long long)stats_.starved_slab, + (unsigned long long)stats_.starved_pool, (unsigned long long)stats_.quarantined); + if (stats_.ssd_reads) + s += fmt(" file tier: %llu demand reads (%.2f GiB), each a blocking pread in the middle " + "of a dispatch. Raise --host-pool-mib.\n", + (unsigned long long)stats_.ssd_reads, (double)stats_.ssd_bytes * gib); + /* The routed layers read from the container, and what they cost the issuing thread: read is + * the drive, wait is a window whose copies had not drained when it came round again. */ + if (stats_.file_layers) { + const double rs = (double)stats_.file_read_ns * 1e-9; + s += fmt(" file stager: %llu routed layers read, %llu units, %.2f GiB in %llu preads; " + "%.2f s reading (%.2f GB/s), %.2f s waiting on windows\n", + (unsigned long long)stats_.file_layers, (unsigned long long)stats_.file_units, + (double)stats_.file_bytes * gib, (unsigned long long)stats_.file_preads, rs, + rs > 0 ? (double)stats_.file_bytes / rs * 1e-9 : 0.0, + (double)stats_.file_wait_ns * 1e-9); + } + return s; +} + +} /* namespace rad */ diff --git a/core/place/mover.h b/core/place/mover.h new file mode 100644 index 00000000..59e104f9 --- /dev/null +++ b/core/place/mover.h @@ -0,0 +1,766 @@ +/* mover.h -- residency and the mover: the substrate every tier stands on. + * + * Three storage tiers, one address space of slots: + * + * FIXED-STRIDE VRAM SLAB SLOTS PER WEIGHT CLASS. A slot is interchangeable within its class, so + * a promotion is an integer swap and not an allocation, and a slab that never fragments is a + * slab whose hit rate does not depend on the order promotions happened to arrive in. + * + * A PINNED HOST POOL, at the same stride. Pinned rather than pageable because the whole point of + * the host tier is that a card can DMA out of it: a device-visible pinned pool is what makes a + * non-resident expert a zero-copy read inside the GEMM instead of a bounce-buffer memcpy in + * front of it. It is also allocated and owned here rather than read through the container's + * mmap, because with an mmap the KERNEL decides what stays resident and under real memory + * pressure it decides badly for this workload -- the same reads run several times slower inside + * a decode run than in isolation, and MADV_WILLNEED makes it worse, which is the tell that the + * faults are not too small and that a hint cannot fix a policy disagreement. + * + * A FILE TIER READ WITH O_DIRECT INTO PINNED BUFFERS. Predictable latency, no page-cache + * double-copy, and the read lands where the mover can DMA from it without a bounce. A buffered + * fallback is refused rather than offered: a tier whose latency is the page cache's mood is not + * a tier you can budget against. + * + * ---- THE ONE PROPERTY EVERYTHING ELSE RESTS ON ----------------------------------------------- + * + * THE MOVER RUNS ON A DEDICATED STREAM AND THE COMPUTE STREAM WAITS ON ITS EVENTS. NO HOST + * SYNCHRONISATION IS INVOLVED IN A TRANSFER. That is what lets placement be dynamic without + * serialising the step, and it is the difference between MoE offload being unusable and being + * fast. rad_issue waits with rad_event_wait, never rad_event_sync. + * + * The lead gate below IS a host wait, and it is not a contradiction: it throttles how far the + * host runs ahead of the cards. It is a SUPPLY mechanism, not a transfer synchronisation, and the + * reason it exists is spelled out at MoverConfig::max_lead_dispatches. + * + * ---- SHADOW SLOTS AND QUARANTINE ------------------------------------------------------------- + * + * A promotion writes into a SHADOW slot -- a slab slot that is allocated but holds nothing -- and + * only then publishes the new pointer. So a live slot is never DMA'd over while a kernel might + * still be reading it, and a promotion never invalidates a pointer the run phase is already + * holding. Getting that ordering wrong does not crash: it produces fluent output with a different + * hash every run, which is the single most expensive bug class in this design. + * + * The freed slot then goes into QUARANTINE rather than straight back to the free list, because + * kernels issued in earlier layers still name its old address. The barrier is an event recorded + * on the COMPUTE stream after the publish; when it signals, every launch that could still name + * the slot has retired. + */ +#pragma once +#include "../device/directio.h" +#include "../mem/pools.h" +#include "heat.h" +#include "planner.h" +#include "residency_iface.h" + +#include +#include +#include +#include +#include + +namespace rad { + +/* ------------------------------------------------------------------ slot bookkeeping */ +/* Pure host state, no device call in it, so the whole supply half is testable without a card. + * Used for both the VRAM slab and the pinned host pool -- they are the same structure with + * different backing memory, and writing it twice is how two free lists come to disagree about + * what a slot index means. + * + * ---- SEGMENTS: ONE RANGE FOR THE SLAB'S OWN SLOTS, ONE FOR EACH LENDER ------------------------ + * + * The slots are numbered in SEGMENTS laid end to end. Segment 0 is the budgeted range the pool + * was built with; every later one is a stretch of another pool's memory lent to this one -- the + * KV cache's blocks, the activation arena's top -- added once its addresses are known. Each + * segment has its own TARGET: the slots below it are the ones that may be handed out, and a + * lender moves only its own. Two lenders cannot share one target, because what one of them can + * spare says nothing about the other: the arena takes its memory back for every prefill while the + * cache is still lending, and a single mark over both would either hold the arena's slots past its + * recall or give up the cache's with it. + * + * ---- WHY THE LOWEST FREE SLOT, AND WHY A LIVE MARK ------------------------------------------- + * + * A lent segment is VRAM its owner can want back, and it has to be handed back when it does. That + * is only possible if the occupied slots pack toward the BOTTOM of the segment, so its top is free + * to retire. Handing out the lowest free slot is what packs them; a LIFO stack hands back the slot + * released most recently, which after a busy period is exactly the high slot the pool wants to + * give up, and the mark would never fall. + * + * A segment's `live` is how far its slots exist right now and `target` how far they should. They + * differ while a shrink waits on the units still sitting above the target: the mark stops at the + * highest slot something holds, so shrinking can never evict -- it only declines to hand a slot + * out again. + * + * THE FREE LIST IS REBUILT WHENEVER A TARGET MOVES, from the held flags, and holds exactly the + * covered slots nothing holds. Carried across a shrink and a regrow instead, it lists only some of + * the slots the shrink dropped -- a slot freed while it sat above the target is never pushed, and + * one the heap still held is discarded by the first take() that walks past it -- and a regrow + * that trusts it never hands the others out again. The rebuild is a scan of the capacity at the + * arbiter's cadence; take() and add_free, which the mover calls several times a dispatch, stay + * heap operations. + */ +class SlotPool { +public: + /* `n_live` slots exist in segment 0 and every one of them is HELD until add_free says + * otherwise, which is what the plan's resident set is. `n_cap` is how far segment 0 may ever + * grow -- address space the caller has reserved and will back on demand -- and defaults to no + * growth at all. */ + void init(int64_t n_live, int64_t stride, int64_t n_cap = -1) { + stride_ = stride; + n_ = n_cap > n_live ? n_cap : n_live; + segs_.assign(1, Seg{ 0, n_, n_live > 0 ? n_live : 0, n_live > 0 ? n_live : 0 }); + free_.clear(); + held_.assign((size_t)(n_ > 0 ? n_ : 0), 1); + n_usable_ = 0; + n_held_ = n_live > 0 ? n_live : 0; + } + /* A segment of `n_slots` after every existing one, covering nothing and holding nothing until + * a target reaches into it. Returns its index; slot numbers in it start at seg_lo(index). */ + int add_segment(int64_t n_slots) { + if (n_slots < 0) n_slots = 0; + segs_.push_back(Seg{ n_, n_ + n_slots, n_, n_ }); + held_.resize((size_t)(n_ + n_slots), 1); + n_ += n_slots; + return (int)segs_.size() - 1; + } + int n_segments() const { return (int)segs_.size(); } + int64_t seg_lo(int k) const { return segs_[(size_t)k].lo; } + int64_t seg_hi(int k) const { return segs_[(size_t)k].hi; } + + void add_free(int64_t slot) { + if (slot < 0 || slot >= n_) return; + if (!held_[(size_t)slot]) return; + held_[(size_t)slot] = 0; + --n_held_; + Seg& g = segs_[(size_t)seg_of(slot)]; + if (slot < g.target) push(slot); + else settle(g); + } + bool empty() const { return n_usable_ == 0; } + /* How many slots exist, over every segment. */ + int64_t size() const { + int64_t n = 0; + for (const Seg& g : segs_) n += g.live - g.lo; + return n; + } + int64_t capacity() const { return n_; } + int64_t stride() const { return stride_; } + int64_t n_free() const { return n_usable_; } + /* Slots something is in: a resident unit, a staged one, or a copy still in flight. The + * number the fill and drain decisions are made against, because the working slots have to + * stay free whatever the target is. */ + int64_t held() const { return n_held_; } + /* Where segment `k`'s covered slots end, as a slot number. */ + int64_t target(int k = 0) const { return segs_[(size_t)k].target; } + /* May this slot be handed out -- is it below its segment's target? */ + bool covered(int64_t slot) const { + if (slot < 0 || slot >= n_) return false; + return slot < segs_[(size_t)seg_of(slot)].target; + } + /* -1 when there is none. A caller that treats that as "try again next dispatch" is right; + * one that treats it as an error is wrong -- slot starvation is the normal steady state. */ + int64_t take() { + while (!free_.empty()) { + std::pop_heap(free_.begin(), free_.end(), std::greater()); + const int64_t s = free_.back(); + free_.pop_back(); + if (!covered(s) || held_[(size_t)s]) continue; /* never a slot to hand out */ + held_[(size_t)s] = 1; + ++n_held_; + --n_usable_; + return s; + } + return -1; + } + + /* Where segment `k`'s covered slots should end, as a slot number inside it. Growing is + * immediate -- the caller has already backed the memory. Shrinking is a statement of intent: + * the mark falls as far as the slots nothing holds allow, and the rest follows as those + * retire. */ + void set_target(int64_t target) { set_target(0, target); } + void set_target(int k, int64_t target) { + Seg& g = segs_[(size_t)k]; + g.target = target < g.lo ? g.lo : (target > g.hi ? g.hi : target); + /* Nothing ever holds a slot at or past the mark -- take() hands out only covered slots, + * and the mark never falls past a held one -- so a set flag there only says the slot has + * never existed. */ + for (int64_t s = g.live; s < g.target; ++s) held_[(size_t)s] = 0; + if (g.target > g.live) g.live = g.target; + else settle(g); + rebuild(); + } + + /* take(), restricted to slots at or above `lo`. The slots below it that are free stay free + * and stay listed; there are at most the working slots of them, so this is a handful of heap + * operations. */ + int64_t take_at_least(int64_t lo) { + std::vector keep; + int64_t got = -1; + while (!free_.empty()) { + std::pop_heap(free_.begin(), free_.end(), std::greater()); + const int64_t s = free_.back(); + free_.pop_back(); + if (!covered(s) || held_[(size_t)s]) continue; /* never a slot to hand out */ + if (s < lo) { keep.push_back(s); continue; } + held_[(size_t)s] = 1; + ++n_held_; + --n_usable_; + got = s; + break; + } + for (int64_t s : keep) { + free_.push_back(s); + std::push_heap(free_.begin(), free_.end(), std::greater()); + } + return got; + } + /* The highest slot of segment `k` something holds -- a unit, a copy in flight, a slot in + * quarantine -- or -1. A scan down from the segment's mark. */ + int64_t top_held(int k = 0) const { + const Seg& g = segs_[(size_t)k]; + for (int64_t s = g.live; s-- > g.lo;) + if (held_[(size_t)s]) return s; + return -1; + } + /* How many existing slots at or past `from` something holds, over every segment. */ + int64_t held_from(int64_t from) const { + int64_t k = 0; + for (const Seg& g : segs_) + for (int64_t s = std::max(g.lo, from); s < g.live; ++s) k += held_[(size_t)s]; + return k; + } + +private: + struct Seg { int64_t lo, hi, target, live; }; + int seg_of(int64_t slot) const { + for (size_t k = segs_.size(); k-- > 1;) + if (slot >= segs_[k].lo) return (int)k; + return 0; + } + void push(int64_t s) { + free_.push_back(s); + std::push_heap(free_.begin(), free_.end(), std::greater()); + ++n_usable_; + } + void settle(Seg& g) { while (g.live > g.target && !held_[(size_t)(g.live - 1)]) --g.live; } + /* Every covered slot that nothing holds, once each. Ascending order is already a min-heap. */ + void rebuild() { + free_.clear(); + for (const Seg& g : segs_) + for (int64_t s = g.lo; s < g.target; ++s) + if (!held_[(size_t)s]) free_.push_back(s); + n_usable_ = (int64_t)free_.size(); + } + + int64_t stride_ = 0, n_ = 0, n_usable_ = 0, n_held_ = 0; + std::vector segs_; + std::vector free_; + std::vector held_; +}; + +/* ------------------------------------------------------------------ the file tier */ +/* A thin skin over the device layer's DirectFile, which is where the O_DIRECT mechanics live and + * where they belong: the prefix cache reads the same way for the same reasons, and two + * implementations of "align the offset, the length and the buffer" is two places for the + * alignment rule to drift. What this adds is the tier's own accounting -- a file-tier read is a + * blocking pread in the middle of a dispatch and the counter is how a run that leans on it stops + * being a mystery in the throughput. */ +class FileTier { +public: + /* O_DIRECT, and a refusal rather than a buffered fallback: a tier whose latency is the page + * cache's mood is not a tier you can budget against. `path` is the container. */ + int open(const std::string& path); + bool ok() const { return f_.is_open(); } + void close() { f_.close(); } + + /* One expert-sized read into a pinned buffer. Blocking, counted, and a cliff: a dispatch that + * meets a file-tier unit stops until the read returns. That is the price of a bet the plan + * made -- give the cold tail to disk and buy a host pool big enough to hold a working set + * that can actually move -- paid in full each time the bet is wrong. What changes in response + * is the plan, not this function. */ + int read(uint64_t offset, int64_t bytes, void* pinned_dst, int64_t dst_cap); + + /* Every RadFileEntry offset is RAD_ALIGN_UNIT-aligned by construction (rad_format.h) and that + * is DirectFile's alignment, so the mover's reads take the path with no bounce in it. */ + static int64_t direct_align(int64_t v) { return align_up(v, DirectFile::alignment()); } + + uint64_t reads() const { return reads_; } + uint64_t bytes_read() const { return bytes_; } + +private: + DirectFile f_; + uint64_t reads_ = 0, bytes_ = 0; +}; + +/* ------------------------------------------------------------------ residency */ +class Residency final : public ResidencyTable { +public: + void init(const Program& prog, const Plan& plan); + + const WeightSlot* lookup(rad_weight w) const override { + return (size_t)w < slot_.size() ? &slot_[w] : nullptr; + } + uint64_t epoch() const override { return epoch_; } + const std::vector& changes() const override { return changed_; } + void clear_changes() override { + for (rad_weight w : changed_) noted_[w] = 0; + changed_.clear(); + } + + /* The only two writers, and BOTH BUMP THE GENERATION. `publish` settles a slot -- the bytes + * are there, nothing to wait on. `begin_transfer` opens one: a copy into `ptr` is in flight + * and `ready` is the event the compute stream must be ordered behind. + * + * begin_transfer bumping is the part that is easy to get wrong and expensive to debug. The + * run phase memoises the wait per generation, so installing a new event at the old generation + * makes it skip the wait entirely (residency_iface.h). */ + void publish(rad_weight w, void* ptr); + void begin_transfer(rad_weight w, void* ptr, RadEvent ready); + void settle(rad_weight w) { + if ((size_t)w >= slot_.size()) return; + slot_[w].ready = nullptr; + ++epoch_; + } + +private: + void note(rad_weight w) { + if (noted_[w]) return; + noted_[w] = 1; + changed_.push_back(w); + } + + std::vector slot_; + uint64_t epoch_ = 1; + std::vector changed_; + std::vector noted_; +}; + +/* ------------------------------------------------------------------ configuration */ +struct MoverConfig { + /* Shadow slots and the staging ring are NOT here. They are budgeted by the planner out of + * --vram-weights-mib and reported in the plan (SlabClass::n_shadow, n_stage), and a second + * knob for the same quantity is a second number for the mover and the operator to disagree + * about -- with an overrun as the direction that disagreement goes wrong in. + * + * ---- HOW FAR THE HOST MAY RUN AHEAD OF THE CARDS, IN LAYER DISPATCHES -------------------- + * + * 0 is unbounded, and unbounded STARVES THE MOVER. A freed slot returns to the free list only + * after its quarantine event signals, and that event is on the COMPUTE stream -- so the + * recycle latency is however deep that stream happens to be queued, and the move rate is + * `shadow slots / recycle latency`. Let the host run and the stream carries a whole step's + * work, and almost every round finds no free slot to move into. The guard is not what binds; + * the engine simply never gets the supply to spend. + * + * Holding the host near the cards is therefore not a latency measure but a SUPPLY one. 2 is + * the smallest depth that recovers the effect while leaving the issue path a dispatch of + * margin. A coarser gate -- per step rather than per layer dispatch -- does nothing, because + * one step is already the whole model's worth of queued work; the granularity has to be the + * layer. */ + int max_lead_dispatches = 2; + + /* The container, for the file tier. Empty means there is no file tier and a unit the planner + * put there is an error rather than a slow path. */ + std::string container_path; + /* Pinned staging buffers for file-tier reads. Each is one class stride, and the count is the + * planner's -- RAD_PLACE_FILE_STAGE_SLOTS, which is what the operator was charged for out of + * --host-pool-mib. A separate default here would be a second number for one allocation. */ + int stage_slots = RAD_PLACE_FILE_STAGE_SLOTS; +}; + +/* ------------------------------------------------------------------ the loan */ +/* ONE STRETCH OF ANOTHER POOL'S VRAM THAT MAY BE LENT TO THE SLAB, described from its top down. + * + * The owner keeps it backed and lends it from the top downwards, and it states how much it has + * lent in its own measure -- tokens, for the KV cache -- so the mover can tell which slots a loan + * covers without knowing what the owner stores there. `unit_bytes` of the stretch are one unit of + * that measure and a unit is `unit_tokens` tokens: a loan of T tokens is the top + * floor(T / unit_tokens) * unit_bytes bytes of every stretch. */ +struct LoanStrip { + char* top = nullptr; /* one past the stretch's highest byte */ + int64_t bytes = 0; /* how far below `top` it runs */ + int64_t unit_bytes = 0; + int64_t unit_tokens = 0; +}; + +struct MoverStats { + uint64_t dispatches = 0; + uint64_t promotions = 0, demotions = 0; + uint64_t h2d_bytes = 0, d2h_bytes = 0; + uint64_t prefetched = 0, prefetch_bytes = 0; + /* Why a move did not go out. `no_record` is every in-flight move record busy -- the shadow + * slots, still waiting on their copies. The two `starved` counts are the free lists empty. + * Without these a starved mover is indistinguishable from a satisfied one. */ + uint64_t no_record = 0, starved_slab = 0, starved_pool = 0; + uint64_t quarantined = 0; + /* Demotions that copied nothing: the unit sat in a lent slot and kept its host copy, so going + * back to the host tier was a change of address. Counted inside `demotions` as well. */ + uint64_t dropped = 0; + uint64_t ssd_reads = 0, ssd_bytes = 0; + /* The prefill stager's copies (stage_units): layers staged, units and bytes copied, and + * pooled units a buffer had no room left for -- those were read across the link in place. */ + uint64_t stage_layers = 0, staged_units = 0, staged_bytes = 0, stage_overflow = 0; + /* The file stager's reads (stage_file_units): routed layers read from the container, the + * units and bytes they carried, the preads that carried them, and the host time spent inside + * those reads and waiting for a window's copies to drain -- the two halves of what a step + * that reads the drive costs the thread issuing it. */ + uint64_t file_layers = 0, file_units = 0, file_bytes = 0, file_preads = 0; + uint64_t file_read_ns = 0, file_wait_ns = 0; +}; + +/* ------------------------------------------------------------------ the mover */ +class Mover { +public: + ~Mover(); + Mover() = default; + Mover(const Mover&) = delete; + Mover& operator=(const Mover&) = delete; + + /* Allocates every pool the plan asked for and lays every unit into a slot. Does NOT read a + * byte of the model: the load phase fills the addresses this hands it. Returns RAD_E_NOMEM + * naming the pool that failed, because "out of memory" without which pool is not a + * diagnosis. + * + * `budget` IS THE PRODUCTION PATH AND SHOULD ALWAYS BE PASSED. Pools already allocated + * --vram-weights-mib as one block; a mover that called rad_dev_alloc beside it would spend + * that budget TWICE and the overrun would surface as an out-of-memory from an unrelated + * launch much later. Reserving from Pools::weights() is also what makes it structurally + * impossible for a promotion to reach a KV block -- there is no path from the weights pool to + * the KV pool (mem/pools.h), which is the whole reason the weight slab is a fixed budget. + * + * Null is the standalone-test path and says so at Warn. It is not a supported deployment. */ + int init(const Program& prog, const Plan& plan, const MoverConfig& cfg, Pools* budget = nullptr); + + /* The compute stream this rank issues on. The mover's transfers are ordered against it and + * the quarantine barrier is recorded on it, so without one the mover refuses to move rather + * than storing a table edit blind. */ + int bind_compute_stream(RadStream s); + + /* THE MAINTENANCE STREAM, AND WHY ANYTHING ELSE MAY HAVE IT. + * + * A HIP stream costs a hardware queue, and on RDNA4 a fourth concurrent queue is not a small + * cost: on a two-card R9700 Flash-Next server, a fourth stream that never carries a single + * byte takes the decode step from 20.5 ms to 33.9 (GPU_MAX_HW_QUEUES 1, 2 or 3 all run at + * full speed; 4 and 8 do not). The engine already issues on three -- compute, the second + * compute lane, and this one -- so a subsystem that wants a stream to move bytes off the + * critical path must TAKE THIS ONE rather than make a fourth. + * + * Null before init(), and null on a rank with nothing to move. A caller that gets null must + * fall back to its own stream: three streams is under the cliff either way. + * + * THE MOVER'S RUN PHASE ISSUES ON IT, so this stream is not idle: a sharer queueing a hundred + * megabytes on it will sit in front of a transfer the compute stream is waiting on. Gate the + * two -- do not answer it by making a fourth queue. */ + RadStream transfer_stream() const { return mover_; } + + ResidencyTable* residency() { return &res_; } + /* THE ONE ADDRESS THE MOVER DOES NOT OWN. A Tier::Mapped weight lives in the container's + * mapping and the LOAD PHASE is what holds the RadFile, so it publishes the pointer and the + * mover only records it -- the residency table is the mover's, and a second table would be a + * second answer to "where is this weight". Nothing here ever moves it afterwards: a mapped + * unit has no slab class, so unit_base() has no address of its own to republish over this. */ + void publish_mapped(rad_weight w, void* p) { res_.publish(w, p); } + + /* ---- the run phase, in the order a layer dispatch calls it ----------------------------- + * + * begin_dispatch retire whatever landed, gate the host's lead, record the ordering event + * prefetch_to_op release what this op has finished with, then start everything the exact + * schedule says is due -- and keep starting, as long as slots are free + * issue one heat proposal + * + * There is no end_dispatch, and the absence is deliberate. The quarantine barrier belongs + * DOWNSTREAM of the publish in stream order, and begin_dispatch's retire() is exactly that + * point: by the time it runs, every launch the previous dispatch made has been issued. A + * symmetric end-of-dispatch hook would record the barrier before those launches and the + * quarantine would be satisfied for a reason that has nothing to do with the kernels it is + * guarding. + * + * ---- A CALLER MUST DO ALL OF IT, EVERY DISPATCH ------------------------------------------- + * + * begin_dispatch only RETIRES; it never starts anything. A loop that retires without issuing + * is not a slower engine, it is a stuck one: the pool free list starts empty, so the first + * round can only promote out of the shadow slots, and the pool slot that promotion frees + * arrives several dispatches later -- by which time, if nothing is asking, the resident set + * has grown by the shadow count and never shrinks again. The symptom is zero demotions + * forever, and it appears only on a real card: on the host backend every copy lands inside + * the dispatch that issued it, so the same mistake passes unnoticed. + * + * The compute stream must also carry the dispatch's actual work. The quarantine barrier is an + * event on that stream and its claim is "every kernel that could still name this slot has + * retired"; against an empty stream the claim is vacuous and the lead gate paces nothing. + */ + /* `begin_dispatch` and `issue` are the engine's, once a step: Engine::tiering_dispatch is the + * seam, and it is a step and not a layer because the mover relocates BETWEEN steps and never + * during one (runtime/ctx.cpp honours `weights_dirty_` once, at the top of run_step). + * + * `prefetch_to_op` has no caller but tests/place_test.cpp, and that is DELIBERATE -- the + * exact-schedule path is kept built and tested rather than deleted and rewritten later. Do + * not read "no caller" there as the dead-surface shape it resembles elsewhere in this tree. */ + int begin_dispatch(int dispatch, HeatEngine* heat); + int prefetch_to_op(int32_t op_index); + int issue(const Swap& s, HeatEngine* heat); + + /* ---- the loan: VRAM another pool is not using ------------------------------------------ + * + * VRAM some other pool carved and is not using is worth more here than it is there: an + * expert unit that does not fit the slab is read across the link on the critical path of + * every step that routes to it. The KV cache keeps its whole carve backed and LENDS the slab + * the part nothing holds, and the activation arena lends the part a step smaller than the + * largest one does not reach -- each at addresses it already owns, so the slab grows into + * that memory with no allocation, no mapping and no driver call, and gives it back the same + * way. The ONLY caller that may lend is the one that arbitrates the whole card: two callers + * with two opinions about how much is spare is the same memory in two pools. + * + * EACH LENDER LENDS IN ITS OWN MEASURE, into its own segment of the slab (SlotPool): the KV + * cache in tokens, the arena in bytes. They move independently -- a prefill takes the arena's + * memory back while the cache goes on lending -- so every call names the lender it is about. + * + * A UNIT IN A LENT SLOT KEEPS ITS HOST COPY. Weights never change, so the pinned pool slot it + * was promoted from still holds exactly its bytes, and giving the slot back is a change of + * address rather than a copy across the link. That is what makes a loan cheap to recall: + * the cache waits for kernels to stop naming the slot, never for bytes to move. */ + + enum Lender { kLendKV = 0, kLendArena = 1, kLenders = 2 }; + + /* The stretches a lender may ever lend, once per lender, after its memory is carved. Carves + * every stretch into slots of each class's stride from the top down, so the slots a small loan + * covers are the ones a large loan covers first, and the slot a loan gives back first is the + * deepest. */ + int lend_from(int lender, const std::vector& strips); + + /* HOW MUCH A LENDER LENDS, in its own measure. A TARGET, not a transaction: slots the loan + * newly covers can be filled at once, while slots it no longer covers are emptied as their + * units are dropped and their quarantine clears -- `loan_held` is how far down the lender's + * memory the slab still reaches, and the lender may not use those bytes again until it has + * fallen. */ + int set_loan(int lender, int64_t amount); + int64_t loan_held(int lender) const; + int64_t loan(int lender) const { return loan_[lender]; } + + /* THE SAME, NOW, for a lender that cannot wait: every unit past `amount` is dropped to its + * host copy and both streams that can touch a slot are drained before this returns, so the + * memory is the lender's the moment it does. A host wait, taken only when the lender needs + * more than it kept in hand -- a request larger than the cache's buffer, a step larger than + * the arena's lent level allows. */ + int reclaim(int lender, int64_t amount, HeatEngine* heat); + + /* What the lent slots hold and what the loan offers, in bytes, and every slot the stretches + * could ever hold. Read by the HTTP thread for the dashboard, hence stored rather than + * computed from the slot pools, which only this thread may walk. */ + int64_t flex_used_bytes() const { return flex_used_.load(std::memory_order_relaxed); } + int64_t flex_offered_bytes() const { return flex_offered_.load(std::memory_order_relaxed); } + int64_t flex_capacity() const; + /* THE LOAN PAST WHICH NOTHING MORE WOULD BE USED, in the lender's measure: the one that + * covers every slot carved from it. The slots were carved no deeper than the units the host + * pool holds, so a loan this size already has room for every unit that could move -- more VRAM + * from the lender would sit empty. Zero with nothing carved. */ + int64_t loan_ceiling(int lender) const; + + /* FILL EVERY SLOT THERE IS ROOM IN, AND EMPTY EVERY SLOT THE LOAN NO LONGER COVERS -- the + * half-swaps the heat engine never proposes, because its decision is a COMPARISON and a + * comparison needs a victim. Not bounded by a count: a slot left empty while a unit streams + * across the link is VRAM bought and wasted on every step, so every free slot is filled in + * one call, hottest units first, and the copies run at the rate the link carries them. */ + int balance(HeatEngine* heat); + + /* balance() for a rank with no step to ride on. Retires what has landed and fills what is + * free, so a loan made while the server is idle is filled before the next request rather + * than by it. Only while the rank thread is parked. */ + int idle_tick(HeatEngine* heat); + + /* Where a unit's bytes are right now, as a device-visible address, or null for a file-tier + * unit that has not been staged. */ + void* unit_base(int32_t unit) const; + + /* ---- STAGING WITHIN A PASS: the prefill stager (core/place/stager.h) ---------------------- + * + * Everything else the mover does happens between steps, and a unit's address is fixed for the + * length of a step. These two are the exception, and they change only the PUBLISHED address, + * never where a unit lives: the unit stays in its pinned pool slot, and for one routed layer's + * ops the run phase reads a copy of it in a buffer the caller owns. + * + * stage_units copy every unit of `units` that lives in the pinned pool, has no slab slot and + * has no copy of its own in flight into `dst`, one after another at the allocation + * unit, until `cap` has no room for the next -- on the mover's stream, behind + * `after` when it is not null, with `done` recorded behind the last copy. Each + * copied unit's weights are then published at the copy, SETTLED: the caller + * orders the ops that read them behind `done` with one stream wait, where an + * event on every weight would cost the run phase one wait per weight -- a few + * hundred a layer. `staged` gets the units copied, in order. + * unstage_units publish those units at their pool slots again. The caller must already have + * ordered the next writer of `dst` behind every op that read the copies; this + * only moves the address the NEXT issue resolves. + */ + int stage_units(const std::vector& units, char* dst, int64_t cap, RadEvent after, + RadEvent done, std::vector* staged); + void unstage_units(const std::vector& staged); + + /* ---- ROUTED LAYERS READ FROM THE CONTAINER: the file stager (core/place/stager.h) -------- + * + * A routed unit the plan put on the file tier has no address at all (unit_base is null), and a + * grouped GEMM is handed every expert's pointer at issue -- so before a routed layer's first + * expert op, every one of its file-tier units is read into a VRAM buffer and published there, + * and after the layer it is published as null again (unstage_units does that half). The + * buffers are the two the plan charged out of --vram-weights-mib (Plan::file_stage_vram). + * + * stage_file_units read every unit of `units` that is on the file tier into `dst`, packed at + * RAD_ALIGN_UNIT in the order given, through the pinned read windows: the + * layer's weights are read in container order as long runs -- a run skips a + * gap of resident units rather than reading through it -- each window drains + * to `dst` on the mover's stream while the next fills, behind `after` when it + * is not null, with `done` recorded behind the last copy. Published SETTLED, + * for the reason stage_units gives. Refuses with RAD_E_SCRATCH when the units + * do not fit `cap`, which a buffer sized by the plan never meets. The reads + * are BLOCKING on this thread; that is the price of the tier and the stats + * above carry it. + * file_buffer buffer 0 or 1 of the plan's two, or null when the plan has none. */ + int stage_file_units(const std::vector& units, char* dst, int64_t cap, + RadEvent after, RadEvent done, std::vector* staged); + char* file_buffer(int i) const { + return (file_vram_ && (i == 0 || i == 1)) ? file_vram_ + i * file_buf_bytes_ : nullptr; + } + int64_t file_buffer_bytes() const { return file_vram_ ? file_buf_bytes_ : 0; } + + const MoverStats& stats() const { return stats_; } + std::string report() const; + +private: + /* One in-flight relocation. The state machine is Free -> Copying -> Published -> Quarantine + * -> Free, and every transition is made by the DISPATCH THREAD at a layer boundary. The + * transfers are asynchronous; the table edits are not. No mutex on the read side, because + * that side is the critical path of every layer, and no background thread mutating placement + * mid-layer, because placement would then depend on host timing and stop being reproducible. */ + struct Move { + enum class State { Free, Copying, Published, Quarantine }; + /* Five kinds, one state machine. Promote and Demote are the heat engine's swaps. Stage is + * the exact prefetch bringing an offloaded unit into a slot. Release is the same slot + * going back once the declared order says nothing will read it again this step -- it + * copies nothing and still needs the quarantine, because the barrier is about kernels + * already issued and not about bytes in flight. Drop is a unit in a lent slot going back + * to the host copy it kept: no copy either, and the same quarantine for the same reason. */ + enum class Kind { Promote, Demote, Stage, Release, Drop }; + State state = State::Free; + Kind kind = Kind::Promote; + int32_t unit = -1; + int64_t slab_slot = -1; + int64_t pool_slot = -1; + RadEvent ev = nullptr; + }; + + struct UnitState { + Tier tier = Tier::VRAM; + Site site = Site::Device; + int64_t slab_slot = -1; /* index into class slab, or -1 */ + int64_t pool_slot = -1; /* index into class host pool, or -1 */ + int64_t static_off = -1; /* byte offset into the static VRAM region, or -1 */ + int32_t klass = -1; + int64_t bytes = 0; + }; + + /* One weight class's memory. The slab is two kinds of slot rather than one: the BUDGETED slots + * come out of --vram-weights-mib like every other weight allocation and sit at a fixed stride + * from one base, and the FLEX slots past them are addresses inside another pool's memory -- + * the KV cache's carve, the activation arena's top -- lent while that pool is not using them. + * They cannot be one range because the flex slots are scattered over every layer's stripe of + * the cache, wherever a stripe has room for one. + * + * A slot index therefore carries no information about which kind it is; slot_ptr is the only + * place that distinction exists. Each lender's flex slots are one segment of the slab, ordered + * by the loan that covers each, so a loan of any size is a prefix of its segment. */ + struct ClassPools { + SlotPool slab, pool; + void* slab_base = nullptr; + void* pool_base = nullptr; + void* pool_dev = nullptr; /* the pinned pool as the device addresses it */ + int64_t stride = 0; + int64_t n_fixed = 0; /* slots in the budgeted range; the flex ones start here */ + int64_t n_work = 0; /* shadow + staging: free slots the mover needs to move at all */ + std::vector flex_ptr; + /* ONE SEGMENT OF THE SLAB PER LENDER THAT CARVED SLOTS FOR THIS CLASS. `need[i]` is the + * loan, in the lender's measure, that covers the segment's i-th slot; ascending, so a + * loan of any size covers a prefix. */ + struct Lent { int lender = 0; int seg = -1; int64_t first = 0; std::vector need; }; + std::vector lent; + /* A slot leaves coverage only when a loan shrinks, and nothing is ever placed in an + * uncovered one, so units stranded past the loan exist only after a shrink. Set there, and + * cleared by a balance() sweep that dropped every one of them. */ + bool strand_check = true; + + char* slot_ptr(int64_t slot) const { + return slot < n_fixed ? (char*)slab_base + slot * stride + : flex_ptr[(size_t)(slot - n_fixed)]; + } + bool is_flex(int64_t slot) const { return slot >= n_fixed; } + }; + + const Program* prog_ = nullptr; + const Plan* plan_ = nullptr; + MoverConfig cfg_; + Residency res_; + MoverStats stats_; + Pools* budget_ = nullptr; + /* True only when this object called the allocator itself, which is the test path. A Pool + * reservation is owned by the Pool and freeing it here would be a double free. */ + bool owns_memory_ = false; + + RadStream mover_ = nullptr; + RadStream compute_ = nullptr; + RadEvent gate_ = nullptr; /* recorded on compute, waited on by the mover stream */ + int gate_dispatch_ = -1; + + std::vector pools_; + std::vector unit_; + std::vector moves_; + + void* static_vram_ = nullptr; + int64_t static_bytes_ = 0; + void* pageable_ = nullptr; + int64_t pageable_bytes_ = 0; + + FileTier file_; + void* stage_ = nullptr; /* pinned staging ring for file-tier reads */ + int64_t stage_stride_ = 0; + int stage_next_ = 0; + + /* The file stager's two VRAM buffers, one allocation, and the pinned windows it reads + * through, each with the event behind the copies out of it. */ + char* file_vram_ = nullptr; + int64_t file_buf_bytes_ = 0; + char* windows_ = nullptr; + int n_windows_ = 0; + int win_next_ = 0; + std::vector win_ev_; + std::vector win_rec_; + + /* The lead gate's ring: one event a dispatch, and a host wait on the one from + * max_lead_dispatches ago. */ + std::vector lead_; + int lead_next_ = 0; + int32_t prefetch_cursor_ = 0; + int32_t last_op_ = -1; + int dispatch_ = 0; + + /* THE LOAN, in the owner's tokens, and what the dashboard reads of it. */ + int64_t loan_[kLenders] = {}; + std::atomic flex_used_{0}; + std::atomic flex_offered_{0}; + /* Where the last free record was found. Records free up roughly in the order they were taken, + * so starting the next search there makes it a step rather than a walk of every record, which + * matters once the lent slots have put a record's worth of them in flight. */ + mutable size_t rec_cursor_ = 0; + + int retire(HeatEngine* heat); + int record_gate(); + void republish(int32_t unit); + void* reserve(const char* what, int64_t bytes, int kind); + int free_move_record() const; + int start_stage(int32_t unit, int64_t slab_slot); + void release_slot(int32_t unit); + bool unit_in_flight(int32_t unit) const; + /* A unit in a lent slot back to the host copy it kept. See Move::Kind::Drop. */ + int drop(int32_t unit, HeatEngine* heat); + /* One promotion out of the unit's pool slot into `slot`, which the caller has taken. */ + int promote_to(int32_t unit, int64_t slot); + /* Promote the hottest pooled units of one class into up to `room` free slots. */ + int fill(size_t klass, int64_t room, HeatEngine* heat); + void count_flex(); +}; + +} /* namespace rad */ diff --git a/core/place/planner.cpp b/core/place/planner.cpp new file mode 100644 index 00000000..e185ac5c --- /dev/null +++ b/core/place/planner.cpp @@ -0,0 +1,1209 @@ +/* planner.cpp -- the placement planner. See planner.h for the design; this file is the mechanics. + * + * The planner runs once, between declare and load, and it is pure: it reads the Program, the + * Config and the container's profile, and it writes a Plan. It queries no device, reads no clock + * and looks at no environment. That is not tidiness -- it is what makes Config::deterministic + * implementable (spec §17) and what makes the resident set identical on every tensor-parallel + * rank (planner.h, MoveUnit). + * + * DO NOT ADD A DEVICE QUERY HERE, and the reason is concrete rather than principled. Every pool is + * budgeted explicitly from Config (spec §6) -- no profiling pass, no utilisation fraction. A + * planner that instead derived a budget from RadDeviceProps would have to cope with rad_dev_count() + * reporting devices that are not the target: an integrated GPU enumerates alongside the discrete + * ones and reports tens of GiB of "VRAM" that is really system RAM, so summing capacity across + * devices overstates the budget by that much and produces a plan that cannot load. Any future code + * that does look at props must be per-device and must filter on RadDeviceProps::arch, never on + * index and never on capacity. + */ +#include "planner.h" + +#include +#include +#include + +namespace rad { + +/* ------------------------------------------------------------------ names */ +/* These live here because placement is the component that owns what a tier and a site MEAN. + * rad_core.h declares them; if a second definition appears, one of us is wrong about ownership. */ +const char* tier_name(Tier t) { + switch (t) { + case Tier::VRAM: return "vram"; + case Tier::HostPinned: return "pinned"; + case Tier::HostPageable: return "pageable"; + case Tier::SSD: return "ssd"; + case Tier::Mapped: return "mapped"; + } + return "?"; +} + +const char* site_name(Site s) { + switch (s) { + case Site::Device: return "device"; + case Site::DeviceStaged: return "staged"; + case Site::DeviceZeroCopy: return "zero-copy"; + case Site::Host: return "host"; + } + return "?"; +} + +const char* strategy_name(Strategy s) { + switch (s) { + case Strategy::AllVram: return "all_vram"; + case Strategy::LayerOffload: return "layer_offload"; + case Strategy::ExpertTiered: return "expert_tiered"; + case Strategy::Auto: return "auto"; + } + return "?"; +} + +int strategy_parse(const char* s, Strategy* out) { + if (!s || !out) return RAD_E_INVAL; + if (!std::strcmp(s, "all_vram")) { *out = Strategy::AllVram; return RAD_OK; } + if (!std::strcmp(s, "layer_offload")) { *out = Strategy::LayerOffload; return RAD_OK; } + if (!std::strcmp(s, "expert_tiered")) { *out = Strategy::ExpertTiered; return RAD_OK; } + if (!std::strcmp(s, "auto")) { *out = Strategy::Auto; return RAD_OK; } + return RAD_E_INVAL; +} + +Budgets Budgets::from(const Config& c) { + Budgets b; + b.vram_weights = c.vram_weights_mib * 1024 * 1024; + b.host_pool = c.host_pool_mib * 1024 * 1024; + b.ssd = c.weights_disk_tier; + return b; +} + +/* ------------------------------------------------------------------ sizes and keys */ +int64_t weight_bytes(const WeightInfo& w) { + /* The layout pass's answer when it has run: the stored layout is what actually occupies a + * tier, and for a kernel that re-layouts its weights it is not the logical size. Before the + * layout pass -- which is the state a planner unit test builds -- fall back to the declared + * dtype and shape, which is what logical_bytes is. */ + if (w.stored_bytes > 0) return w.stored_bytes; + if (w.logical_bytes > 0) return w.logical_bytes; + int64_t n = w.decl.rank ? 1 : 0; + for (uint32_t i = 0; i < w.decl.rank; ++i) n *= w.decl.shape[i]; + return rad_dtype_bytes(w.decl.dtype, n); +} + + +/* See planner.h. Planner::resolve_sites, Planner::build_units and Planner::pin_mapped, run over + * the same program without allocating a Plan -- the budget resolver calls this before a Planner + * exists. Kept adjacent to the three so a change to any of them has this in the same diff. */ +void weight_footprint(const Program& prog, WeightFootprint* out) { + if (!out) return; + *out = WeightFootprint{}; + + /* resolve_sites: a weight every one of whose ops lacks a device band cannot be read on the + * card, so it is never copied there whatever the budgets say. */ + std::vector device_ok(prog.weights.size(), 1u); + for (const OpInfo& o : prog.ops) { + bool dev = !o.bands.empty(); + for (const Band& b : o.bands) if (!b.dom[RAD_DOMAIN_DEVICE]) dev = false; + if (dev) continue; + for (rad_weight w : o.weights) + if (w != RAD_NULL_HANDLE && w < device_ok.size()) device_ok[w] = 0u; + } + + /* build_units: a model-level weight is its own unit, everything else groups by the declared + * (layer, expert). Ordered, for the same reason build_units is. */ + struct U { int32_t layer = -1, expert = -1; int64_t bytes = 0; bool mapped = false; }; + std::map, size_t> by_group; + std::vector units; + + for (rad_weight w = 1; (size_t)w < prog.weights.size(); ++w) { + const WeightInfo& wi = prog.weights[w]; + const int32_t layer = wi.decl.group.layer, expert = wi.decl.group.expert; + size_t u; + if (layer < 0) { + u = units.size(); + units.push_back(U{}); + } else { + auto key = std::make_pair(layer, expert); + auto it = by_group.find(key); + if (it == by_group.end()) { + u = units.size(); + by_group.emplace(key, u); + units.push_back(U{}); + units.back().layer = layer; + units.back().expert = expert; + } else { + u = it->second; + } + } + U& mu = units[u]; + const int64_t a = wi.align > 0 ? wi.align : RAD_ALIGN_UNIT; + mu.bytes = align_up(mu.bytes, a) + weight_bytes(wi); + /* pin_mapped: THE WHOLE UNIT GOES, not the one weight. */ + if (w < device_ok.size() && !device_ok[w]) mu.mapped = true; + } + + /* And one align_up a unit, because that is how Mover::init spends the slab: `us.static_off = + * align_up(static_need, RAD_ALIGN_UNIT)` before every unit it places. A budget that summed raw + * bytes would be short by one alignment per unit, which on a 512-expert MoE is real. */ + std::map layer_experts; + for (const U& mu : units) { + const int64_t b = align_up(mu.bytes, RAD_ALIGN_UNIT); + if (mu.mapped) out->mapped += b; + else if (mu.expert >= 0) { out->experts += b; layer_experts[mu.layer] += b; } + else out->statics += b; + } + for (const auto& le : layer_experts) + out->expert_layer_max = std::max(out->expert_layer_max, le.second); + out->n_units = (int64_t)units.size(); +} +std::string weight_class_key(const std::string& name) { + std::string out; + out.reserve(name.size()); + for (size_t i = 0; i < name.size();) { + if (name[i] >= '0' && name[i] <= '9') { + out += '*'; + while (i < name.size() && name[i] >= '0' && name[i] <= '9') ++i; + } else { + out += name[i++]; + } + } + return out; +} + +/* ------------------------------------------------------------------ site availability */ +/* Host-site execution needs a RAD_DOMAIN_HOST kernel from a kernel plugin, and where none + * resolved that site is UNAVAILABLE for that op (spec §5.1). The planner does not take that as a + * flag from somewhere; it reads the Band's per-domain resolution, because the resolution IS the + * fact and anything else can drift from it. + * + * EVERY band, not the band that happens to run. A bucket table exists because the same op serves + * M=1 at decode and M=4096 at prefill (spec §2.2), and a site that is available for one and not + * the other is a site that changes under load. Placement is decided once; it has to hold for + * every step the plan is legal for. + * + * BOTH DOMAINS ARE TRACKED, and they answer different questions. Host says whether the host SITE + * is available -- an option the budgets may or may not take. Device says whether the weight may be + * placed on a card AT ALL, and a weight whose op has no device kernel anywhere may not: it is + * pinned to the container's mapping by pin_mapped below, before any budget is consulted. + * + * Tracking host alone would rest on the argument that a missing device kernel is fatal at declare + * and never reaches the planner. That is true only of an op with NO kernel in either domain: an op + * such as `embed_lookup_q` resolves on the host and nowhere else -- deliberately, because its + * table is far too large for the card and must not be copied there -- and declare reports that + * device band as unserved without refusing the model. */ +void Planner::resolve_sites(const Program& prog) { + host_ok_.assign(prog.weights.size(), 1u); + device_ok_.assign(prog.weights.size(), 1u); + + for (const OpInfo& o : prog.ops) { + bool host = !o.bands.empty(); + bool dev = !o.bands.empty(); + for (const Band& b : o.bands) { + if (!b.dom[RAD_DOMAIN_HOST]) host = false; + if (!b.dom[RAD_DOMAIN_DEVICE]) dev = false; + } + for (rad_weight w : o.weights) { + if (w == RAD_NULL_HANDLE || w >= host_ok_.size()) continue; + if (!host) host_ok_[w] = 0u; + /* AND THE OTHER DIRECTION, which is not the same statement. The absence of a host + * kernel removes a placement OPTION; the absence of a DEVICE one removes every option + * but host, and that is a decision rather than a preference: bytes an op can only be + * computed over on the CPU must not be copied to a card that cannot read them. + * + * Declare's asymmetry still holds -- a band with neither kernel is fatal before the + * planner runs -- so reaching here with `!dev` means `host` is true. */ + if (!dev) device_ok_[w] = 0u; + } + } +} + +/* ------------------------------------------------------------------ the mapped tier */ +/* A weight no device kernel can read is pinned to the container's mapping BEFORE any budget is + * consulted, because it is not a budget question. The other three off-device tiers are what the + * planner falls back to when VRAM runs out; this one is where the weight has to be whatever the + * budgets say, and charging a pool for bytes that are never copied would make the operator size a + * pool against a number that does not exist. + * + * THE WHOLE UNIT GOES, not the one weight. A unit is the movement granularity and a half-mapped + * one has no meaning -- and it costs nothing here, because `device_ok_` is cleared for EVERY + * weight operand of a host-only op, so the unit's other members are the same op's scale and + * constants. What this does exclude is a plugin that groups a host-only weight with a device one: + * that collapses the whole group onto the host, so the report names it. */ +void Planner::pin_mapped(const Program& prog, Plan* p) { + for (MoveUnit& mu : p->units) { + bool mapped = false; + for (rad_weight w : mu.weights) + if (w < device_ok_.size() && !device_ok_[w]) mapped = true; + if (!mapped) continue; + + mu.tier = Tier::Mapped; + mu.site = Site::Host; + mu.movable = false; + mu.reason = "no device kernel for its op; read from the container's mapping"; + /* AND ONLY WHAT LIES IN THE CONTAINER AS THE KERNEL READS IT can be read from the mapping: + * a weight its kernel rearranges at load, or a shard of one, has no place in the file + * that already looks the way the kernel reads it (spec §5.1). */ + if (!in_.container) + note_unfit(p, mu, "only a host kernel reads it, so it must be read from a " + "container's mapping -- and a checkpoint served directly has " + "none; convert it to a container"); + else + for (rad_weight w : mu.weights) + if (w < prog.weights.size() && + !weight_file_direct(prog.weights[w], prog.ctx.world_size)) + note_unfit(p, mu, "only a host kernel reads it, so it must be read from the " + "container's mapping -- and its stored form is not the " + "container's (a relayout, a widening or a shard)"); + for (rad_weight w : mu.weights) + if (w < device_ok_.size() && device_ok_[w]) + RAD_WARN("placement: '%s' is grouped with a weight only a host kernel can read, " + "so the whole group stays in the container's mapping", + prog.weights[w].name.c_str()); + } +} + +/* ------------------------------------------------------------------ units */ +int access_strength(int access) { + switch (access) { + case RAD_ACCESS_PER_TOKEN: return 4; + case RAD_ACCESS_VOCAB: return 4; + case RAD_ACCESS_PER_REQUEST: return 2; + case RAD_ACCESS_CONDITIONAL: return 1; + case RAD_ACCESS_RARE: return 0; + default: return 4; /* an access class we do not know is not one to + * gamble a demotion on */ + } +} + +void Planner::build_units(const Program& prog, Plan* p) { + p->unit_of_weight.assign(prog.weights.size(), -1); + p->units.clear(); + + /* Keyed on the declared RadWeightGroup, which is the plugin's statement about what moves + * together. Ordered, not hashed: the unit order has to be a function of the model and not of + * a hash seed, or two ranks can rank the same profile differently and disagree about which + * experts are resident. */ + std::map, int32_t> by_group; + + for (rad_weight w = 1; (size_t)w < prog.weights.size(); ++w) { + const WeightInfo& wi = prog.weights[w]; + const int32_t layer = wi.decl.group.layer; + const int32_t expert = wi.decl.group.expert; + + /* A model-level weight is its own unit. Grouping every model-level weight together would + * make the embedding table and the output norm one movement unit of wildly different + * access classes, and the mover would have to carry the larger of them for the smaller. */ + int32_t u; + if (layer < 0) { + u = (int32_t)p->units.size(); + p->units.push_back(MoveUnit{}); + p->units.back().layer = -1; + p->units.back().expert = -1; + } else { + auto key = std::make_pair(layer, expert); + auto it = by_group.find(key); + if (it == by_group.end()) { + u = (int32_t)p->units.size(); + by_group.emplace(key, u); + p->units.push_back(MoveUnit{}); + p->units.back().layer = layer; + p->units.back().expert = expert; + } else { + u = it->second; + } + } + + MoveUnit& mu = p->units[(size_t)u]; + const int64_t a = wi.align > 0 ? wi.align : RAD_ALIGN_UNIT; + const int64_t at = align_up(mu.bytes, a); + mu.weights.push_back(w); + mu.offset.push_back(at); + mu.bytes = at + weight_bytes(wi); + if (!in_.container || !weight_file_direct(wi, prog.ctx.world_size)) mu.file_direct = false; + if (wi.first_use_op >= 0 && (mu.first_use_op < 0 || wi.first_use_op < mu.first_use_op)) + mu.first_use_op = wi.first_use_op; + if (wi.last_use_op > mu.last_use_op) mu.last_use_op = wi.last_use_op; + if (mu.weights.size() == 1 || + access_strength(wi.decl.access) > access_strength(mu.access)) + mu.access = wi.decl.access; + p->unit_of_weight[w] = u; + } + + /* Warm start from the profile. It ranks which experts BEGIN resident and nothing else: it is + * worth about a point of hit rate against an arbitrary order and honestly not more, because + * imatrix popularity is not decode popularity and the heat engine re-ranks from real routing + * within a few dispatches regardless. A warm start, not a policy (spec §5.3). */ + if (in_.profile && in_.n_profile > 0) { + std::map, float> share; + for (int64_t i = 0; i < in_.n_profile; ++i) + share[std::make_pair(in_.profile[i].layer, in_.profile[i].expert)] = + in_.profile[i].share; + for (MoveUnit& mu : p->units) { + auto it = share.find(std::make_pair(mu.layer, mu.expert)); + if (it != share.end()) mu.profile_share = it->second; + } + } +} + +/* ------------------------------------------------------------------ slab classes */ +/* One class per (unit kind, byte size). A slab slot is interchangeable within its class and + * nowhere else, which is what lets a promotion be an integer swap instead of an allocation, and + * what lets a slot be LAYER-AGNOSTIC: heat promotes the hottest pooled expert against the coldest + * resident one wherever they sit, so capacity moves to the layers that need it. A per-layer + * ranking cannot repair the residency skew a global profile leaves behind, and the slab being + * layer-agnostic is the whole reason a global ranking is legal. + */ +void Planner::build_classes(Plan* p) { + std::map, int32_t> seen; + + for (MoveUnit& mu : p->units) { + /* A MAPPED UNIT HAS NO CLASS AND NO SLOT. Classes exist so a slab slot is interchangeable + * within one; a unit that is never copied anywhere has nothing to be interchangeable with, + * and giving it a stride would charge its whole size to a pool it does not occupy. Its + * slot_bytes stays 0, which is what every budget below spends against. */ + if (mu.tier == Tier::Mapped) continue; + const int kind = mu.expert >= 0 ? 2 : (mu.layer >= 0 ? 1 : 0); + const int64_t stride = align_up(mu.bytes, RAD_ALIGN_UNIT); + auto key = std::make_pair(kind, stride); + auto it = seen.find(key); + if (it == seen.end()) { + const int32_t c = (int32_t)p->classes.size(); + seen.emplace(key, c); + SlabClass sc; + sc.name = kind == 2 ? "expert" : (kind == 1 ? "layer" : "model"); + sc.name += "/" + humanb(stride); + sc.stride = stride; + p->classes.push_back(sc); + mu.slab_class = c; + } else { + mu.slab_class = it->second; + } + mu.slot_bytes = p->classes[(size_t)mu.slab_class].stride; + p->classes[(size_t)mu.slab_class].n_units++; + } +} + +/* ------------------------------------------------------------------ the ranking */ +/* Rank-invariant by construction. The key is (profile share desc, layer, expert, unit index) and + * every component of it is a property of the model or of the container -- nothing rank-local, + * nothing timed, nothing from the device. Under tensor parallel every rank runs this and gets the + * same order, which is what makes a slab slot mean the same thing on every card. */ +void Planner::rank_units(Plan* p, std::vector* order) const { + order->clear(); + order->reserve(p->units.size()); + for (int32_t i = 0; i < (int32_t)p->units.size(); ++i) order->push_back(i); + std::stable_sort(order->begin(), order->end(), [&](int32_t a, int32_t b) { + const MoveUnit& ua = p->units[(size_t)a]; + const MoveUnit& ub = p->units[(size_t)b]; + if (ua.profile_share != ub.profile_share) return ua.profile_share > ub.profile_share; + /* EXPERT-MAJOR, NOT LAYER-MAJOR, AND THE TIE-BREAK IS THE WHOLE POLICY WHEN THERE IS NO + * PROFILE -- which is the common case, because a container without one gives every unit + * share 0.0 and every comparison above falls through to here. + * + * Layer-major fills every expert of layer 0, then layer 1, and stops wherever the budget + * runs out, so the layers past the cut begin the run with NOTHING resident. The heat + * engine cannot repair that quickly: a promotion needs the candidate to beat the victim by + * `hysteresis * cold + min_gain`, and an expert in a starved layer is routed to rarely + * enough that the skew is worked off a few hundred units at a time, paying both link + * directions for every one. + * + * WHAT THE SKEW COSTS IS ON-DEMAND STREAMING, not mover churn. A starved layer misses on + * most of what it routes to and streams those shards over the link inside the GEMM, so its + * expert projections run several times longer than a well-stocked layer's, every step. + * + * Expert-major puts expert 0 of every layer before expert 1 of any, so the budget cut + * lands at the same expert index in every layer and residency starts balanced. That is + * not a better RANKING -- with no profile there is no information to rank on -- it is the + * absence of an arbitrary one, and it leaves the heat engine's moves to do the job it + * exists for instead of repairing the fill. heat.h makes the same argument about its own + * tie-break: ties go to the layer that can most afford it, never to the low index. + * + * NO CAPACITY IS ADDED BY THIS, and the per-layer residency histogram in HeatEngine::report + * is where that shows: the mean resident count a layer is unchanged and only its spread + * collapses. Well-stocked layers give up some slots and get slightly slower; starved ones + * gain more than that back. The largest single beneficiary is whichever layer runs more + * than once a step -- a draft head runs once per draft round -- because every slot there is + * spent several times a step. + * + * Uniform is still the right fill when there is no profile to rank on, and the heat engine + * already sees the extra activations of a multiply-run layer in its own counter, so the + * planner does not weight for it. */ + if (ua.expert != ub.expert) return ua.expert < ub.expert; + return ua.layer < ub.layer; + }); +} + +/* ------------------------------------------------------------------ assignment */ +namespace { + +/* The three ways a unit can live off the device, in the order the planner tries them. Split out + * so the expert path and the layer path cannot drift: they are the same mechanism at two + * granularities and they have to spell the fallback the same way. */ +struct HostFall { + int64_t host_used = 0; + int64_t host_budget = 0; + bool ssd = false; + + /* Returns true and sets tier/site, or false when nothing below VRAM will take it. + * + * THE SITE DECIDES THE TIER, which is the independent-axes claim made concrete. Only a unit + * the DEVICE has to read needs pinned memory; a host-site unit is read by a host kernel and + * pinning it buys nothing. That matters because pinned memory is genuinely scarce -- past a + * driver-dependent total the registration call starts returning success and leaving the + * process broken -- so pinning tens of gigabytes of weights only the CPU touches is not a + * waste, it is a failure mode. Both kinds are charged against the same --host-pool-mib, + * because an unbudgeted tier is how a process gets OOM-killed. */ + bool place(MoveUnit& mu, bool host_kernel, const char** reason) { + if (host_used + mu.slot_bytes <= host_budget) { + host_used += mu.slot_bytes; + if (host_kernel && mu.access == RAD_ACCESS_PER_TOKEN) { + /* llama.cpp -ngl: the bytes stay in host memory and the arithmetic happens there + * too, so a weight read every token is never moved at all. It costs the + * activation crossing at the run boundary, which is why runs are the objective. */ + mu.tier = Tier::HostPageable; + mu.site = Site::Host; + *reason = "host kernel resolved; host run"; + return true; + } + /* Everything below is read by the DEVICE out of host memory, so it must be pinned. */ + mu.tier = Tier::HostPinned; + if (mu.access == RAD_ACCESS_CONDITIONAL) { + /* THE HYBRID TIER. A routed expert that is not resident is NOT copied into + * VRAM and then multiplied: the GEMM's tile names the pinned pool and streams the + * shard over the link as it computes, so the transfer is inside the kernel rather + * than in front of it, and a miss costs one shard rather than a shard plus a + * slab slot plus an eviction. No slot, so it costs no residency either. */ + mu.site = Site::DeviceZeroCopy; + *reason = "pooled expert; streamed over the link"; + } else { + /* Read every token with no host kernel: staging into a slab slot is right, + * because zero-copy would re-stream the same bytes every single step while a + * staged copy pays once and the prefetch schedule hides it. */ + mu.site = Site::DeviceStaged; + *reason = "no host kernel; staged into a slab slot"; + } + return true; + } + /* THE FILE TIER, for a unit that lies in the container as its kernel reads it. + * + * A Tier::SSD unit has NO ADDRESS until something stages it, and the two kinds of unit + * are staged two ways. A SCHEDULED one is `Plan::prefetch` -- an exact schedule built from + * first_use_op, because declare enumerated the whole access sequence. A ROUTED one cannot + * be scheduled: the router picks it on the card, and a grouped MoE GEMM is handed every + * expert's pointer at issue. So the file stager reads ALL of a routed layer's file-tier + * experts into a VRAM buffer before the layer's first expert op, on every pass, routed to + * or not (place/stager.h). Every pointer then exists at issue; what it costs is the whole + * layer's file-tier bytes a pass, which a prefill chunk -- routing to nearly every expert + * of a layer -- reads anyway, and which makes a decode step as slow as the drive. That is + * the trade --weights-disk-tier asks for by name, and the plan sizes the two buffers it + * needs (Plan::file_stage_vram). + * + * Never MOVABLE: the heat engine promotes out of the pinned pool, and a unit with no pool + * slot has nothing to promote from. assign_expert_tiered says so where it sets the bit. */ + if (ssd && mu.file_direct) { + mu.tier = Tier::SSD; + mu.site = Site::DeviceStaged; + *reason = mu.access == RAD_ACCESS_CONDITIONAL + ? "host pool exhausted; read from the container a routed layer at a time" + : "host pool exhausted; file tier"; + return true; + } + return false; + } +}; + +} /* namespace */ + +int Planner::assign_all_vram(Plan* p) { + int64_t used = 0; + for (MoveUnit& mu : p->units) { + /* A MAPPED UNIT IS ALREADY PLACED and no strategy may move it: there is no device kernel + * that could read it anywhere else. Every assignment pass below begins with this line. */ + if (mu.tier == Tier::Mapped) continue; + mu.tier = Tier::VRAM; + mu.site = Site::Device; + mu.movable = false; /* the degenerate case: the mover never runs */ + used += mu.slot_bytes; + } + if (p->vram_budget > 0 && used > p->vram_budget) { + p->notes.push_back(fmt("all_vram needs %s of weights against a --vram-weights-mib " + "budget of %s: %s short", + humanb(used).c_str(), humanb(p->vram_budget).c_str(), + humanb(used - p->vram_budget).c_str())); + return RAD_E_NOMEM; + } + return RAD_OK; +} + +/* LAYER OFFLOAD IS A SCHEDULING PROBLEM, and this is the whole of the decision half: pick which + * layers leave VRAM. The prefetch that follows is exact, because declare enumerated every op with + * its weight operands in order and WeightInfo::first_use_op is that order. + * + * CONTIGUOUS HOST RUNS ARE AN EXPLICIT OBJECTIVE (spec §5.3). A host-site op leaves its activation + * in host memory, so every boundary between a device run and a host run costs a link crossing. A + * few hundred KB is nothing; alternating per layer is 2L of them. llama.cpp gets this free because + * -ngl assigns a contiguous suffix; here the suffix is chosen on purpose, and for a second reason + * as well: the FIRST layers are needed earliest in the step, so a staged prefix has to have landed + * before the step can start at all, while a staged suffix has the whole step's duration to arrive. + * Spilling the tail is the only choice that gives the mover any lead at all. + */ +int Planner::assign_layer_offload(Plan* p) { + for (MoveUnit& mu : p->units) { + if (mu.tier == Tier::Mapped) continue; + mu.tier = Tier::VRAM; mu.site = Site::Device; + } + + int64_t total = 0; + for (const MoveUnit& mu : p->units) total += mu.slot_bytes; + if (p->vram_budget <= 0 || total <= p->vram_budget) return RAD_OK; + + /* Layers in EXECUTION order. The layer index is normally that order already, but the order + * declare produced is the authority -- a plugin is free to declare a tower whose layer + * numbering is not its issue order, and a run computed against the wrong order is not a run. */ + std::vector layers; + std::map bytes_of; + std::map first_of; + for (const MoveUnit& mu : p->units) { + if (mu.layer < 0) continue; + if (!bytes_of.count(mu.layer)) { layers.push_back(mu.layer); first_of[mu.layer] = mu.first_use_op; } + bytes_of[mu.layer] += mu.slot_bytes; + if (mu.first_use_op >= 0 && (first_of[mu.layer] < 0 || mu.first_use_op < first_of[mu.layer])) + first_of[mu.layer] = mu.first_use_op; + } + std::stable_sort(layers.begin(), layers.end(), [&](int32_t a, int32_t b) { + if (first_of[a] != first_of[b]) return first_of[a] < first_of[b]; + return a < b; + }); + + /* RESERVE THE STAGING RING BEFORE CHOOSING THE CUT. A spilled layer with no host kernel is + * staged, and a staged unit needs a slab slot to be staged into -- so a plan that spills + * exactly to the budget and only then discovers it has nowhere to stage is a plan that does + * not load. Deciding this before the cut means asking whether ANY layer lacks a host kernel, + * which over-reserves when the spill happens to land only on host-capable ones. That is the + * right direction to be wrong in. */ + /* AND THE RING IS PER CLASS, NOT ONE RING FOR THE WIDEST CLASS. + * + * The mover allocates a staging ring in EVERY slab class that has one (Mover::init sums + * n_slab + shadow + n_stage per class, and finish() charges (n_shadow + n_stage) * stride per + * class to slab_overhead). A hybrid model has two layer classes -- attention layers and linear + * layers are different strides -- so reserving one ring at the widest stride is short by a + * whole ring, and the plan then reports a fit that the mover refuses for want of VRAM. A plan + * that does not load is worse than one that spills a layer too many, because the second serves. + * + * Summed over the classes that actually carry a layer unit, which is the same set the mover + * builds a slab for. The tail pad is per class too, for the same reason. */ + bool any_stage = ssd_; + std::map stride_of; + for (const MoveUnit& mu : p->units) { + if (mu.layer < 0 || mu.slab_class < 0) continue; + stride_of[mu.slab_class] = p->classes[(size_t)mu.slab_class].stride; + for (rad_weight w : mu.weights) if (!host_ok_[w]) { any_stage = true; break; } + } + int64_t reserve = 0; + if (any_stage) + for (const auto& kv : stride_of) + reserve += (int64_t)RAD_PLACE_STAGE_RING * kv.second + RAD_ALIGN_UNIT; + + int64_t need = total + reserve - p->vram_budget; + /* Walk the tail. `cut` is the first layer, in execution order, that leaves VRAM -- so the + * spilled set is a suffix of the execution order and therefore ONE run by construction. */ + size_t cut = layers.size(); + int64_t freed = 0; + while (cut > 0 && freed < need) { --cut; freed += bytes_of[layers[cut]]; } + if (freed < need) { + p->notes.push_back(fmt("layer_offload cannot fit: every layer spilled frees %s against " + "%s needed; the model-level weights alone exceed the budget", + humanb(freed).c_str(), humanb(need).c_str())); + } + + HostFall fall{0, p->host_budget, ssd_}; + int rc = RAD_OK; + for (size_t i = cut; i < layers.size(); ++i) { + for (MoveUnit& mu : p->units) { + if (mu.layer != layers[i] || mu.tier == Tier::Mapped) continue; + bool host_kernel = true; + for (rad_weight w : mu.weights) if (!host_ok_[w]) { host_kernel = false; break; } + if (!fall.place(mu, host_kernel, &mu.reason)) { + mu.reason = "fits in no tier"; + note_unfit(p, mu, ssd_ ? "neither VRAM nor the host pool has room" + : "the host pool is full and no --weights-disk-tier was given"); + rc = RAD_E_NOMEM; + } + } + } + return rc; +} + +/* EXPERT OFFLOAD IS A PREDICTION PROBLEM, and this is the initial guess. Everything that is not + * conditional is pinned to VRAM first: a PER_TOKEN weight is read on every forward pass, so + * spilling one to buy residency for an expert that MIGHT be routed to is a certain cost against a + * probabilistic saving. The conditional units then take what is left, ranked by the container's + * profile, and the heat engine re-ranks from real routing from the first dispatch onward. + */ +int Planner::assign_expert_tiered(Plan* p) { + int64_t fixed = 0; + for (MoveUnit& mu : p->units) { + if (mu.tier == Tier::Mapped) continue; + mu.tier = Tier::VRAM; + mu.site = Site::Device; + if (mu.access != RAD_ACCESS_CONDITIONAL) fixed += mu.slot_bytes; + } + + if (p->vram_budget > 0 && fixed > p->vram_budget) { + /* The dense part alone does not fit. That is a layer-offload problem wearing an expert + * hat, and answering it here with a second copy of the run-picking logic is how two + * granularities of one mechanism drift apart. Hand it over. */ + RAD_WARN("placement: the non-routed weights alone need %s against a %s weight budget; " + "falling through to layer offload for them", + humanb(fixed).c_str(), humanb(p->vram_budget).c_str()); + RAD_TRY(assign_layer_offload(p)); + fixed = 0; + for (const MoveUnit& mu : p->units) + if (mu.access != RAD_ACCESS_CONDITIONAL && mu.tier == Tier::VRAM) fixed += mu.slot_bytes; + } + + std::vector order; + rank_units(p, &order); + + /* RESERVE THE SPARE SLOTS OUT OF THE BUDGET. The slab has to hold the residents AND the + * shadow slots a promotion writes into, and they all come out of --vram-weights-mib -- so a + * fill that spends the whole budget on residents leaves the mover with nowhere to move into + * and, worse, makes the mover's allocation overrun the pool the operator sized. + * + * Two passes, and the second is enough: the reserve depends only on the first pass's slot + * counts, and the first pass over-counts (it had more room), so the reserve it produces is an + * upper bound. A third pass can only give slots back, never take more. */ + HostFall fall{0, p->host_budget, ssd_}; + int rc = RAD_OK; + + /* ONE FILL: the conditional units in rank order, at most `cap` of them resident and the rest to + * the host pool or the file tier; what it costs the VRAM side comes back -- the residents, the + * shadow slots and the staging ring, and the file stager's two buffers. */ + struct Cost { int64_t used = 0, spare = 0, file = 0, residents = 0; }; + auto fill = [&](int64_t room, int64_t cap) -> Cost { + Cost k; + for (int32_t ui : order) { + MoveUnit& mu = p->units[(size_t)ui]; + if (mu.access != RAD_ACCESS_CONDITIONAL) continue; + mu.tier = Tier::VRAM; + mu.site = Site::Device; + mu.reason = "fits in vram"; + } + for (SlabClass& sc : p->classes) sc.n_shadow = 0; + p->unfit.clear(); + fall = HostFall{0, p->host_budget, ssd_}; + rc = RAD_OK; + + for (int32_t ui : order) { + MoveUnit& mu = p->units[(size_t)ui]; + if (mu.access != RAD_ACCESS_CONDITIONAL) continue; + if (k.residents < cap && k.used + mu.slot_bytes <= room) { + k.used += mu.slot_bytes; + ++k.residents; + mu.tier = Tier::VRAM; + mu.site = Site::Device; + mu.reason = "resident: ranked by the container's profile"; + /* Movable is what the heat engine is allowed to touch. Under + * Config::deterministic this is left false everywhere and the resident set is + * exactly what this loop decided, for the whole run. */ + mu.movable = p->dynamic; + continue; + } + bool host_kernel = true; + for (rad_weight w : mu.weights) if (!host_ok_[w]) { host_kernel = false; break; } + if (!fall.place(mu, host_kernel, &mu.reason)) { + mu.tier = Tier::SSD; + mu.site = Site::DeviceStaged; + mu.reason = "fits in no tier"; + /* With the file tier on, only a unit the container does not hold as its kernel + * reads it gets here -- a relayout, a widening or a shard (HostFall::place). */ + note_unfit(p, mu, ssd_ ? "neither VRAM nor the host pool has room, and its " + "stored form is not the container's (a relayout, a " + "widening or a shard), so the file tier cannot read it " + "in place" + : "the host pool is full and no --weights-disk-tier was " + "given"); + rc = RAD_E_NOMEM; + continue; + } + /* A pooled expert is still MOVABLE: it is exactly what the heat engine promotes. + * Movability is about whether placement may change, not about where it is. A + * file-tier one is not: the mover promotes out of a pool slot and it has none -- the + * file stager reads it a layer at a time instead. */ + mu.movable = p->dynamic && mu.tier != Tier::SSD; + } + + /* How many slots the fill actually used, per class, and therefore how many spares to + * keep. A static plan reserves none: nothing moves, so nothing needs somewhere to move + * into. */ + std::vector resident(p->classes.size(), 0), staged(p->classes.size(), 0); + for (const MoveUnit& mu : p->units) { + if (mu.slab_class < 0) continue; + if (mu.movable && mu.tier == Tier::VRAM) ++resident[(size_t)mu.slab_class]; + /* THE STAGING RING IS A SLAB ALLOCATION TOO, so this reserve has to charge for it. + * finish() sizes it from the units that ended up staged, which is known only after + * the fill -- the same chicken-and-egg the shadow slots have, and solved the same way. + * + * A ring exists only when something falls to the host or file tier, so a model that + * fits entirely in VRAM never exercises this. On one that spills, leaving the ring + * uncharged overruns the weight budget by a few slots, and the mover then refuses the + * statically placed weights on a plan the report called a fit. A ROUTED file-tier + * unit is not counted: the file stager reads it into buffers of its own. */ + if (mu.site == Site::DeviceStaged && mu.access != RAD_ACCESS_CONDITIONAL) + ++staged[(size_t)mu.slab_class]; + } + for (size_t c = 0; c < p->classes.size(); ++c) { + const int64_t ring = std::min(RAD_PLACE_STAGE_RING, staged[c]); + const int64_t shadow = (p->dynamic && resident[c] > 0) + ? std::min(RAD_PLACE_SHADOW_SLOTS, std::max(1, resident[c] / 4)) + : 0; + p->classes[c].n_shadow = shadow; + if (shadow + ring <= 0) continue; + /* Plus the slab's tail padding, which is a real allocation and therefore a real + * charge: a kernel that assembles a packed code window from a wide read legitimately + * reads a few bytes past the last slot's data. Inside the slab that lands in a + * neighbour; at the end it runs off the allocation and faults the card. */ + k.spare += (shadow + ring) * p->classes[c].stride + RAD_ALIGN_UNIT; + } + + /* THE FILE STAGER'S BUFFERS: two, each the largest routed layer's file-tier units at the + * stager's packing, and the same tail pad. */ + std::map layer_bytes; + for (const MoveUnit& mu : p->units) + if (mu.tier == Tier::SSD && mu.access == RAD_ACCESS_CONDITIONAL && mu.layer >= 0) + layer_bytes[mu.layer] += align_up(mu.bytes, RAD_ALIGN_UNIT); + p->file_layer_max = 0; + for (const auto& kv : layer_bytes) p->file_layer_max = std::max(p->file_layer_max, kv.second); + k.file = p->file_layer_max > 0 ? 2 * p->file_layer_max + RAD_ALIGN_UNIT : 0; + p->file_stage_vram = k.file; + return k; + }; + + const int64_t uncapped = INT64_MAX; + const int64_t room0 = p->vram_budget > 0 ? p->vram_budget - fixed : INT64_MAX; + Cost k = fill(room0, uncapped); + if (p->vram_budget > 0) k = fill(room0 - k.spare, uncapped); + + /* THE FILE BUFFERS COME OUT OF THE SAME BUDGET, AND THEY PULL THE OTHER WAY. The two-pass fill + * above made as many residents as fit beside the shadow slots; a routed layer it then put on + * the file tier needs two buffers it never paid for. Each resident given up pays for some of + * them -- and may put one more unit into a layer's file-tier share, growing them again -- so + * the resident count steps down, in rank order, from what the fill made until the residents, + * the shadow slots and the buffers fit together. Rank order spreads residency over the layers + * (rank_units), which is what keeps the largest layer's share -- the buffer -- small. A plan + * with nothing on the file tier never enters the loop. */ + if (p->vram_budget > 0 && k.file > 0) { + int64_t cap = k.residents; + while (fixed + k.used + k.spare + k.file > p->vram_budget && cap > 0) + k = fill(uncapped, --cap); + if (fixed + k.used + k.spare + k.file > p->vram_budget) { + p->notes.push_back(fmt("the file tier's two layer buffers need %s, beside %s of " + "fixed weights, against a --vram-weights-mib budget of %s", + humanb(k.file).c_str(), humanb(fixed).c_str(), + humanb(p->vram_budget).c_str())); + return RAD_E_NOMEM; + } + } + return rc; +} + +void Planner::note_unfit(Plan* p, const MoveUnit& mu, const char* why) const { + const std::string what = mu.weights.empty() + ? std::string("") + : weight_class_key(in_.program->weights[mu.weights.front()].name); + for (Plan::Unfit& u : p->unfit) + if (u.what == what && u.why == why) { ++u.count; u.bytes += mu.bytes; return; } + p->unfit.push_back(Plan::Unfit{what, why, 1, mu.bytes}); +} + +/* ------------------------------------------------------------------ op-level agreement */ +/* WeightInfo carries the site, but an OP runs in exactly one domain. Two weight operands of one + * op that disagree about whether the arithmetic is on the host is not a placement the run phase + * can execute -- a host kernel cannot read a VRAM pointer and a device kernel cannot read a + * pageable one. So the planner reconciles, and it reconciles DOWNWARD: any disagreement collapses + * to the device side, staged, because staging is the site that works from every tier. + * + * It is a repair and it is reported. A plan that needs it is usually a plugin that put a + * per-layer weight in a model-level group, and the note is how that gets noticed. */ +void Planner::enforce_op_site_agreement(const Program& prog, Plan* p) { + for (const OpInfo& o : prog.ops) { + bool any_host = false, any_dev = false; + for (rad_weight w : o.weights) { + if (w == RAD_NULL_HANDLE || w >= p->unit_of_weight.size()) continue; + const int32_t u = p->unit_of_weight[w]; + if (u < 0) continue; + if (p->units[(size_t)u].site == Site::Host) any_host = true; + else any_dev = true; + } + if (!(any_host && any_dev)) continue; + for (rad_weight w : o.weights) { + if (w == RAD_NULL_HANDLE || w >= p->unit_of_weight.size()) continue; + const int32_t u = p->unit_of_weight[w]; + if (u < 0 || p->units[(size_t)u].site != Site::Host) continue; + MoveUnit& mu = p->units[(size_t)u]; + /* EXCEPT A MAPPED ONE, which cannot be demoted: staging works from every tier but + * this one, because no device kernel for the op exists to read the staged copy. The + * op would be unrunnable either way, so the plan says so instead of quietly producing + * a placement that cannot serve. A weight reaches here only if the plugin grouped it + * with a host-only weight or an op reads both kinds -- both are plugin bugs. */ + if (mu.tier == Tier::Mapped) { + p->notes.push_back(fmt("op '%s' reads a weight only a host kernel can read " + "alongside one placed on the device; no site serves both", + o.op.c_str())); + RAD_ERR("placement: op '%s' mixes a mapped weight with a device one. The mapped " + "weight has no device kernel to be staged for.", o.op.c_str()); + continue; + } + mu.site = Site::DeviceStaged; + mu.reason = "op mixes host and device operands; demoted to staged"; + /* A repair, not a misfit, so it does not go in the plan's did-not-fit list -- a plan + * that was repaired still fits, and marking it otherwise would make a caller treat a + * working plan as a failure. It IS visible: the class table shows a `staged` site + * where a `host` one was intended, and this line says which op caused it. */ + RAD_WARN("placement: op '%s' mixes host-site and device-site weight operands; layer " + "%d demoted to staged", o.op.c_str(), (int)mu.layer); + } + } +} + +/* ------------------------------------------------------------------ prefetch */ +/* The exact prefetch schedule. `at_op` is a DEADLINE, not a launch time: declare enumerated the + * whole access sequence, so the planner knows precisely when each staged unit's bytes are needed + * and states that. WHEN to start the transfer is the mover's problem, because it is a question + * about slot supply -- a slot returns to the free list only when its quarantine event signals -- + * and a lead baked in here would be a constant guessing at a queue depth the planner cannot see. + * + * No policy and no predictor: a unit appears here exactly once, at the op that first reads it. */ +void Planner::schedule_prefetch(Plan* p) { + p->prefetch.clear(); + for (int32_t i = 0; i < (int32_t)p->units.size(); ++i) { + const MoveUnit& mu = p->units[(size_t)i]; + if (mu.site != Site::DeviceStaged) continue; + if (mu.access == RAD_ACCESS_CONDITIONAL) continue; /* predicted, not scheduled */ + p->prefetch.push_back(Plan::Prefetch{mu.first_use_op < 0 ? 0 : mu.first_use_op, i}); + } + std::stable_sort(p->prefetch.begin(), p->prefetch.end(), + [](const Plan::Prefetch& a, const Plan::Prefetch& b) { + if (a.at_op != b.at_op) return a.at_op < b.at_op; + return a.unit < b.unit; + }); +} + +/* ------------------------------------------------------------------ finish */ +void Planner::finish(const Program& prog, Plan* p) { + /* Slab slots. Only a MOVABLE unit needs one: a statically resident weight is allocated once + * at a fixed offset and never relocates, so giving it a slot would buy nothing and cost the + * mover a slot it could have used. WeightInfo::slab_slot == -1 means exactly this. */ + std::vector next(p->classes.size(), 0); + std::vector staged(p->classes.size(), 0); + for (MoveUnit& mu : p->units) { + if (mu.movable && mu.tier == Tier::VRAM && mu.slab_class >= 0) { + mu.slab_slot = (int32_t)next[(size_t)mu.slab_class]++; + } else { + mu.slab_slot = -1; + } + /* The ring serves the exact prefetch; a routed file-tier unit is read into the file + * stager's own buffers instead (Plan::file_stage_vram). */ + if (mu.site == Site::DeviceStaged && mu.slab_class >= 0 && + mu.access != RAD_ACCESS_CONDITIONAL) + ++staged[(size_t)mu.slab_class]; + } + for (size_t c = 0; c < p->classes.size(); ++c) { + p->classes[c].n_slots = next[c]; + p->classes[c].movable = next[c] > 0; + /* The staging ring, capped at the number of units that could use it: a class with one + * staged unit does not need two slots to double-buffer a single copy. */ + p->classes[c].n_stage = std::min(RAD_PLACE_STAGE_RING, staged[c]); + /* n_shadow was set by the assignment pass, which is the only place that can reserve it + * out of the budget. Recomputing it here from the resident count would produce a second, + * differing number, and the mover would allocate against one while the operator was + * charged for the other. */ + if (!p->classes[c].movable) p->classes[c].n_shadow = 0; + const int64_t slots = p->classes[c].n_slots + p->classes[c].n_shadow + + p->classes[c].n_stage; + p->slab_overhead += (p->classes[c].n_shadow + p->classes[c].n_stage) * p->classes[c].stride; + if (slots > 0) p->slab_overhead += RAD_ALIGN_UNIT; /* the slab's tail pad */ + } + + /* Host runs, from the final assignment rather than from the intent. One entry is one run. */ + std::vector> host_layers; + for (const MoveUnit& mu : p->units) + if (mu.site == Site::Host && mu.layer >= 0) host_layers.push_back({mu.layer, mu.bytes}); + std::sort(host_layers.begin(), host_layers.end()); + for (size_t i = 0; i < host_layers.size();) { + Plan::HostRun r; + r.first_layer = host_layers[i].first; + r.last_layer = host_layers[i].first; + r.bytes = 0; + while (i < host_layers.size() && + (host_layers[i].first == r.last_layer || host_layers[i].first == r.last_layer + 1)) { + r.last_layer = host_layers[i].first; + r.bytes += host_layers[i].second; + ++i; + } + p->host_runs.push_back(r); + } + /* Two crossings a run: the activation goes to host at the run's first layer and comes back at + * its last. This is the number the contiguity objective exists to hold down, so it is + * computed and printed rather than assumed. */ + p->link_crossings = 2 * (int32_t)p->host_runs.size(); + + /* Push the unit's decision down onto every weight, which is what the rest of the engine + * reads. WeightInfo is frozen and the planner is the component that fills these three. */ + p->weight.assign(prog.weights.size(), Placement{}); + p->totals = Plan::Totals{}; + for (int32_t i = 0; i < (int32_t)p->units.size(); ++i) { + const MoveUnit& mu = p->units[(size_t)i]; + for (rad_weight w : mu.weights) { + Placement& pl = p->weight[w]; + pl.tier = mu.tier; + pl.site = mu.site; + pl.slab_slot = mu.slab_slot; + pl.unit = i; + pl.reason = mu.reason; + pl.bytes = weight_bytes(prog.weights[w]); + p->totals.bytes[(int)mu.tier] += pl.bytes; + } + } +} + +/* ------------------------------------------------------------------ plan */ +int Planner::plan(Plan* out) { + if (!out || !in_.program || !in_.config) return RAD_E_INVAL; + const Program& prog = *in_.program; + const Config& cfg = *in_.config; + + *out = Plan{}; + out->rank = in_.rank; + out->world_size = in_.world_size; + out->dynamic = !cfg.deterministic; + + const Budgets b = Budgets::from(cfg); + out->vram_budget = b.vram_weights; + out->host_budget = b.host_pool; + ssd_ = b.ssd; + + if (strategy_parse(cfg.placement.c_str(), &out->strategy) < 0) { + RAD_ERR("placement: unknown strategy '%s'; expected all_vram, layer_offload, " + "expert_tiered or auto", cfg.placement.c_str()); + return RAD_E_INVAL; + } + + resolve_sites(prog); + build_units(prog, out); + /* BEFORE build_classes and before assign: the mapped tier is not a fallback the budgets + * choose, it is where a weight no device kernel can read has to be. */ + pin_mapped(prog, out); + build_classes(out); + + /* CHARGE THE FILE TIER'S STAGING POOL BEFORE PLACING ANYTHING IN THE HOST POOL. + * + * A unit read from the container lands in a pinned buffer, and those come out of + * --host-pool-mib. Handing HostFall the whole budget lets it fill the pool with pinned units, + * and the mover then asks the exhausted pool for its staging slots and refuses a plan the + * report has just called a fit. Reserving here is the same rule the VRAM side follows for the + * slab ring: the component that budgets an allocation has to budget ALL of it. + * + * Sized off the widest class that carries a LAYER unit, because that is the only kind either + * offload strategy spills -- model-level weights stay put in both. It is an upper bound on + * what the mover will compute from the units that actually land on the file tier, and over- + * reserving costs one spilled layer where under-reserving costs the whole plan. + * + * A model with ROUTED units also gets the read windows a routed layer streams through + * (RAD_PLACE_FILE_WINDOWS), whether or not this plan ends up putting one there: which units + * land on the file tier is decided by the fill below, and that fill spends the host budget + * this line leaves it. */ + if (ssd_) { + int64_t widest = 0; + bool routed = false; + for (const MoveUnit& mu : out->units) { + if (mu.access == RAD_ACCESS_CONDITIONAL && mu.layer >= 0) routed = true; + if (mu.layer < 0 || mu.slab_class < 0) continue; + widest = std::max(widest, out->classes[(size_t)mu.slab_class].stride); + } + const int64_t windows = routed ? (int64_t)RAD_PLACE_FILE_WINDOWS * + RAD_PLACE_FILE_WINDOW_BYTES : 0; + const int64_t need = (int64_t)RAD_PLACE_FILE_STAGE_SLOTS * widest + windows; + if (need > 0) { + if (need >= out->host_budget) { + RAD_ERR("placement: the file tier needs %s of pinned staging (%d slots of %s%s) " + "and --host-pool-mib is %s. Raise it, or drop --weights-disk-tier.", + humanb(need).c_str(), RAD_PLACE_FILE_STAGE_SLOTS, humanb(widest).c_str(), + windows ? fmt(", and %d read windows of %s", RAD_PLACE_FILE_WINDOWS, + humanb(RAD_PLACE_FILE_WINDOW_BYTES).c_str()).c_str() : "", + humanb(out->host_budget).c_str()); + return RAD_E_NOMEM; + } + out->host_budget -= need; + out->file_stage_reserve = need; + out->file_windows = windows; + } + } + + int rc = assign(out); + enforce_op_site_agreement(prog, out); + schedule_prefetch(out); + finish(prog, out); + return rc; +} + +int Planner::assign(Plan* p) { + int64_t total = 0; + bool has_conditional = false; + for (const MoveUnit& mu : p->units) { + total += mu.slot_bytes; + if (mu.access == RAD_ACCESS_CONDITIONAL) has_conditional = true; + } + + Strategy s = p->strategy; + if (s == Strategy::Auto) { + /* `auto` is a choice between three named strategies and nothing more -- it never invents a + * fourth. It fits if it can, prefers spilling routed experts over dense layers when there + * are experts to spill (a conditional weight is read only when selected; a dense one is + * read every token), and offloads layers otherwise. */ + if (p->vram_budget <= 0 || total <= p->vram_budget) s = Strategy::AllVram; + else if (has_conditional) s = Strategy::ExpertTiered; + else s = Strategy::LayerOffload; + p->strategy = s; + RAD_DEBUG("placement: auto chose %s (%s of weights against a %s budget)", + strategy_name(s), humanb(total).c_str(), humanb(p->vram_budget).c_str()); + } + + if (s != Strategy::AllVram && p->vram_budget <= 0) { + /* Every pool is budgeted explicitly (spec §6). An offload strategy with no number to + * spill against would have to infer one from free VRAM, and an engine that quietly + * re-optimises its own split is an engine whose benchmarks do not reproduce. */ + RAD_ERR("placement: %s needs --vram-weights-mib; there is nothing to spill against", + strategy_name(s)); + return RAD_E_INVAL; + } + + switch (s) { + case Strategy::AllVram: return assign_all_vram(p); + case Strategy::LayerOffload: return assign_layer_offload(p); + case Strategy::ExpertTiered: return assign_expert_tiered(p); + default: return RAD_E_INVAL; + } +} + +/* ------------------------------------------------------------------ the report (spec §16) */ +std::string Plan::report(const Program& prog) const { + /* One line per weight CLASS. A model with eleven thousand routed experts has eleven thousand + * weights and three lines worth reading; printing one line each is how a report becomes + * something nobody opens. */ + struct Row { + int64_t n = 0, bytes = 0; + int64_t per_tier[kTierCount] = {0}; + int64_t per_site[4] = {0, 0, 0, 0}; + }; + std::map rows; + std::vector order; + + for (rad_weight w = 1; (size_t)w < prog.weights.size() && (size_t)w < weight.size(); ++w) { + const std::string key = weight_class_key(prog.weights[w].name); + if (!rows.count(key)) order.push_back(key); + Row& r = rows[key]; + ++r.n; + r.bytes += weight[w].bytes; + r.per_tier[(int)weight[w].tier] += 1; + r.per_site[(int)weight[w].site] += 1; + } + + size_t kw = 5; + for (const std::string& k : order) kw = std::max(kw, k.size()); + + std::string s; + s += fmt("placement plan rank %d/%d strategy %s %s\n\n", + rank, world_size, strategy_name(strategy), + dynamic ? "dynamic" : "static (--deterministic)"); + + s += fmt(" %-*s %8s %12s %-34s %s\n", (int)kw, "class", "count", "bytes", "tier", "site"); + for (const std::string& k : order) { + const Row& r = rows[k]; + std::string tiers, sites; + for (int t = 0; t < kTierCount; ++t) + if (r.per_tier[t]) + tiers += fmt("%s%s %lld", tiers.empty() ? "" : " / ", tier_name((Tier)t), + (long long)r.per_tier[t]); + for (int t = 0; t < 4; ++t) + if (r.per_site[t]) + sites += fmt("%s%s %lld", sites.empty() ? "" : " / ", site_name((Site)t), + (long long)r.per_site[t]); + s += fmt(" %-*s %8lld %12s %-34s %s\n", (int)kw, k.c_str(), (long long)r.n, + humanb(r.bytes).c_str(), tiers.c_str(), sites.c_str()); + } + + s += "\n pool budget used\n"; + s += fmt(" vram weights %12s %12s\n", + vram_budget > 0 ? humanb(vram_budget).c_str() : "uncapped", + humanb(totals.bytes[(int)Tier::VRAM]).c_str()); + s += fmt(" host pinned %12s %12s\n", + host_budget > 0 ? humanb(host_budget).c_str() : "none", + humanb(totals.bytes[(int)Tier::HostPinned]).c_str()); + if (totals.bytes[(int)Tier::HostPageable]) + s += fmt(" host pageable %12s %12s\n", "-", + humanb(totals.bytes[(int)Tier::HostPageable]).c_str()); + s += fmt(" ssd tier %12s %12s\n", "unbounded", + humanb(totals.bytes[(int)Tier::SSD]).c_str()); + /* NO BUDGET COLUMN, and the dash is the statement: a mapped weight occupies the container's + * own mapping and no pool at all, so there is nothing for an operator to size. What it does + * cost is page cache, which is the OS's to manage. */ + if (totals.bytes[(int)Tier::Mapped]) + s += fmt(" mapped %12s %12s (the container's mapping; no pool)\n", "-", + humanb(totals.bytes[(int)Tier::Mapped]).c_str()); + /* Taken out of --host-pool-mib before any weight was placed, so the `host pinned` budget above + * is smaller than the flag by exactly this. Printed rather than folded in: an operator who + * raises --host-pool-mib and sees less of it reach the weights than expected is owed the + * reason on the same page. */ + if (file_stage_reserve) + s += fmt(" file staging %12s %12s (%d slots%s, pinned)\n", "-", + humanb(file_stage_reserve).c_str(), RAD_PLACE_FILE_STAGE_SLOTS, + file_windows ? fmt(" and %d read windows", RAD_PLACE_FILE_WINDOWS).c_str() : ""); + /* Out of the VRAM weight budget, beside the residents and not among them: the two buffers a + * routed layer's file-tier experts are read into, each sized to the layer that puts the most + * there. */ + if (file_stage_vram) + s += fmt(" file buffers %12s %12s (two of %s: the most one routed layer reads from " + "the container)\n", "-", humanb(file_stage_vram).c_str(), + humanb(file_layer_max).c_str()); + + if (slab_overhead) + s += fmt(" slab overhead %12s %12s (shadow slots + the staging ring)\n", "-", + humanb(slab_overhead).c_str()); + + bool any_slab = false; + for (const SlabClass& c : classes) if (c.movable || c.n_stage) any_slab = true; + if (any_slab) { + s += "\n slab stride slots shadow stage\n"; + for (const SlabClass& c : classes) { + if (!c.movable && !c.n_stage) continue; + s += fmt(" %-16s %10s %10lld %10lld %10lld\n", c.name.c_str(), + humanb(c.stride).c_str(), (long long)c.n_slots, (long long)c.n_shadow, + (long long)c.n_stage); + } + } + + if (!host_runs.empty()) { + s += fmt("\n host runs: %d run%s, %d link crossing%s a step\n", (int)host_runs.size(), + host_runs.size() == 1 ? "" : "s", link_crossings, + link_crossings == 1 ? "" : "s"); + for (const HostRun& r : host_runs) + s += fmt(" layers %d-%d %s\n", (int)r.first_layer, (int)r.last_layer, + humanb(r.bytes).c_str()); + } + + if (!prefetch.empty()) + s += fmt("\n %d staged unit%s with an exact prefetch deadline; the first is op %d\n", + (int)prefetch.size(), prefetch.size() == 1 ? "" : "s", (int)prefetch[0].at_op); + + if (!notes.empty() || !unfit.empty()) { + s += "\n DID NOT FIT\n"; + for (const std::string& n : notes) s += " " + n + "\n"; + /* Aggregated, so nine hundred stranded experts are one line. The count and the bytes are + * what an operator needs to size the next run; the identity of expert 107 of layer 47 is + * not, and printing it nine hundred times buries the two numbers that are. */ + for (const Unfit& u : unfit) + s += fmt(" %lld x %s (%s): %s\n", (long long)u.count, u.what.c_str(), + humanb(u.bytes).c_str(), u.why.c_str()); + } + return s; +} + +} /* namespace rad */ diff --git a/core/place/planner.h b/core/place/planner.h new file mode 100644 index 00000000..10f2035d --- /dev/null +++ b/core/place/planner.h @@ -0,0 +1,372 @@ +/* planner.h -- the placement planner. Runs ONCE, after declare and before load, and assigns every + * weight a tier and an execution site against explicit pool budgets (spec §5.3). + * + * ---- THE ONE IDEA IN THIS DIRECTORY ------------------------------------------------------------ + * + * All-in-VRAM, layer offload to RAM/SSD, and expert offload to RAM/SSD are ONE MECHANISM AT THREE + * GRANULARITIES. What separates them is not the tiering -- the tiers are the same four -- but + * whether the access is PREDICTABLE, and that distinction is the shape of this code: + * + * LAYER OFFLOAD IS A SCHEDULING PROBLEM. Declare already enumerated every op with its weight + * operands in order, so WeightInfo::first_use_op is the entire future access sequence, known + * statically. The planner emits an exact prefetch schedule off it (Plan::prefetch). No policy, + * no predictor, nothing to be wrong about. + * + * EXPERT OFFLOAD IS A PREDICTION PROBLEM. Routing is data-dependent, so the only thing the + * planner can do is rank an initial residency and hand the rest to heat.h. This is why expert + * offload needs a heat engine and layer offload (llama.cpp's) does not. + * + * ALL-IN-VRAM IS THE DEGENERATE CASE where every weight lands on tier 0 and the mover never + * runs. It is not a separate path; it is this one with a budget that fits. + * + * ---- TIER AND SITE ARE INDEPENDENT AXES (spec §5.1) -------------------------------------------- + * + * Tier is where the bytes live. Site is where the arithmetic happens. All four combinations are + * core behaviour: + * + * VRAM + Device vLLM + * host/SSD + DeviceStaged staged into a slab slot, exact or predicted + * host + DeviceZeroCopy the GEMM streams the weight over the link as it computes; no + * slab slot, so a read-once weight costs no residency at all + * host + Host llama.cpp -ngl + * + * Host-site execution needs a RAD_DOMAIN_HOST kernel. Where declare resolved none, that site is + * UNAVAILABLE for that op, and the planner is told so by reading Band::dom[RAD_DOMAIN_HOST] + * rather than by being passed a flag -- the resolution is the fact. + */ +#pragma once +#include "../rad_core.h" +#include "rad_format.h" + +#include +#include + +namespace rad { + +/* ------------------------------------------------------------------ strategy */ +enum class Strategy { AllVram = 0, LayerOffload = 1, ExpertTiered = 2, Auto = 3 }; + +const char* strategy_name(Strategy s); +/* RAD_E_INVAL and *out untouched if the string is not one of the four. */ +int strategy_parse(const char* s, Strategy* out); + +/* ------------------------------------------------------------------ budgets */ +/* Every pool is budgeted explicitly. No profiling pass, no utilisation fraction, no inference + * about what the workload will be (spec §6). The one thing a zero means is stated here rather + * than guessed at each use: zero vram_weights is "no cap", which is answerable only under + * all_vram -- any offload strategy needs a number to spill against and says so by name. + */ +struct Budgets { + int64_t vram_weights = 0; /* bytes; 0 = uncapped, legal only when everything fits */ + int64_t host_pool = 0; /* bytes; the pinned host tier. 0 = no host tier */ + bool ssd = false; /* --weights-disk-tier was given */ + + static Budgets from(const Config& c); +}; + +/* ------------------------------------------------------------------ the movement unit */ +/* THE UNIT OF PLACEMENT IS A GROUP, NOT A TENSOR. An expert's gate/up/down share one + * RadWeightGroup because a dispatch holding two of the three has nothing it can compute; a + * layer's weights share one because layer offload is a contiguous run rather than a scatter + * (spec §4.1). Everything below -- the slab's fixed stride, the mover's copy, heat's ranking -- + * is per unit, and a weight's placement is its unit's placement. + * + * UNDER TENSOR PARALLEL A UNIT IS THIS RANK'S SHARD OF THE GROUP. The plugin declares dimensions + * already divided (spec §9), so `bytes` is already per-rank and the planner budgets against this + * card. What the planner still owes TP is the harder half, and it is an invariant rather than an + * arithmetic: THE RESIDENT SET MUST BE IDENTICAL ON EVERY RANK. Each rank holds its own half of + * every resident expert, so a slab slot only means the same thing everywhere if every rank + * decided the same experts were in it. That is why the ranking below is keyed on the container's + * profile and the unit's identity and on nothing rank-local -- no free-VRAM query, no timing, no + * device enumeration. The invariant is a property of how the ranking is computed rather than a + * condition checked before placement may run. + */ +struct MoveUnit { + int32_t layer = -1; /* RadWeightGroup::layer; -1 for a model-level weight */ + int32_t expert = -1; /* RadWeightGroup::expert; -1 for a non-expert group */ + int32_t slab_class = -1; /* index into Plan::classes */ + int64_t bytes = 0; /* THIS RANK's shard of the whole group */ + int32_t first_use_op = -1; /* min over the group; the prefetch schedule keys on it */ + int32_t last_use_op = -1; + int access = RAD_ACCESS_PER_TOKEN; /* the group's strongest access class */ + float profile_share = 0.0f; /* the container's popularity profile, or 0 */ + + Tier tier = Tier::VRAM; + Site site = Site::Device; + int32_t slab_slot = -1; + bool movable = false; /* may the heat engine relocate it after load */ + const char* reason = "fits in vram"; /* a fixed string, so the report never guesses */ + + /* The group's INTERNAL LAYOUT, computed once here so the mover never has to. `offset[i]` is + * where weights[i] sits inside the unit, honouring that weight's declared alignment, and + * `bytes` is the padded total. One definition, because the mover's copy size, the pool offset + * it reads and the pointer it publishes must agree and they are written in three places. */ + std::vector weights; + std::vector offset; + + /* WHAT THE UNIT ACTUALLY COSTS A POOL, which is its class's slot stride and not `bytes`. The + * planner budgets against this and the mover allocates this, so the two cannot drift -- and + * the direction they would drift in is an overrun of the pool the operator sized. `bytes` is + * still what the report attributes to the weights, because padding is not a weight. */ + int64_t slot_bytes = 0; + + /* Every weight of it lies in the container exactly as its kernel reads it (weight_file_direct), + * so the file tier can stage it with a read. A unit that is not is never placed there. */ + bool file_direct = true; +}; + +/* The strongest access class in a group decides the group's. Strongest means "read most surely": + * a group holding one PER_TOKEN weight is read on every forward pass whatever the rest of it is, + * and calling it conditional would let the heat engine demote something the next token needs. + * VOCAB ranks with PER_TOKEN -- lm_head and the embedding table are read every token; what makes + * them their own class is their size and the gather, not their certainty (spec §19.2). */ +int access_strength(int access); + +/* ------------------------------------------------------------------ the slab class */ +/* Fixed-stride VRAM slab slots per weight class (spec §5.4). One stride per class, so a slot is + * interchangeable within its class and the mover's bookkeeping is an integer rather than an + * allocator. The stride is the class's largest unit rounded to the movement-unit alignment; the + * padding that costs is the price of never fragmenting, and a fragmenting slab is a slab whose + * hit rate depends on the order promotions happened to arrive in. + */ +struct SlabClass { + std::string name; /* "expert", "layer", "model" plus the byte size */ + int64_t stride = 0; /* bytes per slot, aligned */ + int64_t n_units = 0; /* units of this class in the model */ + int64_t n_slots = 0; /* resident slots the planner bought in VRAM */ + int64_t n_shadow = 0; /* spare slots for in-flight promotions; see mover.h */ + int64_t n_stage = 0; /* the staging ring; see RAD_PLACE_STAGE_RING */ + bool movable = false; +}; + +/* THE STAGING RING. A DeviceStaged unit lives off the device and is copied into a slab slot + * before its op runs, so a class holding staged units needs slots that belong to no unit. Two is + * double buffering -- one slot being read by the op that is running, one landing for the op + * after it -- and it is the minimum depth that overlaps anything at all. + * + * More is better hiding at more VRAM, and where the curve flattens is a measurement rather than a + * principle; it is not a Config field because Config is frozen and this is the honest + * default rather than a tuned one. If it becomes worth tuning it wants a --stage-ring flag beside + * the other explicit budgets in spec §6, NOT a heuristic derived from free VRAM. */ +#define RAD_PLACE_STAGE_RING 2 + +/* THE FILE TIER'S STAGING POOL, IN PINNED HOST SLOTS. A unit read from the container lands in a + * pinned buffer the mover can DMA out of without a bounce (spec §5.4), and those buffers come out + * of --host-pool-mib like everything else on the host side. + * + * It is defined HERE, beside the VRAM ring, because the planner has to charge the operator for it + * and the mover has to allocate exactly what was charged. Were it a mover-side default instead, + * the planner would fill the host pool with pinned units and the mover would then ask the + * exhausted pool for these slots and refuse the plan -- the same shape as the slab overhead on + * the VRAM side, and the same rule: whoever budgets a thing owns its number. */ +#define RAD_PLACE_FILE_STAGE_SLOTS 4 + +/* THE WINDOWS A ROUTED LAYER IS READ THROUGH, when routed experts land on the file tier. A layer's + * file-tier experts are read as long sequential runs of the container -- a few gigabytes a layer + * for a bf16 model -- so the read does not go a unit at a time into the slots above: it fills one + * pinned window while the window before it drains to the card, and the host waits on a window + * only when it comes round again. Four of 32 MiB keep a drive at its sequential rate (a pread of + * this size is ~5 ms at 7 GB/s, the copy out of it under 2) for 128 MiB of pinned memory, charged + * out of --host-pool-mib like the slots. */ +#define RAD_PLACE_FILE_WINDOWS 4 +#define RAD_PLACE_FILE_WINDOW_BYTES ((int64_t)32 << 20) + +/* SHADOW SLOTS: slab slots that are allocated but hold no unit, so a promotion writes into one + * and only then publishes and never DMAs over a slot a kernel might still be reading (mover.h). + * + * THEY COME OUT OF --vram-weights-mib, like everything else in the slab. Taking them from + * whatever VRAM is left over after the slabs is not an option: spec §6 budgets every pool + * explicitly and --gpu-headroom-mib is memory the engine promises NOT to touch. So dynamic + * placement costs a few resident units, and the plan report prints exactly how many. + * + * 32 is far past where the knob stops mattering, and MORE is the wrong end of the problem: extra + * shadows raise the move rate and run SLOWER, because more copies in flight contend with the + * zero-copy tier for the same link. The quarter-of-the-slab cap only ever binds on a slab too + * small for the number to be meaningful. */ +#define RAD_PLACE_SHADOW_SLOTS 32 + +/* ------------------------------------------------------------------ per-weight result */ +struct Placement { + Tier tier = Tier::VRAM; + Site site = Site::Device; + int32_t slab_slot = -1; + int32_t unit = -1; + int64_t bytes = 0; + /* Why this and not VRAM/device, as a fixed string so the report never has to guess. */ + const char* reason = ""; +}; + +/* ------------------------------------------------------------------ the plan */ +class Plan { +public: + int rank = 0, world_size = 1; + Strategy strategy = Strategy::Auto; + + /* False under Config::deterministic. Dynamic placement sets which experts are resident and + * residency sets the summation order, so identical inputs do not give identical outputs + * (spec §17). This is that mode as a real property of the plan -- the heat engine reads it + * and stays off, and the mover reads it and allocates no shadow slots -- rather than a flag + * that is checked nowhere. */ + bool dynamic = true; + + std::vector weight; /* by rad_weight; index 0 is the sentinel */ + std::vector units; + std::vector unit_of_weight; /* by rad_weight; -1 for the sentinel */ + std::vector classes; + + /* Host-site work, in EXECUTION ORDER, as runs. A host-site op leaves its activation in host + * memory, so a host layer between two device layers costs two link crossings; a few hundred + * KB is nothing and alternating per layer is not. llama.cpp gets this free because -ngl + * assigns a contiguous suffix. Here it is an explicit objective, and this vector is the + * evidence: one entry means one run, and `link_crossings` is what the plan costs a step. */ + struct HostRun { int32_t first_layer = 0, last_layer = 0; int64_t bytes = 0; }; + std::vector host_runs; + int32_t link_crossings = 0; + + /* THE EXACT PREFETCH SCHEDULE. Layer offload is a scheduling problem: this is the whole of + * the policy, and it is a sorted list rather than a predictor. `at_op` is the op index by + * which the unit's bytes must have landed, already backed off by the configured lead. */ + struct Prefetch { int32_t at_op = 0; int32_t unit = 0; }; + std::vector prefetch; + + struct Totals { int64_t bytes[kTierCount] = {0}; }; /* indexed by Tier */ + Totals totals; + /* `host_budget` is what is left for WEIGHTS after the file tier's staging pool is taken out of + * --host-pool-mib, so the number the placement passes spend against is the number they may + * actually have. `file_stage_reserve` is what was taken, reported so the operator can see + * where the difference went: the unit slots, plus the read windows when a routed expert can + * land on the file tier. */ + int64_t vram_budget = 0, host_budget = 0; + int64_t file_stage_reserve = 0; + int64_t file_windows = 0; /* the read windows' part of it */ + /* ROUTED EXPERTS ON THE FILE TIER have no address of their own: a routed layer's are read into + * one of two VRAM buffers before the layer's first expert op and published there until the next + * routed layer starts (place/stager.h, FileStager). `file_layer_max` is the most one layer's + * file-tier units take in a buffer, each at its own size rounded to RAD_ALIGN_UNIT, which is + * how the stager packs them; `file_stage_vram` is the two buffers, taken out of + * --vram-weights-mib before any expert is made resident. Both 0 when nothing routed is on the + * file tier. */ + int64_t file_layer_max = 0; + int64_t file_stage_vram = 0; + /* VRAM the slab holds that no weight occupies: the shadow slots and the staging ring. It is + * reported rather than folded into the tier total because it is the price of dynamic + * placement and of offload respectively, and an operator comparing two runs needs to see + * which of the two changed. */ + int64_t slab_overhead = 0; + + /* What did not fit. Two lists because there are two kinds of failure and they read + * differently: `notes` is a whole-plan statement ("the budget is 3 GiB short"), and `unfit` + * is per unit -- aggregated by class and reason, because a plan that strands nine hundred + * experts must print one line about it and not nine hundred (spec §16). */ + std::vector notes; + struct Unfit { + std::string what; /* the weight class key */ + std::string why; + int64_t count = 0; + int64_t bytes = 0; + }; + std::vector unfit; + bool fits() const { return notes.empty() && unfit.empty(); } + + const MoveUnit* unit_for(rad_weight w) const { + if (w >= unit_of_weight.size() || unit_of_weight[w] < 0) return nullptr; + return &units[(size_t)unit_of_weight[w]]; + } + + /* THE PLACEMENT PLAN REPORT (spec §16): every weight's tier and site, the pool totals, and + * what did not fit. One line per weight CLASS rather than per weight, because a model with + * eleven thousand experts has eleven thousand weights and three interesting lines. */ + std::string report(const Program& p) const; +}; + +/* ------------------------------------------------------------------ the planner */ +struct PlannerInput { + const Program* program = nullptr; + const Config* config = nullptr; + int rank = 0; + int world_size = 1; + + /* The container's expert-popularity profile, derived from the imatrix's activation counts. + * Null is fine and costs about a point of hit rate. See Planner::rank_units. */ + const RadFileProfile* profile = nullptr; + int64_t n_profile = 0; + /* The weights are in a container, which the file and mapped tiers read in place. A checkpoint + * served directly is neither grouped by movement unit nor aligned for O_DIRECT, so with this + * false no unit is file-direct and both tiers are closed (spec §4.3). */ + bool container = true; +}; + +class Planner { +public: + explicit Planner(const PlannerInput& in) : in_(in) {} + + /* Runs the whole plan. Returns RAD_OK, or a negative status with `out` still filled in far + * enough to print -- a plan that does not fit is a plan the operator has to read. */ + int plan(Plan* out); + +private: + const PlannerInput& in_; + + /* Per-weight facts derived from declare, indexed by rad_weight. */ + std::vector host_ok_; /* every op reading it resolved a RAD_DOMAIN_HOST kernel */ + std::vector device_ok_; /* ...and a RAD_DOMAIN_DEVICE one. Cleared means the weight + * can ONLY be read on the host, which is a decision and + * not a preference -- see pin_mapped. */ + bool ssd_ = false; /* --weights-disk-tier was given */ + + void resolve_sites(const Program& prog); + void build_units(const Program& prog, Plan* p); + void pin_mapped(const Program& prog, Plan* p); + void build_classes(Plan* p); + void rank_units(Plan* p, std::vector* order) const; + int assign(Plan* p); + int assign_all_vram(Plan* p); + int assign_layer_offload(Plan* p); + int assign_expert_tiered(Plan* p); + void enforce_op_site_agreement(const Program& prog, Plan* p); + void schedule_prefetch(Plan* p); + void finish(const Program& prog, Plan* p); + /* Fold one stranded unit into the aggregated list. Found-or-appended by (class, reason), so + * the cost of reporting nine hundred stranded experts is one line and one counter. */ + void note_unfit(Plan* p, const MoveUnit& mu, const char* why) const; +}; + +/* Bytes of a declared weight as THIS RANK will hold them: the stored size once the layout pass + * has run, the logical size before it. Exposed because the mover and the report both need the + * same answer and two spellings of it is how two components disagree about a budget. */ +int64_t weight_bytes(const WeightInfo& w); + +/* ------------------------------------------------------------------ what the weights would cost + * + * ONE RANK'S DECLARED WEIGHTS, SPLIT INTO THE PART THAT IS NOT NEGOTIABLE AND THE PART THAT IS. + * + * The VRAM budget needs this BEFORE the planner runs, because the two questions are asked in that + * order: how much room is there, and only then what goes in it. And the split matters more than + * the total. A model's static weights -- everything that is not an expert -- have to be resident + * for the model to run at a sensible speed at all, so they come off the top; the expert plane is + * the only thing that trades against the KV cache, and it is what --expert-vs-cache-ratio divides. + * Applying a ratio to the two together would let a 0.3 setting demote the attention projections to + * host memory to make room for a cache nothing will fill. + * + * The three answers are per RANK, and under tensor parallel that is already the even split across + * devices: declare runs once per rank with every dimension ALREADY DIVIDED (spec §9), so summing + * this rank's declared weights is summing its shard. + * + * IT MUST AGREE WITH THE PLANNER AND THAT IS WHY IT LIVES HERE. The unit grouping, the alignment + * accumulation and the mapped-tier rule are Planner::build_units', Planner::resolve_sites' and + * Planner::pin_mapped's respectively; a second copy of any of them somewhere else would drift and + * the failure would be a budget that overcommits the card by exactly the difference. */ +struct WeightFootprint { + int64_t statics = 0; /* non-expert and device-readable -- the floor under any budget */ + int64_t experts = 0; /* the elastic plane: what streams from host when it does not fit */ + int64_t expert_layer_max = 0; /* the most expert bytes any one routed layer holds */ + int64_t mapped = 0; /* no device kernel can read them; they never enter a pool at all */ + int64_t n_units = 0; +}; +void weight_footprint(const Program& prog, WeightFootprint* out); + +/* "blk.12.ffn_gate_exps.3.weight" -> "blk.*.ffn_gate_exps.*.weight". The report's grouping key: + * one line per weight class rather than per weight (spec §16). */ +std::string weight_class_key(const std::string& name); + +} /* namespace rad */ diff --git a/core/place/residency_iface.h b/core/place/residency_iface.h new file mode 100644 index 00000000..998ea1e2 --- /dev/null +++ b/core/place/residency_iface.h @@ -0,0 +1,14 @@ +/* residency_iface.h -- THE SEAM between placement and the run phase. + * + * core/runtime/ owns the declaration and this file only forwards to it. Placement does not keep a + * copy: two declarations of a struct that crosses a component boundary is an ODR violation waiting + * for the first translation unit that includes both, and the symptom would be a WeightSlot whose + * fields the two components disagree about. + * + * The contract itself is documented where it is declared. Read core/runtime/residency.h -- in + * particular the rule that begin_transfer and publish are the ONLY writers and that BOTH must bump + * the generation, because the run phase memoises the stream wait per generation and installing a + * new event at the old generation makes it skip the wait entirely. + */ +#pragma once +#include "runtime/residency.h" diff --git a/core/place/stager.cpp b/core/place/stager.cpp new file mode 100644 index 00000000..2d44e40e --- /dev/null +++ b/core/place/stager.cpp @@ -0,0 +1,345 @@ +/* stager.cpp -- see stager.h. */ +#include "place/stager.h" + +#include + +namespace rad { + +PrefillStager::~PrefillStager() { + for (int b = 0; b < 2; ++b) { + if (done_[b]) rad_event_destroy(done_[b]); + if (free_[b]) rad_event_destroy(free_[b]); + } +} + +int PrefillStager::init(const Program& prog, const Plan& plan, Mover* mover, char* region, + int64_t bytes, int64_t min_rows) { + layers_.clear(); + if (!mover || !region || bytes <= 0) return RAD_OK; + + /* A ROUTED LAYER IS ITS EXPERT UNITS, and the ops that read it are the span their declared + * uses cover: the first is the one that must find the copies, the last the one after which + * nothing reads them again -- once the block's last pass of rows has issued it (after_op). */ + std::map by_layer; + for (size_t u = 0; u < plan.units.size(); ++u) { + const MoveUnit& mu = plan.units[u]; + if (mu.expert < 0 || mu.layer < 0 || mu.first_use_op < 0 || mu.last_use_op < 0) continue; + Layer& L = by_layer[mu.layer]; + L.layer = mu.layer; + L.units.push_back((int32_t)u); + L.first_op = L.first_op < 0 ? mu.first_use_op : std::min(L.first_op, mu.first_use_op); + L.last_op = std::max(L.last_op, mu.last_use_op); + } + for (auto& kv : by_layer) layers_.push_back(std::move(kv.second)); + std::sort(layers_.begin(), layers_.end(), + [](const Layer& a, const Layer& b) { return a.first_op < b.first_op; }); + /* Two layers' spans must not overlap: a layer's copies are released at its last op, and the + * next layer's buffer is the one the layer before it released. */ + for (size_t i = 1; i < layers_.size(); ++i) + if (layers_[i].first_op <= layers_[i - 1].last_op) { + RAD_WARN("prefill staging: routed layers %d and %d are read by interleaved ops (%d..%d " + "and %d..%d); staging is off", layers_[i - 1].layer, layers_[i].layer, + layers_[i - 1].first_op, layers_[i - 1].last_op, layers_[i].first_op, + layers_[i].last_op); + layers_.clear(); + return RAD_OK; + } + if (layers_.empty()) return RAD_OK; + + first_of_.assign(prog.ops.size(), -1); + last_of_.assign(prog.ops.size(), -1); + for (size_t i = 0; i < layers_.size(); ++i) { + if ((size_t)layers_[i].first_op < first_of_.size()) first_of_[(size_t)layers_[i].first_op] = (int32_t)i; + if ((size_t)layers_[i].last_op < last_of_.size()) last_of_[(size_t)layers_[i].last_op] = (int32_t)i; + } + + mover_ = mover; + cap_ = bytes / 2 / RAD_ALIGN_UNIT * RAD_ALIGN_UNIT; + buf_[0] = region; + buf_[1] = region + cap_; + min_rows_ = min_rows; + for (int b = 0; b < 2; ++b) { + if (rad_event_create_local(&done_[b]) < 0 || rad_event_create_local(&free_[b]) < 0) { + layers_.clear(); + return RAD_E_DEVICE; + } + } + started_.assign(layers_.size(), 0); + return RAD_OK; +} + +bool PrefillStager::begin_pass(const RadBatch* b) { + armed_ = full_ && enabled() && b && b->n_tok >= min_rows_; + if (!armed_) return false; + std::fill(started_.begin(), started_.end(), (uint8_t)0); + holds_[0] = holds_[1] = -1; + first_op_ = true; + pass_kind_ = b->draft_pass; + last_issued_ = -1; + return true; +} + +bool PrefillStager::will_issue(int32_t li) const { + const auto it = pass_last_.find(pass_kind_); + return it == pass_last_.end() || layers_[(size_t)li].first_op <= it->second; +} + +int PrefillStager::start(int32_t li) { + started_[(size_t)li] = 1; + const int b = li & 1; + if (holds_[b] >= 0) return RAD_OK; /* the layer before still holds it: stream this one */ + const int rc = mover_->stage_units(layers_[(size_t)li].units, buf_[b], cap_, + free_rec_[b] ? free_[b] : nullptr, done_[b], &staged_[b]); + if (rc < 0) return rc; + if (!staged_[b].empty()) { holds_[b] = li; read_[b] = false; } + return RAD_OK; +} + +/* The host half of letting a buffer go: its units are published at their pool slots again, which + * the next residency sync hands to the weight tables. The device half is `free_`. */ +void PrefillStager::release(int32_t b) { + mover_->unstage_units(staged_[b]); + staged_[b].clear(); + holds_[b] = -1; + read_[b] = false; +} + +int PrefillStager::finish(int32_t b, RadStream s) { + RAD_TRY(rad_event_record(free_[b], s)); + free_rec_[b] = true; + release(b); + return RAD_OK; +} + +int PrefillStager::before_op(rad_op h, RadStream s, bool* resync) { + *resync = false; + if ((int32_t)h > last_issued_) last_issued_ = (int32_t)h; + + /* THE PASS'S FIRST ROUTED LAYER, staged at its first op of any kind, so the copy runs behind + * whatever the pass issues before the layer. */ + if (first_op_) { + first_op_ = false; + const auto it = std::lower_bound(layers_.begin(), layers_.end(), (int32_t)h, + [](const Layer& L, int32_t op) { return L.first_op < op; }); + if (it != layers_.end()) { + const int32_t li = (int32_t)(it - layers_.begin()); + if (!started_[(size_t)li] && will_issue(li)) { + RAD_TRY(start(li)); + *resync = true; + } + } + } + + if ((size_t)h >= first_of_.size()) return RAD_OK; + const int32_t li = first_of_[(size_t)h]; + if (li < 0) return RAD_OK; + /* This layer's copies were published a layer ago: the one wait that orders its ops behind + * them. */ + for (int b = 0; b < 2; ++b) + if (holds_[b] == li) RAD_TRY(rad_event_wait(s, done_[b])); + /* The layer before is done with its buffer: every pass of rows issued its last op, the last + * of them recorded `free_`, and a layer's ops do not interleave with the next one's. Released + * here and not at that op, whose next run would read copies already overwritten. */ + for (int b = 0; b < 2; ++b) + if (holds_[b] >= 0 && holds_[b] != li && read_[b]) release(b); + /* And the next layer's copies go out now, behind it. */ + const int32_t next = li + 1; + if ((size_t)next < layers_.size() && !started_[(size_t)next] && will_issue(next)) { + RAD_TRY(start(next)); + *resync = true; + } + return RAD_OK; +} + +/* THE LAYER'S LAST OP: `free_` goes behind it, so the copies two layers on can start as early as + * they could before -- and goes behind it again if the block issues the op for another pass of + * rows, which is why the copies themselves are not released until the next layer starts. */ +int PrefillStager::after_op(rad_op h, RadStream s) { + if ((size_t)h >= last_of_.size()) return RAD_OK; + const int32_t li = last_of_[(size_t)h]; + if (li < 0) return RAD_OK; + for (int b = 0; b < 2; ++b) + if (holds_[b] == li) { + RAD_TRY(rad_event_record(free_[b], s)); + free_rec_[b] = true; + read_[b] = true; + } + return RAD_OK; +} + +int PrefillStager::end_pass(RadStream s) { + if (!armed_) return RAD_OK; + armed_ = false; + pass_last_[pass_kind_] = last_issued_; + int rc = RAD_OK; + for (int b = 0; b < 2; ++b) + if (holds_[b] >= 0) { + const int r = finish(b, s); + if (r < 0 && rc >= 0) rc = r; + } + return rc; +} + +/* ================================================================== the file stager */ +FileStager::~FileStager() { + for (int b = 0; b < 2; ++b) { + if (done_[b]) rad_event_destroy(done_[b]); + if (free_[b]) rad_event_destroy(free_[b]); + } +} + +int FileStager::init(const Program& prog, const Plan& plan, Mover* mover) { + layers_.clear(); + if (!mover) return RAD_OK; + + std::map by_layer; + for (size_t u = 0; u < plan.units.size(); ++u) { + const MoveUnit& mu = plan.units[u]; + if (mu.tier != Tier::SSD || mu.access != RAD_ACCESS_CONDITIONAL || mu.layer < 0) continue; + if (mu.first_use_op < 0 || mu.last_use_op < 0) continue; /* declared and never read */ + Layer& L = by_layer[mu.layer]; + L.layer = mu.layer; + L.units.push_back((int32_t)u); + L.first_op = L.first_op < 0 ? mu.first_use_op : std::min(L.first_op, mu.first_use_op); + L.last_op = std::max(L.last_op, mu.last_use_op); + } + for (auto& kv : by_layer) layers_.push_back(std::move(kv.second)); + if (layers_.empty()) return RAD_OK; + std::sort(layers_.begin(), layers_.end(), + [](const Layer& a, const Layer& b) { return a.first_op < b.first_op; }); + /* A layer's copies stay published until the next one starts, so two layers whose ops + * interleave would need both buffers at once and a third for the read ahead. That is a plugin + * shape this tier cannot serve, and a file-tier unit has no address to fall back on. */ + for (size_t i = 1; i < layers_.size(); ++i) + if (layers_[i].first_op <= layers_[i - 1].last_op) { + RAD_ERR("file stager: routed layers %d and %d are read by interleaved ops (%d..%d and " + "%d..%d), and a routed layer read from the container is published one layer " + "at a time", layers_[i - 1].layer, layers_[i].layer, layers_[i - 1].first_op, + layers_[i - 1].last_op, layers_[i].first_op, layers_[i].last_op); + layers_.clear(); + return RAD_E_UNSUPPORTED; + } + + buf_[0] = mover->file_buffer(0); + buf_[1] = mover->file_buffer(1); + cap_ = mover->file_buffer_bytes(); + if (!buf_[0] || !buf_[1] || cap_ < plan.file_layer_max) { + RAD_ERR("file stager: the plan reads %zu routed layers from the container and the mover " + "holds no buffers for them", layers_.size()); + layers_.clear(); + return RAD_E_STATE; + } + first_of_.assign(prog.ops.size(), -1); + for (size_t i = 0; i < layers_.size(); ++i) + if ((size_t)layers_[i].first_op < first_of_.size()) + first_of_[(size_t)layers_[i].first_op] = (int32_t)i; + mover_ = mover; + for (int b = 0; b < 2; ++b) + if (rad_event_create_local(&done_[b]) < 0 || rad_event_create_local(&free_[b]) < 0) { + layers_.clear(); + return RAD_E_DEVICE; + } + return RAD_OK; +} + +/* EVERY PASS: there is no other address for a file-tier unit, so a pass the stager sat out would + * reach its first routed layer with null expert pointers. */ +bool FileStager::begin_pass(const RadBatch* b) { + armed_ = enabled() && b; + if (!armed_) return false; + holds_[0] = holds_[1] = -1; + cur_ = -1; + first_op_ = true; + pass_kind_ = b->draft_pass; + last_issued_ = -1; + return true; +} + +bool FileStager::will_issue(int32_t li) const { + const auto it = pass_last_.find(pass_kind_); + return it == pass_last_.end() || layers_[(size_t)li].first_op <= it->second; +} + +int FileStager::start(int32_t li) { + const int b = li & 1; + if (holds_[b] >= 0) return RAD_E_STATE; /* released before the next read, by construction */ + const int rc = mover_->stage_file_units(layers_[(size_t)li].units, buf_[b], cap_, + free_rec_[b] ? free_[b] : nullptr, done_[b], + &staged_[b]); + if (rc < 0) return rc; + if (!staged_[b].empty()) holds_[b] = li; + return RAD_OK; +} + +int FileStager::finish(int32_t b, RadStream s) { + RAD_TRY(rad_event_record(free_[b], s)); + free_rec_[b] = true; + mover_->unstage_units(staged_[b]); + staged_[b].clear(); + holds_[b] = -1; + return RAD_OK; +} + +int FileStager::before_op(rad_op h, RadStream s, bool* resync) { + *resync = false; + if ((int32_t)h > last_issued_) last_issued_ = (int32_t)h; + + /* THE PASS'S FIRST ROUTED LAYER, read at its first op of any kind. */ + if (first_op_) { + first_op_ = false; + const auto it = std::lower_bound(layers_.begin(), layers_.end(), (int32_t)h, + [](const Layer& L, int32_t op) { return L.first_op < op; }); + if (it != layers_.end()) { + const int32_t li = (int32_t)(it - layers_.begin()); + if (will_issue(li)) { + RAD_TRY(start(li)); + *resync = true; + } + } + } + + if ((size_t)h >= first_of_.size()) return RAD_OK; + const int32_t li = first_of_[(size_t)h]; + if (li < 0 || li == cur_) return RAD_OK; + + /* Entering layer `li`: the layer before is behind every op issued so far on this stream. */ + for (int b = 0; b < 2; ++b) + if (holds_[b] >= 0 && holds_[b] != li) { RAD_TRY(finish(b, s)); *resync = true; } + /* A layer the read-ahead skipped -- the learned bound said this pass ends before it -- is read + * here rather than issued without addresses. */ + if (holds_[li & 1] != li) { + RAD_TRY(start(li)); + *resync = true; + } + if (holds_[li & 1] == li) RAD_TRY(rad_event_wait(s, done_[li & 1])); + cur_ = li; + + const int32_t next = li + 1; + if ((size_t)next < layers_.size() && will_issue(next)) { + RAD_TRY(start(next)); + *resync = true; + } + return RAD_OK; +} + +int FileStager::after_op(rad_op h, RadStream s) { + (void)h; + (void)s; + return RAD_OK; +} + +int FileStager::end_pass(RadStream s) { + if (!armed_) return RAD_OK; + armed_ = false; + pass_last_[pass_kind_] = last_issued_; + int rc = RAD_OK; + for (int b = 0; b < 2; ++b) + if (holds_[b] >= 0) { + const int r = finish(b, s); + if (r < 0 && rc >= 0) rc = r; + } + cur_ = -1; + return rc; +} + +} /* namespace rad */ diff --git a/core/place/stager.h b/core/place/stager.h new file mode 100644 index 00000000..622a911d --- /dev/null +++ b/core/place/stager.h @@ -0,0 +1,197 @@ +/* stager.h -- the prefill stager: a routed layer's non-resident experts copied onto the card one + * layer ahead of the layer that reads them. + * + * ---- WHY A PREFILL NEEDS IT ------------------------------------------------------------------- + * + * An expert the slab has no room for lives in the pinned host pool, and a GEMM that routes to it + * reads it across the link in place (Site::DeviceZeroCopy). At decode that is the right trade: a + * step routes a few dozen rows to a few dozen experts and reads a few of them from the host. A + * prefill chunk routes tens of thousands of rows to nearly EVERY expert of every layer, so the + * whole pooled part of each layer -- ~85 MB a card on Qwen3.8-Flash-Next -- crosses the link inside + * the layer's two GEMMs, at the link's rate and on the critical path, while the rest of the layer's + * work leaves the link idle. Measured with r4d_selftest --perfmoe, the gate_up GEMM of a 2048-token + * chunk is 1.53 ms with every expert on the card and 4.34 ms with the coldest 13% in host memory. + * + * So at a step large enough, the stager copies layer L+1's pooled experts into a VRAM buffer while + * layer L runs, publishes the copies for layer L+1's ops, and publishes the host addresses again + * once those ops are behind it. The copy is the same bytes the GEMM would have read, so the output + * is bit-identical; only when the link carries them moves. + * + * ---- WHERE THE BUFFERS ARE, AND WHEN THEY ARE ITS --------------------------------------------- + * + * Two buffers, each one layer's share of the experts the budget leaves off the card, at the top of + * the activation arena (Program::arena_stage_off, sized by vram_budget_resolve). A step smaller + * than the arena's full plan LENDS that top to the expert slab, so the buffers are the stager's + * only in a step at the full plan -- which is exactly the steps worth staging for -- and the rest of + * the time they hold resident experts like any other lent slot. The scheduler says which it is, + * pass by pass (set_full_arena). + * + * ---- THE ORDER, AND WHAT KEEPS IT SAFE --------------------------------------------------------- + * + * the pass's first op stage the first routed layer the pass issues, into buffer 0 or 1 + * a layer's first op stage the NEXT layer into the other buffer; re-read the residency + * table so this layer's ops resolve the copies made one layer ago + * a layer's last op record "buffer free" on the op's stream; publish the host addresses + * the pass's end the same for anything still staged: nothing outlives its pass + * + * A copy into a buffer waits on that buffer's "free" event, recorded behind the last op that read + * the layer it held -- in this pass or an earlier one. The layer's ops wait on the copies' event + * through ONE stream wait, issued before the layer's first op: the copies are published settled + * (Mover::stage_units says why), and nothing but the layer's own ops ever resolves them. + * + * A LAYER IS STAGED AHEAD ONLY WHEN THE PASS WILL ISSUE IT. A step issues its routed layers across + * more than one pass -- the trunk in one, the MTP head's in the next -- and the last layer a trunk + * pass stages ahead would otherwise be the head's, copied for a pass that never reads it and thrown + * away at its end. The stager learns the last op each kind of pass issues (by draft_pass) and stages + * a layer ahead only when its first op is at or below it. + */ +#pragma once +#include "../runtime/stager.h" +#include "mover.h" +#include "planner.h" + +#include +#include + +namespace rad { + +class PrefillStager final : public OpStager { +public: + ~PrefillStager() override; + + /* The routed layers of `plan` and the ops that read them, and `bytes` of device memory at + * `region` as two buffers. `min_rows` is the smallest pass it arms for. Leaves it disabled -- + * enabled() false -- when the plan has no routed layer with a pooled unit to stage. */ + int init(const Program& prog, const Plan& plan, Mover* mover, char* region, int64_t bytes, + int64_t min_rows); + + /* Per pass, before it is released: whether the step runs at the arena's full plan, which is + * when the buffers are not lent. */ + void set_full_arena(bool full) { full_ = full; } + + bool enabled() const { return !layers_.empty(); } + int64_t buffer_bytes() const { return cap_; } + size_t n_layers() const { return layers_.size(); } + + bool begin_pass(const RadBatch* b) override; + int before_op(rad_op h, RadStream s, bool* resync) override; + int after_op(rad_op h, RadStream s) override; + int end_pass(RadStream s) override; + +private: + struct Layer { + int32_t layer = -1; + std::vector units; + int32_t first_op = -1, last_op = -1; + }; + std::vector layers_; /* the routed layers, in first-op order */ + std::vector first_of_; /* by op: the layer whose first op it is, or -1 */ + std::vector last_of_; /* by op: the layer whose last op it is, or -1 */ + + Mover* mover_ = nullptr; + char* buf_[2] = { nullptr, nullptr }; + int64_t cap_ = 0; + int64_t min_rows_ = 0; + RadEvent done_[2] = { nullptr, nullptr }; /* behind a buffer's copies, on the mover stream */ + RadEvent free_[2] = { nullptr, nullptr }; /* behind a buffer's last reader */ + bool free_rec_[2] = { false, false }; + std::vector staged_[2]; + int32_t holds_[2] = { -1, -1 }; /* the layer a buffer holds, or -1 */ + /* The holder's last op has been issued at least once, and `free_` is recorded behind it. A + * step longer than the MoE block's pass of rows issues a layer's ops once per pass, so the + * last op can run again: the copies are released at the NEXT layer's first op, which is past + * every pass, while each run of the last op moves `free_` behind itself. */ + bool read_[2] = { false, false }; + + bool full_ = false; + bool armed_ = false; + bool first_op_ = false; /* the pass has issued nothing yet */ + std::vector started_; /* by layer: staged (or tried) this pass */ + int32_t pass_kind_ = 0; + int32_t last_issued_ = -1; + std::map pass_last_; /* by draft_pass: the last op such a pass issued */ + + bool will_issue(int32_t li) const; + int start(int32_t li); + int finish(int32_t b, RadStream s); + void release(int32_t b); +}; + +/* ---- THE FILE STAGER: routed layers read from the container ------------------------------------- + * + * A routed unit the plan put on the file tier (--weights-disk-tier) has no address of its own, and + * a grouped GEMM is handed every expert's pointer at issue. So on EVERY pass -- a decode step as + * much as a prefill chunk -- each routed layer's file-tier units are read into one of the mover's + * two file buffers before the layer's first expert op and published there, and published as null + * again when the next routed layer starts. Which experts the router picks cannot be known on the + * host without a round trip, so the whole layer's file-tier part is read; a prefill chunk routes to + * nearly all of it anyway, and a decode step is paced by the drive -- the trade the flag names. + * + * the pass's first op read the first routed layer the pass issues + * a layer's first op release the layer before (record its buffer free on the stream, publish + * null), wait on this layer's copies, and read the NEXT layer into the + * buffer just released -- its copies queue behind that free event + * the pass's end release whatever is still held + * + * A LAYER IS RELEASED WHEN THE NEXT ONE STARTS, not at its own last op: a routed block that slices a + * large step into passes of `rows` tokens issues its expert ops once a slice, so the last declared + * op of the layer comes round again, and a release there would leave the second slice reading null. + * Repeats of the current layer's first op do nothing. + * + * THE READ IS ON THE ISSUING THREAD and blocks it; the card meanwhile runs whatever was issued + * before it. A routed layer's file-tier part is gigabytes and its compute milliseconds, so the step + * is the drive's either way, and a reader thread would buy the few percent the layer's own compute + * is worth at the cost of a second writer of the residency table. + * + * A layer is read ahead only when the pass will issue it -- the same learned bound PrefillStager + * keeps (by draft_pass), so a trunk pass does not read the MTP head's layer for nothing. */ +class FileStager final : public OpStager { +public: + ~FileStager() override; + + /* The routed layers of `plan` that hold a unit on the file tier and the ops that read them, + * over the mover's two file buffers. Leaves it disabled -- enabled() false -- when the plan + * puts no routed unit there; refuses a plan whose routed layers are read by interleaved ops, + * because a file-tier unit has no other address to fall back on. */ + int init(const Program& prog, const Plan& plan, Mover* mover); + + bool enabled() const { return !layers_.empty(); } + size_t n_layers() const { return layers_.size(); } + int64_t buffer_bytes() const { return cap_; } + + bool begin_pass(const RadBatch* b) override; + int before_op(rad_op h, RadStream s, bool* resync) override; + int after_op(rad_op h, RadStream s) override; + int end_pass(RadStream s) override; + +private: + struct Layer { + int32_t layer = -1; + std::vector units; + int32_t first_op = -1, last_op = -1; + }; + std::vector layers_; /* the routed layers with file-tier units, in first-op order */ + std::vector first_of_; /* by op: the layer whose first op it is, or -1 */ + + Mover* mover_ = nullptr; + char* buf_[2] = { nullptr, nullptr }; + int64_t cap_ = 0; + RadEvent done_[2] = { nullptr, nullptr }; /* behind a buffer's copies, on the mover stream */ + RadEvent free_[2] = { nullptr, nullptr }; /* behind the ops that read a buffer's layer */ + bool free_rec_[2] = { false, false }; + std::vector staged_[2]; + int32_t holds_[2] = { -1, -1 }; /* the layer a buffer holds, or -1 */ + int32_t cur_ = -1; /* the layer whose ops are being issued */ + + bool armed_ = false; + bool first_op_ = false; + int32_t pass_kind_ = 0; + int32_t last_issued_ = -1; + std::map pass_last_; + + bool will_issue(int32_t li) const; + int start(int32_t li); + int finish(int32_t b, RadStream s); +}; + +} /* namespace rad */ diff --git a/core/plugin/CMakeLists.txt b/core/plugin/CMakeLists.txt new file mode 100644 index 00000000..5dfcce5d --- /dev/null +++ b/core/plugin/CMakeLists.txt @@ -0,0 +1,5 @@ +# The plugin layer's own sources (registry.h, loader.cpp, schema.cpp, select.cpp, bands.cpp) are +# picked up by core/CMakeLists.txt's per-directory glob and compiled into rad_core. This file +# exists only for the test plugins below it, which must be .so files rather than part of the +# engine -- the plugin loader cannot be tested by anything it does not dlopen. +add_subdirectory(testplugin) diff --git a/core/plugin/bands.cpp b/core/plugin/bands.cpp new file mode 100644 index 00000000..0ab795e3 --- /dev/null +++ b/core/plugin/bands.cpp @@ -0,0 +1,129 @@ +/* bands.cpp -- the bucket table. spec.md §2.2. + * + * A parameter may be declared as a range rather than a value, because some of them are properties + * of the batch and not of the model. M is the obvious one: a GEMM sees one row at decode, + * sixty-four at a speculative verify and thousands in a prefill chunk, and libr4d has a different + * kernel for each band. Resolving once at M = max_tok would pick the prefill kernel and then run + * it at M = 1, which is exactly the loss that skinny-GEMM specialisation exists to recover. + * + * THE BUCKET BOUNDARIES ARE THE CONSTRAINT VALUES THEMSELVES. Nothing here picks a policy, a + * power-of-two ladder or a bucket count: the kernels already said where their bands end, and this + * file only collects what they said. A kernel whose fast band sits at an odd boundary gets that + * boundary, because it said so. + */ +#include "registry.h" + +#include + +namespace rad { + +namespace { + +/* "M <= 64" for the first band, "M in (16, 64]" for a later one -- the half-open form is what a + * band actually is, and a reader who sees only "<= 64" on the second row will read the table as + * overlapping. */ +std::string band_span(std::string_view key, int64_t lo_excl, int64_t hi, bool first) { + if (hi == INT64_MAX) return std::string("any shape"); /* the op has no ranged parameter */ + if (first) return fmt("%.*s <= %lld", (int)key.size(), key.data(), (long long)hi); + return fmt("%.*s in (%lld, %lld]", (int)key.size(), key.data(), (long long)lo_excl, + (long long)hi); +} + +} /* namespace */ + +std::vector Registry::build_bands(std::string_view op, std::string_view ranged_key, + int64_t lo, int64_t hi, const Geometry& base, + const RowFilter* accept) { + std::vector out; + + /* No ranged parameter: one band covering everything. hi is INT64_MAX rather than the declared + * value so the issue path's band scan finds it for any issue count -- an op with no range has no + * value to index by, and a table that can miss on an op that cannot miss is a trap. */ + if (ranged_key.empty()) { + lo = 0; + hi = INT64_MAX; + } else if (hi < lo) { + RAD_WARN("op '%s' declares the empty range %s in [%lld, %lld]; resolving the single value " + "%lld", std::string(op).c_str(), std::string(ranged_key).c_str(), + (long long)lo, (long long)hi, (long long)lo); + hi = lo; + } + + /* The union of the LE, GE and EQ values candidate kernels place on the ranged parameter, from + * EVERY plugin and BOTH domains -- the boundaries are a property of the op's candidate set, + * not of whichever kernel happens to win a given band. DIV and IN cut nothing: a kernel that + * wants K divisible by 128 wants it at every value in the range, and set membership is not an + * interval, so neither can be a band edge. */ + std::vector bounds; + auto add = [&](int64_t b) { + if (b >= lo && b < hi) bounds.push_back(b); /* clamped to the declared range; hi closes + * the last band and is appended below */ + }; + if (!ranged_key.empty()) { + if (const std::vector* rows = rows_for(op)) { + for (const KernelRow* r : *rows) { + for (int i = 0; i < r->info->n_constraints; ++i) { + const RadConstraint& c = r->info->constraints[i]; + if (!c.key || ranged_key != c.key) continue; + switch (c.op) { + case RAD_C_LE: add(c.ival); break; + /* A kernel that starts at v ends the band below it at v-1, so the band it + * serves begins exactly where it said it does. */ + case RAD_C_GE: add(c.ival - 1); break; + /* An EQ needs both edges, or the single value it serves would share a band + * with values it does not. */ + case RAD_C_EQ: add(c.ival - 1); add(c.ival); break; + default: break; + } + } + } + } + } + std::sort(bounds.begin(), bounds.end()); + bounds.erase(std::unique(bounds.begin(), bounds.end()), bounds.end()); + bounds.push_back(hi); + + /* Each band is resolved AT ITS UPPER BOUND, in both domains. The upper bound is the worst case + * in the band, so a kernel that serves it serves the whole band; resolving at the lower bound + * would hand a band to a kernel that cannot run its largest value. */ + int64_t prev = lo - 1; + for (size_t i = 0; i < bounds.size(); ++i) { + Band b; + b.hi = bounds[i]; + + Geometry g = base; + if (!ranged_key.empty()) g.set_i(ranged_key, b.hi); + + SelectionTrace t; + for (int dom = 0; dom < RAD_N_DOMAINS; ++dom) { + b.dom[dom] = resolve(op, g, dom, &t, accept); + if (!b.dom[dom]) b.miss[dom] = t.reason; + } + + b.span = band_span(ranged_key, prev, b.hi, i == 0); + if (!b.dom[RAD_DOMAIN_DEVICE]) { + /* Fatal, but not here: declare always completes, and the caller reports every miss at + * the end rather than the first one at the top (§3.1). A range with a hole in it is + * reported as that band, not as the whole op. */ + RAD_DEBUG("op '%s' %s: no device kernel -- %s", std::string(op).c_str(), + b.span.c_str(), b.miss[RAD_DOMAIN_DEVICE].c_str()); + } + if (!b.dom[RAD_DOMAIN_HOST]) + b.miss[RAD_DOMAIN_HOST] += "; site 'host' is unavailable for this band"; + out.push_back(std::move(b)); + prev = bounds[i]; + } + + /* Absence is asymmetric. No device kernel is fatal and the caller says so; no host kernel + * removes one placement option -- host-site execution needs a RAD_DOMAIN_HOST kernel, and + * where none resolves the planner may not put this op's arithmetic on the host. The host + * and SSD TIERS are untouched: a weight can still live there and stage to the device (§5.1). + * + * NEITHER IS REPORTED HERE. This function runs once per DECLARED OP, so a 64-layer model + * calls it 64 times for the same op name, and a warning emitted here would print one line + * per (layer, band) -- hundreds of identical sentences at startup. The band's miss string is + * the record instead; Builder collects them and reports once, over the whole graph. */ + return out; +} + +} /* namespace rad */ diff --git a/core/plugin/loader.cpp b/core/plugin/loader.cpp new file mode 100644 index 00000000..1762659b --- /dev/null +++ b/core/plugin/loader.cpp @@ -0,0 +1,701 @@ +/* loader.cpp -- dlopen, the ABI gate, the configured hierarchy, and the registration of one + * plugin's schemas and kernel rows. spec.md §2, §18. + */ +#include "registry.h" +#include "../device/device.h" +#include "../format/encoding.h" + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace rad { + +namespace { + +/* dlsym returns void*, which is not a function pointer in standard C++ and is one everywhere this + * engine will ever run. The cast is isolated here so the rest of the file reads. */ +template +Fn dl_fn(void* h, const char* name) { + dlerror(); + return reinterpret_cast(dlsym(h, name)); +} + +std::string stem_of(const std::string& path) { + size_t slash = path.find_last_of('/'); + std::string base = slash == std::string::npos ? path : path.substr(slash + 1); + if (base.size() > 3 && base.compare(base.size() - 3, 3, ".so") == 0) + base.resize(base.size() - 3); + if (base.compare(0, 3, "lib") == 0 && base.size() > 3) base.erase(0, 3); + return base; +} + +const char* or_empty(const char* s) { return s ? s : ""; } + +/* Does a plugin's declared coverage include this device's architecture? The field is a list, so a + * binary built for several is one entry per name, separated by spaces or commas. */ +bool target_covers(const std::string& declared, const char* arch) { + for (size_t i = 0; i < declared.size(); ) { + size_t e = declared.find_first_of(" ,;", i); + if (e == std::string::npos) e = declared.size(); + if (e > i && declared.compare(i, e - i, arch) == 0) return true; + i = e + 1; + } + return false; +} + +/* Two schemas for one op name are the SAME schema when every positional slot means the same thing. + * Parameter keys, types and requiredness are load-bearing: they are the geometry the selector + * matches on. Operand roles, count and optionality are load-bearing: arguments are positional. + * Operand NAMES are not -- the ABI says they are for diagnostics -- so two plugins spelling slot 1 + * "b" and "w_gate" agree, and refusing that would be refusing a synonym. */ +bool schema_same(const RadOpSchema& a, const RadOpSchema& b, std::string* diff) { + if (a.n_params != b.n_params) { + *diff = fmt("%d parameters vs %d", a.n_params, b.n_params); + return false; + } + for (int i = 0; i < a.n_params; ++i) { + const RadParamSpec& x = a.params[i]; + const RadParamSpec& y = b.params[i]; + if (std::strcmp(or_empty(x.key), or_empty(y.key)) != 0) { + *diff = fmt("parameter %d is '%s' vs '%s'", i, or_empty(x.key), or_empty(y.key)); + return false; + } + if (x.type != y.type) { + *diff = fmt("parameter '%s' is %s vs %s", or_empty(x.key), + x.type == RAD_P_STR ? "a string" : "an integer", + y.type == RAD_P_STR ? "a string" : "an integer"); + return false; + } + if (x.required != y.required) { + *diff = fmt("parameter '%s' is %s vs %s", or_empty(x.key), + x.required ? "required" : "optional", y.required ? "required" : "optional"); + return false; + } + } + if (a.n_operands != b.n_operands) { + *diff = fmt("%d operands vs %d", a.n_operands, b.n_operands); + return false; + } + for (int i = 0; i < a.n_operands; ++i) { + if (a.operands[i].role != b.operands[i].role || + a.operands[i].optional != b.operands[i].optional) { + *diff = fmt("operand %d ('%s' / '%s') has a different role", i, + or_empty(a.operands[i].name), or_empty(b.operands[i].name)); + return false; + } + } + return true; +} + +} /* namespace */ + +/* ------------------------------------------------------------------ diagnostics */ +void Registry::err_(const char* f, ...) { + char msg[2048]; + va_list ap; + va_start(ap, f); + vsnprintf(msg, sizeof msg, f, ap); + va_end(ap); + load_errors_.emplace_back(msg); + RAD_ERR("%s", msg); +} + +/* ------------------------------------------------------------------ staging */ +/* dlopen and read the plugin's identity, without registering anything. Two phases, because the + * hierarchy is ordered by plugin NAME and the name lives inside the .so: the whole directory must + * be open before anything can be registered, and registration order is what fixes an op's schema. */ +int Registry::stage_(const std::string& path, Staged* out) { + out->path = path; + out->file = stem_of(path); + + /* RTLD_LOCAL is not a preference. Every kernel plugin exports the same four symbol names -- + * rad_kernel_count and friends -- so RTLD_GLOBAL would let the first plugin loaded answer for + * every plugin after it, and the failure would look like a plugin whose kernels vanished. We + * dlsym against the handle instead, which is exactly what RTLD_LOCAL is for. */ + out->code_from = rad::dev_code_mark(); + out->handle = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL); + out->code_to = rad::dev_code_mark(); + if (!out->handle) { + err_("plugin '%s' failed to load: %s", path.c_str(), or_empty(dlerror())); + return RAD_E_IO; + } + + auto abi = dl_fn(out->handle, "rad_plugin_abi_version"); + if (!abi) { + err_("'%s' is not a radiance plugin: it exports no rad_plugin_abi_version", path.c_str()); + unstage_(*out); + return RAD_E_ABI; + } + const uint32_t v = abi(); + if (v != RAD_ABI_VERSION) { + /* Named by FILE, not by RadPluginInfo::name: the struct is exactly the thing that may have + * changed shape between ABI versions, so reading it here would be reading a different + * layout than the one this build was compiled against. Both versions are printed because + * "ABI mismatch" alone does not tell an operator which side is stale. */ + err_("plugin '%s' was built against ABI version %u; this engine is version %u -- refused", + path.c_str(), v, (unsigned)RAD_ABI_VERSION); + unstage_(*out); + return RAD_E_ABI; + } + + auto info_fn = dl_fn(out->handle, "rad_plugin_info"); + if (!info_fn || !(out->info = info_fn())) { + err_("plugin '%s' exports no usable rad_plugin_info", path.c_str()); + unstage_(*out); + return RAD_E_INVAL; + } + out->name = out->info->name && out->info->name[0] ? out->info->name : out->file; + if (auto ref = dl_fn(out->handle, "rad_plugin_reference")) + out->reference = out->info->kind == RAD_PLUGIN_KERNEL && ref() != 0; + return RAD_OK; +} + +void Registry::unstage_(Staged& s) { + if (s.handle) dlclose(s.handle); + s.handle = nullptr; + s.info = nullptr; +} + +/* ------------------------------------------------------------------ registration */ +int Registry::commit_(Staged& s, int order) { + for (const Plugin& p : plugins_) { + if (p.name == s.name) { + err_("two plugins claim the name '%s': %s and %s -- refusing the second", + s.name.c_str(), p.path.c_str(), s.path.c_str()); + unstage_(s); + return RAD_E_DUPLICATE; + } + } + + Plugin p; + p.name = s.name; + p.file = s.file; + p.path = s.path; + p.version = or_empty(s.info->version); + p.description = or_empty(s.info->description); + p.build_target = or_empty(s.info->build_target); + p.kind = s.info->kind; + p.reference = s.reference; + p.order = order; + p.handle = s.handle; + p.close = dl_fn(s.handle, "rad_plugin_close"); + + std::vector staged_schemas; + std::vector> staged_rows; /* the row and its index */ + std::vector staged_quants; + int n_declared_schemas = 0; + + if (p.kind == RAD_PLUGIN_ARCH) { + auto id_fn = dl_fn(s.handle, "rad_arch_id"); + p.arch_declare = dl_fn( + s.handle, "rad_arch_declare"); + p.arch_step = dl_fn(s.handle, "rad_arch_step"); + if (!id_fn || !p.arch_declare || !p.arch_step) { + err_("architecture plugin '%s' is missing rad_arch_id, rad_arch_declare or " + "rad_arch_step", p.name.c_str()); + unstage_(s); + return RAD_E_INVAL; + } + p.arch_id = or_empty(id_fn()); + if (p.arch_id.empty()) { + err_("architecture plugin '%s' returns an empty architecture id", p.name.c_str()); + unstage_(s); + return RAD_E_INVAL; + } + /* The second half of the key. OPTIONAL: a plugin written before this export existed serves + * an unquantised container, which is what "" means, so its absence is not an error. */ + if (auto q_fn = dl_fn(s.handle, "rad_arch_quant")) + p.arch_quant = or_empty(q_fn()); + + /* ALSO OPTIONAL, and for the same reason: it answers what the core needs to know before + * it can build the RadBuildCtx that declare runs against. Absent means every answer is + * the zero -- see rad_builder.h. */ + p.arch_probe = dl_fn(s.handle, + "rad_arch_probe"); + /* AND THE REPLY FORMAT, optional for the same reason: a plugin that says nothing has its + * model's format read off the chat template. */ + p.arch_chat_format = dl_fn( + s.handle, "rad_arch_chat_format"); + + /* One plugin implements one architecture id AT ONE QUANTISATION, and no two may claim the + * same pair: the pair is what selects the plugin, so two claimants is a coin toss over + * which graph a model gets built from (§2.4). Two plugins sharing an id at different + * quantisations is the NORMAL case -- qwen35_bf16 and qwen35_fp8 are the same architecture + * over two weight formats -- and refusing that would make §2.4 unimplementable. */ + for (const Plugin& q : plugins_) { + if (q.arch_id == p.arch_id && q.arch_quant == p.arch_quant) { + err_("architecture id '%s' at quantisation '%s' is claimed by both '%s' and '%s' " + "-- refusing the second", p.arch_id.c_str(), + p.arch_quant.empty() ? "(unquantised)" : p.arch_quant.c_str(), + q.name.c_str(), p.name.c_str()); + unstage_(s); + return RAD_E_DUPLICATE; + } + } + } else if (p.kind == RAD_PLUGIN_KERNEL) { + auto sc_n = dl_fn(s.handle, "rad_kernel_schema_count"); + auto sc_at = dl_fn(s.handle, "rad_kernel_schema_at"); + auto k_n = dl_fn(s.handle, "rad_kernel_count"); + auto k_at = dl_fn(s.handle, "rad_kernel_at"); + if (!sc_n || !sc_at || !k_n || !k_at) { + err_("kernel plugin '%s' is missing rad_kernel_schema_count/at or " + "rad_kernel_count/at", p.name.c_str()); + unstage_(s); + return RAD_E_INVAL; + } + + /* Schemas are checked WHOLE before any of them is committed. A plugin that conflicts on + * its fourth op must not leave its first three registered under its name -- a half-loaded + * plugin is a state nobody can reason about afterwards. */ + n_declared_schemas = sc_n(); + for (int i = 0; i < n_declared_schemas; ++i) { + const RadOpSchema* sch = sc_at(i); + if (!sch || !sch->op || !sch->op[0]) { + err_("kernel plugin '%s' declares a schema with no op name at index %d", + p.name.c_str(), i); + unstage_(s); + return RAD_E_INVAL; + } + std::string diff; + auto it = schemas_.find(sch->op); + if (it != schemas_.end()) { + if (!schema_same(*it->second.schema, *sch, &diff)) { + /* Refused at load with both plugins named. Since arguments are positional, two + * disagreeing schemas would make the same call mean different things depending + * on which plugin won selection, and that is not a diagnosable failure -- it + * is silent numerical garbage (§2.3). The whole plugin is refused, not just + * the op: a plugin built against a different vocabulary is stale everywhere. */ + err_("op '%s' has two different schemas: '%s' fixed it first, '%s' disagrees " + "(%s) -- refusing '%s'", + sch->op, it->second.plugin.c_str(), p.name.c_str(), diff.c_str(), + p.name.c_str()); + unstage_(s); + return RAD_E_DUPLICATE; + } + continue; /* same-shape re-declaration: expected, every plugin declares its ops */ + } + for (const RadOpSchema* q : staged_schemas) { + if (std::strcmp(q->op, sch->op) == 0 && !schema_same(*q, *sch, &diff)) { + err_("kernel plugin '%s' declares op '%s' twice with different schemas (%s)", + p.name.c_str(), sch->op, diff.c_str()); + unstage_(s); + return RAD_E_DUPLICATE; + } + } + staged_schemas.push_back(sch); + } + + for (int i = 0, n = k_n(); i < n; ++i) { + const RadKernelInfo* k = k_at(i); + if (!k || !k->name || !k->op || !k->op[0]) { + err_("kernel plugin '%s' declares a kernel with no name or op at index %d", + p.name.c_str(), i); + unstage_(s); + return RAD_E_INVAL; + } + /* A row with no entry point is a row that resolves and then cannot run, which is the + * one failure this layer exists to make impossible. */ + if (!k->launch) { + err_("kernel '%s' in plugin '%s' has no launch function", k->name, p.name.c_str()); + unstage_(s); + return RAD_E_INVAL; + } + if (k->domain != RAD_DOMAIN_DEVICE && k->domain != RAD_DOMAIN_HOST) { + err_("kernel '%s' in plugin '%s' declares domain %d, which is neither device nor " + "host", k->name, p.name.c_str(), k->domain); + unstage_(s); + return RAD_E_INVAL; + } + /* EVERY TUNABLE AXIS CARRIES A DEFAULT, AND THE DEFAULT IS ONE OF ITS OWN VALUES. + * + * This is what makes an untuned install fast rather than broken (spec §15): a machine + * with no cache, a shape nobody measured, a cache from a different card -- all of them + * land on the defaults, and there is no other fallback beneath them. A kernel that + * declares an axis without a usable default has no answer at all for those cases, so + * it is refused here rather than resolving and then launching a zero tile. + * + * Checked at LOAD and not at first use, for the same reason the missing launch + * function above is: a library author finds out when the plugin loads, not when some + * shape three hours into a serve happens to miss the cache. */ + for (int v = 0; v < k->n_tunables; ++v) { + const RadTunable& t = k->tunables[v]; + if (!t.key || !t.key[0] || !t.values || t.n_values <= 0) { + err_("kernel '%s' in plugin '%s' declares tunable %d with no key or no legal " + "values", k->name, p.name.c_str(), v); + unstage_(s); + return RAD_E_INVAL; + } + bool ok = false; + for (int j = 0; j < t.n_values; ++j) if (t.values[j] == t.deflt) ok = true; + if (!ok) { + err_("kernel '%s' in plugin '%s': tunable '%s' defaults to %lld, which is not " + "one of the values it declares. The default is what runs when this " + "machine has no measurement for a shape, so it has to be a value the " + "kernel can actually launch", + k->name, p.name.c_str(), t.key, (long long)t.deflt); + unstage_(s); + return RAD_E_INVAL; + } + for (int w = 0; w < v; ++w) + if (k->tunables[w].key && std::strcmp(k->tunables[w].key, t.key) == 0) { + err_("kernel '%s' in plugin '%s' declares tunable '%s' twice", k->name, + p.name.c_str(), t.key); + unstage_(s); + return RAD_E_INVAL; + } + } + staged_rows.emplace_back(k, i); + } + + /* A KERNEL LIBRARY WITH NO CODE FOR THIS CARD IS LEFT OUT OF THE CARD'S SELECTION. Its + * device rows would otherwise resolve -- a row's constraints say nothing about which card + * it was compiled for -- and the first launch would fail, so an installation carrying + * libraries for several cards would serve none of them but the first in the hierarchy. + * What the library carries is read out of the fat binaries its dlopen registered, which is + * what the launch itself will consult (core/device/aql_code.cpp), not out of + * build_target, which is prose. Its host rows run anywhere and stay. */ + int n_device = 0; + for (const auto& r : staged_rows) n_device += r.first->domain == RAD_DOMAIN_DEVICE; + std::string why; + if (n_device > 0 && s.code_to > s.code_from && + rad::dev_code_runs(s.code_from, s.code_to, code_device_, &why) == 0) { + std::vector> keep; + for (const auto& r : staged_rows) + if (r.first->domain != RAD_DOMAIN_DEVICE) keep.push_back(r); + RAD_WARN("kernel plugin '%s' has no device code for device %d: %s. Its %d device " + "kernel(s) are left out of selection here%s.", p.name.c_str(), code_device_, + why.c_str(), n_device, + keep.empty() ? "" : fmt(" and its %zu host kernel(s) stay", keep.size()).c_str()); + staged_rows.swap(keep); + p.device_code_absent = true; + } + } else if (p.kind == RAD_PLUGIN_QUANT) { + auto q_n = dl_fn(s.handle, "rad_quant_count"); + auto q_at = dl_fn(s.handle, "rad_quant_at"); + if (!q_n || !q_at) { + err_("quantiser plugin '%s' is missing rad_quant_count or rad_quant_at", + p.name.c_str()); + unstage_(s); + return RAD_E_INVAL; + } + /* Checked WHOLE before any is registered, for the reason the kernel schemas are: a plugin + * refused on its third quantiser must not leave the first two answering to a recipe. */ + for (int i = 0, n = q_n(); i < n; ++i) { + const RadQuantizerInfo* q = q_at(i); + if (!q || !q->name || !q->name[0] || !q->encoding || !q->quantize) { + err_("quantiser plugin '%s' declares a quantiser with no name, no encoding hook or " + "no quantize hook at index %d", p.name.c_str(), i); + unstage_(s); + return RAD_E_INVAL; + } + /* A NAME IS ONE QUANTISER. A recipe that names it would otherwise mean different + * numbers depending on which plugin loaded first. */ + auto clash = [&](const char* other) { return std::strcmp(other, q->name) == 0; }; + for (const QuantRow& r : quants_) + if (clash(r.info->name)) { + err_("quantiser '%s' is offered by both '%s' and '%s' -- refusing '%s'", + q->name, r.plugin.c_str(), p.name.c_str(), p.name.c_str()); + unstage_(s); + return RAD_E_DUPLICATE; + } + for (const RadQuantizerInfo* o : staged_quants) + if (clash(o->name)) { + err_("quantiser plugin '%s' declares '%s' twice", p.name.c_str(), q->name); + unstage_(s); + return RAD_E_DUPLICATE; + } + staged_quants.push_back(q); + } + } else { + err_("plugin '%s' declares kind %u, which is not a kernel, architecture or quantiser " + "plugin", p.name.c_str(), p.kind); + unstage_(s); + return RAD_E_INVAL; + } + + /* Once after the plugin is loaded and before any selection (rad_abi.h). A plugin that cannot + * open -- no device, no config table -- is refused rather than asked to select. */ + if (auto open = dl_fn(s.handle, "rad_plugin_open")) { + int st = open(); + /* RAD_E_UNSUPPORTED is a plugin saying this machine is not one it serves -- a library for + * another card, in an installation that ships several. That is a skip, said once, and + * not a failure: the next library in the hierarchy is the one that serves this card. */ + if (st == RAD_E_UNSUPPORTED) { + RAD_INFO("plugin '%s' declines this machine and is not loaded", p.name.c_str()); + unstage_(s); + return 1; + } + if (st < 0) { + err_("plugin '%s' refused to open: %s", p.name.c_str(), rad_strerror(st)); + unstage_(s); + return st; + } + } + + /* What the plugin DECLARES, not what it fixed: a plugin below another one re-declares the same + * ops with the same shapes, and reporting 0 there would read as a plugin that declares + * nothing. Which plugin fixed a given op is schema_owner()'s answer, not a count. */ + p.n_schemas = n_declared_schemas; + p.n_kernels = (int)staged_rows.size(); + for (const RadOpSchema* sch : staged_schemas) schemas_[sch->op] = SchemaEntry{sch, p.name}; + for (const RadQuantizerInfo* q : staged_quants) { + quants_.push_back(QuantRow{ q, p.name }); + /* Its own schemes are read through it, by everything that decodes a weight. */ + if (q->decode) enc_add_decoder(q->decode); + } + const auto concurrent = dl_fn(s.handle, "rad_kernel_concurrent"); + for (const auto& sr : staged_rows) { + KernelRow row; + row.info = sr.first; + row.plugin = p.name; + row.plugin_order = order; + row.index = sr.second; + row.concurrent = concurrent && concurrent(sr.second) != 0; + row.reference = p.reference; + rows_.push_back(row); + } + + /* A KERNEL LIBRARY BUILT FOR ANOTHER CARD FAILS AT EVERY LAUNCH, AND THIS IS THE ONE PLACE IT + * CAN BE NAMED ONCE. An installed .so travelling to a machine it was not compiled for is + * otherwise invisible until the first dispatch, where it surfaces as a driver error carrying a + * kernel name and nothing about why. + * + * A WARNING AND NOT A REFUSAL, deliberately. build_target is text the plugin's author writes; + * it is not derived from what the binary actually contains, so a library covering several + * architectures may still name only one, and refusing on it would be refusing on a claim the + * engine cannot verify. The launch is what is authoritative. This predicts it by name. + * + * "host" and "" are not claims about a device: the first is a library of CPU kernels, which + * run anywhere, and the second is a plugin that declines to claim anything. */ + if (p.kind == RAD_PLUGIN_KERNEL && s.code_to == s.code_from && !p.build_target.empty() && + p.build_target != "host") { + RadDeviceProps dp{}; + if (rad_dev_count() > code_device_ && rad_dev_props(code_device_, &dp) == RAD_OK && + dp.arch[0] && !target_covers(p.build_target, dp.arch)) + RAD_WARN("kernel plugin '%s' declares it was built for %s and this machine reports %s. " + "Its kernels will fail to launch; build it for %s, or put a library that " + "serves this device ahead of it with --kernels.", + p.name.c_str(), p.build_target.c_str(), dp.arch, dp.arch); + } + + RAD_DEBUG("plugin %d: %s %s (%s) -- %d kernels, %d schemas, %zu fat binaries, %s", order, + p.name.c_str(), p.version.c_str(), p.path.c_str(), p.n_kernels, p.n_schemas, + s.code_to - s.code_from, p.build_target.empty() ? "portable" : p.build_target.c_str()); + plugins_.push_back(std::move(p)); + index_rows_(); + s.handle = nullptr; /* the Plugin owns it now */ + return RAD_OK; +} + +/* The per-op index select() walks, in (hierarchy order, declaration order). Rebuilt whole on every + * registration: loading is startup and the row count is in the hundreds, so the simple thing is + * also the fast enough thing, and an index that can never be stale is one fewer invariant. */ +void Registry::index_rows_() { + by_op_.clear(); + for (const KernelRow& r : rows_) by_op_[r.info->op].push_back(&r); + for (auto& kv : by_op_) { + std::stable_sort(kv.second.begin(), kv.second.end(), + [](const KernelRow* a, const KernelRow* b) { + if (a->plugin_order != b->plugin_order) + return a->plugin_order < b->plugin_order; + return a->index < b->index; + }); + } +} + +/* ------------------------------------------------------------------ the public loading API */ +int Registry::load_plugin(const std::string& path, int order) { + Staged s; + int st = stage_(path, &s); + if (st < 0) return st; + return commit_(s, order); +} + +int Registry::load_dir(const std::string& dir, const std::vector& hierarchy) { + return load_dirs({ dir }, hierarchy); +} + +int Registry::load_dirs(const std::vector& dirs, + const std::vector& hierarchy) { + int first_error = RAD_OK; + + /* Directory by directory in the order given, and within one in filename order, so a set of + * plugins nobody named still loads the same way twice. A file whose name an earlier directory + * already supplied is SHADOWED rather than loaded: the first directory is the one the operator + * put first -- their own plugins ahead of an installation's -- and loading both would be two + * plugins claiming one name, which is refused. */ + std::vector files, stems; + std::string where; + for (const std::string& dir : dirs) { + DIR* d = opendir(dir.c_str()); + if (!d) { + err_("plugin directory '%s': %s", dir.c_str(), std::strerror(errno)); + return RAD_E_IO; + } + where += (where.empty() ? "" : ", ") + dir; + std::vector here; + while (const dirent* e = readdir(d)) { + const std::string n = e->d_name; + if (n.size() < 4 || n.compare(n.size() - 3, 3, ".so") != 0) continue; + const std::string path = dir + "/" + n; + struct stat st {}; + if (stat(path.c_str(), &st) != 0 || !S_ISREG(st.st_mode)) continue; + here.push_back(path); + } + closedir(d); + std::sort(here.begin(), here.end()); + for (const std::string& f : here) { + const std::string stem = stem_of(f); + auto at = std::find(stems.begin(), stems.end(), stem); + if (at != stems.end()) { + RAD_INFO("plugin %s is shadowed by %s, which comes first on the search path", + f.c_str(), files[(size_t)(at - stems.begin())].c_str()); + continue; + } + files.push_back(f); + stems.push_back(stem); + } + } + const std::string dir = where; + + std::vector staged; + for (const std::string& f : files) { + Staged s; + int st = stage_(f, &s); + if (st < 0) { + if (first_error == RAD_OK) first_error = st; + continue; + } + staged.push_back(s); + } + + /* The hierarchy is configured, not discovered. A plugin the operator named takes that + * position; a plugin present on disk but absent from the list loads after everything named, + * so dropping an .so into the directory adds it with no configuration and naming it ahead of + * another is what substitutes it. + * + * A REFERENCE LIBRARY IS PINNED BELOW EVERY OTHER UNNAMED PLUGIN. It declares a kernel for + * every op it knows, so a plugin ranked behind it is unreachable -- an unnamed kernel library + * for this machine's card would load, never be selected for anything, and leave the whole + * model resolving to the naive implementation. Pinning it is what makes an unconfigured + * drop-in work. Naming it in the hierarchy overrides this, which is how it is put in front of + * a library to compare against. Which library is one is its own declaration + * (RadPluginReferenceFn), not its name. */ + const size_t kUnnamed = (size_t)INT_MAX - 1; + std::vector rank(staged.size()); + for (size_t i = 0; i < staged.size(); ++i) + rank[i] = staged[i].reference ? (size_t)INT_MAX : kUnnamed; + for (size_t h = 0; h < hierarchy.size(); ++h) { + bool found = false; + for (size_t i = 0; i < staged.size(); ++i) { + if (staged[i].name == hierarchy[h] || staged[i].file == hierarchy[h]) { + rank[i] = h; + found = true; + } + } + if (!found) + RAD_WARN("kernel hierarchy names '%s', which is not in %s -- ignored", + hierarchy[h].c_str(), dir.c_str()); + } + std::vector idx(staged.size()); + for (size_t i = 0; i < idx.size(); ++i) idx[i] = i; + std::stable_sort(idx.begin(), idx.end(), + [&](size_t a, size_t b) { return rank[a] < rank[b]; }); + + /* Orders continue from what is already loaded, so loading kernels/ and then architectures/ + * does not produce two plugins at position 0. */ + int order = 0; + for (const Plugin& p : plugins_) order = std::max(order, p.order + 1); + + for (size_t i : idx) { + int st = commit_(staged[i], order); + if (st < 0) { + if (first_error == RAD_OK) first_error = st; + continue; /* refused, and the next plugin still gets its chance */ + } + if (st > 0) continue; /* declined this machine */ + ++order; + } + + int st = check_complete(); + if (st < 0 && first_error == RAD_OK) first_error = st; + return first_error; +} + +/* ------------------------------------------------------------------ the tuning cache (§15) */ +int Registry::load_tune(const std::string& radiance_home, const std::string& machine) { + const std::string key = machine.empty() ? rad_machine_key() : machine; + const int s = tune_.load(radiance_home, key); + if (s < 0) return s; + /* A cache measured on another card is not a slower answer, it is a wrong one -- tunecache.h + * makes the machine key line 2 of the file for exactly this. `load` already refuses a + * mismatch, so reaching here with rows means they are this machine's. */ + return (int)tune_.rows().size(); +} + +/* Kernel plugins declare the ops they implement AND the parameter schema for each. A row whose op + * has no schema anywhere in the loaded set is a plugin that supplied only half of that contract, + * and the cost is exact: no architecture plugin's parameters for that op can ever be checked, so a + * typo in them becomes a silent miss instead of a named one. Checked once the set is complete, + * because an override plugin may legitimately rely on the schema of the plugin BELOW it, which + * loads later. */ +int Registry::check_complete() { + int st = RAD_OK; + for (const KernelRow& r : rows_) { + if (schemas_.find(r.info->op) == schemas_.end()) { + err_("kernel '%s' in plugin '%s' implements op '%s', which no loaded plugin declares a " + "schema for", r.info->name, r.plugin.c_str(), r.info->op); + st = RAD_E_NOSCHEMA; + } + } + return st; +} + +/* ------------------------------------------------------------------ lookup and teardown */ +const Plugin* Registry::plugin(std::string_view name) const { + for (const Plugin& p : plugins_) + if (p.name == name || p.file == name) return &p; + return nullptr; +} + +const Registry::QuantRow* Registry::quantizer(std::string_view name) const { + for (const QuantRow& q : quants_) + if (name == q.info->name) return &q; + return nullptr; +} + +const std::vector* Registry::rows_for(std::string_view op) const { + auto it = by_op_.find(std::string(op)); + return it == by_op_.end() ? nullptr : &it->second; +} + +void Registry::close() { + fini_instances(); + for (const QuantRow& q : quants_) + if (q.info && q.info->decode) enc_remove_decoder(q.info->decode); + /* Reverse order: a plugin lower in the hierarchy may have been opened against state a higher + * one established, and unwinding in the order things were built is the only order that is + * always safe. */ + for (auto it = plugins_.rbegin(); it != plugins_.rend(); ++it) { + if (it->close) it->close(); + if (it->handle) dlclose(it->handle); + } + plugins_.clear(); + rows_.clear(); + quants_.clear(); + by_op_.clear(); + schemas_.clear(); + load_errors_.clear(); + clear_selections(); +} + +Registry::~Registry() { close(); } + +} /* namespace rad */ diff --git a/core/plugin/registry.h b/core/plugin/registry.h new file mode 100644 index 00000000..c5c31580 --- /dev/null +++ b/core/plugin/registry.h @@ -0,0 +1,358 @@ +/* registry.h -- the plugin layer: dlopen, the configured hierarchy, the op-schema registry, the + * constraint selector, bucket tables and the selection table. spec.md §2 and §16. + * + * Four rules live here and nowhere else, because every one of them is a rule somebody would + * otherwise reinvent slightly differently in a second place: + * + * THE HIERARCHY IS ABSOLUTE. Plugins are queried in configured order and the first plugin with + * any matching kernel supplies it. A lower-priority plugin never outbids a higher one no matter + * how specialised its kernel -- that is what makes a user override an override (§2.1). + * + * SPECIFICITY IS DECLARED, NOT DERIVED. Within one plugin the highest `priority` among matching + * rows wins, ties broken by declaration order. Counting matched constraints gets it backwards: + * {head_dim<=1024, gqa>=1, block%16==0, causal in {0,1}} matches four and {head_dim==256, gqa==6} + * matches two, and the second is by far the more specialised. + * + * SCHEMAS ARE FIXED BY FIRST DECLARATION. The first plugin in hierarchy order to declare an op + * fixes its schema; a later plugin declaring the same op name with a different one is refused at + * load with both plugins named. Arguments are positional, so two disagreeing schemas make the + * same call mean different things depending on which plugin won selection -- silent numerical + * garbage rather than a diagnosable failure (§2.3). + * + * THE BUCKET BOUNDARIES ARE THE CONSTRAINT VALUES THEMSELVES. The union of the LE, GE and EQ + * values candidate kernels place on the ranged parameter, clamped to the declared range. No + * policy is chosen by anyone (§2.2). + * + * A REFERENCE LIBRARY IS LAST BY CONSTRUCTION. A library that declares itself one + * (RadPluginReferenceFn) matches every op it declares, so anything ranked behind it would be + * unreachable. An unnamed plugin sorts after every named one but still ahead of a reference, + * which is what makes dropping in a kernel library for a new card work with no configuration + * (§2.1). Naming it in the hierarchy still overrides that. The rule is keyed on the declaration, + * never on a name: the libraries that ship with radiance load exactly as a third party's do. + * + * LIFETIME. A Resolved, a Band and a KernelRow all point into a plugin's static tables. They are + * valid exactly as long as the Registry that loaded them: close() dlcloses, and everything handed + * out before it dangles after. The core keeps one Registry for the life of the process, so this + * costs nothing; a tool that loads two kernel sets in turn has to finish with the first. + * + * THREADING. Loading is startup, single-threaded, before the rank threads exist. select() and + * init_instance() are called from every rank thread during declare, so the selection log and the + * instance list are behind one mutex. It is uncontended at declare and never touched on the step + * path, which is the only place a lock would cost anything. + */ +#pragma once +#include "rad_core.h" +#include "rad_quant.h" +#include "../format/tunecache.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace rad { + +inline const char* domain_name(int d) { return d == RAD_DOMAIN_HOST ? "host" : "device"; } + + +/* ------------------------------------------------------------------ one loaded .so */ +struct Plugin { + std::string name; /* RadPluginInfo::name -- what the hierarchy list names */ + std::string file; /* the .so's stem; the hierarchy list accepts this spelling too */ + std::string path; + std::string version; + std::string description; + std::string build_target; + + uint32_t kind = 0; /* RAD_PLUGIN_KERNEL | RAD_PLUGIN_ARCH */ + int order = 0; /* hierarchy position; 0 is highest */ + void* handle = nullptr; + + int n_kernels = 0; + int n_schemas = 0; + /* A kernel library whose fat binaries hold no code object the card runs: its device rows were + * left out at load (loader.cpp, commit_), and only its host rows are selectable. */ + bool device_code_absent = false; + /* A kernel library that declared itself a reference implementation (RadPluginReferenceFn). */ + bool reference = false; + + /* Architecture plugins are loaded and IDENTIFIED here; the build component drives them. The + * core never calls declare or step from the registry -- it only guarantees that no two + * plugins claim the same (architecture id, quantisation) PAIR (§2.4). The pair, not the id: + * qwen35_bf16 and qwen35_fp8 are the same architecture at two weight formats and both answer + * "qwen35", which is the whole reason §2.4 splits on quantisation at all. `arch_quant` is "" + * for a plugin that serves an unquantised container, including one that predates the export. */ + std::string arch_id; + std::string arch_quant; + int (*arch_declare)(RadBuilder*, const RadModelMeta*, const RadBuildCtx*) = nullptr; + void (*arch_step)(RadCtx*, const RadBatch*) = nullptr; + /* OPTIONAL (rad_builder.h): null when the plugin exports none, and every question then + * answers zero. It is what the core asks BEFORE declare, so that a fact which is an input to + * declaration and a property of the model is still read by the plugin and not by us. */ + int (*arch_probe)(const RadModelMeta*, RadArchProbe*) = nullptr; + /* OPTIONAL (rad_builder.h): null when the plugin exports none, and the reply format is then + * derived from the chat template. */ + const RadChatFormat* (*arch_chat_format)(const RadModelMeta*) = nullptr; + + RadPluginCloseFn close = nullptr; +}; + +/* ------------------------------------------------------------------ one selection question */ +/* What select() did, in enough detail to print §16's table and to answer "why did it not pick the + * kernel I wrote". `candidates` is every row that was CONSIDERED -- rows of the other domain are + * not, since they answer a different question, and rows behind a plugin that already supplied a + * match are not either, because the hierarchy stopped there. */ +struct SelectionTrace { + struct Candidate { + std::string plugin; + std::string kernel; + int priority = 0; + bool ok = false; + std::string why; /* the constraint that refused it, or "ok" */ + }; + + std::string op; + std::string query; /* the geometry as asked */ + int domain = RAD_DOMAIN_DEVICE; + + std::string kernel; /* empty on a miss */ + std::string plugin; + int priority = 0; + std::string reason; /* on a miss: the constraint(s) that refused it */ + + /* A RAD_DERIVED parameter the CALLER did not supply: its constraints were skipped during + * matching, and the winning kernel's RAD_C_EQ value for the key was written into the resolved + * geometry afterwards. `known` is false when the winner has no EQ on that key -- ref's + * `block_size >= 1` is exactly that case -- and an unset derived key is a condition the + * caller has to report, not a zero to be read. */ + struct DerivedParam { + std::string key; + long long value = 0; + bool known = false; + }; + std::vector derived; + + std::vector candidates; + bool other_domain_has_rows = false; /* the op exists, just not in the domain asked for */ +}; + +/* ------------------------------------------------------------------ the registry */ +class Registry { +public: + Registry() = default; + ~Registry(); + Registry(const Registry&) = delete; + Registry& operator=(const Registry&) = delete; + + /* ---------------------------------------------------------- loading (§2, §18) */ + /* Scan a directory of .so files and load them in HIERARCHY ORDER. The hierarchy is configured, + * not discovered: `hierarchy` is an ordered list of plugin names (RadPluginInfo::name, or the + * file's stem, whichever the operator wrote), so substituting a kernel is dropping an .so in a + * directory and naming it ahead of the default. A plugin present on disk but absent from the + * list loads at the END, after everything named, in filename order so the result is + * reproducible. + * + * Always completes: every plugin that can be loaded is, every refusal is recorded in + * load_errors(), and the FIRST negative status is returned. Reporting the whole list beats + * reporting the first failure at the top -- an operator with two stale plugins wants to hear + * about both in one run (§3.1). */ + int load_dir(const std::string& dir, const std::vector& hierarchy); + /* The same over several directories -- a $RADIANCE_HOME search path -- as one set: the + * hierarchy orders plugins across all of them, and a file an earlier directory already holds + * by the same name is shadowed, not loaded. */ + int load_dirs(const std::vector& dirs, const std::vector& hierarchy); + + /* One plugin at a known hierarchy position. rad-info and rad-kbench load a single .so; the + * engine goes through load_dir. 1, and nothing registered, when the plugin declines this + * machine (its rad_plugin_open answers RAD_E_UNSUPPORTED). */ + int load_plugin(const std::string& path, int order); + + /* Every registered kernel row's op must have a schema SOMEWHERE in the loaded set -- an + * override plugin may legitimately ship kernels for an op whose schema the plugin below it + * declared, and that plugin loads later, so the check can only run once the set is complete. + * load_dir calls this; a caller assembling a set by hand calls it when it is done. */ + int check_complete(); + + /* The device a kernel library's device code is checked against when it loads: the first card + * the caller will run on. 0 unless the caller says otherwise -- the engine says so before it + * loads anything, once it has chosen its cards. */ + void set_code_device(int device) { code_device_ = device; } + + void close(); /* fini instances, close hooks, dlclose, forget everything */ + + const std::vector& plugins() const { return plugins_; } + const Plugin* plugin(std::string_view name) const; + const std::vector& load_errors() const { return load_errors_; } + + /* Every quantiser the loaded quantiser plugins offer, in load order. A name is unique across + * them -- two plugins naming one quantiser is refused at load -- so the lookup is the answer + * and not the first of several. Null when nothing offers it. */ + struct QuantRow { + const RadQuantizerInfo* info = nullptr; + std::string plugin; + }; + const std::deque& quantizers() const { return quants_; } + const QuantRow* quantizer(std::string_view name) const; + + /* Every kernel row, in (hierarchy order, declaration order). rad-info prints this. */ + const std::deque& rows() const { return rows_; } + /* The rows implementing one op, in the order select() considers them. Empty if none. */ + const std::vector* rows_for(std::string_view op) const; + + /* ---------------------------------------------------------- op schemas (§2.3) */ + const RadOpSchema* schema(std::string_view op) const; + const Plugin* schema_owner(std::string_view op) const; + std::vector op_names() const; /* sorted; the vocabulary this set implements */ + + /* Check a declared parameter set against the op's schema. Without this, a typo and an + * unimplemented op are the same diagnostic; with it, a misspelled op fails declare with the + * near-miss named. Returns RAD_OK, RAD_E_NOSCHEMA (no such op) or RAD_E_SCHEMA, and fills + * `err` with a sentence an architecture-plugin author can act on. */ + int validate(std::string_view op, const RadParam* p, int n_p, std::string* err) const; + + /* The closest known op name to `op` within a small edit distance, or "" if nothing is close. + * Public because the builder wants it in its own messages too. */ + std::string near_miss(std::string_view op) const; + + /* ---------------------------------------------------------- the tuning cache (§15) */ + /* Load $RADIANCE_HOME/tune/.tune, which rad-tune wrote. resolve() then moves a shape + * off each axis's declared default wherever there is a row for it. A missing file is not an + * error and leaves every shape on that default, which is what makes an untuned install fast + * rather than broken. + * + * THE CORE OWNS THE CACHE AND THE POLICY, so no plugin has to (tunecache.h; the choice is + * applied in select.cpp). Without this call every kernel runs its axis defaults whatever the + * file on disk says, which is slow rather than wrong -- but silently so. + * + * Returns the number of rows loaded, or a negative status. */ + int load_tune(const std::string& radiance_home, const std::string& machine = std::string()); + const TuneCache& tune() const { return tune_; } + + /* ---------------------------------------------------------- selection (§2.1) */ + /* The first plugin in hierarchy order with any matching row supplies the kernel; within that + * plugin the highest declared priority wins, ties on declaration order. Null on a miss, with + * the refusing constraint in `why->reason`. Every call is recorded in the selection table. + * + * RAD_DERIVED parameters (rad_abi.h) are supplied by the KERNEL, so a constraint on one is + * SKIPPED here when the caller did not name it, and the winner's RAD_C_EQ value for the key + * comes back in `why->derived` -- resolve() is what writes it into the geometry. Without that + * skip, spec §7.2 is circular: the block manager reads the block size off the resolved + * attention kernel, but a kernel constrained to block_size == 16 can never be selected by a + * query that omits block_size, because a constraint whose key the geometry lacks does not + * hold. A caller that supplies the key anyway pins it and matches normally, which is how an + * operator forces a block size and gets a refusal by name instead of a substitution. */ + /* `record` is false for a caller asking the selector a question the ENGINE did not ask -- the + * graph dump replays every band to recover the candidate list it threw away. The selection + * table is a record of what this deployment resolved, and a reporting tool inflating its + * counts would make it a record of itself. */ + /* `accept`, when given, is asked of every row whose constraints hold, and an answer that is + * not empty takes the row out as a candidate with that answer as the reason. It is how a + * weight's encoding takes part in selection: a kernel whose layout hook does not read the + * encoding a weight operand has (RAD_E_DTYPE) is not a candidate, and the next one is chosen + * -- a bf16 lm_head goes to the bf16 GEMM instead of being refused by the fp8 one. */ + using RowFilter = std::function; + const KernelRow* select(std::string_view op, const Geometry& g, int domain, + SelectionTrace* why = nullptr, bool record = true, + const RowFilter* accept = nullptr); + + /* Selection plus the per-instance bookkeeping: the tuned axes, where they came from, and the frozen + * geometry -- the query plus whatever the winning kernel supplied for a derived key, so + * rad_kv_block_size() and RadArgs.p both see it. init() is NOT called here -- see + * init_instance(). */ + Resolved resolve(std::string_view op, const Geometry& g, int domain, SelectionTrace* why = nullptr, + const RowFilter* accept = nullptr); + + /* ---------------------------------------------------------- bucket tables (§2.2) */ + /* Resolve a ranged parameter into a bucket table: one resolution per band, per domain, built + * at declare and indexed by the actual value at issue. The boundaries are the constraint + * values themselves. Each band is resolved AT ITS UPPER BOUND, which is the worst case in the + * band and therefore the only value that is safe to size and select on. + * + * `ranged_key` empty means the op has no ranged parameter: exactly one band is returned, whose + * hi is INT64_MAX so the issue path's band scan always finds it. + * + * Both domains are resolved wherever both exist, so the core can change execution site at + * runtime without re-resolving. Absence is asymmetric: a band with no DEVICE kernel is fatal + * and the caller reports it (this function does not abort -- declare always completes); a band + * with no HOST kernel is a warning naming the placement options it just removed. */ + std::vector build_bands(std::string_view op, std::string_view ranged_key, + int64_t lo, int64_t hi, const Geometry& base, + const RowFilter* accept = nullptr); + + /* ---------------------------------------------------------- instances (§2.1) */ + /* init() once per resolved instance -- one op, one band, one domain -- with the frozen + * geometry, the rank and the world size. libr4d's all-reduce needs its peer signal buffers and + * IPC handles established across ranks before the first call, and a kernel that JITs or loads + * a config table wants somewhere to do it that is not the hot path. A negative return aborts + * startup and the caller names the kernel. */ + int init_instance(Resolved& r, int rank, int world_size); + void fini_instances(); + size_t n_instances() const; + + /* ---------------------------------------------------------- the selection table (§16) */ + /* Every DISTINCT question the selector was asked, in the order first asked, with what it + * resolved to and, for a miss, the constraint that refused it. Repeats are folded and counted: + * a 64-layer model asks the same question 64 times, and "asked 64 times" says how much of the + * model resolved to that kernel. This is the record of why a fallback is running. */ + std::string selection_table() const; + size_t n_selections() const; + void clear_selections(); + +private: + struct Staged { + void* handle = nullptr; + std::string path, file, name; + const RadPluginInfo* info = nullptr; + /* The device backend's fat-binary registrations before and after this plugin's dlopen: + * [code_from, code_to) is the device code it brought in. */ + size_t code_from = 0, code_to = 0; + bool reference = false; /* RadPluginReferenceFn answered nonzero */ + }; + + struct SchemaEntry { + const RadOpSchema* schema = nullptr; + std::string plugin; /* who fixed it, for the conflict message */ + }; + + struct SelectionRecord { + std::string op, query, key, kernel, plugin, reason; + std::string derived; /* "block_size:=16", rendered apart from the query because it + * was NOT part of the question the selector was asked */ + int domain = 0; + int priority = 0; + long long count = 1; + }; + + int code_device_ = 0; + TuneCache tune_; + + int stage_(const std::string& path, Staged* out); + int commit_(Staged& s, int order); + void unstage_(Staged& s); + void index_rows_(); + void record_(const std::string& op, int domain, const Geometry& g, const SelectionTrace& t); + void err_(const char* fmt, ...) __attribute__((format(printf, 2, 3))); + + std::vector plugins_; + std::deque rows_; /* deque: KernelRow* handed out must stay valid */ + std::deque quants_; + std::unordered_map> by_op_; + std::unordered_map schemas_; + std::vector load_errors_; + + mutable std::mutex mu_; + std::vector log_; + std::vector> instances_; +}; + +/* The value a kernel's own constraints place on one key, e.g. the paged block size the resolved + * attention kernel is compiled for. §7.2: the block manager reads that off the resolved kernel and + * sizes itself accordingly, because a core that picked its own block size would be a core that has + * to be edited when a kernel changes. Returns false when the kernel says nothing about that key + * with that operator -- which is not the same as a default, and the caller has to decide. */ +bool kernel_constraint(const KernelRow& r, std::string_view key, int c_op, long long* out); + +} /* namespace rad */ diff --git a/core/plugin/schema.cpp b/core/plugin/schema.cpp new file mode 100644 index 00000000..105e9ba5 --- /dev/null +++ b/core/plugin/schema.cpp @@ -0,0 +1,202 @@ +/* schema.cpp -- the op-schema registry and the check an architecture plugin's declared parameters + * go through. spec.md §2.3. + * + * Without a schema, a typo and an unimplemented op are the same diagnostic: both are "nothing + * resolved". With one, a misspelled op fails declare with the near-miss named, and that is the + * whole reason this file exists -- new ops still need no core change, because the core learns the + * vocabulary from the plugins rather than carrying a copy of it. + */ +#include "registry.h" + +#include +#include + +namespace rad { + +namespace { + +/* Levenshtein, bounded by the two lengths. The strings are op and parameter names -- a dozen + * characters against a few hundred candidates, once per failed declare -- so the textbook O(nm) + * table is already far below anything worth optimising. */ +int edit_distance(std::string_view a, std::string_view b) { + const size_t n = b.size(); + std::vector prev(n + 1), cur(n + 1); + for (size_t j = 0; j <= n; ++j) prev[j] = (int)j; + for (size_t i = 1; i <= a.size(); ++i) { + cur[0] = (int)i; + for (size_t j = 1; j <= n; ++j) { + const int sub = prev[j - 1] + (a[i - 1] == b[j - 1] ? 0 : 1); + cur[j] = std::min({ sub, prev[j] + 1, cur[j - 1] + 1 }); + } + prev.swap(cur); + } + return prev[n]; +} + +/* How wrong a name may be and still be worth suggesting. One edit for a short name, up to three + * for a long one: "gemm_nt" against "gemm_nq" is a typo worth naming, and "rmsnorm" against + * "softmax" is not -- a suggestion that is wrong is worse than none, because it sends the reader + * to check something that was never the problem. */ +bool close_enough(std::string_view a, std::string_view b, int d) { + const size_t len = std::max(a.size(), b.size()); + const int budget = len <= 4 ? 1 : (len <= 10 ? 2 : 3); + return d <= budget; +} + +std::string suggest(std::string_view want, const std::vector& known) { + std::string best; + int best_d = INT32_MAX; + for (const std::string& k : known) { + const int d = edit_distance(want, k); + if (d < best_d || (d == best_d && k < best)) { best_d = d; best = k; } + } + if (best.empty() || !close_enough(want, best, best_d)) return ""; + return best; +} + +const char* kind_name(int kind) { + switch (kind) { + case RAD_P_INT: return "an integer"; + case RAD_P_STR: return "a string"; + case RAD_P_RANGE: return "a range"; + case RAD_P_F64: return "a float"; + default: return "of an unknown kind"; + } +} + +} /* namespace */ + +const RadOpSchema* Registry::schema(std::string_view op) const { + auto it = schemas_.find(std::string(op)); + return it == schemas_.end() ? nullptr : it->second.schema; +} + +const Plugin* Registry::schema_owner(std::string_view op) const { + auto it = schemas_.find(std::string(op)); + return it == schemas_.end() ? nullptr : plugin(it->second.plugin); +} + +std::vector Registry::op_names() const { + std::vector out; + out.reserve(schemas_.size()); + for (const auto& kv : schemas_) out.push_back(kv.first); + /* Rows may implement an op nobody declared a schema for -- check_complete() calls that out, + * but until it is fixed the name should still show up in a near-miss search, or the author of + * the broken plugin gets told their own op does not exist. */ + for (const KernelRow& r : rows_) + if (schemas_.find(r.info->op) == schemas_.end()) out.emplace_back(r.info->op); + std::sort(out.begin(), out.end()); + out.erase(std::unique(out.begin(), out.end()), out.end()); + return out; +} + +std::string Registry::near_miss(std::string_view op) const { + return suggest(op, op_names()); +} + +int Registry::validate(std::string_view op, const RadParam* p, int n_p, std::string* err) const { + std::string sink; + if (!err) err = &sink; + err->clear(); + + const std::string name(op); + auto it = schemas_.find(name); + if (it == schemas_.end()) { + const std::string did = near_miss(op); + *err = fmt("no loaded kernel plugin declares op '%s'%s", name.c_str(), + did.empty() ? "" : fmt("; did you mean '%s'?", did.c_str()).c_str()); + return RAD_E_NOSCHEMA; + } + const RadOpSchema& s = *it->second.schema; + + std::vector keys; + keys.reserve((size_t)s.n_params); + for (int i = 0; i < s.n_params; ++i) keys.emplace_back(s.params[i].key ? s.params[i].key : ""); + + int n_ranged = 0; + std::string ranged_key; + for (int i = 0; i < n_p; ++i) { + if (!p[i].key || !p[i].key[0]) { + *err = fmt("%s: parameter %d has no name", name.c_str(), i); + return RAD_E_SCHEMA; + } + for (int j = 0; j < i; ++j) { + if (p[j].key && std::strcmp(p[i].key, p[j].key) == 0) { + *err = fmt("%s: parameter '%s' is given twice", name.c_str(), p[i].key); + return RAD_E_SCHEMA; + } + } + + const RadParamSpec* spec = nullptr; + for (int j = 0; j < s.n_params; ++j) + if (keys[(size_t)j] == p[i].key) { spec = &s.params[j]; break; } + if (!spec) { + const std::string did = suggest(p[i].key, keys); + *err = fmt("%s: no parameter '%s' in this op's schema%s", name.c_str(), p[i].key, + did.empty() ? "" : fmt("; did you mean '%s'?", did.c_str()).c_str()); + return RAD_E_SCHEMA; + } + + /* A range is an integer parameter that has not been collapsed yet, so it satisfies an + * integer slot and nothing else. */ + const bool int_ok = (p[i].kind == RAD_P_INT || p[i].kind == RAD_P_RANGE); + if (spec->type == RAD_P_INT && !int_ok) { + *err = fmt("%s: parameter '%s' is %s, but the schema says it is an integer", + name.c_str(), p[i].key, kind_name(p[i].kind)); + return RAD_E_SCHEMA; + } + if (spec->type == RAD_P_STR && p[i].kind != RAD_P_STR) { + *err = fmt("%s: parameter '%s' is %s, but the schema says it is a string", + name.c_str(), p[i].key, kind_name(p[i].kind)); + return RAD_E_SCHEMA; + } + if (spec->type == RAD_P_STR && !p[i].sval) { + *err = fmt("%s: string parameter '%s' is null", name.c_str(), p[i].key); + return RAD_E_SCHEMA; + } + /* A float slot takes a float and nothing else. An integer in it would land in `ival` while + * the kernel reads `dval`, which is a zero eps rather than a diagnostic -- exactly the + * silent-garbage class the schema exists to catch. Constraints never match on a float + * (rad_types.h), so this check is the only thing standing between the two spellings. */ + if (spec->type == RAD_P_F64 && p[i].kind != RAD_P_F64) { + *err = fmt("%s: parameter '%s' is %s, but the schema says it is a float -- declare it " + "with RAD_F64()", name.c_str(), p[i].key, kind_name(p[i].kind)); + return RAD_E_SCHEMA; + } + + if (p[i].kind == RAD_P_RANGE) { + if (p[i].ihi < p[i].ival) { + *err = fmt("%s: parameter '%s' is the empty range [%lld, %lld]", name.c_str(), + p[i].key, p[i].ival, p[i].ihi); + return RAD_E_SCHEMA; + } + if (++n_ranged == 1) ranged_key = p[i].key; + else { + /* At most one ranged parameter per op. That is what keeps the bucket-table index a + * single integer at issue, and it is a promise the run phase depends on rather + * than a limitation of the table (docs/OPS.md). */ + *err = fmt("%s: '%s' and '%s' are both ranges; an op may have at most one ranged " + "parameter", name.c_str(), ranged_key.c_str(), p[i].key); + return RAD_E_SCHEMA; + } + } + } + + for (int j = 0; j < s.n_params; ++j) { + /* RAD_REQUIRED and nothing else. RAD_DERIVED is supplied by the KERNEL, so demanding it + * from the caller would re-create the circularity it exists to break: the caller cannot + * know the block size until a kernel is resolved, and no kernel resolves until the block + * size is known (rad_abi.h, spec §7.2). A caller MAY still supply one, which pins it. */ + if (s.params[j].required != RAD_REQUIRED) continue; + bool given = false; + for (int i = 0; i < n_p && !given; ++i) given = (keys[(size_t)j] == p[i].key); + if (!given) { + *err = fmt("%s: required parameter '%s' was not given (declared by plugin '%s')", + name.c_str(), keys[(size_t)j].c_str(), it->second.plugin.c_str()); + return RAD_E_SCHEMA; + } + } + return RAD_OK; +} + +} /* namespace rad */ diff --git a/core/plugin/select.cpp b/core/plugin/select.cpp new file mode 100644 index 00000000..db9c1b96 --- /dev/null +++ b/core/plugin/select.cpp @@ -0,0 +1,436 @@ +/* select.cpp -- the constraint selector, the selection table, and the per-instance init/fini. + * spec.md §2.1 and §16. + * + * The selector answers one question: is there a kernel compiled for this geometry, in this domain, + * in the highest plugin that has one. It is a NECESSARY condition and not a sufficient one -- + * strides, contiguity, alignment and buffer sizes are properties of a call rather than of a model + * and stay in the entry point, which still rejects what it cannot run. libr4d's registry makes the + * same point at length. + */ +#include "registry.h" + +#include +#include +#include +#include +#include +#include + +namespace rad { + +namespace { + +/* True when every constraint holds. Otherwise `why` names the FIRST one that did not and what it + * wanted: "no kernel" on its own is not an answer anyone can act on, and the first failure is the + * one a reader can fix -- listing all four of a row's unmet constraints buries it. */ +bool row_matches(const KernelRow& r, const Geometry& g, const std::vector& skip, + std::string* why) { + for (int i = 0; i < r.info->n_constraints; ++i) { + const RadConstraint& c = r.info->constraints[i]; + /* A constraint on a RAD_DERIVED parameter the caller did not name is not a predicate on + * the question -- it IS the answer, read back afterwards. Matching on it would make the + * kernel unreachable by the only query anyone can ask (rad_abi.h, spec §7.2). */ + if (c.key && std::find(skip.begin(), skip.end(), c.key) != skip.end()) continue; + if (!constraint_holds(c, g)) { + if (why) *why = constraint_why(c, g); + return false; + } + } + if (why) *why = "ok"; + return true; +} + +/* The question, normalised so two spellings of the same one fold together in the table. The + * geometry is displayed as asked, because a plugin author writes the parameters in the order that + * reads best; only the fold key is sorted. */ +std::string fold_key(std::string_view op, int domain, const Geometry& g) { + const std::string q = g.str(); /* named: split_ws returns views into it */ + std::vector kv; + for (auto tok : split_ws(q)) kv.emplace_back(tok); + std::sort(kv.begin(), kv.end()); + std::string k = std::string(op) + "/" + domain_name(domain) + "/"; + for (const std::string& s : kv) { k += s; k += ';'; } + return k; +} + +} /* namespace */ + +bool kernel_constraint(const KernelRow& r, std::string_view key, int c_op, long long* out) { + if (!r.info) return false; + for (int i = 0; i < r.info->n_constraints; ++i) { + const RadConstraint& c = r.info->constraints[i]; + if (c.op != c_op || !c.key || key != c.key) continue; + if (out) *out = c.ival; + return true; + } + return false; +} + +/* ------------------------------------------------------------------ selection */ +const KernelRow* Registry::select(std::string_view op, const Geometry& g, int domain, + SelectionTrace* why, bool record, const RowFilter* accept) { + SelectionTrace local; + SelectionTrace& t = why ? *why : local; + t = SelectionTrace{}; + t.op = std::string(op); + t.query = g.str(); + t.domain = domain; + + /* The derived keys of this op that the caller did NOT supply. Derivedness is a property of the + * op's schema, so it is known here and nowhere else; a caller that supplied one anyway has + * pinned it, and it drops out of this list and matches like any other parameter. */ + std::vector derived_keys; + if (const RadOpSchema* sch = schema(op)) { + for (int i = 0; i < sch->n_params; ++i) { + if (sch->params[i].required != RAD_DERIVED || !sch->params[i].key) continue; + if (!g.has(sch->params[i].key)) derived_keys.emplace_back(sch->params[i].key); + } + } + + const std::vector* rows = rows_for(op); + const KernelRow* best = nullptr; + std::vector misses; + + if (rows) { + bool in_group = false; + int cur_order = 0; + for (const KernelRow* r : *rows) { + /* A kernel in the other domain answers a different question. It is not a candidate and + * not a refusal -- but the fact that it exists is worth carrying, because "there is a + * device kernel and no host one" is the sentence the placement planner needs (§5.1). */ + if (r->info->domain != domain) { t.other_domain_has_rows = true; continue; } + + if (!in_group || r->plugin_order != cur_order) { + /* THE HIERARCHY IS ABSOLUTE. The first plugin with any matching kernel supplies + * it; the moment we would step down to the next plugin with a winner in hand, we + * stop. A lower-priority plugin never outbids a higher one no matter how + * specialised its kernel -- that is what makes a user override an override. */ + if (best) break; + cur_order = r->plugin_order; + in_group = true; + } + + std::string whynot; + bool ok = row_matches(*r, g, derived_keys, &whynot); + if (ok && accept && *accept) { + whynot = (*accept)(*r, g); + ok = whynot.empty(); + } + if (ok) { + t.candidates.push_back({ r->plugin, r->info->name, r->info->priority, true, "ok" }); + /* SPECIFICITY IS DECLARED, NOT DERIVED: the highest priority wins, and a tie goes + * to the row declared first. Counting matched constraints would get it backwards. */ + if (!best || r->info->priority > best->info->priority) best = r; + } else { + t.candidates.push_back({ r->plugin, r->info->name, r->info->priority, false, whynot }); + if (std::find(misses.begin(), misses.end(), whynot) == misses.end()) + misses.push_back(whynot); + } + } + } + + if (best) { + t.kernel = best->info->name; + t.plugin = best->plugin; + t.priority = best->info->priority; + /* The answer to the question that could not be asked: whatever the winner's RAD_C_EQ says + * about each skipped derived key. A kernel with no EQ on one -- ref's `block_size >= 1`, + * which admits every value -- leaves it UNKNOWN rather than zero, because "any" is not a + * number and the caller has to decide rather than be handed a plausible one. */ + for (const std::string& key : derived_keys) { + SelectionTrace::DerivedParam d; + d.key = key; + d.known = kernel_constraint(*best, key, RAD_C_EQ, &d.value); + t.derived.push_back(std::move(d)); + } + } else if (!rows) { + const std::string did = near_miss(op); + t.reason = fmt("no loaded kernel plugin implements op '%s'%s", t.op.c_str(), + did.empty() ? "" : fmt("; did you mean '%s'?", did.c_str()).c_str()); + } else if (misses.empty()) { + t.reason = fmt("no %s kernel for op '%s' in any plugin", domain_name(domain), t.op.c_str()); + } else { + for (size_t i = 0; i < misses.size(); ++i) t.reason += (i ? "; " : "") + misses[i]; + } + + if (record) record_(t.op, domain, g, t); + return best; +} + +/* "gemm_nt:sk=8,mb=1;all_reduce:drain=3" -> the axes asked for `op`, or empty. Parsed on every + * resolve rather than once: resolve runs a few thousand times at startup and never again, and a + * parsed-once cache would need a mutex for a string that does not change. */ +static std::string tune_pin_for(const char* spec, std::string_view op) { + for (const char* p = spec; *p;) { + const char* semi = std::strchr(p, ';'); + const char* end = semi ? semi : p + std::strlen(p); + if (const char* colon = (const char*)std::memchr(p, ':', (size_t)(end - p))) { + if (op == std::string_view(p, (size_t)(colon - p))) + return std::string(colon + 1, (size_t)(end - colon - 1)); + } + p = semi ? semi + 1 : end; + } + return {}; +} + +/* For an error message, which is the whole value of refusing a bad pin rather than defaulting. */ +static std::string tunable_names(const RadKernelInfo* k) { + std::string s; + for (int i = 0; i < k->n_tunables; ++i) { + if (i) s += ", "; + s += k->tunables[i].key; + s += '='; + for (int j = 0; j < k->tunables[i].n_values; ++j) { + if (j) s += '|'; + s += std::to_string((long long)k->tunables[i].values[j]); + } + } + return s.empty() ? "(nothing tunable)" : s; +} + +/* Is `v` one of the values this axis declares? A cached or pinned value outside the list is not + * applied: the axis list is the kernel's statement of what it can run, and honouring a number it + * never offered is how a stale cache launches a shape the kernel cannot serve. */ +static bool axis_allows(const RadTunable& t, int64_t v) { + for (int i = 0; i < t.n_values; ++i) if (t.values[i] == v) return true; + return false; +} + +/* Does this combination survive the kernel's own cross-axis test? Null means yes. */ +static bool choice_valid(const RadKernelInfo* k, const Geometry& g, + const std::vector>& c) { + if (!k->tune_valid) return true; + std::vector cp; + cp.reserve(c.size()); + for (const auto& e : c) { + RadParam p{}; + p.key = e.first.c_str(); + p.kind = RAD_P_INT; + p.ival = e.second; + cp.push_back(p); + } + return k->tune_valid(g.params(), g.n_params(), cp.data(), (int)cp.size()) == 1; +} + +Resolved Registry::resolve(std::string_view op, const Geometry& g, int domain, SelectionTrace* why, + const RowFilter* accept) { + SelectionTrace local; + SelectionTrace& t = why ? *why : local; + + Resolved r; + r.row = select(op, g, domain, &t, true, accept); + if (!r.row) return r; + + /* The frozen geometry is the query PLUS what the kernel supplied for it. Writing the derived + * value here rather than leaving it to the caller is what makes rad_kv_block_size() and + * RadArgs.p agree: the kernel is launched with the block size it was compiled for, and the + * block manager sizes itself from the same number. */ + r.geom = g; + for (const SelectionTrace::DerivedParam& d : t.derived) + if (d.known) r.geom.set_i(d.key, d.value); + /* THE TUNED AXES. A kernel declares a SPACE (RadTunable) and this is where a point in it is + * chosen: the cache when this shape has been measured on this machine, each axis's own + * `deflt` otherwise -- so an untuned install is fast rather than broken (spec §15). The core + * owns the cache and the policy, so no plugin has to. + * + * THE KEY IS THE FROZEN GEOMETRY BEFORE THE CHOICES GO IN, which is why `geom_key` is captured + * here and the choices are folded into `geom` afterwards. rad-tune keys its rows on the + * geometry the builder recorded; a key that included its own answer could never match. It also + * has to sit after the derived parameters are written in, or the two spellings of one shape + * would never meet. + * + * An axis the cached row does not mention keeps its default, and a key the row carries that + * this kernel no longer declares is ignored. That is exactly what tunecache.h promises: a + * library may add or widen an axis between builds without throwing away the measurements that + * still apply, and a cache is an optimisation that must never stop a server. */ + r.geom_key = TuneCache::canon_geometry(r.geom); + + const RadKernelInfo* ki = r.row->info; + if (ki->n_tunables > 0) { + std::vector> chosen; + chosen.reserve((size_t)ki->n_tunables); + for (int i = 0; i < ki->n_tunables; ++i) + chosen.emplace_back(ki->tunables[i].key, ki->tunables[i].deflt); + r.tune_source = "axis defaults"; + + if (!tune_.empty()) { + if (const TuneRow* tr = tune_.find(ki->name, r.row->plugin, r.geom_key)) { + bool took = false; + for (const auto& kv : TuneCache::parse_choice(tr->choice)) + for (int i = 0; i < ki->n_tunables; ++i) + if (kv.first == ki->tunables[i].key && + axis_allows(ki->tunables[i], kv.second)) { + chosen[(size_t)i].second = kv.second; + took = true; + } + if (took) r.tune_source = "tuned " + tr->measured; + } + } + + /* RADIANCE_TUNE=op:key=value[,key=value][;op:...] pins axes for every kernel serving that + * op. It is the debug half of the cache, and it exists because an axis is where a kernel's + * fences and launch geometry live: the all-reduce's drain depth and acquire ordering are + * axes, so questions like "is the missing acquire fence why this deployment is not + * reproducible" are answerable without a rebuild. + * + * An unknown key, or a value the axis does not offer, is a HARD ERROR rather than a silent + * default: a pin that did not take is worse than no pin, because the run looks like it + * tested something. A kernel with nothing tunable is not a failed pin, though -- the same + * op is served by libr4d on the device and by libref on the host, and libref declares no + * axes for anything, so refusing here would take the host band out over a device pin. */ + if (const char* pin = std::getenv("RADIANCE_TUNE")) { + const std::string want = tune_pin_for(pin, op); + for (const auto& kv : TuneCache::parse_choice(want)) { + int idx = -1; + for (int i = 0; i < ki->n_tunables; ++i) + if (kv.first == ki->tunables[i].key) { idx = i; break; } + if (idx < 0 || !axis_allows(ki->tunables[idx], kv.second)) { + RAD_ERR("RADIANCE_TUNE asks %s=%lld of op '%s', which kernel '%s' does not " + "offer. It has: %s", kv.first.c_str(), (long long)kv.second, + std::string(op).c_str(), ki->name, tunable_names(ki).c_str()); + r.row = nullptr; + return r; + } + chosen[(size_t)idx].second = kv.second; + r.tune_source = "RADIANCE_TUNE"; + } + } + + /* A combination the kernel's own cross-axis test refuses is not launched. Falling back to + * every axis's default is the one answer that cannot be wrong here: the defaults are what + * an untuned install runs, so they are the kernel's own statement of what it can always + * do. A cache written for a different build, or a pin that is individually legal on each + * axis but not together, lands here. */ + if (!choice_valid(ki, r.geom, chosen)) { + std::vector> dflt; + for (int i = 0; i < ki->n_tunables; ++i) + dflt.emplace_back(ki->tunables[i].key, ki->tunables[i].deflt); + if (r.tune_source != "axis defaults") + RAD_WARN("kernel '%s' refuses the %s axes for %s; falling back to its defaults", + ki->name, r.tune_source.c_str(), r.geom_key.c_str()); + chosen = std::move(dflt); + r.tune_source = "axis defaults"; + } + + for (const auto& kv : chosen) r.geom.set_i(kv.first, kv.second); + r.choice = TuneCache::canon_choice(chosen); + } + + /* scratch_bytes stays 0: the scratch hook takes a RadArgs, which needs the operand tensors, + * and those belong to the builder. It sizes the arena; this layer only says which kernel. */ + return r; +} + +/* ------------------------------------------------------------------ the selection table (§16) */ +void Registry::record_(const std::string& op, int domain, const Geometry& g, + const SelectionTrace& t) { + const std::string key = fold_key(op, domain, g); + std::lock_guard lk(mu_); + for (SelectionRecord& s : log_) { + if (s.key == key) { ++s.count; return; } /* same question, therefore the same answer */ + } + SelectionRecord s; + s.op = op; + s.domain = domain; + s.query = g.str(); + s.key = key; + s.kernel = t.kernel; + s.plugin = t.plugin; + s.priority = t.priority; + s.reason = t.reason; + /* Kept apart from the query. A derived key was not part of the question -- printing it inside + * the geometry would read as something the caller asked for, and the next reader would go + * looking for the code that passed it. ":=" is the kernel answering, "?" is a winner with no + * EQ on the key, which is a hole the caller has to fill and not a value. */ + for (const SelectionTrace::DerivedParam& d : t.derived) { + if (!s.derived.empty()) s.derived += ' '; + s.derived += d.known ? fmt("%s:=%lld", d.key.c_str(), d.value) + : fmt("%s:=?", d.key.c_str()); + } + log_.push_back(std::move(s)); +} + +size_t Registry::n_selections() const { + std::lock_guard lk(mu_); + return log_.size(); +} + +void Registry::clear_selections() { + std::lock_guard lk(mu_); + log_.clear(); +} + +std::string Registry::selection_table() const { + std::lock_guard lk(mu_); + if (log_.empty()) return "selection table: the selector was never asked anything\n"; + + size_t wop = 2, wdom = 3, wq = 8; + long long total = 0; + for (const SelectionRecord& s : log_) { + wop = std::max(wop, s.op.size()); + wdom = std::max(wdom, std::strlen(domain_name(s.domain))); + wq = std::max(wq, s.query.size()); + total += s.count; + } + + std::string out = fmt("selection table -- %zu distinct questions, %lld asked\n", + log_.size(), total); + out += fmt(" %-*s %-*s %5s %-*s %s\n", (int)wop, "op", (int)wdom, "domain", "asked", + (int)wq, "geometry", "resolved"); + for (const SelectionRecord& s : log_) { + std::string got = s.kernel.empty() + ? fmt("-- none: %s", s.reason.c_str()) + : fmt("%s (%s, prio %d)%s%s", s.kernel.c_str(), s.plugin.c_str(), s.priority, + s.derived.empty() ? "" : " derived ", s.derived.c_str()); + out += fmt(" %-*s %-*s %5lld %-*s %s\n", (int)wop, s.op.c_str(), + (int)wdom, domain_name(s.domain), s.count, (int)wq, s.query.c_str(), + got.c_str()); + } + return out; +} + +/* ------------------------------------------------------------------ instances */ +/* init() once per resolved instance -- one op, one band, one domain -- with the frozen geometry, + * the rank and the world size. Some kernels have per-instance state that must be established once + * and not per launch: libr4d's all-reduce needs its peer signal buffers and IPC handles set up + * across ranks before the first call, and a kernel that JITs or loads a config table wants + * somewhere to do it that is not the hot path. */ +int Registry::init_instance(Resolved& r, int rank, int world_size) { + if (!r.row || !r.row->info) return RAD_E_INVAL; + const RadKernelInfo* k = r.row->info; + if (!k->init) { r.instance = nullptr; return RAD_OK; } + + void* inst = nullptr; + const int st = k->init(r.geom.params(), r.geom.n_params(), rank, world_size, &inst); + if (st < 0) { + /* A negative init aborts startup, and the caller names the kernel -- which it can, because + * the message below already did. Continuing would mean launching a kernel whose one-time + * setup failed, and that is a fault three frames later instead of here. */ + RAD_ERR("kernel '%s' (%s) failed to initialise for %s: %s", k->name, r.row->plugin.c_str(), + r.geom.str().c_str(), rad_strerror(st)); + return st; + } + r.instance = inst; + /* Registered even when the kernel returned null: fini pairs 1:1 with a successful init, and a + * kernel with global setup and no handle still needs its fini call. */ + std::lock_guard lk(mu_); + instances_.emplace_back(k, inst); + return RAD_OK; +} + +void Registry::fini_instances() { + std::vector> take; + { + std::lock_guard lk(mu_); + take.swap(instances_); + } + for (auto it = take.rbegin(); it != take.rend(); ++it) + if (it->first->fini) it->first->fini(it->second); +} + +size_t Registry::n_instances() const { + std::lock_guard lk(mu_); + return instances_.size(); +} + +} /* namespace rad */ diff --git a/core/plugin/testplugin/CMakeLists.txt b/core/plugin/testplugin/CMakeLists.txt new file mode 100644 index 00000000..ff81027e --- /dev/null +++ b/core/plugin/testplugin/CMakeLists.txt @@ -0,0 +1,51 @@ +# Test plugins from one source, so that plugin_test has a hierarchy to load, a schema conflict to +# refuse and a stale ABI to reject. They go under $RADIANCE_HOME/testkernels rather than kernels/, +# because the engine scans kernels/ at startup and these rows implement nothing: a test plugin that +# a real run could select is a fallback nobody knows about (spec.md §17). +# +# The two that must be refused live one directory down, so that loading testkernels/ is a clean +# load and the refusals are asked for explicitly by path. +rad_add_plugin(radtest_base testkernels SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/testplugin.cc) +target_compile_definitions(radtest_base PRIVATE RADTEST_BASE=1) + +rad_add_plugin(radtest_over testkernels SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/testplugin.cc) +target_compile_definitions(radtest_over PRIVATE RADTEST_OVER=1) + +rad_add_plugin(radtest_conflict testkernels/bad SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/testplugin.cc) +target_compile_definitions(radtest_conflict PRIVATE RADTEST_CONFLICT=1) + +rad_add_plugin(radtest_badabi testkernels/bad SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/testplugin.cc) +target_compile_definitions(radtest_badabi PRIVATE RADTEST_BADABI=1) + +# Two architecture plugins claiming one architecture id, in their own directory so that loading it +# is the whole test: the first is identified, the second is refused. +rad_add_plugin(radtest_arch testarch SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/testplugin.cc) +target_compile_definitions(radtest_arch PRIVATE RADTEST_ARCH=1) + +rad_add_plugin(radtest_arch2 testarch SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/testplugin.cc) +target_compile_definitions(radtest_arch2 PRIVATE RADTEST_ARCH2=1) + +# Two more from the same source, in a directory of their own, so that a load with NO hierarchy has +# something to be observed on. One of them declares itself a reference implementation. +# +# THE FILE NAMES ARE THE POINT. load_dir reads a directory in sorted order, so `..._a` (the +# reference) is staged first; if the loader did not pin a reference library below every other +# kernel plugin, it would keep that position and answer for every op, and the library that actually +# serves the card would never be selected. Naming them the other way round would make the test pass +# on alphabetical order alone. Its name is nobody's in particular: the rule is the declaration's. +rad_add_plugin(radtest_ord_a testkernels/order SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/testplugin.cc) +target_compile_definitions(radtest_ord_a PRIVATE RADTEST_BASE=1 RADTEST_REFERENCE=1 + RADTEST_BASE_NAME=\"radtest_reference\") + +rad_add_plugin(radtest_ord_b testkernels/order SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/testplugin.cc) +target_compile_definitions(radtest_ord_b PRIVATE RADTEST_BASE=1) + +# The KV tiers' transfer test. Unlike everything above it COMPUTES -- byte-row gather and scatter +# registered in the device domain, running on the host backend's memory -- so it lives in a +# directory of its own that only tests/mem_test.cpp loads, by path. It calls back into the device +# API for stream order, which the test executable exports. +rad_add_plugin(radtest_rows testrows SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/tierrows.cc) + +# A quantiser with a scheme of its own, which only its decode hook reads: tests/quant_test.cpp +# loads it by path to show a weight it wrote decodes through the core's decoder all the same. +rad_add_plugin(radtest_quant testquant SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/testquant.cc) diff --git a/core/plugin/testplugin/testplugin.cc b/core/plugin/testplugin/testplugin.cc new file mode 100644 index 00000000..f71df373 --- /dev/null +++ b/core/plugin/testplugin/testplugin.cc @@ -0,0 +1,429 @@ +/* testplugin.cc -- in-tree kernel plugins that exist to be loaded by tests/plugin_test.cpp. + * + * It computes nothing: every launch returns RAD_E_UNSUPPORTED, because a test kernel that returned + * RAD_OK would be a slow path nobody knows about, waiting to be selected by a real model. What it + * does have is a registry: rows that exercise every constraint operator, two plugins' worth of + * hierarchy, a priority tie, a schema conflict that must be refused, and an op with kernels at + * M<=16, M<=64 and unconstrained -- which is spec.md §2.2's worked example, so the test can assert + * the exact band table and the paragraph becomes a regression test. + * + * One source, six .so files, selected by -D: two kernel plugins that load, two that must be + * refused, and two architecture plugins that claim one id between them. The rows are worth reading + * side by side, and six near-copies of this file would drift. + * + * The extension is .cc, not .cpp, and that is load-bearing: core/CMakeLists.txt globs + * every core/plugin .cpp file into the rad_core static library, and a plugin's exports + * (rad_kernel_count and friends) do not belong inside the engine. The alternative is an + * exclusion rule in a file this component does not own. + */ +#include "rad_abi.h" + +#include +#include + +#if defined(RADTEST_ARCH) || defined(RADTEST_ARCH2) +#define RADTEST_IS_ARCH 1 +#include "rad_builder.h" +#include "rad_runtime.h" +#endif + +#if !defined(RADTEST_BASE) && !defined(RADTEST_OVER) && !defined(RADTEST_CONFLICT) && \ + !defined(RADTEST_BADABI) && !defined(RADTEST_IS_ARCH) +#define RADTEST_BASE 1 +#endif + +#define NELEM(a) (int)(sizeof(a) / sizeof((a)[0])) + +/* ------------------------------------------------------------------ hooks */ +namespace { + +int g_open_calls = 0; +int g_init_calls = 0; +int g_fini_calls = 0; + +struct TestInstance { + long long m; /* the frozen geometry's ranged value, so a test can prove which band's + * upper bound reached init */ + int rank, world; +}; + +/* Every row shares one launch, and it refuses. Nothing here can run. */ +[[maybe_unused]] int t_launch(const RadArgs* a, RadStream s) { + (void)a; (void)s; + return RAD_E_UNSUPPORTED; +} + +[[maybe_unused]] int t_init(const RadParam* p, int n_p, int rank, int world_size, void** out) { + TestInstance* inst = (TestInstance*)std::calloc(1, sizeof(TestInstance)); + if (!inst) return RAD_E_NOMEM; + inst->m = -1; + inst->rank = rank; + inst->world = world_size; + for (int i = 0; i < n_p; ++i) + if (p[i].kind == RAD_P_INT && p[i].key && std::strcmp(p[i].key, "M") == 0) + inst->m = p[i].ival; + *out = inst; + ++g_init_calls; + return RAD_OK; +} + +[[maybe_unused]] void t_fini(void* inst) { + ++g_fini_calls; + std::free(inst); +} + +/* A kernel whose one-time setup fails. A negative init aborts startup naming the kernel, and that + * path needs a kernel that takes it. */ +[[maybe_unused]] int t_init_fails(const RadParam* p, int n_p, int rank, int world_size, void** out) { + (void)p; (void)n_p; (void)rank; (void)world_size; (void)out; + return RAD_E_NOMEM; +} + +} /* namespace */ + +extern "C" { + +int radtest_open_calls(void) { return g_open_calls; } +int radtest_init_calls(void) { return g_init_calls; } +int radtest_fini_calls(void) { return g_fini_calls; } +long long radtest_instance_m(void* inst) { return inst ? ((TestInstance*)inst)->m : -1; } + +int rad_plugin_open(void) { ++g_open_calls; return RAD_OK; } + +/* ------------------------------------------------------------------ operands */ +/* Roles matter to the core (a weight operand is resolved through a handle, an output feeds the + * buffer planner); names are diagnostics only, which is why two plugins may spell them + * differently and still agree on the schema. */ +static const RadOperandSpec kOpdGemm[] = { + { "a", RAD_OPD_IN, 0 }, { "b", RAD_OPD_WEIGHT, 0 }, { "y", RAD_OPD_OUT, 0 }, +}; +static const RadOperandSpec kOpdNorm[] = { + { "x", RAD_OPD_IN, 0 }, { "w", RAD_OPD_WEIGHT, 0 }, { "y", RAD_OPD_OUT, 0 }, +}; +static const RadOperandSpec kOpdAttn[] = { + { "q", RAD_OPD_IN, 0 }, { "kv_cache", RAD_OPD_INOUT, 0 }, { "out", RAD_OPD_OUT, 0 }, +}; + +/* ------------------------------------------------------------------ schemas */ +static const RadParamSpec kPGemm[] = { + { "M", RAD_P_INT, RAD_REQUIRED }, + { "N", RAD_P_INT, RAD_REQUIRED }, + { "K", RAD_P_INT, RAD_REQUIRED }, + { "dtype", RAD_P_STR, RAD_REQUIRED }, +}; +static const RadParamSpec kPNorm[] = { + { "M", RAD_P_INT, RAD_REQUIRED }, + { "n", RAD_P_INT, RAD_REQUIRED }, + /* A float slot. Constraints never match on one; it is here so the schema check has something + * to refuse an integer spelling of. */ + { "eps", RAD_P_F64, RAD_OPTIONAL }, + { "dtype", RAD_P_STR, RAD_REQUIRED }, +}; +static const RadParamSpec kPTie[] = { + { "M", RAD_P_INT, RAD_REQUIRED }, + { "n", RAD_P_INT, RAD_REQUIRED }, +}; +static const RadParamSpec kPAttn[] = { + { "q_len", RAD_P_INT, RAD_REQUIRED }, + { "head_dim", RAD_P_INT, RAD_REQUIRED }, + { "window", RAD_P_INT, RAD_REQUIRED }, + /* Supplied by the KERNEL, which is what makes t_attn_paged reachable at all: its + * block_size == 16 would otherwise refuse every query that did not already know the answer + * (rad_abi.h RAD_DERIVED, spec §7.2). */ + { "block_size", RAD_P_INT, RAD_DERIVED }, + { "causal", RAD_P_INT, RAD_REQUIRED }, + { "n_head", RAD_P_INT, RAD_REQUIRED }, + { "kv_dtype", RAD_P_STR, RAD_REQUIRED }, +}; + +/* The conflicting spelling: same op name, no dtype. Since arguments are positional, a call built + * against this schema and served by a kernel selected against the other one is not a diagnosable + * failure -- it is silent numerical garbage, which is why the load refuses it (§2.3). */ +static const RadParamSpec kPGemmWrong[] = { + { "M", RAD_P_INT, RAD_REQUIRED }, + { "N", RAD_P_INT, RAD_REQUIRED }, + { "K", RAD_P_INT, RAD_REQUIRED }, +}; + +/* ------------------------------------------------------------------ constraints */ +/* Between them these rows use every operator the ABI has: EQ, LE, GE, DIV and IN. */ +static const RadConstraint kCGemmM16[] = { + RAD_CLE("M", 16), RAD_CDIV("K", 256), RAD_CIN("dtype", "bf16 w4a8"), +}; +static const RadConstraint kCGemmM64[] = { + RAD_CLE("M", 64), RAD_CDIV("K", 16), RAD_CIN("dtype", "bf16 w4a8"), +}; +static const RadConstraint kCNorm4096[] = { + RAD_CEQ("n", 4096), +}; +static const RadConstraint kCTie[] = { + RAD_CGE("M", 1), +}; +/* Constraint ORDER is the order the miss message reports in: the first unmet one is what a reader + * is told, so the cheapest and most identifying predicate goes first. */ +static const RadConstraint kCAttn[] = { + RAD_CEQ("head_dim", 128), RAD_CGE("window", 0), RAD_CEQ("block_size", 16), + RAD_CIN("causal", "0 1"), RAD_CLE("q_len", 16), RAD_CDIV("n_head", 4), + RAD_CIN("kv_dtype", "bf16 fp8_e4m3"), +}; +/* The other half of the derived story: a row that admits every block size and names none. ref's + * rows are exactly this -- every extent is read off the operands at launch -- so the winner has no + * RAD_C_EQ to read back and the derived key stays UNSET. "any" is not a number. */ +static const RadConstraint kCAttnAny[] = { + RAD_CEQ("head_dim", 128), RAD_CGE("block_size", 1), RAD_CIN("kv_dtype", "bf16 fp8_e4m3"), +}; +static const RadConstraint kCSkinnyM64[] = { RAD_CLE("M", 64) }; +static const RadConstraint kCSkinnyBig[] = { RAD_CGE("M", 4096) }; +static const RadConstraint kCEqM32[] = { RAD_CEQ("M", 32) }; + +/* A TUNABLE AXIS, declared the way an out-of-tree library declares one: the legal values and a + * default, not a list of pre-named combinations. `deflt` is what runs when this machine has no + * measurement for an instantiation, and the loader refuses the plugin if it is not one of the + * values (§15). */ +static const int64_t kBnValues[] = { 64, 128 }; +static const RadTunable kTGemmM64[] = { + { "bn", kBnValues, NELEM(kBnValues), 64, "columns of C one block covers" }, +}; + +/* ================================================================== radtest_base */ +#if defined(RADTEST_BASE) + +static const RadOpSchema kSchemas[] = { + { "t_gemm", kPGemm, NELEM(kPGemm), kOpdGemm, NELEM(kOpdGemm), "the §2.2 worked example" }, + { "t_norm", kPNorm, NELEM(kPNorm), kOpdNorm, NELEM(kOpdNorm), "hierarchy vs priority" }, + { "t_tie", kPTie, NELEM(kPTie), kOpdNorm, NELEM(kOpdNorm), "a declaration-order tie" }, + { "t_attn", kPAttn, NELEM(kPAttn), kOpdAttn, NELEM(kOpdAttn), "every constraint operator" }, + { "t_attn_ref", kPAttn, NELEM(kPAttn), kOpdAttn, NELEM(kOpdAttn), + "a derived key its kernel does not pin" }, + { "t_skinny", kPGemm, NELEM(kPGemm), kOpdGemm, NELEM(kOpdGemm), "a range with a hole in it" }, + { "t_eq", kPTie, NELEM(kPTie), kOpdNorm, NELEM(kOpdNorm), "an EQ band boundary" }, +}; + +static const RadKernelInfo kKernels[] = { + { .name = "t_gemm_m16", .op = "t_gemm", .family = "gemm", + .computes = "nothing; a registry row", .shape = "M <= 16, K divisible by 256", + .dtypes = "bf16 / w4a8", .domain = RAD_DOMAIN_DEVICE, .priority = 30, + .constraints = kCGemmM16, .n_constraints = NELEM(kCGemmM16), + .init = t_init, .fini = t_fini, .launch = t_launch }, + + { .name = "t_gemm_m64", .op = "t_gemm", .family = "gemm", + .computes = "nothing; a registry row", .shape = "M <= 64, K divisible by 16", + .dtypes = "bf16 / w4a8", .domain = RAD_DOMAIN_DEVICE, .priority = 20, + .constraints = kCGemmM64, .n_constraints = NELEM(kCGemmM64), + .tunables = kTGemmM64, .n_tunables = NELEM(kTGemmM64), + .init = t_init, .fini = t_fini, .launch = t_launch }, + + /* Unconstrained, and lowest priority: the prefill row that serves whatever the two skinny rows + * above it will not. It is what closes the last band of the bucket table. */ + { .name = "t_gemm_any", .op = "t_gemm", .family = "gemm", + .computes = "nothing; a registry row", .shape = "any", .dtypes = "any", + .domain = RAD_DOMAIN_DEVICE, .priority = 10, + .init = t_init, .fini = t_fini, .launch = t_launch }, + + /* A CPU kernel is an ordinary kernel with domain = host, resolved through the same hierarchy + * and the same constraints (§2.1). */ + { .name = "t_gemm_host", .op = "t_gemm", .family = "gemm", + .computes = "nothing; a registry row", .shape = "any", .dtypes = "any", + .domain = RAD_DOMAIN_HOST, .priority = 10, .launch = t_launch }, + + /* Very specialised and very high priority -- and still beaten by a plugin above it, which is + * the point of the t_norm rows. */ + { .name = "t_norm_specialised", .op = "t_norm", .family = "norm", + .computes = "nothing; a registry row", .shape = "n == 4096", .dtypes = "bf16", + .domain = RAD_DOMAIN_DEVICE, .priority = 100, + .constraints = kCNorm4096, .n_constraints = NELEM(kCNorm4096), .launch = t_launch }, + { .name = "t_norm_host", .op = "t_norm", .family = "norm", + .computes = "nothing; a registry row", .shape = "any", .dtypes = "any", + .domain = RAD_DOMAIN_HOST, .priority = 10, .launch = t_launch }, + + /* Same op, same priority, same constraints. Ties break on declaration order, so t_tie_first + * wins -- and if it ever does not, the tie rule has silently changed. */ + { .name = "t_tie_first", .op = "t_tie", .family = "norm", + .computes = "nothing; a registry row", .shape = "M >= 1", .dtypes = "any", + .domain = RAD_DOMAIN_DEVICE, .priority = 10, + .constraints = kCTie, .n_constraints = NELEM(kCTie), .launch = t_launch }, + { .name = "t_tie_second", .op = "t_tie", .family = "norm", + .computes = "nothing; a registry row", .shape = "M >= 1", .dtypes = "any", + .domain = RAD_DOMAIN_DEVICE, .priority = 10, + .constraints = kCTie, .n_constraints = NELEM(kCTie), .launch = t_launch }, + + /* Device only: nothing serves t_attn on the host, which is the asymmetric-absence case. */ + { .name = "t_attn_paged", .op = "t_attn", .family = "attn", + .computes = "nothing; a registry row", + .shape = "head_dim 128, block 16, q_len <= 16, n_head divisible by 4", + .dtypes = "bf16 / fp8_e4m3 kv", .domain = RAD_DOMAIN_DEVICE, .priority = 10, + .constraints = kCAttn, .n_constraints = NELEM(kCAttn), .launch = t_launch }, + + { .name = "t_attn_ref_any", .op = "t_attn_ref", .family = "attn", + .computes = "nothing; a registry row", .shape = "head_dim 128, any block size", + .dtypes = "bf16 / fp8_e4m3 kv", .domain = RAD_DOMAIN_DEVICE, .priority = 10, + .constraints = kCAttnAny, .n_constraints = NELEM(kCAttnAny), .launch = t_launch }, + + /* M <= 64 and M >= 4096, with nothing in between: a range with a hole in it, reported as that + * band rather than as the whole op (§2.2). */ + { .name = "t_skinny_m64", .op = "t_skinny", .family = "gemm", + .computes = "nothing; a registry row", .shape = "M <= 64", .dtypes = "any", + .domain = RAD_DOMAIN_DEVICE, .priority = 10, + .constraints = kCSkinnyM64, .n_constraints = NELEM(kCSkinnyM64), .launch = t_launch }, + { .name = "t_skinny_big", .op = "t_skinny", .family = "gemm", + .computes = "nothing; a registry row", .shape = "M >= 4096", .dtypes = "any", + .domain = RAD_DOMAIN_DEVICE, .priority = 5, + .constraints = kCSkinnyBig, .n_constraints = NELEM(kCSkinnyBig), .launch = t_launch }, + + { .name = "t_eq_m32", .op = "t_eq", .family = "norm", + .computes = "nothing; a registry row", .shape = "M == 32", .dtypes = "any", + .domain = RAD_DOMAIN_DEVICE, .priority = 10, + .constraints = kCEqM32, .n_constraints = NELEM(kCEqM32), + .init = t_init_fails, .launch = t_launch }, +}; + +/* The name is a -D so that two of these can load side by side, and one of them can declare itself + * a reference implementation -- the only way to observe the loader's rule that a reference library + * sorts below every other kernel plugin. */ +#ifndef RADTEST_BASE_NAME +#define RADTEST_BASE_NAME "radtest_base" +#endif +static const RadPluginInfo kInfo = { + RAD_PLUGIN_KERNEL, RADTEST_BASE_NAME, "0.1", + "test rows: the §2.2 band table, a priority tie, every constraint operator", "host", +}; +#ifdef RADTEST_REFERENCE +extern "C" int rad_plugin_reference(void) { return 1; } +#endif + +/* ================================================================== radtest_over */ +#elif defined(RADTEST_OVER) + +/* The same schemas, declared again with the same shape. That is expected and not an error: every + * plugin declares the ops it implements, and an override that did not would be relying on a plugin + * below it that a user may well have removed. */ +static const RadOpSchema kSchemas[] = { + { "t_gemm", kPGemm, NELEM(kPGemm), kOpdGemm, NELEM(kOpdGemm), "re-declared, same shape" }, + { "t_norm", kPNorm, NELEM(kPNorm), kOpdNorm, NELEM(kOpdNorm), "re-declared, same shape" }, +}; + +static const RadKernelInfo kKernels[] = { + /* Unconstrained and priority 1 -- as unspecialised as a row can be. Placed above + * radtest_base in the hierarchy it still wins t_norm outright, because the hierarchy is + * absolute and priority only orders rows WITHIN one plugin. */ + { .name = "t_over_norm", .op = "t_norm", .family = "norm", + .computes = "nothing; a registry row", .shape = "any", .dtypes = "any", + .domain = RAD_DOMAIN_DEVICE, .priority = 1, .launch = t_launch }, +}; + +static const RadPluginInfo kInfo = { + RAD_PLUGIN_KERNEL, "radtest_over", "0.1", + "one generic row that must still beat a specialised one below it", "host", +}; + +/* ================================================================== radtest_conflict */ +#elif defined(RADTEST_CONFLICT) + +static const RadOpSchema kSchemas[] = { + { "t_gemm", kPGemmWrong, NELEM(kPGemmWrong), kOpdGemm, NELEM(kOpdGemm), + "the same op name with a different parameter list" }, +}; + +static const RadKernelInfo kKernels[] = { + { .name = "t_conflict_gemm", .op = "t_gemm", .family = "gemm", + .computes = "nothing; a registry row", .shape = "any", .dtypes = "any", + .domain = RAD_DOMAIN_DEVICE, .priority = 1000, .launch = t_launch }, +}; + +static const RadPluginInfo kInfo = { + RAD_PLUGIN_KERNEL, "radtest_conflict", "0.1", + "declares t_gemm with a different schema; must be refused at load", "host", +}; + +/* ================================================================== radtest_arch, radtest_arch2 */ +/* Two architecture plugins claiming ONE architecture id. An architecture id is what selects the + * plugin a model is built from, so two claimants is a coin toss over which graph gets built -- + * refused at load, and the second one loses (§2.4). They export no kernel symbols at all, which is + * how the loader learns that an arch plugin is not a kernel plugin with missing exports. */ +#elif defined(RADTEST_IS_ARCH) + +static const RadPluginInfo kInfo = { + RAD_PLUGIN_ARCH, +#if defined(RADTEST_ARCH) + "radtest_arch", +#else + "radtest_arch2", +#endif + "0.1", "claims architecture id 'radtest.v1'", "host", +}; + +/* ================================================================== radtest_badabi */ +#else + +static const RadOpSchema kSchemas[] = { + { "t_gemm", kPGemm, NELEM(kPGemm), kOpdGemm, NELEM(kOpdGemm), "never registered" }, +}; + +static const RadKernelInfo kKernels[] = { + { .name = "t_badabi_gemm", .op = "t_gemm", .family = "gemm", + .computes = "nothing; a registry row", .shape = "any", .dtypes = "any", + .domain = RAD_DOMAIN_DEVICE, .priority = 1000, .launch = t_launch }, +}; + +static const RadPluginInfo kInfo = { + RAD_PLUGIN_KERNEL, "radtest_badabi", "0.1", + "reports an ABI version this engine does not speak; must be refused at load", "host", +}; + +#endif + +/* ------------------------------------------------------------------ the exports */ +#if defined(RADTEST_BADABI) +/* Deliberately wrong. A plugin that does not report exactly RAD_ABI_VERSION is refused at load, by + * name, with both versions printed. */ +uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION + 7u; } +#else +uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; } +#endif + +const RadPluginInfo* rad_plugin_info(void) { return &kInfo; } + +#if defined(RADTEST_IS_ARCH) +const char* rad_arch_id(void) { return "radtest.v1"; } +/* The other half of the selection key (spec §2.4). This plugin serves an unquantised container, + * which is what "" means. */ +const char* rad_arch_quant(void) { return ""; } +/* The core loads and identifies architecture plugins; the build component drives them. Neither + * hook is called by anything this test exercises, and declare refuses rather than pretending. */ +int rad_arch_declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { + (void)b; (void)meta; (void)ctx; + return RAD_E_UNSUPPORTED; +} +void rad_arch_step(RadCtx* c, const RadBatch* batch) { (void)c; (void)batch; } + +#if defined(RADTEST_ARCH) +/* The optional reply-format export, declared the way an out-of-tree plugin would declare its + * model's syntax: static storage, struct_size as compiled. radtest_arch2 leaves it out. */ +static const char* const kTestBreaks[] = { "" }; +static const char* const kTestTriggers[] = { "" }; +static const RadChatFormat kTestFormat = { + sizeof(RadChatFormat), "radtest-format", + "", "", kTestBreaks, 1, RAD_CHAT_THINK_FROM_PROMPT, + "", "", "", + "", "", "", "", + "", + RAD_CHAT_VALUE_CDATA, RAD_CHAT_VALUE_JSON, 0, + kTestTriggers, 1, +}; +const RadChatFormat* rad_arch_chat_format(const RadModelMeta* meta) { + (void)meta; + return &kTestFormat; +} +#endif +#else +int rad_kernel_schema_count(void) { return NELEM(kSchemas); } +const RadOpSchema* rad_kernel_schema_at(int i) { + return (i < 0 || i >= NELEM(kSchemas)) ? nullptr : &kSchemas[i]; +} +int rad_kernel_count(void) { return NELEM(kKernels); } +const RadKernelInfo* rad_kernel_at(int i) { + return (i < 0 || i >= NELEM(kKernels)) ? nullptr : &kKernels[i]; +} +#endif + +} /* extern "C" */ diff --git a/core/plugin/testplugin/testquant.cc b/core/plugin/testplugin/testquant.cc new file mode 100644 index 00000000..aba658e2 --- /dev/null +++ b/core/plugin/testplugin/testquant.cc @@ -0,0 +1,60 @@ +/* testquant.cc -- a quantiser plugin with a scheme of its own, for tests/quant_test.cpp. + * + * "radtest-halves" stores each value as the nearest multiple of one half, as an i8 code that is + * twice the value, and nothing else: one plane, no scale, a scheme the core does not define. What + * it exists to show is that a weight written that way is READ through the quantiser that wrote it + * -- enc_decode_rows asks the loaded quantisers' decode hooks for any scheme but plain and affine + * (abi/rad_quant.h) -- and that a decoder answers RAD_E_UNSUPPORTED for a scheme it did not write. + */ +#include "rad_quant.h" + +#include +#include + +namespace { + +const char kScheme[] = "radtest-halves"; + +int enc(const RadParam*, int, const RadQuantWeight* w, RadEncoding* out) { + if (w->rank < 2) return RAD_E_UNSUPPORTED; + rad_enc_clear(out); + rad_enc_copy_str(out->scheme, kScheme); + rad_enc_add_plane(out, "codes", RAD_I8, 1, 1); + return RAD_OK; +} + +int64_t row_block(const RadParam*, int, const RadQuantWeight*) { return 1; } + +int quantize(const RadParam*, int, const RadQuantWeight* w, float* src, int64_t, int64_t rows, + void* const* planes) { + int8_t* q = static_cast(planes[0]); + for (int64_t i = 0; i < rows * w->cols; ++i) { + const float v = std::nearbyint(src[i] * 2.0f); + q[i] = (int8_t)(v > 127.f ? 127.f : v < -128.f ? -128.f : v); + } + return RAD_OK; +} + +int decode(const RadEncoding* e, const RadQuantWeight* w, const void* const* planes, int64_t row0, + int64_t rows, float* out) { + if (std::strcmp(e->scheme, kScheme) != 0) return RAD_E_UNSUPPORTED; + const int8_t* q = static_cast(planes[0]) + row0 * w->cols; + for (int64_t i = 0; i < rows * w->cols; ++i) out[i] = 0.5f * (float)q[i]; + return RAD_OK; +} + +const RadQuantizerInfo kQuant[] = {{ + "radtest-halves", "the nearest multiple of one half, as twice it in i8: a scheme of its own", + nullptr, 0, enc, row_block, quantize, decode, +}}; + +const RadPluginInfo kInfo = { + RAD_PLUGIN_QUANT, "radtest_quant", "0.1", "a quantiser whose scheme only it decodes", "host", +}; + +} // namespace + +extern "C" uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; } +extern "C" const RadPluginInfo* rad_plugin_info(void) { return &kInfo; } +extern "C" int rad_quant_count(void) { return 1; } +extern "C" const RadQuantizerInfo* rad_quant_at(int i) { return i == 0 ? &kQuant[0] : nullptr; } diff --git a/core/plugin/testplugin/tierrows.cc b/core/plugin/testplugin/tierrows.cc new file mode 100644 index 00000000..250270c8 --- /dev/null +++ b/core/plugin/testplugin/tierrows.cc @@ -0,0 +1,114 @@ +/* tierrows.cc -- device-domain byte-row gather and scatter on the host backend, for the KV tiers' + * transfer test (tests/mem_test.cpp). + * + * The tiers move KV through `gather_rows` and `scatter_rows` resolved in the DEVICE domain, and the + * reference library registers those ops in the host domain only -- so without this, the one piece + * of the tier that can put another conversation's context into a restored entry (the addressing: + * layer-major strides, staging pitch, arena runs, a rank's window of a shared slot) could only be + * tested on a card. Here the host backend's memory stands in for the card's. + * + * STREAM ORDER IS KEPT BY WAITING. The host backend runs each stream on a worker thread, and a + * launch here runs on the caller's thread; draining the stream first puts the kernel exactly where + * a device launch would sit -- after everything enqueued before it and before everything enqueued + * after it returns. The test executable exports the device API for that call (tests/CMakeLists.txt). + * + * It lives in its own directory, under a name no hierarchy lists, so nothing but the test that asks + * for it by path ever loads it: a kernel that computes, registered in the device domain, is exactly + * what a real run must never select by accident. + */ +#include "rad_abi.h" +#include "rad_device.h" + +#include +#include + +#define NELEM(a) (int)(sizeof(a) / sizeof((a)[0])) + +namespace { + +/* Rows of bytes: shape[0] rows of shape[1] bytes, rows `stride[0]` bytes apart. */ +struct Rows { + char* p; + int64_t n, width, pitch; +}; +bool rows_of(const RadTensor& t, Rows* out) { + if (t.rank != 2 || t.dtype != RAD_U8 || !t.data || t.stride[1] != 1) return false; + out->p = (char*)t.data; + out->n = t.shape[0]; + out->width = t.shape[1]; + out->pitch = t.stride[0]; + return true; +} + +int copy_rows(const RadArgs* a, RadStream s, bool scatter) { + if (!a || a->n_t != 3) return RAD_E_INVAL; + if (rad_stream_sync(s) != RAD_OK) return RAD_E_DEVICE; + /* gather: pool, idx, pack. scatter: pack, idx, pool. */ + Rows pool, pack; + if (!rows_of(a->t[scatter ? 2 : 0], &pool) || !rows_of(a->t[scatter ? 0 : 2], &pack)) + return RAD_E_SHAPE; + const RadTensor& idx = a->t[1]; + if (idx.dtype != RAD_I32 || !idx.data || idx.shape[0] < pack.n || pack.width != pool.width) + return RAD_E_SHAPE; + const int32_t* ix = (const int32_t*)idx.data; + for (int64_t i = 0; i < pack.n; ++i) { + const int32_t r = ix[i]; + if (r >= pool.n) return RAD_E_INVAL; + char* row = pack.p + i * pack.pitch; + if (r < 0) { + if (!scatter) std::memset(row, 0, (size_t)pack.width); + continue; + } + char* slot = pool.p + (int64_t)r * pool.pitch; + if (scatter) std::memcpy(slot, row, (size_t)pack.width); + else std::memcpy(row, slot, (size_t)pack.width); + } + return RAD_OK; +} + +int t_gather(const RadArgs* a, RadStream s) { return copy_rows(a, s, false); } +int t_scatter(const RadArgs* a, RadStream s) { return copy_rows(a, s, true); } + +} /* namespace */ + +extern "C" { + +static const RadParamSpec kP[] = { + { "M", RAD_P_INT, RAD_REQUIRED }, { "n", RAD_P_INT, RAD_REQUIRED }, + { "dtype", RAD_P_STR, RAD_REQUIRED }, +}; +static const RadOperandSpec kGather[] = { + { "x", RAD_OPD_IN, 0 }, { "idx", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 }, +}; +static const RadOperandSpec kScatter[] = { + { "v", RAD_OPD_IN, 0 }, { "idx", RAD_OPD_IN, 0 }, { "x", RAD_OPD_INOUT, 0 }, +}; +static const RadOpSchema kSchemas[] = { + { "gather_rows", kP, NELEM(kP), kGather, NELEM(kGather), "y[i,:] = x[idx[i],:]" }, + { "scatter_rows", kP, NELEM(kP), kScatter, NELEM(kScatter), "x[idx[i],:] = v[i,:]" }, +}; +static const RadKernelInfo kKernels[] = { + { .name = "t_rows_gather", .op = "gather_rows", .family = "elem", + .computes = "byte rows, on the host backend's memory", .shape = "any", .dtypes = "u8", + .domain = RAD_DOMAIN_DEVICE, .priority = 0, .launch = t_gather }, + { .name = "t_rows_scatter", .op = "scatter_rows", .family = "elem", + .computes = "byte rows, on the host backend's memory", .shape = "any", .dtypes = "u8", + .domain = RAD_DOMAIN_DEVICE, .priority = 0, .launch = t_scatter }, +}; +static const RadPluginInfo kInfo = { + RAD_PLUGIN_KERNEL, "radtest_rows", "0.1", + "device-domain byte-row gather/scatter for the KV tier transfer test", "host", +}; + +uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; } +const RadPluginInfo* rad_plugin_info(void) { return &kInfo; } +int rad_kernel_schema_count(void) { return NELEM(kSchemas); } +const RadOpSchema* rad_kernel_schema_at(int i) { + return (i < 0 || i >= NELEM(kSchemas)) ? nullptr : &kSchemas[i]; +} +int rad_kernel_count(void) { return NELEM(kKernels); } +const RadKernelInfo* rad_kernel_at(int i) { + return (i < 0 || i >= NELEM(kKernels)) ? nullptr : &kKernels[i]; +} + +} /* extern "C" */ diff --git a/core/rad_core.h b/core/rad_core.h new file mode 100644 index 00000000..45598ccf --- /dev/null +++ b/core/rad_core.h @@ -0,0 +1,696 @@ +/* rad_core.h -- the data model shared BETWEEN core components. Each component owns its own + * header for its own methods; this file owns the structs that cross a component boundary, so + * two components cannot disagree about what a weight or a band or a request is. + * + * If you need to add a field here, add it. If you need to CHANGE one, say so loudly -- somebody + * else is reading it. + */ +#pragma once +#include "rad_internal.h" + +#include +#include +#include +#include +#include + +namespace rad { + +namespace mm { struct Item; struct PromptMedia; } + +class Registry; +class Builder; +class Program; +class Ctx; +class Arena; +class Pools; +class KVManager; +class PrefixCache; +class Scheduler; +class Planner; +class Mover; +class HeatEngine; +class Sampler; +struct GbnfProgram; +class Tokenizer; +class ChatTemplate; +class RadFile; +class Engine; + +/* ================================================================== plugin layer */ + +/* One kernel row plus where it came from. The hierarchy is absolute: the first plugin with any + * matching kernel supplies it, and a lower-priority plugin never outbids a higher one no matter + * how specialised its kernel (spec §2.1). `plugin_order` is that hierarchy position. */ +struct KernelRow { + const RadKernelInfo* info = nullptr; + std::string plugin; + int plugin_order = 0; /* 0 is highest priority */ + int index = 0; /* declaration order within the plugin */ + /* The plugin's rad_kernel_concurrent answer for this row: its launches touch nothing but + * their operands and their scratch, so one may run beside another that shares none of those + * bytes. False when the plugin does not say. */ + bool concurrent = false; + /* The row's plugin declared itself a reference implementation (RadPluginReferenceFn). */ + bool reference = false; +}; + +/* A kernel bound to one geometry, one domain and one variant, with init() already run. */ +struct Resolved { + const KernelRow* row = nullptr; + void* instance = nullptr; + /* The frozen geometry, INCLUDING the tuned axes: once selection has picked a point in the + * kernel's RadTunable space it is set here, so RadArgs.p carries it and the kernel reads `sk` + * with the same rad_args_geti() it reads `M` with. There is no variant index anywhere. */ + Geometry geom; + int64_t scratch_bytes = 0; + /* The geometry WITHOUT the tuned axes, in tunecache.h's canonical spelling. The cache keys on + * it, so it has to be captured BEFORE the choices are folded into `geom` -- otherwise the key + * would depend on the answer it is used to look up. */ + std::string geom_key; + /* The chosen axes, `key=value` comma separated and sorted -- the cache's `choice` column -- + * and where they came from: "axis defaults", "tuned " or "RADIANCE_TUNE" (spec §15). + * Both empty for a kernel with nothing to tune. */ + std::string choice; + std::string tune_source; + + explicit operator bool() const { return row != nullptr; } +}; + +/* One row of a bucket table: a band of the ranged parameter, resolved per domain. + * The bucket boundaries are the constraint values themselves -- take the union of the LE, GE and + * EQ values that candidate kernels place on the ranged parameter, and those are the bands. No + * policy was chosen by anyone (spec §2.2). */ +struct Band { + int64_t hi = 0; /* inclusive upper bound */ + Resolved dom[RAD_N_DOMAINS]; /* [RAD_DOMAIN_DEVICE], [RAD_DOMAIN_HOST] */ + std::string miss[RAD_N_DOMAINS]; /* why nothing resolved, for the report */ + + /* The band as a reader sees it -- "M <= 64", "M in (64, 512]", "any shape". Carried on + * the band rather than recomputed at each reporting site, because the exclusive lower + * bound is the previous band's hi and only the table's builder has that. */ + std::string span; +}; + +/* ================================================================== the declared program */ + +/* MAPPED IS NOT "HOST MEMORY", IT IS THE CONTAINER'S OWN MAPPING, and that is the whole of the + * difference. The other three off-device tiers all COPY: pinned and pageable allocate an arena and + * memcpy the weight into it at load, and SSD preads it a slot at a time. A mapped weight is never + * copied and occupies no pool -- the loader publishes a pointer into the mmap that + * core/format/radfile.cpp already holds, and the OS page cache decides what is resident. + * + * It exists for a weight that is tens of gigabytes and read A HANDFUL OF ROWS A TOKEN -- an + * n-gram embedding table is the shape. Every copying tier is wrong for that: staging the unit + * moves the whole table to use a few kilobytes of it, pinning it forces all of it resident on a + * host whose RAM is the same order as the table, and an arena copy wants a second copy of it + * beside the mapping that already holds one. A sparse Zipfian gather of a dozen rows out of + * hundreds of millions is exactly what a page cache is good at. + * + * Only a HOST kernel can read one -- the bytes are pageable and at no device address -- so the + * planner assigns this tier where, and only where, no device kernel for the op exists at all + * (embed_lookup_q, libavx/avx_ngram.cpp, is the one such op in this tree). */ +enum class Tier { VRAM = 0, HostPinned = 1, HostPageable = 2, SSD = 3, Mapped = 4 }; +enum class Site { Device = 0, DeviceStaged = 1, DeviceZeroCopy = 2, Host = 3 }; + +/* Tier-indexed arrays are sized by this rather than by a literal: the report, the live view and + * the planner's totals all index by (int)Tier and a fifth tier that fits in four of them is an + * out-of-bounds write that costs nothing until it costs everything. */ +constexpr int kTierCount = 5; + +const char* tier_name(Tier t); +const char* site_name(Site s); + +struct WeightInfo { + std::string name; + RadWeightDecl decl{}; + int64_t logical_bytes = 0; /* from the declared dtype and shape */ + /* An uneven shard's slice of the split dimension (rad_weight_shard_span); hi 0 is the even + * split. */ + int64_t shard_lo = 0, shard_hi = 0; + + /* WHAT IT IS A VIEW OF (RadWeightDecl::source and ::planes, spec §4.3). `enc` is the source's + * encoding as the model holds it -- or, with nothing behind the builder, plain in the declared + * dtype -- and `sel` the planes this declaration takes, in its order. `sel_rows`/`sel_cols` + * are each plane's extents for THIS RANK, which is what a layout hook is shown. */ + std::string source; + RadEncoding enc{}; + bool enc_known = false; + int32_t n_sel = 0; + int32_t sel[RAD_ENC_MAX_PLANES] = {0}; + int64_t sel_rows[RAD_ENC_MAX_PLANES] = {0}; + int64_t sel_cols[RAD_ENC_MAX_PLANES] = {0}; + + /* Filled by the layout pass: what the resolved kernel stores for it. `identity` is the + * selected plane's bytes unchanged -- the only form the file and mapped tiers can serve, + * since they read the container where it lies; `widen` is identity but for an exact widening + * (a bf16 norm read as f32) the loader performs. Otherwise the kernel at (lay_op, lay_band, + * lay_dom) relayouts it at load, as operand `lay_operand`. */ + std::string layout_tag; + bool identity = true; + bool widen = false; + int32_t lay_op = -1, lay_band = -1, lay_dom = -1, lay_operand = -1; + uint32_t stored_dtype = RAD_DT_INVALID; + uint32_t stored_rank = 0; + int64_t stored_shape[RAD_MAX_RANK] = {0}; /* what the kernel will receive. A layout + * hook may reshape -- WMMA fragment order is not the + * declared shape -- and the kernel has to be handed the + * shape it actually gets, not the logical one. */ + int64_t stored_bytes = 0; + int64_t align = RAD_ALIGN_UNIT; + + /* Filled by the planner (spec §5.3). */ + Tier tier = Tier::VRAM; + Site site = Site::Device; + int32_t slab_slot = -1; /* -1 = not slab-resident */ + + /* Filled at load. Under TP this is THIS RANK's shard, not the whole weight. */ + void* ptr = nullptr; + void* host_ptr = nullptr; + uint64_t file_offset = 0; + std::atomic generation{0}; /* bumped when the mover relocates it */ + + /* Ordering, so layer offload is a scheduling problem and not a prediction one: this is the + * first op index that reads the weight, and prefetch runs off it (spec §5). */ + int32_t first_use_op = -1; + int32_t last_use_op = -1; + + /* The atomic makes the copy hand-written, so a field added above has to be added here too. + * The weight list reallocates through this copy as the plugin declares, so a field left out + * is reset to its default on every weight declared before the last growth. */ + WeightInfo() = default; + WeightInfo(const WeightInfo& o) { *this = o; } + WeightInfo& operator=(const WeightInfo& o) { + name = o.name; decl = o.decl; logical_bytes = o.logical_bytes; + shard_lo = o.shard_lo; shard_hi = o.shard_hi; + source = o.source; enc = o.enc; enc_known = o.enc_known; n_sel = o.n_sel; + for (int i = 0; i < RAD_ENC_MAX_PLANES; ++i) { + sel[i] = o.sel[i]; sel_rows[i] = o.sel_rows[i]; sel_cols[i] = o.sel_cols[i]; + } + layout_tag = o.layout_tag; identity = o.identity; widen = o.widen; + lay_op = o.lay_op; lay_band = o.lay_band; lay_dom = o.lay_dom; lay_operand = o.lay_operand; + stored_dtype = o.stored_dtype; + stored_bytes = o.stored_bytes; align = o.align; + stored_rank = o.stored_rank; + for (int i = 0; i < RAD_MAX_RANK; ++i) stored_shape[i] = o.stored_shape[i]; + tier = o.tier; site = o.site; slab_slot = o.slab_slot; + ptr = o.ptr; host_ptr = o.host_ptr; file_offset = o.file_offset; + generation.store(o.generation.load()); + first_use_op = o.first_use_op; last_use_op = o.last_use_op; + return *this; + } +}; + +/* THIS RANK'S SELECTED PLANES AS A LAYOUT HOOK SEES THEM: dense rank-2 geometry, `data` null + * unless the caller fills it. One definition, because the builder asks the hook with it at + * declare and the runtime asks again before moving an op to another domain, and the two + * questions have to be the same question. */ +inline void weight_planes(const WeightInfo& w, RadTensor* t) { + for (int k = 0; k < w.n_sel; ++k) { + t[k] = RadTensor{}; + t[k].dtype = w.enc.plane[w.sel[k]].dtype; + t[k].rank = 2; + t[k].shape[0] = w.sel_rows[k]; + t[k].shape[1] = w.sel_cols[k]; + t[k].stride[0] = w.sel_cols[k]; + t[k].stride[1] = 1; + } +} + +/* CAN THE BYTES BE READ WHERE THEY LIE IN THE CONTAINER -- the file tier's O_DIRECT stage, the + * mapped tier's pointer? Only when they are the selected plane's bytes unchanged and this rank + * holds all of it: a relayout has no place in the file that already looks the way the kernel + * reads it, and a column shard is not one range of it. */ +inline bool weight_file_direct(const WeightInfo& w, int world_size) { + return w.identity && !w.widen && (w.decl.shard == RAD_SHARD_NONE || world_size <= 1); +} + +struct BufferInfo { + std::string name; + RadBufDecl decl{}; + int64_t bytes = 0; + + /* From the buffer plan: liveness over the declared op list, and the arena offset the plan + * assigned. Two transients whose lives do not overlap share storage (spec §3.1). */ + int32_t first_def = -1; + int32_t last_use = -1; + int64_t arena_offset = -1; + void* ptr = nullptr; +}; + +struct OpInfo { + std::string op; + Geometry base; /* the declared params, ranges NOT collapsed */ + std::string ranged_key; /* "" if none */ + int64_t range_lo = 0, range_hi = 0; + std::vector bands; + std::vector weights; + /* Which SCHEMA OPERAND POSITION each declared weight belongs to, parallel to `weights`. + * + * It is NOT the index. The n-th declared weight is not the n-th operand whose role is + * RAD_OPD_WEIGHT, because RAD_OPD_WTAB lets one operand position consume a whole RUN of + * declared weights (a MoE layer's experts), so the mapping is many-to-one. Recorded once at + * declare rather than recomputed at each site that needs it: the recomputation is easy to get + * wrong, and one recorded answer is one the sites cannot disagree about. */ + std::vector weight_opd; + const RadOpSchema* schema = nullptr; + int32_t index = 0; /* position in the declared order */ + bool issued = false; /* did the run phase ever issue it */ +}; + +struct KVGroupInfo { + std::string name; + RadKVGroupDecl decl{}; + int64_t block_size = 0; /* taken off the resolved attention kernel, not chosen */ + int64_t bytes_per_block = 0; + int64_t bytes_per_state = 0; /* linear/conv: per sequence */ + std::vector layers; +}; + +/* Everything declare produced. The core owns it; the plugin only ever sees handles into it. */ +class Program { +public: + std::vector weights; /* index 0 is a sentinel: handles are 1-based */ + std::vector buffers; + std::vector ops; + std::vector kv_groups; + std::vector name_map; + std::vector notes; + + RadBuildCtx ctx{}; + RadModelMeta meta{}; + + /* The buffer the plugin named as this step's logits (rad_declare_logits). Zero when the + * plugin declared none, which is what an encoder-only or embedding-only plugin does on + * purpose -- the engine refuses to SERVE such a program and says so at startup, rather + * than discovering at the first step that there is nothing to sample. */ + rad_buf logits_buf = 0; + + /* THE DRAFT HEAD THIS PLUGIN DECLARED (rad_declare_drafter). `kind == RAD_DRAFT_NONE` when + * it declared none, which is the normal case -- the engine then speculates with the + * scheduler's prompt-lookup drafter or not at all. `name` is kept beside the decl because + * RadDrafterDecl::name points into the plugin's own storage. */ + RadDrafterDecl drafter{}; + std::string drafter_name; + + /* THE MEDIA ENCODER THIS PLUGIN DECLARED (rad_declare_encoder). `modalities == 0` when it + * declared none, which is every text-only program and every deployment that asked for no + * media (RadBuildCtx::max_enc_patches 0). `encoder_name` for the reason `drafter_name` is. */ + RadEncoderDecl encoder{}; + std::string encoder_name; + + /* Two arenas, because a host-site activation cannot index device memory. The buffer plan + * colours the domains SEPARATELY -- a transient may share storage only with a transient in the + * same domain -- so each of these is a high-water mark in its own offset space and + * BufferInfo::arena_offset is relative to the arena of that buffer's declared domain. Both are + * sized for max_tok, which is the worst step (spec §3.1). */ + int64_t arena_bytes = 0; /* RAD_DOMAIN_DEVICE */ + /* Where the device arena's TRANSIENTS start: everything below is PERSIST and DERIVED, at the + * same offset at every size a step can be, and everything above is the part a smaller step + * packs smaller (core/build/rad_bufplan.cpp, plan_level). */ + int64_t arena_fixed_bytes = 0; + /* THE PREFILL STAGING REGION, above every buffer the plan placed: where a step at the full + * plan copies a routed layer's non-resident experts ahead of the layer (core/place/stager.h). + * Sized by the VRAM budget, appended by the engine after it, and part of the top of the arena + * that the smaller levels lend to the expert slab. -1 / 0 where there is none. */ + int64_t arena_stage_off = -1; + int64_t arena_stage_bytes = 0; + int64_t host_arena_bytes = 0; /* RAD_DOMAIN_HOST */ + int64_t scratch_bytes = 0; /* the largest single kernel scratch requirement */ + /* How many scratch regions of that size the arena holds: one per lane the program runs. + * Every kernel on a stream is handed the same region, which its in-order launches make safe; + * a second lane is a second stream, and a region both lanes wrote would take two kernels' + * partials at once. Two when the architecture declared a buffer rad_buf_concurrent. */ + int32_t scratch_regions = 1; + + /* Everything that resolved to nothing, reported whole rather than the first failure at the + * top (spec §3.1). + * + * STRUCTURED, not a pre-formatted sentence, because the two domains want two different + * reports and one flat list of strings cannot give them. A DEVICE miss is a hole a request + * will fall into and deserves its own line; a HOST miss removes one placement option for one + * op and deserves a line per OP, not per band. A flat list of strings leaves the reporting + * site able only to print all of them, and a deep model at tp2 then opens with thousands of + * lines of `E` -- every one of them expected, and a real device hole invisible among them. */ + struct Miss { + std::string op; + std::string geom; /* the band's display geometry */ + std::string span; /* the band, as Band::span */ + std::string why; + int domain = 0; /* RAD_DOMAIN_DEVICE | RAD_DOMAIN_HOST */ + std::string line() const; /* "op geometry [domain] -> why", the full-detail rendering */ + }; + std::vector misses; + + /* Every (kernel, shape) pair rad-tune would need to benchmark (spec §15). */ + /* `info` is the kernel's own row, so rad-tune can read its RadTunable axes and expand the + * cross product itself. A count would not do: the tuner has to know the KEYS and their legal + * values to build a candidate, and the validity predicate to discard the ones this geometry + * cannot run. Plugins outlive the Program, so the pointer is good for the process. */ + /* ONE PER KERNEL INSTANTIATION: the kernel, the plugin it came from, and the input parameters + * it was resolved at. `geom` is what a launch is handed and therefore CARRIES the axis + * defaults the selector folded in -- a tuner overrides them per candidate with set_i. + * `geom_key` is the instantiation WITHOUT them, in tunecache.h's canonical spelling, and it is + * the cache key: the selector looks an instantiation up before it knows what to choose, so a + * key that included the choice could never be found. */ + struct TuneRequest { + std::string kernel, plugin; + Geometry geom; + std::string geom_key; + const RadKernelInfo* info = nullptr; + }; + std::vector tune_requests; + + WeightInfo* weight(rad_weight h) { return h && h < weights.size() ? &weights[h] : nullptr; } + BufferInfo* buffer(rad_buf h) { return h && h < buffers.size() ? &buffers[h] : nullptr; } + OpInfo* op(rad_op h) { return h && h < ops.size() ? &ops[h] : nullptr; } + +}; + +/* ================================================================== requests */ + +enum class ReqState { Waiting, Running, Preempted, Finished, Failed, Cancelled }; + +struct SamplingParams { + float temp = 1.0f; + int top_k = 0; /* 0 = off */ + float top_p = 1.0f; + float min_p = 0.0f; + float typical_p = 1.0f; + float rep_penalty = 1.0f; + float freq_penalty = 0.0f; + float pres_penalty = 0.0f; + int penalty_last_n = 64; + float dry_multiplier = 0.0f; + float dry_base = 1.75f; + int dry_allowed_length = 2; + int dry_penalty_last_n = -1; + float xtc_probability = 0.0f; + float xtc_threshold = 0.1f; + uint64_t seed = 0; + bool greedy() const { return top_k == 1 || temp <= 0.0f; } + std::string grammar; /* GBNF, or "" */ + std::vector dry_seq_breakers; + + /* A LAZY GRAMMAR CONSTRAINS NOTHING UNTIL A TRIGGER FIRES, and that is the only shape in + * which a tool-calling chat template can be enforced: the reply is free prose until the + * model starts writing a call, and grammar-shaped from there. Without this a request that + * carries `tools` would be constrained to emit a tool call and nothing else, so a lazy + * grammar arriving as a non-lazy one is not a small difference -- it is a model that can no + * longer answer in words. The trigger types are common_grammar_trigger_type's, kept as ints + * because rad_core.h does not include the lift: 0 token, 1 word, 2 pattern, 3 pattern-full. + * Resolving a word or a token to vocabulary ids happens in the sampler, which is the layer + * that has the vocabulary. */ + struct GrammarTrigger { int type = 0; std::string value; }; + bool grammar_lazy = false; + std::vector grammar_triggers; + + /* Text the grammar has already seen: a chat template's grammar describes the whole assistant + * turn, generation prompt included, but those bytes are in the prompt rather than in what is + * about to be sampled. See GrammarSpec::prefix in core/sample/grammar.h. */ + std::string grammar_prefix; + + /* `grammar` COMPILED, by the thread that admitted the request (core/sample/gbnf.h, + * gbnf_compile). Compiling a grammar builds its mask plan, which is host work in the tens to + * hundreds of milliseconds, and the sampler starts a request on the scheduler thread with + * every other request's step waiting on it. Holding the program here keeps it findable by + * the sampler for as long as the request lives, so starting the request there is a lookup. + * Null for a request that was not admitted through the server; the sampler then compiles. */ + std::shared_ptr grammar_program; +}; + +struct Request { + uint64_t id = 0; + std::vector prompt; + std::vector output; + SamplingParams sp; + int32_t max_tokens = 0; + std::vector stop; + /* GENERATE PAST THE END-OF-TEXT TOKEN, to max_tokens. It exists so a caller can ask for a + * request whose LENGTH IS THE ONE IT ASKED FOR. Without it the length is the model's opinion + * and varies from run to run on the same prompt, so a steady-state decode measurement over + * such a request may be measuring a mostly idle engine, and its variance reads as a + * difference between whatever was being compared. + * + * It ignores the EOS TOKEN and nothing else: `stop` strings and max_tokens still end a + * request, which is vLLM's meaning of the field and the one a client already expects. */ + bool ignore_eos = false; + int priority = 0; + bool stream = false; + + ReqState state = ReqState::Waiting; + int32_t n_computed = 0; /* prompt tokens already in the KV */ + int32_t n_cached = 0; /* of those, how many came from the prefix cache */ + std::vector blocks; /* per KV group, flattened by group offset */ + int32_t state_slot = -1; /* linear/conv state slot */ + + /* THE MEDIA THIS PROMPT CARRIES, null for a text prompt: each item's patches, where its + * token run sits in `prompt`, the rotary layout those runs give the prompt, and -- once the + * encoder has run -- the rows that replace the placeholders' embeddings (core/mm). */ + std::shared_ptr media; + + int32_t n_draft = 0; /* speculative window this step */ + /* AND THE PROPOSAL ITSELF, because masking a speculative window needs the tokens and not + * just the count: Sampler::build_step walks a constraining grammar over these to mask the + * position behind each one, then rewinds. Points into the scheduler's own array for this + * request -- SchedReq owns this Request, so it outlives it -- and is written beside n_draft, + * in the same two places, for the reason the comment there gives. Null when n_draft is 0. */ + const int32_t* draft = nullptr; + int32_t n_accepted = 0; /* from the previous verify */ + + /* MAY THIS REQUEST BE SPECULATED ON AT ALL. Written by the engine after every step, read by + * the scheduler when it sizes the next one. One thing clears it, and it is a property the + * scheduler cannot see for itself: its grammar is constraining right now. The mask for draft + * position i depends on which of 0..i-1 were accepted, and the host automaton cannot know + * that before the verify runs. A LAZY grammar clears this only once its trigger fires, so a + * tool-calling request speculates through its prose and stops the moment it starts writing + * the call. + * + * TEMPERATURE DOES NOT CLEAR IT. A sampled target does not need rejection sampling to stay + * exact: acceptance compares against the token the target itself drew, and the sampler gives + * every verified position its own RNG coordinate. See Engine::collect_step. + * + * It is a flag rather than a call because there are two drafters and an n-gram fallback inside + * step() itself, and every one of them has to obey: the fallback fills any proposal the others + * left empty, so guarding only the drafters guards nothing. */ + bool may_speculate = true; + /* AND WHETHER THAT ANSWER CAN CHANGE AT A COMMIT, which only a grammar that cannot rewind + * makes it do. A step issued ahead is sized before the commit in front of it, so the scheduler + * issues ahead for a request only when this is set. Written by the engine when the sampler + * starts the request (Sampler::speculation_fixed); false until then. */ + bool speculation_fixed = false; + + /* A LOGITS ROW AT EVERY PROMPT POSITION, not only at the last: each trunk step that carries + * this request's prompt names all of its tokens in `out_ids`, after the rows the sampler + * reads, and the engine hands them to the KL scorer (core/kld.h). Only the --kld mode sets + * it; the logits buffer is sized for it there and nowhere else. */ + bool score = false; + + std::string finish_reason; + void* sink = nullptr; /* the server's per-request stream sink */ +}; + +/* ================================================================== engine config */ + +struct Config { + std::string model; /* path to the .rad */ + std::string radiance_home; + std::vector kernel_hierarchy; /* ordered; first wins */ + + int tp = 1; + /* THE TENSOR-PARALLEL WIRE, and it is a deployment choice rather than a tuning one. 1 is the + * exact bf16 all-reduce. 0 accepts a LOSSY wire: at two ranks libr4d serves a + * Walsh-Hadamard-rotated 6-bit payload -- 6 bits an element plus a bf16 scale per group of + * 64, against 16 bits an element -- so the message a prefill chunk pushes across PCIe drops + * by 2.4x. The sum a rank receives is then not the sum it would have received and no check + * downstream can tell, which is why it is a named flag and not a heuristic. */ + int tp_wire_exact = 1; /* --tp-wire exact|wht6 */ + /* WHERE THE LOSSY WIRE STARTS PAYING, in KiB of one all-reduce message. Compression only wins + * once the transfer is bandwidth-bound: a decode step all-reduces a handful of residual rows + * and the exact kernel already moves that at most of what the link delivers, so rotating it + * costs more than the bytes it saves. A prefill chunk's message is orders of magnitude larger + * and is squarely on the wire. Below this floor `--tp-wire wht6` therefore serves the message + * EXACTLY -- which also means a decode-only serve sees no quality change from the flag at all. + * + * 128 KiB IS THE KNEE. A decode step's message scales with the number of sequences in the + * batch, so concurrency decides which side of the floor a step lands on. Compressing pays for + * every message above the floor and costs on the smallest ones, and 128 KiB is the smallest + * floor that compresses everything which benefits while leaving single-sequence decode + * exact. */ + int64_t tp_wire_min_kb = 128; /* --tp-wire-min-kb */ + int64_t max_tok = 8192; /* --max-num-batched-tokens */ + int64_t max_seqs = 256; + int64_t max_ctx = 0; /* 0 = the model's training context */ + + /* THE OPERATOR STATES A BUDGET OR THE ENGINE DERIVES ONE FROM THE CARD, AND EITHER WAY IT IS + * STATED IN FULL BEFORE ANYTHING IS ALLOCATED. + * + * Spec §6 forbids a derived budget because a budget derived from the FREE VRAM at startup is + * a benchmark that moves when a desktop opens a window. What it does not forbid is arithmetic + * on numbers that are all known and all printed: the card total is a fixed property, every + * non-pool allocation this engine makes is computed from the program before it is made, and + * what the driver already holds is measured rather than assumed. core/mem/vram_budget.cpp does + * that sum and writes the answer back into the two fields below, so every consumer downstream + * -- the planner, the KV manager, the pool report -- reads one resolved number and there is no + * second place for them to disagree. + * + * Zero means "derive"; a stated --vram-weights-mib / --vram-kv-mib still wins outright. */ + int64_t vram_weights_mib = 0; + int64_t vram_kv_mib = 0; + int64_t gpu_headroom_mib = 96; /* --gpu-headroom, left unclaimed on every card */ + /* --kv-cache-dtype bf16|fp8. fp8 is an E4M3 cache with per-(sequence, head) descales, and it + * halves what a token of context costs -- which at a production context is most of the KV + * pool. It is a real quantisation and the model computes a slightly different function with + * it, so it is stated rather than inferred, and bf16 is the default. + * + * TWO VALUES AND NOT THREE. An "auto" that resolved to bf16 everywhere in this tree would be + * a third name for the second one, and a flag whose values are not all distinct is a flag + * whose log line cannot be read back. */ + std::string kv_cache_dtype = "bf16"; + double expert_cache_ratio = 0.75; /* --expert-vs-cache-ratio, weights vs KV of the remainder */ + /* SET BY THE RESOLVER, NOT BY A FLAG. vram_budget_resolve writes the two budgets above into + * this config, which erases the only evidence of whether they were stated or derived -- and + * Pools needs that to know whether unspent VRAM is a mis-stated budget worth warning about or + * a split it made itself and already printed a receipt for. */ + bool vram_budget_derived = false; + int64_t host_pool_mib = 0; + /* THE FILE TIER FOR WEIGHTS: what fits neither the VRAM slab nor the pinned host pool is read + * from the container itself, with O_DIRECT, ahead of the ops that read it -- a scheduled unit by + * the exact prefetch, a routed expert a routed layer at a time. Off unless asked for, because a + * weight served from disk is a step paced by the drive: a budget that spills there by accident + * is a server that is correct and several orders of magnitude slow. The tier needs no directory + * of its own; the container is the file. */ + bool weights_disk_tier = false; + + std::string placement = "auto"; /* all_vram | layer_offload | expert_tiered | auto */ + bool deterministic = false; + int64_t checkpoint_interval = 2048; /* linear-state checkpoints (spec §7.3) */ + /* HOW MANY LINEAR-STATE SNAPSHOTS THE SERVER MAY HOLD AT ONCE -- a CAP and not a charge. + * The slots are address space in the KV pool and are backed as they are handed out, so a + * run that writes no snapshot pays nothing for them and one holding two pays for two. What + * it still bounds is the ADDRESS SPACE: a slot is a sizeable fraction of a gigabyte on a + * linear-attention model, and the range it reserves is range the paged groups do not get, + * so raising this trades addressable context rather than VRAM (spec 7.3, 19.1). */ + int64_t checkpoint_slots = 8; + bool prefix_cache = true; + /* geometric-backoff | tip-only | keep-all. §19.1 records the default as a GUESS until there is + * a workload to measure, and core/mem/prefix.h ships the two ends of the trade beside it for + * exactly that measurement -- which needs a way to select them. */ + std::string checkpoint_policy = "geometric-backoff"; + + /* ---------------- IDLE SESSION TIERS (spec §7.3) ---------------- + * + * A finished turn leaves its prefix in the cache holding KV blocks, which is what makes the + * next turn cheap. Those blocks are the most valuable thing in the pool while a session is + * live and the least valuable thing in it once the session stops. With a host tier, a + * finished conversation is COPIED to host memory at once and its VRAM given up the moment + * something wants it -- the expert slab's loan, or a request -- so no threshold decides when + * it leaves the card: the copy makes leaving free. With a disk tier every host copy is copied + * on to disk too, so a full host tier gives the oldest slots up for nothing in the same way. + * + * Moving is worth it because the alternative is a re-prefill. Recovering a 200K-token turn + * costs a copy over PCIe; recomputing it costs minutes. The two are not the same order. + * + * CAPACITY IS WHAT TURNS THEM ON. Nothing is copied until the host tier has a size: a tier of + * zero bytes holds nothing, so the feature is off until an operator says how much memory and + * how much disk it may have. */ + int64_t prefix_cache_host_mib = 0; /* the host tier's size. 0 is off */ + int64_t prefix_cache_disk_mib = 0; /* the disk tier's size. 0 is off */ + /* WHERE THE DISK TIER LIVES, and a flag of its own rather than a second meaning for + * --weights-disk-tier. That one is the WEIGHT planner's permission to place weights on the file + * tier -- it reads the container, needs pinned staging, and refuses startup without it. The + * two have nothing in common but the word "disk", and a shared flag would make asking for a KV + * cache also ask for weight offload, which fails for want of a host pool nobody wanted. */ + std::string prefix_cache_dir; + + /* THE CACHE ALWAYS LENDS AND THERE IS NO FLAG FOR IT. It keeps the blocks it is using plus a + * buffer it derives, and lends the rest to the expert plane at the addresses it already owns; + * see core/mem/kv.h. The buffer's right size is a property of the workload (a prefill chunk, + * or the largest recent shortfall) that nobody can state in advance, which is why it is + * derived rather than a number to set. + * + * The loan allocates nothing, so it does not touch --gpu-headroom-mib: that reserve stays what + * a card keeps for the things this engine does not allocate -- chief among them a kernel's + * code object, which HIP loads on the kernel's FIRST LAUNCH and not at startup, and which + * faults inside the HIP runtime rather than returning an error when there is no room. */ + + /* The speculative window, and the whole of the draft policy: the depth is constant and this + * is it. See core/sched/draft.h. */ + /* -1 is `auto`: engine_bringup asks rad_arch_probe for the depth THIS container's drafter was + * trained at, and a container with no draft head resolves to 0 with a line saying so. + * + * IT DEFAULTS TO AUTO BECAUSE MERGING A DRAFTER IS THE STATEMENT OF INTENT. rad-kbench and + * rad-tune read the container's own operating point; a serving engine that defaulted to off + * would leave a deployment that forgot the flag paying for a draft head at convert time, + * paying for it again in VRAM, and then running at one token a step -- a small fraction of + * the throughput the same container gives at its declared depth. */ + int n_spec = -1; /* --num-speculative-tokens; -1 = auto, 0 = off */ + + /* ---------------- KL DIVERGENCE AGAINST A REFERENCE (core/kld.h) ---------------- + * + * A MODE, LIKE --debug-graph: the engine starts as it would to serve, then runs a fixed + * corpus through prefill instead of listening, with a full-vocabulary logits row at every + * scored position. `--kld-record DIR` makes THIS model the yardstick and writes its + * log-probabilities to DIR once; `--kld-ref DIR` scores this model against what is there, and + * only the candidate's own logits are computed. Exactly one of the two. */ + std::string kld_record; /* --kld-record DIR */ + std::string kld_ref; /* --kld-ref DIR */ + std::string kld_corpus; /* --kld-corpus FILE, read by --kld-record only */ + std::string kld_out; /* --kld-out FILE: the report as JSON, rows beside it */ + bool kld() const { return !kld_record.empty() || !kld_ref.empty(); } + + /* --mm-max-patches: the most patches one encoder pass carries, which bounds the largest image + * (one image is one pass) and sizes the encoder's activations. -1 is `auto`: the default below + * when the container carries a vision tower and 0 when it does not. 0 serves text only and + * keeps a tower the container carries off the card. */ + int64_t mm_max_patches = -1; + + std::string host = "0.0.0.0"; + /* The chat endpoint's default `reasoning_effort`, empty for the template's own default. + * Passed through verbatim: the legal set belongs to the template, not to us. */ + std::string reasoning_effort; + int port = 8000; + /* --api-key: the bearer key every request but the probes and the dashboard page must carry. + * Empty serves without one. */ + std::string api_key; + + /* WHAT A REQUEST THAT SENDS NO SAMPLER SETTINGS IS SERVED WITH. + * + * A checkpoint states the sampling it was tuned for, and serving it at anything else is a + * different model. Left alone these are resolved from the container and from the + * `generation_config.json` beside it (resolve_sampling_defaults in engine.cpp); set, they win over + * both, which is what makes a deployment able to pin a sampler a container gets wrong. + * + * -1 IS "NOT SET HERE" RATHER THAN A VALUE, because every one of these has a legal setting + * that would otherwise be indistinguishable from silence: 0 is a real temperature (greedy), + * 0 is a real top_k (off) and 0 is a real min_p. A flag that cannot say "unset" cannot have + * anything resolved underneath it. */ + float sample_temp = -1.0f; + int sample_top_k = -1; + float sample_top_p = -1.0f; + float sample_min_p = -1.0f; + /* An operator-supplied generation_config.json, overriding the search described above. */ + std::string generation_config; + + bool debug_graph = false; + bool debug_selection = false; + bool debug_placement = false; + bool profile_ops = false; + /* --live: the live view (spec §16). Off by default like everything else in that section. */ + bool live_view = false; + + /* libref is the ORACLE and the last resort, not a deployment. An op silently falling + * back to it is a model running orders of magnitude below the machine with nothing in the + * output to say so, so it is refused unless this says otherwise -- deliberately, and by a + * flag with `debug` in its name (startup.h, rad_gate_reference_kernels). */ + bool accept_reference_kernels = false; +}; + +} /* namespace rad */ + +/* Declared here because config.cpp is owned by the engine, and every tool parses the same flags + * so that `rad-info --model X` and `radiance --model X` cannot disagree about what a flag means. */ +namespace rad { +int config_parse(int argc, char** argv, Config* c); +void config_usage(const char* argv0); +} diff --git a/core/rad_internal.h b/core/rad_internal.h new file mode 100644 index 00000000..09390b9d --- /dev/null +++ b/core/rad_internal.h @@ -0,0 +1,177 @@ +/* rad_internal.h -- shared by everything under core/, tools/ and tests/. NOT installed and NOT + * visible to plugins: plugins see abi/ and nothing else. C++20 is fine here. + */ +#pragma once +#include "rad_abi.h" +#include "rad_device.h" +#include "rad_builder.h" +#include "rad_runtime.h" +#include "rad_format.h" + +#include +#include +#include +#include +#include +#include + +namespace rad { + +/* ------------------------------------------------------------------ logging */ +/* Normal operation is a few lines. Everything verbose is off by default (spec §16). */ +enum class Log { Error = 0, Warn = 1, Info = 2, Debug = 3, Trace = 4 }; + +void log_set_level(Log l); +Log log_level(); +void log_emit(Log l, const char* file, int line, const char* fmt, ...) + __attribute__((format(printf, 4, 5))); + +/* WHICH RANK IS SPEAKING. + * + * Every per-rank component -- the pools, the planner, the mover, the sampler -- prints the same + * sentence once per rank, so with nothing to distinguish them a tp2 startup prints each of those + * lines twice with no way to tell which card it is about. The tag is a SCOPE rather than + * an argument because the components doing the printing are three layers down, and a rank + * threaded through every log call is a rank that will be missing from the next one. + * + * Off unless log_rank_tags(true) is called: at tp 1 there is nothing to disambiguate, and every + * tool that is not the engine has one rank by construction. */ +void log_rank_tags(bool on); + +class LogRank { +public: + explicit LogRank(int rank); + ~LogRank(); + LogRank(const LogRank&) = delete; + LogRank& operator=(const LogRank&) = delete; +private: + int prev_; +}; + +#define RAD_LOG(lvl, ...) \ + do { if ((int)::rad::Log::lvl <= (int)::rad::log_level()) \ + ::rad::log_emit(::rad::Log::lvl, __FILE__, __LINE__, __VA_ARGS__); } while (0) + +#define RAD_ERR(...) RAD_LOG(Error, __VA_ARGS__) +#define RAD_WARN(...) RAD_LOG(Warn, __VA_ARGS__) +#define RAD_INFO(...) RAD_LOG(Info, __VA_ARGS__) +#define RAD_DEBUG(...) RAD_LOG(Debug, __VA_ARGS__) +#define RAD_TRACE(...) RAD_LOG(Trace, __VA_ARGS__) + +/* The same with the level as a VALUE rather than an enumerator name, for the sites where whether + * something is a warning depends on what was found. */ +#define RAD_LOG_AT(lvl, ...) \ + do { ::rad::Log _l = (lvl); \ + if ((int)_l <= (int)::rad::log_level()) \ + ::rad::log_emit(_l, __FILE__, __LINE__, __VA_ARGS__); } while (0) + +/* Propagate a negative status, logging where it came from. */ +#define RAD_TRY(expr) \ + do { int _s = (expr); \ + if (_s < 0) { RAD_DEBUG("%s -> %s", #expr, rad_strerror(_s)); return _s; } } while (0) + +/* An unrecoverable condition: a device fault, a corrupt container, an invariant broken. Prints + * and exits non-zero rather than serving from a wedged queue (spec §17). */ +[[noreturn]] void fatal(const char* fmt, ...) __attribute__((format(printf, 1, 2))); + +/* ------------------------------------------------------------------ small helpers */ +std::string fmt(const char* f, ...) __attribute__((format(printf, 1, 2))); + +inline int64_t align_up(int64_t v, int64_t a) { return (v + a - 1) / a * a; } + +/* Human-readable byte counts, for every report that prints a size. */ +std::string humanb(int64_t bytes); + +/* ONE MONOTONIC CLOCK, so that everything reasoning about elapsed time is reasoning about the + * same elapsed time. The idle-session tiers write a timestamp when an entry is used and read + * one when deciding what has gone cold; those two calls live in different translation units, + * and two clocks there would make the thresholds mean nothing in particular. Monotonic and + * not wall time: a tier that demoted an hour of sessions because NTP stepped the clock would + * be correct by its own arithmetic and wrong by any other measure. */ +uint64_t rad_mono_ns(); + +/* Split on whitespace -- what RAD_C_IN's set is encoded as. */ +std::vector split_ws(std::string_view s); + +/* ------------------------------------------------------------------ geometry */ +/* A resolved parameter set: the geometry after ranges are collapsed to a band's upper bound. + * Owns its strings, because a RadParam's char* may point into a plugin the core outlives. */ +class Geometry { +public: + Geometry() = default; + + /* The cached RadParam view holds char* into THIS object's own strings. An implicit copy would + * carry those pointers into the copy along with dirty_ = false, so the copy would hand a + * kernel pointers that dangle the moment the source dies -- and every Resolved holds a + * Geometry while every Band holds two, so this type is copied constantly. A copy therefore + * takes the storage and NOT the view, and rebuilds on first use. + * + * The move is the same rule for a different reason: a moved-from vector's buffer may be + * stolen, so the view's pointers stop meaning anything even though nothing was destroyed. */ + Geometry(const Geometry& o) + : keys_(o.keys_), svals_(o.svals_), ivals_(o.ivals_), dvals_(o.dvals_), kinds_(o.kinds_) {} + + Geometry& operator=(const Geometry& o) { + if (this != &o) { + keys_ = o.keys_; svals_ = o.svals_; ivals_ = o.ivals_; dvals_ = o.dvals_; + kinds_ = o.kinds_; + view_.clear(); dirty_ = true; + } + return *this; + } + + Geometry(Geometry&& o) noexcept + : keys_(std::move(o.keys_)), svals_(std::move(o.svals_)), + ivals_(std::move(o.ivals_)), dvals_(std::move(o.dvals_)), + kinds_(std::move(o.kinds_)) { + o.view_.clear(); o.dirty_ = true; + } + + Geometry& operator=(Geometry&& o) noexcept { + if (this != &o) { + keys_ = std::move(o.keys_); svals_ = std::move(o.svals_); + ivals_ = std::move(o.ivals_); dvals_ = std::move(o.dvals_); + kinds_ = std::move(o.kinds_); + view_.clear(); dirty_ = true; + o.view_.clear(); o.dirty_ = true; + } + return *this; + } + + void set_i(std::string_view k, long long v); + void set_s(std::string_view k, std::string_view v); + /* eps, rope theta, an attention scale. Carried so they reach RadArgs.p, and NOT matched on: + * constraint_holds() never sees a float, because a tolerance is not a predicate and a kernel + * that discriminates on eps to that precision has a bug. */ + void set_f(std::string_view k, double v); + bool get_i(std::string_view k, long long* out) const; + bool get_f(std::string_view k, double* out) const; + const char* get_s(std::string_view k) const; + bool has(std::string_view k) const; + + /* A view suitable for RadArgs.p. Valid while this object lives. */ + const RadParam* params() const; + int n_params() const; + + std::string str() const; /* "M=64 N=8192 K=5120 dtype=w4a8", for diagnostics */ + +private: + std::vector keys_, svals_; + std::vector view_; + mutable bool dirty_ = true; + void rebuild() const; + std::vector ivals_; + std::vector dvals_; + std::vector kinds_; +}; + +/* Does this geometry satisfy this constraint? The one place the matching rule lives. + * + * A float parameter can never satisfy one: get_i and get_s both miss a RAD_P_F64 slot, so a + * constraint naming a float key does not hold, which is the correct answer. A tolerance is not a + * predicate, and a kernel that discriminates on eps to that precision has a bug. */ +bool constraint_holds(const RadConstraint& c, const Geometry& g); +/* Why not -- for the selection table's miss column (spec §16). */ +std::string constraint_why(const RadConstraint& c, const Geometry& g); + +} /* namespace rad */ diff --git a/core/runtime/arena.cpp b/core/runtime/arena.cpp new file mode 100644 index 00000000..82d0919e --- /dev/null +++ b/core/runtime/arena.cpp @@ -0,0 +1,88 @@ +/* arena.cpp -- one allocation, sized once. See arena.h for why there is no allocate(). */ +#include "arena.h" + +#include + +namespace rad { + +int Arena::init(int64_t plan_bytes, int64_t scratch_bytes, int kind, int regions) { + release(); + if (plan_bytes < 0 || scratch_bytes < 0 || regions < 1) return RAD_E_INVAL; + + /* The scratch region starts on a page boundary. Kernels that want 4 KiB alignment for a + * workspace get it for free, and the ones that do not are not charged for it -- the padding is + * one page against an arena measured in hundreds of megabytes. */ + const int64_t off = align_up(plan_bytes, RAD_ALIGN_UNIT); + const int64_t pitch = align_up(scratch_bytes, RAD_ALIGN_UNIT); + const int64_t tail = pitch * regions; + int64_t total = off + tail; + + /* A zero-byte arena would hand every buffer a null base and turn a plan bug into a segfault + * with no name on it. One page instead, so a stray offset lands somewhere reportable. */ + if (total == 0) total = RAD_ALIGN_UNIT; + + void* p = rad_dev_alloc(total, kind); + if (!p) { + RAD_ERR("arena: %s of %s failed: %s", + kind == RAD_MEM_DEVICE ? "device allocation" : "host allocation", + humanb(total).c_str(), rad_dev_last_error()); + return RAD_E_NOMEM; + } + + base_ = static_cast(p); + kind_ = kind; + bytes_ = total; + scratch_off_ = off; + scratch_bytes_ = scratch_bytes; + scratch_pitch_ = pitch; + scratch_regions_ = regions; + return RAD_OK; +} + +void Arena::release() { + if (base_) rad_dev_free(base_, kind_); + base_ = nullptr; + bytes_ = 0; + scratch_off_ = 0; + scratch_bytes_ = 0; + scratch_pitch_ = 0; + scratch_regions_ = 1; +} + + +/* See arena.h. The walk is Ctx::bind_arena's, lifted here whole so the budget resolver and the + * allocation cannot disagree. + * + * THIS ASSUMES the plan gives host-domain buffers their own offset space. If it interleaves them + * with device buffers instead, both arenas come out sparse: correct, but paying VRAM for host + * activations. BufferInfo carries one arena_offset and one total, so the contract has to be stated + * somewhere and this is it. */ +int64_t arena_plan_bytes(const Program& P, int64_t* dev_out, int64_t* total_out) { + int64_t dev_hw = 0, host_hw = 0; + for (size_t i = 1; i < P.buffers.size(); ++i) { + const BufferInfo& bi = P.buffers[i]; + if (bi.arena_offset < 0) continue; /* the plan did not run; bind_arena refuses by name */ + int64_t bytes = bi.bytes; + if (bytes <= 0) { + int64_t n = 1; + for (uint32_t d = 0; d < bi.decl.rank; ++d) n *= bi.decl.shape[d]; + bytes = rad_dtype_bytes(bi.decl.dtype, n); + } + int64_t& hw = (bi.decl.domain == RAD_DOMAIN_HOST) ? host_hw : dev_hw; + hw = std::max(hw, bi.arena_offset + bytes); + } + /* With no host-domain buffers the plan's own total is authoritative: it may carry alignment + * slack the high-water mark does not see. */ + int64_t dev_bytes = host_hw > 0 ? dev_hw : std::max(dev_hw, P.arena_bytes); + /* The staging region sits above every buffer, so it is its own term, whichever of the two + * above set the high-water mark. */ + if (P.arena_stage_bytes > 0 && P.arena_stage_off >= 0) + dev_bytes = std::max(dev_bytes, P.arena_stage_off + P.arena_stage_bytes); + int64_t total = align_up(dev_bytes, RAD_ALIGN_UNIT) + + align_up(P.scratch_bytes, RAD_ALIGN_UNIT) * std::max(P.scratch_regions, 1); + if (total == 0) total = RAD_ALIGN_UNIT; /* Arena::init's floor, for the same reason */ + if (dev_out) *dev_out = dev_bytes; + if (total_out) *total_out = total; + return total; +} +} /* namespace rad */ diff --git a/core/runtime/arena.h b/core/runtime/arena.h new file mode 100644 index 00000000..f3e348d2 --- /dev/null +++ b/core/runtime/arena.h @@ -0,0 +1,71 @@ +/* arena.h -- ONE contiguous allocation, sized by the buffer plan at load and never allocated from + * at runtime. + * + * There is deliberately no allocate() on this class. If there were one somebody would eventually + * call it from inside rad_arch_step, and an allocator on the step path is precisely the class of + * dynamic behaviour this engine exists to remove (spec §3.1). Offsets come from the buffer plan, + * which computed liveness over the declared op list and is conservative on purpose: a plan that is + * correct for the worst step is correct for every step. The arena only owns the block those + * offsets index into. + * + * The scratch region sits at the tail and is shared by every op on a stream. That is safe and not + * merely convenient: launches on one stream execute in order, so no two kernels' scratch lifetimes + * overlap. A context's second lane is a second stream, where that order does not hold, so a program + * that declares one gets a second region and each lane's kernels are handed their own + * (Program::scratch_regions). A lane used without that declaration shares region 0, and there + * Ctx::issue orders a scratch user behind one on the other lane that nothing has ordered it after + * yet. Program::scratch_bytes is the largest single kernel's requirement, so a region of that size + * serves all of them -- and if a kernel asks for more than the plan reserved, prepare refuses by + * name rather than handing it a short buffer. + */ +#pragma once +#include "../rad_core.h" + +namespace rad { + +class Arena { +public: + Arena() = default; + ~Arena() { release(); } + Arena(const Arena&) = delete; + Arena& operator=(const Arena&) = delete; + + /* `kind` is a RAD_MEM_* class. The device arena is RAD_MEM_DEVICE; a program with + * RAD_DOMAIN_HOST buffers gets a second arena in RAD_MEM_HOST. `regions` scratch regions of + * `scratch_bytes` each sit at the tail, one per lane (Program::scratch_regions). */ + int init(int64_t plan_bytes, int64_t scratch_bytes, int kind, int regions = 1); + void release(); + + char* base() const { return base_; } + /* Region `r`, or region 0 when the arena holds fewer. */ + void* scratch(int r = 0) const { + if (!base_) return nullptr; + return base_ + scratch_off_ + (r > 0 && r < scratch_regions_ ? r * scratch_pitch_ : 0); + } + int64_t scratch_bytes() const { return scratch_bytes_; } + int scratch_regions() const { return scratch_regions_; } + int64_t bytes() const { return bytes_; } + bool live() const { return base_ != nullptr; } + +private: + char* base_ = nullptr; + int kind_ = RAD_MEM_DEVICE; + int64_t bytes_ = 0; + int64_t scratch_off_ = 0; + int64_t scratch_bytes_ = 0; + int64_t scratch_pitch_ = 0; /* scratch_bytes_ padded to RAD_ALIGN_UNIT */ + int scratch_regions_ = 1; +}; + + +/* THE ARENA'S SIZE, COMPUTED WITHOUT ALLOCATING IT. Two callers need the same answer at two + * different times: Ctx::bind_arena, which allocates it at the end of startup, and the VRAM budget + * resolver, which has to subtract it from the card BEFORE the pools are allocated near the top of + * startup. Two copies of this walk would agree today and drift the first time the plan grows a + * domain -- and the failure would be a budget that overcommits the card by exactly the difference. + * + * `dev_out` is what the device arena's init() will be given as plan_bytes; `total_out` is what it + * will actually allocate, plan and scratch both padded to RAD_ALIGN_UNIT as Arena::init pads them. + * Returns the total. */ +int64_t arena_plan_bytes(const Program& P, int64_t* dev_out, int64_t* total_out); +} /* namespace rad */ diff --git a/core/runtime/ctx.cpp b/core/runtime/ctx.cpp new file mode 100644 index 00000000..53c5f2c4 --- /dev/null +++ b/core/runtime/ctx.cpp @@ -0,0 +1,1401 @@ +/* ctx.cpp -- everything the run phase does that is not the hot path: bringing the arena and the + * plans up, driving a step, the routing handoff, and the opt-in per-op timing. The hot path itself + * is issue.cpp, kept in its own translation unit so it stays readable at the size it has to be. + */ +#include +#include "ctx.h" +#include "../device/device.h" + +#include +#include +#include +#include + +namespace rad { + +/* ================================================================== lifecycle */ + +Ctx::~Ctx() { shutdown(); } + +int Ctx::init(const CtxDesc& d) { + if (!d.program) return RAD_E_INVAL; + program_ = d.program; + rank_ = d.rank; + world_size_= d.world_size < 1 ? 1 : d.world_size; + device_ = d.device; + record_passes_ = d.record_passes; + residency_ = d.residency; + kv_ = d.kv; + arch_step_ = d.arch_step; + profiling_ = d.profile_ops; + + /* The rank owns one device. Set it here so allocation lands on the right card, and again from + * the rank thread in bind_thread() because the backend's current device is thread-local. */ + RAD_TRY(rad_dev_set(device_)); + + if (d.stream) { + stream_ = d.stream; + own_stream_ = false; + } else { + /* Ordinary priority. The mover runs on its own stream and the compute stream waits on its + * events (spec §5.4); making compute high-priority would let it preempt the transfers it + * is about to wait for, which is exactly backwards. */ + RAD_TRY(rad_stream_create(&stream_, 0)); + own_stream_ = true; + } + + /* The second lane is NOT created here. See lane_init(). */ + + int s = prepare(); + if (s < 0) { shutdown(); return s; } + return RAD_OK; +} + +void Ctx::shutdown() { + oracle_close(); + /* The one host synchronisation in the whole component, and it is at teardown rather than on + * the step path. Everything below frees memory the stream may still be reading or writing -- + * the routing staging is the destination of a copy nobody waited on by design (spec §5.5), and + * the arena is every kernel's operands. Freeing either out from under an in-flight stream is a + * use-after-free that reproduces once a week and never under a debugger. */ + if (stream_) rad_stream_sync(stream_); + if (lane1_) rad_stream_sync(lane1_); + + for (PassTape& t : tapes_) tape_drop(t); + tapes_.clear(); + + for (auto& p : prof_ring_) { + if (p.a) rad_event_destroy(p.a); + if (p.b) rad_event_destroy(p.b); + } + prof_ring_.clear(); + + for (RadEvent& e : route_done_) + if (e) { rad_event_destroy(e); e = nullptr; } + route_.clear(); + + if (route_pool_) { rad_dev_free(route_pool_, RAD_MEM_HOST_PINNED); route_pool_ = nullptr; } + if (route_dev_) { rad_dev_free(route_dev_, RAD_MEM_DEVICE); route_dev_ = nullptr; } + + /* The expert pointer tables. Freed after the stream syncs above for exactly the reason those + * syncs exist: the device half is the source operand of a grouped GEMM and the host half is + * the source of a copy on that stream. */ + free_weight_tables(); + + arena_.release(); + host_arena_.release(); + + for (int i = 0; i < 2; ++i) { + if (lane_ev_[i]) { rad_event_destroy(lane_ev_[i]); lane_ev_[i] = nullptr; } + if (host_touch_ev_[i]) { rad_event_destroy(host_touch_ev_[i]); host_touch_ev_[i] = nullptr; } + host_touch_pending_[i] = false; + } + if (own_lane1_ && lane1_) rad_stream_destroy(lane1_); + lane1_ = nullptr; + own_lane1_ = false; + lane_ = 0; + scratch_open_[0] = scratch_open_[1] = false; + + if (own_stream_ && stream_) rad_stream_destroy(stream_); + stream_ = nullptr; + own_stream_ = false; + program_ = nullptr; +} + +int Ctx::bind_thread() { return rad_dev_set(device_); } + +/* ================================================================== prepare */ + +int Ctx::prepare() { + oracle_open(); + RAD_TRY(bind_arena()); + RAD_TRY(bind_buffers()); + RAD_TRY(bind_weights(/*refresh_only=*/false)); + RAD_TRY(bind_weight_tables()); + RAD_TRY(bind_ops()); + RAD_TRY(bind_routing()); + RAD_TRY(bind_profiling()); + /* Recorded passes need a backend that records, and are off for everything that has to see + * each issue: the per-op profile, the oracle, and the argument digest. */ + tape_on_ = record_passes_ && tape_supported() && !profiling_ && !oracle_ && + std::getenv("RADIANCE_DEBUG_ARGSHA") == nullptr; + return RAD_OK; +} + +int Ctx::bind_arena() { + Program& P = *program_; + + /* The buffer plan hands us one offset per buffer, and arena_plan_bytes() turns those into the + * two numbers Arena::init wants. THE WALK LIVES THERE AND NOT HERE because the VRAM budget + * resolver has to subtract this allocation from the card before any of it exists -- see + * core/mem/vram_budget.cpp. What stays here is the part that can only be done at bind time: + * refusing a plan that did not run, and filling in a size the plan left at zero. + * + * Where a program has RAD_DOMAIN_HOST buffers -- host-site execution, spec §5.1 -- those + * offsets cannot index the same block, so there are two arenas. */ + int64_t host_hw = 0; + for (size_t i = 1; i < P.buffers.size(); ++i) { + BufferInfo& bi = P.buffers[i]; + if (bi.arena_offset < 0) { + RAD_ERR("buffer '%s' has no arena offset: the buffer plan did not run", + bi.name.c_str()); + return RAD_E_STATE; + } + if (bi.bytes <= 0) { + int64_t n = 1; + for (uint32_t d = 0; d < bi.decl.rank; ++d) n *= bi.decl.shape[d]; + bi.bytes = rad_dtype_bytes(bi.decl.dtype, n); + RAD_DEBUG("buffer '%s' had no size from the plan; %s from its declaration", + bi.name.c_str(), humanb(bi.bytes).c_str()); + } + if (bi.decl.domain == RAD_DOMAIN_HOST) + host_hw = std::max(host_hw, bi.arena_offset + bi.bytes); + } + + int64_t dev_bytes = 0, total = 0; + arena_plan_bytes(P, &dev_bytes, &total); + + RAD_TRY(arena_.init(dev_bytes, P.scratch_bytes, RAD_MEM_DEVICE, std::max(P.scratch_regions, 1))); + /* SAY WHAT THIS COSTS, BECAUSE NOTHING ELSE DOES. The allocation is in no pool, and it is not + * something --gpu-headroom-mib can cover: it scales with max_tok, so any round number an + * operator picks either under-reserves or wastes VRAM. On a part whose experts do not fit, + * waste is not free -- a GiB of headroom nothing uses is about 1.4 ms a decode step, because + * that GiB is experts that would otherwise be resident. So it is computed and charged by name: + * core/mem/vram_budget.cpp does the charging, this line is the receipt, and the two numbers + * must agree. */ + RAD_INFO("arena: %s device + %d x %s scratch = %s, charged to the VRAM budget before it was " + "split", humanb(dev_bytes).c_str(), arena_.scratch_regions(), + humanb(P.scratch_bytes).c_str(), humanb(total).c_str()); + + if (host_hw > 0) { + /* RAD_MEM_HOST_MAPPED AND NOT RAD_MEM_HOST, AND THAT IS THE WHOLE OF HOW A HOST RUN + * REACHES THE DEVICE GRAPH. + * + * A host-site op writes a host-domain buffer and something downstream reads it on the + * device. NOTHING IN THIS RUNTIME COPIES BETWEEN THE TWO ARENAS -- there is no transfer op + * and no implicit staging in rad_issue, and the planner's `link_crossings` is an objective + * it minimises, not a mechanism it provides. With plain RAD_MEM_HOST the host arena is + * "ordinary malloc'd pages the GPU has never been shown" (core/device/hip.cpp), so the + * device side of that hand-off had no way to read it and host-site execution could not + * complete a step. Mapped, the same allocation is addressable from a kernel over the link + * and the crossing IS the read -- which is row three of spec 5.1 applied to an activation + * rather than to a weight. + * + * The cost is that every device access to a host-domain buffer is a link read, so this is + * for the narrow hand-off at a host run's edge and not for a hot activation. A buffer's + * domain is declared by the ARCHITECTURE, so that judgement stays where it belongs. */ + RAD_TRY(host_arena_.init(host_hw, 0, RAD_MEM_HOST_MAPPED)); + /* ONE POINTER SERVES BOTH SIDES, AND THAT IS CHECKED RATHER THAN ASSUMED. bind_buffers + * stores a single base per buffer, which is correct exactly while the mapped allocation's + * host and device views share an address -- true under HIP's unified addressing and true + * by construction on the host backend. A backend where they differ gets a refusal here + * instead of handing one of the two sides a pointer into nothing. */ + void* hb = host_arena_.base(); + void* db = rad_dev_device_ptr(hb); + if (!db || db != hb) { + RAD_ERR("the host activation arena at %p has device view %p: this runtime binds one " + "pointer per buffer, so a mapped allocation whose two views differ cannot be " + "handed to both a host kernel and a device kernel", hb, db); + return RAD_E_UNSUPPORTED; + } + RAD_DEBUG("arena: %s host, mapped (host-site activations)", humanb(host_hw).c_str()); + } + return RAD_OK; +} + +int Ctx::bind_buffers() { + Program& P = *program_; + buf_tmpl_.assign(P.buffers.size(), RadTensor{}); + buf_bits_.assign(P.buffers.size(), 0); + buf_host_.assign(P.buffers.size(), 0); + + for (size_t i = 1; i < P.buffers.size(); ++i) { + BufferInfo& bi = P.buffers[i]; + RadTensor& t = buf_tmpl_[i]; + + t.dtype = bi.decl.dtype; + t.rank = bi.decl.rank; + for (uint32_t d = 0; d < bi.decl.rank && d < RAD_MAX_RANK; ++d) t.shape[d] = bi.decl.shape[d]; + rad_tensor_pack(&t); + + Arena& a = (bi.decl.domain == RAD_DOMAIN_HOST) ? host_arena_ : arena_; + if (!a.live()) { + RAD_ERR("buffer '%s' wants the %s arena, which was not allocated", + bi.name.c_str(), bi.decl.domain == RAD_DOMAIN_HOST ? "host" : "device"); + return RAD_E_STATE; + } + if (bi.arena_offset + bi.bytes > a.bytes()) { + RAD_ERR("buffer '%s' at offset %lld + %s runs past the %s arena (%s)", + bi.name.c_str(), (long long)bi.arena_offset, humanb(bi.bytes).c_str(), + bi.decl.domain == RAD_DOMAIN_HOST ? "host" : "device", + humanb(a.bytes()).c_str()); + return RAD_E_FULL; + } + + /* rad_buf_ptr is arena_base + BufferInfo::arena_offset, and nothing else -- there is no + * table walk and no allocator between a handle and its bytes. */ + t.data = a.base() + bi.arena_offset; + bi.ptr = t.data; + buf_bits_[i] = rad_dtype_bits(bi.decl.dtype); + buf_host_[i] = bi.decl.domain == RAD_DOMAIN_HOST ? 1 : 0; + } + level_tmpl_.assign(1, buf_tmpl_); + level_ = 0; + return RAD_OK; +} + +int Ctx::add_level(int64_t rows, const std::vector& offset, + const std::vector& decl) { + Program& P = *program_; + if (level_tmpl_.empty() || offset.size() != P.buffers.size() || decl.size() != P.buffers.size()) + return RAD_E_INVAL; + std::vector t = level_tmpl_[0]; + for (size_t i = 1; i < P.buffers.size(); ++i) { + const BufferInfo& bi = P.buffers[i]; + /* THE HOST ARENA AND THE FIXED REGION ARE NOT LEVELLED: their template is level 0's. */ + if (bi.decl.domain == RAD_DOMAIN_HOST || bi.decl.kind != RAD_BUF_TRANSIENT) { + if (offset[i] != bi.arena_offset) return RAD_E_STATE; + continue; + } + const int64_t bytes = rad_dtype_bytes(decl[i].dtype, [&] { + int64_t n = 1; + for (uint32_t d = 0; d < decl[i].rank; ++d) n *= decl[i].shape[d]; + return n; + }()); + if (offset[i] < P.arena_fixed_bytes || offset[i] + bytes > arena_.bytes()) { + RAD_ERR("arena level for %lld rows puts buffer '%s' at %lld + %s, outside the arena's " + "transient region", (long long)rows, bi.name.c_str(), (long long)offset[i], + humanb(bytes).c_str()); + return RAD_E_STATE; + } + RadTensor& r = t[i]; + for (uint32_t d = 0; d < decl[i].rank && d < RAD_MAX_RANK; ++d) r.shape[d] = decl[i].shape[d]; + rad_tensor_pack(&r); + r.data = arena_.base() + offset[i]; + } + level_tmpl_.push_back(std::move(t)); + return (int)level_tmpl_.size() - 1; +} + +int Ctx::set_level(int level) { + if (level < 0 || level >= (int)level_tmpl_.size()) return RAD_E_INVAL; + if (level == level_) return RAD_OK; + buf_tmpl_ = level_tmpl_[(size_t)level]; + level_ = level; + return RAD_OK; +} + +int Ctx::bind_weights(bool refresh_only) { + Program& P = *program_; + ++w_tmpl_epoch_; + if (!refresh_only) { + w_tmpl_.assign(P.weights.size(), RadTensor{}); + w_bits_.assign(P.weights.size(), 0); + w_gen_.assign(P.weights.size(), 0); + waited_gen_.assign(P.weights.size(), UINT32_MAX); + w_direct_.assign(P.weights.size(), 0); + } + + for (size_t i = 1; i < P.weights.size(); ++i) { + WeightInfo& wi = P.weights[i]; + const uint32_t gen = wi.generation.load(std::memory_order_acquire); + if (refresh_only && w_gen_[i] == gen) continue; + + RadTensor& t = w_tmpl_[i]; + /* The stored dtype is what the resolved kernel's layout hook asked for; the logical dtype + * is what the plugin declared. The kernel reads the layout it chose, so the stored one + * wins where the layout pass filled it in. + * + * THE SHAPE IS THE DECLARED ONE and the dtype is the stored one, which is a seam worth + * naming rather than a symmetry. WeightInfo DOES carry stored_shape -- the layout pass + * fills it beside stored_dtype -- and this deliberately does not use it, because a kernel + * whose layout reshapes has to keep working out its own stride from the geometry either + * way: a row-sharded weight's stored shape is the whole tensor's, not this rank's. + * + * So a layout that changes the WIDTH (libr4d's fp8 lm_head appends each row's scales to + * its own row) is invisible here, and its kernel derives the stride from the same rule its + * layout hook used. What keeps the two honest is the layout TAG the engine checks at load, + * not a shape it could compare. The declared shape is already divided by world_size, + * because the plugin declares dimensions per rank (spec §9). */ + t.dtype = wi.stored_dtype != RAD_DT_INVALID ? wi.stored_dtype : wi.decl.dtype; + t.rank = wi.decl.rank; + for (uint32_t d = 0; d < wi.decl.rank && d < RAD_MAX_RANK; ++d) t.shape[d] = wi.decl.shape[d]; + rad_tensor_pack(&t); + t.data = wi.ptr; + w_bits_[i] = rad_dtype_bits(t.dtype); + w_gen_[i] = gen; + } + /* A rebinding can move any template, and a table entry the residency table has no slot for + * reads its template: every table resolves every entry at its next issue. */ + if (refresh_only) + for (WeightTable& t : wtabs_) if (t.checked) { t.full = true; t.pend.clear(); } + return RAD_OK; +} + +int Ctx::bind_ops() { + Program& P = *program_; + + plans_.assign(P.ops.size(), OpPlan{}); + unflushed_.clear(); + unflushed_.reserve(P.ops.size()); + for (uint32_t i = 1; i < (uint32_t)P.ops.size(); ++i) unflushed_.push_back(i); + op_domain_ = std::vector>(P.ops.size()); + band_table_.clear(); + issue_table_.clear(); + + int64_t n_bands_total = 0, n_plans = 0; + for (auto& o : P.ops) { n_bands_total += (int64_t)o.bands.size(); } + n_plans = n_bands_total * RAD_N_DOMAINS; + band_table_.reserve((size_t)n_bands_total); + issue_table_.reserve((size_t)n_plans); + + for (size_t i = 1; i < P.ops.size(); ++i) { + OpInfo& oi = P.ops[i]; + OpPlan& p = plans_[i]; + p.info = &oi; + p.band_off = (int32_t)band_table_.size(); + p.n_bands = (int32_t)oi.bands.size(); + p.plan_off = (int32_t)issue_table_.size(); + p.n_opd_schema = oi.schema ? (int32_t)oi.schema->n_operands : -1; + /* The one op whose issue costs interconnect bytes. Matched by name once, here, rather + * than on the issue path -- see OpPlan::collective. */ + p.collective = (oi.op == "all_reduce"); + + for (const Band& b : oi.bands) band_table_.push_back(b.hi); + + for (const Band& b : oi.bands) { + for (int d = 0; d < RAD_N_DOMAINS; ++d) { + IssuePlan ip{}; + const Resolved& r = b.dom[d]; + if (r && r.row && r.row->info && r.row->info->launch) { + ip.row = r.row; + ip.launch = r.row->info->launch; + + /* Bound once. args.p views the frozen geometry inside Program::ops, which is + * why declare must not touch a Resolved after this point: the vector would + * reallocate and every one of these would dangle. */ + ip.args.t = tbuf_; + ip.args.n_t = 0; + ip.args.p = r.geom.params(); + ip.args.n_p = r.geom.n_params(); + ip.args.scratch = arena_.scratch(); + ip.args.scratch_bytes = r.scratch_bytes; + ip.args.instance = r.instance; + ip.args.rank = rank_; + ip.args.world_size = world_size_; + + if (r.scratch_bytes > arena_.scratch_bytes()) { + RAD_ERR("op '%s' band %lld kernel %s wants %s of scratch but the plan " + "reserved %s -- the arena was sized before this kernel was " + "resolved", + oi.op.c_str(), (long long)b.hi, r.row->info->name, + humanb(r.scratch_bytes).c_str(), + humanb(arena_.scratch_bytes()).c_str()); + return RAD_E_SCRATCH; + } + } + issue_table_.push_back(ip); + } + } + + /* Execution site. Site is a property of the weights (spec §5.1), so an op whose every + * weight operand was placed on the host runs its host kernel and everything else runs on + * the device. An op with no weights stays on the device; the planner overrides through + * set_op_domain, which is where the "contiguous host runs" objective actually lands. */ + int dom = RAD_DOMAIN_DEVICE; + if (!oi.weights.empty()) { + bool all_host = true; + for (rad_weight w : oi.weights) { + const WeightInfo* wi = P.weight(w); + if (!wi || wi->site != Site::Host) { all_host = false; break; } + } + /* ...and whether that host kernel can READ the weights, which is a separate question + * from whether one exists. The planner asked for the host; the device is always a + * correct answer, so this is a fallback and a warning rather than a refusal. */ + std::string why; + if (all_host && check_domain_layout((rad_op)i, RAD_DOMAIN_HOST, &why) < 0) { + RAD_WARN("op '%s' was placed on the host and runs on the device instead: %s", + oi.op.c_str(), why.c_str()); + all_host = false; + } + if (all_host) dom = RAD_DOMAIN_HOST; + } + op_domain_[i].store((uint8_t)dom, std::memory_order_relaxed); + + if (dom == RAD_DOMAIN_HOST) { + int s = check_domain((rad_op)i, RAD_DOMAIN_HOST); + if (s < 0) return s; + } + } + return RAD_OK; +} + +/* CAN THE KERNEL THAT WOULD SERVE THIS OP ON `domain` READ THE BYTES THE CONTAINER HOLDS? + * + * A weight is stored ONCE, in whatever arrangement the kernel that claimed it at declare asked + * for (spec 4.2), and that claimant is always a DEVICE row: rad_builder.cpp exempts the host + * domain from the layout claim deliberately, because libref declares no layout for anything and + * every re-laying device kernel would otherwise collide with its own reference fallback and no + * model would declare at all. + * + * So moving an op to a domain whose kernel reads its weights AS DECLARED hands that kernel a + * plane it cannot read. libr4d stores an fp8a8 weight in WMMA fragment order -- the same N*K + * bytes in a different arrangement -- so the byte count matches, every shape check passes, and + * the op computes a plausible wrong answer for the life of the process. Two readings of one + * permuted plane are uncorrelated tensors, which is a model that serves and lies. + * + * The load-time tag check in engine_bringup cannot see this: it compares the container against + * the tag the claimant recorded, and both of those are the device row's. This asks the same + * question of the kernel that will actually run. + * + * `why` gets the sentence; the caller decides whether it is a warning or a refusal, because the + * two callers differ. The planner ASKED for the host and can be given the device instead, which + * is always a correct answer; an explicit set_op_domain has no such fallback. */ +int Ctx::check_domain_layout(rad_op h, int domain, std::string* why) const { + if (h == RAD_NULL_HANDLE || h >= plans_.size()) return RAD_E_INVAL; + if (domain < 0 || domain >= RAD_N_DOMAINS) return RAD_E_INVAL; + const OpPlan& p = plans_[h]; + if (!p.info || !program_) return RAD_OK; + const OpInfo& oi = *p.info; + + for (size_t j = 0; j < oi.weights.size() && j < oi.weight_opd.size(); ++j) { + const rad_weight wh = oi.weights[j]; + if (!wh || (size_t)wh >= program_->weights.size()) continue; + const WeightInfo& w = program_->weights[(size_t)wh]; + if (w.layout_tag.empty()) continue; /* stored as it is: any reader will do */ + const int opd = oi.weight_opd[j]; + + for (int b = 0; b < p.n_bands; ++b) { + const IssuePlan& ip = + issue_table_[(size_t)p.plan_off + (size_t)b * RAD_N_DOMAINS + (size_t)domain]; + const RadKernelInfo* ki = ip.row ? ip.row->info : nullptr; + if (!ki) continue; /* no kernel here at all: check_domain's answer */ + RadLayout L{}; + RadTensor t[RAD_ENC_MAX_PLANES]; + weight_planes(w, t); + /* A row with no hook, or one that declines this operand, is asserting that it reads + * the selected plane AS IT IS -- the same reading rad_builder.cpp gives the same code. + * One that does not read the encoding at all cannot take the op either. */ + const int st = ki->layout ? ki->layout(ip.args.p, ip.args.n_p, opd, &w.enc, w.sel, t, + w.n_sel, &L) + : RAD_E_UNSUPPORTED; + const std::string tag = st == RAD_OK ? (L.tag && *L.tag ? L.tag : ki->name) + : std::string(); + if (st >= 0 || st == RAD_E_UNSUPPORTED) { + if (tag == w.layout_tag) continue; + } + if (why) + *why = "'" + w.name + "' is stored as '" + w.layout_tag + "' -- what the kernel " + "that claimed it asked for -- and " + ki->name + " reads it " + + (st < 0 && st != RAD_E_UNSUPPORTED + ? std::string("not at all (") + rad_strerror(st) + ")" + : tag.empty() ? std::string("as it is") : "as '" + tag + "'") + + ". A weight is stored once, so this is a different reading of the same " + "bytes and not a fallback"; + return RAD_E_FORMAT; + } + } + return RAD_OK; +} + + +int Ctx::check_domain(rad_op h, int domain) const { + if (h == RAD_NULL_HANDLE || h >= plans_.size()) return RAD_E_INVAL; + if (domain < 0 || domain >= RAD_N_DOMAINS) return RAD_E_INVAL; + const OpPlan& p = plans_[h]; + if (!p.info) return RAD_E_INVAL; + + for (int b = 0; b < p.n_bands; ++b) { + const IssuePlan& ip = issue_table_[(size_t)p.plan_off + (size_t)b * RAD_N_DOMAINS + domain]; + if (ip.launch) continue; + const Band& bd = p.info->bands[(size_t)b]; + RAD_ERR("op '%s' was placed on the %s domain, but band %s<=%lld has no %s kernel: %s", + p.info->op.c_str(), domain == RAD_DOMAIN_HOST ? "host" : "device", + p.info->ranged_key.empty() ? "n" : p.info->ranged_key.c_str(), + (long long)bd.hi, domain == RAD_DOMAIN_HOST ? "host" : "device", + bd.miss[domain].empty() ? "nothing resolved" : bd.miss[domain].c_str()); + return RAD_E_NOKERNEL; + } + + /* A kernel existing for the band is not the same as a kernel that can READ THE WEIGHT. */ + std::string why; + if (check_domain_layout(h, domain, &why) < 0) { + RAD_ERR("op '%s' cannot run on the %s domain: %s", p.info->op.c_str(), + domain == RAD_DOMAIN_HOST ? "host" : "device", why.c_str()); + return RAD_E_FORMAT; + } + return RAD_OK; +} + + +int Ctx::set_op_domain(rad_op h, int domain) { + int s = check_domain(h, domain); + if (s < 0) return s; + if (op_domain_[h].exchange((uint8_t)domain, std::memory_order_relaxed) != (uint8_t)domain) + domain_epoch_.fetch_add(1, std::memory_order_relaxed); + return RAD_OK; +} + +int Ctx::op_domain(rad_op h) const { + if (h == RAD_NULL_HANDLE || h >= op_domain_.size()) return RAD_E_INVAL; + return (int)op_domain_[h].load(std::memory_order_relaxed); +} + +/* ================================================================== routing (spec §5.5) */ + +int Ctx::bind_routing() { + const Program& P = *program_; + /* THE ROUTED LAYER COUNT IS NOT meta.n_layers, AND A DRAFTER IS WHY. + * + * `meta.n_layers` counts TRUNK layers. An MTP head is a further block with its own expert + * plane, and it reports itself as the layer one past that count. Sized from `meta.n_layers` + * this vector is one short, so every one of that head's route reports is refused with an error + * and the heat engine never sees a single count for it. The placement plan still knows about + * the units but has no measurement to promote on, so they stay wherever the warm start left + * them -- and the head's experts stream over the link on EVERY draft round of every step, + * which is worth several percent of the decode step on a model that has one. + * + * The weights know the answer and the header does not, so ask them. A drafter, a shared + * expert plane, anything a plugin declares past the trunk lands here by construction rather + * than by the core being told about it. + */ + int64_t n_layer = P.meta.n_layers; + for (const WeightInfo& w : P.weights) + if (w.decl.group.expert >= 0) + n_layer = std::max(n_layer, (int64_t)w.decl.group.layer + 1); + const int64_t n_expert = P.meta.n_expert; + if (n_layer <= 0 || n_expert <= 0) return RAD_OK; /* dense: nothing routes */ + + route_n_expert_ = n_expert; + route_.assign((size_t)n_layer, RouteSlot{}); + + /* One pinned block for every bank, and ONE ROW A LAYER on the card. Pinned because the copy + * has to be a real asynchronous DMA: a pageable destination makes the driver stage it through + * its own buffer and, on some paths, synchronise -- which would put a host sync on the compute + * stream, which is the one thing §5.5 says routing must never do. + * + * The card's rows are not banked: a pass's reports land in them and the pass's flush carries + * them to the step's bank on the host, both on the compute stream, so the next pass's reports + * queue behind the flush that reads them. A report's copy then names the same address every + * step, which is what lets a recorded pass be replayed without rewriting it. */ + const int64_t elems = n_layer * kRouteBanks * n_expert; + const int64_t bytes = elems * (int64_t)sizeof(int32_t); + const int64_t dbytes = n_layer * n_expert * (int64_t)sizeof(int32_t); + void* p = rad_dev_alloc(bytes, RAD_MEM_HOST_PINNED); + void* d = rad_dev_alloc(dbytes, RAD_MEM_DEVICE); + if (!p || !d) { + RAD_ERR("routing: %s of %s staging failed: %s", humanb(p ? dbytes : bytes).c_str(), + p ? "device" : "pinned", rad_dev_last_error()); + if (p) rad_dev_free(p, RAD_MEM_HOST_PINNED); + if (d) rad_dev_free(d, RAD_MEM_DEVICE); + return RAD_E_NOMEM; + } + route_pool_ = static_cast(p); + route_dev_ = static_cast(d); + std::memset(route_pool_, 0, (size_t)elems * sizeof(int32_t)); + + for (int64_t l = 0; l < n_layer; ++l) { + RouteSlot& r = route_[(size_t)l]; + for (int i = 0; i < kRouteBanks; ++i) { + r.staging[i] = route_pool_ + ((int64_t)i * n_layer + l) * n_expert; + r.step[i] = -1; /* never written, as against written at step 0 */ + } + } + /* Local: the host reads the bank on the strength of this event, but the bytes it reads were + * put in host memory by the copy in front of it, whose own packets carry the system scope. */ + for (RadEvent& e : route_done_) RAD_TRY(rad_event_create_local(&e)); + return RAD_OK; +} + +/* THE PASS'S HISTOGRAMS GO TO THE HOST IN ONE TRANSFER: the layers it reported, which are + * contiguous rows of the bank, and then the bank's event. Called at the end of every pass. */ +int Ctx::route_flush() { + if (route_bank_ < 0 || route_lo_ > route_hi_) return RAD_OK; + const int64_t n_layer = (int64_t)route_.size(); + const int64_t off = ((int64_t)route_bank_ * n_layer + route_lo_) * route_n_expert_; + const int64_t n = (int64_t)(route_hi_ - route_lo_ + 1) * route_n_expert_; + RAD_TRY(rad_memcpy_async(route_pool_ + off, route_dev_ + (int64_t)route_lo_ * route_n_expert_, + n * (int64_t)sizeof(int32_t), stream_)); + RAD_TRY(rad_event_record(route_done_[route_bank_], stream_)); + route_lo_ = 1; + route_hi_ = 0; + return RAD_OK; +} + +int Ctx::route_report(int layer, const RadRouting* r) { + if (rec_ && r) { + tape_cut(); + TapeStep st; + st.kind = kTapeRoute; + st.a = (int32_t)rec_->route.size(); + rec_->route.emplace_back(layer, *r); + rec_->steps.push_back(st); + } + return route_report_impl(layer, r, true); +} + +int Ctx::route_report_impl(int layer, const RadRouting* r, bool copy) { + if (!r) return RAD_E_INVAL; + if (layer < 0 || (size_t)layer >= route_.size()) { + RAD_ERR("rad_route_report: layer %d is outside the %zu layers the model declared " + "(or the model has no experts)", layer, route_.size()); + return RAD_E_INVAL; + } + + RouteSlot& s = route_[(size_t)layer]; + const int step = batch_ ? batch_->step : 0; + const int bank = ((step % kRouteBanks) + kRouteBanks) % kRouteBanks; + + /* The plugin computed these with ordinary declared ops. This is the handoff, not a + * computation: we record the device buffers so the mover can be told what was wanted, and + * nothing here reads them. */ + s.routing = *r; + s.reported = step; + + if (r->expert_count) { + int64_t n = r->n_expert; + if (n > route_n_expert_) { + RAD_WARN("rad_route_report: layer %d reported %lld experts, staging holds %lld; " + "the histogram is truncated", layer, (long long)n, (long long)route_n_expert_); + n = route_n_expert_; + } + if (n > 0) { + /* Asynchronous, on the compute stream, and nothing waits on it. The heat engine reads + * it on the NEXT step, so placement decisions are always one step stale -- which for + * heat-based promotion is irrelevant, because a hot expert is hot across many steps + * (spec §5.5). + * + * "NOTHING WAITS ON IT" IS TRUE OF THE HOST AND NOT OF THE STREAM. A copy is a blit + * kernel, so it sits in the compute stream's order and every later kernel queues + * behind it -- and a copy INTO HOST MEMORY must also make its writes visible to the + * host before it completes, which waits out every write still crossing the link. With + * the link carrying streamed experts, that release and the event record after it would + * cost a routed layer several microseconds of an otherwise idle compute stream. + * + * So the layer's counts are copied WITHIN THE CARD, into its row of the step's bank, + * and the rows this pass wrote cross to the host once, at the end of the pass + * (route_flush). One card-local blit a routed layer is the whole cost -- and none when + * the router wrote the row itself (rad_route_counts), which is the report naming it. + * + * MOVING IT OFF THE COMPUTE STREAM IS WORTH LESS THAN IT LOOKS. The second lane would + * have to wait on this stream first, or the copy races the routing kernel that writes + * `expert_count`. That is a lane_join a routed layer and an event record back on the + * compute stream, which costs more than the blit it moves. */ + /* RECYCLING A BANK NOBODY READ IS THE RING BEING TOO SHALLOW FOR THIS RUN-AHEAD, and + * it is the only way evidence is lost, since the drain takes every landed bank. It + * is counted here, at the one place it can happen, rather than inferred from a total + * that came up short. A second report of the SAME step is not a recycle: the drain + * does not take a bank before its step is over, and `reports` carries the pass. */ + const bool again = s.step[bank] == step; + if (s.step[bank] >= 0 && !again && !s.credited[bank]) ++route_dropped_; + s.credited[bank] = false; + if (route_bank_ != bank) { + /* Empty: every pass flushes at its end. Not recorded if it were not. */ + if (rec_) tape_pause(true); + const int rf = route_flush(); + if (rec_) tape_pause(false); + RAD_TRY(rf); + route_bank_ = bank; + } + int32_t* const row = route_dev_ + (int64_t)layer * route_n_expert_; + if (copy && r->expert_count != row) + RAD_TRY(rad_memcpy_async(row, r->expert_count, n * (int64_t)sizeof(int32_t), + stream_)); + if (route_lo_ > route_hi_) { + route_lo_ = route_hi_ = layer; + } else { + if (layer < route_lo_) route_lo_ = layer; + if (layer > route_hi_) route_hi_ = layer; + } + s.reports[bank] = again ? s.reports[bank] + 1 : 1; + s.step[bank] = step; + + /* ==================== WHAT A FAULT LOOKS LIKE IN THIS HISTOGRAM ==================== + * + * The sum of a layer's counts is the number of placements, which cannot exceed + * n_tok * top_k. Negative counts, or totals orders of magnitude above that bound, say + * something OUTSIDE this path wrote over the buffer rather than that the routing + * kernel is wrong. + * + * The shape such an overrun takes is worth knowing, because it hides. A routed expert + * plane is one row per (token, slot), so a buffer declared at max_tok rows is written + * `rows * top_k` deep and runs past its declaration -- and the overrun only EXISTS + * once rows * top_k exceeds the declared extent. A short prefill chunk and a decode + * step are therefore clean while a full batch is not, and the discriminator is not + * `n_tok == max_tok` but how far past the end the write reaches and what the arena + * put there. core/runtime/issue.cpp carries the guard that refuses an operand reaching + * past its declaration. + * + * RADIANCE_DEBUG_ROUTING: a composition fault in a routed model shows up here first. + * It SYNCHRONISES THE STREAM, which is exactly what the copy above exists to avoid -- + * so it is an environment variable, off, and costs nothing when it is not set. The + * value is the layer to print. */ + static const char* dbg = std::getenv("RADIANCE_DEBUG_ROUTING"); + if (copy && dbg && layer == (int)std::strtol(dbg, nullptr, 10) && step < 3) { + RAD_TRY(route_flush()); + rad_stream_sync(stream_); + /* READ THE DEVICE BUFFER AGAIN, SYNCHRONOUSLY, and print both totals. The staging + * copy is asynchronous and this print is the only reader of it, so a disagreement + * here says the copy raced and an agreement says the histogram itself is what it + * is. Debug-only, so the extra transfer costs nothing when the variable is off. */ + std::vector direct((size_t)n, 0); + int64_t dtot = 0; + if (rad_memcpy_async(direct.data(), r->expert_count, + n * (int64_t)sizeof(int32_t), stream_) >= 0 && + rad_stream_sync(stream_) >= 0) + for (int64_t i = 0; i < n; ++i) dtot += direct[(size_t)i]; + const int32_t* h = s.staging[bank]; + int64_t tot = 0, used = 0, mx = 0; int arg = 0; + for (int64_t i = 0; i < n; ++i) { + tot += h[i]; + if (h[i]) ++used; + if (h[i] > mx) { mx = h[i]; arg = (int)i; } + } + std::string first; + for (int64_t i = 0; i < n && i < 24; ++i) + first += (i ? "," : "") + std::to_string(h[i]); + RAD_WARN("routing layer %d step %d: %lld experts of %lld used, %lld placements " + "(direct read %lld), max %lld at e%d; first 24 = [%s]", + layer, step, (long long)used, (long long)n, (long long)tot, + (long long)dtot, (long long)mx, arg, first.c_str()); + } + } + } + return RAD_OK; +} + +/* THE OLDEST LANDED BANK THIS LAYER HAS NOT BEEN CREDITED FOR, or -1 when there is none. + * + * OLDEST AND NOT NEWEST, because the caller drains in a loop and the heat engine decays a layer's + * plane on every observation. Fed newest-first, a burst would apply the most recent decay to the + * oldest evidence and rank the plane by an order the device never produced. + * + * A BANK IS SKIPPED UNTIL ITS COPY HAS COMPLETED. `step[b]` is stamped when the copy is ISSUED, + * which on a long prefill chunk is many steps before the device reaches it; reading the staging + * then would hand back whatever the bank's previous occupant left in it, which is a histogram from + * kRouteBanks steps ago wearing this step's number. The event is the only thing that separates + * the two, so it is queried rather than assumed -- and that also excludes a half-written bank, + * which a mid-step reader would otherwise see. + * + * A BANK OF A STEP STILL BEING ISSUED IS SKIPPED TOO, landed or not: a later pass of that step can + * still report into it. See `before_step` in ctx.h. + */ +void Ctx::mark_credited(int layer, int bank) { + if (layer < 0 || (size_t)layer >= route_.size()) return; + if (bank < 0 || bank >= kRouteBanks) return; + route_[(size_t)layer].credited[bank] = true; +} + +int Ctx::next_histogram(int layer, int after_step, int before_step, int8_t* landed) const { + if (layer < 0 || (size_t)layer >= route_.size()) return -1; + const RouteSlot& s = route_[(size_t)layer]; + int best = -1; + for (int b = 0; b < kRouteBanks; ++b) { + if (s.step[b] < 0 || s.step[b] <= after_step || s.step[b] >= before_step) continue; + if (best >= 0 && s.step[b] >= s.step[best]) continue; + int8_t ok = landed ? landed[b] : (int8_t)-1; + if (ok < 0) { + ok = (route_done_[b] && rad_event_query(route_done_[b]) == 1) ? 1 : 0; + if (landed) landed[b] = ok; + } + if (!ok) continue; + best = b; + } + return best; +} + +const int32_t* Ctx::last_histogram(int layer, int bank) const { + if (layer < 0 || (size_t)layer >= route_.size()) return nullptr; + if (bank < 0 || bank >= kRouteBanks) return nullptr; + const RouteSlot& s = route_[(size_t)layer]; + return s.step[bank] >= 0 ? s.staging[bank] : nullptr; +} + +int Ctx::last_histogram_step(int layer, int bank) const { + if (layer < 0 || (size_t)layer >= route_.size()) return -1; + if (bank < 0 || bank >= kRouteBanks) return -1; + return route_[(size_t)layer].step[bank]; +} + +int Ctx::last_histogram_reports(int layer, int bank) const { + if (layer < 0 || (size_t)layer >= route_.size()) return 0; + if (bank < 0 || bank >= kRouteBanks) return 0; + return route_[(size_t)layer].reports[bank]; +} + +const RadRouting* Ctx::last_routing(int layer) const { + if (layer < 0 || (size_t)layer >= route_.size()) return nullptr; + return route_[(size_t)layer].reported >= 0 ? &route_[(size_t)layer].routing : nullptr; +} + +/* ================================================================== profiling (spec §16) */ + +int Ctx::bind_profiling() { + prof_ms_.assign(program_->ops.size(), 0.0); + prof_calls_.assign(program_->ops.size(), 0); + prof_host_.assign(program_->ops.size(), 0); + prof_join_ms_.assign(program_->ops.size(), 0.0); + if (!profiling_) return RAD_OK; + + /* Printed, not buried in a doc. Anyone reading a profiled run's numbers has to see this on the + * same terminal that produced them. */ + RAD_WARN("per-op timing is ON. It restores synchronisations that change the mover's slot " + "supply, so THIS RUN IS NOT COMPARABLE against an unprofiled one (spec §16). " + "Anything being measured across builds runs without it."); + + /* A fixed ring, allocated here, because the step path does not allocate. 8192 pairs covers a + * 64-layer model at ~20 ops a layer with room for speculation; past that we stop timing and + * say so, rather than growing a vector inside a step. + * + * CARD-LOCAL EVENTS, NOT HOST-WAIT ONES. A host-wait record takes an interrupt signal, of which + * a process has a few thousand, and every pair recorded in a step holds two until the pair is + * recorded again a step later: a prefill step on a large model records more pairs than that + * across the ranks, and the engine's own staging event then has no signal left to take. The + * host never waits on these one at a time -- profile_collect waits for the stream once -- and + * a card-scope release keeps the records from waiting out writes still on their way to the + * host, which would be charged to the op they bracket. */ + const size_t cap = 8192; + prof_ring_.resize(cap); + for (size_t i = 0; i < cap; ++i) { + if (rad_event_create_local(&prof_ring_[i].a) < 0 || + rad_event_create_local(&prof_ring_[i].b) < 0) { + RAD_ERR("per-op timing: could not create %zu event pairs", cap); + return RAD_E_DEVICE; + } + } + return RAD_OK; +} + +void Ctx::profile_collect() { + /* This is the synchronisation the caveat above is about. It is here, at the end of the step, + * rather than per launch, so at least the ordering inside a step is undisturbed -- but the + * mover's slot supply still sees a step boundary it would not otherwise see. */ + if (prof_n_ > 0) { + /* Lane 1 is already joined into the compute stream (end of step), so that stream finishing + * is every bracketed launch finishing. */ + ++n_host_syncs_; /* counted, so the caveat is a number and not a claim */ + if (rad_stream_sync(stream_) < 0) prof_n_ = 0; + } + for (size_t i = 0; i < prof_n_; ++i) { + ProfSlot& s = prof_ring_[i]; + float ms = 0.0f; + if (rad_event_elapsed_ms(s.a, s.b, &ms) < 0) continue; + prof_ms_[(size_t)s.op] += (double)ms; + prof_calls_[(size_t)s.op] += 1; + } + if (prof_overflowed_) { + RAD_WARN("per-op timing: the step issued more than %zu ops; the tail was not timed", + prof_ring_.size()); + prof_overflowed_ = false; + } + prof_n_ = 0; +} + +void Ctx::dump_profile() const { + if (!profiling_) { RAD_WARN("per-op timing was not enabled for this run"); return; } + if (!program_) { RAD_WARN("per-op timing: the context has already been shut down"); return; } + + fprintf(stderr, + "\nper-op timing, rank %d. NOT COMPARABLE against an unprofiled run:\n" + "enabling this restores synchronisations that change the mover's slot supply.\n" + "A row marked `host` was timed on the HOST CLOCK around a host-site launch and\n" + "includes everything that call waited on -- page faults, link reads. The rest are\n" + "device event pairs around a kernel.\n\n" + " %10s %12s %10s %5s %10s %s\n", rank_, "calls", "total ms", "us/call", "site", + "join us", "op / geometry"); + + /* Slowest first: the only ordering anybody reads this table in. */ + std::vector order; + for (size_t i = 1; i < prof_calls_.size(); ++i) if (prof_calls_[i]) order.push_back(i); + std::sort(order.begin(), order.end(), + [&](size_t a, size_t b) { return prof_ms_[a] > prof_ms_[b]; }); + + double total = 0.0; + for (size_t i : order) { + const OpInfo& o = program_->ops[i]; + const bool ho = i < prof_host_.size() && prof_host_[i]; + char jbuf[32] = " -"; + if (ho && i < prof_join_ms_.size()) + std::snprintf(jbuf, sizeof jbuf, "%10.2f", + prof_join_ms_[i] * 1000.0 / (double)prof_calls_[i]); + /* The op's position and its first weight name the LAYER: every layer's instance of an + * op declares the same geometry, so without them sixty rows read alike and a per-layer + * cost -- residency, a pooled expert streamed by one layer and not the next -- cannot be + * tied to anything. */ + const char* wname = !o.weights.empty() && o.weights[0] < program_->weights.size() + ? program_->weights[o.weights[0]].name.c_str() : "-"; + fprintf(stderr, " %10lld %12.3f %10.2f %5s %s %s %s #%d %s\n", + (long long)prof_calls_[i], prof_ms_[i], + prof_ms_[i] * 1000.0 / (double)prof_calls_[i], ho ? "host" : "dev", jbuf, + o.op.c_str(), o.base.str().c_str(), (int)o.index, wname); + total += prof_ms_[i]; + } + fprintf(stderr, " %10s %12.3f\n\n", "total", total); +} + +/* ================================================================== the step driver */ + +/* LAZY, AND THAT IS THE POINT: an architecture that never asks for a second lane must take the + * same code path an architecture with one lane would take if this feature did not exist, so that + * "the lane costs nothing when unused" is a property of the source rather than a claim about a + * measurement. Building the stream eagerly would make it one -- and one that is hard to establish, + * because a second stream's cost is small enough to sit inside the run-to-run spread a warming + * part produces. */ +int Ctx::lane_init() { + if (lane1_) return RAD_OK; + RAD_TRY(rad_dev_set(device_)); + RAD_TRY(rad_stream_create(&lane1_, 0)); + own_lane1_ = true; + /* Local: a lane join orders one card's two queues and nothing else reads through it. */ + for (int i = 0; i < 2; ++i) + if (!lane_ev_[i]) RAD_TRY(rad_event_create_local(&lane_ev_[i])); + return RAD_OK; +} + +int Ctx::set_lane(int lane) { + if (lane != 0 && lane != 1) return RAD_E_INVAL; + if (lane == 0 && !lane1_) { lane_ = 0; return RAD_OK; } /* lane 0 needs nothing built */ + RAD_TRY(lane_init()); + lane_ = lane; + return RAD_OK; +} + +int Ctx::lane_join(int from, int to) { + if (from == to) return RAD_OK; + if (from < 0 || from > 1 || to < 0 || to > 1) return RAD_E_INVAL; + /* Nothing was ever issued on lane 1, so there is nothing to order against. This is the arm + * every unpipelined step takes at the end of run_step, and it must not build a stream. */ + if (!lane1_) return RAD_OK; + RadStream fs = from ? lane1_ : stream_, ts = to ? lane1_ : stream_; + RAD_TRY(rad_event_record(lane_ev_[from], fs)); + RAD_TRY(rad_event_wait(ts, lane_ev_[from])); + scratch_open_[from] = false; /* `to` is now behind every scratch user `from` issued */ + return RAD_OK; +} + +/* ================================================================== recorded passes */ +/* See "recorded passes" in ctx.h. */ + +uint64_t Ctx::pass_key(const RadBatch* b) const { + /* An encoder pass is shaped by its media, and a pass that carries encoder rows issues the + * scatter that puts them in place only when it has some: neither repeats as a tape would. */ + if (b->enc || b->n_mm_rows > 0) return 0; + uint64_t h = 0x9e3779b97f4a7c15ull; + auto mix = [&](uint64_t v) { + h ^= v + 0x9e3779b97f4a7c15ull + (h << 6) + (h >> 2); + h *= 0xbf58476d1ce4e5b9ull; + }; + auto ptr = [&](const void* p) { mix((uint64_t)(uintptr_t)p); }; + mix((uint64_t)b->phase); mix((uint64_t)b->n_tok); mix((uint64_t)b->n_seq); + mix((uint64_t)b->n_out); mix((uint64_t)b->max_q_len); mix((uint64_t)b->max_ctx_len); + mix((uint64_t)b->n_kv_groups); mix((uint64_t)b->n_spec); mix((uint64_t)b->draft_pass); + mix((uint64_t)b->n_checkpoints); mix((uint64_t)b->n_seq_decode); + mix((uint64_t)b->n_tok_decode); mix((uint64_t)b->max_q_len_decode); + mix((uint64_t)b->max_q_len_prefill); mix((uint64_t)b->n_draft_out); mix((uint64_t)b->n_ahead); + mix((uint64_t)b->rope_mixed); ptr(b->rope_pos); + ptr(b->token_ids); ptr(b->positions); ptr(b->cu_seqlens); ptr(b->seq_ids); + ptr(b->out_ids); ptr(b->q_lens); ptr(b->ctx_lens); ptr(b->num_accepted); + ptr(b->spec_parent); ptr(b->checkpoint_tok); ptr(b->checkpoint_slot); ptr(b->draft_out_ids); + for (int g = 0; g < b->n_kv_groups; ++g) { + const RadKVGroupBatch& k = b->kv[g]; + mix((uint64_t)k.group); ptr(k.slot_mapping); ptr(k.block_table); + mix((uint64_t)k.block_table_pitch); ptr(k.seqused); ptr(k.state_index); + mix((uint64_t)k.state_index_pitch); mix((uint64_t)k.block_size); mix((uint64_t)k.max_blocks); + } + mix((uint64_t)level_); + mix(w_tmpl_epoch_); + mix(dense_epoch_); + mix(domain_epoch_.load(std::memory_order_relaxed)); + ptr(arena_.base()); + mix((lane1_ ? 1u : 0u) | (host_touch_pending_[0] ? 2u : 0u) | (host_touch_pending_[1] ? 4u : 0u) | + (scratch_open_[0] ? 8u : 0u) | (scratch_open_[1] ? 16u : 0u)); + return h | 1; +} + +bool Ctx::tape_seen(uint64_t key) { + for (uint64_t k : tape_seen_) if (k == key) return true; + tape_seen_[tape_seen_at_++ % (sizeof tape_seen_ / sizeof tape_seen_[0])] = key; + return false; +} + +void Ctx::tape_cut() { + const int m = tape_mark(); + if (m > rec_mark_) { + TapeStep st; + st.kind = kTapePlay; + st.a = rec_mark_; + st.b = m; + rec_->steps.push_back(st); + } + rec_mark_ = m; +} + +void Ctx::tape_drop(PassTape& t) { + if (t.dev) tape_destroy(t.dev); + t.dev = nullptr; +} + +/* Issues the pass for real, through the architecture, recording it. Returns 1 when `out` holds a + * tape, 0 when the pass ran but cannot be recorded. */ +int Ctx::record_pass(const RadBatch* b, uint64_t key, PassTape* out) { + *out = PassTape{}; + out->key = key; + if (tape_begin() < 0) { arch_step_(this, b); return 0; } + const int64_t i0 = n_issues_, c0 = ar_calls_.load(), y0 = ar_bytes_.load(); + rec_ = out; + rec_mark_ = 0; + haz_ops_.clear(); + haz_rng_.clear(); + arch_step_(this, b); + tape_cut(); + rec_ = nullptr; + RadTape t = tape_end(step_status_ >= 0); + if (!t) { + if (step_status_ >= 0) { + tape_refused_.push_back(key); + RAD_WARN("rank %d: draft pass %d at %lld tokens is issued in full every step: %s", + rank_, b->draft_pass, (long long)b->n_tok, rad_dev_last_error()); + } + return 0; + } + out->dev = t; + out->issues = n_issues_ - i0; + out->ar_calls = ar_calls_.load() - c0; + out->ar_bytes = ar_bytes_.load() - y0; + out->touch_pending[0] = host_touch_pending_[0]; + out->touch_pending[1] = host_touch_pending_[1]; + out->scratch_open[0] = scratch_open_[0]; + out->scratch_open[1] = scratch_open_[1]; + if (haz_mark(*out) < 0) { + tape_destroy(t); + out->dev = nullptr; + return 0; + } + const int bit = b->draft_pass + 8; + if (rank_ == 0 && bit >= 0 && bit < 64 && !(tape_told_ & (1ull << bit))) { + tape_told_ |= 1ull << bit; + RAD_INFO("recorded pass: draft pass %d at %lld token(s) -- %d records, %d of the %d " + "dispatches unordered behind the one before; %zu host op(s), " + "%zu table refresh point(s) and %zu routing report(s) between the played " + "stretches", b->draft_pass, (long long)b->n_tok, tape_len(t), out->unordered, + out->dispatches, out->host.size(), + (size_t)std::count_if(out->steps.begin(), out->steps.end(), + [](const TapeStep& st) { return st.kind == kTapeTable; }), + out->route.size()); + } + return 1; +} + +/* WHICH DISPATCHES OF A RECORDED PASS CAN START BEFORE THE ONES IN FRONT OF THEM FINISH. + * + * Walked once, in queue order, per queue: the ops launched since the queue last ordered a packet + * are in flight together, and the next op may join them when it reads nothing they write and + * writes nothing they read or write. Anything the walk cannot see into orders its packet: the + * dispatch after an event, every dispatch after an op's first (an op's own dispatches depend on + * each other), a dispatch no op owns (a routing copy), and an opaque op on either side. A run is + * cut at kTapeOverlapRun, the bound the backend reclaims its argument slots on. + * + * The host work between played stretches needs nothing here. A host op joins the device work it + * depends on before it runs, and whatever a stretch of host work puts on a queue -- a table patch, + * a mover wait -- makes the backend order the next played packet on that queue itself. */ +int Ctx::haz_mark(PassTape& t) { + const int n = tape_len(t.dev); + if (n < 0) return n; + std::vector first_of((size_t)n, -1), part_of((size_t)n, -1); + for (size_t k = 0; k < haz_ops_.size(); ++k) { + const HazOp& o = haz_ops_[k]; + if (o.rec0 < 0 || o.rec1 > n) continue; + first_of[(size_t)o.rec0] = (int32_t)k; + for (int32_t r = o.rec0; r < o.rec1; ++r) part_of[(size_t)r] = (int32_t)k; + } + auto overlaps = [&](uint32_t a, uint32_t na, uint32_t b, uint32_t nb) { + for (uint32_t i = 0; i < na; ++i) + for (uint32_t j = 0; j < nb; ++j) + if (haz_rng_[a + i].first < haz_rng_[b + j].second && + haz_rng_[b + j].first < haz_rng_[a + i].second) + return true; + return false; + }; + struct Q { + uint32_t id = 0; + std::vector infl; /* ops in flight since the last ordered packet */ + bool opaque = true; /* something unknown is among them */ + int run = 0; + }; + std::vector qs; + for (int i = 0; i < n; ++i) { + int kind = 0; + uint32_t qid = 0; + const int rc = tape_record(t.dev, i, &kind, &qid); + if (rc < 0) return rc; + Q* q = nullptr; + for (Q& x : qs) if (x.id == qid) { q = &x; break; } + if (!q) { qs.push_back(Q{}); q = &qs.back(); q->id = qid; } + /* An event's packet, and the dispatch after it is ordered too: a wait is complete only + * once the event it names is, and nothing after it may start before that. */ + if (kind != 0) { q->infl.clear(); q->opaque = true; q->run = 0; continue; } + ++t.dispatches; + + const int32_t op = first_of[(size_t)i]; + bool ok = op >= 0 && !q->opaque && !haz_ops_[(size_t)op].opaque && q->run < kTapeOverlapRun; + if (ok) { + const HazOp& h = haz_ops_[(size_t)op]; + for (int32_t x : q->infl) { + const HazOp& f = haz_ops_[(size_t)x]; + if (overlaps(h.rd, h.n_rd, f.wr, f.n_wr) || overlaps(h.wr, h.n_wr, f.rd, f.n_rd) || + overlaps(h.wr, h.n_wr, f.wr, f.n_wr)) { ok = false; break; } + } + } + if (ok) { + const int sc = tape_set_overlap(t.dev, i, true); + if (sc < 0) return sc; + q->infl.push_back(op); + ++q->run; + ++t.unordered; + continue; + } + /* Ordered: everything before it has finished, and it is what is in flight now. */ + const int32_t own = part_of[(size_t)i]; + q->infl.clear(); + if (own >= 0) q->infl.push_back(own); + q->opaque = own < 0 || haz_ops_[(size_t)own].opaque; + q->run = 0; + } + return RAD_OK; +} + +/* Two recordings of one key, compared: the backend's records, and the host work between them. */ +bool Ctx::tapes_agree(const PassTape& a, const PassTape& b, std::string* why) { + if (a.steps.size() != b.steps.size()) { + *why = fmt("%zu stretches against %zu", a.steps.size(), b.steps.size()); + return false; + } + for (size_t i = 0; i < a.steps.size(); ++i) { + const TapeStep& x = a.steps[i]; + const TapeStep& y = b.steps[i]; + if (x.kind != y.kind || x.lane != y.lane || x.opd != y.opd || x.a != y.a || x.b != y.b) { + *why = fmt("stretch %zu: kind %d [%d, %d) lane %d against kind %d [%d, %d) lane %d", i, + x.kind, x.a, x.b, x.lane, y.kind, y.a, y.b, y.lane); + return false; + } + } + for (size_t i = 0; i < a.host.size(); ++i) { + const TapeHost& x = a.host[i]; + const TapeHost& y = b.host[i]; + bool same = x.h == y.h && x.launch == y.launch && x.n == y.n && x.drain == y.drain && + x.args.n_t == y.args.n_t && x.args.scratch == y.args.scratch; + for (int k = 0; same && k < x.args.n_t; ++k) + same = std::memcmp(&x.t[k], &y.t[k], sizeof(RadTensor)) == 0; + if (!same) { *why = fmt("host op %zu (op %u) differs", i, (unsigned)x.h); return false; } + } + for (size_t i = 0; i < a.route.size(); ++i) + if (a.route[i].first != b.route[i].first || + std::memcmp(&a.route[i].second, &b.route[i].second, sizeof(RadRouting)) != 0) { + *why = fmt("routing report %zu (layer %d) differs", i, a.route[i].first); + return false; + } + std::string d; + if (tape_diff(a.dev, b.dev, &d) >= 0) { *why = d; return false; } + return true; +} + +int Ctx::play_pass(PassTape& t) { + const int l0 = lane_; + for (const TapeStep& st : t.steps) { + int rc = RAD_OK; + switch (st.kind) { + case kTapePlay: + rc = tape_play(t.dev, st.a, st.b); + if (rc < 0) step_fail_ = fmt("a recorded pass could not be submitted: %s", + rad_dev_last_error()); + break; + case kTapeTable: { + WeightTable& wt = wtabs_[(size_t)st.a]; + if (wt.full || !wt.pend.empty()) { + lane_ = st.lane; + rc = table_refresh((rad_op)st.b, st.opd, wt); + lane_ = l0; + } + break; + } + case kTapeHost: { + TapeHost& th = t.host[(size_t)st.a]; + lane_ = st.lane; + rc = host_join_wait(th.drain); + if (rc >= 0) { + th.args.t = th.t; + rc = th.launch(&th.args, cur_stream()); + rad_dev_host_wrote(); + } + lane_ = l0; + if (rc < 0) step_fail_ = fmt("a host op of a recorded pass (op %u) failed: %s", + (unsigned)th.h, rad_strerror(rc)); + break; + } + case kTapeRoute: + rc = route_report_impl(t.route[(size_t)st.a].first, &t.route[(size_t)st.a].second, + false); + break; + } + if (rc < 0) { + if (step_status_ >= 0) step_status_ = rc; + return rc; + } + } + n_issues_ += t.issues; + ar_calls_.fetch_add(t.ar_calls, std::memory_order_relaxed); + ar_bytes_.fetch_add(t.ar_bytes, std::memory_order_relaxed); + host_touch_pending_[0] = t.touch_pending[0]; + host_touch_pending_[1] = t.touch_pending[1]; + scratch_open_[0] = t.scratch_open[0]; + scratch_open_[1] = t.scratch_open[1]; + ++t.plays; + t.used = ++tape_clock_; + return RAD_OK; +} + +/* THE PASS: played from its tape, or issued -- and recorded, or checked against its tape. */ +int Ctx::run_pass(const RadBatch* b) { + const auto bump = [](std::atomic& c) { c.fetch_add(1, std::memory_order_relaxed); }; + scratch_cur_[0] = scratch_cur_[1] = 0; + /* A pass the stager armed for is issued live: see runtime/stager.h. */ + if (!tape_on_ || staging_) { bump(pc_unkeyed_); arch_step_(this, b); return RAD_OK; } + const uint64_t key = pass_key(b); + if (key == 0) { bump(pc_unkeyed_); arch_step_(this, b); return RAD_OK; } + if (std::find(tape_refused_.begin(), tape_refused_.end(), key) != tape_refused_.end()) { + bump(pc_refused_); + arch_step_(this, b); + return RAD_OK; + } + PassTape* t = nullptr; + for (PassTape& x : tapes_) if (x.key == key) { t = &x; break; } + + if (t && t->plays > 0 && t->plays % kAuditPlays != 0) { + bump(pc_played_); + pc_dispatched_.fetch_add(t->dispatches, std::memory_order_relaxed); + pc_unordered_.fetch_add(t->unordered, std::memory_order_relaxed); + return play_pass(*t); + } + + if (t) { + bump(pc_audited_); + /* The check: issue the pass for real, recording it, and compare. The first comparison + * comes before the tape is ever played, and then one every kAuditPlays plays. */ + PassTape fresh; + if (!record_pass(b, key, &fresh)) return RAD_OK; + std::string why; + if (!tapes_agree(*t, fresh, &why)) { + tape_drop(*t); + *t = std::move(fresh); + t->used = ++tape_clock_; + step_fail_ = fmt("rank %d: draft pass %d at %lld tokens issued differently from its " + "recording after %lld plays, so the pass depends on something the " + "recording's key does not carry: %s", rank_, b->draft_pass, + (long long)b->n_tok, (long long)t->plays, why.c_str()); + RAD_ERR("%s", step_fail_.c_str()); + step_status_ = RAD_E_STATE; + return RAD_E_STATE; + } + tape_drop(fresh); + ++t->plays; + t->used = ++tape_clock_; + return RAD_OK; + } + + /* A KEY IS RECORDED THE SECOND TIME IT IS SEEN, so a pass that never recurs -- a prefill + * chunk, whose token count and positions are its own -- costs no recording and does not push + * a tape that will be played out of the least-recently-used set. A DECODE pass recurs by + * construction: the same shape runs every step until a sequence's context crosses its bound's + * bucket, and then the new key runs every step after that. Seen-once is a whole live issue + * spent learning that, at every crossing, so a decode pass is recorded the first time. The + * audit before its first play is unchanged. */ + if (b->phase != RAD_PHASE_DECODE && !tape_seen(key)) { + bump(pc_first_); + arch_step_(this, b); + return RAD_OK; + } + + bump(pc_recorded_); + PassTape nt; + if (!record_pass(b, key, &nt)) return RAD_OK; + nt.used = ++tape_clock_; + if (tapes_.size() < kTapes) { + tapes_.push_back(std::move(nt)); + } else { + PassTape* lru = &tapes_[0]; + for (PassTape& x : tapes_) if (x.used < lru->used) lru = &x; + tape_drop(*lru); + *lru = std::move(nt); + } + return RAD_OK; +} + +int Ctx::run_step(const RadBatch* b) { + + if (!b) return RAD_E_INVAL; + if (!arch_step_) { + RAD_WARN("Ctx::run_step: no architecture step function was installed"); + return RAD_E_STATE; + } + + /* The mover relocates between steps, never during one. Honouring WeightInfo::generation here + * costs one relaxed atomic load per step instead of one per weight per issue. */ + if (weights_dirty_.exchange(false, std::memory_order_acq_rel)) + bind_weights(/*refresh_only=*/true); + sync_residency(); + + batch_ = b; + step_status_ = RAD_OK; + step_fail_.clear(); + prof_n_ = 0; + in_step_ = true; + + staging_ = stager_ != nullptr && stager_->begin_pass(b); + { + const int rc = run_pass(b); + if (rc < 0 && step_status_ >= 0) step_status_ = rc; + } + + /* EVERY LANE JOINS BACK BEFORE THE STEP ENDS, whatever the architecture did or forgot to do. + * The engine synchronises the COMPUTE stream to know a step is finished; work still queued on + * lane 1 would be read by the sampler, or freed under, while it was in flight. Ordering lane 0 + * behind lane 1 here costs one event record and one wait on a step that never used lane 1 -- + * and it means a plugin cannot leave the runtime in a state where that is possible. */ + lane_ = 0; + lane_join(1, 0); /* a no-op, and allocates nothing, when lane 1 is unbuilt */; + /* Behind the join, so the compute stream is behind every reader of what the stager published; + * and whatever the pass's status, because a staged weight must never outlive its pass. */ + if (staging_) { + const int se = stager_->end_pass(stream_); + if (se < 0 && step_status_ >= 0) step_status_ = se; + staging_ = false; + } + { + const int rf = route_flush(); + if (rf < 0 && step_status_ >= 0) step_status_ = rf; + } + + in_step_ = false; + if (profiling_) profile_collect(); + flush_issued(); + return step_status_; +} + +/* WHICH DECLARED OPS THE RUN PHASE HAS ACTUALLY ISSUED, copied out of the per-step plans into the + * Program the graph dump reads. Walks only the ops not yet seen issued and drops each one as it + * fires, so the cost falls away within a few steps to the ops that have never fired -- and those + * are exactly what a reader of this field is looking for. Shrinking in place, so no allocation on + * the step path. */ +void Ctx::flush_issued() { + size_t w = 0; + for (size_t r = 0; r < unflushed_.size(); ++r) { + const uint32_t i = unflushed_[r]; + if (i < plans_.size() && i < program_->ops.size() && plans_[i].issued) + program_->ops[i].issued = true; + else + unflushed_[w++] = i; + } + unflushed_.resize(w); +} + +} /* namespace rad */ diff --git a/core/runtime/ctx.h b/core/runtime/ctx.h new file mode 100644 index 00000000..8a231df4 --- /dev/null +++ b/core/runtime/ctx.h @@ -0,0 +1,807 @@ +/* ctx.h -- the run phase. Ordinary C++ with one rule: it may only issue handles obtained during + * declare (spec §3.2). Nothing else is constrained, and its whole job is to be cheap. + * + * Everything expensive already happened. Declare resolved every op against the kernel hierarchy + * per band and per domain, the buffer plan sized one arena for the worst step, and the planner + * assigned every weight a tier and a site. What is left for a step is: index a bucket table with + * an integer, copy a tensor template per operand, patch in the pointers, and launch. The per-issue + * work is filling a struct we already own, not constructing one. + * + * COST. An issue is single-digit nanoseconds. Nearly all of it is the RadTensor template copies at + * 112 bytes each; the band scan is one or two compares off a cache line and the RadArgs patch is a + * single store. tests/runtime_test.cpp times it and prints it, so the number is checkable rather + * than claimed, and it is a tripwire -- a hundredfold miss means somebody put an allocation or a + * map lookup back on this path. + * + * At a 64-layer model issuing ~20 ops a layer that is ~1280 issues, so order ten microseconds of + * CORE time per decode step. Spec §3.2 accepts roughly 1-2 ms of launch overhead per step at 64 + * layers; the rest of that budget is the driver's own per-launch dispatch cost -- order 1 us per + * hipLaunchKernel, which is what 1280 launches actually costs -- and it is not ours to spend. It is + * also what HIP-graph capture would attack if v1 wanted it, which §3.2 says is a change to that + * section and not to the ABI. The core is therefore not where the step budget goes, against a + * Python engine's 10-20 ms of the same thing. + * + * A residency table with a pending event adds one rad_event_wait -- once per weight per + * GENERATION, not per issue, which is why residency.h makes the mover bump it. + */ +#pragma once +#include "../rad_core.h" +#include "arena.h" +#include "rank_barrier.h" +#include "residency.h" +#include "stager.h" +#include "device/device.h" + +#include +#include +#include +#include + +/* RadCtx is opaque in the ABI: rad_runtime.h forward-declares it and nothing else. Completing it + * here as an empty base gives a well-defined static_cast from the C handle to the C++ object, + * instead of a reinterpret_cast that merely happens to work. The run phase is the only component + * that ever holds one, so this is the right place for the definition. */ +struct RadCtx { }; + +namespace rad { + +/* The widest op in the conventional vocabulary is gdn_conv_prep at sixteen operands, with + * gdn_recurrent_update behind it at fourteen -- both grew when the two kernel plugins' schemas + * were reconciled (docs/OPS.md, "How a schema is written"). Thirty-two leaves room for an + * architecture plugin's private ops without putting a variable-length array on the hot path. */ +constexpr int MAX_OPERANDS = 32; + +typedef void (*ArchStepFn)(RadCtx*, const RadBatch*); + +/* ------------------------------------------------------------------ the issue plan */ +/* One resolved (op, band, domain) with everything that does not change per issue already filled + * in: the geometry view the kernel reads its parameters out of, the scratch pointer, the instance + * init() returned, the rank and the world size. Per issue we set `t` and `n_t` and call `launch`. + * + * `launch` is hoisted out of row->info so the fast path chases one pointer rather than two, and + * `row` is diagnostics only -- it is read when a launch fails and never otherwise. */ +struct IssuePlan { + RadArgs args{}; + RadLaunchFn launch = nullptr; + const KernelRow* row = nullptr; +}; + +/* Per declared op. Trivially copyable on purpose: the bucket table and the issue plans live in two + * flat Ctx-owned arrays and this holds offsets into them, so a step touches one small dense record + * per op instead of walking two vectors' worth of indirection. */ +struct OpPlan { + const OpInfo* info = nullptr; + int32_t band_off = 0; /* into Ctx::band_table_ */ + int32_t n_bands = 0; + int32_t plan_off = 0; /* into Ctx::issue_table_, band * RAD_N_DOMAINS + domain */ + /* The schema's operand count, copied here so the arity check is a compare against a hot field + * rather than two pointer chases into a cold OpInfo. -1 when the op has no schema. */ + int32_t n_opd_schema = -1; + bool issued = false; /* did the run phase ever issue it (spec §16's graph dump) */ + /* IS THIS OP A COLLECTIVE -- i.e. does issuing it put bytes on the interconnect? Set once at + * bind, so the accounting on the issue path is a predicted branch and not a string compare. + * The link is shared with the expert mover, so separating "how much of it is the all-reduce" + * needs the collective's own traffic counted. */ + bool collective = false; +}; + +/* ------------------------------------------------------------------ routing handoff */ +/* A RING OF STAGING BANKS, indexed by step, so that the heat engine reads a histogram the device + * actually wrote rather than one still queued behind it. + * + * TWO BANKS ARE NOT ENOUGH AND THE REASON IS THE HOST'S RUN-AHEAD. The dispatch that consumes + * these runs before the step is issued and every issue path returns immediately, so on a long + * prefill chunk -- most of a second of device time -- the host reaches the end of the prompt while + * the card is still on its first chunks. With two banks, the copy for step S is overwritten by the + * one for S+2 long before the device has reached either, the freshest bank always holds a copy in + * flight, and the engine skips the layer: over 41 chunks of 2048 tokens, two banks credit 79 + * layer-histograms and skip 3800 as not yet landed. + * + * THE BYTES ARE NOT THE PROBLEM -- the device does execute every copy, in order, spread over its + * own progress. A shallow ring overwrites them before anyone reads them. A ring as deep as the + * run-ahead keeps each one until it is credited, and the dispatch drains every landed bank rather + * than only the newest, so a burst of host steps followed by a wait still credits every histogram + * the card produced in between. + * + * DEPTH IS A MEMORY-FOR-EVIDENCE TRADE AND IT IS CHEAP: one int32 an expert a bank a layer, which + * on a 49-layer 254-expert plane is about 50 KiB a bank. What it cannot do is exceed the run-ahead + * for free, so the engine counts what it still loses and prints it -- see the routing-evidence + * line at shutdown. */ +static const int kRouteBanks = 32; + +struct RouteSlot { + RadRouting routing{}; + int32_t* staging[kRouteBanks] = {}; /* this layer's row of the bank's host copy */ + int step[kRouteBanks] = {}; + /* HOW MANY TIMES THIS LAYER REPORTED INTO THAT BANK, which is not always once. A bank is + * indexed by the step, so every report a layer makes WITHIN one step lands in the same one + * and overwrites the last -- and a speculative draft head reports once per draft pass, n_spec + * times a step. Uncredited, the heat engine sees a fraction of that layer's routing and prices + * its experts accordingly, which starves a draft head's resident set relative to every other + * layer's. The histogram itself cannot be summed here -- it arrives by an async copy off the + * compute stream -- but the COUNT is free, and one pass credited n times is the right + * expectation when the passes route from the same distribution. + * + * THIS IS AN ACCOUNTING FIX, NOT A PERFORMANCE LEVER, and the distinction is the useful part. + * Crediting the passes raises that layer's resident expert count and tightens the spread + * across layers, and the step time does not move. + * + * WHY IT IS NULL IS THE THING TO REMEMBER: RESIDENCY AGAINST TIME IS CONVEX, STEEPLY. A cache + * whose hot set is already in has nothing left to gain from the marginal entry, and a layer + * holding more than half its experts already has its hot set in. Rescuing a layer at 35-45% + * residency is worth about a millisecond a step; topping one up from 55% to 63% is worth zero + * -- do not price the second from the first. + */ + int reports[kRouteBanks] = {}; + /* Whether the drain has taken this bank yet, which is what makes "the ring lost one" an exact + * count rather than an upper bound: a bank recycled while this is false held evidence nobody + * read. */ + bool credited[kRouteBanks] = {}; + int reported = -1; /* the last step this layer reported at all */ +}; + +/* ------------------------------------------------------------------ construction */ +/* Where a KV group's pool lives, per group, bound at load. RAD_OPK_KV resolves through this: + * RadKVGroupBatch carries the slot mapping, the block table and the sequence lengths, but the pool + * BASE belongs to the block manager and not to a per-step batch -- it does not change from step to + * step and rebuilding it every step would be work the arena exists to avoid. + * + * One cache per BOUND LAYER, so the operand's `offset` is the layer and `layer_stride` is what + * separates two layers of the same group. A group with no bound layers never gets here: the + * builder refuses it at declare, because its page size would otherwise be a guess. */ +/* ONE LAYER'S CACHE, WITH ITS SHAPE. The shape is here and not in the kernel because the core is + * where every number in it already lives: the group's RadKVGroupDecl gives the head count, the head + * dimension, the per-head state geometry and the conv width, and the block manager decided the + * block size, the block count and the state count. A kernel handed a flat span would have to + * reconstruct all of that from its own parameters -- and cannot: the conv window's depth is + * `conv_width - 1 + n_spec` and the slot count is `max_num_seqs`, neither of which appears in any + * op's parameter list. Shims check a cache operand's rank -- 4 for a paged cache, 3 for a conv + * window -- and refuse anything else, so a RAD_OPK_KV operand may not arrive as a flat byte span. + * + * The layouts are the ones libref/ref_ops.h states once for the whole project: + * + * FULL / WINDOW [n_blocks, n_head_kv, block_size, 2 * head_dim] K then V inside a slot + * LINEAR [n_states, n_head_kv, state_dim[0], state_dim[1]] + * CONV [n_states, n_head_kv * head_dim, conv_slots] channel-major, then time + */ +struct KVPoolBinding { + void* base = nullptr; + int64_t layer_stride = 0; /* bytes between one layer's cache and the next */ + int64_t bytes = 0; /* the whole group's pool, for the bounds check */ + uint32_t dtype = RAD_DT_INVALID; + /* THE OPERAND NAMES AN ABSOLUTE MODEL LAYER AND THE GROUP HOLDS ONE CACHE PER BOUND LAYER, so + * the rebase is a POSITION LOOKUP and not a subtraction. Subtracting the first bound layer is + * right only when a group's layers are contiguous, and they need not be -- 15 attention layers + * scattered through 64, say, where the fifth of them at absolute index 19 would come out as + * slot 16 of a 15-slot pool. Indexed by absolute layer; -1 means the group does not + * hold that layer, which is a caller bug rather than a runtime condition. */ + std::vector layer_slot; + uint32_t rank = 0; /* 0 when the group has no plan: the operand stays a flat span */ + int64_t shape[RAD_MAX_RANK] = {0}; +}; + +struct CtxDesc { + Program* program = nullptr; + int rank = 0; + int world_size = 1; + int device = 0; /* the one device this rank owns */ + RadStream stream = nullptr; /* null: the Ctx creates its own compute stream */ + ResidencyTable* residency = nullptr; /* null in the all-in-VRAM case */ + ArchStepFn arch_step = nullptr; /* the architecture plugin's rad_arch_step */ + bool profile_ops = false; /* spec §16, and it changes what you measure */ + /* Whether a repeated pass may be recorded and played back. False for a caller whose pass + * body issues work the batch does not describe -- a test driving another component through + * run_step -- so every pass is issued, since a recording keyed on the batch would stand for + * passes that differ. */ + bool record_passes = true; + + /* By rad_kvgroup. Empty until the KV manager has allocated, which is why it is bound here and + * not derived: a Ctx built before the pools exist would resolve every cache operand to null. */ + std::vector kv; +}; + +/* ------------------------------------------------------------------ Ctx */ +class Ctx : public RadCtx { +public: + Ctx() = default; + ~Ctx(); + Ctx(const Ctx&) = delete; + Ctx& operator=(const Ctx&) = delete; + + int init(const CtxDesc& d); + void shutdown(); + + /* ---------------------------------------------------------- the hot path */ + int issue(rad_op h, const RadOperand* opd, int n_opd, int64_t n); + /* A weight stager for the passes it arms for (runtime/stager.h); null for none. */ + void set_stager(OpStager* s) { stager_ = s; } + + /* ---------------------------------------------------------- the step driver */ + /* Sets the batch and calls the architecture plugin's rad_arch_step through the function + * pointer the engine handed us. Under tensor parallel N rank threads each own one Ctx and one + * device and are released against the SAME RadBatch by pointer (spec §1); the batch is const + * and nobody writes it during a step. Returns RAD_OK, or the negative status of the first + * kernel that refused -- rad_arch_step is void, so the abort has to be latched. */ + int run_step(const RadBatch* b); + + /* The rank thread must call this once before its first run_step: the device backend's "current + * device" is thread-local, and init may well have run on the engine's thread. */ + int bind_thread(); + + /* ---------------------------------------------------------- run-phase queries */ + const RadBatch* batch() const { return batch_; } + int rank() const { return rank_; } + int world_size() const { return world_size_; } + RadStream stream() const { return stream_; } + Program* program() const { return program_; } + + /* The lane subsequent issues launch on, and the stream that is. Lane 0 is `stream_` and is + * what every architecture that does not ask for a second lane ever sees. See lane1_ for the + * three things a second lane may not do. */ + RadStream cur_stream() const { return lane_ ? lane1_ : stream_; } + int lane() const { return lane_; } + int set_lane(int lane); + /* Builds the second stream and its events on first use. Never called by an architecture that + * does not ask for a lane, which is what keeps this feature free when it is unused. */ + int lane_init(); + /* Order `to` behind everything already issued on `from`: an event recorded on `from` that + * `to` waits for. The HOST does not block, and neither stream is drained -- this is the only + * thing that makes two lanes a pipeline rather than a race. */ + int lane_join(int from, int to); + + void* weight_ptr(rad_weight w); + void* buf_ptr(rad_buf b); + + /* ---------------------------------------------------------- routing (spec §5.5) */ + int route_report(int layer, const RadRouting* r); + /* Layer `layer`'s row of the card-side histogram, when it holds `n_expert` counts; null + * otherwise. A report naming this row is taken in place (see rad_route_counts). */ + int32_t* route_counts(int layer, int64_t n_expert) const { + if (!route_dev_ || layer < 0 || (size_t)layer >= route_.size() || n_expert <= 0 || + n_expert > route_n_expert_) + return nullptr; + return route_dev_ + (int64_t)layer * route_n_expert_; + } + /* How many layers reported routing, which is how many the heat engine has to sweep. Zero on a + * dense model, where nothing routes and bind_routing allocated nothing. */ + int n_route_layers() const { return (int)route_.size(); } + int64_t route_n_expert() const { return route_n_expert_; } + /* DRAIN, DO NOT SAMPLE. `next_histogram` returns the oldest staging bank holding a LANDED + * histogram for a step past `after_step` and before `before_step`, or -1; a caller loops on it + * with the step of the last one it credited and so sees every histogram the device produced, + * in order, rather than whichever one happened to be newest when it looked. The three readers + * below take the bank it returned. Null / -1 / 0 for a layer that has never reported. + * + * `before_step` IS THE STEP THE CALLER IS ABOUT TO ISSUE, and a bank of that step or later is + * not finished. A step runs as more than one pass when it drafts, every pass reports into the + * step's one bank, and the drain runs again before each of them: a bank credited between two + * passes stands for the passes so far, and the rest land after `after_step` has moved to that + * step, where nothing will ever read them. + * + * `landed`, when given, is kRouteBanks entries of -1 that this fills in as it asks: whether a + * bank's copy has landed is the bank's answer, not the layer's, so a sweep over every layer + * asks each bank's event once rather than once a layer. */ + int next_histogram(int layer, int after_step, int before_step, + int8_t* landed = nullptr) const; + const int32_t* last_histogram(int layer, int bank) const; + int last_histogram_step(int layer, int bank) const; + /* How many times that layer reported into that bank. 1 for every layer of a non-speculative + * step; n_spec for a draft head. See RouteSlot::reports. */ + int last_histogram_reports(int layer, int bank) const; + /* HISTOGRAMS THE RING LOST: a bank recycled for a later step while it still held an + * uncredited copy, which is what says the ring is shallower than the host's run-ahead. Nothing + * reads a dropped histogram, so this is the whole of the error in the routing-evidence + * accounting. A further pass of the SAME step reporting into its bank is not a loss: the bank + * counts it in `reports` and is credited for all of them at once. */ + uint64_t route_dropped() const { return route_dropped_; } + /* Told by the drain, so the ring knows which banks are still owed a reader. */ + void mark_credited(int layer, int bank); + const RadRouting* last_routing(int layer) const; + + /* ---------------------------------------------------------- the placement seam */ + /* Change an op's execution site. Refuses with RAD_E_NOKERNEL, naming the op and the band, if + * the requested domain has a hole in its bucket table -- §5.1 says the planner was told at + * declare which sites are unavailable, so asking for one anyway is a planner bug and not a + * runtime condition to paper over. */ + int set_op_domain(rad_op h, int domain); + int op_domain(rad_op h) const; + /* The mover calls this after relocating weights. WeightInfo::generation is honoured BETWEEN + * steps rather than per issue: a per-issue atomic load of a cold WeightInfo line costs more + * than the relocation it guards against, and within a step the ResidencyTable is the + * authority on where a weight is. */ + void note_weights_moved() { weights_dirty_.store(true, std::memory_order_release); } + + /* ---------------------------------------------------------- diagnostics */ + /* OpPlan::issued -> Program::ops[i].issued, which is what /graph publishes. Called at the end + * of every step, and it must be: without it the graph dump reports every op in the model as + * never issued, and a reader using that to find a dead declaration gets all of them. */ + void flush_issued(); + void dump_profile() const; /* spec §16, opt-in, with its caveat printed */ + const char* step_error() const { return step_fail_.c_str(); } + int64_t stream_waits() const { return n_stream_waits_; } + /* Host synchronisations the runtime performed on the STEP PATH. Zero, always, unless per-op + * timing is on -- which is the caveat in spec §16 expressed as a number a test can read, + * rather than a claim in a comment. Teardown's drain is not counted; it is not a step. */ + int64_t host_syncs() const { return n_host_syncs_; } + /* WHAT THIS RANK PUT ON THE INTERCONNECT, and why it is counted here rather than in the + * kernel. The link between the two cards carries two completely different things -- the + * tensor-parallel all-reduce after every attention and MLP block, and the expert mover's + * promotions and demotions -- and they compete for the same PCIe bytes. The mover counts its + * own (MoverStats) and this counts the collective's, so "is the link busy because the model is + * wide or because placement is thrashing" has an answer. + * + * `ar_bytes` is the MESSAGE PAYLOAD: numel * the operand's element size, summed over issues. + * At two ranks that IS the bytes this rank pushes across the link -- libr4d's one-shot exact + * kernel pushes the whole input into the peer's scratch once, and the two-shot's + * reduce-scatter plus all-gather is (N-1)/N of it twice, which is the same at N=2. At more + * ranks it is a floor. A lossy wire (--tp-wire) compresses below it and the number stays the + * payload, because what a reader is comparing against the mover's bytes is the traffic the + * model asked for, not the encoding it got. + * + * Relaxed atomics: written by this rank's step thread, read by whatever thread is drawing. */ + int64_t ar_calls() const { return ar_calls_.load(std::memory_order_relaxed); } + int64_t ar_bytes() const { return ar_bytes_.load(std::memory_order_relaxed); } + + /* HOW EACH PASS WAS RUN, since the host cost of a pass is almost all in which of these it + * took: a play writes the recorded packets, every other outcome walks the architecture's + * issue path. `issued_*` split the passes that had no tape to play by why -- the pass had no + * key, its key was refused, or its key was seen for the first time. `audited` counts the + * plays that re-issued to check the tape. `dispatched` is the kernels the plays wrote and + * `unordered` how many of them went without the barrier bit (see haz_mark). Same threading as + * ar_calls. */ + struct PassCounts { + int64_t played = 0, recorded = 0, audited = 0; + int64_t issued_unkeyed = 0, issued_refused = 0, issued_first = 0; + int64_t dispatched = 0, unordered = 0; + }; + PassCounts pass_counts() const { + PassCounts c; + c.played = pc_played_.load(std::memory_order_relaxed); + c.recorded = pc_recorded_.load(std::memory_order_relaxed); + c.audited = pc_audited_.load(std::memory_order_relaxed); + c.issued_unkeyed = pc_unkeyed_.load(std::memory_order_relaxed); + c.issued_refused = pc_refused_.load(std::memory_order_relaxed); + c.issued_first = pc_first_.load(std::memory_order_relaxed); + c.dispatched = pc_dispatched_.load(std::memory_order_relaxed); + c.unordered = pc_unordered_.load(std::memory_order_relaxed); + return c; + } + void* arena_base() const { return arena_.base(); } + int64_t arena_bytes() const { return arena_.bytes(); } + void* scratch() const { return arena_.scratch(); } + + /* ---- the arena's levels ------------------------------------------------------------------ + * + * Level 0 is the plan the arena was built for: every buffer sized for the largest step. A + * later level is the same buffers packed for a step of at most `rows` tokens (ArenaLevel, + * core/build/rad_bufplan.cpp), so the arena past its `end` is free while the steps are that + * small -- and the engine lends it to the expert slab. The fixed region is at the same address + * in every level, which is what lets a persistent buffer outlive a change of level. + * + * A LEVEL IS CHANGED BETWEEN STEPS, NEVER DURING ONE, and only while this rank's thread is + * parked: every issue reads the active table, and a step that saw two would hand one op a + * buffer another op of the same step had placed somewhere else. The operand guard in issue + * checks against the active level's extents, so a step larger than its level is refused by + * name rather than written past the level's end into lent memory. */ + int add_level(int64_t rows, const std::vector& offset, + const std::vector& decl); + int set_level(int level); + int level() const { return level_; } + int n_levels() const { return (int)level_tmpl_.size(); } + +private: + int prepare(); + int bind_arena(); + int bind_buffers(); + int bind_weights(bool refresh_only); + int bind_ops(); + int bind_routing(); + int bind_profiling(); + int check_domain(rad_op h, int domain) const; + /* Whether the kernel serving this op on `domain` reads the layout the weights are STORED in. + * A weight is stored once, in the claiming DEVICE row's arrangement, so a domain move can + * hand a kernel a plane it cannot read -- same byte count, different order, no shape check + * anywhere can see it. Fills `why` with the sentence and leaves the severity to the caller. */ + int check_domain_layout(rad_op h, int domain, std::string* why) const; + void profile_collect(); + /* Which staging bank the heat engine may read. Mid-step that is the one this step is NOT + * filling; between steps it is simply the freshest, so "one step stale" means exactly one + * step and never two. */ + uint64_t route_dropped_ = 0; + + /* The handle-to-pointer resolution, shared by the issue path and rad_weight_ptr. Waits on the + * mover's event where one is pending, on the STREAM, never on the host. */ + void* resolve_weight(rad_weight w); + + /* ---- weight TABLES (RAD_OPK_WTAB), which a routed mixture of experts issues and nothing + * else does. + * + * A run of consecutively declared weights becomes a DEVICE ARRAY OF POINTERS, because after + * placement a layer's experts are not in one place and `base + e*stride` is true only of the + * all-in-VRAM case. One table per (op, operand position), bound at prepare and kept. + * + * The first issue resolves every entry and uploads the whole array from `host`, which is + * pinned because the copy is asynchronous and never written again. After that the device + * array changes only by patch (runtime/wtab.h): the residency table names the weights the + * mover changed (ResidencyTable::changes), sync_residency queues each one against the tables + * holding it, and the table's next issue resolves those entries and writes the ones whose + * pointer differs from `cur`. A step moves a handful of experts, so that is a handful of + * resolves, where re-walking every table whenever anything moved would be the whole expert + * set of every routed layer on most steps. */ + struct WeightTable { + uint64_t key = 0; /* (op << 32) | operand position */ + rad_weight first = 0; + int64_t n = 0; + void** host = nullptr; + void* dev = nullptr; + /* THE SHAPE AGREEMENT IS CHECKED ONCE, AT THE FIRST ISSUE, beside the first upload. What + * the check compares -- dtype, rank, shape and stride of each entry against entry 0 -- are + * declaration facts, fixed before a step has ever run and incapable of changing + * afterwards. */ + bool checked = false; + std::vector cur; /* what the device array holds, entry for entry */ + std::vector pend; /* entries a residency change named since the last issue */ + bool full = false; /* every entry: the templates were rebound */ + }; + /* Which tables hold a weight, as a list per weight: `wmemb_head_[w]` indexes `wmemb_`, and + * -1 means none. A table's entries are declared weights, and nothing stops two ops sharing a + * run, so a weight can be in more than one. */ + struct WMemb { int32_t slot, entry, next; }; + std::vector wmemb_head_; + std::vector wmemb_; + /* Whether a weight was ever resolved straight into an operand (RAD_W, rad_weight_ptr) rather + * than through a table. Such a pointer is part of the pass's arguments, so a move of that + * weight bumps `dense_epoch_`; a move of a table-only weight changes one device entry. */ + std::vector w_direct_; + uint64_t dense_epoch_ = 0; + /* The residency table's changes, queued against the tables they touch. Once a pass, before + * any of it is issued. */ + void sync_residency(); + /* Brings the table's device array up to date on the current stream: every entry on the first + * issue, afterwards the queued ones. */ + int table_refresh(rad_op h, int operand, WeightTable& t); + /* ------------------------------------------------------------------ recorded passes + * + * A DECODE PASS IS THE SAME PASS STEP AFTER STEP: the same kernels, with the same arguments, + * on the same queues. Everything the host does to produce it -- the architecture's block code, + * the operand resolution in `issue`, the kernel library's argument packing, the dispatch -- is + * therefore the same work repeated, and it is almost the whole of a rank thread's time. So a + * pass is recorded once (the backend keeps the finished packets and argument blocks, see + * DeviceBackend::tape_begin) and after that written straight into the queues. + * + * WHAT MAKES TWO PASSES THE SAME is the KEY: every field of the batch that a pass's shape or + * arguments can depend on -- counts, the host-side bounds, every device pointer, each KV + * group's geometry -- and the runtime state the issue path reads: the arena level, the weight + * templates, the directly resolved weights (dense_epoch_), the op domains, and the lane and + * host-arena bookkeeping a pass starts from. The batch builder rounds the two bounds that grow + * with the context (batch.cpp, bound_bucket), which is what keeps a key standing for hundreds + * of steps. The step number is not in it: nothing a pass issues depends on it except the + * routing bank, which is the host's. + * + * WHAT A TAPE CANNOT HOLD is the host work inside a pass, and it is cut around each piece and + * replays it: a HOST-site op (joined and run again, on the operands it recorded), a routed + * layer's report (the host bookkeeping; the copy is in the tape), and a weight table's refresh + * (the patch of whatever the mover changed since, see table_refresh). A table the mover did + * not touch costs its step a flag test. + * + * TRUSTED ONLY AFTER IT IS CHECKED. A key is recorded the second time it is seen, recorded + * again and compared the third, and only then played; a played tape is compared against a + * fresh issue again every kAuditPlays plays. A difference means the pass depends on something + * the key does not carry, and it fails the step naming the first dispatch that differs -- a + * silent difference would be wrong output. */ + enum TapeKind : uint8_t { kTapePlay = 0, kTapeTable = 1, kTapeHost = 2, kTapeRoute = 3 }; + struct TapeStep { + uint8_t kind = kTapePlay; + uint8_t lane = 0; /* the lane the host work ran on */ + int16_t opd = 0; /* kTapeTable: the operand position, for its error message */ + int32_t a = 0, b = 0; /* play [a, b) | table slot, op | host op index | route index */ + }; + struct TapeHost { + rad_op h = 0; + RadLaunchFn launch = nullptr; + RadArgs args{}; /* as it ran; `t` points at `t` below */ + RadTensor t[MAX_OPERANDS] = {}; + int64_t n = 0; + bool drain = false; /* an operand the arena does not track: drain instead */ + }; + struct PassTape { + uint64_t key = 0; + RadTape dev = nullptr; + std::vector steps; + std::vector host; + std::vector> route; + /* What the recording added to the Ctx's counters, and the bookkeeping it ended on. */ + int64_t issues = 0, ar_calls = 0, ar_bytes = 0, stream_waits = 0, host_syncs = 0; + bool touch_pending[2] = {}; + bool scratch_open[2] = {}; + int64_t plays = 0; + uint64_t used = 0; + int32_t dispatches = 0, unordered = 0; /* its kernels, and those haz_mark left unordered */ + }; + /* WHAT EACH DEVICE OP OF A PASS BEING RECORDED READS AND WRITES, as byte ranges, so the tape + * can be played with the dispatches that depend on nothing still running left unordered + * behind it (haz_mark). The packet processor otherwise waits for each kernel to finish before + * it launches the next, and on independent kernels that wait is pure idle. + * + * Ranges come from the operands the op was issued with and the roles its schema gives them -- + * a weight is never written in a pass, a table's entries are written only between played + * stretches -- and the op's scratch is a range like any other. What cannot be bounded makes + * the op OPAQUE, ordered on both sides: a kernel whose plugin does not promise it touches + * nothing else (rad_kernel_concurrent), a collective (its flags live outside every operand), + * an op with no schema, an operand with no extent. */ + struct HazOp { + int32_t rec0 = 0, rec1 = 0; /* its dispatches in the tape */ + uint32_t op = 0; + bool opaque = false; + uint32_t rd = 0, n_rd = 0, wr = 0, n_wr = 0; /* into haz_rng_ */ + }; + std::vector haz_ops_; + std::vector> haz_rng_; + void haz_note(const OpPlan& p, const IssuePlan& ip, const RadTensor* t, int n_opd, int rec0, + int rec1); + int haz_mark(PassTape& t); + + static constexpr size_t kTapes = 24; /* recorded passes kept, least recently used out */ + static constexpr int64_t kAuditPlays = 1024; + + std::vector tapes_; + uint64_t tape_clock_ = 0; + /* Keys seen once, and keys recorded once and not yet verified. */ + uint64_t tape_seen_[32] = {}; + size_t tape_seen_at_ = 0; + std::vector tape_refused_; /* keys whose pass could not be recorded */ + uint64_t tape_told_ = 0; /* draft passes whose first recording was logged */ + bool tape_on_ = false; /* the backend can, and nothing needs every issue */ + bool record_passes_ = true; /* CtxDesc::record_passes */ + PassTape* rec_ = nullptr; /* the tape being recorded, while one is */ + int rec_mark_ = 0; /* the backend record its current play step starts at */ + std::atomic domain_epoch_{0}; /* bumped by set_op_domain */ + + uint64_t pass_key(const RadBatch* b) const; + int run_pass(const RadBatch* b); + int record_pass(const RadBatch* b, uint64_t key, PassTape* out); + int play_pass(PassTape& t); + void tape_cut(); /* while recording: close the current play step */ + void tape_drop(PassTape& t); + static bool tapes_agree(const PassTape& a, const PassTape& b, std::string* why); + bool tape_seen(uint64_t key); /* true the second time a key is asked about */ + /* A routed layer's report. With `copy` false it is the host bookkeeping alone, which is what a + * replay runs: the copy itself is in the tape. */ + int route_report_impl(int layer, const RadRouting* r, bool copy); + + std::vector wtabs_; + std::unordered_map wtab_of_; + + /* Resolves the run, refreshes the table if it moved, and fills `out` with the tensor the + * kernel sees: entry 0's dtype and trailing extents, `shape[0]` = n, `stride[0]` = 0. + * Returns RAD_OK, or aborts the step and returns its status. */ + int ensure_weight_table(uint64_t key, rad_weight first, int64_t n, size_t* slot_out); + int bind_weight_tables(); + int resolve_weight_table(rad_op h, int operand, rad_weight first, int64_t n, RadTensor* out); + int weight_table_tensor(rad_op h, int operand, const WeightTable& t, const RadTensor& e0, + RadTensor* out); + void free_weight_tables(); + + /* Cold, noinline paths. Kept out of issue() so the hot path stays one straight line. */ + int abort_step(rad_op h, int band, int dom, const IssuePlan& ip, int64_t n, int status); + int abort_step_msg(rad_op h, int status, std::string what); + +public: + /* What rad_step_fail() reaches. Same effect as an operand rejection -- the step stops and the + * message is what the engine prints -- with the reason coming from the caller. */ + int step_fail(const char* what); +private: + [[noreturn]] void fatal_issue(rad_op h, int64_t n, const char* why) const; + + /* ---- the op oracle. runtime/oracle.cpp; inert unless RADIANCE_OP_ORACLE names an op. + * It runs the HOST kernel for the same (op, band) on a host copy of the operands the device + * kernel was just given, and compares. Everything about it is off the hot path: `oracle_` is + * null in every run that did not ask for it, and the one branch that reads it is the same + * predictable not-taken compare as the profiling branch beside it. */ + struct OracleState; + OracleState* oracle_ = nullptr; + void oracle_open(); + void oracle_close(); + bool oracle_arm(rad_op h) const; + /* Extents, aliasing and the per-operand byte count for one issue. Separate from the copy + * because a weight TABLE operand is an array of pointers and its snapshot is the STACKED + * plane behind them -- a size the operand itself does not state. */ + void oracle_size(rad_op h, int n_opd); + int64_t oracle_opd_bytes(int i) const; + void oracle_snap(int n_opd, bool post); + void oracle_run(rad_op h, const IssuePlan& hip, int64_t seq, int n_opd); + /* Put a re-laid weight back into the form a dense reference reads, through the DEVICE row's + * own inverse, into the logical form the HOST row describes. False when the comparison cannot + * be made honestly, which is a named skip. */ + bool oracle_unrelayout(rad_op h, const IssuePlan& hip, const IssuePlan& dip, int64_t seq, + int n_opd); + /* Repeat mode (RADIANCE_OP_REPEAT): no host kernel. The DEVICE plan is re-launched on the + * restored bytes and the two results are byte-compared, which names a kernel that is not a + * function of its inputs. A host-vs-device oracle structurally cannot see that: both of its + * sides run once, so a kernel that answers differently on the same bytes agrees with itself + * exactly as often as it disagrees. */ + void oracle_repeat(rad_op h, const IssuePlan& dip, int64_t seq, int n_opd); + const char* ip_kernel_name(rad_op h) const; + const IssuePlan* oracle_before(rad_op h, int band, int n_opd); + void oracle_after(rad_op h, const IssuePlan& hip, const IssuePlan& dip, int n_opd); + + Program* program_ = nullptr; + std::vector kv_; /* by rad_kvgroup; RAD_OPK_KV resolves through it */ + ResidencyTable* residency_ = nullptr; + OpStager* stager_ = nullptr; + bool staging_ = false; /* the stager armed for the pass being issued */ + int issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n); + ArchStepFn arch_step_ = nullptr; + + int rank_ = 0; + int world_size_ = 1; + int device_ = 0; + RadStream stream_ = nullptr; + bool own_stream_ = false; + + /* ---- THE SECOND LANE, and it exists for exactly one thing: overlapping the tensor-parallel + * all-reduce with compute at prefill, which is worth on the order of 15% of prefill + * throughput. Nothing else may use it without reading the three constraints below. + * + * ONE: EVERY COLLECTIVE MUST RIDE THE SAME LANE. The all-reduce carries a per-block `seq` + * counter and double-buffers its scratch on `seq & 1`, so two launches that race differently + * on the two ranks would pick DIFFERENT slots for the same message and deadlock or corrupt. + * Both ranks run the same architecture code, so putting every all-reduce on lane 1 keeps them + * ordered against each other and therefore identically numbered on both ranks. Splitting the + * collectives ACROSS lanes is the bug this comment exists to prevent. + * + * TWO: A DEVICE-WIDE ARRIVAL COUNTER MUST BE KEYED ON THE STREAM. `split_ctr` in + * r4d_gemm_fp8a8.hip is the split-K finisher's counter, self-resetting, and it is sound only + * because two launches of this kernel never overlap -- they are ordered by the same stream. + * One counter block for the whole device would hold only with one compute stream a rank; a + * second lane running a narrow GEMM beside one on lane 0 breaks it. There is therefore one + * counter block a STREAM, so ordering does the work again -- and any OTHER plugin kernel with + * a device-wide counter has to do the same or stay off lane 1, because nothing here can check + * it. + * + * THREE: THE BUFFER PLANNER PACKS FROM ONE LINEAR ORDER. Two lanes can therefore write the + * same arena bytes through two buffers whose declared lifetimes do not overlap. The + * architecture names the buffers its second lane touches to `rad_buf_concurrent`, which hands + * each of them the whole program -- a few MiB for one block's transients. + * + * FOUR: A SLICE MUST LAND IN THE SAME BUCKET-TABLE BAND AS THE WHOLE. This is the one that + * would silently change the model's output rather than break it. An op's kernel is chosen by + * which band `n` falls in, and `--debug-graph` prints the boundaries a model actually has. + * They are sparse and uneven -- a representative set is + * + * 8 16 56 64 256 1024 4096 8192 16384 49152 65536 + * + * so a 4096-token chunk cut in HALF gives 2048 and 2048, both inside (1024, 4096] and both + * resolving to the same kernel -- while cutting it in FOUR gives 1024, which is the TOP of the + * band below and picks a different kernel with a different summation order. The ragged last + * chunk of a prompt is worse: 16449 tokens is four full chunks and then 65, and halving 65 + * crosses the boundaries at 64 and 56. So the rule a pipelined path must obey is that every + * slice sits strictly above the largest boundary below T, which at a 4096-token chunk means + * TWO slices and no more. + * + * The T-dependent selections inside the architecture hold at two slices: `ar_wire_is_exact` + * only flips below T = 13 (`numel * 2 < wire_min_bytes`), and the gated-GEMM fold and the + * fused attention prologue both band at T <= 64. + * + * WHAT MAKES ALL OF THIS WORTH IT: a many-block SPINNING kernel on one stream does not starve + * a bandwidth-bound kernel on another. The all-reduce launches min(M, 256) blocks that spin on + * a peer flag while the fabric drains, and if those held their CUs there would be nothing to + * overlap with. Run a dependent-FMA spinner and a large copy on two streams and the pair costs + * the MAX of the two rather than the sum: the copy finishes inside the spinner's window at + * every block count, including counts higher than the part can hold resident at once. */ + RadStream lane1_ = nullptr; + bool own_lane1_ = false; + int lane_ = 0; + RadEvent lane_ev_[2] = { nullptr, nullptr }; + /* THE LAST DEVICE OP ON EACH LANE THAT TOUCHED HOST-DOMAIN MEMORY. A host op reads and writes + * the host arena at issue, on this thread, while the device may still be working through what + * this thread issued before it. What it has to be ordered behind is every device op that + * touched the host arena before it -- the producer of its input, or a reader of bytes its + * output reuses -- and on each lane those complete no later than the last of them. So a device + * op with a host-domain buffer operand re-records its lane's event, and a host op waits on the + * recorded ones instead of on everything the stream holds (see the host join in Ctx::issue). */ + RadEvent host_touch_ev_[2] = { nullptr, nullptr }; + bool host_touch_pending_[2] = { false, false }; + int host_join(const RadOperand* opd, int n_opd); + bool host_join_drains(const RadOperand* opd, int n_opd) const; + int host_join_wait(bool drain); + /* A lane issued a kernel that uses the shared scratch region and the other lane has not been + * joined behind it since. The issue path reads these to keep two scratch users off the region + * at once; lane_join clears its `from` side. See the scratch block in Ctx::issue. */ + bool scratch_open_[2] = { false, false }; + bool scratch_join_warned_ = false; + /* WHERE IN ITS REGION THE NEXT SCRATCH USER STARTS. Consecutive users are handed consecutive + * slices rather than all the same bytes, wrapping to the start when one does not fit, so two + * of them that are otherwise independent share nothing and may run at once (haz_mark). Back + * to zero at the start of every pass, so a pass issued twice hands its ops the same slices -- + * the pointers are in its recording's arguments. */ + int64_t scratch_cur_[2] = { 0, 0 }; + void* scratch_take(int region, int64_t bytes); + /* The kernel that last opened each lane's scratch, and its row count, for the warning. */ + const char* scratch_kernel_[2] = { nullptr, nullptr }; + int64_t scratch_n_[2] = { 0, 0 }; + + Arena arena_; /* device: the buffer plan plus the shared scratch region */ + Arena host_arena_; /* only if the program declares RAD_DOMAIN_HOST buffers */ + + const RadBatch* batch_ = nullptr; + + /* Per-issue tensor storage, bound into every IssuePlan::args.t at prepare so an issue stores + * n_t and nothing else. One array, because issues do not nest. */ + RadTensor tbuf_[MAX_OPERANDS]; + + /* Prebuilt tensor templates, indexed by handle. A buffer's template already carries its arena + * pointer, dtype, shape and packed strides; a weight's already carries WeightInfo::ptr. An + * issue copies one and patches at most the data pointer and dim 0. */ + std::vector buf_tmpl_; + std::vector buf_bits_; + std::vector buf_host_; /* per handle: a RAD_DOMAIN_HOST buffer */ + /* Every level's templates; `buf_tmpl_` is a copy of the active one, so the issue path reads + * one vector whatever level it is at. */ + std::vector> level_tmpl_; + int level_ = 0; + std::vector w_tmpl_; + std::vector w_bits_; + std::vector w_gen_; /* the generation each template was built from */ + std::vector waited_gen_; /* the generation we last made the stream wait on */ + + std::vector plans_; + /* THE OPS NOT YET SEEN ISSUED. flush_issued walks this rather than every op, and drops each + * index as it fires, so the per-step cost falls to the ops that have never fired -- which + * after a few steps is only the ones that never will, and those are the point. */ + std::vector unflushed_; + std::vector band_table_; + std::vector issue_table_; + std::vector> op_domain_; /* sized once, never resized */ + + std::vector route_; + int64_t route_n_expert_ = 0; + /* A BANK IS ONE STEP'S HISTOGRAMS FOR EVERY LAYER, [kRouteBanks][n_layer][n_expert] in pinned + * host memory. A report copies one layer's counts into that layer's row on the card, + * [n_layer][n_expert], which is a copy within the card and orders nothing else; the end of the + * pass copies the rows it touched into the step's bank in one transfer and records the bank's + * event. See route_report. */ + int32_t* route_pool_ = nullptr; /* host */ + int32_t* route_dev_ = nullptr; /* card */ + RadEvent route_done_[kRouteBanks] = {}; + /* The layers this pass reported into `route_bank_`, as [lo, hi]; lo > hi when none. */ + int route_bank_ = -1, route_lo_ = 1, route_hi_ = 0; + int route_flush(); + + /* Profiling. Off by default; when on it restores synchronisations that change the mover's slot + * supply, so a profiled run is not comparable against an unprofiled one (spec §16). */ + bool profiling_ = false; + struct ProfSlot { RadEvent a = nullptr, b = nullptr; int32_t op = 0; }; + std::vector prof_ring_; + size_t prof_n_ = 0; + bool prof_overflowed_ = false; + std::vector prof_ms_; + std::vector prof_calls_; + /* Which rows were timed on the HOST clock rather than by a device event pair. The two are not + * the same measurement -- a host row includes page faults and link reads, a device row is + * kernel time -- so the table says which each one is rather than letting a reader assume. */ + std::vector prof_host_; + /* The stream drain a host-site op forces, timed apart from the op itself: it is the cost of + * the pipeline the op STOPS, not of the arithmetic it does, and the two differ by two orders + * of magnitude on the PLE gather. */ + std::vector prof_join_ms_; + + std::atomic weights_dirty_{false}; + /* Bumped whenever bind_weights rewrites the templates: any weight pointer resolved from one + * before may have moved. */ + uint64_t w_tmpl_epoch_ = 1; + + bool in_step_ = false; + int step_status_ = RAD_OK; + std::string step_fail_; + + int64_t n_issues_ = 0; + int64_t n_stream_waits_ = 0; + int64_t n_host_syncs_ = 0; + std::atomic ar_calls_{0}, ar_bytes_{0}; + std::atomic pc_played_{0}, pc_recorded_{0}, pc_audited_{0}; + std::atomic pc_unkeyed_{0}, pc_refused_{0}, pc_first_{0}; + std::atomic pc_dispatched_{0}, pc_unordered_{0}; +}; + +} /* namespace rad */ diff --git a/core/runtime/issue.cpp b/core/runtime/issue.cpp new file mode 100644 index 00000000..079fcb4e --- /dev/null +++ b/core/runtime/issue.cpp @@ -0,0 +1,1324 @@ +/* issue.cpp -- THE hot path, and the C surface the architecture plugin actually calls. + * + * Per rad_issue, in order: index the op's bucket table with `n`, pick the domain from the resolved + * instance's current execution site, materialise a RadTensor for each operand out of a template + * built at declare, resolve every weight handle to a pointer (waiting on the mover's event on the + * STREAM if the weight is in flight), store the operand count into a RadArgs that was already + * filled in, and launch. + * + * NO ALLOCATION. NO HOST SYNCHRONISATION. NO DEVICE ROUND TRIP. Every one of those is a property + * you lose by accident, so each of them is checkable here: the only writes are into arrays sized + * at prepare, the only device call besides the launch is rad_event_wait (which orders a stream and + * does not block the host), and nothing in this file reads a device value back. + * + * See ctx.h for the per-issue cost and where it sits against spec §3.2's budget. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include "ctx.h" +#include "device/device.h" +#include "wtab.h" + +#include + +namespace rad { + +/* A COLUMN SLICE: `cols` narrows the LAST dimension while every stride is left alone, so the + * declared width stays the row pitch. That is what makes a fused projection usable without a + * copy -- q and the attention gate are interleaved per head inside one buffer, and GDN's `a` and + * `b` are columns of one in-projection. The element offset is what selects the first column, so + * the two fields compose: offset picks the start, cols picks the width. + * + * Narrowing the last dimension rather than dim 0 is the whole point: shortening the OUTERMOST + * dimension leaves every stride correct because they are products of the trailing ones, and + * shortening the INNERMOST one leaves them correct because nothing is a product of it. Any other + * dimension would need the strides rewritten, so the ABI offers only these two. */ +static inline void narrow_cols(const RadOperand& o, RadTensor* t) { + if (o.cols > 0 && t->rank >= 1) t->shape[t->rank - 1] = o.cols; +} + +/* DOES THE OPERAND FIT THE BUFFER IT NAMES? The span is the largest element index the descriptor + * can reach, measured from the buffer's base -- `offset` plus the sum of (extent - 1) * stride + * over every dimension. It is NOT shape[0] against the declared shape[0]: a row count larger than + * the declared one is legitimate when `cols` is narrower, because a [T, 2560] buffer read at 160 + * columns IS T*16 rows of 160 and the PLE gather does exactly that. The span is the only reading + * that accepts the legal case and refuses the overrun. + * + * An empty extent reaches nothing and is not an error here; the kernel's own bounds decide. */ +static inline bool operand_fits(const RadTensor& t, int64_t offset, const RadTensor& decl) { + if (offset < 0) return false; + int64_t span = offset; + for (uint32_t d = 0; d < t.rank; ++d) { + if (t.shape[d] <= 0) return true; + span += (t.shape[d] - 1) * t.stride[d]; + } + return span < rad_tensor_numel(&decl); +} + +/* Extents and strides, for the message that refuses. oracle.cpp has one of these in an anonymous + * namespace; duplicating four lines beats exporting a debug formatter across translation units. */ +static inline std::string opd_shape_str(const RadTensor& t) { + std::string s = "["; + for (uint32_t d = 0; d < t.rank; ++d) + s += fmt("%s%lld", d ? "," : "", (long long)t.shape[d]); + s += "]/["; + for (uint32_t d = 0; d < t.rank; ++d) + s += fmt("%s%lld", d ? "," : "", (long long)t.stride[d]); + return s + "]"; +} + +/* Element offset to byte offset. Split out because the sub-byte cases are the interesting ones: + * a W4 weight has no addressable odd element, and a plugin-private dtype has no size the core + * knows at all -- both are refused by name rather than silently truncated into a misaligned + * pointer. Returns false when the offset cannot be expressed. */ +static inline bool byte_delta(int bits, int64_t elems, int64_t* out) { + if (bits >= 8) { *out = elems * (int64_t)(bits >> 3); return true; } + if (bits <= 0) return false; /* plugin-private: the core has no size */ + const int64_t nbits = (int64_t)bits * elems; + if (nbits & 7) return false; /* mid-byte offset into a packed weight */ + *out = nbits >> 3; + return true; +} + +void* Ctx::resolve_weight(rad_weight w) { + /* The template already carries WeightInfo::ptr, bound at prepare and refreshed between steps + * when the mover says it moved something. In the all-in-VRAM case that is the whole answer and + * there is no table, no virtual call and no branch beyond this one. */ + void* p = w_tmpl_[w].data; + if (!residency_) return p; + + const WeightSlot* s = residency_->lookup(w); /* never blocks -- residency.h */ + if (s) { + p = s->ptr; + /* Wait once per generation, not once per issue. A stream wait orders everything issued + * after it, so repeating it buys nothing and at eight experts a layer across 64 layers it + * would be thousands of runtime calls a step. The mover bumps `generation` when it starts + * a transfer, which is what makes the memo sound (residency.h). */ + if (s->ready && waited_gen_[w] != s->generation) { + /* Not part of a recording: once issued it orders everything after it, every later + * play included, and a move of a weight a pass names directly re-keys the pass. */ + if (rec_) tape_pause(true); + rad_event_wait(cur_stream(), s->ready); /* the STREAM waits; the host does not */ + if (rec_) tape_pause(false); + waited_gen_[w] = s->generation; + ++n_stream_waits_; + } + } + return p; +} + +/* ================================================================== weight tables + * + * RAD_OPK_WTAB. See the comment on Ctx::WeightTable and the RAD_WTAB macro in rad_runtime.h: this + * is where a run of declared weights becomes the device pointer array a grouped GEMM walks. + * + * THE ENTRIES MUST AGREE ABOUT SHAPE AND DTYPE, and the check is not pedantry -- the kernel is + * given one set of trailing extents for the whole table and strides its way through an entry with + * them, so a run that mixes two shapes is a run the kernel reads off the end of. A MoE layer + * declares 256 identical experts, so this holds by construction and a violation is a plugin bug + * that is worth naming at the first issue rather than debugging from wrong logits. */ +/* THE TABLE'S MEMORY, ALLOCATED ONCE AND NOT ON THE STEP PATH. + * + * Allocating it inside resolve_weight_table, which runs at ISSUE, would have the first step of the + * first request allocate one pinned array and one device array per grouped-GEMM operand -- an + * allocator on the step path, and spec §3.1 says there is not one. It would also be invisible to + * the VRAM budget: the pools are sized before a step has ever run, so those bytes would come out + * of --gpu-headroom-mib without being named in it. + * + * Binding every declared table at prepare() avoids both. The run is a property of the DECLARATION + * (OpInfo::weights with OpInfo::weight_opd naming the operand position), not of the issue, so + * there is nothing about it that has to wait for a step. resolve_weight_table still handles a + * miss, because a plugin may legally issue a table the declaration did not describe -- it just + * does not happen on any model this engine ships. + * + * Returns the slot in wtabs_. */ +int Ctx::ensure_weight_table(uint64_t key, rad_weight first, int64_t n, size_t* slot_out) { + auto it = wtab_of_.find(key); + if (it != wtab_of_.end()) { *slot_out = it->second; return RAD_OK; } + + WeightTable t; + t.key = key; + t.first = first; + t.n = n; + t.host = (void**)rad_dev_alloc(n * (int64_t)sizeof(void*), RAD_MEM_HOST_PINNED); + t.dev = rad_dev_alloc(n * (int64_t)sizeof(void*), RAD_MEM_DEVICE); + if (!t.host || !t.dev) { + if (t.host) rad_dev_free(t.host, RAD_MEM_HOST_PINNED); + if (t.dev) rad_dev_free(t.dev, RAD_MEM_DEVICE); + return RAD_E_NOMEM; + } + std::memset(t.host, 0, (size_t)n * sizeof(void*)); + t.pend.reserve((size_t)n); + *slot_out = wtabs_.size(); + if (wmemb_head_.size() < program_->weights.size()) + wmemb_head_.resize(program_->weights.size(), -1); + for (int64_t e = 0; e < n; ++e) { + const rad_weight w = (rad_weight)(first + e); + if ((size_t)w >= wmemb_head_.size()) break; + wmemb_.push_back(WMemb{ (int32_t)*slot_out, (int32_t)e, wmemb_head_[w] }); + wmemb_head_[w] = (int32_t)wmemb_.size() - 1; + } + wtabs_.push_back(std::move(t)); + wtab_of_.emplace(key, *slot_out); + return RAD_OK; +} + +/* Every RAD_OPD_WTAB operand of every declared op, bound before the first step. The run is + * contiguous by construction -- rad_decl_weight hands out consecutive indices and a declaration + * loop over experts produces exactly such a run -- so it is the smallest declared handle at that + * operand position and the count of them. A gap would be a plugin bug, and it is named rather + * than papered over: a table assembled from a non-contiguous run would read the wrong expert. */ +int Ctx::bind_weight_tables() { + const Program& P = *program_; + int64_t tables = 0, bytes = 0; + for (size_t oi = 1; oi < P.ops.size(); ++oi) { + const OpInfo& op = P.ops[oi]; + if (!op.schema || op.weights.size() != op.weight_opd.size()) continue; + for (int p = 0; p < op.schema->n_operands; ++p) { + if (op.schema->operands[p].role != RAD_OPD_WTAB) continue; + rad_weight lo = 0, hi = 0; + int64_t cnt = 0; + for (size_t k = 0; k < op.weights.size(); ++k) { + if (op.weight_opd[k] != p) continue; + const rad_weight w = op.weights[k]; + if (cnt == 0) { lo = hi = w; } + else { lo = std::min(lo, w); hi = std::max(hi, w); } + ++cnt; + } + if (cnt <= 0) continue; + if ((int64_t)(hi - lo) + 1 != cnt) { + RAD_ERR("op '%s' operand %d is a weight table of %lld entries whose declared " + "handles run [%u, %u] -- a table must be a CONTIGUOUS run, because the " + "kernel is handed one base and strides through it", + op.op.c_str(), p, (long long)cnt, lo, hi); + return RAD_E_INVAL; + } + size_t slot = 0; + const uint64_t key = ((uint64_t)(rad_op)oi << 32) | (uint32_t)p; + const int rc = ensure_weight_table(key, lo, cnt, &slot); + if (rc < 0) { + RAD_ERR("op '%s' operand %d: a table of %lld weights needs %s of pointers and it " + "could not be allocated", op.op.c_str(), p, (long long)cnt, + humanb(cnt * 2 * (int64_t)sizeof(void*)).c_str()); + return rc; + } + ++tables; + bytes += cnt * 2 * (int64_t)sizeof(void*); + } + } + if (tables > 0) + RAD_DEBUG("weight tables: %lld bound at prepare, %s of pointer arrays -- none of it " + "allocated on the step path", (long long)tables, humanb(bytes).c_str()); + return RAD_OK; +} + +static const bool g_dbg_issue = std::getenv("RADIANCE_DEBUG_ISSUE") != nullptr; +/* THE WEIGHT-TABLE WALK, charged separately from the rest of `own`. A grouped-GEMM operand names a + * run of experts; the first issue walks every entry and later ones the entries the mover changed + * (WeightTable::pend). Two counters -- entries walked, and the wall time of the walks -- so that + * cost is read directly rather than inferred from the difference between two builds. */ +static double g_wtab_us = 0.0, g_wtab_us_p = 0.0; +static long g_wtab_e = 0, g_wtab_e_p = 0; + +int Ctx::resolve_weight_table(rad_op h, int operand, rad_weight first, int64_t n, + RadTensor* out) { + const uint64_t key = ((uint64_t)h << 32) | (uint32_t)operand; + size_t slot; + auto it = wtab_of_.find(key); + if (it == wtab_of_.end()) { + /* A MISS IS NOT THE NORMAL PATH ANY MORE -- bind_weight_tables() bound every table the + * declaration describes. Reaching here means a plugin issued a table at an operand + * position its declaration did not name as one, which is legal and is served, but it is + * an allocation on the step path and the log says so once. */ + RAD_DEBUG("op %u operand %d issued a weight table of %lld entries that the declaration did " + "not describe; allocating it now", (unsigned)h, operand, (long long)n); + const int rc = ensure_weight_table(key, first, n, &slot); + if (rc < 0) + return abort_step_msg(h, RAD_E_NOMEM, + fmt("operand %d is a table of %lld weights and the %lld bytes it " + "needs could not be allocated", operand, (long long)n, + (long long)(n * 2 * (int64_t)sizeof(void*)))); + } else { + slot = it->second; + if (wtabs_[slot].first != first || wtabs_[slot].n != n) + return abort_step_msg(h, RAD_E_INVAL, + fmt("operand %d named weights [%u, +%lld) and now names " + "[%u, +%lld). A table's run is fixed by the declaration", + operand, wtabs_[slot].first, (long long)wtabs_[slot].n, + first, (long long)n)); + } + WeightTable& t = wtabs_[slot]; + /* In a pass being recorded the refresh is host work: the recording is cut and the table named, + * so a play refreshes it here, on this lane, with whatever the mover has changed by then. */ + if (rec_) { + tape_cut(); + TapeStep st; + st.kind = kTapeTable; + st.lane = (uint8_t)lane_; + st.opd = (int16_t)operand; + st.a = (int32_t)slot; + st.b = (int32_t)h; + rec_->steps.push_back(st); + tape_pause(true); + } + int rc = RAD_OK; + if (!t.checked || t.full || !t.pend.empty()) rc = table_refresh(h, operand, t); + if (rec_) tape_pause(false); + if (rc < 0) return rc; + return weight_table_tensor(h, operand, t, w_tmpl_[first], out); +} + +int Ctx::table_refresh(rad_op h, int operand, WeightTable& t) { + const RadTensor& e0 = w_tmpl_[t.first]; + const bool wt_time = g_dbg_issue && rank() == 0; /* same rule: one thread accumulates */ + const auto t_wt0 = wt_time ? std::chrono::steady_clock::now() + : std::chrono::steady_clock::time_point{}; + auto resolve = [&](int64_t e, void** out) -> int { + const rad_weight w = (rad_weight)(t.first + e); + void* p = resolve_weight(w); + if (!p) + return abort_step_msg(h, RAD_E_STATE, + fmt("weight '%s' (entry %lld of operand %d's table) has no " + "pointer at issue: the load phase never bound it and no " + "residency table claims it", + program_->weights[w].name.c_str(), (long long)e, operand)); + *out = p; + return RAD_OK; + }; + + int64_t walked = 0; + if (!t.checked) { + /* THE FIRST ISSUE: agreement, every entry, and the whole array up in one copy. `host` is + * never written after this, so the copy reads what was resolved here however late the + * card reaches it. */ + t.cur.assign((size_t)t.n, nullptr); + for (int64_t e = 0; e < t.n; ++e) { + const rad_weight w = (rad_weight)(t.first + e); + const RadTensor& te = w_tmpl_[w]; + if (te.dtype != e0.dtype || te.rank != e0.rank) + return abort_step_msg(h, RAD_E_SHAPE, + fmt("operand %d is a weight table whose entry %lld ('%s') " + "is %s rank %u while entry 0 ('%s') is %s rank %u; every " + "entry of one table must have the same dtype and shape", + operand, (long long)e, program_->weights[w].name.c_str(), + rad_dtype_name(te.dtype), te.rank, + program_->weights[t.first].name.c_str(), + rad_dtype_name(e0.dtype), e0.rank)); + for (uint32_t d = 0; d < te.rank; ++d) + if (te.shape[d] != e0.shape[d] || te.stride[d] != e0.stride[d]) + return abort_step_msg(h, RAD_E_SHAPE, + fmt("operand %d is a weight table whose entry %lld " + "('%s') disagrees with entry 0 about axis %u", + operand, (long long)e, + program_->weights[w].name.c_str(), d)); + RAD_TRY(resolve(e, &t.cur[(size_t)e])); + t.host[e] = t.cur[(size_t)e]; + } + walked = t.n; + const int rc = rad_memcpy_async(t.dev, t.host, t.n * (int64_t)sizeof(void*), cur_stream()); + if (rc < 0) + return abort_step_msg(h, rc, + fmt("operand %d: the weight table could not be uploaded", operand)); + t.checked = true; + } else { + /* THE ENTRIES THAT MAY HAVE MOVED, each resolved -- which is also what orders the stream + * behind a transfer still in flight -- and written only if its pointer differs. */ + WtabPatch pt; + auto one = [&](int64_t e) -> int { + void* p = nullptr; + RAD_TRY(resolve(e, &p)); + ++walked; + if (t.cur[(size_t)e] == p) return RAD_OK; + t.cur[(size_t)e] = p; + pt.dst[pt.n] = static_cast(t.dev) + e; + pt.val[pt.n] = p; + if (++pt.n == (uint32_t)kWtabPatch) { + RAD_TRY(wtab_patch(pt, cur_stream())); + pt.n = 0; + } + return RAD_OK; + }; + if (t.full) { + for (int64_t e = 0; e < t.n; ++e) RAD_TRY(one(e)); + } else { + for (int32_t e : t.pend) RAD_TRY(one(e)); + } + const int rc = wtab_patch(pt, cur_stream()); + if (rc < 0) + return abort_step_msg(h, rc, + fmt("operand %d: the weight table could not be patched", operand)); + } + t.full = false; + t.pend.clear(); + if (wt_time) { + g_wtab_us += std::chrono::duration( + std::chrono::steady_clock::now() - t_wt0).count(); + g_wtab_e += walked; + } + return RAD_OK; +} + +/* The residency table's changes since the last pass, queued against every table that holds the + * weight. A weight also resolved straight into an operand moves `dense_epoch_` as well. */ +void Ctx::sync_residency() { + if (!residency_) return; + const std::vector& ch = residency_->changes(); + if (ch.empty()) return; + for (rad_weight w : ch) { + if ((size_t)w < w_direct_.size() && w_direct_[w]) ++dense_epoch_; + if ((size_t)w >= wmemb_head_.size()) continue; + for (int32_t m = wmemb_head_[w]; m >= 0; m = wmemb_[(size_t)m].next) { + WeightTable& t = wtabs_[(size_t)wmemb_[(size_t)m].slot]; + /* A table not yet issued resolves every entry at its first issue, and one already + * marked resolves every entry at its next. */ + if (!t.checked || t.full) continue; + if ((int64_t)t.pend.size() >= t.n) { t.full = true; t.pend.clear(); continue; } + t.pend.push_back(wmemb_[(size_t)m].entry); + } + } + residency_->clear_changes(); +} + +/* The operand a kernel is handed for a table: entry 0's dtype and trailing extents, with the + * expert axis PREPENDED at stride zero -- the marker that says the axis is not addressable by + * arithmetic and `data` is a pointer array. */ +int Ctx::weight_table_tensor(rad_op h, int operand, const WeightTable& t, const RadTensor& e0, + RadTensor* out) { + if (e0.rank + 1 > RAD_MAX_RANK) + return abort_step_msg(h, RAD_E_SHAPE, + fmt("operand %d is a table of rank-%u weights, and one more axis " + "does not fit RAD_MAX_RANK", operand, e0.rank)); + *out = e0; + for (int d = (int)e0.rank; d >= 1; --d) { + out->shape[d] = e0.shape[d - 1]; + out->stride[d] = e0.stride[d - 1]; + } + out->rank = e0.rank + 1; + out->shape[0] = t.n; + out->stride[0] = 0; + out->data = t.dev; + return RAD_OK; +} + +void Ctx::free_weight_tables() { + for (WeightTable& t : wtabs_) { + if (t.host) rad_dev_free(t.host, RAD_MEM_HOST_PINNED); + if (t.dev) rad_dev_free(t.dev, RAD_MEM_DEVICE); + } + wtabs_.clear(); + wtab_of_.clear(); +} + +/* RADIANCE_DEBUG_ISSUE: WHAT THE ISSUE PATH ACTUALLY COSTS, split from the launch it wraps. + * + * A draft pass costs several microseconds a dispatch where a bare `hipLaunchKernelGGL` costs + * around one and a half (`isa/graphrate.hip` prices one). The difference has to be here, and + * nothing else in the tree can see it: an op's host cost is invisible in a kernel trace, and the + * per-op profiler times the DEVICE. + * + * `own` is everything before the launch -- the band scan, the domain lookup, the operand + * resolution loop. `launch` is the plugin shim plus HIP. Two clock reads an issue, ~50 ns on a + * path this says is microseconds, and only when the variable is set. + * + * REPORTED PER WINDOW AND NOT AS A RUNNING MEAN. Load and the first prefill put seconds into the + * accumulator over relatively few issues, so a cumulative average decays through a series of + * individually plausible numbers, every one of them the startup transient and none of them the + * steady state. A statistic that is still moving after a million samples is measuring the warm-up, + * and printing it as "us each" invites exactly the wrong conclusion. */ + +/* RADIANCE_DEBUG_ARGSHA: ARE A DRAFTER PASS'S KERNEL ARGUMENTS THE SAME EVERY STEP? + * + * This is the one question that decides what a captured graph would cost to maintain. A draft pass + * is the same op sequence at the same shapes every step -- the concurrency does not change inside a + * request -- so if the ARGUMENTS are identical too, a graph can be captured once and replayed. If + * they move, every replay needs `hipGraphExecKernelNodeSetParams` over ~50 nodes, which is most of + * the submit cost back. + * + * The staging arena is DOUBLE BUFFERED, so the expectation is not one digest but TWO, alternating. + * That still replays -- two graphs, picked by parity -- and it is worth knowing before anyone + * builds either. + * + * Digests the operand bytes and `n` of every issue of pass 1 into one FNV-1a and prints it a step. */ +static const bool g_dbg_argsha = std::getenv("RADIANCE_DEBUG_ARGSHA") != nullptr; + +static int g_argsha_pass = -99; +static long g_argsha_seen = 0; +/* ONE DIGEST AN ISSUE, not one a pass: the pass-wide digest only says "something moved", and what + * decides whether a captured graph is maintainable is HOW MANY nodes move. Kept per position in + * the pass and compared against the previous step's. */ +/* TWO digests, not one, and the op handle beside them. A count of moving nodes is enough to SIZE + * a graph; it is not enough to DESIGN one. A node whose operand pointer moved can be left alone if + * the pointer can be made stable -- the same address refilled in place -- and then the captured + * graph replays untouched. A node whose SHAPE moved cannot: the launch geometry is baked into the + * node at capture, so that one needs a real update, which needs launch params only the plugin shim + * has. Which kind the ten are decides whether this is a contained change or an ABI change. */ +struct ArgSha { rad_op h; uint64_t ptr; uint64_t shp; }; +static std::vector g_argsha_cur, g_argsha_prev; +static size_t g_argsha_i = 0; +static ArgSha argsha_of(rad_op h, int64_t n, const RadTensor* t, int n_opd) { + uint64_t v = 1469598103934665603ull, w = 1469598103934665603ull; + auto mix = [&](const void* p, size_t k) { + const unsigned char* b = (const unsigned char*)p; + for (size_t i = 0; i < k; ++i) { v ^= b[i]; v *= 1099511628211ull; } + }; + auto mixw = [&](const void* p, size_t k) { + const unsigned char* b = (const unsigned char*)p; + for (size_t i = 0; i < k; ++i) { w ^= b[i]; w *= 1099511628211ull; } + }; + mix(&h, sizeof h); + mixw(&h, sizeof h); + mixw(&n, sizeof n); /* the row count IS geometry: it is what the grid is derived from */ + /* ONLY THE LIVE FIELDS. `RadTensor` carries shape[RAD_MAX_RANK] and stride[RAD_MAX_RANK] of + * which only `rank` are meaningful, and `tbuf_` is REUSED across issues -- so hashing the + * struct whole picks up whatever the last op left in the tail slots and reports very nearly + * every issue as having moved, which is the instrument's own scratch and not the model's + * arguments. */ + for (int i = 0; i < n_opd; ++i) { + const RadTensor& tt = t[i]; + mix(&tt.data, sizeof tt.data); /* WHERE -- a node-update-free fix exists */ + mixw(&tt.dtype, sizeof tt.dtype); /* WHAT -- baked into the node at capture */ + mixw(&tt.rank, sizeof tt.rank); + for (uint32_t d = 0; d < tt.rank && d < RAD_MAX_RANK; ++d) { + mixw(&tt.shape[d], sizeof tt.shape[d]); + mixw(&tt.stride[d], sizeof tt.stride[d]); + } + } + return ArgSha{h, v, w}; +} +/* PER OP, because the average is the one number that cannot be acted on. Subtracting the price of + * a bare fifteen-argument hipLaunchKernelGGL (isa/graphrate.hip has one) from `launch` leaves most + * of a microsecond an issue in the shim's own prologue -- but that is a subtraction across two + * different kernels, and an average over a step's ~1850 issues hides whether it is a flat tax or + * three ops doing something silly. This charges host launch time to the op that spent it. */ +struct IssOp { double lau = 0.0, own = 0.0; long n = 0; }; +static std::unordered_map g_iss_by_op; +static double g_iss_own = 0.0, g_iss_lau = 0.0; +static double g_iss_own_p = 0.0, g_iss_lau_p = 0.0; +static long g_iss_n = 0; + +/* THE STAGER'S TWO CALLS, around an op of a pass it armed for. Before the op, because what it + * stages for this op has to be in the residency table before the op's tables are resolved -- and + * sync_residency is what carries a table change into the tables that hold the weight, which the + * pass otherwise does once, at its start. After the op, on the stream the op went to, because that + * is where "every reader of this weight is behind us" can be recorded. */ +int Ctx::issue(rad_op h, const RadOperand* opd, int n_opd, int64_t n) { + if (!staging_) return issue_body(h, opd, n_opd, n); + if (step_status_ < 0) return step_status_; + bool resync = false; + const int sb = stager_->before_op(h, cur_stream(), &resync); + if (sb < 0) + return abort_step_msg(h, sb, "the weight stager could not stage this op's weights"); + if (resync) sync_residency(); + const int rc = issue_body(h, opd, n_opd, n); + if (rc < 0) return rc; + const int sa = stager_->after_op(h, cur_stream()); + if (sa < 0) + return abort_step_msg(h, sa, "the weight stager could not release this op's weights"); + return rc; +} + +int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) { + const auto t_iss0 = g_dbg_issue ? std::chrono::steady_clock::now() + : std::chrono::steady_clock::time_point{}; + /* The step is already aborted. rad_arch_step is void and cannot know, so it will keep issuing + * the rest of the layer; launching those would burn a step whose output is already wrong and + * bury the first error under fifty more. */ + if (step_status_ < 0) return step_status_; + + if (h == RAD_NULL_HANDLE || (size_t)h >= plans_.size()) + fatal_issue(h, n, "the plugin issued a handle declare never returned. An op that did not " + "resolve is RAD_NULL_HANDLE and becomes an error exactly here"); + + OpPlan& p = plans_[h]; + + /* RAD_N_BATCH is what almost every op wants: the ranged parameter is the step's token count. */ + if (n == RAD_N_BATCH) n = batch_ ? batch_->n_tok : 0; + + /* The bucket table. Bands are sorted by their inclusive upper bound and there are two to four + * of them -- the union of the LE/GE/EQ values the candidate kernels placed on the ranged + * parameter (spec §2.2). A linear scan is one to three predictable compares off one cache + * line, which beats any table or division scheme at this size. */ + const int64_t* hi = band_table_.data() + p.band_off; + int b = 0; + while (b < p.n_bands && n > hi[b]) ++b; + if (b == p.n_bands) + fatal_issue(h, n, "falls outside every band of the op's bucket table -- the declared " + "range does not cover the value the run phase issued at"); + + const int dom = (int)op_domain_[h].load(std::memory_order_relaxed); + IssuePlan& ip = issue_table_[(size_t)p.plan_off + (size_t)b * RAD_N_DOMAINS + (size_t)dom]; + if (!ip.launch) + fatal_issue(h, n, dom == RAD_DOMAIN_HOST + ? "has no host kernel for this band, and the placement planner put " + "it on the host anyway" + : "has no device kernel for this band"); + + if (n_opd < 0 || n_opd > MAX_OPERANDS) + return abort_step_msg(h, RAD_E_INVAL, + fmt("issued with %d operands; the runtime carries at most %d", + n_opd, MAX_OPERANDS)); + if (p.n_opd_schema >= 0 && n_opd != p.n_opd_schema) + return abort_step_msg(h, RAD_E_SCHEMA, + fmt("issued with %d operands; the op's schema declares %d. Operands " + "are positional, so a miscount is silent numerical garbage", + n_opd, (int)p.n_opd_schema)); + + RadTensor* t = tbuf_; + bool touches_host = false; /* a host-domain buffer among the operands; see host_touch_ev_ */ + + for (int i = 0; i < n_opd; ++i) { + const RadOperand& o = opd[i]; + RadTensor& tt = t[i]; + + switch (o.kind) { + case RAD_OPK_BUF: { + const uint32_t bh = o.handle; + if (bh == RAD_NULL_HANDLE || (size_t)bh >= buf_tmpl_.size()) + return abort_step_msg(h, RAD_E_INVAL, + fmt("operand %d names buffer handle %u, which declare never " + "returned", i, bh)); + /* One struct copy: dtype, rank, shape and packed strides came from the declaration and + * the data pointer is already arena_base + BufferInfo::arena_offset. */ + tt = buf_tmpl_[bh]; + touches_host |= buf_host_[bh] != 0; + if (o.offset) { + int64_t d; + if (!byte_delta(buf_bits_[bh], o.offset, &d)) + return abort_step_msg(h, RAD_E_ALIGN, + fmt("operand %d offsets buffer '%s' by %lld elements, " + "which is not a whole number of bytes in %s", i, + program_->buffers[bh].name.c_str(), + (long long)o.offset, + rad_dtype_name(tt.dtype))); + tt.data = static_cast(tt.data) + d; + } + /* rows > 0 narrows dim 0, which is how a prefill chunk of `rows` tokens issues against + * a buffer the plan sized at max_tok. The strides do not change and must not: they are + * products of the trailing dimensions, so shortening the outermost one leaves every + * one of them correct. That is the whole reason the narrowing is dim 0 only. */ + if (o.rows > 0) tt.shape[0] = o.rows; + narrow_cols(o, &tt); + /* AND IT HAS TO FIT THE BUFFER IT NAMES. Narrowing dim 0 is how a chunk of `rows` + * tokens issues against a plan sized at max_tok, and the arrow points one way only: + * an operand may name FEWER rows than the declaration, never more. + * + * A read past the end is uninitialised memory. A WRITE past the end is another + * buffer's bytes, and the arena packs by liveness -- so what it lands on is whatever + * the planner put there, which changes with the graph. That is the worst shape of + * bug this runtime can have: it is silent, it is not reproducible across a config + * change, and the model can stay correct for as long as the victim happens to be + * dead. The canonical shape of it is a MoE expert plane declared at max_tok rows while + * the gated quantiser writes rows*top_k of them, which nothing notices until some + * later op happens to read the buffer the overrun lands on. */ + if (!operand_fits(tt, o.offset, buf_tmpl_[bh])) + return abort_step_msg(h, RAD_E_SHAPE, + fmt("operand %d reaches past buffer '%s': %s at offset " + "%lld, declared %s", i, + program_->buffers[bh].name.c_str(), + opd_shape_str(tt).c_str(), (long long)o.offset, + opd_shape_str(buf_tmpl_[bh]).c_str())); + /* AND THE OP HAS TO BE INSIDE THE BUFFER'S PLANNED LIFETIME. + * + * rad_op_reads/rad_op_writes are what the buffer plan is computed from, and they are + * OPT-IN per op -- a buffer nothing declared gets the whole program and shares nothing, + * which is the sound default. What is NOT sound is an op that touches a buffer other + * ops DID declare, outside the range those declarations produced: the arena has laid + * something else over those bytes, and what comes back is whatever the planner put + * there. It reads as data, so nothing downstream can tell. + * + * This defect class recurs, and its shape is always the same: an op acquires a read + * its declaration never mentioned. `attn_paged` reading the QSA selection is the + * pattern -- the block table arrives as a raw batch pointer, so the op's declared read + * set is just the query, and a page id fetched out of a reused buffer is an address + * outside every mapping. It survives every step until a wider buffer changes the + * packing. + * + * REFUSED RATHER THAN WARNED, because the failure it prevents is silent and is not + * reproducible across a graph change -- the victim buffer is whatever the plan chose + * this time. */ + { + const BufferInfo& bi = program_->buffers[bh]; + if (bi.first_def >= 0 && + ((int32_t)h < bi.first_def || (int32_t)h > bi.last_use)) + return abort_step_msg(h, RAD_E_STATE, + fmt("operand %d names buffer '%s', which this op never " + "declared: the plan gives it ops %d..%d and this is " + "op %u, so the arena may have reused those bytes. " + "Call rad_op_reads/rad_op_writes for it at declare", + i, + bi.name.c_str(), (int)bi.first_def, + (int)bi.last_use, (unsigned)h)); + } + break; + } + + case RAD_OPK_WEIGHT: { + const uint32_t wh = o.handle; + if (wh == RAD_NULL_HANDLE || (size_t)wh >= w_tmpl_.size()) + return abort_step_msg(h, RAD_E_INVAL, + fmt("operand %d names weight handle %u, which declare never " + "returned", i, wh)); + tt = w_tmpl_[wh]; + tt.data = resolve_weight(wh); + w_direct_[wh] = 1; + if (!tt.data) + return abort_step_msg(h, RAD_E_STATE, + fmt("weight '%s' has no pointer at issue: the load phase " + "never bound it and no residency table claims it", + program_->weights[wh].name.c_str())); + if (o.offset) { + int64_t d; + if (!byte_delta(w_bits_[wh], o.offset, &d)) + return abort_step_msg(h, RAD_E_ALIGN, + fmt("operand %d offsets weight '%s' by %lld elements, " + "which is not a whole number of bytes in %s", i, + program_->weights[wh].name.c_str(), + (long long)o.offset, rad_dtype_name(tt.dtype))); + tt.data = static_cast(tt.data) + d; + } + if (o.rows > 0) tt.shape[0] = o.rows; + narrow_cols(o, &tt); + /* THE SAME FIT A BUFFER OPERAND HAS TO PASS, for the same reason. A slice that reaches + * past the declared weight reads whatever the loader or the mover put after it -- the + * next weight in the slab, or the end of the allocation -- and a GEMM over it produces + * plausible numbers. Only a sliced operand can overrun, so the whole-weight case every + * RAD_W issue takes skips the arithmetic. */ + if ((o.offset || o.rows > 0 || o.cols > 0) && + !operand_fits(tt, o.offset, w_tmpl_[wh])) + return abort_step_msg(h, RAD_E_SHAPE, + fmt("operand %d reaches past weight '%s': %s at offset " + "%lld, declared %s", i, + program_->weights[wh].name.c_str(), + opd_shape_str(tt).c_str(), (long long)o.offset, + opd_shape_str(w_tmpl_[wh]).c_str())); + break; + } + + case RAD_OPK_WTAB: { + /* A RUN of declared weights, handed over as a device array of pointers. `handle` is + * the first and `rows` is the count -- rad_decl_weight gives out consecutive indices, + * so a declaration loop over experts produces exactly such a run. */ + const uint32_t w0 = o.handle; + const int64_t cnt = o.rows; + if (w0 == RAD_NULL_HANDLE || cnt <= 0 || + (size_t)((int64_t)w0 + cnt) > w_tmpl_.size()) + return abort_step_msg(h, RAD_E_INVAL, + fmt("operand %d names a weight table of %lld entries from " + "handle %u; declare handed out %zu weights", + i, (long long)cnt, w0, w_tmpl_.size() - 1)); + if (o.offset || o.cols) + return abort_step_msg(h, RAD_E_INVAL, + fmt("operand %d is a weight table and carries an offset or " + "a column slice; neither has a meaning for a table -- " + "slice the entries at declare instead", i)); + const int rc = resolve_weight_table(h, i, (rad_weight)w0, cnt, &tt); + if (rc < 0) return rc; + break; + } + + case RAD_OPK_RAW: + /* A pointer the core did not allocate -- a RadBatch field, almost always. It has no + * BufferInfo, so there is no dtype and no shape to derive: the kernel knows both from + * the op's schema, which is where that knowledge belongs. The core carries the pointer + * and, if the caller gave one, the row count. */ + if (o.offset && o.dtype == RAD_DT_INVALID) + return abort_step_msg(h, RAD_E_INVAL, + fmt("operand %d is a raw pointer with an element offset of " + "%lld and no dtype. Give the operand a dtype with " + "RAD_P_T() or do the arithmetic on the caller's side; " + "the core cannot size an element it was never told about", + i, (long long)o.offset)); + std::memset(&tt, 0, sizeof tt); + tt.data = o.raw; + tt.dtype = o.dtype; /* RAD_DT_INVALID unless the caller said, which is the point of + * the field: libref reads positions, cu_seqlens and + * num_accepted through the tensor's dtype and cannot guess. */ + /* `cols` on a RAW operand is the SECOND EXTENT, not a column slice: there is no + * declared width to slice out of. RAD_P_T2 is how a batch field that is genuinely + * two-dimensional says so, and the block table is why it exists -- [n_seq, max_blocks] + * handed over as rank 1 loses its width, and every kernel that reads it then guesses. */ + if (o.rows > 0 && o.cols > 0) { + tt.rank = 2; + tt.shape[0] = o.rows; tt.shape[1] = o.cols; + tt.stride[0] = o.cols; tt.stride[1] = 1; + } else if (o.rows > 0) { + tt.rank = 1; tt.shape[0] = o.rows; tt.stride[0] = 1; + } + break; + + case RAD_OPK_KV: { + /* A KV group's cache for one layer. `handle` is the rad_kvgroup and `offset` is the + * ABSOLUTE layer index, which the binding rebases -- a group holds one cache per bound + * layer, not one per model layer, and 48 GDN layers interleaved with 16 attention ones + * would otherwise index a 64-deep pool that was never allocated. */ + const uint32_t g = o.handle; + if ((size_t)g >= kv_.size() || !kv_[g].base) + return abort_step_msg(h, RAD_E_STATE, + fmt("operand %d names KV group %u, which has no pool bound. " + "The block manager allocates it at load and binds it " + "into the Ctx; a group with none is a startup bug, not " + "a runtime condition", i, g)); + const KVPoolBinding& b = kv_[g]; + /* A POSITION LOOKUP, not `o.offset - first_layer`. The subtraction is right only for a + * group whose layers are contiguous, and they need not be: with 15 attention layers + * interleaved through 64, absolute layer 19 -- the fifth of them -- subtracts to slot + * 16 of a 15-slot pool, which the bounds check below refuses. */ + const int64_t layer = (o.offset >= 0 && (size_t)o.offset < b.layer_slot.size()) + ? b.layer_slot[(size_t)o.offset] + : -1; + const int64_t off = layer * b.layer_stride; + if (layer < 0 || (b.bytes && off + b.layer_stride > b.bytes)) + return abort_step_msg(h, RAD_E_INVAL, + fmt("operand %d asks KV group %u for layer %lld, which is " + "outside the %lld bytes it was allocated", i, g, + (long long)o.offset, (long long)b.bytes)); + std::memset(&tt, 0, sizeof tt); + tt.data = static_cast(b.base) + off; + tt.dtype = b.dtype; + /* THE OPERAND CARRIES THE LAYER'S SHAPE, not a flat byte span. The binding composed it + * at load out of the plugin's declaration and the block manager's decisions, because + * neither half alone is enough (core/runtime/ctx.h says which numbers and why). Every + * libr4d shim refuses a flat span -- `if (kv->rank != 4) return RAD_E_SHAPE` -- and + * refuses correctly: a paged cache walked as one dimension is not a cache. */ + if (b.rank) { + tt.rank = b.rank; + for (uint32_t d = 0; d < b.rank; ++d) tt.shape[d] = b.shape[d]; + rad_tensor_pack(&tt); + } else { + tt.rank = 1; + tt.shape[0] = b.layer_stride + ? b.layer_stride * 8 / + (rad_dtype_bits(b.dtype) ? rad_dtype_bits(b.dtype) : 8) + : 0; + tt.stride[0] = 1; + } + if (o.rows > 0) tt.shape[0] = o.rows; + break; + } + + default: + /* RAD_OPK_NONE: an absent optional operand is a null RadTensor.data, per rad_abi.h. */ + std::memset(&tt, 0, sizeof tt); + break; + } + } + + /* Everything else in RadArgs -- the geometry view, the scratch pointer and its size, the + * instance init() returned, the rank and the world size -- was filled in at prepare and has + * not changed. args.t already points at tbuf_. */ + ip.args.n_t = n_opd; + p.issued = true; + ++n_issues_; + + /* RADIANCE_DEBUG_ARGSHA -- see the note by the digest. Pass 1 only, so the sequence compared + * step to step is the same sequence. */ + + /* RANK 0 ONLY. These accumulators are file-scope statics and `Ctx::issue` runs on EVERY rank + * thread, so without this the two ranks interleave into one sequence: the issue COUNT then + * varies run to run and every digest differs, which reads exactly like a data-dependent op + * sequence and is not one. */ + if (g_dbg_argsha && batch_ && rank() == 0) { + const int dp = batch_->draft_pass; + if (dp != g_argsha_pass) { + if (g_argsha_pass == 1 && !g_argsha_cur.empty() && g_argsha_seen < 12) { + size_t mptr = 0, mshp = 0; + const size_t k = g_argsha_cur.size() < g_argsha_prev.size() + ? g_argsha_cur.size() : g_argsha_prev.size(); + for (size_t i = 0; i < k; ++i) { + if (g_argsha_cur[i].ptr != g_argsha_prev[i].ptr) ++mptr; + if (g_argsha_cur[i].shp != g_argsha_prev[i].shp) ++mshp; + } + if (!g_argsha_prev.empty()) { + std::fprintf(stderr, + "D argsha: draft pass 1 -- %zu issues, %zu moved a POINTER, " + "%zu moved a SHAPE\n", + g_argsha_cur.size(), mptr, mshp); + if (g_argsha_seen < 2) { + auto nm = [&](rad_op oh) -> const char* { + return (oh != RAD_NULL_HANDLE && (size_t)oh < plans_.size() && + plans_[oh].info) + ? plans_[oh].info->op.c_str() : ""; + }; + for (size_t i = 0; i < k; ++i) { + const bool p = g_argsha_cur[i].ptr != g_argsha_prev[i].ptr; + const bool q = g_argsha_cur[i].shp != g_argsha_prev[i].shp; + if (p || q) + std::fprintf(stderr, "D argsha: %2zu %-24s %s%s\n", i, + nm(g_argsha_cur[i].h), p ? "ptr " : "", + q ? "shape" : ""); + } + } + } + ++g_argsha_seen; + g_argsha_prev = g_argsha_cur; + } else if (g_argsha_pass == 1) { + g_argsha_prev = g_argsha_cur; + } + if (dp == 1) { g_argsha_cur.clear(); g_argsha_i = 0; } + g_argsha_pass = dp; + } + if (dp == 1) { g_argsha_cur.push_back(argsha_of(h, n, t, n_opd)); ++g_argsha_i; } + } + + /* THE LINK BILL, charged where the message size is known and nothing has to be guessed: `n` + * IS the collective's `numel` (every all_reduce declares it as the ranged parameter) and + * operand 0 carries the dtype it is sent in, which is the ACTIVATION's dtype and not the op's + * `dtype` key -- that key is the architecture's operand-combination spelling ("w4a8"), which + * is not an element width. Two relaxed adds on seventeen issues a step. */ + if (p.collective && n_opd > 0) { + const int bits = rad_dtype_bits(t[0].dtype); + ar_calls_.fetch_add(1, std::memory_order_relaxed); + if (bits > 0) ar_bytes_.fetch_add(n * bits / 8, std::memory_order_relaxed); + } + + /* The oracle, if this issue is one it was asked about. It snapshots every operand to the host + * before the launch so the host kernel can be given the same bytes -- an in-place op would + * otherwise be compared against its own output. Null in every run that did not arm it. */ + const IssuePlan* horacle = oracle_ ? oracle_before(h, b, n_opd) : nullptr; + + /* ============================== A HOST LAUNCH IS A JOIN ============================== + * + * THE HOST THREAD RUNS AHEAD OF THE DEVICE. Every device launch is asynchronous, so by the + * time this function is called for op N the GPU may still be somewhere back at op N-200 -- + * that gap is the whole reason the issue path is allowed to cost a microsecond. A HOST-SITE op + * is the one place it stops being harmless: it runs NOW, on this thread, and reads and writes + * the host arena NOW. + * + * A PLE gather is exactly that shape. `ngram_ids` writes the hashed row ids into a host-domain + * buffer on the device, and `embed_lookup_q` reads them on the host. With no join the host + * reads whatever the arena holds from an earlier step and gathers the rows of the wrong + * n-gram -- valid ids, valid rows, every kernel agreeing with its oracle, and fluent text that + * is a stable wrong answer rather than an intermittent one. + * + * WHAT THE JOIN WAITS FOR is the last device op on each lane that touched the host arena + * (host_touch_ev_), not the whole stream. Every hazard a host op has is with such an op -- the + * producer of an input, or a device reader of bytes its output reuses -- and on one lane they + * all complete no later than the last of them. Draining the stream instead waits for + * everything issued before the op, which on a decode step is every layer in front of it, and + * then the device runs dry while the host works, because nothing after the host op has been + * issued yet. Waiting on the producer alone lets an architecture issue it early and keep the + * device busy with the layers issued in between while the host gathers. + * + * AN OPERAND THE ARENA DOES NOT DESCRIBE IS NOT TRACKED -- a raw batch pointer, a KV cache, a + * device-domain buffer -- so a host op that names one drains its stream (host_join). + * + * AND THE HOST'S WRITES HAVE TO REACH THE DEVICE. Host-arena memory is cached on the device like + * any other memory, and with no host wait between the host op and the kernel that reads its + * output, nothing would make that kernel look past a stale line: rad_dev_host_wrote, after the + * launch below, is what does. */ + if (dom == RAD_DOMAIN_HOST) { + /* TIMED APART FROM THE OP, because it is not the op's cost -- it is the cost of the + * PIPELINE this op stops. */ + if (profiling_) { + const auto j0 = std::chrono::steady_clock::now(); + const int js = host_join(opd, n_opd); + const auto j1 = std::chrono::steady_clock::now(); + prof_join_ms_[(size_t)h] += std::chrono::duration(j1 - j0).count(); + if (js < 0) return abort_step(h, b, dom, ip, n, js); + } else { + const int js = host_join(opd, n_opd); + if (js < 0) return abort_step(h, b, dom, ip, n, js); + } + } + + /* A SCRATCH REGION IS ONE STREAM'S. The kernels on a lane are handed consecutive slices of it + * (scratch_take), and two that could run at once on the lane are kept apart by the slices + * being disjoint -- the pass's recording orders any pair whose slices meet (haz_mark). A + * scratch user on each lane with no join between them overlaps with nothing recorded to order + * it, and the two would overwrite each other's partials with nothing downstream able to tell. + * A split-K router GEMM on lane 0 and the shared arm's split-K GEMM on lane 1 meet exactly + * like that on every MoE layer. + * + * So a program that declares its second lane gets a region per lane, and each launch is + * pointed at its own lane's. A lane used WITHOUT that declaration shares region 0, and there + * the second of such a pair is ordered behind the first instead -- the overlap is given up for + * that launch, never the numbers. That fallback is kept on lane 0 before lane 1 exists as well: + * a lane built later starts with nothing ordering it behind what lane 0 already issued. */ + if (ip.args.scratch_bytes > 0 && dom != RAD_DOMAIN_HOST && arena_.scratch_regions() > 1) { + /* Each lane has its own region, so two scratch users on two lanes never share bytes and + * nothing has to be ordered. The plan entry serves whichever lane issues it. */ + ip.args.scratch = scratch_take(lane_, ip.args.scratch_bytes); + } else if (ip.args.scratch_bytes > 0 && dom != RAD_DOMAIN_HOST) { + ip.args.scratch = scratch_take(0, ip.args.scratch_bytes); + const int other = lane_ ^ 1; + if (scratch_open_[other]) { + if (!scratch_join_warned_) { + scratch_join_warned_ = true; + RAD_WARN("op '%s' (%s, n=%lld) uses scratch on lane %d while '%s' (n=%lld) on lane " + "%d, also a scratch user, is not ordered before it; lane %d now waits for " + "lane %d there, which costs the overlap at that point", + p.info->op.c_str(), + ip.row && ip.row->info ? ip.row->info->name : "?", (long long)n, lane_, + scratch_kernel_[other] ? scratch_kernel_[other] : "?", + (long long)scratch_n_[other], other, lane_, other); + } + const int js = lane_join(other, lane_); + if (js < 0) return abort_step(h, b, dom, ip, n, js); + } + scratch_open_[lane_] = true; + scratch_kernel_[lane_] = ip.row && ip.row->info ? ip.row->info->name : nullptr; + scratch_n_[lane_] = n; + } + + /* A HOST-SITE OP IN A PASS BEING RECORDED is host work a tape cannot hold: the recording is + * cut here and the op kept, to be joined and run again on these operands at every play. Its + * launch is not recorded either way -- anything it submitted would be submitted twice. */ + if (rec_ && dom == RAD_DOMAIN_HOST) { + tape_cut(); + TapeHost th; + th.h = h; + th.launch = ip.launch; + th.args = ip.args; + th.n = n; + th.drain = host_join_drains(opd, n_opd); + for (int i = 0; i < n_opd; ++i) th.t[i] = t[i]; + TapeStep st; + st.kind = kTapeHost; + st.lane = (uint8_t)lane_; + st.a = (int32_t)rec_->host.size(); + rec_->host.push_back(th); + rec_->steps.push_back(st); + } + const bool host_paused = rec_ && dom == RAD_DOMAIN_HOST; + if (host_paused) tape_pause(true); + const int rec0 = rec_ && !host_paused ? tape_mark() : 0; + + int s; + if (profiling_ && dom == RAD_DOMAIN_HOST) { + + /* A HOST-SITE OP IS TIMED ON THE HOST CLOCK, because device events cannot see it: they + * record when the STREAM reaches them and the stream does not stall for a host call, so an + * event pair around this launch measures nothing and the op vanishes from the table. + * + * Without this the most expensive thing in the step vanishes from the table. The PLE + * gather reads sixteen 160-byte rows out of a multi-gigabyte mapping per token, so its + * layer costs milliseconds a step against tens of microseconds of device kernels -- and a + * device-event profile shows only the tens of microseconds. A host kernel's cost is a + * STALL in the middle of the step, which is the one thing an operator most needs named. + * + * Wall clock and not a device event, so it includes whatever the host call waits on: + * page faults, the link read of its input, everything. That is the number that matters. */ + const auto t0 = std::chrono::steady_clock::now(); + s = ip.launch(&ip.args, cur_stream()); + const auto t1 = std::chrono::steady_clock::now(); + prof_ms_[(size_t)h] += + std::chrono::duration(t1 - t0).count(); + prof_calls_[(size_t)h] += 1; + if ((size_t)h < prof_host_.size()) prof_host_[(size_t)h] = 1; + } else if (profiling_) { + /* One predictable branch in exchange for §16's per-op timing. The events go on the compute + * stream around the launch; the synchronisation that reads them is at the end of the step, + * and it is what makes a profiled run incomparable to an unprofiled one. */ + if (prof_n_ < prof_ring_.size()) { + ProfSlot& ps = prof_ring_[prof_n_++]; + ps.op = (int32_t)h; + rad_event_record(ps.a, cur_stream()); + s = ip.launch(&ip.args, cur_stream()); + rad_event_record(ps.b, cur_stream()); + } else { + prof_overflowed_ = true; + s = ip.launch(&ip.args, cur_stream()); + } + /* RANK 0 ONLY, FOR THE SECOND TIME IN THIS FILE. `Ctx::issue` runs on every rank thread, so a + * file-scope accumulator is written by both. Unguarded, the digest above gives wrong NUMBERS + * -- two ranks interleaving into one sequence -- and the per-op std::unordered_map here gives + * a SEGFAULT within a window. Doubles race benignly enough to mislead, a hash map does not + * race at all. Anything this instrument accumulates belongs to one thread. */ + } else if (g_dbg_issue && rank() == 0) { + const auto ta = std::chrono::steady_clock::now(); + s = ip.launch(&ip.args, cur_stream()); + const auto tb = std::chrono::steady_clock::now(); + using us = std::chrono::duration; + g_iss_own += us(ta - t_iss0).count(); + g_iss_lau += us(tb - ta).count(); + IssOp& io = g_iss_by_op[(uint32_t)h]; + io.own += us(ta - t_iss0).count(); + io.lau += us(tb - ta).count(); + ++io.n; + if (++g_iss_n % 200000 == 0) { + const double w = 200000.0; + std::fprintf(stderr, "D issue: %ld issues -- this window: own %.3f us, launch %.3f us " + "an issue (%.3f total)\n", + g_iss_n, (g_iss_own - g_iss_own_p) / w, (g_iss_lau - g_iss_lau_p) / w, + (g_iss_own - g_iss_own_p + g_iss_lau - g_iss_lau_p) / w); + /* The walk is inside `own`, so this says how much of `own` it IS. */ + std::fprintf(stderr, "D issue: of which weight tables: %.3f us an issue over " + "%.1f entries (%.1f ns an entry)\n", + (g_wtab_us - g_wtab_us_p) / w, + (double)(g_wtab_e - g_wtab_e_p) / w, + (g_wtab_e - g_wtab_e_p) > 0 + ? (g_wtab_us - g_wtab_us_p) * 1000.0 / (double)(g_wtab_e - g_wtab_e_p) + : 0.0); + /* Top by TOTAL host launch time, not by the per-issue mean: an op issued 48 times a + * step at 2 us costs more than one issued twice at 20. Both columns are printed so a + * fat prologue and a fat call count can be told apart. */ + std::vector> ord; + ord.reserve(g_iss_by_op.size()); + for (const auto& kv : g_iss_by_op) ord.push_back({kv.second.lau, kv.first}); + std::sort(ord.begin(), ord.end(), std::greater<>()); + for (size_t i = 0; i < ord.size() && i < 12; ++i) { + const IssOp& io = g_iss_by_op[ord[i].second]; + const OpInfo* oi = (size_t)ord[i].second < plans_.size() + ? plans_[ord[i].second].info : nullptr; + std::fprintf(stderr, + "D issue: %-26s %7ld issues launch %6.3f us own %6.3f us " + "(%8.1f us of launch in all)\n", + oi ? oi->op.c_str() : "", io.n, io.lau / (double)io.n, + io.own / (double)io.n, io.lau); + } + g_iss_by_op.clear(); + g_wtab_us_p = g_wtab_us; + g_wtab_e_p = g_wtab_e; + g_iss_own_p = g_iss_own; + g_iss_lau_p = g_iss_lau; + } + } else { + s = ip.launch(&ip.args, cur_stream()); + } + if (host_paused) tape_pause(false); + + if (s < 0) return abort_step(h, b, dom, ip, n, s); + if (rec_ && !host_paused) haz_note(p, ip, t, n_opd, rec0, tape_mark()); + + if (dom == RAD_DOMAIN_HOST) { + rad_dev_host_wrote(); + } else if (touches_host) { + const int l = lane_; + if (!host_touch_ev_[l]) { + const int ec = rad_event_create(&host_touch_ev_[l]); + if (ec < 0) return abort_step(h, b, dom, ip, n, ec); + } + const int er = rad_event_record(host_touch_ev_[l], cur_stream()); + if (er < 0) return abort_step(h, b, dom, ip, n, er); + host_touch_pending_[l] = true; + } + if (horacle) oracle_after(h, *horacle, ip, n_opd); + return RAD_OK; +} + +/* The next slice of a scratch region; see scratch_cur_ in ctx.h. */ +void* Ctx::scratch_take(int region, int64_t bytes) { + constexpr int64_t kAlign = 256; + const int64_t need = (bytes + kAlign - 1) / kAlign * kAlign; + int64_t off = scratch_cur_[region]; + if (off + need > arena_.scratch_bytes()) off = 0; + scratch_cur_[region] = off + need; + return (char*)arena_.scratch(region) + off; +} + +/* What one device op of a pass being recorded reads and writes; see HazOp in ctx.h. */ +void Ctx::haz_note(const OpPlan& p, const IssuePlan& ip, const RadTensor* t, int n_opd, int rec0, + int rec1) { + if (rec1 <= rec0) return; + HazOp o; + o.rec0 = rec0; + o.rec1 = rec1; + o.op = (uint32_t)(&p - plans_.data()); + const RadOpSchema* sc = p.info ? p.info->schema : nullptr; + o.opaque = p.collective || !sc || sc->n_operands != n_opd || !ip.row || !ip.row->concurrent; + std::pair rd[MAX_OPERANDS + 1], wr[MAX_OPERANDS + 1]; + int n_rd = 0, n_wr = 0; + for (int i = 0; i < n_opd && !o.opaque; ++i) { + const RadTensor& tt = t[i]; + if (!tt.data) continue; + const int role = sc->operands[i].role; + if (role == RAD_OPD_WEIGHT) continue; + const uintptr_t lo = (uintptr_t)tt.data; + if (role == RAD_OPD_WTAB) { + /* The pointer array itself; the experts it names are weights. */ + if (tt.rank < 1 || tt.shape[0] <= 0) { o.opaque = true; break; } + rd[n_rd++] = { lo, lo + (uintptr_t)tt.shape[0] * sizeof(void*) }; + continue; + } + const int bits = rad_dtype_bits(tt.dtype); + if (tt.rank == 0 || bits <= 0) { o.opaque = true; break; } + int64_t span = 1; + bool empty = false; + for (uint32_t d = 0; d < tt.rank; ++d) { + if (tt.shape[d] <= 0) { empty = true; break; } + if (tt.stride[d] < 0) { o.opaque = true; break; } + span += (tt.shape[d] - 1) * tt.stride[d]; + } + if (o.opaque) break; + if (empty) continue; + const std::pair r{ lo, lo + (uintptr_t)((span * bits + 7) / 8) }; + if (role == RAD_OPD_IN || role == RAD_OPD_INOUT) rd[n_rd++] = r; + if (role == RAD_OPD_OUT || role == RAD_OPD_INOUT) wr[n_wr++] = r; + } + if (!o.opaque && ip.args.scratch_bytes > 0 && ip.args.scratch) { + const uintptr_t lo = (uintptr_t)ip.args.scratch; + rd[n_rd++] = wr[n_wr++] = { lo, lo + (uintptr_t)ip.args.scratch_bytes }; + } + o.rd = (uint32_t)haz_rng_.size(); + o.n_rd = (uint32_t)n_rd; + for (int i = 0; i < n_rd; ++i) haz_rng_.push_back(rd[i]); + o.wr = (uint32_t)haz_rng_.size(); + o.n_wr = (uint32_t)n_wr; + for (int i = 0; i < n_wr; ++i) haz_rng_.push_back(wr[i]); + haz_ops_.push_back(o); +} + +/* THE HOST OP'S JOIN; see "A HOST LAUNCH IS A JOIN" in Ctx::issue. */ +int Ctx::host_join(const RadOperand* opd, int n_opd) { + return host_join_wait(host_join_drains(opd, n_opd)); +} + +/* Whether an operand is one the arena does not track, which the join can only cover by draining + * the stream. */ +bool Ctx::host_join_drains(const RadOperand* opd, int n_opd) const { + for (int i = 0; i < n_opd; ++i) { + const RadOperand& o = opd[i]; + if (o.kind == RAD_OPK_WEIGHT || o.kind == RAD_OPK_WTAB || o.kind == RAD_OPK_NONE) continue; + if (o.kind == RAD_OPK_BUF && buf_host_[o.handle]) continue; + return true; + } + return false; +} + +int Ctx::host_join_wait(bool drain) { + ++n_host_syncs_; + if (drain) return rad_stream_sync(cur_stream()); + for (int l = 0; l < 2; ++l) { + if (!host_touch_pending_[l]) continue; + RAD_TRY(rad_event_sync(host_touch_ev_[l])); + host_touch_pending_[l] = false; + } + return RAD_OK; +} + +/* ================================================================== the cold paths */ + +int Ctx::abort_step(rad_op h, int band, int dom, const IssuePlan& ip, int64_t n, int status) { + const OpInfo& o = *plans_[h].info; + const char* kname = ip.row && ip.row->info ? ip.row->info->name : ""; + const char* pname = ip.row ? ip.row->plugin.c_str() : ""; + const Resolved& r = o.bands[(size_t)band].dom[dom]; + const char* key = o.ranged_key.empty() ? "n" : o.ranged_key.c_str(); + + /* std::string here, on a path that has already lost the step. The hot path above allocates + * nothing; this one is allowed to, because the alternative is a truncated diagnostic on the + * one occasion anybody needs a complete one. */ + step_fail_ = fmt("kernel %s (%s, %s, %s domain) refused op '%s' at %s=%lld " + "[band %s<=%lld] geometry {%s}: %s", + kname, pname, r.choice.empty() ? "no tunables" : r.choice.c_str(), + dom == RAD_DOMAIN_HOST ? "host" : "device", + o.op.c_str(), key, (long long)n, key, + (long long)o.bands[(size_t)band].hi, r.geom.str().c_str(), + rad_strerror(status)); + + RAD_ERR("%s", step_fail_.c_str()); + RAD_ERR("a kernel returning negative at issue is a bug in SELECTION, not a runtime condition. " + "The step is aborted and the requests in it fail. There is no fallback here, silent " + "or otherwise -- a silent fallback is how you ship a slow path nobody knows about " + "(spec §17)."); + + step_status_ = status; + return status; +} + +int Ctx::step_fail(const char* what) { + step_fail_ = what ? what : "the architecture block refused this batch"; + RAD_ERR("%s", step_fail_.c_str()); + step_status_ = RAD_E_SHAPE; + return RAD_E_SHAPE; +} + +int Ctx::abort_step_msg(rad_op h, int status, std::string what) { + const OpInfo* o = (h != RAD_NULL_HANDLE && (size_t)h < plans_.size()) ? plans_[h].info : nullptr; + step_fail_ = o ? fmt("op '%s' {%s}: %s", o->op.c_str(), o->base.str().c_str(), what.c_str()) + : fmt("op handle %u: %s", h, what.c_str()); + RAD_ERR("%s", step_fail_.c_str()); + step_status_ = status; + return status; +} + +void Ctx::fatal_issue(rad_op h, int64_t n, const char* why) const { + if (h == RAD_NULL_HANDLE || (size_t)h >= plans_.size() || !plans_[h].info) + fatal("rad_issue: op handle %u at n=%lld %s", (unsigned)h, (long long)n, why); + const OpInfo& o = *plans_[h].info; + fatal("rad_issue: op '%s' {%s} at %s=%lld %s", + o.op.c_str(), o.base.str().c_str(), + o.ranged_key.empty() ? "n" : o.ranged_key.c_str(), (long long)n, why); +} + +/* ================================================================== pointer queries */ + +void* Ctx::weight_ptr(rad_weight w) { + if (w == RAD_NULL_HANDLE || (size_t)w >= w_tmpl_.size()) { + RAD_WARN("rad_weight_ptr: handle %u was never declared", (unsigned)w); + return nullptr; + } + w_direct_[w] = 1; + return resolve_weight(w); +} + +void* Ctx::buf_ptr(rad_buf b) { + if (b == RAD_NULL_HANDLE || (size_t)b >= buf_tmpl_.size()) { + RAD_WARN("rad_buf_ptr: handle %u was never declared", (unsigned)b); + return nullptr; + } + return buf_tmpl_[b].data; +} + +} /* namespace rad */ + +/* ================================================================== the C surface */ +/* rad_runtime.h is C, and this is the whole of its implementation. Ctx derives from RadCtx, so + * every one of these is a static_cast and a forwarded call -- the compiler sees straight through + * it, which is the point of the empty base rather than a reinterpret_cast. */ +extern "C" { + +int rad_issue(RadCtx* c, rad_op op, const RadOperand* opd, int n_opd, int64_t n) { + if (!c) rad::fatal("rad_issue: null RadCtx"); + return static_cast(c)->issue(op, opd, n_opd, n); +} + +int rad_step_fail(RadCtx* c, const char* what) { + if (!c) rad::fatal("rad_step_fail: null RadCtx"); + return static_cast(c)->step_fail(what ? what : "the architecture block refused this batch"); +} + +const RadBatch* rad_batch(RadCtx* c) { return c ? static_cast(c)->batch() : nullptr; } +int rad_rank(RadCtx* c) { return c ? static_cast(c)->rank() : 0; } +int rad_world_size(RadCtx* c) { return c ? static_cast(c)->world_size() : 1; } +RadStream rad_stream(RadCtx* c) { return c ? static_cast(c)->stream() : nullptr; } + +/* The second lane. `rad_lane` says which one subsequent issues launch on; `rad_lane_join` orders + * one behind the other with an event and blocks neither the host nor either stream. The runtime + * joins lane 1 back into lane 0 at the end of every step whatever the plugin did, so forgetting + * the join is a performance bug and not a correctness one. Read Ctx::lane1_ before using this: + * every collective must ride ONE lane, a second lane may not carry a split-K GEMM, and the buffer + * planner packs from a single linear order. */ +int rad_lane(RadCtx* c, int lane) { + if (!c) return RAD_E_INVAL; + return static_cast(c)->set_lane(lane); +} +int rad_lane_join(RadCtx* c, int from, int to) { + if (!c) return RAD_E_INVAL; + return static_cast(c)->lane_join(from, to); +} + +int rad_route_report(RadCtx* c, int layer, const RadRouting* r) { + if (!c) return RAD_E_INVAL; + return static_cast(c)->route_report(layer, r); +} + +int32_t* rad_route_counts(RadCtx* c, int layer, int64_t n_expert) { + return c ? static_cast(c)->route_counts(layer, n_expert) : nullptr; +} + +void* rad_weight_ptr(RadCtx* c, rad_weight w) { + return c ? static_cast(c)->weight_ptr(w) : nullptr; +} + +void* rad_buf_ptr(RadCtx* c, rad_buf b) { + return c ? static_cast(c)->buf_ptr(b) : nullptr; +} + +} /* extern "C" */ diff --git a/core/runtime/oracle.cpp b/core/runtime/oracle.cpp new file mode 100644 index 00000000..0d75695d --- /dev/null +++ b/core/runtime/oracle.cpp @@ -0,0 +1,958 @@ +/* oracle.cpp -- run the HOST kernel beside the device one, on the same bytes, every issue. + * + * ================================================================= why this exists + * + * rad-kbench falsifies one op at a time against libref, with operands rad-kbench invented. A build + * can pass nearly every configuration it knows while the engine answers the same token to every + * prompt. That gap is structural and not a gap in coverage: rad-kbench's operands are ITS shapes, dense and + * rank-2 and freshly filled, and the engine's are row slices of a max_tok buffer, column slices of + * a fused projection, rank-3 views a scan kernel required, and weights that came off a file. An op + * can be correct at every shape rad-kbench knows and wrong at the one shape the model issues. + * + * So this checks the shape the model actually issued. For a matching op it + * + * 1. copies every operand to the host BEFORE the launch -- inputs, outputs, weights, all of it; + * 2. lets the device kernel run and synchronises; + * 3. copies every operand back into a second host buffer; + * 4. puts every weight the device row stores RELAID back through that row's own + * RadUnrelayoutFn, because the kernel rearranged it at load and a dense reference reads the + * canonical planes (see oracle_unrelayout -- this step is not optional, it is the + * difference between checking a kernel and comparing a permutation against itself); + * 5. runs the HOST kernel for the same (op, band) on the copy from step 1 -- same RadTensor + * shapes, same strides, same parameters, only the pointers differ; + * 6. compares, per operand, the host result against the device result. + * + * Step 5 is the part that has no substitute. The host row is libref's, resolved by the same + * selector into the same bucket table -- `issue_table_[plan_off + band*RAD_N_DOMAINS + HOST]` is + * already sitting there beside the device plan, filled in at prepare and never used, because the + * placement planner put every op on the device. It is a second implementation of the op, against + * the same schema, and it is free. + * + * ================================================================= what it costs + * + * Everything. Two device-to-host copies of every operand -- a fused gate_up weight is 170 MiB -- + * a host synchronisation per issue, and a reference kernel that is not trying to be fast. A step + * with the oracle on takes minutes. It is a debugging instrument and it is off unless asked. + * + * ================================================================= how to ask + * + * RADIANCE_OP_ORACLE=gemm_nt_q,rmsnorm op names, comma separated; `*` for every op + * RADIANCE_OP_ORACLE_MAX=32 stop after this many checks (default 32) + * RADIANCE_OP_ORACLE_FROM=0 first ISSUE INDEX to consider (default 0) + * RADIANCE_OP_ORACLE_TO=100000 last issue index to consider + * RADIANCE_OP_ORACLE_TOL=0.02 relative tolerance below which an operand is silent + * RADIANCE_OP_ORACLE_MAXBYTES the largest operand a check will copy (default 4 GiB) + * + * The issue index is the same counter Ctx tracks internally and the same order --debug-graph + * prints, so a failure names a position in the graph and not just an op. + * + * ================================================================= the repeat mode + * + * RADIANCE_OP_REPEAT asks a different question with the same machinery: not "does this kernel + * agree with libref" but "does this kernel agree with ITSELF". It snapshots the operands, lets + * the device kernel run, puts the operands back exactly as they were, runs the SAME DEVICE KERNEL + * again, and byte-compares the two results. + * + * That is the one fault class every other instrument here is structurally blind to. The oracle, + * rad-kbench and the residual probe all run an op ONCE per side, so a kernel with an unordered + * reduction, a workgroup reading what another workgroup is writing, or a workspace it assumed was + * zeroed passes them at exactly the rate it happens to be right. Byte-exact, no tolerance: the + * same kernel on the same bytes has no licence to move, and one mantissa bit is a different token + * a few hundred greedy steps later. + * + * RADIANCE_OP_REPEAT=* op names, comma separated; `*` for every op + * RADIANCE_OP_REPEAT_MAX=1000000 stop after this many checks + * RADIANCE_OP_REPEAT_FROM / _TO issue index window + * RADIANCE_OP_REPEAT_MAXBYTES=8388608 operands above this are not copied, restored or + * compared -- which is what keeps a 170 MiB fused weight + * from making the mode unaffordable, and is right only + * because such an operand is read-only. + * + * ================================================================= what it cannot see + * + * An op ISSUED ON A LANE THE SNAPSHOT DOES NOT SYNCHRONISE -- fixed for lane 1, which is the only + * one the ABI has, and a third would need the same line. + * + * An op with no host kernel for the band -- the oracle skips it and says so once. An op whose + * dtype the core cannot size (a plugin-private one) -- skipped, since a byte span is the one thing + * this needs to know. An op whose device row re-lays a weight and publishes no inverse -- skipped + * BY NAME, because the alternative is a page of false mismatches that drowns the true ones. And + * an op that is wrong in the SAME WAY on both sides, which is what a shared misreading of the + * schema would look like; that is what rad-kbench's independent operands + * are for, and the two instruments are complementary rather than redundant. + */ +#include "ctx.h" +#include "format/encoding.h" +#include "rad_plugin.h" + +#include +#include +#include +#include +#include +#include + +namespace rad { + +/* ------------------------------------------------------------------ the state */ +struct Ctx::OracleState { + std::vector want; /* op names; a single "*" means every op */ + int64_t budget = 32; + int64_t from = 0, to = INT64_MAX; + double tol = 2e-2; + int64_t checked = 0, skipped_nohost = 0; + bool said_nohost = false; + /* ---- repeat mode. `maxbytes` is what makes it affordable: a fused gate_up operand is 170 MiB + * and a weight is read-only, so an operand past the cap is not snapshotted, not restored and + * not compared. Every activation this graph carries at decode is far below it. */ + bool repeat = false; + int64_t maxbytes = 8 << 20; + /* ---- AN OPERAND THE HOST CANNOT HOLD, which is the oracle mode's own cap and not the one + * above. A snapshot is two host copies of every operand, plus a third for a weight stored + * re-laid, so an operand of tens of gigabytes does not make a check slow -- it ends the + * process with nothing reported. Four gibibytes clears a routed layer's whole expert table, + * which is the largest operand a check has to hold. */ + int64_t maxopd = 4LL << 30; + int64_t differed = 0, unchecked = 0; + int skip[MAX_OPERANDS] = {0}; + + std::vector scratch; /* the host kernel's, sized per launch */ + /* A re-laid weight inverted back into the form a dense reference reads, one buffer per + * operand that needed it, and which operands those were. See oracle_unrelayout. */ + std::vector> logical; + int unlaid[MAX_OPERANDS] = {0}; + std::vector> pre, post; /* one snapshot per operand */ + int64_t span[MAX_OPERANDS] = {0}; /* elements, stacked */ + int64_t ent [MAX_OPERANDS] = {0}; /* bytes, ONE entry */ + /* Entries when the operand is a weight TABLE and 0 when it is a plane. See oracle_size: a + * table is materialised stacked, because the operand itself is an array of pointers. */ + int64_t tab [MAX_OPERANDS] = {0}; + int alias[MAX_OPERANDS] = {0}; /* which operand owns the copy */ + RadTensor ht[MAX_OPERANDS]{}; +}; + +namespace { + +/* The number of ELEMENTS a tensor's strides can reach, which is what has to be copied. Not + * numel: a row slice of a [max_tok, n] buffer is dense, but a column slice of a fused projection + * is not, and copying numel elements of one of those copies the wrong bytes. */ +int64_t span_of(const RadTensor* t) { + if (!t->data || t->rank == 0) return 0; + int64_t s = 1; + for (uint32_t d = 0; d < t->rank; ++d) { + if (t->shape[d] <= 0) return 0; + const int64_t st = t->stride[d]; + if (st > 0) s += (t->shape[d] - 1) * st; + } + return s; +} + +float f8e4m3_to_f32(uint8_t b) { + const uint32_t sgn = (uint32_t)(b & 0x80u) << 24; + const int e = (b >> 3) & 0x0F; + const uint32_t m = b & 0x07u; + float f; + uint32_t u; + if (e == 0) { /* subnormal: m * 2^-9 */ + if (!m) { u = sgn; std::memcpy(&f, &u, 4); return f; } + int ex = -6; uint32_t mm = m; + while (!(mm & 0x08u)) { mm <<= 1; --ex; } /* normalise into 1.mmm */ + u = sgn | ((uint32_t)(ex + 127) << 23) | ((mm & 0x07u) << 20); + } else if (e == 0x0F && m == 0x07) { /* the two NaN encodings */ + u = sgn | 0x7FC00000u; + } else { + u = sgn | ((uint32_t)(e - 7 + 127) << 23) | (m << 20); + } + std::memcpy(&f, &u, 4); + return f; +} + +/* One element as a double, by dtype. Returns false for a dtype with no meaningful value -- the + * comparison then falls back to a byte compare, which is the right answer for an index plane. */ +bool elem(const uint8_t* p, uint32_t dt, int64_t i, double* out) { + switch (dt) { + case RAD_F32: { float v; std::memcpy(&v, p + i * 4, 4); *out = v; return true; } + case RAD_BF16: { uint32_t u = (uint32_t)((uint16_t)(p[i * 2] | (p[i * 2 + 1] << 8))) << 16; + float v; std::memcpy(&v, &u, 4); *out = v; return true; } + case RAD_F16: { uint16_t h = (uint16_t)(p[i * 2] | (p[i * 2 + 1] << 8)); + const uint32_t s = (uint32_t)(h & 0x8000u) << 16; + const int e = (h >> 10) & 0x1F; + const uint32_t m = h & 0x3FFu; + uint32_t u; + if (e == 0) u = s | (m ? ((uint32_t)(127 - 15 + 1) << 23) | (m << 13) : 0u); + else if (e == 31) u = s | 0x7F800000u | (m << 13); + else u = s | ((uint32_t)(e - 15 + 127) << 23) | (m << 13); + float v; std::memcpy(&v, &u, 4); *out = v; return true; } + case RAD_F8E4M3: *out = f8e4m3_to_f32(p[i]); return true; + case RAD_I8: *out = (double)(int8_t)p[i]; return true; + case RAD_U8: + case RAD_BOOL: *out = (double)p[i]; return true; + case RAD_I16: { int16_t v; std::memcpy(&v, p + i * 2, 2); *out = v; return true; } + case RAD_I32: { int32_t v; std::memcpy(&v, p + i * 4, 4); *out = v; return true; } + case RAD_U32: { uint32_t v; std::memcpy(&v, p + i * 4, 4); *out = v; return true; } + case RAD_I64: { int64_t v; std::memcpy(&v, p + i * 8, 8); *out = (double)v; return true; } + default: return false; + } +} + +double row_at(const uint8_t* p, uint32_t dt, int64_t base, int64_t k, int64_t n) { + double v = 0; + if (base + k < n) elem(p, dt, base + k, &v); + return v; +} + +std::string shape_str(const RadTensor* t) { + std::string s = "["; + for (uint32_t d = 0; d < t->rank; ++d) + s += fmt("%s%lld", d ? "," : "", (long long)t->shape[d]); + s += "]/["; + for (uint32_t d = 0; d < t->rank; ++d) + s += fmt("%s%lld", d ? "," : "", (long long)t->stride[d]); + return s + "]"; +} + +} /* namespace */ + +/* ------------------------------------------------------------------ open / close */ +void Ctx::oracle_open() { + /* REPEAT MODE IS THE SAME MACHINERY WITH THE SECOND SIDE SWAPPED, so it shares the arming, + * the op filter and the snapshot and differs only in what it runs and how it compares. Named + * separately because the two answer different questions: the oracle asks whether a kernel is + * RIGHT, this asks whether it is a FUNCTION. */ + const char* spec = std::getenv("RADIANCE_OP_REPEAT"); + const bool rep = spec && *spec; + if (!rep) spec = std::getenv("RADIANCE_OP_ORACLE"); + if (!spec || !*spec) return; + + oracle_ = new OracleState(); + oracle_->repeat = rep; + for (const char* s = spec; *s; ) { + const char* e = s; + while (*e && *e != ',') ++e; + if (e > s) oracle_->want.emplace_back(s, (size_t)(e - s)); + s = *e ? e + 1 : e; + } + auto geti = [](const char* k, int64_t d) { + const char* v = std::getenv(k); + return (v && *v) ? (int64_t)std::strtoll(v, nullptr, 10) : d; + }; + oracle_->budget = geti(rep ? "RADIANCE_OP_REPEAT_MAX" : "RADIANCE_OP_ORACLE_MAX", rep ? 1000000 : 32); + oracle_->maxbytes = geti("RADIANCE_OP_REPEAT_MAXBYTES", 8 << 20); + oracle_->maxopd = geti("RADIANCE_OP_ORACLE_MAXBYTES", 4LL << 30); + oracle_->from = geti(rep ? "RADIANCE_OP_REPEAT_FROM" : "RADIANCE_OP_ORACLE_FROM", 0); + oracle_->to = geti(rep ? "RADIANCE_OP_REPEAT_TO" : "RADIANCE_OP_ORACLE_TO", INT64_MAX); + if (const char* t = std::getenv("RADIANCE_OP_ORACLE_TOL")) oracle_->tol = std::strtod(t, nullptr); + + if (oracle_->repeat) { + RAD_WARN("op REPEAT armed for {%s}: issues [%lld,%lld], at most %lld checks, operands up " + "to %lld bytes. Every matching issue runs its DEVICE kernel TWICE on the same " + "bytes and byte-compares. A difference is a kernel that is not a function of its " + "inputs. This run is not a measurement of anything.", + spec, (long long)oracle_->from, (long long)oracle_->to, + (long long)oracle_->budget, (long long)oracle_->maxbytes); + return; + } + RAD_WARN("op oracle ARMED for {%s}: issues [%lld,%lld], at most %lld checks, tolerance %.3g, " + "operands up to %lld MiB. Every matching issue copies all its operands to the host " + "twice and runs the host kernel beside the device one -- this run is not a " + "measurement of anything.", + spec, (long long)oracle_->from, (long long)oracle_->to, + (long long)oracle_->budget, oracle_->tol, (long long)(oracle_->maxopd >> 20)); +} + +void Ctx::oracle_close() { + if (!oracle_) return; + if (oracle_->repeat) + RAD_WARN("op REPEAT: %lld issue(s) run twice, %lld of them ANSWERED DIFFERENTLY; %lld " + "more were NOT JUDGED because an operand was over the copy cap (raise " + "RADIANCE_OP_REPEAT_MAXBYTES to cover those)", + (long long)oracle_->checked, (long long)oracle_->differed, + (long long)oracle_->unchecked); + else + RAD_WARN("op oracle: %lld op(s) checked, %lld skipped for want of a host kernel", + (long long)oracle_->checked, (long long)oracle_->skipped_nohost); + delete oracle_; + oracle_ = nullptr; +} + +/* ------------------------------------------------------------------ the check */ +bool Ctx::oracle_arm(rad_op h) const { + OracleState& o = *oracle_; + if (o.budget <= 0) return false; + if (n_issues_ < o.from || n_issues_ > o.to) return false; + const std::string& name = plans_[h].info->op; + for (const std::string& w : o.want) + if (w == "*" || w == name) return true; + return false; +} + +/* ------------------------------------------------------------------ sizing the snapshot + * + * WHAT IS BEING SIZED IS NOT ALWAYS WHAT THE OPERAND POINTS AT, and a routed mixture is where the + * difference is total. A grouped GEMM's weight operand is a TABLE (Ctx::WeightTable): after + * placement a layer's experts are in different places, so the operand handed to the kernel is a + * device array of POINTERS with a zero leading stride, and `base + e*stride` describes only the + * all-in-VRAM case, which stops being true the moment anything is offloaded. + * + * Read as a plane that operand is n*8 bytes pretending to be N*K of weight. Copying it as one + * reads far past the pointer array, and the host kernel then dereferences DEVICE pointers -- so + * the largest weight in the model would be the one the instrument cannot be pointed at without + * reading out of bounds. What it gets instead is the STACKED form: every entry copied into one + * contiguous host buffer behind a non-zero leading stride, which is the other reading libref's + * expert_entry() already accepts and the one a fixture uses. + * + * A PLUGIN-PRIVATE DTYPE HAS NO BYTE COUNT IN THE CORE, by design -- a 4-bit expert plane is two + * elements to a byte and the core deliberately knows nothing about the packing (spec 4.2). The + * container does: the layout pass wrote the resolved kernel's own answer into WeightInfo, so an + * operand the core cannot size is sized from the weight it is bound to, and only an operand that + * is neither sizeable nor a weight is declined. */ +void Ctx::oracle_size(rad_op h, int n_opd) { + OracleState& o = *oracle_; + const OpInfo& oi = *plans_[h].info; + + /* The stored byte count of the weight at each operand position, from the layout pass. Every + * entry of a table maps to one position and they are proven identical at first issue, so the + * last writer and the first agree. */ + int64_t wb[MAX_OPERANDS] = {0}; + int wlaid[MAX_OPERANDS] = {0}; + if (program_) + for (size_t j = 0; j < oi.weights.size() && j < oi.weight_opd.size(); ++j) { + const rad_weight wh = oi.weights[j]; + const int k = (int)oi.weight_opd[j]; + if (!wh || (size_t)wh >= program_->weights.size()) continue; + if (k < 0 || k >= n_opd) continue; + wb[k] = program_->weights[(size_t)wh].stored_bytes; + wlaid[k] = program_->weights[(size_t)wh].layout_tag.empty() ? 0 : 1; + } + + for (int i = 0; i < n_opd; ++i) { + const RadTensor& t = tbuf_[i]; + /* A ZERO LEADING STRIDE IS THE MARKER. resolve_weight_table() prepends the expert axis + * that way precisely to say "this axis is not addressable by arithmetic". */ + o.tab[i] = (t.data && t.rank >= 2 && t.stride[0] == 0 && t.shape[0] > 0) ? t.shape[0] : 0; + const int64_t es = span_of(&t); /* one entry, or the whole plane when not a table */ + o.span[i] = o.tab[i] ? es * o.tab[i] : es; + o.ent[i] = es > 0 ? rad_dtype_bytes(t.dtype, es) : 0; + if (o.ent[i] <= 0 && es > 0) o.ent[i] = wb[i]; + /* A RE-LAID WEIGHT IS AS BIG AS THE CONTAINER SAYS, NOT AS BIG AS ITS DECLARED PLANE, and + * the two differ even where the dtype has a byte count. The fp8 lm_head pads each stored + * row to a 16-byte boundary and carries that row's block scales inside it, so the plane + * is 2608 bytes a row where n_embd * 1 says 2560 -- and the inverse, which checks the + * byte count it is handed against the stride it wrote, refuses a snapshot sized from the + * declared plane. The layout pass records the resolved kernel's own answer for exactly + * this; where a weight is stored re-laid, it wins. */ + if (wlaid[i] && wb[i] > 0) o.ent[i] = wb[i]; + o.ht[i] = t; + /* The stacked reading: the expert axis becomes addressable and its stride is one entry. */ + if (o.tab[i]) o.ht[i].stride[0] = es; + + /* ALIASED OPERANDS SHARE ONE HOST BUFFER. A residual add is issued {x, h} -> {x}: two + * of its three operands are the same device bytes, and giving each its own copy makes + * the host kernel write into a buffer the device kernel's own read-modify-write also + * wrote -- which reports the op as a mismatch of exactly the size of the addend, every + * time, on an op that is correct. The first operand with a given pointer owns the + * copy and the rest point into it, which is what the device sees. */ + o.alias[i] = i; + for (int j = 0; j < i; ++j) + if (t.data && tbuf_[j].data == t.data) { o.alias[i] = o.alias[j]; break; } + } +} + +/* Bytes the snapshot of operand `i` occupies, which for a table is every entry of it. */ +int64_t Ctx::oracle_opd_bytes(int i) const { + const OracleState& o = *oracle_; + if (o.span[i] <= 0 || o.ent[i] <= 0) return 0; + return o.tab[i] ? o.ent[i] * o.tab[i] : o.ent[i]; +} + +void Ctx::oracle_snap(int n_opd, bool post) { + OracleState& o = *oracle_; + std::vector>& into = post ? o.post : o.pre; + into.resize(MAX_OPERANDS); + std::vector ptr; + /* THE SECOND LANE IS DRAINED FIRST, AND THE ORDER IS THE WHOLE POINT. An architecture may + * issue on lane 1 -- the MoE shared expert does -- and the copies below go on `stream_`, which + * is not ordered against it. Draining lane 1 AFTER them leaves the copy racing the kernel + * that writes what it is copying, which is not a fix: the copy has already returned its bytes. + * + * Both snapshots need it and for different reasons. In `post` the race reads an OUTPUT before + * its kernel wrote it, and a correct kernel reports as having produced nothing. In `pre` it + * reads an INPUT before its producer wrote it, and then the two sides are not even given the + * same problem -- the host kernel gets a half-written operand, the device kernel gets the + * whole one, and the operand the oracle prints is an INPUT that disagrees with itself. The + * oracle already costs a host synchronisation per issue; one more stream is free. */ + if (lane1_) rad_stream_sync(lane1_); + for (int i = 0; i < n_opd; ++i) { + const RadTensor& t = tbuf_[i]; + if (o.alias[i] != i) continue; + const int64_t bytes = oracle_opd_bytes(i); + /* THE CAP IS A REPEAT-MODE THING ONLY. The oracle has to see every operand or its host + * kernel has nothing to read; the repeat re-launches the device kernel on the operands + * still in place, so an operand it declines to copy is simply one it cannot restore and + * will not compare -- which is right for a weight and would be wrong for an output. */ + if (!post) o.skip[i] = o.repeat && bytes > o.maxbytes; + if (o.skip[i]) { into[(size_t)i].clear(); continue; } + /* A SLOT KEEPS THE HIGH-WATER CAPACITY OF EVERY OPERAND THAT EVER LANDED IN IT, and on a + * large model that is not a rounding error: operand 2 of one op is a 170 MiB fused weight + * and operand 2 of the next is a few kilobytes, so thirty-two slots across `pre`, `post` + * and `logical` hold the sum of the largest thing each has ever seen -- on a container + * of well over a hundred GiB, enough for the host OOM killer to end a sweep part way + * through. Shrinking when the slot is grossly oversized bounds the footprint by the + * largest SINGLE issue instead of by the sum over the graph; the reallocation costs + * nothing against a synchronised copy. */ + into[(size_t)i].assign((size_t)bytes, 0); + if (into[(size_t)i].capacity() > (size_t)bytes * 2 + (1u << 20)) + into[(size_t)i].shrink_to_fit(); + if (bytes <= 0) continue; + if (!o.tab[i]) { rad_memcpy_async(into[(size_t)i].data(), t.data, bytes, stream_); continue; } + /* The entries are wherever placement put them, so their pointers come back first and the + * copies are issued against those. An entry may be device- or host-resident and the + * direction is inferred from the pointer, which is what makes one call serve both. */ + ptr.assign((size_t)o.tab[i], nullptr); + rad_memcpy_async(ptr.data(), t.data, o.tab[i] * (int64_t)sizeof(void*), stream_); + rad_stream_sync(stream_); + for (int64_t e = 0; e < o.tab[i]; ++e) + if (ptr[(size_t)e]) + rad_memcpy_async(into[(size_t)i].data() + e * o.ent[i], ptr[(size_t)e], + o.ent[i], stream_); + } + rad_stream_sync(stream_); + if (!post) + for (int i = 0; i < n_opd; ++i) + o.ht[i].data = o.span[i] > 0 ? (void*)o.pre[(size_t)o.alias[i]].data() : nullptr; +} + +/* ------------------------------------------------------------------ the stored layout + * + * THE HOST KERNEL READS A WEIGHT CANONICALLY AND THE ENGINE DOES NOT HOLD IT THAT WAY. + * + * A container holds each weight's encoding as canonical planes, and the kernel that reads it may + * rearrange them at load (spec §4.3): libr4d's fp8a8 GEMMs claim WMMA FRAGMENT ORDER, the same N*K + * bytes permuted so a wave's sixteen rows arrive in lane order off one coalesced load. libref + * declares no layout for anything and reads [N, K] row-major. Handing it the operand pointer + * unchanged therefore compares two readings of one permuted plane, which are uncorrelated tensors + * -- a relative error around 1.35 on every operand from element zero, on a kernel that is not + * wrong. + * + * So the stored bytes go back through the device row's own inverse to the canonical planes, and + * from those to the form the HOST row reads: a single plane converted element by element -- an + * expert's int4 codes as the integers the reference multiplies -- or a whole encoding decoded by + * the core's decoder, which is what a reference reading an lm_head of codes and scales together + * wants. Both sides then see the same values, expressed the way each of them reads. + * + * NO INVERSE MEANS NO CHECK, and it is a named skip rather than a tolerance: a comparison that + * cannot be made honestly is worse than one not made, because a page of false failures drowns the + * true ones. Returns false in that case, and the issue is not counted as checked. + * + * WHICH LOGICAL FORM, AND WHO SAYS SO. `opd_shape` describes the operand the kernel is HANDED -- + * for a relayed weight that is the stored form, which is the thing being inverted and cannot also + * be the answer. The form wanted here is the one the READER reads, so the host row is asked first + * and the device row is the fallback. libref publishes a shape for the whole conventional + * vocabulary, so an op inside docs/OPS.md is describable even when the kernel under test + * describes nothing. + * + * The extents come from the parameters AT THIS ISSUE, not from the weight's declaration: a + * tensor-parallel shard's op carries the per-rank N and K. */ +bool Ctx::oracle_unrelayout(rad_op h, const IssuePlan& hip, const IssuePlan& dip, int64_t seq, + int n_opd) { + OracleState& o = *oracle_; + const OpInfo& oi = *plans_[h].info; + for (int i = 0; i < n_opd; ++i) o.unlaid[i] = 0; + + const RadKernelInfo* ki = dip.row ? dip.row->info : nullptr; + if (!ki || !ki->layout || !program_) return true; /* every operand is read as it is */ + const RadKernelInfo* hk = hip.row ? hip.row->info : nullptr; + const RadShapeFn shape = hk && hk->opd_shape ? hk->opd_shape : ki->opd_shape; + + o.logical.resize(MAX_OPERANDS); + for (size_t j = 0; j < oi.weights.size() && j < oi.weight_opd.size(); ++j) { + const rad_weight wh = oi.weights[j]; + if (!wh || (size_t)wh >= program_->weights.size()) continue; + const WeightInfo& w = program_->weights[(size_t)wh]; + if (w.layout_tag.empty()) continue; /* stored as it is */ + const int i = oi.weight_opd[j]; + if (i < 0 || i >= n_opd || o.span[i] <= 0 || o.unlaid[i]) continue; + + if (!ki->unrelayout || !shape) { + RAD_WARN("oracle #%lld op '%s': NOT CHECKED. '%s' is stored as %s's '%s', and no %s " + "can be had for it -- so the reference would read a permuted plane row-major " + "and disagree with a kernel that is right.", + (long long)seq, oi.op.c_str(), w.name.c_str(), ki->name, + w.layout_tag.c_str(), ki->unrelayout ? "RadShapeFn" : "RadUnrelayoutFn"); + return false; + } + RadOpdDesc d{}; + if (shape(dip.args.p, dip.args.n_p, i, &d) != RAD_OK || d.rank == 0) { + RAD_WARN("oracle #%lld op '%s': NOT CHECKED. nothing could describe the logical form " + "of '%s' at this geometry, so there is nothing to invert its layout into.", + (long long)seq, oi.op.c_str(), w.name.c_str()); + return false; + } + RadTensor lg{}; + lg.dtype = d.dtype; + lg.rank = d.rank; + int64_t n = 1, acc = 1; + for (uint32_t k = 0; k < d.rank && k < RAD_MAX_RANK; ++k) { lg.shape[k] = d.shape[k]; n *= d.shape[k]; } + for (int k = (int)d.rank - 1; k >= 0; --k) { lg.stride[k] = acc; acc *= lg.shape[k]; } + const int64_t bytes = rad_dtype_bytes(lg.dtype, n); + if (bytes <= 0) return false; + /* A TABLE'S DESCRIPTION MUST BE THE STACKED PLANE. The two agree on every other axis, so + * a disagreement here is a description that answered for one expert where the operand + * carries the layer's whole set -- and inverting into it would write past the buffer. */ + if (o.tab[i] && (d.rank < 2 || lg.shape[0] != o.tab[i])) { + RAD_WARN("oracle #%lld op '%s': NOT CHECKED. '%s' is a table of %lld experts and the " + "logical form offered for it leads with %lld, so the two are not the same " + "tensor.", (long long)seq, oi.op.c_str(), w.name.c_str(), + (long long)o.tab[i], (long long)(d.rank ? lg.shape[0] : 0)); + return false; + } + o.logical[(size_t)i].assign((size_t)bytes, 0); + if (o.logical[(size_t)i].capacity() > (size_t)bytes * 2 + (1u << 20)) + o.logical[(size_t)i].shrink_to_fit(); + lg.data = o.logical[(size_t)i].data(); + + /* ONE CALL PER ENTRY FOR A TABLE. The hook answers for a weight, and an expert IS the + * weight -- the table is the engine's way of saying where the experts ended up, not a + * shape the plugin ever agreed to. So each entry's stored bytes are inverted on their own + * and land at their own offset in the stacked tensor. */ + const std::vector& src = o.pre[(size_t)o.alias[i]]; + const int64_t n_ent = o.tab[i] ? o.tab[i] : 1; + const int64_t ent_bytes = o.tab[i] ? o.ent[i] : (int64_t)src.size(); + const int64_t ent_n = n / n_ent; + std::vector> pl((size_t)w.n_sel); + RadTensor pt[RAD_ENC_MAX_PLANES]; + weight_planes(w, pt); + int rc = RAD_OK; + std::string why; + for (int64_t e = 0; e < n_ent && rc >= 0; ++e) { + for (int k = 0; k < w.n_sel; ++k) { + pl[(size_t)k].assign((size_t)(w.sel_rows[k] * + rad_enc_row_bytes(pt[k].dtype, w.sel_cols[k])), 0); + pt[k].data = pl[(size_t)k].data(); + } + rc = ki->unrelayout(dip.args.p, dip.args.n_p, i, &w.enc, w.sel, + src.data() + e * ent_bytes, ent_bytes, pt, w.n_sel); + if (rc < 0) break; + uint8_t* dst = (uint8_t*)lg.data + rad_dtype_bytes(lg.dtype, ent_n * e); + const void* pd[RAD_ENC_MAX_PLANES] = {}; + for (int k = 0; k < w.n_sel; ++k) pd[k] = pl[(size_t)k].data(); + rc = enc_selection_logical(w.enc, w.sel, w.n_sel, w.sel_rows, w.sel_cols, pd, + lg.dtype, ent_n, dst, &why); + } + if (rc < 0) { + /* THE TWO NUMBERS IT DISAGREED ABOUT. An inverse refuses on a shape far more often + * than on anything else, and "shape this kernel does not serve" without them says + * only that one of the two sides is wrong -- which is the whole question. */ + RAD_WARN("oracle #%lld op '%s': NOT CHECKED. %s could not invert its own layout for " + "'%s' (%s%s%s): %lld stored bytes into %lld %s elements, so the reference has " + "nothing it can read.", + (long long)seq, oi.op.c_str(), ki->name, w.name.c_str(), rad_strerror(rc), + why.empty() ? "" : ": ", why.c_str(), (long long)ent_bytes, (long long)ent_n, + rad_dtype_name(lg.dtype)); + return false; + } + o.ht[i] = lg; + o.unlaid[i] = 1; + } + return true; +} + + +void Ctx::oracle_run(rad_op h, const IssuePlan& hip, int64_t seq, int n_opd) { + OracleState& o = *oracle_; + const OpInfo& oi = *plans_[h].info; + + /* The host kernel writes into the PRE copy: same shapes, same strides, same parameters, and + * pointers that are the only thing about the call that differs from the device's. */ + RadArgs a = hip.args; + a.t = o.ht; + a.n_t = n_opd; + o.scratch.assign((size_t)(a.scratch_bytes > 0 ? a.scratch_bytes : 0), 0); + a.scratch = o.scratch.empty() ? nullptr : o.scratch.data(); + + const int rc = hip.launch(&a, nullptr); + if (rc < 0) { + /* RAD_E_UNSUPPORTED IS NOT A FINDING. It is the reference saying "not this contract" -- + * an op whose parameters name a form it does not implement, which `gdn_recurrent_update`'s + * two state layouts are the live example of. Reported as the coverage gap it is, because + * the alternative is a reader treating a declined comparison as a passed one. Any OTHER + * code is the reference refusing shapes it claims to serve, and that is about the engine's + * operands rather than about the oracle. */ + if (rc == RAD_E_UNSUPPORTED) + RAD_WARN("oracle #%lld op '%s': NOT CHECKED. the host kernel (%s) does not implement " + "what these parameters ask for {%s}, so there is no comparison to make.", + (long long)seq, oi.op.c_str(), + hip.row && hip.row->info ? hip.row->info->name : "?", oi.base.str().c_str()); + else { + /* AND THE SHAPES IT REFUSED, since that is what this line says the finding is about. + * An error name on its own leaves no way to tell an engine operand the reference + * genuinely cannot serve from a geometry it was handed wrongly, which is the whole + * thing a reader comes to this line for. */ + std::string sh; + for (int i = 0; i < n_opd; ++i) + if (o.ht[i].data) + sh += fmt("%s%d:%s", sh.empty() ? "" : " ", i, shape_str(&o.ht[i]).c_str()); + RAD_WARN("oracle #%lld op '%s': the host kernel (%s) REFUSED the engine's own operands " + "with %s. That is a finding about the shapes, not about the oracle: {%s} %s", + (long long)seq, oi.op.c_str(), + hip.row && hip.row->info ? hip.row->info->name : "?", rad_strerror(rc), + oi.base.str().c_str(), sh.c_str()); + } + return; + } + + /* Per operand: the largest disagreement, scaled by the device side's own magnitude. A pure + * input comes out at zero because neither side touched it, which is the check that the + * snapshot itself is sound. */ + std::string line; + bool bad = false; + for (int i = 0; i < n_opd; ++i) { + if (o.span[i] <= 0) continue; + /* AN INVERTED WEIGHT IS NOT COMPARED. `pre` holds the stored plane and `post` the device's + * copy of the same read-only bytes, so there is nothing here the two sides could disagree + * about -- what the host kernel actually read is the separate logical buffer, in a form + * neither of those two holds. Printed rather than dropped, so that a reader can see the + * operand was handled and know which shape the host side saw. */ + if (o.unlaid[i]) { + line += fmt(" opd%d~ %-6s %-22s read through %s's own inverse; not compared\n", + i, rad_dtype_name(o.ht[i].dtype), shape_str(&o.ht[i]).c_str(), + ip_kernel_name(h) ? ip_kernel_name(h) : "?"); + continue; + } + const uint32_t dt = o.ht[i].dtype; + const uint8_t* hp = o.pre[(size_t)o.alias[i]].data(); + const uint8_t* dp = o.post[(size_t)o.alias[i]].data(); + const int64_t n = o.span[i]; + + double worst = 0, scale = 0, hv = 0, dv = 0, sum = 0, hsum = 0; + int64_t at = -1, nbad = 0; + int64_t badix[4] = { -1, -1, -1, -1 }; + double x = 0, y = 0; + if (!elem(hp, dt, 0, &x)) { + const bool same = std::memcmp(hp, dp, o.pre[(size_t)o.alias[i]].size()) == 0; + line += fmt(" opd%d %-6s %s %s\n", i, rad_dtype_name(dt), + shape_str(&o.ht[i]).c_str(), same ? "bytes equal" : "BYTES DIFFER"); + bad = bad || !same; + continue; + } + /* ONE CODE STEP IN AN fp8 PLANE IS THE FORMAT, NOT A DISAGREEMENT. + * + * E4M3 has three mantissa bits, so the gap between neighbouring codes is between 1/16 and + * 1/8 of the value -- four to eight times the tolerance a comparison of continuous values + * is held to. Any difference at all in the bf16 the quantiser reads, down to a single ulp + * from a different summation order, moves an element that sits near a rounding boundary + * onto the next code, and the reported relative error is then a whole quantum on a kernel + * that is right -- typically a handful of elements in ten thousand, one code apart (host + * 176, device 192), on an fp8 output plane such as rmsnorm_quant_fp8's or hc_read's. + * + * So the two sides are compared in CODE space for these dtypes, where adjacent is a + * question with an exact answer: same sign bit, magnitude codes one apart. Those are + * COUNTED and reported and do not set the verdict; anything further apart is a real + * disagreement and is measured like any other. A kernel whose arithmetic is actually + * wrong does not land one code away on six elements in ten thousand. */ + const bool fp8 = (dt == RAD_F8E4M3 || dt == RAD_F8E5M2); + int64_t ulp1 = 0; + for (int64_t k = 0; k < n; ++k) { + if (!elem(hp, dt, k, &x) || !elem(dp, dt, k, &y)) break; + scale = std::max(scale, std::fabs(y)); + if (std::isfinite(y)) sum += y; + if (std::isfinite(x)) hsum += x; + if (fp8 && hp[k] != dp[k]) { + const int da = (int)(hp[k] & 0x7Fu) - (int)(dp[k] & 0x7Fu); + if (((hp[k] ^ dp[k]) & 0x80u) == 0 && (da == 1 || da == -1)) { ++ulp1; continue; } + } + const double d = std::fabs(x - y); + if (std::isnan(x) != std::isnan(y) || d > worst) { + worst = std::isnan(x) != std::isnan(y) ? INFINITY : d; + at = k; hv = x; dv = y; + } + /* The individually bad elements, not just the worst: WHERE they sit says whether a + * whole operand is wrong or one lane of it is, and those are different bugs. */ + if (d > 1e-30 && (std::isnan(x) != std::isnan(y) || d > o.tol * std::fabs(x))) { + if (nbad < 4) badix[nbad] = k; + ++nbad; + } + } + const double rel = worst / (scale > 0 ? scale : 1.0); + if (rel > o.tol) bad = true; + double f[4] = {0, 0, 0, 0}; + for (int64_t k = 0; k < 4 && k < n; ++k) elem(dp, dt, k, &f[k]); + /* PER-ROW SUMS, up to three rows. A whole-tensor sum is a weak fingerprint and the first + * four values only ever describe row 0, so between them they can say "token 0 is exactly + * right and the total is wrong" -- a statement about the OTHER tokens that neither column + * can localise. A row here is dim 0, which is the token for every activation the graph + * carries. */ + std::string rows; + if (o.ht[i].rank >= 2 && o.ht[i].shape[0] > 1 && o.ht[i].stride[0] > 0) { + const int64_t nr = o.ht[i].shape[0] < 3 ? o.ht[i].shape[0] : 3; + const int64_t w = o.ht[i].stride[0]; + for (int64_t r = 0; r < nr; ++r) { + double rs = 0; + for (int64_t k = r * w; k < (r + 1) * w && k < n; ++k) { + double y = 0; + if (!elem(dp, dt, k, &y)) break; + if (std::isfinite(y)) rs += y; + } + double t[3] = {0, 0, 0}; + const int64_t last = (r + 1) * w < n ? (r + 1) * w : n; + for (int j = 0; j < 3; ++j) + if (last - 3 + j >= r * w) elem(dp, dt, last - 3 + j, &t[j]); + /* HEAD AND TAIL OF EVERY ROW, which is exactly what llama.cpp's eval-callback + * prints -- three at each end and an ellipsis. A sum agrees between two vectors + * that are not the same vector, which is the shape these mismatches take. */ + rows += fmt("\n row%lld sum %.6g head [%.5g %.5g %.5g] tail [%.5g %.5g %.5g]", + (long long)r, rs, + row_at(dp, dt, r * w, 0, n), row_at(dp, dt, r * w, 1, n), + row_at(dp, dt, r * w, 2, n), t[0], t[1], t[2]); + } + } + /* WHERE the worst element is, and what each side said there. Without it a mismatch is a + * number: "rel 2 on a gate cumsum" cannot distinguish a whole tensor that is wrong from + * one padding lane that is, and those want different fixes. The index is flat over the + * operand, which is the same order the row sums above walk. */ + std::string at_s; + if (at >= 0 && rel > o.tol) { + at_s = fmt("\n worst at [%lld]: host %.9g device %.9g (diff %.4g)" + "\n %lld of %lld element(s) differ; host sum %.6g vs device sum %.6g" + "\n first bad at", + (long long)at, hv, dv, worst, (long long)nbad, (long long)n, hsum, sum); + for (int b = 0; b < 4 && badix[b] >= 0; ++b) at_s += fmt(" %lld", (long long)badix[b]); + } + /* The one-code-step count is PRINTED whether or not anything else disagreed. Silently + * absorbing them would make the operand look byte-equal, and a reader comparing two runs + * of the same build wants to see that six elements moved. */ + const std::string u1 = ulp1 ? fmt(" %lld at one fp8 code step", (long long)ulp1) + : std::string(); + line += fmt(" opd%d %-6s %-22s n=%-9lld amax %.4g sum %.6g [%.5g %.5g %.5g %.5g]%s" + " rel %.4g%s%s%s\n", + i, rad_dtype_name(dt), shape_str(&o.ht[i]).c_str(), (long long)n, scale, + sum, f[0], f[1], f[2], f[3], rows.c_str(), rel, u1.c_str(), + rel > o.tol ? " <-- MISMATCH" : "", at_s.c_str()); + } + + const char* dk = ip_kernel_name(h); + RAD_WARN("oracle #%lld op '%s' %s [device %s vs host %s] {%s}\n%s", + (long long)seq, oi.op.c_str(), bad ? "MISMATCH" : "agrees", + dk, hip.row && hip.row->info ? hip.row->info->name : "?", + oi.base.str().c_str(), line.c_str()); +} + +/* The device kernel's name for the report, looked up the same way abort_step does. */ +const char* Ctx::ip_kernel_name(rad_op h) const { + const OpPlan& p = plans_[h]; + const int dom = (int)op_domain_[h].load(std::memory_order_relaxed); + for (int b = 0; b < p.n_bands; ++b) { + const IssuePlan& ip = issue_table_[(size_t)p.plan_off + (size_t)b * RAD_N_DOMAINS + dom]; + if (ip.row && ip.row->info) return ip.row->info->name; + } + return "?"; +} + +/* The one entry point issue() calls. Returns the host plan to check against, or null. */ +/* ------------------------------------------------------------------ the repeat check */ +/* RUN THE DEVICE KERNEL A SECOND TIME ON THE BYTES THE FIRST ONE SAW, AND COMPARE. + * + * The oracle above asks whether a kernel agrees with libref. This asks a question no two-sided + * comparison can: whether the kernel agrees with ITSELF. A kernel with an unordered reduction, a + * workgroup that reads what another workgroup is writing, or a workspace it assumed was zeroed is + * CORRECT on the run the oracle happens to look at and wrong on the next one, and every + * instrument in this tree that runs an op once is blind to it. + * + * BYTE-EXACT AND NO TOLERANCE, deliberately. "Within 2%" is the right question for an + * implementation and the wrong one here: the same kernel on the same bytes has no licence to move + * at all, and a difference in the last mantissa bit is the finding, because greedy decoding + * amplifies it into a different token a few hundred steps later. + * + * WHAT IT CANNOT SEE. A race between the two ranks of a tensor-parallel step: both Ctxs walk the + * same graph and both re-launch, so a collective still meets itself and does not deadlock, but + * what the second launch measures is the pair re-running together rather than either one alone. + * And a kernel whose output depends on a buffer this declined to restore -- see the cap. */ +void Ctx::oracle_repeat(rad_op h, const IssuePlan& dip, int64_t seq, int n_opd) { + OracleState& o = *oracle_; + + /* AN OPERAND THIS COULD NOT COPY MAKES THE WHOLE ISSUE UNJUDGEABLE, and saying so is the + * difference between an instrument and a rumour. The cap exists for read-only weights, but + * nothing here knows that an operand IS a weight -- and a GDN recurrent state is both an input + * and an output and is far over the default cap. Left unrestored it hands the second launch a + * state the first one already advanced, and every GDN issue in the model then reports as + * non-deterministic when what actually happened is that it was asked a different question. + * Raise RADIANCE_OP_REPEAT_MAXBYTES to check those ops; do not guess about them. */ + for (int i = 0; i < n_opd; ++i) + if (o.skip[i]) { ++o.unchecked; return; } + + /* The first result, before anything is put back. oracle_snap writes `post`, so it is moved + * aside rather than copied: the second launch needs the same destination. */ + oracle_snap(n_opd, true); + std::vector> first; + first.swap(o.post); + + /* PUT BACK ONLY WHAT THE KERNEL ACTUALLY CHANGED, and decide that by comparing rather than by + * believing the schema. An op issued {x, h} -> {x} has already overwritten one of its own + * inputs, so without a restore the second launch is not given the same problem and every + * in-place op in the graph reports as non-deterministic. + * + * Restoring everything SEGFAULTS instead: a small weight is a perfectly ordinary operand under + * the size cap, and a weight on Tier::Mapped is the container's read-only mmap. A kernel never + * writes an operand it only reads, so "changed" is both the safe test and the cheap one. + * + * A WEIGHT TABLE IS NEVER RESTORED WHATEVER THE COMPARISON SAYS. Its snapshot is the STACKED + * plane behind an array of pointers (oracle_size), so a byte-for-byte write back would put + * gigabytes of expert weight over a few kilobytes of pointers. No op writes one, which is + * why the comparison alone is enough; if one ever did, a write back would take every weight + * in the graph off its address. */ + bool wrote[MAX_OPERANDS] = {false}; + for (int i = 0; i < n_opd; ++i) { + if (o.alias[i] != i || o.skip[i] || o.span[i] <= 0 || o.tab[i]) continue; + const std::vector& A = o.pre[(size_t)i]; + const std::vector& B = first[(size_t)i]; + if (A.empty() || A.size() != B.size()) continue; + if (std::memcmp(A.data(), B.data(), A.size()) == 0) continue; + wrote[i] = true; + if (tbuf_[i].data) rad_memcpy_async(tbuf_[i].data, A.data(), A.size(), stream_); + } + rad_stream_sync(stream_); + + /* THE SAME PLAN, THE SAME ARGS, THE SAME STREAM. dip.args.t still points at tbuf_ -- the + * device pointers -- because the oracle's rebinding only ever touched its own `ht`. */ + RadArgs a = dip.args; + a.n_t = n_opd; + const int rc = dip.launch(&a, cur_stream()); + if (rc < 0) { + RAD_WARN("repeat #%lld op '%s': the second launch was REFUSED with %s, so this issue says " + "nothing about determinism", (long long)seq, plans_[h].info->op.c_str(), + rad_strerror(rc)); + return; + } + oracle_snap(n_opd, true); + + std::string line; + for (int i = 0; i < n_opd; ++i) { + /* ONLY THE OPERANDS THE KERNEL WROTE. One it merely read is equal by construction, and + * saying so for every input on every issue buries the finding. */ + if (!wrote[i]) continue; + const std::vector& A = first[(size_t)i]; + const std::vector& B = o.post[(size_t)i]; + if (A.size() != B.size() || A.empty()) continue; + if (std::memcmp(A.data(), B.data(), A.size()) == 0) continue; + + /* WHICH ELEMENTS AND BY HOW MUCH. One lane apart at the last bit and a whole tensor of + * garbage are both "BYTES DIFFER", and they are different bugs: the first is a reduction + * order, the second is a read of memory another workgroup owns. */ + const uint32_t dt = o.ht[i].dtype; + const int64_t n = o.span[i]; + int64_t nbad = 0, at = -1; + double worst = 0, av = 0, bv = 0, scale = 0; + for (int64_t k = 0; k < n; ++k) { + double x = 0, y = 0; + if (!elem(A.data(), dt, k, &x) || !elem(B.data(), dt, k, &y)) { nbad = -1; break; } + if (x == y) continue; + ++nbad; + const double d = std::fabs(x - y); + if (d > worst) { worst = d; at = k; av = x; bv = y; } + scale = std::max(scale, std::fabs(y)); + } + if (nbad < 0) + line += fmt(" opd%d %-6s %s BYTES DIFFER (dtype not scalar)\n", i, + rad_dtype_name(dt), shape_str(&o.ht[i]).c_str()); + else + line += fmt(" opd%d %-6s %s %lld of %lld element(s) differ; worst at [%lld] " + "run1 %.9g run2 %.9g (diff %.4g, rel %.3g)\n", + i, rad_dtype_name(dt), shape_str(&o.ht[i]).c_str(), + (long long)nbad, (long long)n, (long long)at, av, bv, worst, + worst / (scale > 0 ? scale : 1.0)); + } + if (line.empty()) return; + ++o.differed; + RAD_ERR("REPEAT #%lld op '%s' (kernel %s) IS NOT A FUNCTION OF ITS INPUTS: two launches on the " + "same bytes disagreed.\n%s", (long long)seq, plans_[h].info->op.c_str(), + ip_kernel_name(h) ? ip_kernel_name(h) : "?", line.c_str()); +} + +const IssuePlan* Ctx::oracle_before(rad_op h, int band, int n_opd) { + if (!oracle_ || !oracle_arm(h)) return nullptr; + oracle_size(h, n_opd); + if (oracle_->repeat) { + for (int i = 0; i < n_opd; ++i) + if (tbuf_[i].data && oracle_opd_bytes(i) <= 0) return nullptr; + oracle_snap(n_opd, false); + /* REPEAT MODE NEEDS NO HOST KERNEL, and the issue path carries this pointer back only to + * say "armed". oracle_after re-launches the DEVICE plan it is handed instead. */ + static const IssuePlan kRepeatArmed{}; + return &kRepeatArmed; + } + /* NOT GATED ON THE DEVICE DOMAIN. Under RADIANCE_HOST_DOMAIN the launch IS the host kernel, + * so the comparison is host against host and agrees by construction -- but the per-operand + * lines are still the only ordered trace of what the graph computed, and diffing those + * against another engine's is what the whole-model reference exists for. */ + const OpPlan& p = plans_[h]; + const IssuePlan& hip = + issue_table_[(size_t)p.plan_off + (size_t)band * RAD_N_DOMAINS + RAD_DOMAIN_HOST]; + if (!hip.launch) { + ++oracle_->skipped_nohost; + if (!oracle_->said_nohost) { + oracle_->said_nohost = true; + RAD_WARN("oracle: op '%s' has no host kernel in this band, so it cannot be checked. " + "A library with host kernels -- a reference one, or the host library -- " + "must be on the kernel search path for the oracle to see anything.", plans_[h].info->op.c_str()); + } + return nullptr; + } + /* AN OPERAND WITH NO BYTE COUNT IS A NAMED SKIP, not a silent one. The count is missing when + * the dtype is plugin-private and the operand is not a weight the layout pass sized -- a + * packed plane the core is not meant to understand (spec 4.2). Dropping the whole issue + * without saying so would report a routed model's expert GEMM as "0 checked" beside a page of + * agreements, which reads as nothing to check rather than as a gap. */ + for (int i = 0; i < n_opd; ++i) { + if (!tbuf_[i].data || oracle_opd_bytes(i) > 0) continue; + RAD_WARN("oracle #%lld op '%s': NOT CHECKED. operand %d is %s and the core cannot size " + "it -- a plugin-private dtype is the plugin's to measure, and nothing bound " + "this operand to a weight whose stored size the container records.", + (long long)n_issues_, plans_[h].info->op.c_str(), i, + rad_dtype_name(tbuf_[i].dtype)); + return nullptr; + } + /* AND AN OPERAND THE HOST CANNOT HOLD IS A NAMED SKIP TOO. The snapshot is two host copies + * of every operand and a third for a weight stored re-laid, so an operand of tens of + * gigabytes is not a slow check -- it is the process being killed with nothing reported, and + * no reason in the log because there is no chance to write one. A 47 GiB n-gram table read + * at decode is such an operand. */ + for (int i = 0; i < n_opd; ++i) { + if (!tbuf_[i].data || oracle_->alias[i] != i) continue; + const int64_t b = oracle_opd_bytes(i); + if (b <= oracle_->maxopd) continue; + const OpInfo& oi = *plans_[h].info; + const char* wn = nullptr; + if (program_) + for (size_t j = 0; j < oi.weights.size() && j < oi.weight_opd.size(); ++j) + if ((int)oi.weight_opd[j] == i && oi.weights[j] + && (size_t)oi.weights[j] < program_->weights.size()) + wn = program_->weights[(size_t)oi.weights[j]].name.c_str(); + RAD_WARN("oracle #%lld op '%s': NOT CHECKED. operand %d%s%s%s is %lld MiB against a cap of " + "%lld MiB, and two host copies of it would end the run instead of reporting on " + "it. RADIANCE_OP_ORACLE_MAXBYTES raises the cap.", + (long long)n_issues_, oi.op.c_str(), i, wn ? " ('" : "", wn ? wn : "", + wn ? "')" : "", (long long)(b >> 20), (long long)(oracle_->maxopd >> 20)); + return nullptr; + } + oracle_snap(n_opd, false); + return &hip; +} + +void Ctx::oracle_after(rad_op h, const IssuePlan& hip, const IssuePlan& dip, int n_opd) { + if (oracle_->repeat) { + oracle_repeat(h, dip, n_issues_, n_opd); + --oracle_->budget; + ++oracle_->checked; + return; + } + oracle_snap(n_opd, true); + /* The pre snapshot's tensors still point into `pre`, which oracle_snap(false) bound -- except + * for a weight the device row stores re-laid, which this repoints at its own inverse. A row + * that cannot be inverted is not checked at all, and not counted as checked either. */ + if (!oracle_unrelayout(h, hip, dip, n_issues_, n_opd)) return; + oracle_run(h, hip, n_issues_, n_opd); + --oracle_->budget; + ++oracle_->checked; +} + +} /* namespace rad */ diff --git a/core/runtime/rank_barrier.cpp b/core/runtime/rank_barrier.cpp new file mode 100644 index 00000000..41b01d73 --- /dev/null +++ b/core/runtime/rank_barrier.cpp @@ -0,0 +1,34 @@ +/* rank_barrier.cpp -- see rank_barrier.h for why this is a condvar and not an IPC handshake. */ +#include "rank_barrier.h" + +namespace rad { + +void RankBarrier::arrive_and_wait() { + std::unique_lock lk(m_); + if (aborted_) return; + + const uint64_t my_gen = gen_; + if (++waiting_ == n_) { + /* Last one in flips the generation and releases the rest. The counter is reset here rather + * than by the wakers, so a rank that re-enters immediately observes a generation it has + * not seen and blocks instead of racing through. */ + waiting_ = 0; + ++gen_; + lk.unlock(); + cv_.notify_all(); + return; + } + cv_.wait(lk, [&] { return aborted_ || gen_ != my_gen; }); +} + +void RankBarrier::abort() { + { + std::lock_guard lk(m_); + aborted_ = true; + waiting_ = 0; + ++gen_; + } + cv_.notify_all(); +} + +} /* namespace rad */ diff --git a/core/runtime/rank_barrier.h b/core/runtime/rank_barrier.h new file mode 100644 index 00000000..fb4a041a --- /dev/null +++ b/core/runtime/rank_barrier.h @@ -0,0 +1,54 @@ +/* rank_barrier.h -- the release point for the tensor-parallel rank threads. + * + * WHY THIS IS NOT IPC. Radiance is one process. One thread per rank, each owning one device + * (spec §1). The ranks therefore share an address space, so the step batch is shared BY POINTER + * rather than broadcast: there is nothing to serialise, no shared-memory segment to map, no file + * descriptor, no pickling, and no handshake protocol that can get out of step with itself. All + * that is left for the barrier to do is establish happens-before between the scheduler's release + * and each rank's first rad_issue, and between the ranks' last issue and the scheduler's next + * batch build. + * + * A futex round trip through a condvar is ~1-2 us on this class of machine. The multiprocessing + * equivalent -- serialise the batch, write it down a pipe, wake N processes, have each one + * deserialise it -- is tens of microseconds per step before any work happens, and it is most of + * what a Python engine's multiprocessing budget actually buys. That difference is the reason §1 + * is written the way it is, and this class is the whole of the cost on our side. + * + * Sense reversal, not a counter reset, so a fast rank that comes back round for the next step + * cannot slip through the barrier its slower peers have not left yet. + */ +#pragma once +#include "../rad_core.h" + +#include +#include + +namespace rad { + +class RankBarrier { +public: + explicit RankBarrier(int n_ranks) : n_(n_ranks < 1 ? 1 : n_ranks), waiting_(0), gen_(0) {} + + RankBarrier(const RankBarrier&) = delete; + RankBarrier& operator=(const RankBarrier&) = delete; + + void arrive_and_wait(); + + /* Release everyone regardless of how many have arrived, and refuse every later arrival. The + * engine calls this on shutdown and on a device fault: a rank that has already exited must not + * leave its peers parked on a barrier that can no longer be completed (spec §17 -- a device + * fault is not recoverable in-process, and the engine exits rather than serving from a wedged + * queue, which it cannot do while a thread is blocked here). */ + void abort(); + + +private: + std::mutex m_; + std::condition_variable cv_; + int n_; + int waiting_; + uint64_t gen_; + bool aborted_ = false; +}; + +} /* namespace rad */ diff --git a/core/runtime/residency.h b/core/runtime/residency.h new file mode 100644 index 00000000..bd734312 --- /dev/null +++ b/core/runtime/residency.h @@ -0,0 +1,74 @@ +/* residency.h -- the seam the placement component plugs into. + * + * The run phase takes weight HANDLES, never pointers (spec §3.2). It resolves a handle to a + * pointer at issue time, which is the only reason the mover is allowed to relocate a weight while + * the model is serving. This header is the whole of the contract between the two: the run phase + * asks a question that never blocks, and the placement component answers it out of a table it + * owns. + * + * The degenerate case matters as much as the interesting one. In the all-in-VRAM deployment the + * planner assigned everything to tier 0 and the mover never runs, so no ResidencyTable is + * installed at all and the lookup collapses to WeightInfo::ptr -- a pointer the run phase already + * baked into its per-weight tensor template. There is no virtual call, no branch on a table entry, + * and nothing to pay for a feature that deployment is not using. + */ +#pragma once +#include "../rad_core.h" + +#include + +namespace rad { + +/* Where a weight's bytes are RIGHT NOW, and whether they have arrived. + * + * `ready` is the mover's event. Null means resident and settled: nothing to wait on, which is the + * common case even under expert offload because a hot expert stays put for many steps. Non-null + * means a transfer into `ptr` is in flight and the compute stream must be ordered behind it -- a + * STREAM wait, never a host sync, which is what lets placement be dynamic without serialising the + * step (spec §5.4). + * + * `generation` is what makes that wait cheap, and it is a contract the mover has to keep: it MUST + * be bumped whenever a new transfer into this slot begins. The run phase memoises "the compute + * stream has already been made to wait on generation g of weight w" and skips the wait every time + * afterwards. That is sound because a stream wait orders everything issued after it, so one wait + * per generation is sufficient and per-issue waits are pure cost -- at 64 layers and eight experts + * a step they would be thousands of runtime calls buying nothing. A mover that reuses an event + * without bumping the generation silently loses the ordering, and the symptom is garbage output + * three layers later with no way to bisect it. + */ +struct WeightSlot { + void* ptr; + RadEvent ready; + uint32_t generation; +}; + +class ResidencyTable { +public: + virtual ~ResidencyTable() = default; + + /* NEVER blocks. Not "usually does not block" -- this is called once per weight operand per + * issue, inside the step, and a lock here would serialise the mover against compute, which is + * the exact failure this design exists to avoid. Returning null means "I have nothing for this + * handle" and the run phase falls back to WeightInfo::ptr. */ + virtual const WeightSlot* lookup(rad_weight) const = 0; + + /* A count that changes whenever any slot's pointer, event or generation does. Everything + * lookup() returns is a function of it, so a caller that resolved a run of weights at one + * epoch may reuse that answer for as long as the epoch stands -- which is what keeps a routed + * layer's expert table from being walked, entry by entry, at every issue. */ + virtual uint64_t epoch() const = 0; + + /* THE SLOTS WHOSE POINTER OR EVENT CHANGED since the run phase last cleared the list, each + * named once. A routed layer's weight table holds its whole expert set and a step moves a + * handful of experts, so the run phase updates the entries named here rather than resolving + * every entry of every table whenever the epoch moves -- which, with experts moving on most + * steps, would be every entry of every table on most steps. + * + * One reader: the run phase of the rank this table belongs to, on the thread that also drives + * the writers, so neither call races the other. A slot that only SETTLED -- its transfer + * landed, the pointer stayed -- is not named, because nothing a reader holds becomes wrong. */ + virtual const std::vector& changes() const = 0; + virtual void clear_changes() = 0; +}; + +} /* namespace rad */ diff --git a/core/runtime/stager.h b/core/runtime/stager.h new file mode 100644 index 00000000..0722281d --- /dev/null +++ b/core/runtime/stager.h @@ -0,0 +1,87 @@ +/* stager.h -- the seam a step-time weight stager plugs into. + * + * The run phase resolves weights through the residency table (runtime/residency.h), and the mover + * changes that table between steps. A stager changes it WITHIN a step: it copies a weight that + * lives off the card into VRAM ahead of the op that reads it and publishes the copy for that op, + * then publishes the host address again once the op is behind it. The run phase does not know what + * is staged or why; it calls the stager around the ops of a pass it armed for and re-reads the + * residency table when the stager says it changed it. + * + * A PASS THE STAGER ARMS FOR IS ISSUED LIVE, never recorded or played from a tape: a tape replays + * the packets of the pass it recorded and not the host work between them, and the copies and + * publishes here are exactly that host work. + */ +#pragma once +#include "../rad_core.h" +#include "rad_device.h" + +namespace rad { + +class OpStager { +public: + virtual ~OpStager() = default; + + /* The pass is about to be issued: whether the stager takes part in it. */ + virtual bool begin_pass(const RadBatch* b) = 0; + + /* Before op `h` is issued on stream `s`. `*resync` is set when the residency table changed, + * so the run phase brings the op's weight tables up to date before resolving them. */ + virtual int before_op(rad_op h, RadStream s, bool* resync) = 0; + + /* After op `h` was issued on stream `s`: the point a staged weight's last reader is behind. */ + virtual int after_op(rad_op h, RadStream s) = 0; + + /* The pass has been issued, on `s`: nothing the stager published may outlive it. */ + virtual int end_pass(RadStream s) = 0; +}; + +/* TWO STAGERS ON ONE PASS, each called only on the passes it armed for. A stager that declined a + * pass is not handed its ops: one that arms only for large passes -- because its buffers are lent + * out the rest of the time -- must not stage into memory it does not own because another stager + * armed. The order is fixed, so the copies and stream waits each issues land in the same order on + * every pass. */ +class StagerChain final : public OpStager { +public: + void set(OpStager* a, OpStager* b) { s_[0] = a; s_[1] = b; } + + bool begin_pass(const RadBatch* b) override { + bool any = false; + for (int i = 0; i < 2; ++i) { + on_[i] = s_[i] != nullptr && s_[i]->begin_pass(b); + any = any || on_[i]; + } + return any; + } + int before_op(rad_op h, RadStream s, bool* resync) override { + *resync = false; + for (int i = 0; i < 2; ++i) { + if (!on_[i]) continue; + bool r = false; + const int rc = s_[i]->before_op(h, s, &r); + if (rc < 0) return rc; + *resync = *resync || r; + } + return RAD_OK; + } + int after_op(rad_op h, RadStream s) override { + for (int i = 0; i < 2; ++i) + if (on_[i]) { const int rc = s_[i]->after_op(h, s); if (rc < 0) return rc; } + return RAD_OK; + } + int end_pass(RadStream s) override { + int rc = RAD_OK; + for (int i = 0; i < 2; ++i) { + if (!on_[i]) continue; + const int r = s_[i]->end_pass(s); + if (r < 0 && rc >= 0) rc = r; + on_[i] = false; + } + return rc; + } + +private: + OpStager* s_[2] = { nullptr, nullptr }; + bool on_[2] = { false, false }; +}; + +} /* namespace rad */ diff --git a/core/runtime/tierexec.cpp b/core/runtime/tierexec.cpp new file mode 100644 index 00000000..72c1903d --- /dev/null +++ b/core/runtime/tierexec.cpp @@ -0,0 +1,772 @@ +#include "runtime/tierexec.h" + +#include "mem/sstier.h" +#include "rad_internal.h" + +#include +#include +#include + +namespace rad { + +TierExec::~TierExec() { close(); } + +/* The two ops are resolved ONCE, at configure, and at the width they will actually be called at. + * `n` is the fragment in bytes and it is a per-group constant, so nothing here re-resolves on the + * maintenance path -- a selector call between steps would be affordable and is still the wrong + * shape: the kernel that serves a transfer must not be able to change underneath a half-finished + * batch. */ +int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers, SSDTier* disk, + const std::vector& groups, int max_batch, int64_t max_copy, + int64_t max_chain, bool leader, int device, int64_t slot_off, + int64_t ck_slot_off, RadStream shared) { + close(); + if (!reg || !kv || !tiers || groups.empty() || max_batch <= 0 || max_copy <= 0 || + max_chain <= 0) + return RAD_E_INVAL; + reg_ = reg; kv_ = kv; tiers_ = tiers; disk_ = disk; leader_ = leader; device_ = device; + max_batch_ = max_batch; max_copy_ = max_copy; max_chain_ = max_chain; + slot_off_ = slot_off; + slot_bytes_ = tiers->entry_bytes(); + ck_bytes_ = kv->checkpoint_bytes(); + ck_slot_bytes_ = tiers->ckpt_bytes(); + ck_slot_off_ = ck_slot_off; + shared_ = shared; + RAD_TRY(rad_dev_set(device_)); + + int64_t off = 0; + for (int32_t g : groups) { + const KVGroupPlan* p = kv->plan(g); + if (!p || !p->paged()) continue; + GroupInfo gi; + gi.g = g; + gi.n_layers = p->n_layers; + gi.frag = p->layer_bytes_per_block(); + gi.layer_stride = p->layer_stride(); + gi.n_blocks = p->n_blocks; + gi.base = p->base; + gi.off = off; + /* THE FRAGMENT WIDTH IS THE CONSTRAINT THE KERNEL IS PICKED ON. libr4d's byte-row pair + * takes n as a multiple of 4; a geometry that does not satisfy it resolves to nothing + * here rather than failing at launch inside a batch. */ + Geometry q; + q.set_s("dtype", "u8"); + q.set_i("n", gi.frag); + q.set_i("M", max_batch); + gi.gather = reg->resolve("gather_rows", q, RAD_DOMAIN_DEVICE); + gi.scatter = reg->resolve("scatter_rows", q, RAD_DOMAIN_DEVICE); + if (!gi.gather || !gi.scatter) { + RAD_WARN("kv tiers: no device gather/scatter for group %d at a %lld-byte fragment, " + "so a finished conversation cannot leave VRAM. The tiers are off.", + (int)g, (long long)gi.frag); + close(); + return RAD_E_UNSUPPORTED; + } + off += gi.n_layers * gi.frag; + gi_.push_back(gi); + } + if (gi_.empty()) return RAD_E_UNSUPPORTED; + entry_bytes_ = off; + + /* NOTHING IS BUILT ON THE DEVICE HERE -- see device_init(). A tier that is configured but has + * no job to run must cost the step nothing, and on this engine that is not a figure of speech: + * building the staging buffer and the stream at bringup costs 13.3 ms of a 20.5 ms decode step + * on a two-card R9700 Flash-Next server, whether or not a single byte ever moves. */ + verify_ = leader && std::getenv("RADIANCE_DEBUG_TIER_VERIFY") != nullptr; + + char buf[320]; + std::snprintf(buf, sizeof buf, + "kv tier transfer: %zu paged group(s), %s an entry, batches of %d through " + "gather_rows/scatter_rows at u8%s%s", + gi_.size(), humanb(entry_bytes_).c_str(), max_batch_, + ck_bytes_ > 0 ? "; linear state as one contiguous copy of " : "", + ck_bytes_ > 0 ? humanb(ck_bytes_).c_str() : ""); + report_ = buf; + enabled_ = true; + return RAD_OK; +} + +void TierExec::close() { + /* Nothing may still be reading the buffers about to be freed. */ + if (stream_) (void)rad_stream_sync(stream_); + if (stream_ && own_stream_) rad_stream_destroy(stream_); + stream_ = nullptr; shared_ = nullptr; own_stream_ = false; + if (stage_) { rad_dev_free(stage_, RAD_MEM_DEVICE); stage_ = nullptr; } + if (idx_dev_) { rad_dev_free(idx_dev_, RAD_MEM_DEVICE); idx_dev_ = nullptr; } + if (idx_host_) { rad_dev_free(idx_host_, RAD_MEM_HOST_PINNED); idx_host_ = nullptr; } + for (int i = 0; i < kRing; ++i) { + if (ring_ev_[i]) rad_event_destroy(ring_ev_[i]); + ring_ev_[i] = nullptr; + ring_used_[i] = false; + } + if (ev_compute_) { rad_event_destroy(ev_compute_); ev_compute_ = nullptr; } + if (ev_copy_) { rad_event_destroy(ev_copy_); ev_copy_ = nullptr; } + if (ev_restore_) { rad_event_destroy(ev_restore_); ev_restore_ = nullptr; } + copy_out_ = false; + gi_.clear(); + order_.clear(); + verify_pending_.clear(); + entry_bytes_ = 0; + ck_bytes_ = ck_slot_bytes_ = ck_slot_off_ = 0; + enabled_ = false; + leader_ = false; + reg_ = nullptr; kv_ = nullptr; tiers_ = nullptr; disk_ = nullptr; + report_.clear(); +} + +/* THE DEVICE SIDE, BUILT ON FIRST USE AND NOT BEFORE. + * + * Ctx::lane_init() makes the same argument for the second compute lane: a stream is cheap + * enough that its cost hides inside the run-to-run spread of a warming part, so the only honest + * way to claim the lane costs nothing when unused is to not build it. The tiers follow the same + * rule, and here the cost is not small enough to hide in anything. Decode step time with the + * device side built at bringup, on a two-card R9700 Flash-Next server at 200K context: + * + * no tiers 20.54 ms/step collect 14.66 + * tiers on, 512 MiB host arena, no disk 33.94 ms/step collect 26.78 + * tiers on, idle threshold a day -- NOTHING EVER MOVED 33.88 ms/step collect 26.66 + * + * In the third line not one byte crosses the link, and the step is still 65% longer. The cost is + * in `collect` -- device time -- and a configured tier that has nothing to do pays it on every + * step. It is not the transfers, not the pinned host arena (512 MiB costs exactly what 12 GiB + * does) and not the VRAM the staging takes (with no tiers and --gpu-headroom-mib lowered to leave + * the same 17 MiB free, the step runs at full speed). + * + * So the device side is built when the first job needs it, and a server whose conversations never + * finish pays nothing for the tiers. */ +int TierExec::device_init() { + if (stream_) return RAD_OK; + RAD_TRY(rad_dev_set(device_)); + const int64_t ng = (int64_t)gi_.size(); + copy_idx_ = max_copy_; + chain_idx_ = max_chain_; + const int64_t idx_n = ng * (copy_idx_ + (int64_t)kRing * chain_idx_); + stage_ = rad_dev_alloc((int64_t)max_batch_ * entry_bytes_, RAD_MEM_DEVICE); + idx_dev_ = (int32_t*)rad_dev_alloc(idx_n * (int64_t)sizeof(int32_t), RAD_MEM_DEVICE); + idx_host_ = (int32_t*)rad_dev_alloc(idx_n * (int64_t)sizeof(int32_t), RAD_MEM_HOST_PINNED); + bool ev = rad_event_create(&ev_compute_) == RAD_OK && rad_event_create(&ev_copy_) == RAD_OK && + rad_event_create(&ev_restore_) == RAD_OK; + for (int i = 0; i < kRing && ev; ++i) ev = rad_event_create(&ring_ev_[i]) == RAD_OK; + auto undo = [&] { + if (stage_) { rad_dev_free(stage_, RAD_MEM_DEVICE); stage_ = nullptr; } + if (idx_dev_) { rad_dev_free(idx_dev_, RAD_MEM_DEVICE); idx_dev_ = nullptr; } + if (idx_host_) { rad_dev_free(idx_host_, RAD_MEM_HOST_PINNED); idx_host_ = nullptr; } + for (int i = 0; i < kRing; ++i) { if (ring_ev_[i]) rad_event_destroy(ring_ev_[i]); ring_ev_[i] = nullptr; } + if (ev_compute_) { rad_event_destroy(ev_compute_); ev_compute_ = nullptr; } + if (ev_copy_) { rad_event_destroy(ev_copy_); ev_copy_ = nullptr; } + if (ev_restore_) { rad_event_destroy(ev_restore_); ev_restore_ = nullptr; } + }; + if (!stage_ || !idx_dev_ || !idx_host_ || !ev) { undo(); return RAD_E_NOMEM; } + /* THE MOVER'S STREAM IF THERE IS ONE, AND A NEW ONE ONLY IF THERE IS NOT. Both move bytes + * nobody is waiting for, so one maintenance stream a rank serves both -- and the fourth + * hardware queue a second one would claim costs about 13 ms a decode step (see + * device_init). Never the step's own stream: a copy out would then be a dependency of the + * next token. */ + if (shared_) { + stream_ = shared_; + own_stream_ = false; + } else if (rad_stream_create(&stream_, /*high_priority=*/0) == RAD_OK) { + own_stream_ = true; + } else { + stream_ = nullptr; + undo(); + return RAD_E_DEVICE; + } + return RAD_OK; +} + +int64_t tier_entry_bytes(const KVManager& kv, const std::vector& groups) { + int64_t n = 0; + for (int32_t g : groups) { + const KVGroupPlan* p = kv.plan(g); + if (p && p->paged()) n += p->bytes_per_block; + } + return n; +} + +/* One (group, layer) launch. `stage_base` is the first entry's staging slot; the rows this call + * writes (or reads) are at a stride of entry_bytes_ from it, which is what puts each entry's + * fragment inside its own contiguous staging entry. */ +int TierExec::run_rows(const Resolved& r, bool scatter, const GroupInfo& gi, int64_t layer, + void* stage_base, const int32_t* d_idx, int64_t n_jobs) { + RadTensor pool{}; + pool.dtype = RAD_U8; + pool.rank = 2; + pool.shape[0] = gi.n_blocks; pool.shape[1] = gi.frag; + pool.stride[0] = gi.frag; pool.stride[1] = 1; + pool.data = (char*)gi.base + layer * gi.layer_stride; + + RadTensor idx{}; + idx.dtype = RAD_I32; idx.rank = 1; + idx.shape[0] = n_jobs; idx.stride[0] = 1; + idx.data = (void*)d_idx; + + RadTensor pack{}; + pack.dtype = RAD_U8; + pack.rank = 2; + pack.shape[0] = n_jobs; pack.shape[1] = gi.frag; + pack.stride[0] = entry_bytes_; /* <-- the whole trick: one entry's stride, not one row's */ + pack.stride[1] = 1; + pack.data = (char*)stage_base + gi.off + layer * gi.frag; + + RadTensor t3[3]; + if (scatter) { t3[0] = pack; t3[1] = idx; t3[2] = pool; } + else { t3[0] = pool; t3[1] = idx; t3[2] = pack; } + + /* THE RESOLVED GEOMETRY, not a hand-built one. It carries whatever the winning kernel + * supplied for a derived key as well as the query, and M in it is the band's upper bound -- + * which is correct and is the convention: both implementations take the row count from the + * OPERAND extent, because M is ranged and the value in the args is the worst case. */ + RadArgs a{}; + a.t = t3; a.n_t = 3; + a.p = r.geom.params(); a.n_p = r.geom.n_params(); + a.instance = r.instance; + return r.row->info->launch(&a, stream_); +} + +/* ------------------------------------------------------------------ RADIANCE_DEBUG_TIER_VERIFY */ + +static uint64_t tier_fnv(const void* p, int64_t n) { + uint64_t h = 1469598103934665603ull; + const unsigned char* b = (const unsigned char*)p; + for (int64_t i = 0; i < n; ++i) { h ^= b[i]; h *= 1099511628211ull; } + return h; +} + +void TierExec::verify_note(const BlockHash& key, const void* p, int64_t n, bool snapshot) { + if (!verify_ || !leader_ || !p || n <= 0) return; + (snapshot ? out_ck_ : out_sum_)[key] = tier_fnv(p, n); +} + +void TierExec::verify_check(const BlockHash& key, const void* p, int64_t n, bool snapshot) { + if (!verify_ || !leader_ || !p || n <= 0) return; + auto& m = snapshot ? out_ck_ : out_sum_; + auto it = m.find(key); + if (it == m.end()) return; /* never went out through this process */ + const uint64_t back = tier_fnv(p, n); + if (back == it->second) return; + RAD_ERR("kv tiers: the %s for %s came back DIFFERENT (%016llx out, %016llx in). The tier is " + "moving the wrong bytes, not the engine choosing differently downstream.", + snapshot ? "linear-state snapshot" : "attention blocks", key.str().c_str(), + (unsigned long long)it->second, (unsigned long long)back); +} + +/* ------------------------------------------------------------------ helpers */ + +/* WHY THIS IS NOT RAD_TRY. A tier that fails is invisible: the entry stays where it was, the pool + * keeps its blocks, and everything still works -- just slower, forever, with a counter nobody is + * looking at. The first failure names the call it came from, because "5824 failures" and nothing + * else is a day of bisecting. */ +#define TIER_TRY(call, what) \ + do { const int _s = (call); \ + if (_s != RAD_OK) { warn_once(what, _s); return _s; } } while (0) + +void TierExec::warn_once(const char* what, int st) { + if (warned_) return; + warned_ = true; + RAD_WARN("kv tiers: %s failed with %s. The entry stays where it was; this is said once, and " + "the running failure count is in /sessions.", what, rad_strerror(st)); +} + +bool TierExec::blocks_backed(const std::vector& blocks, const char* what) { + if (!kv_) return false; + for (size_t k = 0; k < gi_.size(); ++k) { + if (k >= blocks.size()) continue; /* an absent group is the gather's -1 row */ + const int32_t b = blocks[k]; + if (b < 0) continue; + const int64_t live = kv_->live_blocks(gi_[k].g); + if (b < live) continue; + if (warned_unbacked_) return false; + warned_unbacked_ = true; + RAD_ERR("kv tier %s: block %d of group %d is at or past this rank's live mark of %lld, so " + "it is lent to the expert slab and holds weights. The transfer is refused; the " + "entry stays where it is.", what, (int)b, (int)gi_[k].g, (long long)live); + return false; + } + return true; +} + +int TierExec::copy_runs(const std::vector& order, size_t first, int64_t n, bool out) { + int64_t k = 0; + while (k < n) { + const int32_t s0 = order[first + (size_t)k]->host_slot; + int64_t run = 1; + while (k + run < n && order[first + (size_t)(k + run)]->host_slot == s0 + run) ++run; + char* host = (char*)tiers_->arena().at(s0); + if (!host) return RAD_E_STATE; + host += slot_off_; + char* dev = (char*)stage_ + k * entry_bytes_; + const int st = out + ? rad_memcpy_2d_async(host, slot_bytes_, dev, entry_bytes_, entry_bytes_, run, stream_) + : rad_memcpy_2d_async(dev, entry_bytes_, host, slot_bytes_, entry_bytes_, run, stream_); + if (st != RAD_OK) return st; + k += run; + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ copy on idle */ + +int TierExec::issue_copy(std::vector& jobs, RadStream compute) { + if (!enabled_ || jobs.empty()) return RAD_OK; + TIER_TRY(rad_dev_set(device_), "selecting the rank device"); + TIER_TRY(device_init(), "building the transfer staging"); + const int st = enqueue_copy(jobs, compute); + /* A COPY THAT FAILED PART OF THE WAY IN IS DRAINED BEFORE ITS SLOTS GO BACK. The report frees + * every host slot the batch was handed, and a transfer already queued into one would land on + * whatever the arena gives that slot to next. */ + if (st != RAD_OK) (void)rad_stream_sync(stream_); + return st; +} + +int TierExec::enqueue_copy(std::vector& jobs, RadStream compute) { + order_.clear(); + for (TierJob& j : jobs) if (!j.blocks.empty()) order_.push_back(&j); + const int64_t n = (int64_t)order_.size(); + if (n > copy_idx_) return RAD_E_INVAL; + /* EVERY ID FIRST, BEFORE ANY OF THEM IS LAUNCHED AGAINST. A gather over an unbacked id faults + * the whole card rather than failing the transfer. */ + for (TierJob* j : order_) + if (!blocks_backed(j->blocks, "copy to host")) return RAD_E_STATE; + + /* AFTER EVERYTHING THE COMPUTE STREAM HAS BEEN GIVEN, which includes the step that wrote these + * blocks and the save that wrote the snapshots. A stream wait, not a host wait. */ + TIER_TRY(rad_event_record(ev_compute_, compute), "ordering the copy after the step"); + TIER_TRY(rad_event_wait(stream_, ev_compute_), "ordering the copy after the step"); + + if (n > 0) { + const int64_t ng = (int64_t)gi_.size(); + int32_t* h = idx_host_; /* the copy region */ + for (int64_t g = 0; g < ng; ++g) + for (int64_t k = 0; k < n; ++k) { + const std::vector& b = order_[(size_t)k]->blocks; + h[g * n + k] = (size_t)g < b.size() ? b[(size_t)g] : -1; + } + TIER_TRY(rad_memcpy_async(idx_dev_, h, ng * n * (int64_t)sizeof(int32_t), stream_), + "the block-index upload"); + for (int64_t s = 0; s < n; s += max_batch_) { + const int64_t c = std::min(max_batch_, n - s); + for (size_t gidx = 0; gidx < gi_.size(); ++gidx) + for (int64_t l = 0; l < gi_[gidx].n_layers; ++l) + TIER_TRY(run_rows(gi_[gidx].gather, /*scatter=*/false, gi_[gidx], l, stage_, + idx_dev_ + (int64_t)gidx * n + s, c), + "the gather out of the pool"); + TIER_TRY(copy_runs(order_, (size_t)s, c, /*out=*/true), "the copy to host memory"); + } + st_.bytes_out += n * entry_bytes_; + } + + /* The linear half: one contiguous copy each, out of the device slot the snapshot sits in. */ + for (TierJob& j : jobs) { + if (j.ck_host < 0 || j.ck_dev < 0 || ck_bytes_ <= 0) continue; + if (kv_->back_checkpoint(j.ck_dev) < 0) { j.ck_ok = false; continue; } + const void* src = kv_->checkpoint_ptr(j.ck_dev); + char* dst = (char*)tiers_->ckpt_arena().at(j.ck_host); + if (!src || !dst) { j.ck_ok = false; continue; } + const int st = rad_memcpy_async(dst + ck_slot_off_, src, ck_bytes_, stream_); + if (st != RAD_OK) { + warn_once("the snapshot copy to host memory", st); + j.ck_ok = false; + continue; + } + st_.bytes_out += ck_bytes_; + } + + TIER_TRY(rad_event_record(ev_copy_, stream_), "marking the copy"); + copy_out_ = true; + ++st_.passes; + st_.jobs += (int64_t)jobs.size(); + if (verify_) + for (const TierJob& j : jobs) + verify_pending_.push_back({j.key, j.blocks.empty() ? -1 : j.host_slot, + j.ck_ok ? j.ck_host : -1}); + return RAD_OK; +} + +int TierExec::copy_state() { + if (!copy_out_) return 1; + (void)rad_dev_set(device_); + const int q = rad_event_query(ev_copy_); + if (q == 0) return 0; + copy_out_ = false; + if (q > 0 && verify_) { + for (const VerifyNote& v : verify_pending_) { + if (v.host_slot >= 0) + verify_note(v.key, (char*)tiers_->arena().at(v.host_slot) + slot_off_, + entry_bytes_, false); + if (v.ck_host >= 0) + verify_note(v.key, (char*)tiers_->ckpt_arena().at(v.ck_host) + ck_slot_off_, + ck_bytes_, true); + } + } + verify_pending_.clear(); + if (q < 0) warn_once("the copy to host memory", q); + return q > 0 ? 1 : q; +} + +/* ------------------------------------------------------------------ restore */ + +int TierExec::issue_restore(std::vector& jobs, RadStream compute, + std::vector* ok) { + ok->assign(jobs.size(), 0); + if (!enabled_ || jobs.empty()) return RAD_OK; + TIER_TRY(rad_dev_set(device_), "selecting the rank device"); + TIER_TRY(device_init(), "building the transfer staging"); + const size_t ng = gi_.size(); + + /* WHO CHOOSES THE BLOCKS, AND WHO KEEPS THE BOOKS. Ids are shared across ranks -- one block + * table indexes every rank's shard -- so exactly one rank may choose, and that same rank is + * the only one whose allocator means anything: the prefix cache holds the KV references and + * the prefix cache is rank 0's. A follower writes into the ids it is handed and reserves + * nothing. + * + * THE WHOLE CHAIN IS RESERVED BEFORE ANY OF IT MOVES, one recall of the loan for all of it. + * Where the pool runs short the chain is cut at that point and the rest stay unstarted: a hit + * needs a contiguous prefix, so an entry past a gap would be restored for nothing. */ + if (leader_) { + const int64_t n = (int64_t)jobs.size(); + std::vector> ids(ng); + int64_t m = n; + for (size_t k = 0; k < ng; ++k) { + ids[k].reserve((size_t)n); + m = std::min(m, kv_->reserve_blocks(gi_[k].g, m, &ids[k])); + } + for (size_t k = 0; k < ng; ++k) + for (size_t i = (size_t)m; i < ids[k].size(); ++i) kv_->release_block(gi_[k].g, ids[k][i]); + for (size_t i = 0; i < jobs.size(); ++i) { + jobs[i].blocks.clear(); + if ((int64_t)i >= m) continue; + jobs[i].blocks.resize(ng); + for (size_t k = 0; k < ng; ++k) jobs[i].blocks[k] = ids[k][i]; + } + } + size_t m = 0; + while (m < jobs.size() && jobs[m].blocks.size() == ng) ++m; + /* AND WHETHER THIS RANK CAN ADDRESS WHAT IT WAS HANDED. The leader chose these ids against its + * own live mark and the recall moved every follower's with it; this is the check that it did. */ + for (size_t i = 0; i < m; ++i) + if (!blocks_backed(jobs[i].blocks, "restore")) { m = i; break; } + + /* THE CUT IS WHAT THE FOLLOWERS READ. They find their chain by which jobs carry block ids, + * so every job past the point the leader stopped gives its ids back and carries none. A + * follower handed ids for an entry the leader could not address would copy into blocks that + * are not the cache's. */ + if (leader_) { + for (size_t i = m; i < jobs.size(); ++i) { + for (size_t k = 0; k < ng && k < jobs[i].blocks.size(); ++k) + if (jobs[i].blocks[k] >= 0) kv_->release_block(gi_[k].g, jobs[i].blocks[k]); + jobs[i].blocks.clear(); + } + } + if (m == 0) return RAD_OK; + + order_.clear(); + for (size_t i = 0; i < m; ++i) order_.push_back(&jobs[i]); + for (size_t i = 0; i < m; ++i) + verify_check(jobs[i].key, (char*)tiers_->arena().at(jobs[i].host_slot) + slot_off_, + entry_bytes_, false); + + /* FROM HERE ON A FAILURE LEAVES A MIXTURE, so every job about to be written is marked started + * first -- report() drops a started job that failed rather than trusting its host copy to + * describe blocks some layers of which were overwritten. And the compute stream is made to + * wait on whatever was enqueued, success or not: a failed job's blocks go back to the pool, + * and nothing may be written into them before the transfers already queued against them. */ + for (size_t i = 0; i < m; ++i) jobs[i].started = true; + const int ri = ring_next_; + ring_next_ = (ring_next_ + 1) % kRing; + int32_t* h = idx_host_ + ng * copy_idx_ + (int64_t)ri * (int64_t)ng * chain_idx_; + int32_t* d = idx_dev_ + ng * copy_idx_ + (int64_t)ri * (int64_t)ng * chain_idx_; + int st = RAD_OK; + size_t done = 0; + for (size_t s = 0; s < m && st == RAD_OK; s += (size_t)chain_idx_) { + const int64_t c = std::min(chain_idx_, (int64_t)(m - s)); + if (ring_used_[ri] && (st = rad_event_sync(ring_ev_[ri])) != RAD_OK) break; + for (size_t g = 0; g < ng; ++g) + for (int64_t k = 0; k < c; ++k) h[(int64_t)g * c + k] = jobs[s + (size_t)k].blocks[g]; + if ((st = rad_memcpy_async(d, h, (int64_t)ng * c * (int64_t)sizeof(int32_t), stream_)) != RAD_OK) + break; + if ((st = rad_event_record(ring_ev_[ri], stream_)) != RAD_OK) break; + ring_used_[ri] = true; + for (int64_t b = 0; b < c && st == RAD_OK; b += max_batch_) { + const int64_t cc = std::min(max_batch_, c - b); + if ((st = copy_runs(order_, s + (size_t)b, cc, /*out=*/false)) != RAD_OK) break; + for (size_t gidx = 0; gidx < ng && st == RAD_OK; ++gidx) + for (int64_t l = 0; l < gi_[gidx].n_layers && st == RAD_OK; ++l) + st = run_rows(gi_[gidx].scatter, /*scatter=*/true, gi_[gidx], l, stage_, + d + (int64_t)gidx * c + b, cc); + } + if (st == RAD_OK) done = s + (size_t)c; + } + if (st != RAD_OK) warn_once("the restore into the pool", st); + for (size_t i = 0; i < done; ++i) (*ok)[i] = 1; + st_.bytes_in += (int64_t)done * entry_bytes_; + + /* THE LINEAR HALF, into a slot the leader allocates. The same rule as the blocks: the id is + * rank 0's to choose, and a follower takes the id it is handed and backs its own pages. A + * snapshot that cannot be placed is not a failure of the restore -- the session keeps its + * attention hit and replays its linear layers, which is what it would have done with no + * tiers at all. + * + * THE DEEPEST ONE IS WORTH A SLOT SOMEBODY ELSE HAS. A hit resumes from the last checkpoint at + * or below its attention hit, which on a restored chain is the chain's last snapshot; the + * earlier ones take a slot only where one is free. A full pool is then made room in for that + * one snapshot by detaching another session's, which that session's own next restore brings + * back -- rather than for every snapshot on the chain, which would push out as many other + * sessions' states as this one has checkpoints. */ + size_t deepest = done; + for (size_t i = 0; i < done; ++i) + if (jobs[i].ck_want && jobs[i].ck_ok && jobs[i].ck_host >= 0) deepest = i; + for (size_t i = 0; i < done; ++i) { + TierJob& j = jobs[i]; + if (!j.ck_want || !j.ck_ok || j.ck_host < 0 || ck_bytes_ <= 0) continue; + if (leader_) { + int32_t slot = -1; + if (kv_->alloc_checkpoint(&slot) != RAD_OK || slot < 0) { + slot = -1; + if (i != deepest || !ck_room_ || !ck_room_() || + kv_->alloc_checkpoint(&slot) != RAD_OK || slot < 0) + continue; + } + j.ck_dev = slot; + } + if (j.ck_dev < 0) continue; + if (kv_->back_checkpoint(j.ck_dev) < 0) { j.ck_ok = false; continue; } + const char* src = (const char*)tiers_->ckpt_arena().at(j.ck_host); + void* dst = kv_->checkpoint_ptr(j.ck_dev); + if (!src || !dst) { j.ck_ok = false; continue; } + verify_check(j.key, src + ck_slot_off_, ck_bytes_, true); + const int cs = rad_memcpy_async(dst, src + ck_slot_off_, ck_bytes_, stream_); + if (cs != RAD_OK) { warn_once("the snapshot copy back into the pool", cs); j.ck_ok = false; continue; } + st_.bytes_in += ck_bytes_; + } + + /* THE STEP THAT READS THESE WAITS FOR THEM, on the device. If even the marker cannot be + * enqueued the only ordering left is the host's. */ + if (rad_event_record(ev_restore_, stream_) != RAD_OK || + rad_event_wait(compute, ev_restore_) != RAD_OK) { + (void)rad_stream_sync(stream_); + } + ++st_.passes; + st_.jobs += (int64_t)m; + return st; +} + +int TierExec::fence(RadEvent* out) { + *out = nullptr; + if (!enabled_ || !stream_) return RAD_OK; + RAD_TRY(rad_dev_set(device_)); + RadEvent e = nullptr; + RAD_TRY(rad_event_create(&e)); + const int st = rad_event_record(e, stream_); + if (st != RAD_OK) { rad_event_destroy(e); return st; } + *out = e; + return RAD_OK; +} + +/* ------------------------------------------------------------------ the disk store */ + +void TierExec::run_disk(std::vector& jobs, std::vector* ok) { + ok->assign(jobs.size(), 1); + for (size_t i = 0; i < jobs.size(); ++i) (*ok)[i] = run_write(jobs[i]) ? 1 : 0; +} + +bool TierExec::run_write(TierJob& j) { + if (j.kind != TierJob::Kind::ToDisk) return true; /* the drops move nothing */ + bool ok = true; + /* THE WHOLE SLOT, every rank's shard of it, because a disk entry read back must be able to + * serve all of them. A job may carry only the snapshot half, when the blocks are already on + * disk or their write went out earlier. */ + if (j.host_slot >= 0) { + const void* src = tiers_->arena().at(j.host_slot); + ok = disk_ && src && disk_->put_block(j.key, nullptr, 0, src, slot_bytes_) == RAD_OK; + } + if (j.ck_host >= 0) { + const void* cs = tiers_->ckpt_arena().at(j.ck_host); + /* A snapshot store that was never opened -- no room for one inside the disk cap -- refuses + * this, which is the right answer and not an error: the host copy stays the only one, as + * it was. */ + j.ck_ok = disk_ && cs && disk_->put_checkpoint(j.key, j.ck_pos, cs, ck_slot_bytes_) == RAD_OK; + } + return ok; +} + +void TierExec::run_fetch(std::vector& jobs, std::vector* ok) { + ok->assign(jobs.size(), 1); + std::vector keys; + std::vector dst; + std::vector at; + for (size_t i = 0; i < jobs.size(); ++i) { + TierJob& j = jobs[i]; + j.started = true; + if (j.host_slot < 0) continue; /* only the snapshot half */ + keys.push_back(j.key); + dst.push_back(tiers_->arena().at(j.host_slot)); + at.push_back(i); + } + if (!keys.empty()) { + std::vector got(keys.size(), 0); + if (disk_) (void)disk_->get_blocks(keys.data(), (int64_t)keys.size(), dst.data(), + slot_bytes_, got.data()); + for (size_t k = 0; k < keys.size(); ++k) (*ok)[at[k]] = got[k]; + st_.bytes_in += (int64_t)keys.size() * slot_bytes_; + } + for (TierJob& j : jobs) { + if (j.ck_host < 0) continue; + void* cs = tiers_->ckpt_arena().at(j.ck_host); + j.ck_ok = disk_ && cs && disk_->get_checkpoint(j.key, j.ck_pos, cs, ck_slot_bytes_) == RAD_OK; + } +} + +/* ------------------------------------------------------------------ the report */ + +void TierExec::report_pass(std::vector& jobs, const std::vector& ok, + uint64_t now_ns) { + if (!enabled_ || !leader_) return; + for (size_t i = 0; i < jobs.size(); ++i) { + TierJob& j = jobs[i]; + const bool good = i < ok.size() && ok[i]; + /* A SNAPSHOT IS RESTORED ONLY IF EVERY RANK RESTORED ITS SHARD, and the leader is the only + * one that can act on that. It allocates the checkpoint slot and fills its own window + * first, so a follower that then fails leaves the slot holding this rank's new state beside + * another rank's stale state -- a checkpoint the cache would go on to serve, one card + * resuming the conversation and the other resuming whatever it last held. + * + * A PROMOTION THAT FAILED AS A WHOLE gives back everything the leader took for it: report() + * drops or keeps the record, and nothing will ever name these blocks or this slot again. */ + if (j.kind == TierJob::Kind::ToDevice && j.ck_dev >= 0 && (!j.ck_ok || !good)) { + kv_->free_checkpoint(j.ck_dev); + j.ck_dev = -1; + } + if (j.kind == TierJob::Kind::ToDevice && !good) { + for (size_t k = 0; k < gi_.size() && k < j.blocks.size(); ++k) + if (j.blocks[k] >= 0) kv_->release_block(gi_[k].g, j.blocks[k]); + j.blocks.clear(); + } + tiers_->report(j, good, now_ns); + } + std::vector frees; + tiers_->take_checkpoint_frees(&frees); + for (int32_t s : frees) kv_->free_checkpoint(s); +} + +bool TierExec::plan_promote(const BlockHash& key, TierJob* out) { + if (!enabled_ || !leader_) return false; + return tiers_->plan_promote(key, out); +} + +/* ------------------------------------------------------------------ TierIO */ + +TierIO::~TierIO() { stop(); } + +void TierIO::start(TierExec* leader) { + stop(); + x_ = leader; + stop_ = false; + th_ = std::thread([this] { loop(); }); +} + +void TierIO::stop() { + { + std::lock_guard lk(mu_); + stop_ = true; + } + cv_.notify_all(); + if (th_.joinable()) th_.join(); + has_work_ = has_done_ = false; + work_.clear(); + done_.clear(); + ok_.clear(); + work_at_ = 0; + fetch_q_.clear(); + fetch_done_.clear(); +} + +bool TierIO::submit(std::vector&& jobs) { + { + std::lock_guard lk(mu_); + if (has_work_ || has_done_ || !th_.joinable()) return false; + work_ = std::move(jobs); + ok_.assign(work_.size(), 1); + work_at_ = 0; + has_work_ = true; + } + cv_.notify_all(); + return true; +} + +bool TierIO::submit_fetch(Fetch&& f) { + { + std::lock_guard lk(mu_); + if (!th_.joinable()) return false; + fetch_q_.push_back(std::move(f)); + } + cv_.notify_all(); + return true; +} + +bool TierIO::take_fetch(Fetch* out) { + std::lock_guard lk(mu_); + if (fetch_done_.empty()) return false; + *out = std::move(fetch_done_.front()); + fetch_done_.pop_front(); + return true; +} + +bool TierIO::take(std::vector* jobs, std::vector* ok) { + std::lock_guard lk(mu_); + if (!has_done_) return false; + *jobs = std::move(done_); + *ok = std::move(ok_); + done_.clear(); + ok_.clear(); + has_done_ = false; + return true; +} + +bool TierIO::busy() const { + std::lock_guard lk(mu_); + return has_work_ || has_done_; +} + +void TierIO::loop() { + for (;;) { + Fetch f; + bool read = false; + size_t i = 0; + { + std::unique_lock lk(mu_); + cv_.wait(lk, [this] { return stop_ || !fetch_q_.empty() || (has_work_ && !has_done_); }); + if (stop_) return; + if (!fetch_q_.empty()) { + f = std::move(fetch_q_.front()); + fetch_q_.pop_front(); + read = true; + } else { + i = work_at_; + } + } + if (read) { + /* NOT A BYTE UNTIL EVERY RANK'S RESTORES THAT COULD READ THESE SLOTS HAVE RUN. A fence + * that cannot be waited on leaves the read unstarted, and the records stay on disk. */ + bool fenced = true; + for (RadEvent e : f.fences) if (e && rad_event_sync(e) != RAD_OK) fenced = false; + if (fenced) x_->run_fetch(f.jobs, &f.ok); + else f.ok.assign(f.jobs.size(), 0); + std::lock_guard lk(mu_); + fetch_done_.push_back(std::move(f)); + continue; + } + /* One write at a time, so a read that arrives behind a long batch waits for one job. */ + const bool ok = i < work_.size() ? x_->run_write(work_[i]) : true; + std::lock_guard lk(mu_); + if (i < ok_.size()) ok_[i] = ok ? 1 : 0; + work_at_ = i + 1; + if (work_at_ >= work_.size()) { + done_ = std::move(work_); + work_.clear(); + has_work_ = false; + has_done_ = true; + } + } +} +} /* namespace rad */ diff --git a/core/runtime/tierexec.h b/core/runtime/tierexec.h new file mode 100644 index 00000000..9c2ab4d6 --- /dev/null +++ b/core/runtime/tierexec.h @@ -0,0 +1,315 @@ +/* tierexec.h -- the side of the KV tiers that actually moves bytes. + * + * core/mem/kvtier.h decides WHAT should move and hands out TierJobs; this executes them. The split + * is the one KVManager already uses for BlockCopy and it is not decoration: core/mem has no stream + * and must not acquire one, because a synchronisation on the step path is what this design spends + * itself avoiding (spec §5.4). + * + * ============================== NOTHING HERE WAITS ON THE HOST ================================ + * + * A copy out and a restore in are both ENQUEUED and ordered by events, never by a host wait: + * + * - a copy out waits, on the transfer stream, for everything the compute stream had been given + * when it was issued -- the step that wrote the blocks is in there -- and signals an event the + * engine polls between steps. The engine thread goes on building steps the whole time, and the + * scheduler's lock is not held while it runs; + * - a restore in makes the COMPUTE stream wait for it, so the step that reads the restored + * blocks runs after they land without the host having waited for anything. + * + * The disk store is the one part that is synchronous by nature, and it runs on a thread of its own + * (TierIO below), so the engine thread never waits on a file either. + * + * ============================== THE TRANSFER, AND WHY IT IS SHAPED THIS WAY ==================== + * + * A paged pool is LAYER-MAJOR: layer l of group g owns `[base + l*layer_stride, + layer_stride)` + * and a block inside it is `block * layer_bytes_per_block()`. So a logical block is `n_layers` + * fragments of a few hundred bytes, and moving one block at a time means a few hundred bytes a + * transfer -- dispatch cost with the data as a rounding error. + * + * Turned around, WITHIN a layer the blocks are dense rows of a matrix. That makes packing an + * arbitrary set of them exactly `gather_rows` and restoring them exactly `scatter_rows`, and the + * transfer count becomes ONE LAUNCH PER (GROUP, LAYER) for a whole staging batch rather than per + * block. + * + * THE STAGING BUFFER'S LAYOUT IS WHAT MAKES THE HOST COPY CONTIGUOUS. Device staging is + * `max_batch * entry_bytes`, and one entry's bytes are [group][layer][fragment] laid end to end. + * For a given (group, layer) the destination rows are then at a stride of `entry_bytes` from a + * base inside the first entry -- which is exactly `gather_rows`'s `y` pitch, so one launch writes + * every entry's fragment for that layer directly into the place it will be copied from. The host + * side is then one strided copy per run of consecutive arena slots. + */ +#pragma once +#include "mem/kv.h" +#include "mem/kvtier.h" +#include "plugin/registry.h" +#include "rad_core.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rad { + +class SSDTier; + +class TierExec { +public: + ~TierExec(); + /* `groups` is PrefixCache::cached_groups(): the paged groups an entry holds a block in, in the + * order the entry's `blocks` vector uses. The staging layout is derived from them once here, + * because a second derivation of the same offsets is a second place to get them wrong. + * + * `max_batch` is the staging buffer in entries, `max_copy` the most entries one copy out may + * carry, and `max_chain` the longest chain one restore brings back -- the index buffers are + * sized from the last two. */ + int configure(Registry* reg, KVManager* kv, IdleTiers* tiers, SSDTier* disk, + const std::vector& groups, int max_batch, int64_t max_copy, + int64_t max_chain, bool leader, int device, int64_t slot_off, + int64_t ck_slot_off, RadStream shared); + void close(); + bool enabled() const { return enabled_; } + std::string report() const { return report_; } + + /* DECIDING AND DOING ARE SEPARATE, and under tensor parallelism that is the point. The policy + * is one object describing CONVERSATIONS, which are not sharded; the transfer is per rank, + * because each rank holds its own shard of every block. So the leader plans, every rank runs + * the same job list, and the leader reports the outcome once. + * + * A follower that consulted the policy itself would find each record already pending -- or + * already reported -- and would move nothing, silently, leaving its shard of the pool holding + * whatever was there before. That is corrupt KV on one card and not the other, which is the + * worst shape this failure can take. */ + + /* ---------------- copy on idle ---------------- + * + * Enqueue a batch of WriteBack jobs on this rank and return. The copy is ordered after + * everything `compute` had been given, and `copy_state` says when it has landed. One batch + * at a time: the engine does not issue the next until this one has reported, which is what + * lets the staging and index buffers be reused without a wait. */ + int issue_copy(std::vector& jobs, RadStream compute); + /* 1 when nothing is out or the last batch has landed, 0 while it is in flight, negative when + * the transfer stream reported an error. Taking the answer clears it. */ + int copy_state(); + bool copy_out() const { return copy_out_; } + + /* ---------------- restore ---------------- + * + * Enqueue a chain of ToDevice jobs, in chain order, and make `compute` wait for them. Every + * job's bytes are in host memory -- a disk entry was read in first (run_fetch) -- so nothing + * here waits on a file. The leader chooses every block first, recalling the loan for the + * whole chain at once; a chain the pool cannot hold is cut where the reservation ran out, and + * the jobs past the cut are left unstarted. `ok[i]` is whether job i was fully enqueued on + * this rank. */ + int issue_restore(std::vector& jobs, RadStream compute, std::vector* ok); + + /* A MARK ON THIS RANK'S TRANSFER STREAM, after everything enqueued on it so far. A restore + * reads host slots asynchronously, and a slot it is still reading may be given up and handed + * to a read off disk the moment the restore has reported; the IO thread waits for this mark + * before it writes into any slot it was handed. Null when nothing was ever enqueued here. The + * caller owns the event. */ + int fence(RadEvent* out); + + /* ---------------- the disk store (leader only; TierIO's thread) ---------------- */ + void run_disk(std::vector& jobs, std::vector* ok); + /* One ToDisk job; true when it was written. */ + bool run_write(TierJob& j); + /* ToHost jobs: the blocks read in parallel into the host slots they were given, then the + * snapshots. `ok[i]` is the blocks' result, `ck_ok` the snapshot's. */ + void run_fetch(std::vector& jobs, std::vector* ok); + + /* Leader only. Gives back what a failed job held -- a restore's blocks and checkpoint slot -- + * reports every job to the policy, and frees the device checkpoint slots a finished copy was + * holding on the cache's behalf. `now_ns` is when the pass ran: a promotion is a use. */ + void report_pass(std::vector& jobs, const std::vector& ok, uint64_t now_ns); + + /* A lookup hit off-device: the job that would bring it back, or false when the entry is not + * off-device or already has work outstanding. */ + bool plan_promote(const BlockHash& key, TierJob* out); /* leader only */ + + /* Leader only: how a restore gets a device checkpoint slot when the pool is full. The cache + * owns the policy for which snapshot gives its slot up (PrefixCache::free_checkpoint_for_restore); + * this object only knows it needs one. True when a slot was freed. */ + void set_checkpoint_room(std::function f) { ck_room_ = std::move(f); } + + struct Stats { int64_t passes = 0, jobs = 0, bytes_out = 0, bytes_in = 0; }; + const Stats& stats() const { return st_; } + +private: + struct GroupInfo { + int32_t g = -1; + int64_t n_layers = 0; + int64_t frag = 0; /* layer_bytes_per_block() */ + int64_t layer_stride = 0; + int64_t n_blocks = 0; + void* base = nullptr; + int64_t off = 0; /* this group's start inside one entry's staging bytes */ + Resolved gather, scatter; + }; + + /* The staging buffer, the index buffers, the events and the transfer stream, built on the + * first pass that has a job and never at bringup. The cost of building them eagerly is quoted + * where it is defined; it is not small. */ + int device_init(); + /* WHETHER EVERY ID THIS RANK IS ABOUT TO ADDRESS IS THE CACHE'S TO WRITE. + * + * THE KERNEL'S BOUND IS THE CARVE AND NOT THE LIVE MARK. gather_rows and scatter_rows refuse + * an index outside [0, n_blocks), which is every id the carve created -- but the blocks above + * live_blocks() are lent to the expert slab, and a restore into one writes over weights a + * kernel is reading. That reads as fluent text with a new hash on whichever rank is behind + * rather than as a failed transfer, so it is tested here, where the job can still be refused. */ + bool blocks_backed(const std::vector& blocks, const char* what); + void warn_once(const char* what, int st); + int run_rows(const Resolved& r, bool scatter, const GroupInfo& gi, int64_t layer, + void* stage_base, const int32_t* d_idx, int64_t n_jobs); + /* One strided copy per run of consecutive arena slots, `n` entries starting at job `first` of + * `order`. To host when `out`, from host otherwise. */ + int copy_runs(const std::vector& order, size_t first, int64_t n, bool out); + int enqueue_copy(std::vector& jobs, RadStream compute); + + bool enabled_ = false; + bool leader_ = false; /* this rank chooses block ids; the others follow */ + bool warned_ = false; + /* Separate from `warned_`: a transfer that failed and an id this rank cannot address are + * different reports, and the second is a broken invariant rather than a tier having trouble. + * Said once, so a refusal the pass retries every tick does not fill the log with it. */ + bool warned_unbacked_ = false; + /* THE CARD THIS RANK OWNS. Every allocation and every launch below takes the CURRENT device, + * and the engine loop leaves whatever device the last rank used current. Pinned here rather + * than assumed. */ + int device_ = -1; + /* WHERE THIS RANK'S BYTES LIVE INSIDE A SHARED SLOT. One host slot holds an entry for the + * WHOLE ENGINE, and under tensor parallelism an entry is n_ranks shards of KV that are not + * interchangeable. Every rank writing at offset zero would mean the last one to run wins and + * every rank scatters back somebody else's half. So the slot is n_ranks entries wide and a + * rank only ever touches its own window. */ + int64_t slot_off_ = 0; + int64_t slot_bytes_ = 0; /* the whole shared slot: n_ranks * entry_bytes_ */ + Registry* reg_ = nullptr; + KVManager* kv_ = nullptr; + IdleTiers* tiers_ = nullptr; + SSDTier* disk_ = nullptr; + std::function ck_room_; + std::vector gi_; + int64_t entry_bytes_ = 0; + /* ---- the linear half ---- + * `ck_bytes_` is THIS RANK's shard of one snapshot and `ck_slot_bytes_` the whole shared slot, + * exactly as entry_bytes_ and slot_bytes_ are for blocks. Zero on a model with no recurrent + * state, which is the whole of the "off" path here. */ + int64_t ck_bytes_ = 0; + int64_t ck_slot_bytes_ = 0; + int64_t ck_slot_off_ = 0; + int max_batch_ = 0; + int64_t max_copy_ = 0; + int64_t max_chain_ = 0; + void* stage_ = nullptr; /* device, max_batch_ * entry_bytes_ */ + /* ---- the block indices ---- + * + * ONE REGION FOR THE COPY OUT AND A RING OF THEM FOR RESTORES, pinned on the host and mirrored + * on the device. An index list is uploaded with the transfer it serves and read by kernels + * later in the same stream, so a region may be refilled only once the upload that last read + * it has run: one copy is out at a time, so its region is always free when the next is + * issued; several restores can be issued in one step, so each takes the next region of the + * ring and waits on that region's event -- the upload of a restore issued kRing restores ago, + * which has long since run. */ + static constexpr int kRing = 4; + int32_t* idx_host_ = nullptr; /* pinned: copy region, then kRing restore regions */ + int32_t* idx_dev_ = nullptr; + int64_t copy_idx_ = 0; /* entries a copy region holds, per group */ + int64_t chain_idx_ = 0; /* entries a restore region holds, per group */ + RadEvent ring_ev_[kRing] = {}; + bool ring_used_[kRing] = {}; + int ring_next_ = 0; + RadEvent ev_compute_ = nullptr; /* the compute stream, as a copy out found it */ + RadEvent ev_copy_ = nullptr; /* the last copy out, landed */ + RadEvent ev_restore_ = nullptr; /* the last restore, landed */ + bool copy_out_ = false; + /* THE TRANSFER STREAM, WHICH IS USUALLY SOMEBODY ELSE'S. A stream costs a hardware queue and + * a fourth queue costs this card 65% of its decode step, so the tier takes the expert mover's + * maintenance stream when there is one (Mover::transfer_stream) and only makes its own when + * there is not. `own_stream_` is which of those happened, because close() must not destroy a + * stream it was lent. */ + RadStream stream_ = nullptr; + RadStream shared_ = nullptr; + bool own_stream_ = false; + std::vector order_; + /* ---- RADIANCE_DEBUG_TIER_VERIFY ---- + * + * DID THE BYTES SURVIVE THE ROUND TRIP. A tier that corrupts reads back as fluent, plausible, + * wrong text and nothing about the engine says which of a dozen steps lost the bytes. This + * hashes what went out and what came back and names the entry when they differ, which splits + * the only question worth asking first: is the tier moving the wrong bytes, or is it moving + * the right ones and something downstream is choosing differently? + * + * A DIAGNOSTIC, NOT A GUARD. It hashes on the host, which for a snapshot is tens of + * milliseconds an entry -- affordable when a run is being bisected and not otherwise. Off + * unless the variable is set, and leader-only, because the map is keyed by an object the + * followers do not own. A copy out is hashed when it has LANDED, which is when copy_state + * first sees it done. */ + bool verify_ = false; + std::unordered_map out_sum_, out_ck_; + struct VerifyNote { BlockHash key; int32_t host_slot = -1; int32_t ck_host = -1; }; + std::vector verify_pending_; + void verify_note(const BlockHash& key, const void* p, int64_t n, bool snapshot); + void verify_check(const BlockHash& key, const void* p, int64_t n, bool snapshot); + + std::string report_; + Stats st_; +}; + +/* ------------------------------------------------------------------ the disk thread */ +/* THE DISK STORE ON A THREAD OF ITS OWN. A host-to-disk move is a file write of the whole slot, + * and a pass that makes room for a conversation's worth of copies is hundreds of megabytes of it + * -- the engine thread would build no step for as long as the writes took. So a batch is handed + * over and collected later. The thread touches the host arena and the disk store and nothing + * else: every decision about the records is made before the hand-over and after the collection, + * on the engine thread, under the scheduler's lock. + * + * TWO KINDS OF WORK, AND THE READS GO FIRST. A write batch is the background copy to disk: one at + * a time, and the engine does not hand over the next until it has collected the last. A read + * batch is a conversation a request is waiting on (IdleTiers::plan_fetch), so reads queue in the + * order they were asked for and each one is taken ahead of whatever write is out -- between two + * of its jobs, not after the whole batch. */ +class TierIO { +public: + ~TierIO(); + void start(TierExec* leader); + void stop(); + /* False when a batch is already out. */ + bool submit(std::vector&& jobs); + /* The finished batch, when there is one. */ + bool take(std::vector* jobs, std::vector* ok); + bool busy() const; + + /* A read off disk. `tag` is the caller's (the request waiting on it); `fences` are waited on + * before the first byte is written (TierExec::fence) and stay the caller's to destroy. */ + struct Fetch { + uint64_t tag = 0; + std::vector jobs; + std::vector fences; + std::vector ok; + }; + /* False when the thread is not running. */ + bool submit_fetch(Fetch&& f); + /* A finished read, oldest first. */ + bool take_fetch(Fetch* out); + +private: + void loop(); + TierExec* x_ = nullptr; + std::thread th_; + mutable std::mutex mu_; + std::condition_variable cv_; + std::vector work_, done_; + std::vector ok_; + size_t work_at_ = 0; /* the next write job; the thread's alone while has_work_ */ + bool has_work_ = false, has_done_ = false, stop_ = false; + std::deque fetch_q_, fetch_done_; +}; + +} /* namespace rad */ diff --git a/core/runtime/wtab.cpp b/core/runtime/wtab.cpp new file mode 100644 index 00000000..c32974ae --- /dev/null +++ b/core/runtime/wtab.cpp @@ -0,0 +1,22 @@ +/* wtab.cpp -- issuing a weight-table patch. See wtab.h. */ +#include "wtab.h" + +#include "device/device.h" + +namespace rad { + +int wtab_patch(const WtabPatch& p, RadStream s) { + if (p.n == 0) return RAD_OK; + if (device_is_host()) { + for (uint32_t i = 0; i < p.n; ++i) *p.dst[i] = p.val[i]; + return RAD_OK; + } +#if defined(RAD_HAVE_HIP) && RAD_HAVE_HIP + return rad_wtab_patch_launch(&p, (void*)s) == 0 ? RAD_OK : RAD_E_DEVICE; +#else + (void)s; + return RAD_E_UNSUPPORTED; +#endif +} + +} /* namespace rad */ diff --git a/core/runtime/wtab.h b/core/runtime/wtab.h new file mode 100644 index 00000000..661b75a8 --- /dev/null +++ b/core/runtime/wtab.h @@ -0,0 +1,34 @@ +/* wtab.h -- writing entries of a device weight table in stream order. + * + * A routed layer's weight table is a device array of expert pointers, and the mover changes a few + * of its entries on most steps. The new values travel IN THE KERNEL'S ARGUMENTS, which the backend + * copies when the dispatch is enqueued. A copy out of a host array would read that array when the + * card reaches the copy instead -- and the host runs ahead of the card, so by then it may hold the + * NEXT step's pointers, including one whose transfer that earlier step was never ordered behind. + */ +#pragma once +#include + +#include "rad_device.h" + +namespace rad { + +/* One dispatch's worth of writes: dst[i] = val[i] for i < n. Sized so the argument block stays + * inside the backend's per-dispatch argument slot with the implicit arguments beside it. */ +constexpr int kWtabPatch = 24; + +struct WtabPatch { + uint32_t n = 0; + uint32_t pad = 0; + void** dst[kWtabPatch] = {}; + void* val[kWtabPatch] = {}; +}; + +/* Enqueue `p` on `s`. Under the host backend, whose streams run their work as it is issued and + * whose device memory is host memory, the writes happen here. */ +int wtab_patch(const WtabPatch& p, RadStream s); + +} /* namespace rad */ + +/* The launcher in wtab.hip: one kernel onto `stream` through hipLaunchKernel. */ +extern "C" int rad_wtab_patch_launch(const rad::WtabPatch* p, void* stream); diff --git a/core/runtime/wtab.hip b/core/runtime/wtab.hip new file mode 100644 index 00000000..c0297bb0 --- /dev/null +++ b/core/runtime/wtab.hip @@ -0,0 +1,19 @@ +/* wtab.hip -- the weight-table patch kernel: one thread a write. See wtab.h. */ +#include + +#include "wtab.h" + +namespace { + +__global__ __launch_bounds__(64) void rad_wtab_patch(rad::WtabPatch p) { + const uint32_t i = threadIdx.x; + if (i < p.n) *p.dst[i] = p.val[i]; +} + +} // namespace + +extern "C" int rad_wtab_patch_launch(const rad::WtabPatch* p, void* stream) { + if (!p || p->n == 0) return 0; + hipLaunchKernelGGL(rad_wtab_patch, dim3(1), dim3(64), 0, (hipStream_t)stream, *p); + return hipGetLastError() == hipSuccess ? 0 : -1; +} diff --git a/core/sample/accept.cpp b/core/sample/accept.cpp new file mode 100644 index 00000000..b7294dab --- /dev/null +++ b/core/sample/accept.cpp @@ -0,0 +1,152 @@ +/* accept.cpp -- greedy and rejection-sampling acceptance for speculative decoding. See accept.h + * for which rule is correct when, and for why `n_accepted` is a read offset and not a recompute. + */ +#include "accept.h" +#include "host_ref.h" + +#include +#include + +namespace rad { + +int accept_greedy(const int32_t* draft, int n_draft, const int32_t* target, + int32_t* out, int32_t* n_accepted) { + if (!target || !out || !n_accepted || n_draft < 0) return RAD_E_INVAL; + if (n_draft > 0 && !draft) return RAD_E_INVAL; + + int i = 0; + for (; i < n_draft; ++i) { + if (draft[i] != target[i]) break; + out[i] = draft[i]; + } + /* The bonus token. Whether every draft token was accepted or the run stopped at i, the + * target's own answer AT position i is correct to emit -- on a full run that is the free + * extra token speculation buys, and on a rejection it is the correction. One code path for + * both, which is what stops the bonus from being an off-by-one nobody notices until the + * acceptance rate looks a percent low. */ + out[i] = target[i]; + *n_accepted = i; + return RAD_OK; +} + +/* Draw from a distribution given as a callable over token ids, walking in ASCENDING TOKEN ID. + * Any fixed order samples correctly; a distribution over the whole vocabulary has no candidate + * order to follow, and ascending id is the one that needs no sort to be a total order. + * + * Two passes over the vocabulary and NO intermediate array: the residual after a rejection would + * otherwise be a 151K-float allocation on the step path, which the arena discipline (spec §3.1) + * exists to forbid. Returns -1 if the total mass is zero. */ +template +static int32_t draw_from(Weight w, int64_t n, float u) { + double total = 0.0; + for (int64_t v = 0; v < n; ++v) { + const float x = w(v); + if (x > 0.0f) total += (double)x; + } + if (!(total > 0.0)) return -1; + + const double want = (double)u * total; + double acc = 0.0; + int32_t last = -1; + for (int64_t v = 0; v < n; ++v) { + const float x = w(v); + if (!(x > 0.0f)) continue; + last = (int32_t)v; + acc += (double)x; + if (acc >= want) return (int32_t)v; + } + /* Float drift can leave the walk a hair short at the very top of the range; the last token + * with mass is the right answer there, not token 0. */ + return last; +} + +int accept_stochastic(const SpecAcceptParams& p, const int32_t* draft, + const float* target_probs, const float* draft_probs, + int32_t* out, int32_t* n_accepted) { + if (!target_probs || !out || !n_accepted) return RAD_E_INVAL; + if (p.n_draft < 0 || p.n_vocab <= 0) return RAD_E_INVAL; + if (p.n_draft > 0 && !draft) return RAD_E_INVAL; + + const int64_t V = p.n_vocab; + + for (int i = 0; i < p.n_draft; ++i) { + const int32_t x = draft[i]; + if (x < 0 || x >= V) return RAD_E_INVAL; + + const float* prow = target_probs + (int64_t)i * V; + const float px = prow[x]; + /* A greedy drafter is a point mass: q(x) = 1, q(everything else) = 0. Passing null for + * `draft_probs` says so, and it is the case worth being fast at -- every MTP head that + * ships inside a target checkpoint drafts greedily. */ + const float qx = draft_probs ? draft_probs[(int64_t)i * V + x] : 1.0f; + + const float u = rng_uniform(p.seed, p.pos + (uint64_t)i, RAD_RNG_ACCEPT); + const bool accept = !(qx > 0.0f) || (double)u < (double)px / (double)qx; + + if (accept) { out[i] = x; continue; } + + /* Rejected. The emitted token comes from the residual norm(max(0, p - q)); anything else + * -- re-sampling p, or emitting the target's argmax -- changes the distribution the + * scheme emits, which is the one property speculative decoding is supposed to preserve. */ + const float* qrow = draft_probs ? draft_probs + (int64_t)i * V : nullptr; + auto resid = [&](int64_t v) -> float { + const float q = qrow ? qrow[v] : (v == x ? 1.0f : 0.0f); + const float r = prow[v] - q; + return r > 0.0f ? r : 0.0f; + }; + + const int32_t tok = + draw_from(resid, V, rng_uniform(p.seed, p.pos + (uint64_t)i, RAD_RNG_RESID)); + if (tok < 0) { + /* The residual is empty: the target has no mass the drafter did not already claim, + * and the uniform landed on the acceptance boundary anyway. Accepting is the correct + * answer there -- the drafted token is in the target's support by construction -- so + * take it and carry on rather than emitting nothing. */ + out[i] = x; + continue; + } + out[i] = tok; + *n_accepted = i; + return RAD_OK; + } + + /* Every draft token accepted: the bonus position is an ordinary pick from the target's own + * distribution, drawn on the ORDINARY pick stream at its own output position, so it is the + * same token a non-speculative step would have produced there for this seed. */ + const float* brow = target_probs + (int64_t)p.n_draft * V; + const int32_t bonus = + draw_from([&](int64_t v) { return brow[v]; }, V, + rng_uniform(p.seed, p.pos + (uint64_t)p.n_draft, RAD_RNG_PICK)); + if (bonus < 0) { + RAD_ERR("speculative accept: target distribution at the bonus position has no mass " + "(a grammar admitting nothing); the request cannot be continued"); + return RAD_E_STATE; + } + + out[p.n_draft] = bonus; + *n_accepted = p.n_draft; + return RAD_OK; +} + +int accept_sequence(const SpecAcceptParams& p, const int32_t* draft, + const int32_t* target_argmax, + const float* target_probs, const float* draft_probs, + int32_t* out, int32_t* n_accepted) { + if (p.greedy) { + if (!target_argmax) { + RAD_ERR("speculative accept: greedy acceptance was asked for without the target's " + "argmax; a silent switch to rejection sampling would change the output " + "distribution and nothing would say so"); + return RAD_E_INVAL; + } + return accept_greedy(draft, p.n_draft, target_argmax, out, n_accepted); + } + if (!target_probs) { + RAD_ERR("speculative accept: rejection sampling was asked for without target " + "probabilities"); + return RAD_E_INVAL; + } + return accept_stochastic(p, draft, target_probs, draft_probs, out, n_accepted); +} + +} /* namespace rad */ diff --git a/core/sample/accept.h b/core/sample/accept.h new file mode 100644 index 00000000..b22c824d --- /dev/null +++ b/core/sample/accept.h @@ -0,0 +1,98 @@ +/* accept.h -- speculative acceptance. Verification is a declared op; ACCEPTANCE IS CORE SAMPLER + * LOGIC (spec §10), which is why it lives here beside the chain that produced the distributions + * it compares. + * + * Three rules, and the cheapest one is exact everywhere. + * + * AGREEMENT WITH THE TARGET'S OWN TOKEN -- what accept_greedy below actually implements, and what + * this engine uses. A drafted token is accepted when it equals the token the target produced at + * that position. At temperature 0 that token is the argmax, which is where the name came from. + * ABOVE ZERO IT IS THE TARGET'S SAMPLED DRAW, AND ACCEPTING ON IT IS STILL EXACT -- provided each + * verified position draws from its own RNG coordinate, which core/sample/sampler.cpp guarantees + * (`p.pos = n_out + k`). Then the target's draw at position k is the one its own distribution + * specifies there, the first emitted token is that draw whether the draft agreed or not, and every + * later position is conditioned on a prefix accepted only because it matched. The emitted sequence + * is a draw from the target, not an approximation of one. + * + * Exact given the same logits -- which is not the same as byte-identical to a non-speculative run, + * because a verify step's logits are computed at a different M than a decode step's. The text + * matches exactly at temperature 0 and mostly above it. See Engine::collect_step. + * + * What it costs is acceptance RATE: P(y == x) rather than the optimal min(1, p/q). What it costs + * in machinery is nothing, which is why the engine computes no probability planes for it. + * + * ACCEPTING ON ARGMAX AT A POSITIVE TEMPERATURE is the rule that is NOT exact -- it replaces the + * target's distribution with its mode. That is a different thing from the above, and the two are + * easy to conflate. + * + * REJECTION SAMPLING. At temperature > 0 the drafted token x is accepted with probability + * min(1, p(x)/q(x)) where p is the target's filtered distribution and q the drafter's. On + * rejection the emitted token is drawn from the residual, norm(max(0, p - q)), which is what + * makes the whole scheme emit exactly the target's distribution. With a GREEDY DRAFTER q is a + * point mass, so the accept probability collapses to p(x) and the residual is p with x removed + * and the rest renormalised -- which is the case the fast path is written for. + * + * Worth stating plainly because it looks like a regression and is not: acceptance FALLS relative + * to greedy-against-greedy, because a proposal the target agrees with is still only accepted with + * probability p(x) rather than always. That is the price of emitting the target's true + * distribution. + * + * WHAT THE ANSWER IS FOR. `n_accepted` is consumed by two components that do different things + * with it. The scheduler frees paged KV blocks past the accepted position -- a slot-table edit. + * The linear-attention kernels do NOT recompute: the recurrent state and the conv window have + * already absorbed the rejected tokens, and libr4d handles that by treating the conv state cache + * as a rolling window of `conv_width-1 + n_spec` entries and READING AT THE SLOT THE LAST + * ACCEPTED TOKEN LEFT. A rejection is a change of read offset, not a recompute, and `num_accepted` + * is a required operand of `gdn_conv_update` and `gdn_recurrent_update` for exactly that reason + * (docs/OPS.md, spec §10). + */ +#pragma once +#include "../rad_internal.h" + +#include + +namespace rad { + +struct SpecAcceptParams { + int n_draft = 0; /* draft tokens proposed for this sequence */ + int64_t n_vocab = 0; /* row stride of the probability planes */ + uint64_t seed = 0; /* the request's seed */ + uint64_t pos = 0; /* output position of draft token 0 */ + bool greedy = false; /* temperature 0: argmax acceptance instead of rejection */ +}; + +/* Acceptance by agreement, over precomputed target tokens. `target` is [n_draft+1] -- the token + * the target model produced at each verified position, including the bonus position past the last + * draft token, which is why the buffer is one longer than the draft. That token is the argmax at + * temperature 0 and the target's own sampled draw above it; both are exact, for the reason at the + * top of this file. The name describes the temperature-0 case; the rule is correct above it too. + * + * Writes n_accepted+1 tokens into `out` (capacity n_draft+1) and sets *n_accepted. Returns + * RAD_OK. Always emits at least one token: the position after the last accepted one is the + * target's own answer, which is always correct to emit. */ +int accept_greedy(const int32_t* draft, int n_draft, const int32_t* target, + int32_t* out, int32_t* n_accepted); + +/* Rejection sampling. `target_probs` is [(n_draft+1) * n_vocab], each row a NORMALISED + * distribution as the sampler chain left it -- filtered, renormalised over the survivors, zero + * elsewhere. `draft_probs` is [n_draft * n_vocab] on the same terms, or null for a greedy drafter + * (a point mass on the drafted token), which is the common case and the cheap one. + * + * Writes n_accepted+1 tokens into `out` and sets *n_accepted. Returns RAD_OK, or RAD_E_INVAL on + * a malformed argument. A target row that sums to zero -- everything masked out by a grammar -- + * is RAD_E_STATE: there is no token to emit and the request must fail rather than receive one. */ +int accept_stochastic(const SpecAcceptParams& p, const int32_t* draft, + const float* target_probs, const float* draft_probs, + int32_t* out, int32_t* n_accepted); + +/* The one a caller reaches for: dispatches on p.greedy. The greedy path needs `target_argmax` + * (which the `sample_argmax` op already produced) and ignores the probability planes; the + * stochastic path needs the planes and ignores the argmax. Passing the wrong one for the mode is + * RAD_E_INVAL rather than a quiet fallback, because a verify step that silently switched + * acceptance rules would change the output distribution and nothing would say so. */ +int accept_sequence(const SpecAcceptParams& p, const int32_t* draft, + const int32_t* target_argmax, + const float* target_probs, const float* draft_probs, + int32_t* out, int32_t* n_accepted); + +} /* namespace rad */ diff --git a/core/sample/gbnf.cpp b/core/sample/gbnf.cpp new file mode 100644 index 00000000..9c910ba4 --- /dev/null +++ b/core/sample/gbnf.cpp @@ -0,0 +1,1388 @@ +/* gbnf.cpp -- the GBNF grammar state machine, lifted from llama.cpp `src/llama-grammar.cpp` at + * upstream commit 06938ac12 (MIT). See gbnf.h for the list of changes, and gbnf_mask.cpp for how a + * token mask is produced. + */ +#include "gbnf.h" +#include "gbnf_internal.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rad { + +using gbnf::GbnfLimit; +using gbnf::GbnfRuleSet; +using gbnf::OpWork; +using gbnf::SetBuild; +using gbnf::advance_stack; +using gbnf::decode_utf8; +using gbnf::is_end_of_sequence; +using gbnf::match_char; +using gbnf::match_token; +using gbnf::kMaxCompileBytes; +using gbnf::kMaxNesting; + +/* A repetition `S{m,n}` expands into rules, and the expansion multiplies. Past this many the + * grammar is a denial of service against the machine that compiled it, so refuse rather than + * allocate. Upstream calls it MAX_REPETITION_THRESHOLD and picks the same number. */ +static constexpr uint64_t MAX_REPETITION_THRESHOLD = 2000; + +namespace gbnf { + +void throw_set_limit() { + throw GbnfLimit("the grammar's parse forks into more than " + std::to_string(kMaxStacks) + + " stacks or " + std::to_string(kMaxSetElems) + + " stack elements at one position"); +} + +void OpWork::over() const { + throw GbnfLimit("the grammar needs more than " + std::to_string(limit) + + " units of stack work at one position"); +} + +uint64_t stack_hash(const GbnfStack& s) { + uint64_t h = 1469598103934665603ull; + for (const GbnfElement* e : s) { h ^= (uint64_t)(uintptr_t)e; h *= 1099511628211ull; } + return h ^ s.size(); +} + +void SetBuild::insert(GbnfStacks& out, GbnfStack s) { + work.add(s.size() + kStackCost / 4); + if (index.empty() && out.size() < kIndexFrom) { + if (std::find(out.begin(), out.end(), s) != out.end()) return; + } else { + if (index.empty()) + for (size_t i = 0; i < out.size(); ++i) index.emplace(stack_hash(out[i]), i); + const uint64_t h = stack_hash(s); + const auto range = index.equal_range(h); + for (auto it = range.first; it != range.second; ++it) + if (out[it->second] == s) return; + index.emplace(h, out.size()); + } + add(s.size()); + out.push_back(std::move(s)); +} + +/* ================================================================== UTF-8 */ + +std::pair decode_utf8(const char* src) { + static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 }; + const uint8_t first_byte = (uint8_t)*src; + const uint8_t highbits = first_byte >> 4; + const int len = lookup[highbits]; + const uint8_t mask = (uint8_t)((1 << (8 - len)) - 1); + uint32_t value = first_byte & mask; + const char* end = src + len; /* may overrun */ + const char* pos = src + 1; + for (; pos < end && *pos; pos++) value = (value << 6) + ((uint8_t)*pos & 0x3F); + return { value, pos }; +} + +std::pair, PartialUtf8> decode_utf8(const std::string& src, + PartialUtf8 partial_start) { + static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 }; + const char* pos = src.c_str(); + std::vector cps; + cps.reserve(src.size() + 1); + + uint32_t value = partial_start.value; + int n_remain = partial_start.n_remain; + + while (*pos != 0 && n_remain > 0) { + const uint8_t next_byte = (uint8_t)*pos; + if ((next_byte >> 6) != 2) { + cps.push_back(0); + return { std::move(cps), PartialUtf8{ 0, -1 } }; + } + value = (value << 6) + (next_byte & 0x3F); + ++pos; + --n_remain; + } + if (partial_start.n_remain > 0 && n_remain == 0) cps.push_back(value); + + while (*pos != 0) { + const uint8_t first_byte = (uint8_t)*pos; + const uint8_t highbits = first_byte >> 4; + n_remain = lookup[highbits] - 1; + if (n_remain < 0) { + cps.clear(); + cps.push_back(0); + return { std::move(cps), PartialUtf8{ 0, n_remain } }; + } + const uint8_t mask = (uint8_t)((1 << (7 - n_remain)) - 1); + value = first_byte & mask; + ++pos; + while (*pos != 0 && n_remain > 0) { + value = (value << 6) + ((uint8_t)*pos & 0x3F); + ++pos; + --n_remain; + } + if (n_remain == 0) cps.push_back(value); + } + cps.push_back(0); + return { std::move(cps), PartialUtf8{ value, n_remain } }; +} + +} /* namespace gbnf */ + +/* ================================================================== the per-vocabulary cache + * + * EVERYTHING GBNF DERIVES FROM A VOCABULARY, IN ONE OBJECT WHOSE LIFETIME IS THE VOCABULARY'S. + * The vocabulary index (gbnf_mask.cpp) and the programs compiled against it are kept on the + * VocabView itself rather than in a process-global table keyed on its POINTER. A pointer is not + * an identity: a view destroyed and another constructed in the same storage answers to the same + * key, and the second one is served the first one's work -- a mask over a vocabulary it is not + * sampling from, which admits the wrong token set or none at all with nothing anywhere reporting + * it. Hanging it off the view makes that unaskable, and it makes the program cap mean thirty-two + * schemas PER VOCABULARY rather than thirty-two shared between every vocabulary a process holds. + */ +struct GbnfProgram; + +struct VocabGbnf { + std::mutex mu; + std::shared_ptr index; + double index_ms = 0.0; + + /* One program per (text, root). The cache PINS the most recently used ones -- capped, because + * the key comes from client requests and a caller sending a thousand distinct schemas must + * not be able to grow it without bound -- and REMEMBERS every other one that is still alive. + * A program is kept alive by every request compiled against it (SamplingParams holds it from + * admission on), so a request is always served the program it was admitted with, however + * many other grammars were compiled in between, and the scheduler thread never recompiles + * one. */ + struct Cached { + std::shared_ptr pinned; + std::weak_ptr alive; + uint64_t used = 0; + }; + std::map, Cached> programs; + uint64_t clock = 0; +}; + +/* Created on first use under one process-wide lock; read under the cache's own. Two locks rather + * than one because the outer one is taken once per grammar and the inner one is taken for the + * duration of a vocabulary index build, which on a quarter-million-piece vocabulary is not + * brief. */ +static VocabGbnf& gbnf_cache_for(const VocabView* v) { + static std::mutex m; + std::lock_guard lk(m); + if (!v->gbnf_cache) v->gbnf_cache = std::make_shared(); + return *static_cast(v->gbnf_cache.get()); +} + +static std::shared_ptr vocab_index_for(const VocabView* v) { + VocabGbnf& C = gbnf_cache_for(v); + std::lock_guard lk(C.mu); + if (!C.index) { + const auto t0 = std::chrono::steady_clock::now(); + C.index = gbnf::vocab_index_build(*v); + C.index_ms = std::chrono::duration( + std::chrono::steady_clock::now() - t0).count(); + } + return C.index; +} + +int gbnf_prepare_vocab(const VocabView* vocab, GbnfVocabInfo* info) { + if (!vocab) return RAD_E_INVAL; + try { + const auto x = vocab_index_for(vocab); + if (info) { + VocabGbnf& C = gbnf_cache_for(vocab); + std::lock_guard lk(C.mu); + info->build_ms = C.index_ms; + info->bytes = gbnf::vocab_index_bytes(*x); + } + } catch (const std::bad_alloc&) { + return RAD_E_NOMEM; + } + return RAD_OK; +} + +/* ================================================================== lexing helpers */ + +static bool is_digit_char(char c) { return '0' <= c && c <= '9'; } +static bool is_word_char(char c) { + return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '-' || is_digit_char(c); +} + +static std::pair parse_hex(const char* src, int size) { + const char* pos = src; + const char* end = src + size; + uint32_t value = 0; + for (; pos < end && *pos; pos++) { + value <<= 4; + const char c = *pos; + if ('a' <= c && c <= 'f') value += (uint32_t)(c - 'a' + 10); + else if ('A' <= c && c <= 'F') value += (uint32_t)(c - 'A' + 10); + else if ('0' <= c && c <= '9') value += (uint32_t)(c - '0'); + else break; + } + if (pos != end) + throw std::runtime_error("expecting " + std::to_string(size) + " hex chars at " + src); + return { value, pos }; +} + +static const char* parse_space(const char* src, bool newline_ok) { + const char* pos = src; + while (*pos == ' ' || *pos == '\t' || *pos == '#' || + (newline_ok && (*pos == '\r' || *pos == '\n'))) { + if (*pos == '#') { while (*pos && *pos != '\r' && *pos != '\n') pos++; } + else pos++; + } + return pos; +} + +static const char* parse_name(const char* src) { + const char* pos = src; + while (is_word_char(*pos)) pos++; + if (pos == src) throw std::runtime_error(std::string("expecting name at ") + src); + return pos; +} + +static const char* parse_int(const char* src) { + const char* pos = src; + while (is_digit_char(*pos)) pos++; + if (pos == src) throw std::runtime_error(std::string("expecting integer at ") + src); + return pos; +} + +static std::pair parse_char(const char* src) { + if (*src == '\\') { + switch (src[1]) { + case 'x': return parse_hex(src + 2, 2); + case 'u': return parse_hex(src + 2, 4); + case 'U': return parse_hex(src + 2, 8); + case 't': return { (uint32_t)'\t', src + 2 }; + case 'r': return { (uint32_t)'\r', src + 2 }; + case 'n': return { (uint32_t)'\n', src + 2 }; + case '\\': case '"': case '[': case ']': + return { (uint32_t)(uint8_t)src[1], src + 2 }; + default: + throw std::runtime_error(std::string("unknown escape at ") + src); + } + } else if (*src) { + return decode_utf8(src); + } + throw std::runtime_error("unexpected end of input"); +} + +/* `<[id]>` is a literal token id; `` resolves through the vocabulary and must tokenise to + * exactly one token, because a rule element is one terminal. */ +static std::pair parse_token(const VocabView* vocab, const char* src) { + const char* pos = src; + if (*pos != '<') throw std::runtime_error(std::string("expecting '<' at ") + pos); + pos++; + + if (*pos == '[') { + pos++; + const char* int_end = parse_int(pos); + const uint32_t id = (uint32_t)std::stoul(std::string(pos, (size_t)(int_end - pos))); + pos = int_end; + if (*pos != ']') throw std::runtime_error(std::string("expecting ']' at ") + pos); + pos++; + if (*pos != '>') throw std::runtime_error(std::string("expecting '>' at ") + pos); + pos++; + return { id, pos }; + } + + if (!vocab) throw std::runtime_error(std::string("no vocabulary to parse token at ") + src); + + while (*pos != 0 && *pos != '>') pos++; + if (*pos != '>') throw std::runtime_error(std::string("expecting '>' at ") + pos); + pos++; + + std::vector toks; + const std::string text(src, (size_t)(pos - src)); + if (vocab->tokenize(text, &toks) < 0 || toks.size() != 1) + throw std::runtime_error("invalid token '" + text + "' (must be exactly one token)"); + return { (uint32_t)toks[0], pos }; +} + +/* ================================================================== the parser */ + +/* What a symbol costs beyond its name: the map node that holds it and the rule slot it owns. */ +static constexpr uint64_t kSymbolOverhead = 64 + sizeof(GbnfRule); + +void GbnfParser::charge(uint64_t bytes) { + budget_used_ += bytes; + if (budget_used_ > kMaxCompileBytes) + throw std::runtime_error("the grammar expands past " + + std::to_string(kMaxCompileBytes >> 20) + " MiB when compiled; " + "reduce its repetition counts or the size of what they repeat"); +} + +uint32_t GbnfParser::get_symbol_id(const char* src, size_t len) { + const uint32_t next_id = (uint32_t)symbol_ids_.size(); + auto r = symbol_ids_.emplace(std::string(src, len), next_id); + if (r.second) charge(len + kSymbolOverhead); + return r.first->second; +} + +/* A generated name repeats its base, so a long rule name times many generated rules is an + * amplification the text does not pay for; it is charged like any other. */ +uint32_t GbnfParser::generate_symbol_id(const std::string& base) { + charge(base.size() + 12 + kSymbolOverhead); + const uint32_t next_id = (uint32_t)symbol_ids_.size(); + symbol_ids_[base + '_' + std::to_string(next_id)] = next_id; + return next_id; +} + +void GbnfParser::add_rule(uint32_t id, const GbnfRule& rule) { + if (rules_.size() <= id) rules_.resize(id + 1); + rules_[id] = rule; +} + +const char* GbnfParser::parse_alternates(const char* src, const std::string& rule_name, + uint32_t rule_id, bool is_nested) { + GbnfRule rule; + const char* pos = parse_sequence(src, rule_name, rule, is_nested); + while (*pos == '|') { + rule.push_back({ GRE_ALT, 0 }); + pos = parse_space(pos + 1, true); + pos = parse_sequence(pos, rule_name, rule, is_nested); + } + rule.push_back({ GRE_END, 0 }); + add_rule(rule_id, rule); + return pos; +} + +const char* GbnfParser::parse_sequence(const char* src, const std::string& rule_name, + GbnfRule& rule, bool is_nested) { + size_t last_sym_start = rule.size(); + const char* pos = src; + uint64_t n_prev_rules = 1; + + /* S{m,n} is rewritten into rules rather than counted at match time, which is what keeps the + * state machine a pushdown automaton with no counters in it: + * S{m,n} -> S S ... (m times) S'(n-m), S'(x) ::= S S'(x-1) | + * S{m,} -> S S ... (m times) S', S' ::= S S' | + * S* -> S{0,} S+ -> S{1,} S? -> S{0,1} + * The cost is that the rule count multiplies, which is why the threshold above exists. */ + auto handle_repetitions = [&](uint64_t min_times, uint64_t max_times) { + const bool no_max = max_times == UINT64_MAX; + if (last_sym_start == rule.size()) + throw std::runtime_error(std::string("expecting preceding item to */+/?/{ at ") + pos); + + /* `n_opt` below is max - min, which a reversed range would wrap to about 1.8e19 rules. */ + if (!no_max && max_times < min_times) + throw std::runtime_error("repetition {" + std::to_string(min_times) + "," + + std::to_string(max_times) + "} has its minimum above its " + "maximum"); + + const GbnfRule prev_rule(rule.begin() + (std::ptrdiff_t)last_sym_start, rule.end()); + + uint64_t total_rules = 1; + if (!no_max && max_times > 0) total_rules = max_times; + else if (min_times > 0) total_rules = min_times; + + if (n_prev_rules * total_rules >= MAX_REPETITION_THRESHOLD) + throw std::runtime_error("repeated rules multiplied past the sane limit; reduce the " + "number of repetitions or the rule's complexity"); + + /* The copies about to be made: the operand once per required count beyond the first, and + * once more in each optional rule with its reference, ALT and END. Both counts are below + * MAX_REPETITION_THRESHOLD here, so the product cannot overflow. */ + { + const uint64_t w = prev_rule.size(); + const uint64_t n_rest = no_max ? 1 : max_times - min_times; + const uint64_t copies = (min_times > 1 ? (min_times - 1) * w : 0) + n_rest * (w + 3); + charge(copies * sizeof(GbnfElement)); + } + + if (min_times == 0) { + rule.resize(last_sym_start); + } else { + for (uint64_t i = 1; i < min_times; i++) + rule.insert(rule.end(), prev_rule.begin(), prev_rule.end()); + } + + uint32_t last_rec_rule_id = 0; + const uint64_t n_opt = no_max ? 1 : max_times - min_times; + + GbnfRule rec_rule(prev_rule); + for (uint64_t i = 0; i < n_opt; i++) { + rec_rule.resize(prev_rule.size()); + const uint32_t rec_rule_id = generate_symbol_id(rule_name); + if (i > 0 || no_max) + rec_rule.push_back({ GRE_RULE_REF, no_max ? rec_rule_id : last_rec_rule_id }); + rec_rule.push_back({ GRE_ALT, 0 }); + rec_rule.push_back({ GRE_END, 0 }); + add_rule(rec_rule_id, rec_rule); + last_rec_rule_id = rec_rule_id; + } + if (n_opt > 0) rule.push_back({ GRE_RULE_REF, last_rec_rule_id }); + n_prev_rules *= total_rules; + }; + + while (*pos) { + if (*pos == '"') { /* literal string */ + pos++; + last_sym_start = rule.size(); + n_prev_rules = 1; + while (*pos != '"') { + if (!*pos) throw std::runtime_error("unexpected end of input"); + auto cp = parse_char(pos); + pos = cp.second; + rule.push_back({ GRE_CHAR, cp.first }); + } + pos = parse_space(pos + 1, is_nested); + } else if (*pos == '[') { /* char range(s) */ + pos++; + GreType start_type = GRE_CHAR; + if (*pos == '^') { pos++; start_type = GRE_CHAR_NOT; } + last_sym_start = rule.size(); + n_prev_rules = 1; + while (*pos != ']') { + if (!*pos) throw std::runtime_error("unexpected end of input"); + auto cp = parse_char(pos); + pos = cp.second; + const GreType type = last_sym_start < rule.size() ? GRE_CHAR_ALT : start_type; + rule.push_back({ type, cp.first }); + if (pos[0] == '-' && pos[1] != ']') { + if (!pos[1]) throw std::runtime_error("unexpected end of input"); + auto hi = parse_char(pos + 1); + pos = hi.second; + rule.push_back({ GRE_CHAR_RNG_UPPER, hi.first }); + } + } + pos = parse_space(pos + 1, is_nested); + } else if (*pos == '<' || *pos == '!') { /* token terminal */ + GreType type = GRE_TOKEN; + if (*pos == '!') { type = GRE_TOKEN_NOT; pos++; } + auto tp = parse_token(vocab_, pos); + last_sym_start = rule.size(); + n_prev_rules = 1; + rule.push_back({ type, tp.first }); + pos = parse_space(tp.second, is_nested); + } else if (is_word_char(*pos)) { /* rule reference */ + const char* name_end = parse_name(pos); + const uint32_t ref = get_symbol_id(pos, (size_t)(name_end - pos)); + pos = parse_space(name_end, is_nested); + last_sym_start = rule.size(); + n_prev_rules = 1; + rule.push_back({ GRE_RULE_REF, ref }); + } else if (*pos == '(') { /* grouping */ + if (++depth_ > kMaxNesting) + throw std::runtime_error("parentheses nest more than " + + std::to_string(kMaxNesting) + " deep"); + pos = parse_space(pos + 1, true); + const uint32_t n_before = (uint32_t)symbol_ids_.size(); + const uint32_t sub_rule_id = generate_symbol_id(rule_name); + pos = parse_alternates(pos, rule_name, sub_rule_id, true); + --depth_; + n_prev_rules = std::max(1u, (uint32_t)symbol_ids_.size() - n_before); + last_sym_start = rule.size(); + rule.push_back({ GRE_RULE_REF, sub_rule_id }); + if (*pos != ')') throw std::runtime_error(std::string("expecting ')' at ") + pos); + pos = parse_space(pos + 1, is_nested); + } else if (*pos == '.') { /* any char */ + last_sym_start = rule.size(); + n_prev_rules = 1; + rule.push_back({ GRE_CHAR_ANY, 0 }); + pos = parse_space(pos + 1, is_nested); + } else if (*pos == '*') { + pos = parse_space(pos + 1, is_nested); + handle_repetitions(0, UINT64_MAX); + } else if (*pos == '+') { + pos = parse_space(pos + 1, is_nested); + handle_repetitions(1, UINT64_MAX); + } else if (*pos == '?') { + pos = parse_space(pos + 1, is_nested); + handle_repetitions(0, 1); + } else if (*pos == '{') { + pos = parse_space(pos + 1, is_nested); + if (!is_digit_char(*pos)) + throw std::runtime_error(std::string("expecting an int at ") + pos); + const char* int_end = parse_int(pos); + const uint64_t min_times = std::stoull(std::string(pos, (size_t)(int_end - pos))); + pos = parse_space(int_end, is_nested); + + uint64_t max_times = UINT64_MAX; + if (*pos == '}') { + max_times = min_times; + pos = parse_space(pos + 1, is_nested); + } else if (*pos == ',') { + pos = parse_space(pos + 1, is_nested); + if (is_digit_char(*pos)) { + const char* e = parse_int(pos); + max_times = std::stoull(std::string(pos, (size_t)(e - pos))); + pos = parse_space(e, is_nested); + } + if (*pos != '}') throw std::runtime_error(std::string("expecting '}' at ") + pos); + pos = parse_space(pos + 1, is_nested); + } else { + throw std::runtime_error(std::string("expecting ',' at ") + pos); + } + const bool has_max = max_times != UINT64_MAX; + if (min_times > MAX_REPETITION_THRESHOLD || + (has_max && max_times > MAX_REPETITION_THRESHOLD)) + throw std::runtime_error("number of repetitions exceeds the sane limit"); + handle_repetitions(min_times, max_times); + } else { + break; + } + } + return pos; +} + +const char* GbnfParser::parse_rule(const char* src) { + const char* name_end = parse_name(src); + const char* pos = parse_space(name_end, false); + const size_t name_len = (size_t)(name_end - src); + const uint32_t rule_id = get_symbol_id(src, name_len); + const std::string name(src, name_len); + + if (!(pos[0] == ':' && pos[1] == ':' && pos[2] == '=')) + throw std::runtime_error(std::string("expecting ::= at ") + pos); + pos = parse_space(pos + 3, true); + + pos = parse_alternates(pos, name, rule_id, false); + + if (*pos == '\r') pos += pos[1] == '\n' ? 2 : 1; + else if (*pos == '\n') pos++; + else if (*pos) throw std::runtime_error(std::string("expecting newline or end at ") + pos); + return parse_space(pos, true); +} + +int GbnfParser::parse(const char* src, std::string* err) { + if (!src) return RAD_E_INVAL; + budget_used_ = 0; + depth_ = 0; + try { + const char* pos = parse_space(src, true); + while (*pos) pos = parse_rule(pos); + + /* Every referenced rule must exist. Upstream reports the missing NAME rather than the + * index, which is the difference between a diagnostic and a number. */ + for (const auto& rule : rules_) { + if (rule.empty()) throw std::runtime_error("undefined rule"); + for (const auto& e : rule) { + if (e.type != GRE_RULE_REF) continue; + if (e.value < rules_.size() && !rules_[e.value].empty()) continue; + for (const auto& kv : symbol_ids_) + if (kv.second == e.value) + throw std::runtime_error("undefined rule identifier '" + kv.first + "'"); + throw std::runtime_error("undefined rule " + std::to_string(e.value)); + } + } + } catch (const std::exception& ex) { + /* The parser is recursive descent and throws, as upstream's does. Nothing escapes: a + * parse failure is a status and a message, because errors are values here. */ + if (err) *err = ex.what(); + rules_.clear(); + return RAD_E_FORMAT; + } + return RAD_OK; +} + +/* ================================================================== stack machinery */ + +namespace gbnf { + +/* Every bound is an O(1) check on the path each stack already takes, and a grammar that reaches + * one throws GbnfLimit (see "what a grammar may cost" in gbnf_internal.h). */ +void advance_stack(const GbnfRuleSet& rules, const GbnfStack& stack, GbnfStacks& out, + SetBuild& build) { + auto too_wide = [] { + return GbnfLimit("the grammar's rule references expand past " + + std::to_string(kMaxClosureWork) + " stack elements at one position"); + }; + std::vector todo; + todo.push_back(stack); + size_t pushed = stack.size() + 1; + build.work.add(stack.size() + kStackCost); + + while (!todo.empty()) { + GbnfStack curr = std::move(todo.back()); + todo.pop_back(); + if (!build.seen.insert(curr).second) continue; + build.seen_elems += curr.size() + 1; + if (build.seen_elems > kMaxClosureWork) throw too_wide(); + + if (curr.empty()) { + build.insert(out, std::move(curr)); + continue; + } + + const GbnfElement* pos = curr.back(); + switch (pos->type) { + case GRE_RULE_REF: { + const size_t rule_id = (size_t)pos->value; + const GbnfElement* subpos = rules.rule(rule_id); + for (;;) { + pushed += curr.size() + 1; + if (pushed > kMaxClosureWork) throw too_wide(); + build.work.add(curr.size() + kStackCost); + GbnfStack next(curr.begin(), curr.end() - 1); + if (!is_end_of_sequence(pos + 1)) next.push_back(pos + 1); + if (!is_end_of_sequence(subpos)) next.push_back(subpos); + todo.push_back(std::move(next)); + while (!is_end_of_sequence(subpos)) subpos++; + if (subpos->type == GRE_ALT) subpos++; + else break; + } + break; + } + case GRE_CHAR: case GRE_CHAR_NOT: case GRE_CHAR_ANY: + case GRE_TOKEN: case GRE_TOKEN_NOT: + build.insert(out, std::move(curr)); + break; + default: + /* END, ALT, CHAR_ALT and CHAR_RNG_UPPER can never be the top of a stack. Reaching + * one is a broken invariant in this file, not a runtime condition, so it aborts + * rather than returning a status nobody could act on. */ + fatal("gbnf: stack left on element type %d, which cannot be a stack top", + (int)pos->type); + } + } +} + +} /* namespace gbnf */ + +/* LEFT RECURSION MAKES advance_stack GROW A STACK FOREVER, so it is found up front rather than + * run into. Returns the index of a rule on such a cycle, or -1. + * + * The epsilon closure expands the rule reference on top of a stack into the first element of + * each alternative, and when that first element can match nothing it moves on to the second -- + * so a reference is in a rule's LEFT CORNER if everything before it in its alternative is + * NULLABLE. Expanding a reference also pushes whatever follows it in the alternative, unless it + * is the last element; so following a left-corner reference grows the stack by one exactly when + * it is not in TAIL position. A cycle of left-corner references therefore grows the stack without + * end iff one of its references is not in tail position. A cycle of tail references only revisits + * stacks it has already seen, which the closure's `seen` set stops -- `S ::= ("a"?)*` is such a + * cycle, and runs. + * + * NULLABILITY IS A FIXED POINT, not a property of one rule read on its own: `e ::= f` is nullable + * because `f ::= "b" |` is, and a check that only recognises an empty alternative misses + * `root ::= e root "c" | "a"` and hangs on it. It is computed with a worklist, and the cycle + * search is an iterative strongly-connected-components pass, so both are linear in the grammar + * and neither recurses: a 100,000-rule chain is a 100,000-frame recursion otherwise. */ +static int64_t find_left_recursion(const GbnfRules& rules) { + const size_t n = rules.size(); + + /* 1. Which rules can match the empty string. An alternative with a terminal in it never can; + * one made only of rule references can once each of them can, so it waits on a count. */ + std::vector nullable(n, 0); + std::vector alt_owner, alt_pending, work; + std::vector> waiting(n); /* rule -> alternatives it holds up */ + for (size_t r = 0; r < n; ++r) { + const GbnfRule& rule = rules[r]; + for (size_t i = 0; i < rule.size(); ) { + bool terminal = false; + uint32_t refs = 0; + size_t j = i; + for (; !is_end_of_sequence(&rule[j]); ++j) { + if (rule[j].type == GRE_RULE_REF) ++refs; + else terminal = true; + } + if (!terminal) { + if (refs == 0) { + if (!nullable[r]) { nullable[r] = 1; work.push_back((uint32_t)r); } + } else { + const uint32_t a = (uint32_t)alt_owner.size(); + alt_owner.push_back((uint32_t)r); + alt_pending.push_back(refs); + for (size_t k = i; k < j; ++k) waiting[rule[k].value].push_back(a); + } + } + i = j + 1; + if (rule[j].type == GRE_END) break; + } + } + while (!work.empty()) { + const uint32_t s = work.back(); + work.pop_back(); + for (uint32_t a : waiting[s]) { + if (--alt_pending[a] != 0) continue; + const uint32_t r = alt_owner[a]; + if (!nullable[r]) { nullable[r] = 1; work.push_back(r); } + } + } + waiting = {}; + + /* 2. The left-corner graph, one edge per reference that can come first, marked by whether it + * is in tail position. */ + struct Edge { uint32_t to; bool grows; }; + std::vector edge_off(n + 1, 0); + std::vector edges; + for (size_t r = 0; r < n; ++r) { + const GbnfRule& rule = rules[r]; + bool open = true; + for (size_t i = 0; i < rule.size(); ++i) { + const GbnfElement& e = rule[i]; + if (is_end_of_sequence(&e)) { open = true; continue; } + if (!open) continue; + if (e.type != GRE_RULE_REF) { open = false; continue; } + edges.push_back({ e.value, !is_end_of_sequence(&rule[i + 1]) }); + if (!nullable[e.value]) open = false; + } + edge_off[r + 1] = edges.size(); + } + + /* 3. Strongly connected components (Tarjan's, with an explicit call stack). A growing edge + * between two rules of one component -- a self-loop included -- is the cycle. */ + std::vector idx(n, -1), low(n, 0), comp(n, -1); + std::vector on_stack(n, 0); + std::vector scc; + struct Frame { uint32_t v; size_t e; }; + std::vector call; + int32_t counter = 0, n_comp = 0; + for (size_t root = 0; root < n; ++root) { + if (idx[root] >= 0) continue; + idx[root] = low[root] = counter++; + scc.push_back((uint32_t)root); + on_stack[root] = 1; + call.push_back({ (uint32_t)root, edge_off[root] }); + while (!call.empty()) { + const uint32_t v = call.back().v; + if (call.back().e < edge_off[v + 1]) { + const uint32_t w = edges[call.back().e++].to; + if (idx[w] < 0) { + idx[w] = low[w] = counter++; + scc.push_back(w); + on_stack[w] = 1; + call.push_back({ w, edge_off[w] }); + } else if (on_stack[w]) { + low[v] = std::min(low[v], idx[w]); + } + continue; + } + call.pop_back(); + if (!call.empty()) low[call.back().v] = std::min(low[call.back().v], low[v]); + if (low[v] == idx[v]) { + uint32_t w; + do { + w = scc.back(); + scc.pop_back(); + on_stack[w] = 0; + comp[w] = n_comp; + } while (w != v); + ++n_comp; + } + } + } + + for (size_t r = 0; r < n; ++r) + for (size_t k = edge_off[r]; k < edge_off[r + 1]; ++k) + if (edges[k].grows && comp[edges[k].to] == comp[r]) return (int64_t)r; + return -1; +} + +/* ================================================================== the compiled program */ + +/* THE COMPILED GRAMMAR IS NOT PER-REQUEST. + * + * Everything here is a pure function of (grammar text, root, vocabulary): the rules, the initial + * stack set, the mask plan, and the token mask each reachable state admits. None of it depends on + * which request is asking. A GbnfGrammar is created per request all the same, because the + * POSITION in the program is per-request; what a grammar must NOT carry is a private copy of the + * program, or an agent that calls the same tool twenty times parses the same grammar twenty times + * and builds the same plan twenty times over. + * + * So the program is shared, and three things fall out of that beyond the obvious one: every + * TENSOR-PARALLEL RANK shares one plan and one mask cache (the ranks hold separate grammars over + * the same program and ask for the same full-vocabulary mask, so every rank past the first is a + * hit); a state one request reached is a state no later request recomputes; and the plan -- the + * expensive part, built once per grammar -- is built on the thread that ADMITS the first request + * for it, which is never the scheduler thread. + * + * The stacks hold pointers into `rules`, so `rules` is immutable after publication and the + * program is held by shared_ptr: a live grammar keeps its program alive even after the cache has + * stopped pinning it, and those pointers are what makes a state comparable across requests at + * all. */ +struct GbnfState { + GbnfStacks stacks; /* sorted, so the key does not depend on the order a walk produced */ + PartialUtf8 partial; + bool allow_eog = false; + int64_t words = 0; + + bool operator==(const GbnfState& o) const { + return allow_eog == o.allow_eog && words == o.words && + partial.value == o.partial.value && partial.n_remain == o.partial.n_remain && + stacks == o.stacks; + } +}; + +struct GbnfStateHash { + size_t operator()(const GbnfState& k) const { + size_t h = 1469598103934665603ull; + auto mix = [&h](size_t v) { h ^= v; h *= 1099511628211ull; }; + for (const GbnfStack& s : k.stacks) { + mix(s.size()); + for (const GbnfElement* e : s) mix((size_t)e); + } + mix(k.partial.value); + mix((size_t)(k.partial.n_remain + 1)); + mix(k.allow_eog ? 1u : 0u); + mix((size_t)k.words); + return h; + } +}; + +struct GbnfProgram { + GbnfRuleSet rules; + GbnfStacks start; /* the root's alternates, advanced once */ + gbnf::MaskPlanPtr plan; /* see gbnf_mask.cpp */ + GbnfProgramInfo info; + + /* Masks computed rather than served from the memo below, for the sampler's instrument. + * Atomic because it is read and written off the lock; relaxed because it is a counter and + * nothing is ordered against it. */ + mutable std::atomic computed{0}; + + /* THE MASK CACHE IS SHARED BETWEEN THREADS: every rank reaches it. A mask is a few kilobytes, + * so entries are handed out by value under the lock and computed OUTSIDE it -- two threads + * racing the same state both compute it and agree, which wastes a plan lookup and cannot + * produce a wrong mask. It saves every rank past the first the plan work for a state, and a + * speculative window revisiting a state the work again. */ + mutable std::mutex mu; + struct Entry { std::vector mask; uint64_t used = 0; }; + mutable std::unordered_map masks; + mutable uint64_t clock = 0; + + /* A tool-calling schema's working set is on the order of a hundred states; 512 is room for a + * schema several times larger, at a few megabytes of host memory for a large vocabulary. Past + * it, evict the least recently used -- a linear scan, on a path that only runs behind a mask + * that was computed. */ + static constexpr size_t kMaxMasks = 512; + + bool lookup(const GbnfState& k, uint32_t* dst, int64_t n_words) const { + std::lock_guard lk(mu); + auto it = masks.find(k); + if (it == masks.end()) return false; + it->second.used = ++clock; + std::memcpy(dst, it->second.mask.data(), (size_t)n_words * sizeof(uint32_t)); + return true; + } + + void store(const GbnfState& k, const uint32_t* src, int64_t n_words) const { + std::lock_guard lk(mu); + if (masks.size() >= kMaxMasks && !masks.count(k)) { + auto victim = masks.begin(); + for (auto it = masks.begin(); it != masks.end(); ++it) + if (it->second.used < victim->second.used) victim = it; + masks.erase(victim); + } + Entry& e = masks[k]; + e.mask.assign(src, src + n_words); + e.used = ++clock; + } +}; + +const GbnfRuleSet& gbnf::program_rules(const GbnfProgram& p) { return p.rules; } + +GbnfProgramInfo gbnf_program_info(const GbnfProgram& p) { return p.info; } + +namespace { + +/* Thirty-two schemas PINNED PER VOCABULARY. Capped because the key comes from client requests: a + * caller sending a thousand distinct schemas must not be able to grow this without bound. */ +constexpr size_t kMaxPrograms = 32; + +/* Unpin the least recently used past either cap, and forget what nothing holds any more. The + * caller holds C.mu. */ +void cache_trim(VocabGbnf& C) { + for (;;) { + size_t pinned = 0, bytes = 0; + auto victim = C.programs.end(); + for (auto it = C.programs.begin(); it != C.programs.end(); ++it) { + if (!it->second.pinned) continue; + ++pinned; + bytes += it->second.pinned->info.bytes; + if (victim == C.programs.end() || it->second.used < victim->second.used) victim = it; + } + if (pinned <= kMaxPrograms && (bytes <= gbnf::kMaxPinnedBytes || pinned <= 1)) break; + victim->second.pinned.reset(); + } + for (auto it = C.programs.begin(); it != C.programs.end();) { + if (!it->second.pinned && it->second.alive.expired()) it = C.programs.erase(it); + else ++it; + } +} + +/* The program for (text, root) if one is pinned or still alive, re-pinned as the most recently + * used. The caller holds C.mu. */ +std::shared_ptr cache_find(VocabGbnf& C, + const std::pair& key) { + auto it = C.programs.find(key); + if (it == C.programs.end()) return nullptr; + const bool was_pinned = (bool)it->second.pinned; + std::shared_ptr p = + was_pinned ? it->second.pinned : it->second.alive.lock(); + if (!p) { + C.programs.erase(it); + return nullptr; + } + it->second.pinned = p; + it->second.used = ++C.clock; + if (!was_pinned) cache_trim(C); + return p; +} + +} /* namespace */ + +static int program_for_impl(const std::string& text, const std::string& root, + const VocabView* vocab, std::shared_ptr* out, + std::string* err) { + /* KEYED ON (text, root) INSIDE THE VOCABULARY'S OWN CACHE, and not on (text, root, address) + * in a table outside it. A compiled program embeds the vocabulary index and a plan over it, + * so a table keyed on an address serves one vocabulary's whole compiled grammar to whichever + * later view lands in the same storage -- and the mask that comes out is over a vocabulary + * the request is not sampling from. */ + VocabGbnf& C = gbnf_cache_for(vocab); + const std::pair key{ text, root }; + { + std::lock_guard lk(C.mu); + if (auto hit = cache_find(C, key)) { + *out = std::move(hit); + return RAD_OK; + } + } + + /* Compiled outside the lock: two callers racing the same new grammar would otherwise + * serialise behind the plan build. The loser's copy is dropped on insert. */ + const auto t0 = std::chrono::steady_clock::now(); + GbnfParser parser(vocab); + std::string perr; + const int st = parser.parse(text.c_str(), &perr); + if (st < 0) { + if (err) *err = "grammar parse failed: " + perr; + return st; + } + if (parser.rules().empty()) { + if (err) *err = "grammar is empty"; + return RAD_E_FORMAT; + } + + auto sym = parser.symbol_ids().find(root); + if (sym == parser.symbol_ids().end()) { + if (err) *err = "grammar does not contain a '" + root + "' symbol"; + return RAD_E_NOTFOUND; + } + + std::vector names(parser.rules().size()); + for (const auto& kv : parser.symbol_ids()) + if (kv.second < names.size()) names[kv.second] = kv.first; + + const int64_t lr = find_left_recursion(parser.rules()); + if (lr >= 0) { + if (err) { + const std::string name = names[(size_t)lr].empty() + ? "#" + std::to_string(lr) + : "'" + names[(size_t)lr] + "'"; + *err = "left recursion through rule " + name + "; this state machine is a pushdown " + "automaton and cannot run one"; + } + return RAD_E_UNSUPPORTED; + } + + /* `rules` is final from here: the stacks hold pointers INTO it, so any later reallocation + * would dangle every one of them. Upstream makes the same point with a move. */ + auto p = std::make_shared(); + for (const GbnfRule& r : parser.rules()) { + p->rules.start.push_back((uint32_t)p->rules.elems.size()); + p->rules.elems.insert(p->rules.elems.end(), r.begin(), r.end()); + } + + const GbnfElement* pos = p->rules.rule(sym->second); + OpWork start_work; + SetBuild start_set(start_work); + for (;;) { + GbnfStack stack; + if (!is_end_of_sequence(pos)) stack.push_back(pos); + advance_stack(p->rules, stack, p->start, start_set); + while (!is_end_of_sequence(pos)) pos++; + if (pos->type == GRE_ALT) pos++; + else break; + } + + gbnf::PlanStats ps; + const int bs = gbnf::plan_build(p->rules, sym->second, vocab_index_for(vocab), &names, + &p->plan, &ps, err); + if (bs < 0) return bs; + + GbnfProgramInfo& info = p->info; + info.rules = p->rules.n_rules(); + info.elements = p->rules.elems.size(); + info.plan_ms = ps.ms; + info.plan_work = ps.work; + info.keys = ps.keys; + info.dense_masks = ps.dense; + info.max_key_depth = ps.max_depth; + info.rem_nodes = ps.rem_nodes; + info.max_rem_nodes = ps.max_rem; + info.bytes = ps.bytes + p->rules.elems.size() * sizeof(GbnfElement); + info.compile_ms = std::chrono::duration( + std::chrono::steady_clock::now() - t0).count(); + RAD_INFO("gbnf: compiled a grammar of %zu rules in %.1f ms: %zu mask keys (%zu dense, %zu " + "deep at most), %zu remainder nodes, %.1f MiB", info.rules, info.compile_ms, + info.keys, info.dense_masks, info.max_key_depth, info.rem_nodes, + (double)info.bytes / (1024.0 * 1024.0)); + + std::lock_guard lk(C.mu); + if (auto hit = cache_find(C, key)) { /* another thread won the race; use its copy */ + *out = std::move(hit); + return RAD_OK; + } + C.programs[key] = VocabGbnf::Cached{ p, p, ++C.clock }; + cache_trim(C); + *out = std::move(p); + return RAD_OK; +} + +/* NOTHING THROWN WHILE COMPILING LEAVES HERE. The parser catches its own errors, but the stack + * machinery after it throws GbnfLimit on a grammar that outgrows its bounds, and any step can run + * out of memory -- and this runs on the thread that admits the request, where an escaping + * exception is std::terminate for every request on the server. */ +static int program_for(const std::string& text, const std::string& root, const VocabView* vocab, + std::shared_ptr* out, std::string* err) { + try { + return program_for_impl(text, root, vocab, out, err); + } catch (const GbnfLimit& e) { + if (err) *err = std::string("the grammar cannot be run within its bounds: ") + e.what(); + return RAD_E_UNSUPPORTED; + } catch (const std::bad_alloc&) { + if (err) *err = "out of memory compiling the grammar"; + return RAD_E_NOMEM; + } catch (const std::exception& e) { + if (err) *err = std::string("the grammar could not be compiled: ") + e.what(); + return RAD_E_FORMAT; + } +} + +int gbnf_compile(const std::string& text, const std::string& root, const VocabView* vocab, + std::shared_ptr* out, std::string* err) { + if (!vocab || !out) return RAD_E_INVAL; + return program_for(text, root, vocab, out, err); +} + +/* ================================================================== the grammar */ + +int GbnfGrammar::create(const std::string& text, const std::string& root, const VocabView* vocab, + bool lazy, + const std::vector& trigger_words, + const std::vector& trigger_tokens, + std::unique_ptr* out, std::string* err) { + if (!out) return RAD_E_INVAL; + + /* The parse, the left-recursion check and the initial stack set are all shared, and so is the + * mask cache behind them: this is a lookup on the second request that asks for the same + * schema. What stays per-request is the position in the program and the triggers. */ + std::shared_ptr prog; + const int st = program_for(text, root, vocab, &prog, err); + if (st < 0) return st; + + try { + auto g = std::unique_ptr(new GbnfGrammar()); + g->vocab_ = vocab; + g->prog_ = prog; + g->stacks_ = prog->start; + + g->awaiting_trigger_ = lazy; + g->trigger_tokens_ = trigger_tokens; + if (!trigger_words.empty()) { + auto sc = std::make_shared(); + const int bs = sc->build(trigger_words, err); + if (bs < 0) return bs; + g->scanner_ = std::move(sc); + } + + *out = std::move(g); + } catch (const std::bad_alloc&) { + if (err) *err = "out of memory creating the grammar"; + return RAD_E_NOMEM; + } + return RAD_OK; +} + +uint64_t GbnfGrammar::masks_walked() const { + return prog_ ? prog_->computed.load(std::memory_order_relaxed) : 0; +} + +bool GbnfGrammar::complete() const { + for (const auto& s : stacks_) if (s.empty()) return true; + return false; +} + +static void accept_chr(const GbnfRuleSet& rules, const GbnfStack& stack, uint32_t chr, + GbnfStacks& out, SetBuild& build) { + if (stack.empty()) return; + const GbnfElement* pos = stack.back(); + if (pos->type == GRE_TOKEN || pos->type == GRE_TOKEN_NOT) return; + + auto m = match_char(pos, chr); + build.work.add((size_t)(m.second - pos)); + if (!m.first) return; + + GbnfStack next(stack.begin(), stack.end() - 1); + if (!is_end_of_sequence(m.second)) next.push_back(m.second); + advance_stack(rules, next, out, build); +} + +/* A grammar that outgrew its bounds while accepting cannot be continued: the state it would be + * in was never built. It is left with no live stack, so the next mask reports it and the request + * is failed there, and the status says which of the two this was. A speculative walk rewinds + * over it like any other refusal. */ +int GbnfGrammar::accept_token_piece(int32_t token, const std::string& piece) { + try { + return accept_token_piece_impl(token, piece); + } catch (const GbnfLimit& e) { + RAD_WARN("gbnf: token %d cannot be accepted: %s; the request cannot be continued", + token, e.what()); + stacks_.clear(); + return RAD_E_FULL; + } catch (const std::bad_alloc&) { + RAD_ERR("gbnf: out of memory accepting token %d; the request cannot be continued", token); + stacks_.clear(); + return RAD_E_NOMEM; + } +} + +int GbnfGrammar::accept_token_piece_impl(int32_t token, const std::string& piece) { + const auto decoded = decode_utf8(piece, partial_utf8_); + const auto& cps = decoded.first; + + OpWork work; + GbnfStacks new_stacks; + SetBuild new_set(work); + new_stacks.reserve(stacks_.size()); + + /* THE STACKS THAT MATCH CODE POINTS ARE ADVANCED TOGETHER, one code point at a time, as + * accept_str does. Advancing each through the whole piece on its own gives the same set -- + * the union of the parts is the part of the union -- but when many stacks converge on one + * continuation, as every alternative of a wide rule does once it matches, each of them + * re-expands that continuation, and the token costs the square of the width. */ + GbnfStacks current; + for (const auto& stack : stacks_) { + if (stack.empty()) continue; + const GbnfElement* pos = stack.back(); + + if (pos->type == GRE_TOKEN || pos->type == GRE_TOKEN_NOT) { + if (!match_token(pos, token)) continue; + GbnfStack next(stack.begin(), stack.end() - 1); + if (!is_end_of_sequence(pos + 1)) next.push_back(pos + 1); + advance_stack(prog_->rules, next, new_stacks, new_set); + } else { + current.push_back(stack); + } + } + for (auto it = cps.begin(), end = cps.end() - 1; it != end && !current.empty(); ++it) { + GbnfStacks next; + SetBuild next_set(work); + for (const auto& cs : current) accept_chr(prog_->rules, cs, *it, next, next_set); + current = std::move(next); + } + for (auto& s : current) new_set.insert(new_stacks, std::move(s)); + + stacks_ = std::move(new_stacks); + partial_utf8_ = decoded.second; + + if (stacks_.empty()) { + /* NOT AN ERROR HERE, WHICH IS WHY IT LOGS AT DEBUG. This is reached as a matter of course + * by the SPECULATIVE WALK: Sampler::build_step advances the grammar over each PROPOSAL to + * mask the position behind it, and a drafter is free to propose a token the grammar + * forbids -- that is precisely what verification is for, and build_step handles it by + * setting `dead` and masking no further. A speculative window on a constrained request + * reaches this many times a second while behaving perfectly, producing correct, closed + * JSON and stopping cleanly. At error level it reads as a defect and is not one. + * + * A token that is genuinely EMITTED against the mask IS a defect, and only the engine can + * tell the two apart -- it alone knows the token was verified and is leaving. Engine::step + * checks this status on the post-verification accept and reports it there, which is why + * that status must not be dropped. */ + RAD_DEBUG("gbnf: token %d (\"%s\") left no live stack", token, piece.c_str()); + return RAD_E_STATE; + } + return RAD_OK; +} + +int GbnfGrammar::accept_token(int32_t token) { + if (!vocab_) return RAD_E_STATE; + const std::string& piece = vocab_->token_piece(token); + + if (awaiting_trigger_) { + if (std::find(trigger_tokens_.begin(), trigger_tokens_.end(), token) + != trigger_tokens_.end()) { + awaiting_trigger_ = false; + recent_.clear(); + return accept_token_piece(token, piece); + } + if (!scanner_) return RAD_OK; + + recent_.push_back(Recent{ token, scan_.off }); + const uint64_t start = scanner_->feed(scan_, piece.data(), piece.size()); + if (start == WordScanner::npos) { + /* Keep only the tokens a word completing later could begin in: one that ends at or + * before (fed - longest + 1) cannot hold the first byte of any word still to come. */ + const uint64_t reach = scanner_->max_len() - 1; + const uint64_t keep = scan_.off > reach ? scan_.off - reach : 0; + size_t drop = 0; + while (drop < recent_.size()) { + const uint64_t end = drop + 1 < recent_.size() ? recent_[drop + 1].start : scan_.off; + if (end > keep) break; + ++drop; + } + if (drop) recent_.erase(recent_.begin(), recent_.begin() + (ptrdiff_t)drop); + return RAD_OK; + } + + /* Replay from the first byte of the word, splitting the token it begins inside: the bytes + * in front of it were free-form output and the grammar never claimed them. */ + awaiting_trigger_ = false; + std::vector replay; + replay.swap(recent_); + for (size_t i = 0; i < replay.size(); ++i) { + const uint64_t ts = replay[i].start; + const uint64_t te = i + 1 < replay.size() ? replay[i + 1].start : scan_.off; + if (te <= start) continue; + const std::string& pc = vocab_->token_piece(replay[i].token); + if (ts >= start) { + RAD_TRY(accept_token_piece(replay[i].token, pc)); + } else { + RAD_TRY(accept_token_piece(replay[i].token, pc.substr((size_t)(start - ts)))); + } + } + return RAD_OK; + } + + if (vocab_->is_eog(token)) { + if (complete()) return RAD_OK; + /* DEBUG FOR THE SAME REASON AS "left no live stack" in accept_token_piece. The mask admits + * an end-of-generation token only once a stack has completed, so an emitted one does not + * land here; what does is the speculative walk over a drafter's PROPOSAL, and a drafter + * proposes the end of the turn whenever the text looks finished -- often, on a reply that + * its token limit cuts off mid-structure. The emitted case is the defect, and + * Engine::step reports it from this status. */ + RAD_DEBUG("gbnf: end-of-generation token %d offered while no stack had completed", token); + return RAD_E_STATE; + } + + return accept_token_piece(token, piece); +} + +int GbnfGrammar::accept_str(const std::string& piece) { + const auto decoded = decode_utf8(piece, partial_utf8_); + const auto& cps = decoded.first; + + try { + OpWork work; + for (auto it = cps.begin(), end = cps.end() - 1; it != end; ++it) { + GbnfStacks next; + SetBuild next_set(work); + for (const auto& s : stacks_) accept_chr(prog_->rules, s, *it, next, next_set); + stacks_ = std::move(next); + if (stacks_.empty()) { + RAD_ERR("gbnf: the string \"%s\" is not admitted by the grammar", piece.c_str()); + return RAD_E_STATE; + } + } + } catch (const GbnfLimit& e) { + RAD_ERR("gbnf: the string \"%s\" cannot be accepted: %s", piece.c_str(), e.what()); + stacks_.clear(); + return RAD_E_FULL; + } catch (const std::bad_alloc&) { + RAD_ERR("gbnf: out of memory accepting the string \"%s\"", piece.c_str()); + stacks_.clear(); + return RAD_E_NOMEM; + } + partial_utf8_ = decoded.second; + return RAD_OK; +} + + +void GbnfGrammar::push_state() { + saved_.push_back(Snapshot{ stacks_, partial_utf8_, awaiting_trigger_, scan_, recent_ }); +} + +int GbnfGrammar::rollback() { + if (saved_.empty()) { + RAD_ERR("gbnf: rollback with nothing pushed"); + return RAD_E_STATE; + } + Snapshot& s = saved_.back(); + stacks_ = std::move(s.stacks); + partial_utf8_ = s.partial; + awaiting_trigger_ = s.awaiting_trigger; + scan_ = s.scan; + recent_ = std::move(s.recent); + saved_.pop_back(); + return RAD_OK; +} + +/* The cache key for the state the machine is in right now. */ +GbnfState GbnfGrammar::state_key(bool allow_eog, int64_t n_words) const { + GbnfState k; + k.stacks = stacks_; + k.partial = partial_utf8_; + k.allow_eog = allow_eog; + k.words = n_words; + std::sort(k.stacks.begin(), k.stacks.end()); + return k; +} + +/* The mask for the current state, with no memo. */ +int GbnfGrammar::mask_compute(uint32_t* bitmask, int64_t n_words) const { + std::fill(bitmask, bitmask + n_words, 0u); + + /* A DEAD STACK SET ADMITS NOTHING. It is reachable: accept_token_piece assigns the empty set + * on the paths where it reports a failure, so anything that keeps asking for masks after that + * arrives here, and the answer is the status the state deserves -- not a mask. */ + if (stacks_.empty()) { + RAD_ERR("gbnf: the grammar has no live parse left; the request cannot be continued"); + return RAD_E_STATE; + } + + /* A mask that outgrows the bounds in "what a grammar may cost" throws from deep inside the + * stack machinery, and this is on the scheduler thread: it becomes a status that fails the + * request, never an exception that ends the process. */ + try { + return gbnf::plan_fill(*prog_->plan, stacks_, partial_utf8_, complete(), bitmask, n_words); + } catch (const GbnfLimit& e) { + RAD_ERR("gbnf: no mask for this position: %s; the request cannot be continued", e.what()); + return RAD_E_FULL; + } catch (const std::bad_alloc&) { + RAD_ERR("gbnf: out of memory building a mask; the request cannot be continued"); + return RAD_E_NOMEM; + } +} + +int GbnfGrammar::fill_mask(uint32_t* bitmask, int64_t n_words) const { + if (!bitmask || !vocab_) return RAD_E_INVAL; + const int64_t n_tok = vocab_->n_tokens(); + if (n_words < bitmask_words(n_tok)) return RAD_E_SHAPE; + + /* A lazy grammar that has not triggered constrains nothing, so every token is admissible and + * the sampler skips the mask op entirely for this sequence. Saying "all ones" rather than + * "no mask" keeps one code path in the driver. */ + if (awaiting_trigger_) { + std::fill(bitmask, bitmask + n_words, 0xFFFFFFFFu); + return RAD_OK; + } + + /* THE STATE CACHE, ahead of the plan. Keyed on everything fill_mask reads that can change -- + * the stack set, the carried partial and allow_eog -- and hashed but then compared EXACTLY, + * because a collision accepted on the hash alone would hand back a mask for a state the + * sequence is not in and admit the wrong token set. The key sorts the stacks: two requests + * that reach the same state by the same path produce the same order anyway, but the sort is + * what makes that a guarantee rather than an observation. */ + const GbnfState key = state_key(complete(), n_words); + if (prog_->lookup(key, bitmask, n_words)) return RAD_OK; + + prog_->computed.fetch_add(1, std::memory_order_relaxed); + const int st = mask_compute(bitmask, n_words); + if (st < 0) return st; + + /* Store only a mask that stands: a dead state is not worth an entry and returns above. */ + prog_->store(key, bitmask, n_words); + return RAD_OK; +} + +} /* namespace rad */ diff --git a/core/sample/gbnf.h b/core/sample/gbnf.h new file mode 100644 index 00000000..e7b43deb --- /dev/null +++ b/core/sample/gbnf.h @@ -0,0 +1,301 @@ +/* gbnf.h -- the GBNF grammar state machine. + * + * LIFTED from llama.cpp `src/llama-grammar.{h,cpp}` at upstream commit 06938ac12 (MIT). It lives + * under core/sample/ rather than vendor/ because it is on the sampling path and the sampler owns + * it; vendor/ belongs to the text frontend. It is vendor-SHAPED all the same: the algorithm is + * upstream's, element for element, and the changes are listed here so a future re-lift knows what + * to re-apply. + * + * What changed and why: + * - `llama_vocab` became `VocabView` (vocab_view.h), so the sampler does not depend on the + * tokeniser's concrete type and a grammar test can state its vocabulary in four lines. + * - `GGML_ASSERT` / `GGML_ABORT` became this project's status returns and `fatal()`. Errors are + * values (docs/IMPLEMENTATION.md); upstream's aborts inside the stack walk stay aborts, + * because they are broken invariants rather than runtime conditions. + * - The parser still throws internally -- it is a recursive-descent parser and that is what + * upstream does -- but nothing escapes: `parse()` catches and returns a status with the + * message in an out-parameter. + * - `llama_grammar_apply_impl`, which edited a candidate array in place, became `fill_mask`, + * which writes a token bitmask. That is the whole reason the state machine stays on host: at + * a 151K vocab the mask is 19 KiB, cheap enough to upload every step, where a candidate array + * is not (spec §13). + * - Everything a client's grammar can make the machine do is BOUNDED (gbnf_internal.h, "what a + * grammar may cost"): what a repetition expands to, how deep parentheses nest, how large a + * stack set grows, how much an epsilon closure explores, how much work one mask, one accepted + * token or one compile does, and how large the automaton and the mask plan grow. A grammar + * past a bound is refused at compile time or fails its request at run time; it never takes + * the process with it. + * - Left recursion is found with nullability computed as a fixed point and an iterative + * strongly-connected-components pass. Upstream's recursive check missed recursion through an + * indirectly nullable rule, and recursed once per rule of a chain. + * - A closure's explored stacks are shared by every closure that builds the same set, the + * stacks that match code points are advanced together rather than one at a time, and a + * large set is de-duplicated through an index. Each gives the same set as upstream; without + * them, stacks that converge on one continuation re-expand it once each. + * - The token mask is not upstream's candidate walk. It is served from a plan precomputed when + * the grammar is compiled (gbnf_mask.cpp): per stack suffix, the tokens it admits whatever lies + * below it, and a small trie of what depends on what does. Upstream's walk survives only as + * the test oracle (tests/gbnf_oracle.cpp), and every mask is held to it bit for bit. + * + * THE COST OF THE MASK IS ON THE STEP. The mask is built on the scheduler thread with the rank + * threads parked at the barrier, so whatever it takes is added to the step time of a constrained + * request -- up to four times a step under speculation. A mask that walks the vocabulary costs + * more than the decode step it sits inside, and a constrained tool call then runs at many times the + * per-token cost of the same model writing prose. + * + * What it costs as written: + * + * - Compiling a grammar builds its mask plan, which walks the vocabulary once per place in the + * grammar a mask can start. That is milliseconds to a few hundred of them, bounded, and done on + * the thread that ADMITS the request (gbnf_compile), never on the scheduler thread. + * - A mask is then a key lookup per live stack, an OR of precomputed token sets, and a walk of + * the few tokens whose admissibility depends on the stack below the key -- the same cost for + * a state seen before and one never seen. A state seen before is also a memcpy from the + * program's mask cache, shared by every request and rank that uses the grammar. + * - The vocabulary index the plan is built over is computed once per vocabulary and shared. + * Nothing is per request and nothing is on the device. + * + * So the state machine stays on host: the cost that would argue for a device-side grammar is a + * mask computed by walking the vocabulary per step, and the answer to that is to precompute the + * walk (XGrammar's adaptive token-mask cache, carried over to this machine's stacks), not a + * different place to run it (spec §13). + */ +#pragma once +#include "../rad_internal.h" +#include "vocab_view.h" +#include "word_scan.h" + +#include +#include +#include +#include +#include + +namespace rad { + +/* ================================================================== grammar elements */ + +enum GreType { + GRE_END = 0, /* end of rule definition */ + GRE_ALT = 1, /* start of an alternate definition */ + GRE_RULE_REF = 2, /* reference to a rule */ + GRE_CHAR = 3, /* terminal: a code point */ + GRE_CHAR_NOT = 4, /* inverse char set: [^a], [^a-b] */ + GRE_CHAR_RNG_UPPER = 5, /* modifies the preceding CHAR into an inclusive range */ + GRE_CHAR_ALT = 6, /* adds an alternate char to the preceding set */ + GRE_CHAR_ANY = 7, /* '.' */ + GRE_TOKEN = 8, /* terminal: a token id, `<[id]>` */ + GRE_TOKEN_NOT = 9 /* inverse token, `!<[id]>` */ +}; + +struct GbnfElement { + GreType type; + uint32_t value; /* code point, rule id, or token id */ +}; + +/* A UTF-8 sequence split across token boundaries. Byte-level BPE emits partial sequences all the + * time, so a grammar that could not carry one between tokens would reject perfectly good text. */ +struct PartialUtf8 { + uint32_t value = 0; /* bits so far, unshifted */ + int n_remain = 0; /* bytes still needed; -1 marks an invalid sequence */ +}; + +using GbnfRule = std::vector; +using GbnfRules = std::vector; +using GbnfStack = std::vector; +using GbnfStacks = std::vector; + +/* THE COMPILED GRAMMAR, SHARED BY EVERY REQUEST THAT ASKS FOR IT, with its mask plan and its mask + * cache. Defined in gbnf.cpp, which says what it is worth; the short version is that nothing + * inside it is per-request. `GbnfState` is the mask cache's key: the whole of what fill_mask + * reads. */ +struct GbnfProgram; +struct GbnfState; + +/* What compiling a grammar cost and what the compiled program holds. */ +struct GbnfProgramInfo { + double compile_ms = 0.0; /* all of it: parse, checks and the mask plan */ + double plan_ms = 0.0; /* of which, the mask plan */ + uint64_t plan_work = 0; /* units the plan charged against its bound */ + size_t rules = 0; + size_t elements = 0; + size_t keys = 0; /* stack suffixes with a precomputed token set */ + size_t dense_masks = 0; /* of those, held as a whole-vocabulary bitmask */ + size_t max_key_depth = 0; /* the deepest suffix, in stack entries */ + size_t rem_nodes = 0; /* nodes across every remainder trie */ + size_t max_rem_nodes = 0; /* the largest remainder trie */ + size_t bytes = 0; /* rules and plan; the mask cache is extra */ +}; + +/* What the vocabulary index cost and holds. */ +struct GbnfVocabInfo { + double build_ms = 0.0; + size_t bytes = 0; +}; + +/* ================================================================== the parser */ + +class GbnfParser { +public: + explicit GbnfParser(const VocabView* vocab = nullptr) : vocab_(vocab) {} + + /* Returns RAD_OK, or RAD_E_FORMAT with the parse error in *err. Never throws out. */ + int parse(const char* src, std::string* err); + + const std::map& symbol_ids() const { return symbol_ids_; } + const GbnfRules& rules() const { return rules_; } + + +private: + const VocabView* vocab_ = nullptr; + std::map symbol_ids_; + GbnfRules rules_; + + /* What the parse has built beyond the text itself, and how deep the parentheses are right + * now. Both are bounded (gbnf_internal.h, "what a grammar may cost"), because the text is + * client data and the parser runs on shared threads. */ + uint64_t budget_used_ = 0; + uint32_t depth_ = 0; + void charge(uint64_t bytes); + + uint32_t get_symbol_id(const char* src, size_t len); + uint32_t generate_symbol_id(const std::string& base); + void add_rule(uint32_t id, const GbnfRule& rule); + + const char* parse_alternates(const char* src, const std::string& rule_name, + uint32_t rule_id, bool is_nested); + const char* parse_sequence(const char* src, const std::string& rule_name, + GbnfRule& rule, bool is_nested); + const char* parse_rule(const char* src); +}; + +/* ================================================================== the state machine */ + +class GbnfGrammar { +public: + /* Build from grammar text. `root` names the start symbol. Returns RAD_OK, or RAD_E_FORMAT / + * RAD_E_NOTFOUND / RAD_E_UNSUPPORTED with the reason in *err -- left recursion is + * RAD_E_UNSUPPORTED, because it is a grammar this machine cannot run rather than one that is + * malformed, and the distinction is what the user needs to fix it. + * + * A LAZY grammar constrains nothing until a trigger fires, which is how a tool-calling + * template stays free-form until the model starts writing a call. A trigger is a token id, or + * a literal word found in the generated bytes; parsing resumes from where the word begins. */ + static int create(const std::string& text, const std::string& root, const VocabView* vocab, + bool lazy, + const std::vector& trigger_words, + const std::vector& trigger_tokens, + std::unique_ptr* out, std::string* err); + + /* Advance the state machine over one accepted token. Returns RAD_OK, or RAD_E_STATE if the + * token left no stack alive -- which means the sampler emitted a token the grammar forbade, + * a bug in the mask rather than in the request. RAD_E_FULL (or RAD_E_NOMEM) means the parse + * outgrew the bounds in gbnf_internal.h: the grammar is left dead, and the request cannot go + * on. */ + int accept_token(int32_t token); + + /* Advance over a raw string, for replaying a prompt prefix into the grammar. */ + int accept_str(const std::string& piece); + + /* Fill a token bitmask: bit set means admissible. `n_words` must be at least + * ceil(n_tokens/32). Returns RAD_OK, or RAD_E_STATE if the grammar admits no token at all, + * which is a dead grammar and must fail the request rather than produce a random token, or + * RAD_E_FULL / RAD_E_NOMEM if the mask outgrew its bounds, which must fail it the same way. */ + int fill_mask(uint32_t* bitmask, int64_t n_words) const; + + /* Some stack has run to completion, so an end-of-generation token is admissible. */ + bool complete() const; + + /* Masks this grammar's PROGRAM has had to compute rather than serve from its memo. Shared + * with every other request on the same program, which is the point: see grammar.h. */ + uint64_t masks_walked() const; + + /* A lazy grammar that has not seen its trigger yet constrains nothing. */ + bool awaiting_trigger() const { return awaiting_trigger_; } + + /* The state as it stands, read-only: what a mask is a function of. The test oracle computes + * the same mask from these by upstream's candidate walk. */ + const GbnfStacks& stacks() const { return stacks_; } + PartialUtf8 partial() const { return partial_utf8_; } + const VocabView* vocab() const { return vocab_; } + const GbnfProgram& program() const { return *prog_; } + + /* PUSH AND POP THE WHOLE MUTABLE STATE, so a speculative window can be walked forward and + * rewound (grammar.h says why). Everything create() fixes -- the rules, the vocabulary, the + * decoded vocabulary, the trigger words -- is absent from the snapshot by construction; + * what is here is exactly what accepting one token can change. The trigger fields are in it + * because a draft token may fire the trigger mid-window, which is a state change like any + * other and has to rewind with the rest. + * + * Nestable, though the sampler only ever needs one level. */ + void push_state(); + int rollback(); + +private: + /* A token that may still hold the start of a trigger word: its id and the stream offset of its + * first byte. It ends where the next one starts, or at the scan's current offset. */ + struct Recent { + int32_t token; + uint64_t start; + }; + + struct Snapshot { + GbnfStacks stacks; + PartialUtf8 partial; + bool awaiting_trigger = false; + WordScanner::State scan; + std::vector recent; + }; + + const VocabView* vocab_ = nullptr; + + /* THE RULES ARE SHARED AND THE POSITION IN THEM IS NOT. `stacks_` holds pointers INTO + * prog_->rules, so the program has to outlive every grammar positioned in it and must never + * be mutated once published -- which is what the shared_ptr and the const are here to say, + * and also why the mask cache can be keyed on those pointers across requests at all. */ + std::shared_ptr prog_; + GbnfStacks stacks_; + PartialUtf8 partial_utf8_{}; + + std::vector saved_; + + GbnfState state_key(bool allow_eog, int64_t n_words) const; + + /* The mask itself, from the program's plan, with no memo. */ + int mask_compute(uint32_t* bitmask, int64_t n_words) const; + + /* THE TRIGGER, while the grammar is lazy and waiting. The words are scanned as the bytes + * arrive and nothing already scanned is kept except the few tokens a word could still be + * starting in -- at most the longest word's length of them -- which is also all a match + * replays. So waiting costs the same on the ten-thousandth token of a reply as on the first, + * and so does copying it into a snapshot. The scanner is fixed at create() and shared by + * every copy of the state. */ + bool awaiting_trigger_ = false; + std::vector trigger_tokens_; + std::shared_ptr scanner_; + WordScanner::State scan_; + std::vector recent_; + + int accept_token_piece(int32_t token, const std::string& piece); + int accept_token_piece_impl(int32_t token, const std::string& piece); +}; + +/* COMPILE A GRAMMAR, on the calling thread, into the program every GbnfGrammar::create for the + * same (text, root, vocabulary) will be served from while `out` -- or any other holder -- keeps it + * alive. This is the whole of the host work a grammar costs before its first mask: the parse, the + * checks and the mask plan. The server calls it on the thread that admits the request, so the + * scheduler thread never compiles. Returns what GbnfGrammar::create returns. */ +int gbnf_compile(const std::string& text, const std::string& root, const VocabView* vocab, + std::shared_ptr* out, std::string* err); + +GbnfProgramInfo gbnf_program_info(const GbnfProgram& p); + +/* Build the vocabulary index every grammar's plan is compiled against, if it is not built yet. + * Worth calling once at startup: otherwise the first grammar to arrive pays for it. */ +int gbnf_prepare_vocab(const VocabView* vocab, GbnfVocabInfo* info); + +/* Words a bitmask needs for this vocabulary. 19 KiB at 151K tokens, which is the number spec §13 + * quotes and the reason the state machine stays on host. */ +inline int64_t bitmask_words(int64_t n_vocab) { return (n_vocab + 31) / 32; } + +} /* namespace rad */ diff --git a/core/sample/gbnf_internal.h b/core/sample/gbnf_internal.h new file mode 100644 index 00000000..1f347013 --- /dev/null +++ b/core/sample/gbnf_internal.h @@ -0,0 +1,335 @@ +/* gbnf_internal.h -- what the GBNF state machine's three translation units share, and nothing + * else includes. + * + * gbnf.cpp the lifted machine: parser, stack machinery, accepting tokens, the compiled + * program and its caches. + * gbnf_mask.cpp the mask engine: the vocabulary index, the stack-set automaton and the + * precomputed mask plan every fill_mask is served from. + * tests/gbnf_oracle.cpp + * upstream's candidate walk, kept as the oracle the mask engine is tested + * against and nowhere on a serving path. + * + * The stack machinery lives here rather than in one of them because all three must run the SAME + * closure and the same character tests: the oracle is a second implementation of the mask, not of + * the parse, and a difference between the two has to mean a defect in the mask engine. + */ +#pragma once +#include "gbnf.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rad { +namespace gbnf { + +/* ============================================================ what a grammar may cost + + * THE GRAMMAR TEXT IS CLIENT DATA, AND IT IS COMPILED AND WALKED ON SHARED THREADS: the HTTP + * thread that admits the request, and the scheduler thread every other request's tokens come + * from. So nothing a grammar says may make either one use unbounded memory, time or stack -- a + * few hundred bytes of text that exhausts the machine is a request that ends every other + * request with it. Every bound below is one of those, and each is set well above what real + * grammars reach: a JSON schema of 500 tool calls compiles to about 1.3 MB of text, 22,000 rules + * and a few megabytes of compiled grammar, nests parentheses two deep, and never holds more than + * about 1,500 stacks at once; a schema nested 128 objects deep holds stacks about 130 frames + * tall. + * + * WHAT A GRAMMAR MAY COMPILE TO, BEYOND ITS OWN TEXT. The parse itself is linear in the text + * except where a construct amplifies it: a repetition copies its operand once per count, and a + * generated rule's name repeats the name of the rule it came from. Those are charged here, so a + * 100 KB literal under `{1999}` is refused before it allocates the 1.6 GB it asks for, and what + * a program in the cache can hold is bounded by its text plus this. */ +inline constexpr uint64_t kMaxCompileBytes = 32ull << 20; + +/* How deeply parentheses may nest. The parser is recursive descent, a pair of frames per level, + * so an unbounded depth is a stack overflow that 40 KB of '(' reaches. */ +inline constexpr uint32_t kMaxNesting = 256; + +/* One SET OF STACKS, which is the whole state of the pushdown automaton at a position: how many + * distinct stacks it may hold, and how many elements across all of them. A grammar can make the + * set grow without end -- ambiguity that forks a stack per token, or a closure whose paths + * multiply -- and every accept, every mask and every cached state copies it. */ +inline constexpr size_t kMaxStacks = 1u << 14; +inline constexpr size_t kMaxSetElems = 1u << 18; + +/* Stack elements one epsilon closure may push while exploring, and one set may hold as explored, + * which bounds the memory a closure holds. A grammar with no left recursion still has closures + * whose PATHS multiply (each level of `r ::= s "x" | s "y"` doubles them), so the set bound above + * is reached only after the exploring has been done; this is what stops it. */ +inline constexpr size_t kMaxClosureWork = 1u << 20; + +/* THE WORK ONE OPERATION MAY DO: one accepted token, one mask. The bounds above cap sizes, and + * sizes do not cap time: a closure pays for every stack it builds, and a walk pays for every trie + * node it visits. So the machinery counts what it does against one budget per operation, in units + * of roughly a nanosecond of the thread it runs on: a stack element copied or a char-range element + * tested is one; creating a stack -- an allocation and an insertion into the explored set -- costs + * kStackCost more. A grammar that needs more than this at one position fails the request rather + * than holding the scheduler thread for more than about half a second. */ +inline constexpr uint64_t kStackCost = 64; +inline constexpr uint64_t kMaxOpWork = 1ull << 29; + +/* THE WORK ONE COMPILE MAY DO, in the same units. Compiling precomputes the mask plan (see + * gbnf_mask.cpp), which walks the vocabulary once for every place in the grammar where a mask can + * start: on a quarter-million-piece vocabulary a tool-calling grammar needs a few tens of millions + * of units, 200 tools about two hundred million, and a string bounded past the length of the + * vocabulary's longest token -- the most a grammar can make the plan walk -- under two billion. + * It runs on the thread that admits the request, never on the scheduler thread, and a grammar + * that needs more than this is refused there, in a few seconds at most. */ +inline constexpr uint64_t kMaxCompileWork = 1ull << 31; + +/* WHAT ONE COMPILED PLAN MAY HOLD: its precomputed masks and remainder tries. A plan is shared by + * every request that uses the grammar and is kept for later ones, so this is what one grammar may + * cost the process while it is cached. A 200-tool grammar holds about 16 MiB on a + * quarter-million-piece vocabulary, and a string bounded past the longest token about 40. */ +inline constexpr size_t kMaxPlanBytes = 64ull << 20; + +/* What the programs a vocabulary's cache keeps PINNED may hold together, beside the count it pins. + * A program some request still holds is kept whatever this says; one that nothing holds is what + * this bounds. */ +inline constexpr size_t kMaxPinnedBytes = 256ull << 20; + +/* The stack-set automaton is a memo that grows as states are discovered, and a grammar whose + * stacks deepen with every token discovers new states forever. Past the soft bound it is dropped + * and rebuilt lazily at the next mask, which costs warm-up and nothing else; the hard bound is + * what one operation may add before it is refused. */ +inline constexpr size_t kMaxDfaElems = 1u << 22; +inline constexpr size_t kMaxDfaWalkElems = 1u << 23; + +/* A bound above was reached. Thrown from inside the stack machinery, which has no status path + * (it is lifted code, recursive in places), and caught at every public entry point, where it + * becomes a status and the request is refused or failed -- never the process. */ +struct GbnfLimit : std::runtime_error { + using std::runtime_error::runtime_error; +}; + +[[noreturn]] void throw_set_limit(); + +/* The work counter for one operation, passed to everything the operation calls. */ +struct OpWork { + uint64_t used = 0; + uint64_t limit = kMaxOpWork; + + void add(uint64_t n) { + used += n; + if (used > limit) over(); + } + +private: + [[noreturn]] void over() const; +}; + +uint64_t stack_hash(const GbnfStack& s); + +struct StackLess { + bool operator()(const GbnfStack& a, const GbnfStack& b) const { + return std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end(), + [](const GbnfElement* pa, const GbnfElement* pb) { return pa < pb; }); + } +}; + +/* ONE STACK SET WHILE IT IS BUILT, shared by every call that adds to that set: its running size, + * which is what makes the set bounds exact rather than per call; the operation it is built for, + * whose work every addition is charged to; and the stacks already explored for it. + * + * THE EXPLORED STACKS ARE THE SET'S, NOT ONE CLOSURE'S. Every stack a closure pops has had its + * whole closure added to the set, so a later closure into the same set that reaches it has + * nothing left to add there. Keeping `seen` per call instead re-derives it every time -- and when + * many stacks converge on one continuation, as every alternative of a wide rule does once it + * matches, that is one full re-expansion per stack, quadratic in a width the bounds allow. The + * set that comes out, and the order it comes out in, are the same either way. */ +struct SetBuild { + explicit SetBuild(OpWork& w) : work(w) {} + + OpWork& work; + size_t stacks = 0, elems = 0; + + std::set seen; + size_t seen_elems = 0; + + void add(size_t stack_size) { + stacks += 1; + elems += stack_size + 1; + if (stacks > kMaxStacks || elems > kMaxSetElems) throw_set_limit(); + } + + /* Append `s` to `out` -- the set this belongs to -- unless it is already there. + * + * A SET OF A FEW STACKS IS SEARCHED, A LARGE ONE IS INDEXED. The search is what the lifted + * code does and is the fastest thing at the sizes real states have; but many stacks that + * converge on one continuation each re-expand it into the same set, and a linear search per + * insertion makes that quadratic in a set size the bounds allow. Past kIndexFrom the set is + * indexed by hash, and the order stacks land in `out` is the same either way. */ + void insert(GbnfStacks& out, GbnfStack s); + +private: + static constexpr size_t kIndexFrom = 16; + std::unordered_multimap index; +}; + +/* ============================================================ UTF-8 */ + +/* One code point from NUL-terminated text. Assumes valid UTF-8 but checks for overrun. */ +std::pair decode_utf8(const char* src); + +/* Decode a piece, carrying an incomplete sequence in from the previous token and out to the next. + * The returned code-point vector is 0-terminated. An invalid sequence leaves no code points and + * a carried state of {0, -1}. */ +std::pair, PartialUtf8> decode_utf8(const std::string& src, + PartialUtf8 partial_start); + +/* ============================================================ elements */ + +inline bool is_end_of_sequence(const GbnfElement* pos) { + return pos->type == GRE_END || pos->type == GRE_ALT; +} + +inline bool is_char_elem(const GbnfElement* pos) { + return pos->type == GRE_CHAR || pos->type == GRE_CHAR_NOT || pos->type == GRE_CHAR_ANY; +} + +inline bool is_token_elem(const GbnfElement* pos) { + return pos->type == GRE_TOKEN || pos->type == GRE_TOKEN_NOT; +} + +/* True iff chr satisfies the char range at pos (regular or inverse), and the element after the + * range. pos must point at a char range element. */ +inline std::pair match_char(const GbnfElement* pos, uint32_t chr) { + bool found = false; + const bool is_positive = pos->type == GRE_CHAR || pos->type == GRE_CHAR_ANY; + do { + if (pos[1].type == GRE_CHAR_RNG_UPPER) { + found = found || (pos->value <= chr && chr <= pos[1].value); + pos += 2; + } else if (pos->type == GRE_CHAR_ANY) { + found = true; + pos += 1; + } else { + found = found || pos->value == chr; + pos += 1; + } + } while (pos->type == GRE_CHAR_ALT); + return { found == is_positive, pos }; +} + +/* True iff SOME completion of a partial UTF-8 sequence could satisfy the range at pos. This is + * what lets a byte-level BPE token that ends mid-codepoint stay admissible. */ +inline bool match_partial_char(const GbnfElement* pos, PartialUtf8 partial) { + const bool is_positive = pos->type == GRE_CHAR || pos->type == GRE_CHAR_ANY; + + const uint32_t partial_value = partial.value; + const int n_remain = partial.n_remain; + if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) return false; + + uint32_t low = partial_value << (n_remain * 6); + const uint32_t high = low | (uint32_t)((1 << (n_remain * 6)) - 1); + if (low == 0) { + if (n_remain == 2) low = 1u << 11; + else if (n_remain == 3) low = 1u << 16; + } + + do { + if (pos[1].type == GRE_CHAR_RNG_UPPER) { + if (pos->value <= high && low <= pos[1].value) return is_positive; + pos += 2; + } else if (pos->type == GRE_CHAR_ANY) { + return true; + } else { + if (low <= pos->value && pos->value <= high) return is_positive; + pos += 1; + } + } while (pos->type == GRE_CHAR_ALT); + + return !is_positive; +} + +/* How many elements the char range at pos spans, which is what one match_char on it costs: it + * walks the whole range whatever the code point. */ +inline size_t char_range_len(const GbnfElement* pos) { + return (size_t)(match_char(pos, 0).second - pos); +} + +inline bool match_token(const GbnfElement* pos, int32_t token) { + if (pos->type == GRE_TOKEN) return pos->value == (uint32_t)token; + if (pos->type == GRE_TOKEN_NOT) return pos->value != (uint32_t)token; + return false; +} + +/* ============================================================ the compiled rules + + * EVERY RULE IN ONE ARENA, so an element's address is also its index. The stacks hold element + * pointers, and the mask engine needs a fact about every element a stack names -- which class of + * continuation it is (gbnf_mask.cpp) -- on every mask; with the rules held as separate vectors + * that is a search per element, with one arena it is a subtraction. The arena is final once the + * program is published: every stack points into it. */ +struct GbnfRuleSet { + std::vector elems; + std::vector start; /* rule id -> index of its first element */ + + const GbnfElement* rule(size_t id) const { return elems.data() + start[id]; } + uint32_t index(const GbnfElement* e) const { return (uint32_t)(e - elems.data()); } + size_t n_rules() const { return start.size(); } +}; + +/* Expand a stack into the N stacks that each end at a terminal. This is the pushdown automaton's + * epsilon closure and it is where rule references are resolved. `build` is `out` while it is + * built; see SetBuild. Throws GbnfLimit past the bounds above. */ +void advance_stack(const GbnfRuleSet& rules, const GbnfStack& stack, GbnfStacks& out, + SetBuild& build); + +/* The rules a compiled program's stacks point into. */ +const GbnfRuleSet& program_rules(const GbnfProgram& p); + +/* ============================================================ the mask engine (gbnf_mask.cpp) */ + +/* Everything the mask engine derives from a vocabulary: each piece decoded to code points, a + * trie over them, and the index of pieces that resume a split character. Built once per + * vocabulary and shared by every grammar compiled against it. */ +struct VocabIndex; + +/* Throws std::bad_alloc; a vocabulary with no text in it builds an empty index. */ +std::shared_ptr vocab_index_build(const VocabView& v); +size_t vocab_index_bytes(const VocabIndex& x); + +/* What compiling a grammar's mask plan cost and holds, for the log line and the acceptance + * tool. */ +struct PlanStats { + double ms = 0.0; /* wall time of the plan build */ + uint64_t work = 0; /* units charged against kMaxCompileWork */ + size_t classes = 0; /* distinct stack-entry classes */ + size_t keys = 0; /* stack suffixes with a precomputed mask */ + size_t max_depth = 0; /* the deepest of them, in stack entries */ + size_t dense = 0; /* of them, held as a full bitmask */ + size_t rem_nodes = 0; /* nodes across every remainder trie */ + size_t max_rem = 0; /* the largest one remainder trie */ + size_t bytes = 0; /* what the plan holds */ +}; + +/* A grammar's compiled mask plan. Its runtime half -- an automaton over stack sets and the scratch + * a mask needs -- is a memo guarded by the plan's own lock, so a plan is shared by every request + * and every rank that uses the grammar. */ +struct MaskPlan; +struct MaskPlanDeleter { void operator()(MaskPlan* p) const; }; +using MaskPlanPtr = std::unique_ptr; + +/* Build the plan for a grammar whose rules are final. Returns RAD_OK or RAD_E_UNSUPPORTED with + * the reason in *err, naming the rule from `rule_names` (by rule id) where it can: a grammar whose + * masks cannot be precomputed within the bounds above is refused here rather than served slowly + * later. Throws GbnfLimit or std::bad_alloc, which the caller turns into a status. */ +int plan_build(const GbnfRuleSet& rules, uint32_t root, const std::shared_ptr& vx, + const std::vector* rule_names, MaskPlanPtr* out, PlanStats* stats, + std::string* err); + +/* The mask for a stack set: bit set means admissible. `n_words` covers the vocabulary. Returns + * RAD_OK, or RAD_E_STATE if no token at all is admissible; throws GbnfLimit past the per-operation + * bounds. Thread-safe: it takes the plan's lock. */ +int plan_fill(const MaskPlan& plan, const GbnfStacks& stacks, PartialUtf8 partial, bool allow_eog, + uint32_t* bitmask, int64_t n_words); + +} /* namespace gbnf */ +} /* namespace rad */ diff --git a/core/sample/gbnf_mask.cpp b/core/sample/gbnf_mask.cpp new file mode 100644 index 00000000..1decc3ce --- /dev/null +++ b/core/sample/gbnf_mask.cpp @@ -0,0 +1,1845 @@ +/* gbnf_mask.cpp -- the token mask, precomputed per grammar so that no mask walks the vocabulary. + * + * THE COST OF A MASK IS ON THE STEP. fill_mask runs on the scheduler thread with the rank threads + * parked at the barrier, so whatever it takes is added to the decode step of a constrained + * request -- up to four times a step under speculation. A mask that descends the whole vocabulary + * trie for a state it has not seen costs milliseconds on a quarter-million-piece vocabulary, and a + * tool call reaches dozens of such states in its first steps. So nothing here descends the whole + * vocabulary at run time: the grammar's compile does that, once per place a mask can start, and a + * mask is assembled from the answers. + * + * WHAT A MASK IS MADE OF. The state is a set of stacks, and a token is admissible iff SOME stack + * admits it, so the mask is the union of one mask per stack. A stack's mask depends on its whole + * contents in principle and on very little of them in practice: a token of a dozen characters + * either stays inside the few frames nearest the top -- a string's content and its closing + * quote, a free-text parameter and its end tag -- or leaves them through a delimiter. So a stack + * S is split into a KEY, the frames nearest its top, and the CONTEXT below them: + * + * S = context ++ key + * mask(S) = accepted(key) U { t : t leaves the key after a prefix u, and the rest of + * t is admitted by the context } + * + * accepted(key) does not depend on the context at all -- every path through the key's own frames + * is a path through S -- so it is computed at compile time, by descending the vocabulary trie + * with the key alone and an explicit bottom marker under it. What leaves the key is the + * REMAINDER: for every token, the text after each point where it pops the key's last frame. Those + * are kept as a small trie of their own, and at run time only that trie is walked, against the + * real context. This is XGrammar's adaptive token mask cache (Dong et al., 2024) -- tokens split + * into accepted, rejected and context-dependent per grammar position, with only the last checked + * at run time -- carried over to a machine whose positions are stack SUFFIXES. + * + * WHY SUFFIXES AND NOT SINGLE ELEMENTS. The parser rewrites `x*` into a rule of its own and a + * group into another, so the element on top of a stack is usually the one character class of a + * one-element rule: `[^"\\]` inside a JSON string is the whole of its rule, and every token longer + * than one character leaves it. Keyed on the top element alone, nearly the whole vocabulary would + * be context-dependent at the positions that matter most. Keyed on the top three frames -- the + * class, the repetition that loops over it and the closing quote below that -- the only tokens that + * leave are the ones that close the string and keep going, a few hundred of them. The depth is + * ADAPTIVE: a key is extended one frame down, into every frame that can sit below it, for as long + * as its remainder is too large to walk on the step, and not otherwise. + * + * WHAT A KEY IS. Stack entries are element pointers, and two entries at different places in the + * rules behave identically when what remains of their alternatives is the same sequence of + * elements -- `"\n"` closes every parameter of every tool, and its entries differ only + * by address. Entries are therefore replaced by their CLASS, the hash-consed remainder of their + * alternative, and keys are sequences of classes. Rules are hash-consed the same way first, so a + * clause a template writes once per tool is one clause; and a repetition longer than the longest + * token is one class whatever its count, because no token can tell the difference. A grammar of + * fifty free-text parameters has one free-text key, not fifty, and `x{0,1000}` costs what + * `x{0,128}` does on a vocabulary whose longest token is 128 characters. + * + * WHAT A MASK THEN COSTS. For each stack: a lookup of its key, a few class comparisons deep; the + * key's accepted set OR'ed in, which is a word-wise OR for a permissive key and a handful of bits + * for a restrictive one; and, where the key has a remainder and the stack has a context, a walk of + * the remainder trie from the context's state, which visits only the remainders the context keeps + * alive. Nothing is proportional to the vocabulary except the OR, and nothing depends on whether + * this state was seen before. + * + * A STATE CARRYING A SPLIT CHARACTER is the one exception to the plan, because what a token means + * depends on the bytes carried in: only tokens that begin with the bytes that finish the + * character are admissible at all. Those are a few hundred pieces in a byte-level vocabulary, kept + * in a trie of their own per number of missing bytes, and walked with the full stack set. + * + * THE AUTOMATON. Every walk here steps a set of stacks over code points. The successor of a set + * depends only on WHICH of its stacks match the code point, and a set's character classes cut the + * code points into a few intervals on which that answer is constant; so each state carries its + * interval boundaries and the successor per interval, built on first use. A trie node's children + * are sorted by code point, so the walk takes a whole run of children per interval -- an interval + * no stack matches is skipped with one binary search, which is what makes a restrictive state + * cost nothing at the vocabulary's widest node. + * + * WHAT IS REFUSED. A grammar whose keys cannot be made small within kMaxKeyDepth frames -- one + * where how much a token may take depends on how deep the parse is, without bound -- or whose + * plan outgrows kMaxCompileWork, kMaxPlanBytes or the bound on one stack set, is refused when it + * is compiled, naming the rule where it can: the alternative would be masks that are slow for as + * long as the grammar is in use. What is refused is ambiguity and unbounded context, which the + * grammars chat templates and the JSON-schema converter write do not have. + */ +#include "gbnf_internal.h" + +#include +#include +#include +#include +#include +#include + +namespace rad { +namespace gbnf { + +namespace { + +constexpr uint32_t kNone = 0xFFFFFFFFu; +constexpr int32_t kUnbuilt = -2; + +/* HOW LARGE A KEY'S REMAINDER MAY BE, which is what the run-time half of a mask may cost for one + * key: a remainder trie is walked from the context's state, and in the worst case -- a context + * that admits every remainder -- visits every node of it. Past either bound the key is extended + * one frame down instead, where more of what leaves it is decided at compile time. */ +constexpr size_t kMaxRemEntries = 1u << 13; +constexpr size_t kMaxRemNodes = 1u << 13; + +/* A walk whose remainder is already far past the bound is stopped where it is: the key will be + * extended whatever the rest of the walk finds, and a key that leaves after its first character + * would otherwise walk the whole vocabulary to learn that. Counted as tokens under the nodes where + * the key has been left, so it is an overestimate and never stops a walk that could have fitted. */ +constexpr uint64_t kAbortRemTokens = 1u << 15; + +/* How many frames a key may span. Real grammars settle within three or four: a string inside its + * repetition inside its quotes, a whitespace run inside its optional. A key still too permissive + * this deep is a grammar whose masks depend on unbounded stack context, which is refused. */ +constexpr uint16_t kMaxKeyDepth = 12; + +inline void set_bit(uint32_t* bits, int32_t id) { + bits[(uint32_t)id >> 5] |= 1u << ((uint32_t)id & 31u); +} + +inline bool test_bit(const uint32_t* bits, int32_t id) { + return (bits[(uint32_t)id >> 5] >> ((uint32_t)id & 31u)) & 1u; +} + +double ms_since(std::chrono::steady_clock::time_point t0) { + return std::chrono::duration(std::chrono::steady_clock::now() - t0) + .count(); +} + +} /* namespace */ + +/* ============================================================ token tries + + * A trie over code-point sequences, one terminal per token. The vocabulary is one; each key's + * remainder is another; the pieces that resume a split character are three more. + * + * Nodes are in BREADTH-FIRST order, which buys two things: a node's children occupy a CONTIGUOUS + * id range, so an edge scan is a sequential read and no child pointers are stored; and a whole + * level is contiguous, so a walk -- which is also breadth-first -- reads the node array front to + * back. ONE STRUCT PER NODE AND NOT FOUR ARRAYS, because a visit reads all four fields; and the + * terminals are held in NODE ORDER, so a level's terminals are read in increasing order too. The + * walk is bound on how it touches memory rather than on work per node, and a pointer-linked + * layout is slower than the rescanning walk a trie exists to replace. + * + * Beside the breadth-first layout, every node knows its subtree's range in LEXICOGRAPHIC order, + * `lo..hi` into `lex`. A walk never reads it; the compile does, to list what is under a node where + * a key has been left, and so does the one construct that admits a whole subtree at once -- a + * token element (`<[id]>`, `!<[id]>`), which matches a token's id wherever it is reached. */ +struct TrieNode { + uint32_t cp; /* the code point on the edge INTO this node */ + uint32_t first; /* its first child's node id */ + uint32_t n_child; /* how many children follow it */ + uint32_t tbeg; /* its first terminal slot; it ends at the NEXT node's tbeg */ +}; + +struct TokenTrie { + std::vector node; /* plus one sentinel, so node[i+1].tbeg is always valid */ + std::vector tid; /* the tokens that end at a node, in node order */ + std::vector ttail; /* and the incomplete sequence each one leaves behind */ + std::vector lo, hi; /* per node: its subtree's range of `lex` */ + std::vector lex; /* token ids in lexicographic order of their sequences */ + std::vector pos; /* token id -> its index in `lex`, when each appears once */ + uint32_t depth = 0; + + size_t n_nodes() const { return node.empty() ? 0 : node.size() - 1; } + size_t bytes() const { + return node.size() * sizeof(TrieNode) + tid.size() * 4 + + ttail.size() * sizeof(PartialUtf8) + + (lo.size() + hi.size() + lex.size() + pos.size()) * 4; + } +}; + +struct TrieEntry { + uint32_t off; /* where the sequence starts in the arena; it runs to a 0 */ + PartialUtf8 tail; + int32_t id; +}; + +/* LEXICOGRAPHIC ORDER IS WHAT MAKES A NODE A RANGE: two sequences share a d-code-point prefix iff + * they are adjacent in this order and agree to depth d, so every node of the trie is a contiguous + * slice of the sorted entries and the build never needs a per-node map. The sequences are + * 0-terminated in the arena, which stops the comparison. */ +static void trie_build(TokenTrie& t, const uint32_t* cps, std::vector& ents, + int32_t unique_over) { + const uint32_t n = (uint32_t)ents.size(); + std::sort(ents.begin(), ents.end(), [cps](const TrieEntry& a, const TrieEntry& b) { + const uint32_t* pa = cps + a.off; + const uint32_t* pb = cps + b.off; + while (*pa != 0 && *pa == *pb) { ++pa; ++pb; } + return *pa < *pb; + }); + + t.lex.resize(n); + for (uint32_t i = 0; i < n; ++i) t.lex[i] = ents[i].id; + t.tid.reserve(n); + t.ttail.reserve(n); + + struct Range { uint32_t lo, hi; }; + std::vector cur, nxt; + t.node.push_back({ 0u, 0u, 0u, 0u }); + t.lo.push_back(0); + t.hi.push_back(n); + cur.push_back({ 0u, n }); + + /* Level d's nodes were appended in the order their ranges appear in `cur`, so node id + * `level_lo + i` is the node whose range is cur[i]. Children are appended in the same sweep, + * which keeps each node's children -- and the next whole level -- contiguous, and makes node + * ids increase with the order nodes are PROCESSED, which the terminal slots depend on. */ + uint32_t level_lo = 0; + for (uint32_t d = 0; !cur.empty(); ++d) { + nxt.clear(); + const uint32_t next_lo = (uint32_t)t.node.size(); + for (size_t ni = 0; ni < cur.size(); ++ni) { + const uint32_t node = level_lo + (uint32_t)ni; + const Range r = cur[ni]; + t.node[node].tbeg = (uint32_t)t.tid.size(); + + uint32_t i = r.lo; + while (i < r.hi && cps[ents[i].off + d] == 0) { /* ends exactly here */ + t.tid.push_back(ents[i].id); + t.ttail.push_back(ents[i].tail); + ++i; + } + const uint32_t base = (uint32_t)t.node.size(); + t.node[node].first = base; + while (i < r.hi) { + const uint32_t c = cps[ents[i].off + d]; + uint32_t j = i + 1; + while (j < r.hi && cps[ents[j].off + d] == c) ++j; + t.node.push_back({ c, 0u, 0u, 0u }); + t.lo.push_back(i); + t.hi.push_back(j); + nxt.push_back({ i, j }); + i = j; + } + t.node[node].n_child = (uint32_t)t.node.size() - base; + } + level_lo = next_lo; + cur.swap(nxt); + t.depth = d + 1; + } + /* The sentinel: the last real node's terminals end here. */ + t.node.push_back({ 0u, 0u, 0u, (uint32_t)t.tid.size() }); + + if (unique_over > 0) { + t.pos.assign((size_t)unique_over, kNone); + for (uint32_t i = 0; i < n; ++i) t.pos[(size_t)t.lex[i]] = i; + } +} + +/* ============================================================ the vocabulary index */ + +struct VocabIndex { + int32_t n_tokens = 0; + std::vector eog; /* end-of-generation: admissible once a stack completes */ + + /* Every piece decoded from a clean start, 0-terminated, in one arena that opens with a pad + * element. `off` is kNone for a token the walk never considers: end-of-generation, and a + * control token with no text, which can satisfy no character. */ + std::vector cps; + std::vector off; + std::vector tail; + TokenTrie trie; + + /* Pieces that decode to no characters and carry nothing out: an overlong sequence for U+0000 + * first, which ends a decoded sequence. Every live stack admits one -- a completed one too, + * which admits nothing else -- so a state with a completed stack admits these whatever its + * keys do. */ + std::vector blank; + + /* THE PIECES THAT RESUME A SPLIT CHARACTER, per number of bytes the carried character still + * needs. With r bytes missing, a piece is admissible only if its first r bytes are + * continuation bytes and the rest decodes on its own; its first code point is then the + * carried bits followed by those r bytes' bits, and everything after it is fixed. So each + * trie's root edges hold the r bytes' bits (plus one, since 0 ends a sequence) and the walk + * ORs the carried bits in. A piece of fewer than r continuation bytes and nothing else leaves + * the character still unfinished, and is admissible iff some stack could still take it. */ + struct Resume { + std::vector cps; + TokenTrie trie; + struct Short { uint32_t bits; int32_t k; int32_t id; }; + std::vector shorts; + }; + Resume resume[3]; + + size_t bytes() const { + size_t b = cps.size() * 4 + off.size() * 4 + tail.size() * sizeof(PartialUtf8) + + (eog.size() + blank.size()) * 4 + trie.bytes(); + for (const Resume& r : resume) + b += r.cps.size() * 4 + r.trie.bytes() + r.shorts.size() * sizeof(Resume::Short); + return b; + } +}; + +size_t vocab_index_bytes(const VocabIndex& x) { return x.bytes(); } + +std::shared_ptr vocab_index_build(const VocabView& v) { + const auto t0 = std::chrono::steady_clock::now(); + auto x = std::make_shared(); + const int32_t n = v.n_tokens(); + x->n_tokens = n > 0 ? n : 0; + x->off.assign((size_t)x->n_tokens, kNone); + x->tail.assign((size_t)x->n_tokens, PartialUtf8{}); + x->cps.push_back(0); + for (auto& r : x->resume) r.cps.push_back(0); + + std::vector ents; + std::vector rents[3]; + ents.reserve((size_t)x->n_tokens); + + for (int32_t id = 0; id < x->n_tokens; ++id) { + if (v.is_eog(id)) { x->eog.push_back(id); continue; } + const std::string& piece = v.token_piece(id); + if (piece.empty() || piece[0] == 0) continue; + + const auto dec = decode_utf8(piece, PartialUtf8{}); + x->off[(size_t)id] = (uint32_t)x->cps.size(); + x->tail[(size_t)id] = dec.second; + x->cps.insert(x->cps.end(), dec.first.begin(), dec.first.end()); + ents.push_back({ x->off[(size_t)id], dec.second, id }); + + /* Leading continuation bytes, and what they contribute to a character carried in. The + * decode reads the piece as a C string, as decode_utf8 does, so a NUL ends the piece: it + * stops the run like any other non-continuation byte, and a piece of continuation bytes + * and then a NUL is as short as the bytes before it. */ + const size_t len = ::strnlen(piece.c_str(), piece.size()); + size_t k = 0; + uint32_t bits = 0; + while (k < len && ((uint8_t)piece[k] >> 6) == 2 && k < 3) { + bits = (bits << 6) | ((uint8_t)piece[k] & 0x3Fu); + ++k; + } + if (k == 0) continue; + const bool more_cont = k < len && ((uint8_t)piece[k] >> 6) == 2; + for (int r = 1; r <= 3; ++r) { + VocabIndex::Resume& R = x->resume[r - 1]; + if ((int)k == r && !more_cont) { + /* Finishes the character with exactly its first r bytes; the rest decodes from a + * clean start, and an invalid rest takes the whole piece with it. */ + const auto rest = decode_utf8(piece.substr((size_t)r), PartialUtf8{}); + if (rest.second.n_remain < 0) continue; + const uint32_t o = (uint32_t)R.cps.size(); + R.cps.push_back(bits + 1); + R.cps.insert(R.cps.end(), rest.first.begin(), rest.first.end()); + rents[r - 1].push_back({ o, rest.second, id }); + } else if ((int)k < r && k == len) { + R.shorts.push_back({ bits, (int32_t)k, id }); + } + } + } + + trie_build(x->trie, x->cps.data(), ents, x->n_tokens); + for (uint32_t k = x->trie.node[0].tbeg; k < x->trie.node[1].tbeg; ++k) + if (x->trie.ttail[k].n_remain == 0) x->blank.push_back(x->trie.tid[k]); + for (int r = 0; r < 3; ++r) + trie_build(x->resume[r].trie, x->resume[r].cps.data(), rents[r], x->n_tokens); + + RAD_DEBUG("gbnf: vocabulary index over %d tokens: trie of %zu nodes, depth %u; %zu/%zu/%zu " + "pieces resume a split character; %.1f MiB, built in %.0f ms", x->n_tokens, + x->trie.n_nodes(), x->trie.depth, x->resume[0].trie.lex.size(), + x->resume[1].trie.lex.size(), x->resume[2].trie.lex.size(), + (double)x->bytes() / (1024.0 * 1024.0), ms_since(t0)); + return x; +} + +/* ============================================================ the stack-set automaton + + * A set of stacks is one state of the pushdown automaton's subset construction: walking the set + * forward is the same answer as walking every stack and OR-ing, because admissibility is the + * existence of a path, and the union of successors is exactly the set of stacks some path reaches. + * States are interned by value, so a set reached twice is one state. + * + * THE SUCCESSOR OF A STACK DOES NOT DEPEND ON THE CODE POINT. Stepping a char-range top pops the + * range and pushes what follows it, which `match_char(top, 0).second` finds whatever the code + * point; the code point decides only WHETHER the stack steps. So each stack's successor is a + * closure computed once per state, and a state's transition depends only on which stacks fire. + * The character classes of a state's tops cut the code points into intervals over which that + * answer is constant, and the successor is kept per interval. A state holds: + * + * ctop the char-range tops, which step over code points and test a carried partial; + * ttop the token tops (`<[id]>`, `!<[id]>`), which match a token's id wherever reached; + * has_empty whether the set holds the empty stack: a completed parse, or -- in a key's walk -- + * the bottom marker, meaning the key has been left. + * + * States live in a deque, so a reference to one survives interning another. */ +class SetDfa { +public: + struct St { + GbnfStacks stacks; + std::vector ctop; + std::vector cstk; /* ctop[i] is stacks[cstk[i]]'s top */ + std::vector ttop; + bool has_empty = false; + size_t elems = 0; + uint64_t match_cost = 0; /* one match_char over every ctop */ + + bool parted = false; + std::vector lo; /* interval starts, lo[0] == 0 */ + std::vector next; /* successor per interval */ + std::vector succ; /* per ctop: the closure after its top */ + std::vector> fired; /* firing pattern -> successor */ + }; + + explicit SetDfa(const GbnfRuleSet* rules) : rules_(rules) {} + + /* The operation whose work every step is charged to, and the mark its growth is measured + * from. */ + void begin(OpWork* w) { work_ = w; walk_base_ = elems_; } + + size_t elems() const { return elems_; } + size_t n_states() const { return st_.size(); } + const St& st(int32_t sid) const { return st_[(size_t)sid]; } + + /* Canonicalise a stack set and return its state, or -1 for the empty set -- the dead state, + * represented by absence so a caller can prune on the sign alone. */ + int32_t intern(GbnfStacks s) { + if (s.empty()) return -1; + /* WHAT A SORT COSTS, which is not its length: n log n comparisons of stacks, each as long + * as the stacks' common prefix. Charged as every element once per level of the sort, so + * a set too wide to sort within the bound is refused rather than sorted anyway. */ + size_t elems = 0; + for (const GbnfStack& k : s) elems += k.size() + 1; + work_->add(elems * (1 + (uint64_t)std::bit_width(s.size()))); + std::sort(s.begin(), s.end()); + s.erase(std::unique(s.begin(), s.end()), s.end()); + return intern_sorted(std::move(s)); + } + + /* The same for a set already sorted and without duplicates. */ + int32_t intern_sorted(GbnfStacks s) { + std::vector ps; + ps.reserve(s.size()); + for (const GbnfStack& k : s) ps.push_back(&k); + return intern_ptrs(ps, &s); + } + + /* The same, from pointers to the stacks. They are copied only if the set is a new state -- + * moved out of `owned` when the caller holds them in a vector of its own. */ + int32_t intern_ptrs(const std::vector& ps, GbnfStacks* owned = nullptr) { + if (ps.empty()) return -1; + uint64_t h = 1469598103934665603ull; + size_t elems = 0; + for (const GbnfStack* k : ps) { + h ^= stack_hash(*k); + h *= 1099511628211ull; + elems += k->size() + 1; + } + work_->add(elems); + auto range = ids_.equal_range(h); + for (auto it = range.first; it != range.second; ++it) { + const GbnfStacks& have = st_[(size_t)it->second].stacks; + work_->add(elems); + if (have.size() != ps.size()) continue; + size_t i = 0; + while (i < ps.size() && have[i] == *ps[i]) ++i; + if (i == ps.size()) return it->second; + } + + if (ps.size() > kMaxStacks || elems > kMaxSetElems) throw_set_limit(); + work_->add(elems + ps.size() * kStackCost); + elems_ += elems; + if (elems_ - walk_base_ > kMaxDfaWalkElems) + throw GbnfLimit("one operation on this grammar discovers more than " + + std::to_string(kMaxDfaWalkElems) + " stack elements of new states"); + + GbnfStacks s; + if (owned) { + s = std::move(*owned); + } else { + s.reserve(ps.size()); + for (const GbnfStack* k : ps) s.push_back(*k); + } + const int32_t id = (int32_t)st_.size(); + st_.emplace_back(); + St& n = st_.back(); + for (size_t i = 0; i < s.size(); ++i) { + if (s[i].empty()) { n.has_empty = true; continue; } + const GbnfElement* top = s[i].back(); + if (is_token_elem(top)) { + n.ttop.push_back(top); + } else { + n.ctop.push_back(top); + n.cstk.push_back((uint32_t)i); + n.match_cost += char_range_len(top); + } + } + n.elems = elems; + n.stacks = std::move(s); + ids_.emplace(h, id); + return id; + } + + /* advance_stack(s) as a state. Memoised on the stack, because many stacks -- in one state or + * in many -- close to the same place: every alternative of a wide rule that has just matched + * returns to one continuation, and every token of a context is resolved from it. */ + int32_t closure(const GbnfStack& s) { + auto it = closure_ids_.find(s); + if (it != closure_ids_.end()) return it->second; + GbnfStacks out; + SetBuild b(*work_); + advance_stack(*rules_, s, out, b); + const int32_t r = intern(std::move(out)); + elems_ += s.size() + 1; + closure_ids_.emplace(s, r); + return r; + } + + /* The state whose stacks are the union of these states' stacks. + * + * The union is memoised on the states united -- a state's successors over two intervals, or + * the closures of two contexts, are united again and again -- and built by MERGING POINTERS: + * every state's stacks are already sorted, so a balanced tree of pairwise merges compares each + * stack once per level where sorting the concatenation would compare them n log n times, and + * no stack is copied until the union turns out to be a state not seen before. The bounds are + * checked after every merge, so a union that will not fit is refused before it is built. */ + int32_t unite(std::vector& ids) { + std::sort(ids.begin(), ids.end()); + ids.erase(std::unique(ids.begin(), ids.end()), ids.end()); + while (!ids.empty() && ids[0] < 0) ids.erase(ids.begin()); + if (ids.empty()) return -1; + if (ids.size() == 1) return ids[0]; + + work_->add(ids.size() * 2); + auto hit = unions_.find(ids); + if (hit != unions_.end()) return hit->second; + + auto less = [](const GbnfStack* a, const GbnfStack* b) { return *a < *b; }; + std::vector> parts(ids.size()); + for (size_t i = 0; i < ids.size(); ++i) { + const St& S = st_[(size_t)ids[i]]; + work_->add(S.stacks.size()); + parts[i].reserve(S.stacks.size()); + for (const GbnfStack& k : S.stacks) parts[i].push_back(&k); + } + while (parts.size() > 1) { + std::vector> next; + next.reserve((parts.size() + 1) / 2); + for (size_t i = 0; i + 1 < parts.size(); i += 2) { + std::vector m; + m.reserve(parts[i].size() + parts[i + 1].size()); + size_t elems = 0; + for (const GbnfStack* k : parts[i]) elems += k->size() + 1; + for (const GbnfStack* k : parts[i + 1]) elems += k->size() + 1; + work_->add(elems); + std::set_union(parts[i].begin(), parts[i].end(), parts[i + 1].begin(), + parts[i + 1].end(), std::back_inserter(m), less); + if (m.size() > kMaxStacks) throw_set_limit(); + next.push_back(std::move(m)); + } + if (parts.size() % 2) next.push_back(std::move(parts.back())); + parts.swap(next); + } + const int32_t r = intern_ptrs(parts[0]); + elems_ += ids.size() + 1; + unions_.emplace(ids, r); + return r; + } + + /* The state's intervals, built on first use: every boundary of every char-range top. Over + * each interval every top either matches every code point or none, because each of its items + * starts or ends at a boundary. */ + const St& parted(int32_t sid) { + St& S = st_[(size_t)sid]; + if (S.parted) return S; + std::vector& b = bounds_; + b.clear(); + b.push_back(0); + for (const GbnfElement* pos : S.ctop) { + do { + if (pos[1].type == GRE_CHAR_RNG_UPPER) { + b.push_back(pos->value); + if (pos[1].value != kNone) b.push_back(pos[1].value + 1); + pos += 2; + } else if (pos->type == GRE_CHAR_ANY) { + pos += 1; + } else { + b.push_back(pos->value); + if (pos->value != kNone) b.push_back(pos->value + 1); + pos += 1; + } + } while (pos->type == GRE_CHAR_ALT); + } + work_->add(b.size() * 4 + S.match_cost); + std::sort(b.begin(), b.end()); + b.erase(std::unique(b.begin(), b.end()), b.end()); + S.lo = b; + S.next.assign(b.size(), kUnbuilt); + S.succ.assign(S.ctop.size(), kUnbuilt); + S.parted = true; + return S; + } + + /* The successor over interval i of a parted state, computed on first use. The firing pattern + * is memoised as well as the interval: many intervals fire the same stacks -- everything + * that is not a quote or a backslash, in a JSON string -- and their union is built once. */ + int32_t next(int32_t sid, size_t i) { + St& S = st_[(size_t)sid]; + if (S.next[i] != kUnbuilt) return S.next[i]; + const uint32_t cp = S.lo[i]; + work_->add(S.match_cost + 4); + + int32_t r; + if (S.ctop.size() <= 64) { + uint64_t fire = 0; + for (size_t j = 0; j < S.ctop.size(); ++j) + if (match_char(S.ctop[j], cp).first) fire |= 1ull << j; + r = -1; + bool found = fire == 0; + for (const auto& e : S.fired) + if (e.first == fire) { r = e.second; found = true; break; } + if (!found) { + std::vector ids; + for (uint64_t m = fire; m; m &= m - 1) + ids.push_back(succ_of(sid, (size_t)__builtin_ctzll(m))); + r = unite(ids); + st_[(size_t)sid].fired.push_back({ fire, r }); + } + } else { + std::vector ids; + for (size_t j = 0; j < S.ctop.size(); ++j) + if (match_char(S.ctop[j], cp).first) ids.push_back(succ_of(sid, j)); + r = unite(ids); + } + st_[(size_t)sid].next[i] = r; + return r; + } + +private: + /* What follows ctop j once it has matched: pop the range, push the element after it, close. */ + int32_t succ_of(int32_t sid, size_t j) { + { + const St& S = st_[(size_t)sid]; + if (S.succ[j] != kUnbuilt) return S.succ[j]; + } + GbnfStack sa; + { + const GbnfStack& s = st_[(size_t)sid].stacks[st_[(size_t)sid].cstk[j]]; + const GbnfElement* after = match_char(s.back(), 0).second; + sa.assign(s.begin(), s.end() - 1); + if (!is_end_of_sequence(after)) sa.push_back(after); + } + const int32_t r = closure(sa); + st_[(size_t)sid].succ[j] = r; + return r; + } + + struct StackHashFn { + size_t operator()(const GbnfStack& s) const { return (size_t)stack_hash(s); } + }; + struct IdsHashFn { + size_t operator()(const std::vector& v) const { + uint64_t h = 1469598103934665603ull; + for (int32_t x : v) { h ^= (uint32_t)x; h *= 1099511628211ull; } + return (size_t)h; + } + }; + + const GbnfRuleSet* rules_ = nullptr; + OpWork* work_ = nullptr; + std::deque st_; + std::unordered_multimap ids_; + std::unordered_map closure_ids_; + std::unordered_map, int32_t, IdsHashFn> unions_; + std::vector bounds_; + size_t elems_ = 0, walk_base_ = 0; +}; + +/* ============================================================ the walk + + * Descend a trie breadth-first carrying one automaton state per live node, setting a bit for every + * token the state admits there. A node's tokens are admitted as follows, which is the candidate + * walk's rule stated the other way up: + * + * ending here admitted iff nothing is carried out, or some char-range top could take + * some completion of what is; + * below, by id a token top admits the token with its id (`!<[id]>` every other one) + * among those with text left, wherever it is reached; + * below, by text whatever the successor over the next code point admits. + * + * In a key's walk (`exits`), the empty stack is the bottom marker: a node whose state holds it is + * where the key is left, and everything under it is recorded for the remainder. */ +struct Walk { + const TokenTrie* trie = nullptr; + uint32_t* bits = nullptr; + + /* A resume trie's root edges hold continuation bits plus one; the carried bits are OR'ed in. + * `skip_first` leaves the root's first child out of the walk, for fill_resume to serve. */ + bool resume = false; + uint32_t root_base = 0; + bool skip_first = false; + + bool exits = false; + std::vector>* frontier = nullptr; /* (node, depth) */ + uint64_t frontier_tokens = 0; + uint64_t frontier_limit = UINT64_MAX; + bool aborted = false; + + /* The admitted ids in the order they were first set, while there are few enough to be worth + * listing; past `list_cap` only the bits are kept. */ + std::vector* list = nullptr; + size_t list_cap = 0; + bool list_full = false; +}; + +struct WalkScratch { + std::vector> cur, nxt; +}; + +static inline void admit(Walk& w, int32_t id) { + const uint32_t word = (uint32_t)id >> 5, bit = 1u << ((uint32_t)id & 31u); + if (w.bits[word] & bit) return; + w.bits[word] |= bit; + if (w.list && !w.list_full) { + if (w.list->size() < w.list_cap) w.list->push_back(id); + else w.list_full = true; + } +} + +/* What a visit needs of the state it is made in. Read once per RUN of children -- every child in + * one interval of the parent's state shares its successor -- rather than once per child: a + * permissive walk visits every node of the vocabulary trie, and at that count the lookup of a + * state is a measurable part of a visit. */ +struct VisitState { + const SetDfa::St* S = nullptr; + bool expand = false; /* it has char-range tops, so children can be stepped */ + bool tokens = false; /* it has token tops */ + bool exit = false; /* a key's walk, and the state holds the bottom marker */ +}; + +static inline VisitState visit_state(const SetDfa& dfa, const Walk& w, int32_t s) { + VisitState v; + v.S = &dfa.st(s); + v.expand = !v.S->ctop.empty(); + v.tokens = !v.S->ttop.empty(); + v.exit = w.exits && v.S->has_empty; + return v; +} + +/* The tokens ending at a node whose state is live: admitted outright unless they carry out a + * partial character, which some char-range top must be able to finish. */ +static void visit_terminals(Walk& w, OpWork& work, const VisitState& vs, uint32_t t0, + uint32_t t1) { + const TokenTrie& T = *w.trie; + work.add(t1 - t0); + for (uint32_t k = t0; k < t1; ++k) { + const PartialUtf8 tail = T.ttail[k]; + bool ok = tail.n_remain == 0; + if (!ok) { + work.add(vs.S->match_cost); + for (const GbnfElement* top : vs.S->ctop) + if (match_partial_char(top, tail)) { ok = true; break; } + } + if (ok) admit(w, T.tid[k]); + } +} + +/* What a token top admits from below node n, `t1 - t0` of whose tokens end at n itself. */ +static __attribute__((noinline)) void visit_token_tops(Walk& w, OpWork& work, + const VisitState& vs, uint32_t n, + uint32_t n_end) { + const TokenTrie& T = *w.trie; + uint32_t a = T.lo[n] + n_end; /* strictly below n */ + const uint32_t b = T.hi[n]; + if (n == 0 && w.skip_first && T.node[0].n_child) a = std::max(a, T.hi[T.node[0].first]); + if (a >= b) return; + for (const GbnfElement* top : vs.S->ttop) { + const uint32_t v = top->value; + if (top->type == GRE_TOKEN) { + if (!T.pos.empty()) { + if (v < T.pos.size() && T.pos[v] != kNone && T.pos[v] >= a && T.pos[v] < b) + admit(w, (int32_t)v); + } else { + work.add(b - a); + for (uint32_t i = a; i < b; ++i) + if ((uint32_t)T.lex[i] == v) { admit(w, (int32_t)v); break; } + } + } else { + work.add(b - a); + for (uint32_t i = a; i < b; ++i) + if ((uint32_t)T.lex[i] != v) admit(w, T.lex[i]); + } + } +} + +/* Visit node n: admit what ends here and what a token top takes from below, record an exit. + * Returns whether the node's children are worth stepping. */ +static inline __attribute__((always_inline)) bool walk_visit(Walk& w, OpWork& work, + const TrieNode* nd, uint32_t n, + const VisitState& vs, + uint32_t depth) { + const uint32_t t0 = nd[n].tbeg, t1 = nd[n + 1].tbeg; + if (t0 != t1) visit_terminals(w, work, vs, t0, t1); + if (vs.tokens) visit_token_tops(w, work, vs, n, t1 - t0); + if (vs.exit) { + const TokenTrie& T = *w.trie; + w.frontier->push_back({ n, depth }); + w.frontier_tokens += T.hi[n] - T.lo[n]; + if (w.frontier_tokens > w.frontier_limit) { w.aborted = true; return false; } + } + return vs.expand && nd[n].n_child != 0; +} + +static void walk(SetDfa& dfa, int32_t start, Walk& w, OpWork& work, WalkScratch& sc) { + if (start < 0) return; + const TrieNode* nd = w.trie->node.data(); + auto& cur = sc.cur; + auto& nxt = sc.nxt; + cur.clear(); + { + const VisitState vs = visit_state(dfa, w, start); + if (walk_visit(w, work, nd, 0, vs, 0)) cur.push_back({ 0u, start }); + if (w.aborted) return; + } + + for (uint32_t depth = 1; !cur.empty(); ++depth) { + nxt.clear(); + const bool remap = w.resume && depth == 1; + const uint32_t base = w.root_base; + auto cp_of = [nd, remap, base](uint32_t c) -> uint64_t { + return remap ? (uint64_t)(base | (nd[c].cp - 1)) : (uint64_t)nd[c].cp; + }; + for (size_t e = 0; e < cur.size(); ++e) { + const uint32_t n = cur[e].first; + const int32_t s = cur[e].second; + const SetDfa::St& S = dfa.parted(s); + const uint32_t* lo = S.lo.data(); + const size_t m = S.lo.size(); + uint32_t c = nd[n].first + (depth == 1 && w.skip_first ? 1u : 0u); + const uint32_t c1 = nd[n].first + nd[n].n_child; + size_t i = 0; + + /* One run of children per interval: the children are sorted, so the interval only + * moves forward -- a step at a time among a few intervals, by binary search among + * many -- a dead one is skipped by a binary search over the children, and a live one + * hands every child in it the same state. */ + while (c < c1) { + const uint64_t cp = cp_of(c); + if (m <= 16) { + while (i + 1 < m && lo[i + 1] <= cp) ++i; + } else { + i = (size_t)(std::upper_bound(lo + i, lo + m, cp, + [](uint64_t x, uint32_t y) { return x < y; }) - lo) - 1; + } + const uint64_t hi = i + 1 < m ? (uint64_t)lo[i + 1] : (uint64_t)1 << 33; + const int32_t ns = dfa.next(s, i); + if (ns < 0) { + uint32_t a = c, b = c1; + while (a < b) { + const uint32_t mid = a + (b - a) / 2; + if (cp_of(mid) < hi) a = mid + 1; else b = mid; + } + work.add(8); + c = a; + continue; + } + const VisitState vs = visit_state(dfa, w, ns); + const uint32_t c0 = c; + for (; c < c1 && cp_of(c) < hi; ++c) + if (walk_visit(w, work, nd, c, vs, depth)) nxt.push_back({ c, ns }); + work.add(8 + (c - c0)); + if (w.aborted) return; + } + } + cur.swap(nxt); + } +} + +/* ============================================================ the plan */ + +/* A KEY: a suffix of stack entries by class, bottom first. Held as a tree grown downward -- a + * node is its bottom class plus the node for the entries above it -- which is also how a stack + * is looked up: from its top, one entry down per level, until a node that is not extended. + * + * `mask` is the accepted set: of a final node, used with any context; of an extended node that + * can be a whole stack, used only when the stack ends there. `rem` is the remainder trie, walked + * from the context's state when there is a context. */ +struct KeyNode { + uint32_t cls = 0; + int32_t up = -1; + uint16_t depth = 1; + bool extended = false; + bool can_end = false; + int32_t mask = -1; + int32_t rem = -1; + std::vector> kids; /* by class, sorted */ +}; + +/* An accepted set, as a bitmask when that is smaller than listing it. */ +struct KeyMask { + bool dense = false; + std::vector v; /* dense: the words; otherwise the token ids, ascending */ +}; + +struct MaskPlan { + const GbnfRuleSet* rules = nullptr; + std::shared_ptr vx; + std::vector cls; /* element index -> class; 0 where no entry */ + std::vector top_key; /* class -> its depth-one key, or -1 */ + std::vector keys; + std::vector masks; + std::vector rems; + PlanStats stats; + + /* THE RUN-TIME HALF IS A MEMO. The automaton here holds the states contexts close to and the + * remainders step into; it grows as they are discovered and every state in it is a fact about + * the grammar, so one lock covers it and every request and rank shares it. */ + mutable std::mutex mu; + mutable std::unique_ptr dfa; + mutable WalkScratch ws; + mutable std::vector mark; + mutable uint32_t epoch = 0; + mutable std::vector slot; + struct Group { int32_t key; std::vector ctx; }; + mutable std::vector groups; + mutable GbnfStack ctx; +}; + +void MaskPlanDeleter::operator()(MaskPlan* p) const { delete p; } + +namespace { + +/* Everything the build derives from the rules before it walks anything. */ +struct Grammar { + const GbnfRuleSet& R; + uint32_t root; + std::vector erule; /* element index -> rule */ + std::vector reach; /* rule reachable from the root */ + std::vector bottom_ok; /* rule can be the frame at a stack's bottom */ + std::vector> rev_tail; /* rule -> rules that end an alternative in it */ + std::vector> refs_to; /* rule -> reference elements to it */ + std::vector rep; /* class -> a representative element */ + std::vector> tops; /* class -> its terminal elements, reachable */ + std::vector> below; /* rule -> entries that can sit below it */ + std::vector below_done; + std::vector stamp; /* rule -> the below_of search that last saw it */ + uint32_t stamp_now = 0; + + explicit Grammar(const GbnfRuleSet& r, uint32_t rt) : R(r), root(rt) {} + + uint32_t next_unit(uint32_t idx) const { + const GbnfElement* e = &R.elems[idx]; + return is_char_elem(e) ? R.index(match_char(e, 0).second) : idx + 1; + } +}; + +/* WHICH RULES ARE THE SAME RULE. A generated grammar repeats itself: every tool's + * undeclared-parameter clause is `("] | ">" [^\n])* ">\n")`, and the parser gives + * each copy -- the group, the repetition, the alternatives inside it -- rules of its own. Their + * entries would be distinct classes, and each would get a key and a walk of the vocabulary of + * its own, one per tool, for identical answers. + * + * So rules are hash-consed on their bodies with references replaced by the referenced rule's + * canonical id, bottom-up over the reference graph's strongly connected components. A rule that + * refers only to itself -- which is what a repetition is -- is hashed with its self-references + * marked as such, so identical repetitions merge too. A larger cycle of rules is left distinct: + * mutual recursion is rare in what generators emit and is correct unmerged. Returns the canonical + * id of each rule; ids of merged rules are equal, and no id is a rule index. */ +static std::vector canonical_rules(const Grammar& G, const std::vector& nullable, + uint32_t max_cps, OpWork& work) { + const GbnfRuleSet& R = G.R; + const size_t NR = R.n_rules(), NE = R.elems.size(); + auto rule_end = [&](size_t r) { return r + 1 < NR ? R.start[r + 1] : (uint32_t)NE; }; + + /* Tarjan's strongly connected components over references, iteratively. Components come out + * in reverse topological order: every rule a component refers to outside itself is already + * canonical when it is reached. */ + std::vector idx(NR, -1), low(NR, 0); + std::vector on(NR, 0); + std::vector stk; + std::vector> comps; + struct Frame { uint32_t r; uint32_t e; }; + std::vector call; + int32_t counter = 0; + for (size_t root = 0; root < NR; ++root) { + if (idx[root] >= 0) continue; + idx[root] = low[root] = counter++; + stk.push_back((uint32_t)root); + on[root] = 1; + call.push_back({ (uint32_t)root, R.start[root] }); + while (!call.empty()) { + Frame& f = call.back(); + const uint32_t v = f.r; + if (f.e < rule_end(v)) { + const GbnfElement& el = R.elems[f.e++]; + if (el.type != GRE_RULE_REF) continue; + const uint32_t w = el.value; + if (idx[w] < 0) { + idx[w] = low[w] = counter++; + stk.push_back(w); + on[w] = 1; + call.push_back({ w, R.start[w] }); + } else if (on[w]) { + low[v] = std::min(low[v], idx[w]); + } + continue; + } + call.pop_back(); + if (!call.empty()) low[call.back().r] = std::min(low[call.back().r], low[v]); + if (low[v] == idx[v]) { + std::vector c; + uint32_t w; + do { + w = stk.back(); + stk.pop_back(); + on[w] = 0; + c.push_back(w); + } while (w != v); + comps.push_back(std::move(c)); + } + } + } + work.add(NE + NR); + + constexpr uint32_t kSelf = 0xFFFFFFFEu; + std::vector canon(NR, kNone); + std::unordered_map ids; + std::string sig; + uint32_t unique = 0x80000000u; /* ids no body hashes to: rules left unmerged */ + auto put = [](std::string& out, const GbnfElement& el, uint32_t v) { + out.push_back((char)el.type); + out.append((const char*)&v, 4); + }; + + /* A BOUNDED REPETITION IS A STAR, AS FAR AS ANY TOKEN CAN TELL. The parser writes x{0,n} as a + * chain, `S(k) ::= x S(k-1) |` down to `S(1) ::= x |`, and every link is a rule of its own -- + * so `[^"]{0,1000}` would be a thousand keys, each walking the vocabulary. But a token holds + * at most `max_cps` code points, and when x always consumes at least one, a token can take at + * most that many repetitions: with more than that left, no token can tell the link from + * `x*`. Such links are given the star's canonical id; the shorter ones stay what they are. + * `depth` and `operand` hold, per link, how many repetitions it allows and the signature of + * what it repeats; a star, which refers to itself, is not a link. */ + std::vector depth(NR, 0); + std::vector operand(NR); + auto consumes = [&](uint32_t a, uint32_t e) { + for (uint32_t i = a; i < e; i = G.next_unit(i)) { + const GbnfElement& el = R.elems[i]; + if (is_char_elem(&el)) return true; + if (el.type == GRE_RULE_REF && !nullable[el.value]) return true; + } + return false; + }; + auto has_token_elem = [&](uint32_t a, uint32_t e) { + for (uint32_t i = a; i < e; ++i) + if (is_token_elem(&R.elems[i])) return true; + return false; + }; + + for (const auto& c : comps) { + if (c.size() > 1) { + for (uint32_t r : c) canon[r] = unique++; + continue; + } + const uint32_t r = c[0]; + sig.clear(); + for (uint32_t i = R.start[r]; i < rule_end(r); ++i) { + const GbnfElement& el = R.elems[i]; + put(sig, el, el.type != GRE_RULE_REF ? el.value + : el.value == r ? kSelf + : canon[el.value]); + } + work.add(sig.size()); + + /* A link: exactly `x [S(k-1)] | `. */ + const uint32_t a = R.start[r]; + uint32_t alt_end = a; + while (!is_end_of_sequence(&R.elems[alt_end])) ++alt_end; + const bool two_alts = R.elems[alt_end].type == GRE_ALT && + R.elems[alt_end + 1].type == GRE_END; + const bool self_ref = alt_end > a && R.elems[alt_end - 1].type == GRE_RULE_REF && + R.elems[alt_end - 1].value == r; + if (two_alts && alt_end > a && !self_ref && !has_token_elem(a, alt_end)) { + const GbnfElement& last = R.elems[alt_end - 1]; + uint32_t op_end = alt_end, below = kNone; + if (last.type == GRE_RULE_REF && depth[last.value] > 0) { + op_end = alt_end - 1; + below = last.value; + } + std::string op; + for (uint32_t i = a; i < op_end; ++i) { + const GbnfElement& el = R.elems[i]; + put(op, el, el.type == GRE_RULE_REF ? canon[el.value] : el.value); + } + if (op_end > a && consumes(a, op_end) && + (below == kNone || operand[below] == op)) { + depth[r] = below == kNone ? 1 : depth[below] + 1; + operand[r] = op; + if (depth[r] > max_cps) { + std::string star = op; + const GbnfElement self{ GRE_RULE_REF, 0 }; + put(star, self, kSelf); + put(star, GbnfElement{ GRE_ALT, 0 }, 0); + put(star, GbnfElement{ GRE_END, 0 }, 0); + sig = std::move(star); + } + } + } + canon[r] = ids.emplace(sig, (uint32_t)ids.size()).first->second; + } + return canon; +} + +/* Which rules can match the empty string: a fixed point, as in find_left_recursion. An + * alternative with a terminal in it never can; one of rule references only can once all of them + * can, so it waits on a count. */ +static std::vector nullable_rules(const GbnfRuleSet& R, OpWork& work) { + const size_t NR = R.n_rules(), NE = R.elems.size(); + std::vector nullable(NR, 0); + std::vector alt_owner, alt_pending, todo; + std::vector> waiting(NR); + for (size_t r = 0; r < NR; ++r) { + uint32_t i = R.start[r]; + for (;;) { + bool terminal = false; + uint32_t refs = 0; + uint32_t j = i; + for (; !is_end_of_sequence(&R.elems[j]); ++j) { + if (R.elems[j].type == GRE_RULE_REF) ++refs; + else terminal = true; + } + if (!terminal) { + if (refs == 0) { + if (!nullable[r]) { nullable[r] = 1; todo.push_back((uint32_t)r); } + } else { + const uint32_t alt = (uint32_t)alt_owner.size(); + alt_owner.push_back((uint32_t)r); + alt_pending.push_back(refs); + for (uint32_t k = i; k < j; ++k) waiting[R.elems[k].value].push_back(alt); + } + } + if (R.elems[j].type == GRE_END) break; + i = j + 1; + } + } + while (!todo.empty()) { + const uint32_t x = todo.back(); + todo.pop_back(); + for (uint32_t alt : waiting[x]) { + if (--alt_pending[alt] != 0) continue; + const uint32_t r = alt_owner[alt]; + if (!nullable[r]) { nullable[r] = 1; todo.push_back(r); } + } + } + work.add(NE * 2 + NR); + return nullable; +} + +/* THE CLASS OF AN ENTRY is what remains of its alternative from it on, element for element with + * rule references by canonical rule, hash-consed from the end of each alternative backward. Two + * entries of one class behave identically wherever they are: what a stack does next is fixed by + * the elements its entries have left and the rules those reference. Class 0 is the end of an + * alternative and is never an entry. + * + * A RUN OF ONE UNIT is capped the way a repetition chain is (canonical_rules): x{1000} is a + * thousand x in a row, and an entry with more than `max_cps` of a unit that always consumes a + * code point still ahead of it behaves, for every token, like one with one fewer. Such an entry + * takes the class of the entry after it. */ +static void compute_classes(Grammar& G, MaskPlan& P, const std::vector& nullable, + uint32_t max_cps, OpWork& work) { + const GbnfRuleSet& R = G.R; + const size_t NE = R.elems.size(); + const std::vector canon = canonical_rules(G, nullable, max_cps, work); + P.cls.assign(NE, 0); + G.rep.assign(1, 0); + std::unordered_map ids; + std::vector lead(1); /* class -> its first unit's content */ + std::vector run(1, 0); /* class -> how many of that unit lead it, capped */ + std::string key, unit; + std::vector units; + + for (size_t r = 0; r < R.n_rules(); ++r) { + uint32_t idx = R.start[r]; + for (;;) { + units.clear(); + while (!is_end_of_sequence(&R.elems[idx])) { + units.push_back(idx); + idx = G.next_unit(idx); + } + uint32_t nextc = 0; + for (size_t u = units.size(); u-- > 0;) { + unit.clear(); + for (uint32_t e = units[u], end = G.next_unit(units[u]); e < end; ++e) { + const GbnfElement& el = R.elems[e]; + const uint32_t v = el.type == GRE_RULE_REF ? canon[el.value] : el.value; + unit.push_back((char)el.type); + unit.append((const char*)&v, 4); + } + const GbnfElement& ue = R.elems[units[u]]; + const bool consumes = is_char_elem(&ue) || + (ue.type == GRE_RULE_REF && !nullable[ue.value]); + if (consumes && nextc != 0 && run[nextc] > max_cps && lead[nextc] == unit) { + P.cls[units[u]] = nextc; + continue; + } + key = unit; + key.append((const char*)&nextc, 4); + work.add(key.size()); + auto ins = ids.emplace(key, (uint32_t)G.rep.size()); + if (ins.second) { + G.rep.push_back(units[u]); + const uint32_t r = consumes && nextc != 0 && lead[nextc] == unit + ? run[nextc] + 1 : (consumes ? 1u : 0u); + lead.push_back(unit); + run.push_back(r); + } + P.cls[units[u]] = ins.first->second; + nextc = ins.first->second; + } + if (R.elems[idx].type == GRE_END) break; + ++idx; + } + } +} + +/* A RULE THAT CAN NEVER MATCH ANYTHING, and cannot be left either: every way into it comes back + * into it without reaching a character or its own end -- `r ::= r` is the shortest. A stack that + * enters one closes to nothing at all, and upstream's candidate walk reads a stack set that is + * empty as rejecting nothing, so the mask past such a point admits every token while accepting + * any of them ends the parse. A mask built from stack suffixes cannot reproduce that reading -- + * it depends on whether the rest of one particular stack is empty -- and nothing a grammar means + * depends on it, so a grammar that can reach such a rule is refused, by the rule's name. + * + * A rule can POP past itself iff it is nullable, and its closure YIELDS a stack iff some element + * it can reach before a first element that cannot pop is a terminal or a rule that yields. Both are + * least fixed points computed with worklists, linear in the grammar -- a chain of a hundred + * thousand rules is one pass, not one per link. A rule doing neither is blind. Returns a blind + * rule reachable from the root, or kNone. */ +static uint32_t blind_rule(const Grammar& G, const std::vector& nullable, OpWork& work) { + const GbnfRuleSet& R = G.R; + const size_t NR = R.n_rules(); + std::vector yields(NR, 0); + std::vector> waits(NR); /* rule -> rules it would make yield */ + std::vector todo; + for (size_t r = 0; r < NR; ++r) { + uint32_t idx = R.start[r]; + for (;;) { + bool open = true; + for (; !is_end_of_sequence(&R.elems[idx]); idx = G.next_unit(idx)) { + if (!open) continue; + const GbnfElement& e = R.elems[idx]; + if (e.type == GRE_RULE_REF) { + waits[e.value].push_back((uint32_t)r); + open = nullable[e.value] != 0; + } else { + if (!yields[r]) { yields[r] = 1; todo.push_back((uint32_t)r); } + open = false; + } + } + if (R.elems[idx].type == GRE_END) break; + ++idx; + } + } + while (!todo.empty()) { + const uint32_t t = todo.back(); + todo.pop_back(); + for (uint32_t r : waits[t]) + if (!yields[r]) { yields[r] = 1; todo.push_back(r); } + } + work.add(R.elems.size() * 2 + NR); + for (size_t r = 0; r < NR; ++r) + if (G.reach[r] && !yields[r] && !nullable[r]) return (uint32_t)r; + return kNone; +} + +static void analyse(Grammar& G, MaskPlan& P, OpWork& work) { + const GbnfRuleSet& R = G.R; + const size_t NE = R.elems.size(), NR = R.n_rules(); + + G.erule.assign(NE, 0); + for (size_t r = 0; r < NR; ++r) { + const size_t end = r + 1 < NR ? R.start[r + 1] : NE; + for (size_t i = R.start[r]; i < end; ++i) G.erule[i] = (uint32_t)r; + } + work.add(NE); + + /* Reachable rules. A reference inside an unreachable rule is not a place any stack can be, + * and counting it would give frames predecessors they never have. */ + G.reach.assign(NR, 0); + std::vector todo{ G.root }; + G.reach[G.root] = 1; + while (!todo.empty()) { + const uint32_t r = todo.back(); + todo.pop_back(); + const size_t end = r + 1 < NR ? R.start[r + 1] : NE; + for (size_t i = R.start[r]; i < end; ++i) { + const GbnfElement& e = R.elems[i]; + if (e.type == GRE_RULE_REF && !G.reach[e.value]) { + G.reach[e.value] = 1; + todo.push_back(e.value); + } + } + } + + /* Tail references (a frame REPLACED rather than stacked on), and every reference by target. */ + G.rev_tail.assign(NR, {}); + G.refs_to.assign(NR, {}); + std::vector> tail_to(NR); + for (size_t r = 0; r < NR; ++r) { + if (!G.reach[r]) continue; + uint32_t idx = R.start[r]; + for (;;) { + uint32_t last = kNone; + while (!is_end_of_sequence(&R.elems[idx])) { + if (R.elems[idx].type == GRE_RULE_REF) G.refs_to[R.elems[idx].value].push_back(idx); + last = idx; + idx = G.next_unit(idx); + } + if (last != kNone && R.elems[last].type == GRE_RULE_REF) { + tail_to[r].push_back(R.elems[last].value); + G.rev_tail[R.elems[last].value].push_back((uint32_t)r); + } + if (R.elems[idx].type == GRE_END) break; + ++idx; + } + } + + /* The frames a stack can have at its bottom: the root's, and whatever it hands over to by + * tail reference. */ + G.bottom_ok.assign(NR, 0); + todo.assign(1, G.root); + G.bottom_ok[G.root] = 1; + while (!todo.empty()) { + const uint32_t r = todo.back(); + todo.pop_back(); + for (uint32_t t : tail_to[r]) + if (!G.bottom_ok[t]) { G.bottom_ok[t] = 1; todo.push_back(t); } + } + + /* The terminals, by class: every place a stack's top can be. */ + G.tops.assign(G.rep.size(), {}); + for (size_t r = 0; r < NR; ++r) { + if (!G.reach[r]) continue; + uint32_t idx = R.start[r]; + for (;;) { + while (!is_end_of_sequence(&R.elems[idx])) { + const GbnfElement* e = &R.elems[idx]; + if (is_char_elem(e) || is_token_elem(e)) G.tops[P.cls[idx]].push_back(idx); + idx = G.next_unit(idx); + } + if (R.elems[idx].type == GRE_END) break; + ++idx; + } + } + work.add(NE * 4); + + G.below.assign(NR, {}); + G.below_done.assign(NR, 0); + G.stamp.assign(NR, 0); +} + +/* THE ENTRIES THAT CAN SIT DIRECTLY BELOW A FRAME OF RULE r: the element after every reference to + * r, or to a rule that hands over to r by tail reference. Every entry below a stack's top is such + * an element -- where the frame below resumes. + * + * KEPT BY ELEMENT, NOT BY CLASS, and a key's bottom entry carries the elements it can be. Classes + * merge elements of different rules, and so merge what can sit below them: the `space` that ends + * `integer` and the `space` after `integer` in the rule that uses it are one class, and below the + * first is the second, so by class that class can sit below itself without end -- a chain no real + * stack holds, and one a key would be extended along until it was refused. By element, adjacency + * is exact, and a key grows only as deep as real stacks do. */ +static const std::vector& below_of(Grammar& G, uint32_t r, OpWork& work) { + if (G.below_done[r]) return G.below[r]; + std::vector& out = G.below[r]; + std::vector todo{ r }; + const uint32_t mark = ++G.stamp_now; + G.stamp[r] = mark; + while (!todo.empty()) { + const uint32_t b = todo.back(); + todo.pop_back(); + for (uint32_t q : G.refs_to[b]) { + const uint32_t u = q + 1; + if (!is_end_of_sequence(&G.R.elems[u])) out.push_back(u); + } + for (uint32_t t : G.rev_tail[b]) + if (G.stamp[t] != mark) { G.stamp[t] = mark; todo.push_back(t); } + work.add(G.refs_to[b].size() + G.rev_tail[b].size() + 1); + } + std::sort(out.begin(), out.end()); + out.erase(std::unique(out.begin(), out.end()), out.end()); + G.below_done[r] = 1; + return out; +} + +/* The entries that can sit directly below any of `pos`, as (class, element), sorted. */ +static void preds_of(Grammar& G, const MaskPlan& P, const std::vector& pos, + std::vector>* out, OpWork& work) { + out->clear(); + uint32_t last_rule = kNone; + for (uint32_t p : pos) { + const uint32_t r = G.erule[p]; + if (r == last_rule) continue; + last_rule = r; + for (uint32_t u : below_of(G, r, work)) out->push_back({ P.cls[u], u }); + } + std::sort(out->begin(), out->end()); + out->erase(std::unique(out->begin(), out->end()), out->end()); + work.add(out->size() + 1); +} + +static bool can_end(const Grammar& G, const std::vector& pos) { + for (uint32_t p : pos) + if (G.bottom_ok[G.erule[p]]) return true; + return false; +} + +static std::string rule_name_of(const std::vector* names, uint32_t r) { + if (names && r < names->size() && !(*names)[r].empty()) return "'" + (*names)[r] + "'"; + return "#" + std::to_string(r); +} + +/* ============================================================ building the keys */ + +/* What one key's walk decided. A final key keeps its accepted set, which holds whatever the + * context, and its remainder trie. A key that is not final is extended; it keeps an accepted set + * only if it can also be a whole stack, where there is no context and that set is the mask. */ +struct Outcome { + bool final_ = false; + int32_t mask = -1; + int32_t rem = -1; /* -1 when nothing leaves the key */ +}; + +class KeyBuilder { +public: + KeyBuilder(MaskPlan& P, const VocabIndex& X, SetDfa& dfa, OpWork& work) + : P_(P), X_(X), dfa_(dfa), work_(work), + n_words_((X.n_tokens + 31) / 32), bits_((size_t)n_words_, 0u) {} + + /* The outcome of a key whose local stack interns to s0: `exits` when something can sit below + * it, `ends` when it can also be a whole stack. */ + Outcome outcome(int32_t s0, bool exits, bool ends) { + Outcome o; + Walk w = start_walk(exits); + walk(dfa_, s0, w, work_, ws_); + if (decide(w, o)) return o; + if (!ends) { + clear(w); + } else if (!w.aborted) { + o.mask = store(w); + } else { + /* The walk was cut short once the key was known to be extended; as a whole stack it + * needs the rest. */ + clear(w); + Walk whole = start_walk(false); + walk(dfa_, s0, whole, work_, ws_); + o.mask = store(whole); + } + return o; + } + +private: + Walk start_walk(bool exits) { + list_.clear(); + frontier_.clear(); + Walk w; + w.trie = &X_.trie; + w.bits = bits_.data(); + w.list = &list_; + w.list_cap = (size_t)n_words_; + w.exits = exits; + w.frontier = &frontier_; + w.frontier_limit = kAbortRemTokens; + return w; + } + + /* Keep an accepted set: listed when the walk listed it, as a bitmask otherwise. Clears the + * scratch bits either way. */ + int32_t store(Walk& w) { + KeyMask m; + if (!w.list_full) { + m.v.assign(list_.begin(), list_.end()); + std::sort(m.v.begin(), m.v.end()); + for (uint32_t id : m.v) bits_[id >> 5] &= ~(1u << (id & 31u)); + } else { + m.dense = true; + m.v = bits_; + std::fill(bits_.begin(), bits_.end(), 0u); + ++P_.stats.dense; + } + P_.stats.bytes += m.v.size() * 4 + sizeof(KeyMask); + P_.masks.push_back(std::move(m)); + return (int32_t)P_.masks.size() - 1; + } + + void clear(Walk& w) { + if (!w.list_full) + for (int32_t id : list_) bits_[(uint32_t)id >> 5] &= ~(1u << ((uint32_t)id & 31u)); + else + std::fill(bits_.begin(), bits_.end(), 0u); + } + + /* Is the key final? If so its accepted set and remainder are kept and the scratch cleared; + * if not, the walk's accepted set is left in the scratch for the caller. */ + bool decide(Walk& w, Outcome& o) { + if (!w.exits) { + o.final_ = true; + o.mask = store(w); + return true; + } + if (!w.aborted) { + /* What leaves the key and is not already admitted without it: the tokens under each + * node where the key was left, from that depth on. A token that ends exactly there + * leaves an empty remainder, which only a carried-out partial character can make + * worth keeping. */ + rents_.clear(); + bool too_many = false; + for (const auto& f : frontier_) { + const uint32_t n = f.first, d = f.second; + const uint32_t a = X_.trie.lo[n], b = X_.trie.hi[n]; + const uint32_t tend = X_.trie.node[n + 1].tbeg - X_.trie.node[n].tbeg; + work_.add(b - a); + for (uint32_t i = a; i < b; ++i) { + const int32_t id = X_.trie.lex[i]; + if (test_bit(bits_.data(), id)) continue; + const PartialUtf8 tail = X_.tail[(size_t)id]; + if (i < a + tend && tail.n_remain == 0) continue; + rents_.push_back({ X_.off[(size_t)id] + d, tail, id }); + } + if (rents_.size() > kMaxRemEntries) { too_many = true; break; } + } + if (!too_many && rents_.empty()) { + o.final_ = true; + o.mask = store(w); + return true; + } + if (!too_many) { + TokenTrie t; + trie_build(t, X_.cps.data(), rents_, 0); + work_.add(rents_.size() * 16 + t.n_nodes() * 4); + if (t.n_nodes() <= kMaxRemNodes) { + PlanStats& st = P_.stats; + st.rem_nodes += t.n_nodes(); + st.max_rem = std::max(st.max_rem, t.n_nodes()); + st.bytes += t.bytes(); + P_.rems.push_back(std::move(t)); + o.final_ = true; + o.rem = (int32_t)P_.rems.size() - 1; + o.mask = store(w); + return true; + } + } + } + return false; + } + + MaskPlan& P_; + const VocabIndex& X_; + SetDfa& dfa_; + OpWork& work_; + int64_t n_words_; + std::vector bits_; + std::vector list_; + std::vector> frontier_; + std::vector rents_; + WalkScratch ws_; +}; + +} /* namespace */ + +int plan_build(const GbnfRuleSet& R, uint32_t root, const std::shared_ptr& vxp, + const std::vector* rule_names, MaskPlanPtr* out, PlanStats* stats, + std::string* err) { + const auto t0 = std::chrono::steady_clock::now(); + MaskPlanPtr pp(new MaskPlan()); + MaskPlan& P = *pp; + P.rules = &R; + P.vx = vxp; + const VocabIndex& X = *vxp; + PlanStats& st = P.stats; + + OpWork work; + work.limit = kMaxCompileWork; + + Grammar G(R, root); + /* The longest token in code points, which is as far as any mask can see into the grammar. */ + const uint32_t max_cps = X.trie.depth > 0 ? X.trie.depth - 1 : 0; + const std::vector nullable = nullable_rules(R, work); + compute_classes(G, P, nullable, max_cps, work); + analyse(G, P, work); + st.classes = G.rep.size() - 1; + + const uint32_t blind = blind_rule(G, nullable, work); + if (blind != kNone) { + if (err) + *err = "rule " + rule_name_of(rule_names, blind) + " can never match anything: every " + "way into it leads back into it before any character or its own end"; + return RAD_E_UNSUPPORTED; + } + + SetDfa dfa(&R); + dfa.begin(&work); + KeyBuilder kb(P, X, dfa, work); + + /* The elements each key's bottom entry can be, by key; build-time only. */ + std::vector> kpos; + std::vector> preds; + + P.top_key.assign(G.rep.size(), -1); + std::vector todo; + for (uint32_t c = 1; c < G.rep.size(); ++c) { + if (G.tops[c].empty()) continue; + KeyNode k; + k.cls = c; + P.keys.push_back(std::move(k)); + kpos.push_back(std::move(G.tops[c])); + P.top_key[c] = (int32_t)P.keys.size() - 1; + todo.push_back((int32_t)P.keys.size() - 1); + } + + GbnfStack local; + for (size_t qi = 0; qi < todo.size(); ++qi) { + const int32_t ki = todo[qi]; + /* The compile automaton is a memo like the run-time one; it is dropped between keys once + * it is large, never during a walk. Each key is one operation as far as its growth bound + * goes, as each mask is at run time. */ + if (dfa.elems() > kMaxDfaElems) dfa = SetDfa(&R); + dfa.begin(&work); + + /* A node's class is its BOTTOM entry and `up` is the suffix above it, so following `up` + * lists the key bottom-first, which is a stack's order. */ + local.clear(); + for (int32_t k = ki; k >= 0; k = P.keys[(size_t)k].up) + local.push_back(&R.elems[G.rep[P.keys[(size_t)k].cls]]); + preds_of(G, P, kpos[(size_t)ki], &preds, work); + const bool ends = can_end(G, kpos[(size_t)ki]); + P.keys[(size_t)ki].can_end = ends; + st.max_depth = std::max(st.max_depth, P.keys[(size_t)ki].depth); + + const int32_t s0 = dfa.intern(GbnfStacks{ local }); + const Outcome o = kb.outcome(s0, !preds.empty(), ends); + if (o.final_) { + P.keys[(size_t)ki].mask = o.mask; + P.keys[(size_t)ki].rem = o.rem; + } else { + if (P.keys[(size_t)ki].depth >= kMaxKeyDepth) { + if (err) { + const uint32_t top_rule = G.erule[R.index(local.back())]; + *err = "the tokens admissible inside rule " + + rule_name_of(rule_names, top_rule) + " depend on more than " + + std::to_string(kMaxKeyDepth) + + " levels of the parse stack at one position, so its masks cannot be " + "precomputed; restructure it so that what can follow it is decided " + "closer to it"; + } + return RAD_E_UNSUPPORTED; + } + P.keys[(size_t)ki].extended = true; + P.keys[(size_t)ki].mask = o.mask; + const uint16_t depth = P.keys[(size_t)ki].depth; + for (size_t i = 0; i < preds.size();) { + KeyNode k; + k.cls = preds[i].first; + k.up = ki; + k.depth = (uint16_t)(depth + 1); + std::vector at; + for (; i < preds.size() && preds[i].first == k.cls; ++i) + at.push_back(preds[i].second); + const uint32_t c = k.cls; + P.keys.push_back(std::move(k)); + kpos.push_back(std::move(at)); + const int32_t id = (int32_t)P.keys.size() - 1; + P.keys[(size_t)ki].kids.push_back({ c, id }); + todo.push_back(id); + } + } + kpos[(size_t)ki] = {}; + st.bytes += sizeof(KeyNode); + if (st.bytes > kMaxPlanBytes) { + if (err) + *err = "the grammar's precomputed masks need more than " + + std::to_string(kMaxPlanBytes >> 20) + " MiB"; + return RAD_E_UNSUPPORTED; + } + } + + st.keys = P.keys.size(); + st.bytes += P.cls.size() * 4 + P.top_key.size() * 4; + st.work = work.used; + st.ms = ms_since(t0); + P.mark.assign(P.keys.size(), 0); + P.slot.assign(P.keys.size(), -1); + if (stats) *stats = st; + *out = std::move(pp); + return RAD_OK; +} + +/* ============================================================ a mask */ + +/* The key a stack is served by, and how many of its entries it spans: from the top down, one + * entry per level, until a node that is not extended or the stack runs out. -1 is a stack no key + * covers, which the analysis rules out; it is reported rather than served. */ +static int32_t key_of(const MaskPlan& P, const GbnfStack& S, size_t* depth, OpWork& work) { + const GbnfRuleSet& R = *P.rules; + const uint32_t c0 = P.cls[R.index(S.back())]; + int32_t k = c0 < P.top_key.size() ? P.top_key[c0] : -1; + size_t d = 1; + while (k >= 0 && P.keys[(size_t)k].extended && d < S.size()) { + const uint32_t c = P.cls[R.index(S[S.size() - 1 - d])]; + const auto& kids = P.keys[(size_t)k].kids; + auto it = std::lower_bound(kids.begin(), kids.end(), std::make_pair(c, INT32_MIN)); + k = (it != kids.end() && it->first == c) ? it->second : -1; + ++d; + work.add(8); + } + if (k >= 0 && P.keys[(size_t)k].mask < 0) k = -1; + *depth = d; + return k; +} + +static void or_mask(const KeyMask& m, uint32_t* bits, OpWork& work) { + work.add(m.v.size() / (m.dense ? 8 : 1) + 1); + if (m.dense) { + const uint32_t* src = m.v.data(); + for (size_t w = 0, n = m.v.size(); w < n; ++w) bits[w] |= src[w]; + } else { + for (uint32_t id : m.v) bits[id >> 5] |= 1u << (id & 31u); + } +} + +static int fill_keys(const MaskPlan& P, SetDfa& dfa, const GbnfStacks& stacks, uint32_t* bits, + OpWork& work) { + if (++P.epoch == 0) { + std::fill(P.mark.begin(), P.mark.end(), 0u); + P.epoch = 1; + } + P.groups.clear(); + bool completed = false; + for (const GbnfStack& S : stacks) { + if (S.empty()) { completed = true; continue; } + size_t d = 0; + const int32_t k = key_of(P, S, &d, work); + if (k < 0) { + RAD_ERR("gbnf: no precomputed mask covers a stack of this grammar; the request cannot " + "be continued"); + return RAD_E_STATE; + } + const KeyNode& K = P.keys[(size_t)k]; + if (P.mark[(size_t)k] != P.epoch) { + P.mark[(size_t)k] = P.epoch; + P.slot[(size_t)k] = -1; + or_mask(P.masks[(size_t)K.mask], bits, work); + } + if (K.rem < 0 || d >= S.size()) continue; + P.ctx.assign(S.begin(), S.end() - (std::ptrdiff_t)d); + work.add(P.ctx.size() + 8); + const int32_t c = dfa.closure(P.ctx); + if (P.slot[(size_t)k] < 0) { + P.slot[(size_t)k] = (int32_t)P.groups.size(); + P.groups.push_back({ k, {} }); + } + P.groups[(size_t)P.slot[(size_t)k]].ctx.push_back(c); + } + if (completed) { + work.add(P.vx->blank.size() + 1); + for (int32_t id : P.vx->blank) set_bit(bits, id); + } + for (auto& g : P.groups) { + const int32_t x = dfa.unite(g.ctx); + Walk w; + w.trie = &P.rems[(size_t)P.keys[(size_t)g.key].rem]; + w.bits = bits; + walk(dfa, x, w, work, P.ws); + } + return RAD_OK; +} + +static void fill_resume(const MaskPlan& P, SetDfa& dfa, const GbnfStacks& stacks, + PartialUtf8 partial, uint32_t* bits, OpWork& work) { + const int r = partial.n_remain; + const VocabIndex::Resume& RS = P.vx->resume[r - 1]; + const int32_t s0 = dfa.intern(stacks); + if (s0 < 0) return; + const SetDfa::St& S = dfa.st(s0); + const TrieNode* nd = RS.trie.node.data(); + + /* A CHARACTER FINISHED AS U+0000 ENDS THE PIECE. The carried bits are zero only after the + * head of an overlong sequence, and with zero bits to finish it the character decodes to 0 -- + * which in a decoded sequence is its terminator, so the piece reads as having no characters at + * all, whatever follows. Such a piece is admissible as one that ends before its first + * character is: outright if it carries nothing out, and otherwise if some char-range top could + * finish what it does. Those pieces are all under the root edge for zero bits, the first, and + * are served here rather than stepped over as a character. */ + const bool nul = partial.value == 0 && nd[0].n_child > 0 && nd[nd[0].first].cp == 1; + if (nul) { + std::vector todo{ nd[0].first }; + while (!todo.empty()) { + const uint32_t n = todo.back(); + todo.pop_back(); + for (uint32_t k = nd[n].tbeg; k < nd[n + 1].tbeg; ++k) { + const PartialUtf8 tail = RS.trie.ttail[k]; + bool ok = tail.n_remain == 0; + for (size_t j = 0; !ok && j < S.ctop.size(); ++j) + ok = match_partial_char(S.ctop[j], tail); + if (ok) set_bit(bits, RS.trie.tid[k]); + } + for (uint32_t c = nd[n].first; c < nd[n].first + nd[n].n_child; ++c) todo.push_back(c); + work.add(4 + (nd[n + 1].tbeg - nd[n].tbeg) * (S.match_cost + 1)); + } + } + + Walk w; + w.trie = &RS.trie; + w.bits = bits; + w.resume = true; + w.root_base = partial.value << (6 * r); + w.skip_first = nul; + walk(dfa, s0, w, work, P.ws); + + work.add(RS.shorts.size() * (S.match_cost + 1)); + for (const auto& sh : RS.shorts) { + const PartialUtf8 tail{ (partial.value << (6 * sh.k)) | sh.bits, r - sh.k }; + for (const GbnfElement* top : S.ctop) + if (match_partial_char(top, tail)) { set_bit(bits, sh.id); break; } + } +} + +int plan_fill(const MaskPlan& P, const GbnfStacks& stacks, PartialUtf8 partial, bool allow_eog, + uint32_t* bitmask, int64_t n_words) { + std::lock_guard lk(P.mu); + std::fill(bitmask, bitmask + n_words, 0u); + + OpWork work; + /* The automaton is a memo, so past its bound it is dropped and rebuilt rather than refused: + * every state in it can be rediscovered, and a grammar whose stacks deepen with every token + * would otherwise hold a new state per token for as long as it is cached. */ + if (!P.dfa || P.dfa->elems() > kMaxDfaElems) { + if (P.dfa) + RAD_DEBUG("gbnf: the stack-set automaton holds %zu states, %zu stack elements; " + "rebuilding it", P.dfa->n_states(), P.dfa->elems()); + P.dfa = std::make_unique(P.rules); + } + SetDfa& dfa = *P.dfa; + dfa.begin(&work); + + if (allow_eog) + for (int32_t id : P.vx->eog) set_bit(bitmask, id); + + if (partial.n_remain > 0) { + fill_resume(P, dfa, stacks, partial, bitmask, work); + } else { + const int s = fill_keys(P, dfa, stacks, bitmask, work); + if (s < 0) return s; + } + + for (int64_t w = 0; w < n_words; ++w) + if (bitmask[w]) return RAD_OK; + return RAD_E_STATE; +} + +} /* namespace gbnf */ +} /* namespace rad */ diff --git a/core/sample/grammar.cpp b/core/sample/grammar.cpp new file mode 100644 index 00000000..465a24cc --- /dev/null +++ b/core/sample/grammar.cpp @@ -0,0 +1,166 @@ +/* grammar.cpp -- the GBNF backend that ships, and the schema seam onto it. + */ +#include "grammar.h" +#include "gbnf.h" + +#include +#include + +#include +#include +#include + +namespace rad { + +int64_t grammar_mask_words(int64_t n_vocab) { return bitmask_words(n_vocab); } + +/* HOW DEEPLY A SCHEMA MAY NEST, in objects and arrays. The converter recurses once per level and + * names each rule after its whole path, so its output grows with the square of the depth: a + * 72 KB schema 3,000 levels deep compiles to 67 MB of grammar, and deeper ones exhaust the + * memory or the stack of the thread that admits the request. A schema nested as deep as this one + * allows converts in tens of milliseconds to a couple of megabytes, and a schema written to + * describe data nests far less. */ +static constexpr size_t kMaxSchemaDepth = 512; + +/* Walked with an explicit stack, because the values it exists to catch are the ones too deep to + * recurse over. */ +static size_t json_depth(const nlohmann::ordered_json& root) { + std::vector> todo{ { &root, 1 } }; + size_t deepest = 0; + while (!todo.empty()) { + const auto [j, d] = todo.back(); + todo.pop_back(); + if (!j->is_structured()) continue; + deepest = std::max(deepest, d); + for (const auto& c : *j) todo.push_back({ &c, d + 1 }); + } + return deepest; +} + +/* ONE JSON-SCHEMA COMPILER, AND IT IS THE VENDORED ONE. + * + * `response_format` on /v1/chat/completions goes to the chat template, which compiles it with the + * vendored converter; on /v1/completions it is refused by the accept-list (kAcceptedCompletion) + * before parse_output_format runs, and that is the only path to this seam. A second, separately + * maintained copy of the same upstream compiler would therefore be the copy no request reaches, + * while the vendored one serves every schema. The hardening that belongs on a schema compiler + * fed client data -- vendor/patches 0003 and 0004, which close a hang and two out-of-bounds + * reads and refuse three constructs upstream accepts and then gets wrong -- lives in the + * vendored copy, which is the copy that runs. + * + * This function is the seam response_format would go through if /v1/completions accepted it. + * No request reaches it. + * + * The vendored entry point throws; errors are values by the time a caller sees them. */ +int grammar_from_json_schema(const std::string& schema_json, const std::string& root, + std::string* out_gbnf, std::string* err) { + if (!out_gbnf) return RAD_E_INVAL; + /* The converter names its top rule "root" and takes no say in it. Every caller in the tree + * asks for "root"; anything else would silently get that instead, so it is refused. */ + if (!root.empty() && root != "root") { + if (err) *err = "this converter always names the top rule 'root'"; + return RAD_E_UNSUPPORTED; + } + try { + const auto schema = nlohmann::ordered_json::parse(schema_json); + if (json_depth(schema) > kMaxSchemaDepth) { + if (err) *err = "the schema nests more than " + std::to_string(kMaxSchemaDepth) + + " levels deep"; + return RAD_E_INVAL; + } + *out_gbnf = json_schema_to_grammar(schema); + } catch (const std::exception& e) { + if (err) *err = e.what(); + return RAD_E_INVAL; + } + if (out_gbnf->empty()) { + if (err) *err = "the schema compiled to an empty grammar"; + return RAD_E_INVAL; + } + return RAD_OK; +} + +/* ================================================================== the GBNF backend */ + +namespace { + +class GbnfBackend : public GrammarBackend { +public: + explicit GbnfBackend(std::unique_ptr g) : g_(std::move(g)) {} + + const char* name() const override { return "gbnf"; } + int accept_token(int32_t token) override { return g_->accept_token(token); } + int fill_mask(uint32_t* m, int64_t n) const override { return g_->fill_mask(m, n); } + bool complete() const override { return g_->complete(); } + bool constrains() const override { return !g_->awaiting_trigger(); } + uint64_t masks_walked() const override { return g_->masks_walked(); } + + /* The GBNF machine's state is a stack set and a carried UTF-8 partial, both copyable, so a + * rewind is a copy back -- there is nothing to reconstruct and no cost that scales with how + * far the window went. */ + bool can_speculate() const override { return true; } + int push_state() override { g_->push_state(); return RAD_OK; } + int rollback() override { return g_->rollback(); } + +private: + std::unique_ptr g_; +}; + +int gbnf_ctor(const GrammarSpec& spec, const VocabView& vocab, + std::unique_ptr* out, std::string* err) { + std::string text = spec.text; + + /* A JSON Schema is compiled to GBNF here rather than being a second backend, because it is + * not a different state machine -- it is the same one fed different text. Carrying it as a + * backend would mean two places that can disagree about what a schema admits. */ + if (spec.kind == GrammarKind::JsonSchema) { + std::string gbnf; + const int st = grammar_from_json_schema(spec.text, spec.root, &gbnf, err); + if (st < 0) return st; + text = std::move(gbnf); + } + + std::unique_ptr g; + const int st = GbnfGrammar::create(text, spec.root.empty() ? "root" : spec.root, &vocab, + spec.lazy, spec.trigger_words, spec.trigger_tokens, + &g, err); + if (st < 0) return st; + + if (!spec.prefix.empty()) { + const int ps = g->accept_str(spec.prefix); + if (ps < 0) { + /* The grammar does not admit the prompt it was supposed to have been generating. + * Constraining from here would mask against a state that does not describe this + * request, so it is refused rather than run in the wrong place. */ + if (err) *err = "the grammar does not admit this template's generation prompt, so it " + "cannot be positioned at the start of the reply"; + return ps; + } + } + + *out = std::make_unique(std::move(g)); + return RAD_OK; +} + +} /* namespace */ + +int grammar_create(const GrammarSpec& spec, const VocabView& vocab, + std::unique_ptr* out, std::string* err) { + if (!out) return RAD_E_INVAL; + if (spec.text.empty()) { + if (err) *err = "empty grammar"; + return RAD_E_INVAL; + } + + /* The compiler below turns its own failures into statuses; what is left is running out of + * memory on the way, and this is called on the admission thread and the scheduler thread, + * where an escaping exception ends every request on the server rather than this one. */ + try { + return gbnf_ctor(spec, vocab, out, err); + } catch (const std::bad_alloc&) { + if (err) *err = "out of memory building the grammar"; + return RAD_E_NOMEM; + } +} + +} /* namespace rad */ diff --git a/core/sample/grammar.h b/core/sample/grammar.h new file mode 100644 index 00000000..c7671081 --- /dev/null +++ b/core/sample/grammar.h @@ -0,0 +1,127 @@ +/* grammar.h -- structured output: the grammar backend interface, and the bitmask that crosses to + * the device. + * + * Structured output is GBNF, with JSON-schema compiled to a grammar. THE GRAMMAR STATE MACHINE + * STAYS ON HOST, where it belongs -- it is a pushdown automaton over a rule set, it branches per + * candidate, and none of that is work a GPU is good at. What crosses is a TOKEN BITMASK PER + * SEQUENCE, which at a 151K vocab is 19 KiB, cheap enough to upload every step (spec §13). The + * mask lands as the `sample_mask` op (docs/OPS.md), which is an ordinary declared op resolved + * through the ordinary hierarchy. + * + * The backend is a small interface so an alternative can be dropped in, and it is small on + * purpose: three calls. GBNF is the shipped one and there is no reason to carry xgrammar for it. + * If a device-side grammar ever earns its place, it implements this and nothing above it changes + * -- at which point it gets a way to be selected, which is a thing to add then rather than a + * registry to carry now for an entry that never arrived. + */ +#pragma once +#include "../rad_internal.h" +#include "vocab_view.h" + +#include +#include +#include + +namespace rad { + +enum class GrammarKind { + Gbnf = 0, /* the text is GBNF */ + JsonSchema = 1 /* the text is a JSON Schema, compiled to GBNF at create time */ +}; + +struct GrammarSpec { + GrammarKind kind = GrammarKind::Gbnf; + std::string text; + std::string root = "root"; + + /* Lazy grammars constrain nothing until a trigger fires, which is how a tool-calling template + * stays free-form until the model starts emitting a call. A trigger is a token id or a literal + * word in the emitted bytes; see sampler.cpp for how a template's triggers become these. */ + bool lazy = false; + std::vector trigger_words; + std::vector trigger_tokens; + + /* TEXT THE GRAMMAR HAS ALREADY SEEN, replayed into it before it constrains anything. + * + * A chat template's grammar describes the whole assistant turn, generation prompt included: + * its root really does begin `"<|im_start|>assistant\n"`, because that is where the turn + * begins. But those bytes are in the PROMPT, not in what the model is about to generate, so a + * grammar started at its root demands them again -- and the model, obediently masked, emits + * the literal text `<|im_start|>assistant` as its answer. Replaying the prefix is what puts + * the automaton where the sampler actually is. Empty for a caller-supplied grammar, which + * describes the reply and nothing before it. */ + std::string prefix; +}; + +class GrammarBackend { +public: + virtual ~GrammarBackend() = default; + + virtual const char* name() const = 0; + + /* Advance over the token the sampler just emitted. Returns RAD_OK, or RAD_E_STATE if that + * token was not admissible -- which means the mask and the pick disagreed, a bug on this side + * rather than a bad request. RAD_E_FULL or RAD_E_NOMEM means the parse outgrew the backend's + * bounds; the backend is then dead and its next fill_mask fails. */ + virtual int accept_token(int32_t token) = 0; + + /* Fill `bitmask` ([n_words] words, bit set means admissible). RAD_E_STATE if nothing at all is + * admissible, RAD_E_FULL or RAD_E_NOMEM if the state is past the backend's bounds; any of them + * fails the request rather than emitting a token the grammar forbids. */ + virtual int fill_mask(uint32_t* bitmask, int64_t n_words) const = 0; + + /* Some parse has run to completion, so the sequence may stop here. */ + virtual bool complete() const = 0; + + /* INSTRUMENT: how many masks this backend has had to COMPUTE rather than serve from a memo, + * monotonic over the life of whatever the memo belongs to. Diff it around a fill_mask to learn + * which of the two that call was. + * + * It is a counter and not a duration. Inferring computed-versus-hit from how long a fill_mask + * took needs a cost threshold, and no threshold holds: a mask computed on a small grammar + * finishes inside the time a memo hit on a large one takes, so the classification is wrong and + * any per-mask cost derived from it is wrong by the same factor. A backend with no memo counts + * every mask. */ + virtual uint64_t masks_walked() const { return 0; } + + /* False while a lazy grammar is still waiting for its trigger. The driver skips the mask op + * for a sequence that is not being constrained, which is the only reason this is on the + * interface rather than folded into fill_mask returning all-ones. */ + virtual bool constrains() const = 0; + + /* ---------------------------------------------------------- speculation + + * A CONSTRAINED SEQUENCE SPECULATES BY WALKING THE WINDOW AND REWINDING. The mask for draft + * position i is the mask of the state reached by accepting drafts 0..i-1, so the sampler + * pushes the state, advances over each proposal in turn to mask the position behind it, and + * pops back to where the sequence really is. Without it a grammar-constrained request decodes + * one token at a time, at several times the per-token cost of the same model generating + * unconstrained prose. + * + * A backend that cannot do this says so and is driven unspeculated -- the sampler decodes + * such a request a token at a time rather than masking a draft position against a state the + * sequence is not in, which would admit the wrong token set and read as a model that writes + * malformed calls. */ + virtual bool can_speculate() const { return false; } + + /* Push the current state. Nestable; `rollback` pops the most recent. */ + virtual int push_state() { return RAD_E_UNSUPPORTED; } + virtual int rollback() { return RAD_E_UNSUPPORTED; } +}; + +/* Words a mask needs for a vocabulary of this size. */ +int64_t grammar_mask_words(int64_t n_vocab); + +/* Compile a JSON Schema to GBNF text. Separated from create() so a caller that wants to SEE the + * grammar -- `--debug-graph`, or a user asking why their schema behaves as it does -- can get it + * without building a state machine. */ +int grammar_from_json_schema(const std::string& schema_json, const std::string& root, + std::string* out_gbnf, std::string* err); + +/* Build the grammar backend. Returns RAD_OK, or a negative status with a human-readable reason + * in *err. There is ONE backend and it is GBNF: a name-keyed registry over a single entry with no + * second registration site is a lookup that can only ever resolve to that entry. */ +int grammar_create(const GrammarSpec& spec, const VocabView& vocab, + std::unique_ptr* out, std::string* err); + +} /* namespace rad */ diff --git a/core/sample/host_ref.cpp b/core/sample/host_ref.cpp new file mode 100644 index 00000000..ebaaa378 --- /dev/null +++ b/core/sample/host_ref.cpp @@ -0,0 +1,611 @@ +/* host_ref.cpp -- llama.cpp's sampling chain, ported to plain C++ over a float array. + * + * Source: llama.cpp `src/llama-sampler.cpp` at upstream commit 06938ac12 (MIT). Ported rather + * than linked: this is the oracle the device samplers are checked against, and an oracle that + * drags a second inference engine in is a dependency rather than a reference. See host_ref.h for + * the two places this deliberately differs from upstream -- the chain order and the RNG. + */ +#include "host_ref.h" + +#include "rad_sample.h" + +#include +#include +#include +#include + +namespace rad { + +/* ================================================================== the candidate set */ + +void CandidateSet::from_logits(const float* logits, int64_t n_vocab) { + c.resize((size_t)n_vocab); + for (int64_t i = 0; i < n_vocab; ++i) { + c[(size_t)i].id = (int32_t)i; + c[(size_t)i].logit = logits[i]; + c[(size_t)i].p = 0.0f; + } + sorted = false; + selected = -1; +} + +/* Upstream sorts on the logit alone and leaves equal logits in whatever order the partial sort + * happened to produce. That is fine for a single-threaded reference and useless for one that has + * to agree with a device kernel, where the order equal elements land in is a property of the + * block size. The id tie-break makes the sort a total order, so the two agree. */ +void CandidateSet::sort_desc() { + if (sorted) return; + std::stable_sort(c.begin(), c.end(), [](const Candidate& a, const Candidate& b) { + if (a.logit != b.logit) return a.logit > b.logit; + return a.id < b.id; + }); + sorted = true; +} + +/* ================================================================== reproducible randomness */ + +/* The stream's key, from abi/rad_sample.h. A stream this file does not know gets a key of its + * own rather than the pick's, so it can never silently repeat the pick's draw. */ +static uint64_t stream_key(uint32_t stream) { + switch (stream) { + case RAD_RNG_PICK: return RAD_SAMPLE_KEY_PICK; + case RAD_RNG_XTC: return RAD_SAMPLE_KEY_XTC; + case RAD_RNG_ACCEPT: return RAD_SAMPLE_KEY_ACCEPT; + case RAD_RNG_RESID: return RAD_SAMPLE_KEY_RESID; + default: return rad_sample_splitmix64((uint64_t)stream); + } +} + +/* rad_sample_uniform01's bits, before the float conversion: one splitmix64 round over + * ((seed ^ key) * golden ratio + pos). The same handful of integer ops a sampler kernel runs, + * which is what makes it affordable there where a Mersenne twister's state is not. */ +uint64_t rng_bits(uint64_t seed, uint64_t pos, uint32_t stream) { + return rad_sample_splitmix64((seed ^ stream_key(stream)) * 0x9E3779B97F4A7C15ull + pos); +} + +float rng_uniform(uint64_t seed, uint64_t pos, uint32_t stream) { + /* 24 bits, which is every bit a float can hold. Drawing 32 and dividing by 2^32 would round + * to 1.0f for the top values, and a uniform that can return 1.0 walks off the end of an + * inverse CDF. Written as rad_sample_uniform01 itself, so the two cannot drift apart. */ + return rad_sample_uniform01(seed ^ stream_key(stream), pos); +} + +/* ================================================================== individual samplers */ + +void host_softmax(CandidateSet& s, bool do_sort) { + if (s.c.empty()) return; + if (do_sort) s.sort_desc(); + + float max_l = s.c[0].logit; + if (!s.sorted) + for (size_t i = 1; i < s.c.size(); ++i) max_l = std::max(max_l, s.c[i].logit); + + double cum = 0.0; + for (auto& e : s.c) { + const float p = std::exp(e.logit - max_l); + e.p = p; + cum += p; + } + if (cum <= 0.0) return; /* every candidate masked out; leave p at zero and let the pick say so */ + for (auto& e : s.c) e.p = (float)(e.p / cum); +} + +void host_temp(CandidateSet& s, float temp) { + if (s.c.empty()) return; + + /* temp <= 0 is greedy and stays a real path rather than a caller's special case: the argmax + * it produces must use the SAME tie-break the argmax kernel uses (lowest id wins), or a + * temperature-0 request stops matching a greedy run. */ + if (temp <= 0.0f) { + size_t max_i = 0; + for (size_t i = 1; i < s.c.size(); ++i) { + const Candidate& e = s.c[i]; + if (e.logit > s.c[max_i].logit) max_i = i; + } + for (size_t i = 0; i < s.c.size(); ++i) + if (i != max_i) s.c[i].logit = -INFINITY; + return; + } + + for (auto& e : s.c) e.logit /= temp; +} + +void host_top_k(CandidateSet& s, int32_t k) { + if (k <= 0) return; + if ((size_t)k >= s.c.size()) { s.sort_desc(); return; } + s.sort_desc(); + s.c.resize((size_t)k); +} + +void host_top_p(CandidateSet& s, float p, size_t min_keep) { + if (p >= 1.0f || s.c.empty()) return; + + s.sort_desc(); + host_softmax(s, false); + + /* Upstream has an adaptive partial sort that grows k until the nucleus closes; it is a + * performance path over a 151K vocab and produces the same set as a full sort, so the + * reference takes the full sort and the device kernel takes the radix threshold. */ + float cum = 0.0f; + size_t last_idx = s.c.size(); + for (size_t i = 0; i < s.c.size(); ++i) { + cum += s.c[i].p; + if (cum >= p && i + 1 >= min_keep) { last_idx = i + 1; break; } + } + s.c.resize(last_idx); +} + +void host_min_p(CandidateSet& s, float p, size_t min_keep) { + if (p <= 0.0f || s.c.empty()) return; + + /* Upstream has an unsorted fast path that filters in place and falls back to the sorted one + * when too few survive. Both select the same SET and differ only in the order they leave it + * in; the reference takes the sorted path because an order that depends on which path ran is + * an order a device kernel cannot reproduce. */ + s.sort_desc(); + + const float min_logit = s.c[0].logit + std::log(p); /* p_i >= p * p_max */ + size_t i = 1; /* the mode always survives */ + for (; i < s.c.size(); ++i) + if (s.c[i].logit < min_logit && i >= min_keep) break; + + s.c.resize(i); +} + +void host_typical(CandidateSet& s, float p, size_t min_keep) { + if (p >= 1.0f || s.c.empty()) return; + + host_softmax(s, true); + + float entropy = 0.0f; + for (const auto& e : s.c) + if (e.p > 0.0f) entropy += -e.p * std::log(e.p); + + /* The distance between a candidate's surprisal and the distribution's entropy. Sorting by it + * is what makes typical sampling different from every other cut here: it keeps the tokens + * that are AS surprising as expected, not the least surprising ones. */ + std::vector shifted(s.c.size()); + for (size_t i = 0; i < s.c.size(); ++i) { + const float pi = s.c[i].p; + shifted[i] = std::fabs(-(pi > 0.0f ? std::log(pi) : -INFINITY) - entropy); + } + + std::vector idx(s.c.size()); + std::iota(idx.begin(), idx.end(), (size_t)0); + std::stable_sort(idx.begin(), idx.end(), [&](size_t a, size_t b) { + if (shifted[a] != shifted[b]) return shifted[a] < shifted[b]; + return s.c[a].id < s.c[b].id; /* total order, same reason as sort_desc */ + }); + + float cum = 0.0f; + size_t last_idx = idx.size(); + for (size_t i = 0; i < idx.size(); ++i) { + cum += s.c[idx[i]].p; + if (cum > p && (min_keep == 0 || i >= min_keep - 1)) { last_idx = i + 1; break; } + } + + std::vector kept; + kept.reserve(last_idx); + for (size_t i = 0; i < last_idx; ++i) kept.push_back(s.c[idx[i]]); + s.c = std::move(kept); + s.sorted = false; /* surprisal order is not logit order */ +} + +void host_penalties(CandidateSet& s, const int32_t* history, int64_t n_history, + int32_t last_n, float rep, float freq, float pres) { + if (last_n == 0) return; + if (rep == 1.0f && freq == 0.0f && pres == 0.0f) return; + if (!history || n_history <= 0) return; + + const int64_t window = last_n < 0 ? n_history : std::min(last_n, n_history); + std::unordered_map count; + count.reserve((size_t)window * 2); + for (int64_t i = n_history - window; i < n_history; ++i) count[history[i]]++; + + for (auto& e : s.c) { + auto it = count.find(e.id); + if (it == count.end()) continue; + const int n = it->second; + + /* The paper divides. Dividing makes a token with a negative logit MORE likely, which is + * obviously wrong, so everyone multiplies below zero instead. Upstream's comment says the + * same thing and the reference has to reproduce the fix, not the paper. */ + if (e.logit <= 0.0f) e.logit *= rep; + else e.logit /= rep; + + e.logit -= (float)n * freq + (n > 0 ? 1.0f : 0.0f) * pres; + } + s.sorted = false; +} + +/* ------------------------------------------------------------------ DRY */ + +void DryBreakers::index(int32_t n_vocab) { + const size_t words = n_vocab > 0 ? ((size_t)n_vocab + 31) / 32 : 0; + heads.assign(words, 0u); + singles.assign(words, 0u); + for (const auto& e : seqs) { + const int32_t t = e.first; + if (t < 0 || t >= n_vocab) continue; + heads[(size_t)(t >> 5)] |= 1u << ((uint32_t)t & 31u); + if (e.second.empty()) singles[(size_t)(t >> 5)] |= 1u << ((uint32_t)t & 31u); + } +} + +bool DryBreakers::is_head(int32_t t) const { + if (heads.empty()) return seqs.count(t) > 0; + return bit(heads, t); +} + +bool DryBreakers::is_single(int32_t t) const { + if (singles.empty()) { + auto range = seqs.equal_range(t); + for (auto it = range.first; it != range.second; ++it) + if (it->second.empty()) return true; + return false; + } + return bit(singles, t); +} + +/* The longest prefix of `s` of at most `max` bytes that does not end inside a UTF-8 sequence. + * Upstream truncates at the byte; cutting a character in half leaves a tail the tokeniser may + * refuse, and a refused tail fails the whole request. */ +static std::string utf8_prefix(const std::string& s, size_t max) { + if (s.size() <= max) return s; + size_t n = max; + while (n > 0 && ((unsigned char)s[n] & 0xC0u) == 0x80u) --n; + return s.substr(0, n); +} + +int dry_prepare_breakers(const VocabView& vocab, const std::vector& breakers, + DryBreakers* out, int max_tail_len) { + if (!out) return RAD_E_INVAL; + out->seqs.clear(); + out->heads.clear(); + out->singles.clear(); + if (breakers.empty()) return RAD_OK; + if (breakers.size() > kDryMaxBreakers) { + RAD_WARN("dry: %zu sequence breakers, more than the %zu the breaker scan accepts", + breakers.size(), kDryMaxBreakers); + return RAD_E_INVAL; + } + + /* Upstream: get_overlapping_token_sequences. A full vocabulary scan per breaker string, which + * is why this runs once per request on admission and never on the step path. */ + const int32_t n = vocab.n_tokens(); + for (const std::string& given : breakers) { + const std::string str = utf8_prefix(given, kDryBreakerMaxBytes); + if (str.empty()) continue; + + /* THE TAIL DEPENDS ONLY ON WHERE THE BREAKER WAS SPLIT, not on which token covered its + * head: every token whose suffix is the breaker's first i bytes is completed by the + * tokenisation of the remaining bytes. So each split point is tokenised once rather than + * once per matching token -- a breaker that starts with a common byte matches thousands + * of tokens, and tokenising is the expensive half of the scan. */ + std::vector> tail_at(str.size()); + std::vector have(str.size(), 0); + + for (int32_t id = 0; id < n; ++id) { + const std::string& word = vocab.token_piece(id); + if (word.find(str) != std::string::npos) { + out->seqs.emplace(id, std::vector()); + continue; + } + size_t pos = std::string::npos; + while ((pos = word.find(str[0], pos + 1)) != std::string::npos) { + bool match = true; + size_t i = 1; + for (; i < str.size() && i + pos < word.size(); ++i) { + if (word[pos + i] != str[i]) { match = false; break; } + } + if (!match) continue; + + if (!have[i]) { + std::vector& fresh = tail_at[i]; + const int st = vocab.tokenize(str.substr(i), &fresh); + if (st < 0) { + /* A breaker that cannot be tokenised is a breaker that silently stops + * working, and a DRY request whose breakers vanished is a DRY request + * that quietly changed behaviour. Say so. */ + RAD_WARN("dry: sequence breaker \"%s\" does not tokenise (%s)", + str.c_str(), rad_strerror(st)); + out->seqs.clear(); + return st; + } + if (max_tail_len >= 0 && (int)fresh.size() > max_tail_len) + fresh.resize((size_t)max_tail_len); + have[i] = 1; + } + const std::vector& tail = tail_at[i]; + + bool dup = false; + auto range = out->seqs.equal_range(id); + for (auto it = range.first; it != range.second; ++it) + if (it->second == tail) { dup = true; break; } + if (!dup) out->seqs.emplace(id, tail); + } + } + } + out->index(n); + return RAD_OK; +} + +int dry_rep_limit(const DryBreakers& breakers, const int32_t* window, int n) { + if (!window || n <= 0) return n > 0 ? n : 0; + if (breakers.empty()) return n; + + /* rat(i): the i-th token counting back from the end of the window. */ + auto rat = [&](int i) -> int32_t { return window[n - 1 - i]; }; + + for (int i = 0; i < n; ++i) { + const int32_t tok = rat(i); + if (!breakers.is_head(tok)) continue; + + int longest = -1; + auto its = breakers.seqs.equal_range(tok); + for (auto it = its.first; it != its.second; ++it) { + const int seq_len = (int)it->second.size(); + if (seq_len <= longest || seq_len > i) continue; + bool match = true; + for (int off = 0; off < seq_len; ++off) { + if (it->second[(size_t)off] != rat(i - off - 1)) { match = false; break; } + } + if (match) longest = seq_len; + } + if (longest >= 0) return i - longest; + } + return n; +} + +void host_dry(CandidateSet& s, const int32_t* history, int64_t n_history, + int64_t total_context, const DryParams& p, const DryBreakers& breakers) { + if (p.multiplier == 0.0f || p.base < 1.0f || p.penalty_last_n == 0) return; + if (!history || n_history <= 0) return; + if (total_context <= 0) total_context = n_history; + + const int64_t effective = (p.penalty_last_n == -1) ? total_context + : std::max(p.penalty_last_n, 0); + const int n_rep = (int)std::min(std::min(n_history, effective), total_context); + if (n_rep <= p.allowed_length) return; + + /* rat(i): the i-th token counting back from the end of the window. Upstream reads it off a + * ring buffer; here the history is a flat array the scheduler already owns. */ + auto rat = [&](int i) -> int32_t { return history[n_history - 1 - i]; }; + + std::vector repeat_count((size_t)n_rep, 0); + std::unordered_map max_token_repeat; + + /* Step 1: a restart sequence bounds how long a repetition may be counted. Walking back from + * the end, the first token that heads a complete breaker sequence caps it. */ + const int rep_limit = dry_rep_limit(breakers, history + (n_history - n_rep), n_rep); + if (rep_limit < p.allowed_length) return; + + /* Step 2: the Z-algorithm, run in reverse, giving for every position the length of the + * suffix that also appears ending there. Linear despite the nested loops, because lt/rt bound + * each token to one visit. */ + { + const int last = n_rep - 1; + int rt = 0, lt = 0; + for (int k = 1; k < n_rep; ++k) { + if (k > rt) { + int n = 0; + while (n + k < n_rep && rat(n) == rat(n + k)) ++n; + repeat_count[(size_t)(last - k)] = std::min(n, rep_limit); + if (n > 0) { lt = k; rt = k + n - 1; } + } else { + const int pi = k - lt; + const int right_part_len = rt - k + 1; + if (repeat_count[(size_t)(last - pi)] < right_part_len) { + repeat_count[(size_t)(last - k)] = + std::min(repeat_count[(size_t)(last - pi)], rep_limit); + } else { + int i = rt + 1; + while (i < n_rep && rat(i) == rat(i - k)) ++i; + repeat_count[(size_t)(last - k)] = std::min(i - k, rep_limit); + lt = k; rt = i - 1; + } + } + } + } + + /* Step 3: for every position that ends a long-enough repeat, the NEXT token would extend it. + * That token is the one to penalise, and by the length it would reach. */ + for (int i = 0; i < n_rep - 1; ++i) { + const int len = repeat_count[(size_t)i]; + if (len < p.allowed_length) continue; + const int32_t tok = rat(n_rep - 2 - i); + auto it = max_token_repeat.find(tok); + if (it == max_token_repeat.end() || it->second < len) max_token_repeat[tok] = len; + } + + /* Step 4: an exponential penalty in the excess length, clamped so pow() cannot overflow a + * float -- log(FLT_MAX) is 88.72, and past that the penalty is infinite anyway. */ + const float FLOAT_MAX_LOG = 88.7228391f; + int max_exponent = 0; + if (p.base > 1.000001f) max_exponent = (int)(FLOAT_MAX_LOG / std::log(p.base)); + + for (auto& e : s.c) { + auto it = max_token_repeat.find(e.id); + if (it == max_token_repeat.end()) continue; + + /* A token that is itself a single-token breaker is exempt: penalising it would penalise + * the very thing that ends the repetition. */ + if (breakers.is_single(e.id)) continue; + + int exp_n = it->second - p.allowed_length; + if (max_exponent > 0 && exp_n > max_exponent) exp_n = max_exponent; + e.logit -= p.multiplier * std::pow(p.base, (float)exp_n); + } + s.sorted = false; +} + +/* ------------------------------------------------------------------ XTC */ + +void host_xtc(CandidateSet& s, float probability, float threshold, size_t min_keep, + uint64_t seed, uint64_t pos) { + if (probability <= 0.0f || threshold > 0.5f || s.c.size() < 2) return; + + /* Its own RNG stream: XTC's coin and the pick must not be the same number, or a request + * whose XTC fires becomes a request whose pick is correlated with that fact. It fires when + * the uniform is BELOW the probability, the comparison `sample_xtc` makes, so the two agree + * on the draw that lands exactly on it. */ + if (rng_uniform(seed, pos, RAD_RNG_XTC) >= probability) return; + + host_softmax(s, true); + + size_t pos_last = 0; + for (size_t i = 0; i < s.c.size(); ++i) { + if (s.c[i].p >= threshold) pos_last = i; + else break; + } + + /* Drop everything above the threshold EXCEPT the least probable of them. That is the whole + * idea: remove the obvious continuation, not the unlikely ones. */ + if (s.c.size() - pos_last >= min_keep && pos_last > 0) + s.c.erase(s.c.begin(), s.c.begin() + (std::ptrdiff_t)pos_last); +} + +/* ------------------------------------------------------------------ the grammar mask */ + +void host_mask(CandidateSet& s, const uint32_t* bitmask, int64_t n_words) { + if (!bitmask) return; + for (auto& e : s.c) { + const int64_t w = (int64_t)e.id >> 5; + if (w >= n_words) { e.logit = -INFINITY; continue; } + if (!(bitmask[w] & (1u << ((uint32_t)e.id & 31u)))) e.logit = -INFINITY; + } + s.sorted = false; +} + +/* ------------------------------------------------------------------ the pick */ + +int32_t host_pick(CandidateSet& s, uint64_t seed, uint64_t pos) { + if (s.c.empty()) { s.selected = -1; return -1; } + + float max_l = -INFINITY; + for (const auto& e : s.c) max_l = std::max(max_l, e.logit); + if (!(max_l > -INFINITY)) { + /* Every candidate is -inf. That is a fully-masked distribution, which is a grammar that + * admits nothing -- a real failure, not a token. The caller fails the request. */ + s.selected = -1; + return -1; + } + if (s.c.size() == 1) { s.selected = 0; s.c[0].p = 1.0f; return s.c[0].id; } + + /* DESCENDING LOGIT, ties to the lower id, not the set's current order. Any fixed order + * samples correctly, but a total order makes the answer a property of the uniform rather than + * of how the previous stage happened to permute the set -- and this is the order sample_pick + * walks, since sample_topk leaves its candidates in it. */ + std::vector order(s.c.size()); + std::iota(order.begin(), order.end(), (size_t)0); + std::stable_sort(order.begin(), order.end(), [&](size_t a, size_t b) { + if (s.c[a].logit != s.c[b].logit) return s.c[a].logit > s.c[b].logit; + return s.c[a].id < s.c[b].id; + }); + + double total = 0.0; + for (size_t i : order) total += std::exp((double)s.c[i].logit - (double)max_l); + if (!(total > 0.0)) { s.selected = -1; return -1; } + + const double want = (double)rng_uniform(seed, pos, RAD_RNG_PICK) * total; + + /* A candidate at -infinity is never chosen, and the fall-through is the last one above it: a + * draw at the very top of the range can walk past every comparison in floating point, and + * the candidates behind the last real one are the grammar-masked ones. */ + double acc = 0.0; + size_t chosen = order.front(); + for (size_t i : order) { + if (!(s.c[i].logit > -INFINITY)) continue; + chosen = i; + acc += std::exp((double)s.c[i].logit - (double)max_l); + if (acc >= want) break; + } + + for (size_t i = 0; i < s.c.size(); ++i) + s.c[i].p = (float)(std::exp((double)s.c[i].logit - (double)max_l) / total); + + s.selected = (int)chosen; + return s.c[chosen].id; +} + +int32_t host_argmax(const float* logits, int64_t n_vocab) { + if (!logits || n_vocab <= 0) return -1; + int64_t best = 0; + for (int64_t i = 1; i < n_vocab; ++i) + if (logits[i] > logits[best]) best = i; /* strict >, so a tie keeps the lowest id */ + return (int32_t)best; +} + +/* ================================================================== the chain */ + +static int32_t argmax_of(const CandidateSet& s) { + if (s.c.empty()) return -1; + size_t best = 0; + for (size_t i = 1; i < s.c.size(); ++i) { + if (s.c[i].logit > s.c[best].logit) best = i; + else if (s.c[i].logit == s.c[best].logit && s.c[i].id < s.c[best].id) best = i; + } + if (!(s.c[best].logit > -INFINITY)) return -1; /* everything masked out */ + return s.c[best].id; +} + +int32_t host_sample_into(CandidateSet& s, const SamplingParams& sp, const HostRefInput& in, + ChainOrder order) { + /* Penalties first in both orders, because they act on raw logits and every cut below acts on + * probabilities derived from them. */ + host_penalties(s, in.history, in.n_history, sp.penalty_last_n, + sp.rep_penalty, sp.freq_penalty, sp.pres_penalty); + + if (sp.dry_multiplier > 0.0f && in.dry_breakers) { + DryParams dp; + dp.multiplier = sp.dry_multiplier; + dp.base = sp.dry_base; + dp.allowed_length = sp.dry_allowed_length; + dp.penalty_last_n = sp.dry_penalty_last_n; + host_dry(s, in.history, in.n_history, in.total_context, dp, *in.dry_breakers); + } + + /* THE GREEDY PATH SKIPS THE CHAIN, and it masks BEFORE it picks. Ordering matters here in a + * way that is easy to get wrong: temperature 0 collapses every other logit to -inf, so a + * mask applied afterwards can leave nothing at all. A greedy sequence is therefore + * penalties -> mask -> argmax, not the chain with temp=0 threaded through it. */ + if (sp.greedy()) { + host_mask(s, in.bitmask, in.n_words); + const int32_t tok = argmax_of(s); + for (size_t i = 0; i < s.c.size(); ++i) if (s.c[i].id == tok) { s.selected = (int)i; break; } + return tok; + } + + if (order == ChainOrder::Radiance) { + host_temp(s, sp.temp); + host_mask(s, in.bitmask, in.n_words); + host_top_k(s, sp.top_k); + host_top_p(s, sp.top_p, 1); + host_min_p(s, sp.min_p, 1); + host_typical(s, sp.typical_p, 1); + host_xtc(s, sp.xtc_probability, sp.xtc_threshold, 1, sp.seed, in.pos); + } else { + /* llama.cpp's default order, for checking this port against llama.cpp itself. Note the + * absence of top-n-sigma: it is not in SamplingParams and radiance does not ship it, so a + * comparison that enables it upstream will disagree here and should. */ + host_mask(s, in.bitmask, in.n_words); + host_top_k(s, sp.top_k); + host_typical(s, sp.typical_p, 1); + host_top_p(s, sp.top_p, 1); + host_min_p(s, sp.min_p, 1); + host_xtc(s, sp.xtc_probability, sp.xtc_threshold, 1, sp.seed, in.pos); + host_temp(s, sp.temp); + } + + return host_pick(s, sp.seed, in.pos); +} + +int32_t host_sample(const float* logits, int64_t n_vocab, const SamplingParams& sp, + const HostRefInput& in, ChainOrder order) { + if (!logits || n_vocab <= 0) return -1; + CandidateSet s; + s.from_logits(logits, n_vocab); + return host_sample_into(s, sp, in, order); +} + +} /* namespace rad */ diff --git a/core/sample/host_ref.h b/core/sample/host_ref.h new file mode 100644 index 00000000..b5ceff76 --- /dev/null +++ b/core/sample/host_ref.h @@ -0,0 +1,246 @@ +/* host_ref.h -- the host reference sampling chain. + * + * Sampling runs on device (spec §13): at a 151K vocab and batch 256 the logits are ~77 MiB a + * step, and moving them across the link to run a host chain costs the bandwidth AND a + * synchronisation, on the step path, at exactly the concurrency the engine exists to serve. So + * every sampler is a kernel, not a lift. + * + * This file is the other half of that sentence. A fallback you cannot test against is just an + * untested slow path (spec §17), so the device samplers need an oracle, and the oracle is + * llama.cpp's chain ported to plain C++ over a float array. Ported, not linked: there are no + * llama.cpp headers here and no ggml, because a reference that drags a second engine in is a + * dependency, and this is a reference. Each individual sampler below reproduces the semantics of + * its counterpart in llama.cpp `src/llama-sampler.cpp` at upstream commit 06938ac12 (MIT), + * including its edge cases, because reproducing the happy path only is how a comparison harness + * agrees with the thing it is checking and both are wrong. + * + * TWO THINGS DEVIATE FROM UPSTREAM, DELIBERATELY. + * + * 1. THE CHAIN ORDER. llama.cpp's default chain is penalties, DRY, top-n-sigma, top-k, typical, + * top-p, min-p, XTC, TEMPERATURE LAST. Radiance's order is the spec's and vLLM's: penalties, + * temperature, grammar mask, top-k, then top-p / min-p / typical, then the pick. The + * difference is not cosmetic -- top-p, min-p and typical all cut on probabilities, so whether + * temperature ran first changes which tokens survive. Radiance's device kernels run the + * radiance order (it is the order every OpenAI-compatible server is measured against), so + * ChainOrder::Radiance is what rad-kbench compares against. ChainOrder::LlamaCpp exists so + * this file can also be checked against llama.cpp itself, which is the only way to know the + * port is faithful. + * + * 2. THE RNG. Upstream carries a stateful std::mt19937 per sampler. That cannot be a device + * kernel: a kernel has no place to keep a Mersenne twister's 624 words of state per sequence, + * and a stateful generator makes the answer depend on how many draws happened earlier, which + * makes a comparison run irreproducible the moment the batch composition changes. Here the + * randomness is a pure function of (seed, position, stream) -- counter-based, stateless, and + * reproducible across a run with different batching. It is abi/rad_sample.h's draw, bit for + * bit, with the same per-stream keys, so the pick and XTC's coin here see exactly the uniforms + * the device stages see. + */ +#pragma once +#include "../rad_core.h" +#include "vocab_view.h" + +#include +#include +#include +#include + +namespace rad { + +/* ================================================================== the candidate set */ + +/* One candidate. `p` is meaningless until a softmax has run over the set; the samplers that need + * it call one themselves, exactly as upstream's do. */ +struct Candidate { + int32_t id = 0; + float logit = 0.0f; + float p = 0.0f; +}; + +/* The set the chain narrows. `sorted` tracks descending-by-logit order, because half the + * samplers upstream have a fast path that depends on it and a slow path that does not, and + * dropping the flag silently changes which one runs. */ +struct CandidateSet { + std::vector c; + bool sorted = false; + int selected = -1; /* index into c, set by the pick; -1 until then */ + + void from_logits(const float* logits, int64_t n_vocab); + void sort_desc(); /* descending logit, ties broken by ascending id */ + size_t size() const { return c.size(); } +}; + +/* ================================================================== reproducible randomness */ + +/* A counter-based generator: bits are a pure function of the three coordinates, so the same draw + * comes out on the host reference and in the device kernel, in any batch order, at any batch + * size. It IS rad_sample_uniform01 from abi/rad_sample.h -- splitmix64 over + * ((seed ^ key) * golden ratio + pos) -- because a reference with its own generator agrees with + * the device on no seeded draw at all. + * + * `pos` is the sequence's output position -- token index within this request's generation -- so + * a request's draws depend on where it is, not on when it was scheduled. `stream` separates + * independent draws taken at the same position (the pick, XTC's coin, speculative acceptance's + * uniforms) so they are not the same number; each maps to its RAD_SAMPLE_KEY_* key. */ +enum : uint32_t { + RAD_RNG_PICK = 0, /* the final categorical draw */ + RAD_RNG_XTC = 1, /* XTC's "does this fire at all" coin */ + RAD_RNG_ACCEPT = 2, /* speculative acceptance, one per draft position (see accept.h) */ + RAD_RNG_RESID = 3 /* the residual draw after a speculative rejection */ +}; + +uint64_t rng_bits(uint64_t seed, uint64_t pos, uint32_t stream); +/* Uniform in [0,1). 24 bits of mantissa: a float cannot resolve more, and pretending otherwise + * would make the host and the device disagree in the last place. */ +float rng_uniform(uint64_t seed, uint64_t pos, uint32_t stream); + +/* ================================================================== individual samplers */ + +/* Upstream: llama_sampler_softmax_impl. Fills `p` and normalises. */ +void host_softmax(CandidateSet& s, bool do_sort); + +/* Upstream: llama_sampler_temp_impl. temp <= 0 collapses to the argmax by setting every other + * logit to -inf, which is what keeps a temperature-0 request bit-identical to a greedy one. */ +void host_temp(CandidateSet& s, float temp); + +/* Upstream: llama_sampler_top_k_impl. k <= 0 is off. */ +void host_top_k(CandidateSet& s, int32_t k); + +/* Upstream: llama_sampler_top_p_apply. Ties AT the threshold are all kept, which can overshoot + * p by the mass of the tie -- the alternative is inventing an order among equal probabilities. */ +void host_top_p(CandidateSet& s, float p, size_t min_keep); + +/* Upstream: llama_sampler_min_p_apply. A floor relative to the mode, not an absolute one. */ +void host_min_p(CandidateSet& s, float p, size_t min_keep); + +/* Upstream: llama_sampler_typical_apply. Keeps the candidates whose surprisal is closest to the + * distribution's entropy, which is not the same set as the most probable ones. */ +void host_typical(CandidateSet& s, float p, size_t min_keep); + +/* Upstream: llama_sampler_penalties_apply, with the history passed in rather than accumulated in + * a ring buffer. The scheduler already owns each request's token history, and a sampler that + * kept its own copy would be a second place for it to be wrong. + * + * `history` is the sequence's tokens, oldest first; only the last `last_n` are counted. */ +void host_penalties(CandidateSet& s, const int32_t* history, int64_t n_history, + int32_t last_n, float rep, float freq, float pres); + +/* DRY's sequence breakers, resolved to token sequences once per request rather than per step. + * Upstream calls this `dry_processed_breakers` and builds it from the vocabulary; the cost is a + * full vocabulary scan per breaker string, which is why it does not belong on the step path. + * + * `seqs` maps a HEAD token to the tails that complete a breaker after it; an empty tail means the + * head token contains a whole breaker by itself. The two bitsets over the vocabulary answer the + * two questions the step path asks per token -- "does anything start here" and "is this token a + * whole breaker" -- with one load, where the multimap is a hash lookup a token. */ +struct DryBreakers { + std::unordered_multimap> seqs; + std::vector heads; /* bit t: token t heads at least one breaker sequence */ + std::vector singles; /* bit t: token t is a whole breaker by itself */ + + bool empty() const { return seqs.empty(); } + + /* Build the two bitsets from `seqs`. dry_prepare_breakers calls it; a set filled by hand is + * answered from the multimap until it is indexed, so the two ways of building one agree. */ + void index(int32_t n_vocab); + bool is_head(int32_t t) const; + bool is_single(int32_t t) const; + +private: + static bool bit(const std::vector& v, int32_t t) { + if (t < 0 || (size_t)(t >> 5) >= v.size()) return false; + return (v[(size_t)(t >> 5)] >> ((uint32_t)t & 31u)) & 1u; + } +}; + +/* THE BOUNDS ON WHAT A REQUEST MAY ASK THE BREAKER SCAN TO DO. Each breaker costs a pass over the + * whole vocabulary on the scheduler thread, once per rank, so an unbounded list stalls every + * sequence on the server for as long as the scan takes. Upstream truncates a breaker to 40 bytes + * and its token tail to 20 tokens (llama_sampler_init_dry); the count bound is this engine's own, + * well above the four breakers clients send by default, and a request over it is refused at + * admission by name rather than silently shortened. */ +constexpr size_t kDryMaxBreakers = 16; +constexpr size_t kDryBreakerMaxBytes = 40; +constexpr int kDryBreakerMaxTail = 20; + +/* Upstream: get_overlapping_token_sequences, per breaker, with upstream's truncation of each + * breaker to kDryBreakerMaxBytes (cut back to a UTF-8 boundary, so the tail still tokenises) and + * of each tail to `max_tail_len` tokens. Refuses more than kDryMaxBreakers breakers with + * RAD_E_INVAL. Returns RAD_E_UNSUPPORTED if the view has no tokeniser, because a DRY request + * whose breakers silently became empty is a DRY request that quietly stopped working. */ +int dry_prepare_breakers(const VocabView& vocab, const std::vector& breakers, + DryBreakers* out, int max_tail_len = kDryBreakerMaxTail); + +/* Upstream's step 1 of llama_sampler_dry_apply: walking back from the end of `window` (n tokens, + * oldest first), the first token that heads a COMPLETE breaker sequence caps how long a repeat + * may be counted. Returns that cap, or n when no breaker completes inside the window. Shared by + * host_dry and the sampler's per-step staging, so the reference and the device stage are handed + * the same limit. */ +int dry_rep_limit(const DryBreakers& breakers, const int32_t* window, int n); + +struct DryParams { + float multiplier = 0.0f; + float base = 1.75f; + int32_t allowed_length = 2; + int32_t penalty_last_n = -1; /* -1 = the whole context */ +}; + +/* Upstream: llama_sampler_dry_apply, Z-algorithm and all. Ported from Koboldcpp originally + * (LostRuins/koboldcpp#982, author pi6am) by way of llama.cpp. */ +void host_dry(CandidateSet& s, const int32_t* history, int64_t n_history, + int64_t total_context, const DryParams& p, const DryBreakers& breakers); + +/* Upstream: llama_sample_xtc_apply. Fires with probability `probability`; when it fires it drops + * every candidate above the threshold except the least probable of them, which is the point -- + * it removes the obvious continuation rather than the unlikely ones. */ +void host_xtc(CandidateSet& s, float probability, float threshold, size_t min_keep, + uint64_t seed, uint64_t pos); + +/* The grammar mask. One bit per token, set means admissible; a cleared bit takes the logit to + * -inf rather than removing the candidate, so the mask composes with everything downstream + * without renumbering anything. `n_words` is ceil(n_vocab/32). */ +void host_mask(CandidateSet& s, const uint32_t* bitmask, int64_t n_words); + +/* The pick. Inverse CDF over the surviving candidates in DESCENDING LOGIT ORDER, ties to the lower + * id -- a total order, so the answer is a property of the uniform rather than of how the previous + * stage happened to permute the set, and the order `sample_pick` walks the candidate set the + * top-k leaves (and the order upstream's dist sampler walks a sorted set in). A candidate at + * -infinity -- a grammar-masked logit -- is never returned, including by the fall-through a draw + * at the very top of the range takes. Returns the token id, or -1 for an empty or fully masked + * set. */ +int32_t host_pick(CandidateSet& s, uint64_t seed, uint64_t pos); + +/* Argmax over raw logits, lowest id winning a tie. The greedy path skips the chain entirely, so + * this must agree with what host_temp(0) + host_pick would produce or a temperature-0 request + * stops matching a greedy one. */ +int32_t host_argmax(const float* logits, int64_t n_vocab); + +/* ================================================================== the chain */ + +enum class ChainOrder { + Radiance = 0, /* penalties, DRY, temperature, mask, top-k, top-p/min-p/typical, XTC, pick */ + LlamaCpp = 1 /* penalties, DRY, top-k, typical, top-p, min-p, XTC, temperature, pick */ +}; + +/* Everything the chain needs that is not in SamplingParams. Kept separate because SamplingParams + * is frozen in rad_core.h and these are per-step facts, not per-request settings. */ +struct HostRefInput { + const int32_t* history = nullptr; /* the sequence's tokens so far, oldest first */ + int64_t n_history = 0; + int64_t total_context = 0; /* DRY's clamp; 0 means use n_history */ + const uint32_t* bitmask = nullptr; /* grammar mask, or null */ + int64_t n_words = 0; + uint64_t pos = 0; /* output position: the RNG's second coordinate */ + const DryBreakers* dry_breakers = nullptr; +}; + +/* Run the whole chain over one row of logits and return the token. This is what rad-kbench + * compares the device sampler against, per sequence, on the same logits. */ +int32_t host_sample(const float* logits, int64_t n_vocab, const SamplingParams& sp, + const HostRefInput& in, ChainOrder order = ChainOrder::Radiance); + +/* The same, leaving the narrowed candidate set behind for a caller that wants to inspect it -- + * rad-kbench reports which stage diverged, and it cannot do that from a token id alone. */ +int32_t host_sample_into(CandidateSet& s, const SamplingParams& sp, const HostRefInput& in, + ChainOrder order = ChainOrder::Radiance); + +} /* namespace rad */ diff --git a/core/sample/sampler.cpp b/core/sample/sampler.cpp new file mode 100644 index 00000000..bba83fc2 --- /dev/null +++ b/core/sample/sampler.cpp @@ -0,0 +1,925 @@ +/* sampler.cpp -- the sampler driver: declare the sampler ops, build the per-sequence parameter + * array once per step, issue the chain. No sampler is implemented here; see sampler.h for why. + */ +#include "sampler.h" +#include "gbnf.h" + +#include +#include +#include + +namespace rad { + +/* ================================================================== grammar triggers + * + * A chat template names its triggers the way a person would -- "the call starts at the word + * " -- while GbnfGrammar wants them in the two forms it checks as tokens arrive: token + * ids to compare against the id just emitted, and literal words to find in the emitted bytes. + * The translation needs a vocabulary, so it happens here and not in the server. + * + * A WORD IS A TOKEN WHEN THE VOCABULARY SAYS SO. The word is tokenised with special tokens + * recognised, since a template's markers are usually special tokens and a split of `` + * into `<`, `tool`, `_call`, `>` is not what the model emits. One token makes an id trigger, which + * costs a comparison; anything longer is scanned for as bytes, because the tokeniser may split it + * differently depending on what came before it. Getting this wrong does not fail loudly -- it + * yields a trigger that never fires, so the call comes out unconstrained, which reads as a model + * that writes malformed calls. + * + * A REGULAR-EXPRESSION TRIGGER IS REFUSED. Its matcher would run over the reply once per token + * on the scheduler thread; the templates in service all trigger on words. A request whose + * template needs one is refused at admission, naming the pattern. */ +static int resolve_triggers(const VocabView& vocab, + const std::vector& triggers, + std::vector* words, std::vector* tokens, + std::string* err) { + words->clear(); + tokens->clear(); + for (const auto& t : triggers) { + if (t.value.empty()) continue; + std::vector ids; + switch (t.type) { + case 0: /* token: the spelling of exactly one token */ + case 1: { /* word */ + const int st = vocab.tokenize_special(t.value, &ids); + if (st < 0) { + if (err) *err = "grammar trigger '" + t.value + "' could not be tokenised"; + return st; + } + if (ids.size() == 1) { tokens->push_back(ids[0]); break; } + if (t.type == 0) { + if (err) *err = "grammar trigger token '" + t.value + + "' is not a single token in this vocabulary"; + return RAD_E_INVAL; + } + words->push_back(t.value); + break; + } + case 2: /* pattern */ + case 3: /* pattern_full */ + if (err) *err = "this chat template triggers its tool-call grammar on the " + "regular expression '" + t.value + "'; only word and token " + "triggers are supported"; + return RAD_E_UNSUPPORTED; + default: + if (err) *err = "unknown grammar trigger type " + std::to_string(t.type); + return RAD_E_INVAL; + } + } + return RAD_OK; +} + +/* ================================================================== small helpers */ + +/* Copy this rank's window out of a whole-vocabulary bitmask. `vocab_off` is word-aligned for + * every shard this engine builds (the head is split on a multiple of 32), so the aligned arm is + * the one that runs; the bit-shifting arm exists because a shard boundary is a placement decision + * and not a promise, and a mask that is silently off by a few bits admits the wrong tokens. */ +void Sampler::shard_mask(uint32_t* dst) const { + const int64_t full = (int64_t)mask_full_.size(); + std::memset(dst, 0, (size_t)mask_words_ * 4); + if ((cfg_.vocab_off & 31) == 0) { + const int64_t w0 = cfg_.vocab_off >> 5; + const int64_t n = std::min(mask_words_, full - w0); + if (n > 0) std::memcpy(dst, mask_full_.data() + w0, (size_t)n * 4); + return; + } + for (int64_t i = 0; i < cfg_.n_vocab_local; ++i) { + const int64_t g = cfg_.vocab_off + i; + if (g >= cfg_.n_vocab) break; + if (mask_full_[(size_t)(g >> 5)] & (1u << (uint32_t)(g & 31))) + dst[i >> 5] |= 1u << (uint32_t)(i & 31); + } +} + +/* rad_runtime.h's RAD_B / RAD_W macros are C compound literals. They are legal C++ only as a + * compiler extension, and this file is core code that has to build with -Wall -Wextra clean, so + * the operands are built the ordinary way. */ +/* NARROWED TO THIS STEP'S ROWS, always. arch/common/rad_arch.h says why for the model's own + * buffers and the reason is the sampler's too: a kernel cannot read the row count out of `M`, + * because `M` is the band's upper bound, so every shim takes it off the operand. Handed over at + * its DECLARED extent -- max_seqs * (max_spec + 1) rows -- an operand makes every stage compute a + * full candidate set for rows that have no request behind them, over params the upload never + * wrote. The extra rows are discarded, so nothing downstream is wrong and no bench can see it, + * but each phantom row costs a vocabulary-wide reduction, and at one sequence every row but one + * is a phantom. + * + * `rows` is dim 0 for every buffer here -- logits, params, history, mask, candidates, pairs, the + * gather and the token output all count sampled POSITIONS first -- and the strides below it are + * products of the trailing dimensions, so shortening the outermost one leaves them correct. */ +static RadOperand opd_rows(rad_buf h, int64_t rows) { + RadOperand o{}; + o.kind = RAD_OPK_BUF; + o.handle = h; + o.rows = rows; + return o; +} + +/* An optional operand this issue does not pass. The runtime holds every issue to its schema's + * operand COUNT -- operands are positional -- so an absent trailing optional is spelled, not + * dropped. */ +static RadOperand opd_none() { + RadOperand o{}; + o.kind = RAD_OPK_NONE; + return o; +} + +static int64_t rows_for(const SamplerConfig& c) { + /* One row per SAMPLED POSITION, not per sequence: a speculative verify samples n_spec+1 + * positions for a sequence and each one has its own output position, hence its own RNG + * coordinate. Sizing for the worst step is the same rule the arena follows (spec §3.1). */ + return c.max_seqs * (int64_t)(c.max_spec + 1); +} + +/* ================================================================== declare */ + +int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) { + if (!b) return RAD_E_INVAL; + if (cfg.n_vocab <= 0 || cfg.max_seqs <= 0) { + RAD_ERR("sampler: n_vocab=%lld max_seqs=%lld is not a configuration", + (long long)cfg.n_vocab, (long long)cfg.max_seqs); + return RAD_E_INVAL; + } + + cfg_ = cfg; + if (cfg_.n_vocab_local <= 0) cfg_.n_vocab_local = cfg_.n_vocab / cfg_.world_size; + + /* THE STAGED MASK IS THIS RANK'S SHARD, AND THE GRAMMAR'S IS THE WHOLE VOCABULARY. Those are + * different lengths the moment the head is sharded, and conflating them is silent: every + * vocab-scoped sampler op is declared over `n_vocab_local` (op_vocab, below) and `sample_mask` + * indexes its bitmask from bit zero, so a full-vocabulary mask handed to rank 1 masks its + * logits with the admissibility of tokens 0..n_local -- ids that belong to rank 0. The result + * is not a diagnosable error, it is a rank sampling from the wrong permission set. + * + * So the grammar fills `mask_full_` over the whole vocabulary, which is also where the "no + * token is admissible anywhere" check belongs, and only this rank's window of it is staged. */ + mask_words_ = grammar_mask_words(cfg_.n_vocab_local); + mask_full_.assign((size_t)grammar_mask_words(cfg_.n_vocab), 0u); + + const int64_t rows = rows_for(cfg_); + const int64_t nv = cfg_.n_vocab_local; + const int64_t ncand = cfg_.max_candidates; + + /* ---------------------------------------------------------- buffers */ + /* PERSIST, not TRANSIENT: the parameter, history and mask planes are written by an upload + * that happens BEFORE the run phase issues anything, so liveness over the declared op list + * would conclude they are dead where they are in fact being filled. A transient whose first + * definition is invisible to the planner is a transient the planner will happily overwrite. */ + auto decl = [&](const char* name, uint32_t dt, int64_t d0, int64_t d1, int kind) -> rad_buf { + RadBufDecl d{}; + d.dtype = dt; + d.rank = 2; + d.shape[0] = d0; + d.shape[1] = d1; + d.kind = kind; + d.domain = RAD_DOMAIN_DEVICE; + return rad_decl_buffer(b, name, &d); + }; + + buf_params_ = decl("sampler.params", RAD_U32, rows, + (int64_t)(sizeof(DeviceSampleParams) / 4), RAD_BUF_PERSIST); + buf_hist_ = decl("sampler.history", RAD_I32, rows, cfg_.max_hist, RAD_BUF_PERSIST); + /* One byte beside every history token: nonzero where that token is a whole DRY sequence + * breaker, which DRY never penalises. Resolving a token against the breaker strings needs the + * vocabulary, so it happens here on the host and the kernel reads the answer. */ + buf_brk_ = decl("sampler.dry_breakers", RAD_U8, rows, cfg_.max_hist, RAD_BUF_PERSIST); + buf_mask_ = decl("sampler.mask", RAD_U32, rows, mask_words_, RAD_BUF_PERSIST); + buf_cand_i_ = decl("sampler.cand_idx", RAD_I32, rows, ncand, RAD_BUF_TRANSIENT); + buf_cand_v_ = decl("sampler.cand_val", RAD_F32, rows, ncand, RAD_BUF_TRANSIENT); + if (vocab_parallel()) { + /* THE PAIR PLANE AND THE GATHERED PLANE. sample_topk packs this rank's candidates into + * `pairs` as (u32 global id, f32 logit); the all-gather places every rank's pairs for a + * row SIDE BY SIDE, which is the one layout the merge can read at a single row stride. */ + buf_pairs_ = decl("sampler.cand_pairs", RAD_U32, rows, ncand * 2, RAD_BUF_TRANSIENT); + buf_gather_ = decl("sampler.cand_gathered", RAD_U32, rows, + ncand * cfg_.world_size * 2, RAD_BUF_TRANSIENT); + } + + if (!buf_params_ || !buf_hist_ || !buf_brk_ || !buf_mask_ || !buf_cand_i_ || !buf_cand_v_) { + RAD_ERR("sampler: a staging buffer failed to declare"); + return RAD_E_NOMEM; + } + + /* ---------------------------------------------------------- ops */ + /* Every one of these is declared unconditionally and may fail to resolve. That is not an + * error here: a deployment that never sends `typical_p` has no use for a typical kernel, and + * failing declare over it would make an absent sampler an absent model. check_request turns + * an unresolved sampler into a named refusal at admission instead. */ + /* `M` is the ranged parameter and it is the number of SAMPLED POSITIONS, not tokens: one row + * at decode, n_spec+1 per sequence at a verify, and a kernel written for a single row is a + * different kernel from one written for a batch of 256 (spec §2.2). */ + auto op_vocab = [&](const char* name) -> rad_op { + RadParam p[2] = { + RadParam{ "M", RAD_P_RANGE, 1, rows, nullptr }, + RadParam{ "n_vocab", RAD_P_INT, (long long)nv, 0, nullptr }, + }; + return rad_decl_op(b, name, p, 2, nullptr, 0); + }; + /* THE VOCABULARY OFFSET, on the three stages that cross between a token id and a column of + * this rank's logits row: top-k turns a column into a token id, and the penalties and DRY turn + * the history's token ids into columns. Without it a rank past the first penalises the + * columns of whatever ids happen to be small, which are other tokens entirely. Declared only + * when the vocabulary is sharded, so a single-rank graph carries no parameter it has no use + * for. */ + auto op_vocab_off = [&](const char* name) -> rad_op { + if (!vocab_parallel()) + return op_vocab(name); + RadParam p[3] = { + RadParam{ "M", RAD_P_RANGE, 1, rows, nullptr }, + RadParam{ "n_vocab", RAD_P_INT, (long long)nv, 0, nullptr }, + RadParam{ "vocab_off", RAD_P_INT, (long long)cfg_.vocab_off, 0, nullptr }, + }; + return rad_decl_op(b, name, p, 3, nullptr, 0); + }; + /* The stages after top-k read a candidate set, not the vocabulary, so their geometry is the + * candidate width. That is what makes them cheap: 1024 entries rather than 151K. */ + auto op_cand = [&](const char* name) -> rad_op { + RadParam p[2] = { + RadParam{ "M", RAD_P_RANGE, 1, rows, nullptr }, + RadParam{ "n_cand", RAD_P_INT, (long long)ncand, 0, nullptr }, + }; + return rad_decl_op(b, name, p, 2, nullptr, 0); + }; + + op_penalties_ = op_vocab_off("sample_penalties"); + op_dry_ = op_vocab_off("sample_dry"); + op_temp_ = op_vocab("sample_temp"); + op_mask_ = op_vocab("sample_mask"); + op_topk_ = op_vocab_off("sample_topk"); + op_argmax_ = op_vocab("sample_argmax"); + + op_topp_ = op_cand("sample_topp"); + op_minp_ = op_cand("sample_minp"); + op_typical_ = op_cand("sample_typical"); + op_xtc_ = op_cand("sample_xtc"); + op_pick_ = op_cand("sample_pick"); + + if (vocab_parallel()) { + /* lm_head is vocab-sharded, so each rank reduces ITS OWN shard and only the candidate + * sets are combined -- k * world_size pairs, 2 KiB at k=64 and world_size=4, against the + * ~77 MiB a full-logits gather would move (spec §9). */ + RadParam ag[4] = { + RadParam{ "world_size", RAD_P_INT, (long long)cfg_.world_size, 0, nullptr }, + RadParam{ "numel", RAD_P_INT, (long long)(rows * ncand * 2), 0, nullptr }, + RadParam{ "dtype", RAD_P_STR, 0, 0, "f32" }, + /* ROW-INTERLEAVED. One sampled position's pairs from every rank have to land side by + * side, because sample_merge_topk reads one row at one row stride. */ + RadParam{ "row", RAD_P_INT, (long long)(ncand * 2), 0, nullptr }, + }; + op_allgather_ = rad_decl_op(b, "all_gather", ag, 4, nullptr, 0); + op_merge_ = op_cand("sample_merge_topk"); + } + + RAD_TRY(stage_alloc()); + declared_ = true; + + RAD_INFO("sampler: %lld-token vocabulary (%lld this rank), %lld rows, %lld mask words " + "(%s per row)", (long long)cfg_.n_vocab, (long long)nv, (long long)rows, + (long long)mask_words_, humanb(mask_words_ * 4).c_str()); + return RAD_OK; +} + +int Sampler::stage_alloc() { + const int64_t rows = rows_for(cfg_); + + /* Pinned, because these are uploaded every step and a pageable source turns an async copy + * into a staged one with a host bounce -- which is exactly the per-step cost the step batch + * exists to remove (spec §8). */ + params_stage_ = (DeviceSampleParams*)rad_dev_alloc( + rows * (int64_t)sizeof(DeviceSampleParams), RAD_MEM_HOST_PINNED); + greedy_stage_ = (DeviceSampleParams*)rad_dev_alloc( + rows * (int64_t)sizeof(DeviceSampleParams), RAD_MEM_HOST_PINNED); + greedy_ready_ = false; + hist_stage_ = (int32_t*)rad_dev_alloc(rows * cfg_.max_hist * 4, RAD_MEM_HOST_PINNED); + brk_stage_ = (uint8_t*)rad_dev_alloc(rows * cfg_.max_hist, RAD_MEM_HOST_PINNED); + mask_stage_ = (uint32_t*)rad_dev_alloc(rows * mask_words_ * 4, RAD_MEM_HOST_PINNED); + + if (!params_stage_ || !greedy_stage_ || !hist_stage_ || !brk_stage_ || !mask_stage_) { + RAD_ERR("sampler: could not pin %s of staging", + humanb(rows * ((int64_t)sizeof(DeviceSampleParams) + cfg_.max_hist * 5 + + mask_words_ * 4)).c_str()); + stage_free(); + return RAD_E_NOMEM; + } + return RAD_OK; +} + +void Sampler::stage_free() { + if (params_stage_) rad_dev_free(params_stage_, RAD_MEM_HOST_PINNED); + if (greedy_stage_) rad_dev_free(greedy_stage_, RAD_MEM_HOST_PINNED); + if (hist_stage_) rad_dev_free(hist_stage_, RAD_MEM_HOST_PINNED); + if (brk_stage_) rad_dev_free(brk_stage_, RAD_MEM_HOST_PINNED); + if (mask_stage_) rad_dev_free(mask_stage_, RAD_MEM_HOST_PINNED); + params_stage_ = nullptr; + greedy_stage_ = nullptr; + cur_stage_ = nullptr; + hist_stage_ = nullptr; + brk_stage_ = nullptr; + mask_stage_ = nullptr; +} + +Sampler::~Sampler() { stage_free(); } + +/* ================================================================== admission */ + +/* WHEN THE TWO HISTORY STAGES RUN, in one place, because admission, request setup and the step + * staging each ask and must not disagree. llama.cpp's meaning throughout: a window of 0 turns the + * stage off, and DRY also needs a base of at least 1. The multiplier is taken as positive because + * a negative one rewards repetition, which is not a request anyone makes on purpose. */ +static bool penalties_on(const SamplingParams& sp) { + return sp.penalty_last_n != 0 && + (sp.rep_penalty != 1.0f || sp.freq_penalty != 0.0f || sp.pres_penalty != 0.0f); +} + +static bool dry_on(const SamplingParams& sp) { + return sp.dry_multiplier > 0.0f && sp.dry_base >= 1.0f && sp.dry_penalty_last_n != 0; +} + +int Sampler::check_request(const SamplingParams& sp, std::string* why) const { + auto refuse = [&](const char* what, int st) { + if (why) *why = what; + return st; + }; + + if (sp.top_k < 0) return refuse("top_k is negative", RAD_E_INVAL); + if (sp.top_p < 0.0f || sp.top_p > 1.0f) return refuse("top_p is outside [0,1]", RAD_E_INVAL); + if (sp.min_p < 0.0f || sp.min_p > 1.0f) return refuse("min_p is outside [0,1]", RAD_E_INVAL); + if (sp.typical_p < 0.0f || sp.typical_p > 1.0f) + return refuse("typical_p is outside [0,1]", RAD_E_INVAL); + if (sp.temp < 0.0f) return refuse("temperature is negative", RAD_E_INVAL); + if (sp.top_k > cfg_.max_candidates) + return refuse("top_k exceeds the sampler's candidate width (--max-candidates)", + RAD_E_INVAL); + /* Every breaker is a pass over the whole vocabulary on the scheduler thread, and every other + * sequence on the server waits for it; see kDryMaxBreakers. Refused here, before any of that + * work is queued, rather than truncated -- a request whose breakers quietly went missing is a + * request whose output changed. */ + if (dry_on(sp) && sp.dry_seq_breakers.size() > kDryMaxBreakers) { + if (why) + *why = "dry_sequence_breakers has " + std::to_string(sp.dry_seq_breakers.size()) + + " entries; at most " + std::to_string(kDryMaxBreakers) + " are accepted"; + return RAD_E_INVAL; + } + + /* An unresolved sampler is a named refusal, not a silent skip. A request whose min_p quietly + * stopped being applied is a request whose output changed and nothing said so. */ + auto need = [&](bool wanted, rad_op h, const char* n) -> const char* { + return (wanted && !h) ? n : nullptr; + }; + /* A SPLIT VOCABULARY MOVES GREEDY ONTO THE CHAIN, so what a greedy request needs moves with + * it: not the argmax, but the top-k, the merge and the pick that build_step's top_k = 1 sends + * it through. Admission has to check what will actually be issued. */ + const bool greedy_chain = sp.greedy() && vocab_parallel(); + const char* missing = nullptr; + if (!missing) missing = need(sp.greedy() && !greedy_chain, op_argmax_, "sample_argmax"); + if (!missing) missing = need(!sp.greedy(), op_temp_, "sample_temp"); + if (!missing) missing = need(!sp.greedy() || greedy_chain, op_pick_, "sample_pick"); + /* EVERY CHAIN ROW NEEDS THE TOP-K, whatever its own top_k says: it is the stage that writes + * the candidate set every later stage reads. top_k = 0 asks for the whole candidate width, + * not for no candidates. */ + if (!missing) missing = need(!sp.greedy() || greedy_chain, op_topk_, "sample_topk"); + if (!missing) missing = need(sp.top_p < 1.0f, op_topp_, "sample_topp"); + if (!missing) missing = need(sp.min_p > 0.0f, op_minp_, "sample_minp"); + if (!missing) missing = need(sp.typical_p < 1.0f, op_typical_, "sample_typical"); + if (!missing) missing = need(sp.xtc_probability > 0.0f, op_xtc_, "sample_xtc"); + if (!missing) missing = need(dry_on(sp), op_dry_, "sample_dry"); + if (!missing) missing = need(!sp.grammar.empty(), op_mask_, "sample_mask"); + if (!missing) missing = need(penalties_on(sp), op_penalties_, "sample_penalties"); + if (missing) { + if (why) *why = std::string("no kernel resolved for '") + missing + "'"; + return RAD_E_NOKERNEL; + } + + if (!sp.grammar.empty() && !vocab_) + return refuse("a grammar was requested before the vocabulary was attached", RAD_E_STATE); + + /* The triggers are resolved here as well as at begin_request, so a template whose triggers + * this machine cannot run is a refusal at admission rather than a request cancelled on the + * scheduler thread. */ + if (!sp.grammar.empty() && !sp.grammar_triggers.empty()) { + std::vector words; + std::vector tokens; + std::string e; + const int st = resolve_triggers(*vocab_, sp.grammar_triggers, &words, &tokens, &e); + if (st < 0) { + if (why) *why = e; + return st; + } + } + + return RAD_OK; +} + +int Sampler::begin_request(uint64_t req_id, const SamplingParams& sp, std::string* err) { + SeqState st; + + if (!sp.grammar.empty()) { + if (!vocab_) { + if (err) *err = "no vocabulary attached"; + return RAD_E_STATE; + } + GrammarSpec spec; + spec.kind = GrammarKind::Gbnf; + spec.text = sp.grammar; + spec.root = "root"; + spec.lazy = sp.grammar_lazy; + /* ONLY A NON-LAZY GRAMMAR IS POSITIONED AT THE START OF THE TURN. An eager grammar's root + * describes the whole assistant turn and therefore opens with the generation prompt, which + * is already in the prompt -- so it has to be replayed or the model is made to write it + * out again. A LAZY one describes only the region after its trigger: its root begins at + * ``, and feeding it a prefix it never claimed to match fails outright, taking + * every tool-calling request with it. */ + spec.prefix = sp.grammar_lazy ? std::string() : sp.grammar_prefix; + RAD_TRY(resolve_triggers(*vocab_, sp.grammar_triggers, &spec.trigger_words, + &spec.trigger_tokens, err)); + RAD_TRY(grammar_create(spec, *vocab_, &st.grammar, err)); + } + + /* BREAKERS ARE OPTIONAL. DRY runs whenever the request turns it on, as llama.cpp's does with an + * empty breaker list; the breakers only limit how far back a repeat may be counted and exempt + * the tokens that are breakers themselves. */ + if (dry_on(sp) && !sp.dry_seq_breakers.empty()) { + if (!vocab_) { + if (err) *err = "DRY needs a vocabulary to resolve its sequence breakers"; + return RAD_E_STATE; + } + if (sp.dry_seq_breakers.size() > kDryMaxBreakers) { + if (err) *err = "too many DRY sequence breakers"; + return RAD_E_INVAL; + } + /* Once per request, never per step: a full vocabulary scan per breaker string is + * milliseconds at a 151K vocab and has no business on the step path. */ + const int s = dry_prepare_breakers(*vocab_, sp.dry_seq_breakers, &st.dry, + kDryBreakerMaxTail); + if (s < 0) { + if (err) *err = "a DRY sequence breaker could not be resolved against the vocabulary"; + return s; + } + } + + seqs_[req_id] = std::move(st); + return RAD_OK; +} + +void Sampler::end_request(uint64_t req_id) { seqs_.erase(req_id); } +bool Sampler::has_request(uint64_t req_id) const { return seqs_.find(req_id) != seqs_.end(); } + +std::vector Sampler::take_failed() { + std::vector v; + v.swap(failed_); + return v; +} + +int Sampler::accept_token(uint64_t req_id, int32_t token) { + auto it = seqs_.find(req_id); + if (it == seqs_.end()) return RAD_OK; /* no grammar, nothing to advance */ + if (!it->second.grammar) return RAD_OK; + /* TIMED for the same reason build_step is: this runs once per ACCEPTED token per rank, on the + * step thread, so it is wall time on every constrained token. */ + if ((int)log_level() < (int)Log::Debug) return it->second.grammar->accept_token(token); + const auto t0 = std::chrono::steady_clock::now(); + const int s = it->second.grammar->accept_token(token); + accept_us_ += std::chrono::duration( + std::chrono::steady_clock::now() - t0).count(); + if (++accept_n_ == 256) { + RAD_DEBUG("sampler: grammar accept_token %.3f ms mean over 256", accept_us_ / 256000.0); + accept_us_ = 0; accept_n_ = 0; + } + return s; +} + +/* A CONSTRAINING GRAMMAR DOES NOT MEAN NO SPECULATION. build_step masks draft position i + * against the state reached by accepting drafts 0..i-1 and then rewinds, so a backend that can + * push and pop its state speculates like any other request -- which is worth several times the + * per-token cost on a constrained request. What IS refused is a backend that cannot rewind: + * masking its window would mean masking against a state the sequence is not in. */ +bool Sampler::allows_speculation(uint64_t req_id) const { + auto it = seqs_.find(req_id); + if (it == seqs_.end() || !it->second.grammar) return true; + return !it->second.grammar->constrains() || it->second.grammar->can_speculate(); +} + +bool Sampler::speculation_fixed(uint64_t req_id) const { + auto it = seqs_.find(req_id); + return it != seqs_.end() && (!it->second.grammar || it->second.grammar->can_speculate()); +} + +/* ================================================================== the step path */ + +int Sampler::build_step(const std::vector& reqs) { + if (!declared_) return RAD_E_STATE; + + const auto t_build = std::chrono::steady_clock::now(); + const int64_t cap = rows_for(cfg_); + n_seq_ = 0; + any_brk_ = false; + cur_stage_ = params_stage_; + + /* DRY'S HOST HALF, for one row whose history `h[0, take)` is already staged. The breakers are + * strings resolved against the vocabulary, so what they mean for this window is worked out + * here and handed to the kernel as data: the repeat limit the most recent breaker imposes + * (llama.cpp's step 1), and one byte per position marking the tokens that are whole breakers + * and therefore never penalised. The window is the one the kernel will take -- the tail of + * the staged row, `dry_penalty_last_n` long when that is positive. + * + * Returns false when the breakers rule DRY out for the row altogether: a breaker closer to the + * end than `allowed_length` leaves no repeat long enough to count. A row with no breakers + * gets zero marks, because the plane is shared by the whole batch and another row may have + * some. */ + auto stage_dry = [&](DeviceSampleParams& p, const int32_t* h, int64_t take, + const DryBreakers* brk, int64_t row) -> bool { + const int64_t last_n = p.dry_penalty_last_n; + const int64_t win = last_n > 0 ? std::min(take, last_n) : take; + const int64_t w0 = take - win; + const int32_t allowed = p.dry_allowed_length > 0 ? p.dry_allowed_length : 2; + uint8_t* f = brk_stage_ + row * cfg_.max_hist + w0; + if (!brk) { + std::memset(f, 0, (size_t)win); + return true; + } + if (win <= allowed) return true; /* the kernel takes its own early out */ + const int rep = dry_rep_limit(*brk, h + w0, (int)win); + if (rep < allowed) return false; + p.dry_rep_limit = rep < win ? rep : 0; + for (int64_t i = 0; i < win; ++i) f[i] = brk->is_single(h[w0 + i]) ? 1 : 0; + any_brk_ = true; + return true; + }; + + for (Request* r : reqs) { + if (!r) continue; + const SamplingParams& sp = r->sp; + const int n_pos = r->n_draft + 1; + + if (n_pos > 1 && !allows_speculation(r->id)) { + RAD_ERR("sampler: request %llu carries a constraining grammar its backend cannot " + "snapshot, and %d draft tokens. The mask for draft position i is the mask of " + "the state reached by accepting drafts 0..i-1, so masking the window needs " + "push_state/rollback. The scheduler must consult allows_speculation() and " + "decode this one a token at a time.", + (unsigned long long)r->id, r->n_draft); + return RAD_E_UNSUPPORTED; + } + + if (n_seq_ + n_pos > cap) { + RAD_ERR("sampler: %lld sampled positions exceeds the %lld the arena was sized for", + (long long)(n_seq_ + n_pos), (long long)cap); + return RAD_E_FULL; + } + + const int64_t n_prompt = (int64_t)r->prompt.size(); + const int64_t n_out = (int64_t)r->output.size(); + const int64_t n_total = n_prompt + n_out; + const bool pen = penalties_on(sp); + const bool dry = dry_on(sp); + + auto it = seqs_.find(r->id); + SeqState* st = it == seqs_.end() ? nullptr : &it->second; + const DryBreakers* brk = st && !st->dry.empty() ? &st->dry : nullptr; + + /* THE WINDOW IS WALKED, THEN REWOUND. Position 0 is masked against the state the sequence + * is really in; position k against the state reached by accepting drafts 0..k-1. The push + * happens whatever the grammar's current mode, because a draft token can fire a lazy + * grammar's trigger mid-window -- at which point the positions behind it DO need a mask, + * and without the push they would be sampled unconstrained. + * + * `dead` is not a failure. A draft the grammar forbids simply cannot be accepted: the + * target's own masked pick at that position will differ from it, so verification rejects + * there and every position behind it is discarded. Masking stops and the rest of the + * window is left unconstrained, which is what "discarded" needs it to be. */ + GrammarBackend* gr = st && st->grammar ? st->grammar.get() : nullptr; + const bool walk = gr && n_pos > 1; + if (walk) gr->push_state(); + bool dead = false; + + for (int k = 0; k < n_pos; ++k) { + if (walk && k > 0 && !dead && gr->accept_token(r->draft[k - 1]) < 0) dead = true; + const int64_t row = n_seq_++; + + DeviceSampleParams& p = params_stage_[row]; + std::memset(&p, 0, sizeof p); + + p.seed = sp.seed; + /* The output position, advanced across the speculative window: draft position k is + * the (n_out + k)-th token this request will emit, so its randomness is the same + * whether it arrived through speculation or one token at a time. */ + p.pos = (uint64_t)(n_out + k); + + p.temp = sp.temp; + p.top_p = sp.top_p; + p.min_p = sp.min_p; + p.typical_p = sp.typical_p; + p.rep_penalty = sp.rep_penalty; + p.freq_penalty = sp.freq_penalty; + p.pres_penalty = sp.pres_penalty; + p.xtc_probability = sp.xtc_probability; + p.xtc_threshold = sp.xtc_threshold; + p.dry_multiplier = sp.dry_multiplier; + p.dry_base = sp.dry_base; + p.top_k = sp.top_k; + p.penalty_last_n = sp.penalty_last_n; + p.dry_allowed_length = sp.dry_allowed_length; + p.dry_penalty_last_n = sp.dry_penalty_last_n; + p.mask_row = -1; + + /* GREEDY OVER A SPLIT VOCABULARY IS A TOP-1 CHAIN, not an argmax. sample_argmax reads a + * whole logits row and writes the winning COLUMN, which under vocab parallelism is + * this rank's local index into its own shard -- a fluent answer built from the wrong + * token ids. Staging top_k = 1 sends the row through top-k, the pair plane, the + * gather and the merge instead, which is where a local index becomes a global one; + * sample_pick over a single live candidate returns it deterministically, so the + * result is the argmax it was always meant to be. + * + * Such a row is a CHAIN row and does not carry RAD_SP_GREEDY: every candidate stage + * skips a row that does, because in an unsplit batch that flag is what keeps the pick + * from overwriting the argmax's answer with a draw. */ + if (sp.greedy()) { + if (vocab_parallel()) p.top_k = 1; + else p.flags |= RAD_SP_GREEDY; + } + if (sp.xtc_probability > 0.0f) p.flags |= RAD_SP_XTC; + + /* THE HISTORY THE PENALTIES AND DRY READ, staged only for a row that runs one of them + * -- the copy is scheduler-thread work and the upload is step-path bytes, and neither + * buys anything for a row that reads none of it. It is the prompt, everything + * generated so far and, at draft position k, the k drafted tokens in front of it: the + * token sampled there is emitted only if those drafts are, so they are part of the + * output it is penalised against, exactly as they would be one token at a time. Oldest + * first, truncated to the declared window -- a bound on the buffer, not a policy on + * the sampler; penalty_last_n still decides how much of it counts. The row owns its + * own row of the plane, so the window starts at offset 0 within it. */ + p.hist_off = 0; + p.hist_len = 0; + if (pen || dry) { + const int64_t len = n_total + k; + const int64_t take = std::min(len, cfg_.max_hist); + int32_t* h = hist_stage_ + row * cfg_.max_hist; + for (int64_t i = 0; i < take; ++i) { + const int64_t src = len - take + i; + h[i] = src < n_prompt ? r->prompt[(size_t)src] + : src < n_total ? r->output[(size_t)(src - n_prompt)] + : r->draft[src - n_total]; + } + p.hist_len = (int32_t)take; + if (pen) p.flags |= RAD_SP_PENALTY; + if (dry && stage_dry(p, h, take, brk, row)) p.flags |= RAD_SP_DRY; + } + + if (gr && !dead && gr->constrains()) { + uint32_t* dst = mask_stage_ + row * mask_words_; + int s; + /* WHAT THE MASK COSTS, MEASURED RATHER THAN ASSUMED. The mask is scheduler-thread + * work with the rank threads waiting at the barrier, so it is wall time on every + * constrained token and would decide the step if it were slow. Reported at Debug, + * per 256 masks, mean and worst. */ + const bool inst = (int)log_level() >= (int)Log::Debug; + const auto t0 = std::chrono::steady_clock::now(); + /* ASK THE GRAMMAR WHETHER IT COMPUTED THE MASK, rather than inferring it from how + * long the call took. No duration threshold separates the two: a mask computed + * from the plan can finish inside the time a memo hit costs on a large + * vocabulary, so a timing test counts computed masks as hits and any per-mask + * cost derived from the split is wrong by that factor. The counter is exact and + * costs a relaxed load. */ + const uint64_t w0 = inst ? st->grammar->masks_walked() : 0; + if (!vocab_parallel()) { + s = st->grammar->fill_mask(dst, mask_words_); + } else { + s = st->grammar->fill_mask(mask_full_.data(), (int64_t)mask_full_.size()); + if (s >= 0) shard_mask(dst); + } + if (inst) { + const double us = std::chrono::duration( + std::chrono::steady_clock::now() - t0).count(); + mask_us_ += us; mask_worst_us_ = mask_us_n_ && us < mask_worst_us_ + ? mask_worst_us_ : us; + if (st->grammar->masks_walked() != w0) { ++mask_slow_; mask_walk_us_ += us; } + else ++mask_fast_; + if (++mask_us_n_ == 256) { + /* Mean per MASK and mean per COMPUTED mask are different questions and + * the second is the one that says what a new state costs: a window's + * masks are mostly memo hits, so the first tracks how many positions + * asked. */ + RAD_DEBUG("sampler: grammar mask %.2f ms mean, %.2f ms worst over 256; " + "%lld memo hits, %lld computed at %.2f ms mean (%lld vocab, " + "%lld words)", + mask_us_ / 256000.0, mask_worst_us_ / 1000.0, + (long long)mask_fast_, (long long)mask_slow_, + mask_slow_ ? mask_walk_us_ / (1000.0 * (double)mask_slow_) : 0.0, + (long long)cfg_.n_vocab, (long long)mask_words_); + mask_us_ = 0; mask_us_n_ = 0; mask_worst_us_ = 0; + mask_fast_ = 0; mask_slow_ = 0; mask_walk_us_ = 0.0; + } + } + if (s < 0 && k > 0) { + /* A SPECULATIVE POSITION IS NOT A DEAD REQUEST. This is the state reached by + * accepting drafts the sequence has not committed to, so "nothing is + * admissible here" says the draft is wrong, not that the request is stuck. + * Verification will reject at or before this position; stop masking and leave + * the rest of the window unconstrained, since it is about to be discarded. */ + dead = true; + } else if (s < 0) { + /* A DEAD GRAMMAR FAILS ITS REQUEST, NOT THE STEP. Returning a status here + * would reach the step loop as an engine fault and stop it stepping, so every + * other client on the server would stop receiving tokens because one of them + * sent a schema the model painted itself out of. The row is left unmasked for + * this step -- it is about to be cancelled -- and the id goes to the engine + * to close. */ + RAD_WARN("sampler: request %llu has no admissible token under its grammar; " + "failing that request", (unsigned long long)r->id); + failed_.push_back(r->id); + } else { + p.mask_row = (int32_t)row; + p.flags |= RAD_SP_MASK; + if ((int)log_level() >= (int)Log::Trace) { + /* How many tokens the grammar allows THIS RANK to pick. Zero is legal + * under sharding -- the admissible set can live entirely on another rank + * -- and is the first thing to check when a grammar-constrained answer + * comes out unconstrained. */ + int64_t bits = 0; + for (int64_t w = 0; w < mask_words_; ++w) + bits += __builtin_popcount(dst[w]); + RAD_TRACE("sampler: req %llu row %lld mask allows %lld of %lld local " + "tokens (vocab_off %lld)", (unsigned long long)r->id, + (long long)row, (long long)bits, + (long long)cfg_.n_vocab_local, (long long)cfg_.vocab_off); + } + } + } + } + + /* Back to where the sequence actually is. The tokens it really accepted are applied by + * Sampler::accept_token after the step verifies, so anything the walk did must be gone + * before then or the grammar would be ahead of the sequence by the whole window. */ + if (walk) RAD_TRY(gr->rollback()); + } + + /* THE WHOLE OF IT, not just the mask, because that is what the rank threads wait for. Without + * this the mask's own number could fall to nothing and the step stay slow with no way to see + * which side of the barrier the time was on. */ + if ((int)log_level() >= (int)Log::Debug) { + build_us_ += std::chrono::duration( + std::chrono::steady_clock::now() - t_build).count(); + if (++build_n_ == 256) { + RAD_DEBUG("sampler: build_step %.3f ms mean over 256 (%lld rows)", + build_us_ / 256000.0, (long long)n_seq_); + build_us_ = 0; build_n_ = 0; + } + } + return RAD_OK; +} + +int Sampler::build_greedy(int64_t n) { + if (!declared_) return RAD_E_STATE; + if (n < 0) return RAD_E_INVAL; + const int64_t cap = rows_for(cfg_); + if (n > cap) { + RAD_ERR("sampler: %lld greedy rows exceeds the %lld the arena was sized for", + (long long)n, (long long)cap); + return RAD_E_FULL; + } + n_seq_ = n; + any_brk_ = false; + cur_stage_ = greedy_stage_; + if (greedy_ready_) return RAD_OK; + for (int64_t i = 0; i < cap; ++i) { + DeviceSampleParams& p = greedy_stage_[i]; + std::memset(&p, 0, sizeof p); + p.temp = 0.0f; + p.top_k = 1; + p.hist_off = 0; + p.hist_len = 0; + p.mask_row = -1; + /* Over a split vocabulary a greedy row is a top-1 CHAIN row, for the reason build_step + * gives, and so it does not carry the flag every candidate stage skips. */ + p.flags = vocab_parallel() ? 0 : RAD_SP_GREEDY; + } + greedy_ready_ = true; + return RAD_OK; +} + +int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) { + if (!declared_) return RAD_E_STATE; + if (!c || !logits || !out_tokens) return RAD_E_INVAL; + if (n_seq_ == 0) return RAD_OK; + + const RadStream s = rad_stream(c); + + bool any_mask = false, any_greedy = false, any_chain = false; + bool any_penalty = false, any_dry = false, any_xtc = false; + bool any_topp = false, any_minp = false, any_typ = false; + for (int64_t i = 0; i < n_seq_; ++i) { + const DeviceSampleParams& p = cur_stage_[i]; + any_mask |= (p.flags & RAD_SP_MASK) != 0; + any_penalty |= (p.flags & RAD_SP_PENALTY) != 0; + any_dry |= (p.flags & RAD_SP_DRY) != 0; + any_xtc |= (p.flags & RAD_SP_XTC) != 0; + if (p.flags & RAD_SP_GREEDY) any_greedy = true; + else { + any_chain = true; + any_topp |= p.top_p < 1.0f; + any_minp |= p.min_p > 0.0f; + any_typ |= p.typical_p < 1.0f; + } + } + + /* A GREEDY ROW OVER A SPLIT VOCABULARY is staged as a top-1 chain row, never with the flag: + * the argmax would return this rank's column for a token id. build_step and build_greedy both + * hold that, so a flagged row here is a staging bug, and it is refused rather than served. */ + if (any_greedy && vocab_parallel()) { + RAD_ERR("sampler: a greedy-flagged row reached a split vocabulary, where the argmax " + "returns a column of this rank's shard rather than a token id"); + return RAD_E_STATE; + } + + /* Async copies on the compute stream and no host synchronisation, and only of what some row + * will read: the history and the breaker marks for the penalties and DRY, the mask for a + * grammar. The mask upload is 19 KiB a constrained sequence at a 151K vocab, which is the + * number that makes a host-side grammar affordable at all (spec §13). */ + RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_params_), cur_stage_, + n_seq_ * (int64_t)sizeof(DeviceSampleParams), s)); + if (any_penalty || any_dry) + RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_hist_), hist_stage_, + n_seq_ * cfg_.max_hist * 4, s)); + const bool pass_brk = any_dry && any_brk_; + if (pass_brk) + RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_brk_), brk_stage_, + n_seq_ * cfg_.max_hist, s)); + if (any_mask) + RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_mask_), mask_stage_, + n_seq_ * mask_words_ * 4, s)); + + const RadOperand o_logits = opd_rows(logits, n_seq_); + const RadOperand o_params = opd_rows(buf_params_, n_seq_); + const RadOperand o_hist = opd_rows(buf_hist_, n_seq_); + const RadOperand o_brk = opd_rows(buf_brk_, n_seq_); + const RadOperand o_mask = opd_rows(buf_mask_, n_seq_); + const RadOperand o_ci = opd_rows(buf_cand_i_, n_seq_); + const RadOperand o_cv = opd_rows(buf_cand_v_, n_seq_); + const RadOperand o_tok = opd_rows(out_tokens, n_seq_); + + auto issue = [&](rad_op op, std::initializer_list ops) -> int { + std::vector v(ops); + return rad_issue(c, op, v.data(), (int)v.size(), n_seq_); + }; + + /* Penalties act on raw logits, before anything derives a probability from them. DRY takes the + * breaker marks only when some row in the batch has breakers; its fourth operand is optional + * and absent means no token is exempt. */ + if (any_penalty) RAD_TRY(issue(op_penalties_, { o_logits, o_params, o_hist })); + if (any_dry) + RAD_TRY(issue(op_dry_, { o_logits, o_params, o_hist, pass_brk ? o_brk : opd_none() })); + + /* The greedy rows take the argmax after penalties and the mask and never see temperature. + * When the batch is mixed, BOTH the argmax and the chain are issued over the whole batch: the + * argmax writes every row's token, and then every candidate stage skips the greedy rows + * (RAD_SP_GREEDY) so the pick overwrites only the rows the chain owns. The cost is one extra + * pass over the logits for the rows the other op owns -- ~77 MiB read at batch 256 -- against + * one kernel launch per distinct parameter set, which at batch 256 is up to 256 launches. The + * pass wins. + * + * Under vocab parallelism there is no greedy shortcut at all: build_step staged those rows at + * top_k = 1, without the flag, so they take the chain, where the merge turns a local candidate + * index into a global token id. */ + if (any_greedy) { + if (any_mask) RAD_TRY(issue(op_mask_, { o_logits, o_params, o_mask })); + RAD_TRY(issue(op_argmax_, { o_logits, o_params, o_tok })); + } + + if (!any_chain) return RAD_OK; + + RAD_TRY(issue(op_temp_, { o_logits, o_params })); + if (any_mask && !any_greedy) + RAD_TRY(issue(op_mask_, { o_logits, o_params, o_mask })); + + /* top-k reduces the vocabulary to a candidate set, and everything after it works on that set. + * Under tensor parallel this is the LOCAL top-k over this rank's shard; the candidate sets + * are combined below and full logits are never gathered (spec §9). + * + * IT IS ISSUED WHENEVER THE CHAIN RUNS, not only when some row sets top_k. A row at + * top_k = 0 asks for the whole candidate width, and the candidate planes are transient: a + * step that skipped this would hand the pick whatever the planes last held -- the previous + * step's candidates, or another op's bytes. */ + if (vocab_parallel()) { + /* The fifth operand is the pair plane: this rank's candidates with GLOBAL ids, which is + * what crosses the wire. cand_idx and cand_val still come back LOCAL and the merge + * overwrites both, so nothing downstream ever sees a local id. */ + const RadOperand o_p = opd_rows(buf_pairs_, n_seq_); + const RadOperand o_g = opd_rows(buf_gather_, n_seq_); + RAD_TRY(issue(op_topk_, { o_logits, o_params, o_ci, o_cv, o_p })); + RAD_TRY(issue(op_allgather_, { o_p, o_g })); + RAD_TRY(issue(op_merge_, { o_g, o_params, o_ci, o_cv })); + } else { + /* No pair plane on a whole vocabulary, and it is passed as absent rather than left off: + * the schema has five operands and an issue of four is refused. */ + RAD_TRY(issue(op_topk_, { o_logits, o_params, o_ci, o_cv, opd_none() })); + } + + if (any_topp) RAD_TRY(issue(op_topp_, { o_ci, o_cv, o_params })); + if (any_minp) RAD_TRY(issue(op_minp_, { o_ci, o_cv, o_params })); + if (any_typ) RAD_TRY(issue(op_typical_, { o_ci, o_cv, o_params })); + if (any_xtc) RAD_TRY(issue(op_xtc_, { o_ci, o_cv, o_params })); + + RAD_TRY(issue(op_pick_, { o_ci, o_cv, o_params, o_tok })); + return RAD_OK; +} + +} /* namespace rad */ diff --git a/core/sample/sampler.h b/core/sample/sampler.h new file mode 100644 index 00000000..7a60a662 --- /dev/null +++ b/core/sample/sampler.h @@ -0,0 +1,306 @@ +/* sampler.h -- the sampler driver. + * + * SAMPLING RUNS ON DEVICE (spec §13). At a 151K vocab and batch 256 the logits are ~77 MiB a + * step; moving them across the link to run a host chain costs both the bandwidth and a + * synchronisation, on the step path, at exactly the concurrency the engine exists to serve. So + * every sampler is a kernel, not a lift -- and this file does not implement one. It ISSUES the + * declared sampler ops in order, exactly as an architecture plugin issues a GEMM: declared + * through the ordinary builder, resolved through the ordinary hierarchy, serviced by + * `libref` on the host domain or by a device plugin on the fast one. + * + * THE ORDER, and it is not a detail -- reordering changes which tokens survive: + * + * penalties (repetition / frequency / presence, then DRY) + * temperature + * the grammar mask + * top-k + * top-p, min-p, typical + * XTC + * the pick + * + * A GREEDY SEQUENCE SKIPS ALL OF IT and takes `sample_argmax` -- after penalties and the mask, + * because temperature 0 collapses every other logit to -inf and a mask applied afterwards would + * leave nothing at all. host_ref.cpp makes the same choice for the same reason and the two must + * agree, or a temperature-0 request stops matching a greedy run. + * + * PARAMETERS ARE DATA, NOT BRANCHES. Sequences in one batch have different sampling parameters, + * so the parameters are a device-side per-sequence array built once per step from a pinned + * staging buffer -- the same discipline the step batch uses (spec §8). A kernel that branched on + * a host-side parameter would need one launch per distinct parameter set, which at batch 256 is + * up to 256 launches for what is one kernel's worth of work. + * + * THE SCHEMA THIS DRIVER ISSUES AGAINST (docs/OPS.md, "Sampling"). No per-sequence value is an + * op PARAMETER, because parameters are geometry -- the thing the selector matches constraints + * against and freezes at declare. A per-sequence value cannot live there: two requests in one + * batch with different top_p would be two different geometries and therefore two different + * resolutions of the same op. The seed and output position `sample_pick` draws from are in the + * parameter row too. So every sampler op takes the row array as an operand: + * + * sample_penalties M(range) n_vocab vocab_off? logits, params, history -> logits (inout) + * sample_dry M(range) n_vocab vocab_off? logits, params, history, breakers? + * -> logits (inout) + * sample_temp M(range) n_vocab logits, params -> logits (inout) + * sample_mask M(range) n_vocab logits, params, bitmask -> logits (inout) + * sample_topk M(range) n_vocab vocab_off? logits, params -> cand_idx, cand_val, + * pairs? + * sample_argmax M(range) n_vocab logits, params -> token + * sample_topp M(range) n_cand cand_idx, cand_val, params -> cand_idx, cand_val + * sample_minp M(range) n_cand cand_idx, cand_val, params -> cand_idx, cand_val + * sample_typical M(range) n_cand cand_idx, cand_val, params -> cand_idx, cand_val + * sample_xtc M(range) n_cand cand_idx, cand_val, params -> cand_idx, cand_val + * sample_pick M(range) n_cand cand_idx, cand_val, params -> token + * sample_merge_topk M(range) n_cand gathered, params -> cand_idx, cand_val + * + * `M` is the number of SAMPLED POSITIONS, not tokens: one per sequence at decode, n_spec+1 per + * sequence at a verify. `params` is [M] rows of DeviceSampleParams below; `history` is + * [M, max_hist] int32 of GLOBAL token ids, row m addressed by row m's hist_off/hist_len; + * `breakers` is [M, max_hist] uint8 beside it, nonzero where that position's token is a whole DRY + * sequence breaker; `bitmask` is [M, mask_words] uint32 addressed by the row's mask_row. + * `vocab_off` is this rank's first vocabulary row and is declared only when the vocabulary is + * split: the three ops that turn a token id into a column of this rank's logits subtract it. + * Every one of these has a libref implementation: a sampler with no ref implementation has no + * fallback and no oracle (spec §17). + */ +#pragma once +#include "rad_sample.h" + +#include "../rad_core.h" +#include "grammar.h" +#include "host_ref.h" +#include "vocab_view.h" + +#include +#include +#include +#include + +namespace rad { + +/* ================================================================== the per-sequence row */ + +/* THE ROW AND ITS FLAGS LIVE IN abi/rad_sample.h, because they are the wire format of + * an OPERAND and therefore part of the ABI: libref reads these rows and a kernel plugin + * cannot include a core header. The alias keeps this file's spelling. */ +using DeviceSampleParams = RadSampleParams; + +/* ================================================================== configuration */ + +struct SamplerConfig { + int64_t n_vocab = 0; /* the WHOLE vocabulary */ + int64_t n_vocab_local = 0; /* THIS RANK's shard of it; == n_vocab when world_size == 1 */ + int64_t max_seqs = 0; /* the largest number of sequences one step may carry */ + int64_t max_hist = 2048; /* the penalty window bound; a longer request is truncated */ + int max_spec = 0; + int rank = 0; + int world_size = 1; + /* This rank's first vocabulary row, which sample_topk adds to every candidate id it packs + * into the pair plane so the merge sees GLOBAL ids, and which sample_penalties and sample_dry + * subtract from the GLOBAL ids in the history to find this rank's column. Zero unless lm_head + * is row-sharded. */ + int64_t vocab_off = 0; + + /* The candidate-set width the cuts work over. Every sampler after top-k operates on + * candidates rather than the vocabulary, so this bounds the buffers they read and write. It + * is a bound, not a policy: a request asking for a larger top-k than this is refused at + * admission, by name, rather than silently narrowed. */ + int64_t max_candidates = 1024; +}; + +/* ================================================================== the driver */ + +class Sampler { +public: + Sampler() = default; + ~Sampler(); + + /* ---------------------------------------------------------- declare phase */ + + /* Declare every sampler op and every buffer the chain needs, and allocate the pinned staging. + * Runs once, alongside the architecture plugin's declare, so the sampler's kernels resolve + * through the same hierarchy at the same time as everything else and a missing one is in the + * same missing-list (spec §3.1). + * + * A sampler op that does not resolve is NOT a declare failure: a deployment that never sends + * `typical_p` does not need a typical kernel. It becomes a failure when a request asks for + * it, which `check_request` reports by name. */ + int declare(RadBuilder* b, const SamplerConfig& cfg); + + /* The vocabulary view the grammar backends walk. Set after the tokeniser loads, before the + * first request. */ + void attach_vocab(const VocabView* v) { vocab_ = v; } + + /* ---------------------------------------------------------- admission */ + + /* Can this request's sampling parameters be served? Returns RAD_OK, or RAD_E_NOKERNEL naming + * the sampler that did not resolve, or RAD_E_INVAL naming the parameter that is out of range. + * Called on admission, so a request fails at the door rather than three steps in. */ + int check_request(const SamplingParams& sp, std::string* why) const; + + /* Build this request's grammar state, if it has a grammar. Runs on the scheduler thread, so + * it must not compile: a request admitted through the server carries its grammar compiled + * (SamplingParams::grammar_program), and this finds that program and positions a grammar in + * it. A request that arrives without one is compiled here, which costs its mask plan. */ + int begin_request(uint64_t req_id, const SamplingParams& sp, std::string* err); + void end_request(uint64_t req_id); + /* Does this request already have state here? The step loop reaches a request on every step it + * is scheduled in, and begin_request is not idempotent -- calling it twice would rebuild the + * automaton and throw away everything it had accepted, which silently unconstrains a + * generation from its second token onward. */ + bool has_request(uint64_t req_id) const; + + /* Requests build_step could not serve: a grammar that reached a state admitting no token. + * Returned and cleared; the caller cancels them. Empty on almost every step. */ + std::vector take_failed(); + + /* Advance a request's grammar over the token it just emitted. */ + int accept_token(uint64_t req_id, int32_t token); + + /* May the scheduler speculate on this request? Yes, unless it carries a constraining grammar + * whose backend cannot snapshot its state. The mask for draft position i depends on which of + * positions 0..i-1 were accepted, so masking a window means walking the grammar forward over + * the proposals and rewinding afterwards; a backend without push_state/rollback cannot, and + * such a request decodes one token at a time rather than silently emitting drafts the grammar + * forbids. */ + bool allows_speculation(uint64_t req_id) const; + /* Is allows_speculation's answer fixed for this request? It changes only when a grammar whose + * backend cannot rewind starts to constrain, which is a commit's doing; a request with no + * grammar, or one whose backend rewinds, answers the same at every step. */ + bool speculation_fixed(uint64_t req_id) const; + + /* ---------------------------------------------------------- step path */ + + /* Build the per-sequence parameter array, the packed penalty history and the grammar + * bitmasks for this step, into pinned staging. Scheduler-thread work: it touches request + * state and host grammar automata, and it must be done before the rank threads are released + * at the barrier. + * + * Allocates nothing -- every buffer was sized at declare against max_seqs (spec §3.1). */ + int build_step(const std::vector& reqs); + + /* THE SAME STAGING, FILLED FOR A GREEDY DRAFTER. `n` rows of argmax: no penalties, no + * grammar mask, no history, and the RNG untouched -- so the chain resolves to op_argmax and + * nothing else runs. + * + * It exists because a DRAFT round is not a request's own sampling. Its output is a + * proposal the target then verifies, and the verifier is greedy (core/sample/accept.h): a + * drafter that sampled at the request's temperature would spend the request's RNG stream + * on tokens that may never be emitted, and would lower acceptance for nothing. Every MTP + * head that ships inside a target checkpoint is greedy for the same reason. */ + int build_greedy(int64_t n); + + /* Upload the staging and issue the chain. Rank-thread work, on the compute stream, with no + * host synchronisation in it. + * + * `logits` holds [n_seq, n_vocab_local] and `out_tokens` receives [n_seq] token ids. Under + * tensor parallel the candidate merge (`sample_merge_topk`, or `row_topk_merge` fused with the + * top-k) happens between the top-k and the cuts; full logits are never gathered. */ + int run(RadCtx* c, rad_buf logits, rad_buf out_tokens); + + /* The parameter rows the last build_step or build_greedy staged, and how many. What `run` + * uploads, readable so the staging can be checked without a device behind it. */ + const DeviceSampleParams* staged_params(int64_t* n) const { + if (n) *n = n_seq_; + return cur_stage_; + } + +private: + /* IS THE VOCABULARY ACTUALLY SPLIT? Not the same question as "is there more than one rank". + * A tensor-parallel deployment whose plugin declares `output.weight` replicated gives every + * rank the whole vocabulary, and then the candidate merge is not just unnecessary but wrong: + * every rank would contribute the SAME k candidates and the gather would count them once per + * rank. The declared width of this rank's logits is the fact, so that is what this asks. */ + bool vocab_parallel() const { + return cfg_.world_size > 1 && cfg_.n_vocab_local < cfg_.n_vocab; + } + + /* `dry` holds the request's resolved sequence breakers, empty when it sent none -- which is + * not "DRY off": DRY runs whenever its multiplier is set, with or without breakers. */ + struct SeqState { + std::unique_ptr grammar; + DryBreakers dry; + }; + + SamplerConfig cfg_{}; + const VocabView* vocab_ = nullptr; + bool declared_ = false; + + /* Declared op handles. RAD_NULL_HANDLE means the op did not resolve; the admission check + * turns that into a named refusal rather than a silent skip. */ + rad_op op_penalties_ = RAD_NULL_HANDLE; + rad_op op_dry_ = RAD_NULL_HANDLE; + rad_op op_temp_ = RAD_NULL_HANDLE; + rad_op op_mask_ = RAD_NULL_HANDLE; + rad_op op_topk_ = RAD_NULL_HANDLE; + rad_op op_topp_ = RAD_NULL_HANDLE; + rad_op op_minp_ = RAD_NULL_HANDLE; + rad_op op_typical_ = RAD_NULL_HANDLE; + rad_op op_xtc_ = RAD_NULL_HANDLE; + rad_op op_pick_ = RAD_NULL_HANDLE; + rad_op op_argmax_ = RAD_NULL_HANDLE; + rad_op op_allgather_ = RAD_NULL_HANDLE; + rad_op op_merge_ = RAD_NULL_HANDLE; /* the candidate merge, under tensor parallel */ + + /* Device-side buffers, from the ordinary buffer plan. */ + rad_buf buf_params_ = RAD_NULL_HANDLE; + rad_buf buf_hist_ = RAD_NULL_HANDLE; + rad_buf buf_brk_ = RAD_NULL_HANDLE; /* DRY's single-token breaker marks, beside history */ + rad_buf buf_mask_ = RAD_NULL_HANDLE; + rad_buf buf_cand_i_ = RAD_NULL_HANDLE; + rad_buf buf_cand_v_ = RAD_NULL_HANDLE; + rad_buf buf_gather_ = RAD_NULL_HANDLE; + rad_buf buf_pairs_ = RAD_NULL_HANDLE; /* this rank's candidates as (global id, logit) */ + + /* Pinned staging. One allocation each, at declare, never on the step path. */ + DeviceSampleParams* params_stage_ = nullptr; + /* THE GREEDY ROWS HAVE STAGING OF THEIR OWN, written once. A draft pass is staged while the + * step before it -- whose sampler uploads `params_stage_` when the card reaches it -- may not + * have run yet; rows written into the same staging would reach that step's sampler instead. + * Every greedy row is the same row, so this one is filled on first use and never again, and + * no upload of it can ever see a later build. */ + DeviceSampleParams* greedy_stage_ = nullptr; + bool greedy_ready_ = false; + const DeviceSampleParams* cur_stage_ = nullptr; /* what the last build staged */ + int32_t* hist_stage_ = nullptr; + uint8_t* brk_stage_ = nullptr; + uint32_t* mask_stage_ = nullptr; + + int64_t mask_words_ = 0; /* words for THIS RANK's shard; what the mask op indexes */ + int64_t n_seq_ = 0; + /* Does any DRY row this step carry breakers? Only then is the breaker plane uploaded and + * handed to sample_dry; a batch whose DRY requests sent none issues it without the operand. */ + bool any_brk_ = false; + + /* The whole-vocabulary mask the grammar fills, from which the staged shard is cut. Only used + * when the head is sharded; see the note in declare(). */ + std::vector mask_full_; + + /* The grammar mask's cost, accumulated for the Debug line in build_step. Not state the step + path reads -- a diagnostic, and one worth carrying: the mask walk is scheduler-thread work + large enough to decide the step time of a constrained request, so it has to be visible + rather than assumed. */ + double mask_us_ = 0.0; + double mask_worst_us_ = 0.0; + int64_t mask_us_n_ = 0; + int64_t mask_fast_ = 0; /* memo hits */ + int64_t mask_slow_ = 0; /* walks */ + double mask_walk_us_ = 0.0; /* and what only the walks cost */ + double build_us_ = 0.0; + int64_t build_n_ = 0; + double accept_us_ = 0.0; + int64_t accept_n_ = 0; + void shard_mask(uint32_t* dst) const; + + /* Requests whose grammar died this step. Drained by the engine, which cancels them -- one bad + * request must not stop the step loop for everyone else. */ + std::vector failed_; + + /* Per-request grammar and DRY state, keyed by request id. Held here rather than in Request + * because Request is a frozen struct shared across components and a unique_ptr in it would + * make the scheduler's copies a compile error. */ + std::unordered_map seqs_; + + int stage_alloc(); + void stage_free(); +}; + +} /* namespace rad */ diff --git a/core/sample/vocab_view.h b/core/sample/vocab_view.h new file mode 100644 index 00000000..7cb9d2db --- /dev/null +++ b/core/sample/vocab_view.h @@ -0,0 +1,134 @@ +/* vocab_view.h -- what the sampler needs to know about a vocabulary, and nothing else. + * + * The tokeniser lives in core/text/ and belongs to the text frontend. The sampler needs exactly + * three facts about a token -- how many there are, its printable piece, and whether it ends + * generation -- plus, for DRY's sequence breakers and GBNF's `` syntax, the ability to + * tokenise a short literal. Taking a dependency on the whole tokeniser for that would put a + * component boundary on the step path and make every sampler test drag a real vocabulary behind + * it. An abstract view costs one virtual call per token per grammar step, which is host work the + * device is not waiting on. + * + * core/text/ implements this over the real vocab; SimpleVocab below implements it over a table, + * which is what the tests use. + */ +#pragma once +#include "../rad_internal.h" + +#include +#include +#include +#include + +namespace rad { + +class VocabView { +public: + virtual ~VocabView() = default; + + virtual int32_t n_tokens() const = 0; + + /* The token's bytes as they would be appended to the output stream. The grammar walks these, + * so a view that returns a display form rather than the exact bytes will admit the wrong + * token set -- and the failure mode is plausible text with wrong structure, which is the + * hardest kind to notice. */ + virtual const std::string& token_piece(int32_t id) const = 0; + + /* End-of-generation: EOS, EOT, and whatever else this model ends on. A grammar admits one + * only when some stack has run to completion. */ + virtual bool is_eog(int32_t id) const = 0; + + /* Tokenise a short literal. Only DRY's sequence breakers and GBNF's `` form need it, + * and both are optional features, so a view that has no tokeniser returns + * RAD_E_UNSUPPORTED rather than pretending. */ + virtual int tokenize(const std::string& text, std::vector* out) const { + (void)text; (void)out; + return RAD_E_UNSUPPORTED; + } + + /* The same with special tokens recognised in the text, so `` comes back as the + * one control token a template means by it. Grammar triggers are resolved through this. */ + virtual int tokenize_special(const std::string& text, std::vector* out) const { + (void)text; (void)out; + return RAD_E_UNSUPPORTED; + } + + /* ---------------- what a grammar backend derives from this vocabulary ---------------- + * + * A GBNF mask is built over a DECODED form of the whole vocabulary -- every piece as code + * points, plus a trie over them -- which costs a full vocabulary scan and is therefore + * computed once and kept. It is kept HERE, with the vocabulary's own lifetime, because the + * only other place to keep it is a table outside, and the only key such a table has is this + * object's ADDRESS. An address is not an identity: a view destroyed and another constructed + * in the same storage answers to the same key, and the second one is then served what was + * derived for the first -- the decoded vocabulary, the trie over it, and the grammars + * compiled against both. The mask that comes out is a mask over another model's tokens: it + * admits the wrong set, or nothing at all, and nothing downstream can tell. Tying the cache + * to the object makes the question unaskable. + * + * Opaque and mutable: what is cached is the backend's business and this header is the + * sampler's interface, and filling it does not change what the vocabulary says. A backend + * that caches nothing pays one null pointer. */ + mutable std::shared_ptr gbnf_cache; +}; + +/* A vocabulary held as a table. Not a toy: it is what the sampler tests are written against, and + * being able to state a vocabulary in four lines is what makes a grammar test readable. */ +class SimpleVocab : public VocabView { +public: + SimpleVocab() = default; + explicit SimpleVocab(std::vector pieces) : pieces_(std::move(pieces)) {} + + int32_t add(std::string piece, bool eog = false) { + int32_t id = (int32_t)pieces_.size(); + pieces_.push_back(std::move(piece)); + if (eog) eog_.push_back(id); + return id; + } + + void mark_eog(int32_t id) { eog_.push_back(id); } + + int32_t n_tokens() const override { return (int32_t)pieces_.size(); } + + const std::string& token_piece(int32_t id) const override { + static const std::string empty; + if (id < 0 || id >= (int32_t)pieces_.size()) return empty; + return pieces_[id]; + } + + bool is_eog(int32_t id) const override { + for (int32_t e : eog_) if (e == id) return true; + return false; + } + + /* Longest-match over the table, which is not BPE and does not pretend to be. It exists so a + * DRY sequence breaker or a `` literal resolves in a test; a real vocabulary's merge + * machinery lives in core/text/. */ + /* A table has no special tokens of its own: every piece is matched as written. */ + int tokenize_special(const std::string& text, std::vector* out) const override { + return tokenize(text, out); + } + + int tokenize(const std::string& text, std::vector* out) const override { + if (!out) return RAD_E_INVAL; + size_t pos = 0; + while (pos < text.size()) { + int32_t best = -1; + size_t best_len = 0; + for (int32_t id = 0; id < (int32_t)pieces_.size(); ++id) { + const std::string& p = pieces_[id]; + if (p.empty() || p.size() <= best_len) continue; + if (text.compare(pos, p.size(), p) == 0) { best = id; best_len = p.size(); } + } + if (best < 0) return RAD_E_NOTFOUND; + out->push_back(best); + pos += best_len; + } + return RAD_OK; + } + +private: + std::vector pieces_; + std::vector eog_; +}; + +} /* namespace rad */ diff --git a/core/sample/word_scan.cpp b/core/sample/word_scan.cpp new file mode 100644 index 00000000..5487b28b --- /dev/null +++ b/core/sample/word_scan.cpp @@ -0,0 +1,77 @@ +/* word_scan.cpp -- the Aho-Corasick build behind word_scan.h. */ +#include "word_scan.h" + +#include + +namespace rad { + +int WordScanner::build(const std::vector& words, std::string* err) { + for (size_t i = 0; i < words.size(); ++i) { + if (words[i].empty()) { + if (err) *err = "trigger word " + std::to_string(i) + " is empty"; + return RAD_E_INVAL; + } + } + + /* Byte classes: one per distinct byte the words use, and class 0 for every other byte. */ + std::fill(cls_, cls_ + 256, (uint8_t)0); + ncls_ = 1; + for (const std::string& w : words) + for (unsigned char c : w) + if (cls_[c] == 0) { + if (ncls_ == 256) { + if (err) *err = "the trigger words use more distinct bytes than a class holds"; + return RAD_E_INVAL; + } + cls_[c] = (uint8_t)ncls_++; + } + + /* The trie, with its edges held densely from the start: a missing edge is kUnset until the + * breadth-first pass below resolves it through the failure link. */ + constexpr uint32_t kUnset = ~0u; + next_.assign(ncls_, kUnset); + out_len_.assign(1, 0u); + max_len_ = 0; + for (const std::string& w : words) { + uint32_t s = 0; + for (unsigned char c : w) { + uint32_t& e = next_[(size_t)s * ncls_ + cls_[c]]; + if (e == kUnset) { + e = (uint32_t)out_len_.size(); + out_len_.push_back(0u); + next_.resize(next_.size() + ncls_, kUnset); + } + s = next_[(size_t)s * ncls_ + cls_[c]]; + } + out_len_[s] = (uint32_t)w.size(); + max_len_ = std::max(max_len_, (uint32_t)w.size()); + } + + /* Failure links in breadth-first order, so a state's link is final before any deeper state + * reads it. A state's longest match is its own word if it ends one, which is longer than any + * proper suffix, and otherwise its failure state's. */ + const uint32_t n_states = (uint32_t)out_len_.size(); + std::vector fail(n_states, 0u); + std::vector queue; + queue.reserve(n_states); + for (uint32_t c = 0; c < ncls_; ++c) { + uint32_t& e = next_[c]; + if (e == kUnset) { e = 0; continue; } + fail[e] = 0; + queue.push_back(e); + } + for (size_t qi = 0; qi < queue.size(); ++qi) { + const uint32_t s = queue[qi]; + if (out_len_[s] == 0) out_len_[s] = out_len_[fail[s]]; + for (uint32_t c = 0; c < ncls_; ++c) { + uint32_t& e = next_[(size_t)s * ncls_ + c]; + const uint32_t via_fail = next_[(size_t)fail[s] * ncls_ + c]; + if (e == kUnset) { e = via_fail; continue; } + fail[e] = via_fail; + queue.push_back(e); + } + } + return RAD_OK; +} + +} /* namespace rad */ diff --git a/core/sample/word_scan.h b/core/sample/word_scan.h new file mode 100644 index 00000000..5fb353b9 --- /dev/null +++ b/core/sample/word_scan.h @@ -0,0 +1,75 @@ +/* word_scan.h -- find the first of a set of literal words in a byte stream that arrives in pieces. + * + * A lazy grammar waits for its trigger word -- `\n` on the Qwen templates -- and until + * the word appears every generated token passes through here. The stream is the whole reply, so + * anything that looks back over what has already arrived turns a long reply into quadratic host + * work on the step path. This looks back at nothing: the scan state is one integer, each byte is + * one table load, and what a match needs to be replayed is bounded by the longest word. + * + * THE AUTOMATON is Aho-Corasick compiled to a full DFA over byte classes. The trie of the words + * gets failure links in breadth-first order, and every missing edge is resolved through them once, + * at build time, so the scan never follows a failure chain. Bytes that occur in no word share one + * class, which keeps the table at (states x distinct word bytes + 1) entries -- a few hundred for + * any real trigger set, so it stays in L1 however long the reply runs. + * + * THE MATCH REPORTED is the leftmost START among the occurrences that complete inside one fed + * piece. That is the answer a search of the whole stream so far gives after each piece: nothing + * completed in an earlier piece (the caller would have stopped), so every complete occurrence ends + * in this one, and of those the leftmost is the one that begins first. Each state carries the + * length of the LONGEST word ending there, because the longest word ending at a byte is the one + * that starts earliest. + */ +#pragma once +#include "../rad_internal.h" + +#include +#include +#include +#include + +namespace rad { + +class WordScanner { +public: + static constexpr uint64_t npos = ~(uint64_t)0; + + /* Where a stream is: the automaton state and how many bytes have been fed. Plain data, so a + * speculative window can copy it and put it back. */ + struct State { + uint32_t s = 0; + uint64_t off = 0; + }; + + /* Compile `words`. Every word must be non-empty; RAD_E_INVAL names the first that is not. + * An empty set builds a scanner that never matches. */ + int build(const std::vector& words, std::string* err); + + bool empty() const { return max_len_ == 0; } + uint32_t max_len() const { return max_len_; } + + /* Advance over `n` bytes. Returns the stream offset at which the leftmost occurrence that + * completes within these bytes begins, or npos when none completes. */ + uint64_t feed(State& st, const char* p, size_t n) const { + uint64_t best = npos; + uint32_t s = st.s; + uint64_t off = st.off; + for (size_t i = 0; i < n; ++i) { + s = next_[(size_t)s * ncls_ + cls_[(uint8_t)p[i]]]; + ++off; + const uint32_t len = out_len_[s]; + if (len && off - len < best) best = off - len; + } + st.s = s; + st.off = off; + return best; + } + +private: + uint8_t cls_[256] = {}; + uint32_t ncls_ = 1; + uint32_t max_len_ = 0; + std::vector next_{ 0u }; /* [state * ncls_ + class] -> state */ + std::vector out_len_{ 0u }; /* longest word ending in the state, 0 for none */ +}; + +} /* namespace rad */ diff --git a/core/sched/advance.cpp b/core/sched/advance.cpp new file mode 100644 index 00000000..8605df2d --- /dev/null +++ b/core/sched/advance.cpp @@ -0,0 +1,24 @@ +/* advance.cpp -- issuing an advance. See advance.h. */ +#include "advance_impl.h" + +#include "device/device.h" + +namespace rad { + +int step_advance(const AdvanceArgs& a, RadStream s) { + if (a.n_seq <= 0) return RAD_OK; + /* THE HOST BACKEND RUNS A STREAM'S WORK AS IT IS ISSUED, and its device memory is host memory, + * so the rows run here, now, in the order the stream would have run them. */ + if (device_is_host()) { + for (int i = 0; i < a.n_seq; ++i) adv_row(a, i); + return RAD_OK; + } +#if defined(RAD_HAVE_HIP) && RAD_HAVE_HIP + return rad_step_advance_launch(&a, (void*)s) == 0 ? RAD_OK : RAD_E_DEVICE; +#else + (void)s; + return RAD_E_UNSUPPORTED; +#endif +} + +} /* namespace rad */ diff --git a/core/sched/advance.h b/core/sched/advance.h new file mode 100644 index 00000000..4df024c6 --- /dev/null +++ b/core/sched/advance.h @@ -0,0 +1,104 @@ +/* advance.h -- the card's own bookkeeping between passes: which drafts a verify step accepted, and + * the inputs of every pass that follows from it. + * + * WHY THE CARD DOES THIS AND NOT THE HOST. A speculative step is a verify pass and the draft passes + * behind it, and every pass after the verify depends on how many drafts it accepted: the draft + * head continues from the accepted position, and the next verify starts after it. Deciding that on + * the host means reading the sampled tokens back, waiting for them, and only then staging the next + * pass -- a synchronisation per step during which the card has nothing queued. Deciding it here + * lets the host stage and issue every pass of a step, and the next step, before any of them has + * run: the rule is a compare of a few integers a sequence, and the card already holds all of them. + * + * THE STATE IS PER SEQUENCE SLOT (StepSlot), in device memory on every rank, and it carries exactly + * what a pass needs that the host cannot know in advance: where the next verify starts, what it + * rolls back, which tokens it verifies, and where the draft head continues from. Every rank keeps + * its own copy and computes the same numbers from the same sampled tokens, so no rank ever reads + * another's memory. + * + * A PASS NAMES ITS DEVICE ROWS. A batch can mix rows whose inputs the host staged -- a prefill + * chunk, a history row for positions the host already knows -- with rows whose positions come from + * the card; `rows[0][i]` says which, and the advance leaves a host row exactly as it was uploaded. + * + * The same code runs on the host backend, where device memory is host memory and a stream runs + * its work as it is issued (advance_impl.h is shared by both builds). + */ +#pragma once +#include + +#include "rad_device.h" +#include "draft.h" + +namespace rad { + +/* One sequence slot's state between passes. The accept step writes it; every later pass reads it. */ +struct StepSlot { + int32_t ctx; /* the next verify step's first position: tokens committed so far */ + int32_t n_acc; /* its one-based num_accepted: tokens the last verify step committed */ + int32_t head; /* the last committed index, which the draft head's first round extends */ + int32_t acc; /* drafts the last verify step accepted */ + /* The next verify step's input tokens: the bonus token, then the draft head's proposals. */ + int32_t tok[1 + RAD_SCHED_MAX_SPEC]; + int32_t pad[3]; +}; + +enum AdvMode : int32_t { + ADV_ACCEPT = 1, /* after a verify step's sampler: acceptance, and the state it leaves */ + ADV_TRUNK = 2, /* before a verify step: its tokens, positions and rollback count */ + ADV_HIST = 3, /* before the draft head's history pass: the verified positions */ + ADV_ROUND = 4, /* before draft round `round` >= 2: the next position, the last proposal */ + ADV_TAKE = 5, /* after the last round: its proposal into the state */ +}; + +/* One KV group, as the builder stages it for this build. Offsets are bytes into the rank's slab, + * which every rank carves identically. */ +struct AdvGroup { + int32_t block_size; + int32_t paged; /* 0: a state group, whose slots do not depend on the position */ + int32_t pitch; /* this build's block-table pitch */ + int32_t pad; + int64_t slot_off; /* [n_tok] slot_mapping */ + int64_t used_off; /* [n_seq] seqused */ + int64_t bt_off; /* [n_seq][pitch] block table */ + int64_t first_off; /* [n_seq] the position each row's block table starts at */ +}; + +/* One advance: a mode, the build it patches, and where its inputs are. Passed by value as the + * kernel's argument. */ +struct AdvanceArgs { + int32_t mode = 0; + int32_t round = 0; /* ADV_ROUND: the draft round, from 2; ADV_TAKE: the last, from 1 */ + int32_t n_seq = 0; + int32_t n_groups = 0; + char* slab = nullptr; /* this rank's device slab */ + int64_t tok_off = 0, pos_off = 0, ctx_off = 0, acc_off = 0, out_off = 0; + int64_t sid_off = 0, cu_off = 0, q_off = 0; + /* [4][row_pitch] int32: device-row flag; the verify step's token row of the row's first + * verified position; its first sampled row, or -1 for a row that sampled nothing; and one + * number the mode reads -- ADV_ACCEPT the row's draft count, ADV_HIST how many of the row's + * positions come before the verified ones, whose tokens the host staged. */ + int64_t row_off = 0; + int32_t row_pitch = 0; + int64_t grp_off = 0; /* [n_groups] AdvGroup */ + StepSlot* st = nullptr; /* [max_seqs], by scheduler slot */ + /* ADV_ACCEPT and ADV_HIST: the verify step's sampled tokens, one a row. ADV_ROUND and + * ADV_TAKE: the last round's proposals, row i at i * src_pitch. */ + const int32_t* src = nullptr; + int64_t src_pitch = 1; + const int32_t* eog = nullptr; /* end-of-generation ids, sorted */ + int32_t n_eog = 0; + /* THE ROTARY PLANES (RadBatch::rope_pos), [3][rope_pitch] at rope_off, or rope_off -1 when the + * build carries none. A row whose position the card moves carries its rotary position along + * by the offset the host staged for it: the rows the card owns are decode and draft rows, all + * text, and text rotates at its index plus one per-sequence shift. A row the card leaves at + * the host's position keeps the host's three components, which is what a media token needs. */ + int64_t rope_off = -1; + int32_t rope_pitch = 0; +}; + +/* Issue one advance on `s`. The rows are independent, so the card runs them in parallel. */ +int step_advance(const AdvanceArgs& a, RadStream s); + +} /* namespace rad */ + +/* The launcher in advance.hip: one kernel onto `stream` through hipLaunchKernel. */ +extern "C" int rad_step_advance_launch(const rad::AdvanceArgs* args, void* stream); diff --git a/core/sched/advance.hip b/core/sched/advance.hip new file mode 100644 index 00000000..24519305 --- /dev/null +++ b/core/sched/advance.hip @@ -0,0 +1,27 @@ +/* advance.hip -- the advance kernel: one thread a row of the batch it patches. See advance.h. + * + * Launched through hipLaunchKernel like any kernel library's, which the AQL backend intercepts, so + * it is one dispatch on the rank's own queue in stream order with the pass it belongs to. + */ +#include + +#include "advance_impl.h" + +namespace { + +constexpr int kThreads = 64; + +__global__ __launch_bounds__(kThreads) void rad_step_advance(rad::AdvanceArgs a) { + const int i = (int)(blockIdx.x * kThreads + threadIdx.x); + if (i < a.n_seq) rad::adv_row(a, i); +} + +} // namespace + +extern "C" int rad_step_advance_launch(const rad::AdvanceArgs* args, void* stream) { + if (!args || args->n_seq <= 0) return 0; + const unsigned blocks = (unsigned)((args->n_seq + kThreads - 1) / kThreads); + hipLaunchKernelGGL(rad_step_advance, dim3(blocks), dim3(kThreads), 0, (hipStream_t)stream, + *args); + return hipGetLastError() == hipSuccess ? 0 : -1; +} diff --git a/core/sched/advance_impl.h b/core/sched/advance_impl.h new file mode 100644 index 00000000..504fbfdb --- /dev/null +++ b/core/sched/advance_impl.h @@ -0,0 +1,154 @@ +/* advance_impl.h -- one row of an advance, shared by the kernel (advance.hip) and the host backend + * (advance.cpp). See advance.h for what the modes are and why the card computes them. + * + * Every row is independent: it reads its own slot's state and writes only its own positions, + * tokens and slots, so the kernel runs one thread a row and the host a loop. + */ +#pragma once +#include "advance.h" + +#if defined(__HIPCC__) +#define RAD_ADV_FN __host__ __device__ inline +#else +#define RAD_ADV_FN inline +#endif + +namespace rad { + +RAD_ADV_FN int32_t* adv_i32(const AdvanceArgs& a, int64_t off) { + return reinterpret_cast(a.slab + off); +} + +RAD_ADV_FN bool adv_is_eog(const AdvanceArgs& a, int32_t t) { + int32_t lo = 0, hi = a.n_eog; + while (lo < hi) { + const int32_t mid = (lo + hi) / 2; + if (a.eog[mid] < t) lo = mid + 1; else hi = mid; + } + return lo < a.n_eog && a.eog[lo] == t; +} + +/* Every group's slots for the row's `n` positions, read from the positions just written, and its + * length from `base`. A position its block table does not reach gets slot -1, which the kernels + * read as "no slot" -- the builder sized the tables for the furthest position a pass can reach, + * so it only happens to a row that is being computed for nothing. */ +RAD_ADV_FN void adv_groups(const AdvanceArgs& a, int i, int32_t k, int32_t base, int32_t n) { + const AdvGroup* G = reinterpret_cast(a.slab + a.grp_off); + const int32_t* pos = adv_i32(a, a.pos_off); + for (int g = 0; g < a.n_groups; ++g) { + const AdvGroup& e = G[g]; + const int32_t first = adv_i32(a, e.first_off)[i]; + adv_i32(a, e.used_off)[i] = base + n - first; + if (!e.paged) continue; + const int32_t* bt = adv_i32(a, e.bt_off) + (int64_t)i * e.pitch; + int32_t* slot = adv_i32(a, e.slot_off); + for (int32_t j = 0; j < n; ++j) { + const int32_t p = pos[k + j]; + const int32_t bi = (p - first) / e.block_size; + slot[k + j] = (p >= first && bi < e.pitch && bt[bi] >= 0) + ? bt[bi] * e.block_size + p % e.block_size : -1; + } + } +} + +/* A row's position, written, with its rotary components moved by the same amount -- only when it + * moved, so a row the host placed exactly keeps whatever components the host gave it. */ +RAD_ADV_FN void adv_pos(const AdvanceArgs& a, int32_t* pos, int32_t row, int32_t p) { + const int32_t was = pos[row]; + pos[row] = p; + if (a.rope_off < 0 || was == p) return; + int32_t* r = adv_i32(a, a.rope_off); + const int32_t shift = r[row] - was; + r[row] = p + shift; + r[a.rope_pitch + row] = p + shift; + r[2 * a.rope_pitch + row] = p + shift; +} + +RAD_ADV_FN void adv_row(const AdvanceArgs& a, int i) { + const int32_t* rows = adv_i32(a, a.row_off); + const int32_t rtok = rows[a.row_pitch + i]; + const int32_t rout = rows[2 * a.row_pitch + i]; + const int32_t aux = rows[3 * a.row_pitch + i]; + /* Acceptance runs over every row that sampled, whoever staged it; every other mode over the + * rows the card owns. */ + if (a.mode == ADV_ACCEPT ? rout < 0 : !rows[i]) return; + + int32_t* tok = adv_i32(a, a.tok_off); + int32_t* pos = adv_i32(a, a.pos_off); + int32_t* ctx = adv_i32(a, a.ctx_off); + const int32_t slot = adv_i32(a, a.sid_off)[i]; + const int32_t k = adv_i32(a, a.cu_off)[i]; + const int32_t n = adv_i32(a, a.q_off)[i]; + StepSlot& S = a.st[slot]; + + switch (a.mode) { + case ADV_ACCEPT: { + /* THE RULE accept_greedy states, and then the end-of-generation cut collect_step applies: + * a draft is accepted while it equals the target's own pick at its position, and the run + * stops AT an end-of-generation token rather than after it. */ + const int32_t* y = a.src + rout; + const int32_t* d = tok + rtok + 1; + int32_t acc = 0; + while (acc < aux && d[acc] == y[acc]) ++acc; + for (int32_t j = 0; j <= acc; ++j) + if (adv_is_eog(a, y[j])) { acc = j; break; } + const int32_t head = ctx[i] + (rtok - k) + acc; + S.acc = acc; + S.head = head; + S.ctx = head + 1; + S.n_acc = acc + 1; + S.tok[0] = y[acc]; + return; + } + case ADV_TRUNK: { + const int32_t base = S.ctx; + for (int32_t j = 0; j < n; ++j) { tok[k + j] = S.tok[j]; adv_pos(a, pos, k + j, base + j); } + ctx[i] = base; + adv_i32(a, a.acc_off)[i] = S.n_acc; + adv_groups(a, i, k, base, n); + return; + } + case ADV_HIST: { + /* `aux` positions the host already knew the tokens of, then the verify step's own + * positions up to the last one it committed, each with the token committed after it -- + * the sampler's pick there, since the drafts before it agreed with it. The pass has a + * row for every position the step COULD have committed, and the ones past the last + * committed repeat it: a position past it would take a rejected draft's hidden state + * into the head's cache. The repeat is also what makes the run's LAST row draft round + * 1's -- the committed position, its hidden state and the token after it -- whatever + * the acceptance was (RadBatch::draft_out_ids). */ + const int32_t base = S.head - S.acc - aux; + const int32_t last = aux + S.acc; + int32_t* out = adv_i32(a, a.out_off); + const int32_t row0 = out[k]; + for (int32_t j = 0; j < n; ++j) { + const int32_t jj = j < last ? j : last; + if (jj >= aux) tok[k + j] = a.src[rout + jj - aux]; + adv_pos(a, pos, k + j, base + jj); + out[k + j] = row0 + jj; + } + ctx[i] = base; + adv_groups(a, i, k, base, n); + return; + } + case ADV_ROUND: { + /* Round 2 onward: round 1 is the history pass's last row (ADV_HIST above), so every + * round embeds the proposal of the round before it. */ + const int32_t base = S.head + a.round - 1; + const int32_t t = a.src[(int64_t)i * a.src_pitch]; + S.tok[a.round - 1] = t; + tok[k] = t; + adv_pos(a, pos, k, base); + ctx[i] = base; + adv_groups(a, i, k, base, 1); + return; + } + case ADV_TAKE: + S.tok[a.round] = a.src[(int64_t)i * a.src_pitch]; + return; + default: + return; + } +} + +} /* namespace rad */ diff --git a/core/sched/batch.cpp b/core/sched/batch.cpp new file mode 100644 index 00000000..e194eb82 --- /dev/null +++ b/core/sched/batch.cpp @@ -0,0 +1,1317 @@ +/* batch.cpp -- building the step batch once. See batch.h for why. + */ +#include "batch.h" +#include "mm/processor.h" +#include "derive.h" +#include "device/device.h" + +#include +#include +#include + +namespace rad { + +/* Staging arrays are carved out of one slab per set rather than allocated one by one: the copies + * are still per array (each carries only the prefix this step used, and those lengths differ by an + * order of magnitude between a decode step and a prefill chunk), but the allocator is called twice + * at init instead of two dozen times and every array in a set shares one mapping. */ +static const int64_t k_carve_align = 256; + +/* The longest range a build's upload names: one round of the workgroup that copies it, whose loads + * are all in flight before its first store (rad_memcpy_ranges_async). */ +static const int64_t k_range_max = 16384; + +/* A HOST-SIDE BOUND, ROUNDED UP ONTO A COARSE GRID: to a multiple of `min_q`, and above 64 of + * 1/32 to 1/64 of the value's power of two if that is coarser -- so ~3% over at a long context and + * at most `min_q` over at a short one. + * + * `max_ctx_len` and the block-table pitch are ceilings -- a kernel reads each row's own length off + * the card -- and they are the only arguments of a decode pass that move while a request runs: + * attention and the QSA indexer size their grids by them. Exact, they change the pass's arguments + * every step or two; rounded, a pass is the same dispatches with the same arguments for many steps + * at a time, which is what lets a recorded pass be played instead of issued (see Ctx::run_step). + * The price is grid slack that exits on its first compare, and at a short context, where the + * floor is most of the bound, the whole attention term is small. */ +/* THE FLOOR IS 1024 TOKENS. Every crossing re-records each kind of pass a step runs, twice -- the + * recording and the audit before its first play -- at a few hundred microseconds of a rank thread + * each, and at a 256-token floor a short-context decode crosses often enough to spend a tenth of + * its rank threads recording. It is not higher because a block may choose its PATH by this bound + * and not only its grid: rad_block_attn_gated_fp8.h keeps the cheaper dense attention while the + * bound says every sequence is inside the indexer's budget, and a floor at that budget takes the + * dense path away from every short context -- a verify step's attention at eight sequences takes + * 48 us a layer at 2048 instead of 15. */ +static const int64_t k_bound_tokens = 1024; + +static inline int64_t bound_bucket(int64_t v, int64_t min_q) { + if (v <= 0) return v; + int64_t q = min_q < 1 ? 1 : min_q; + if (v > 64) { + const int lg = 63 - __builtin_clzll((unsigned long long)v); + if (((int64_t)1 << (lg - 5)) > q) q = (int64_t)1 << (lg - 5); + } + return (v + q - 1) / q * q; +} + +/* A negative device status inside build() aborts the step; there is nothing to fall back to and a + * partially staged batch is worse than no batch. */ +#define RAD_TRY_NULL(expr) \ + do { int _s = (expr); \ + if (_s < 0) { RAD_ERR("step batch: %s -> %s", #expr, rad_strerror(_s)); \ + return nullptr; } } while (0) + +template +static T* carve(char* base, int64_t& off, int64_t n) { + int64_t o = off; + if (n < 0) n = 0; + off = align_up(off + n * (int64_t)sizeof(T), k_carve_align); + return base ? reinterpret_cast(base + o) : nullptr; +} + +/* The full token sequence of a request is prompt ++ output ++ draft, and n_computed indexes into + * it. One accessor for all three keeps prefill, decode, recompute-after-preemption and speculative + * verify on the same path: a preempted request re-prefills its own generated output because that + * is simply the tail of the same sequence, and a verify reads past the committed end into the + * drafter's proposal. No special case anywhere. */ +static inline int32_t token_at(const StepEntry& e, int64_t i) { + /* A placeholder entry -- a drafter context row whose request has already gone -- has no + * tokens, and the pass it belongs to reads none. */ + if (!e.req) return 0; + const Request& r = *e.req; + int64_t np = (int64_t)r.prompt.size(); + if (i < np) return r.prompt[(size_t)i]; + i -= np; + int64_t no = (int64_t)r.output.size(); + if (i < no) return r.output[(size_t)i]; + i -= no; + return (e.draft && i >= 0 && i < e.n_draft) ? e.draft[(size_t)i] : 0; +} + +/* ------------------------------------------------------------------ set layout */ +/* Walked with null bases to measure and with real ones to assign. Keeping both in one function is + * what stops them drifting, which is the classic way a hand-carved slab ends up with two arrays + * sharing bytes. Every array is carved in PAIRS, host and device at the same offset, including the + * host-only ones: that is what lets one copy of a prefix move a whole build, and it puts the + * block tables -- the only part whose size moves from build to build -- last. */ +void BatchBuilder::carve(Set& s, char* h) { + char* const d = s.dev.empty() ? nullptr : static_cast(s.dev[0]); + const int64_t T = max_tok_, S = max_seqs_; + /* The most logit rows one step can want: one per sequence, or one per verified draft position + * per sequence at a speculative step. It is what bounds Geom::max_logit_rows on the plugin + * side, and the two have to agree or the plugin gathers into a buffer smaller than out_ids. */ + /* ...or one row a TOKEN, which an MTP history pass is: it gathers the trunk`s hidden state + * for every position the step just computed, and names those rows through the same array. */ + int64_t O = S * (1 + (cfg_.n_spec > 0 ? (int64_t)cfg_.n_spec : 0)); + if (O < T) O = T; + /* ...and in the KL mode a row at every token as well, after the sampled ones + * (Request::score). RadBuildCtx::max_out_rows says the same number to the plugin. */ + if (cfg_.kld()) O = T + S; + + int64_t oh = 0, od = 0; + auto pair = [&](int32_t** ph, int32_t** pd, int64_t n) { + *ph = ::rad::carve(h, oh, n); + *pd = ::rad::carve(d, od, n); + }; + /* Twice the step: its own tokens, then up to a step of the prompt that follows + * (RadBatch::n_ahead). */ + pair(&s.h_tok, &s.d_tok, 2 * T); + pair(&s.h_pos, &s.d_pos, T); + pair(&s.h_parent, &s.d_parent, T); + pair(&s.h_cu, &s.d_cu, S + 1); + pair(&s.h_sid, &s.d_sid, S); + pair(&s.h_q, &s.d_q, S); + pair(&s.h_ctx, &s.d_ctx, S); + pair(&s.h_acc, &s.d_acc, S); + pair(&s.h_cktok, &s.d_cktok, S); + pair(&s.h_ckslot, &s.d_ckslot, S); + pair(&s.h_out, &s.d_out, O); + pair(&s.h_dout, &s.d_dout, S); + pair(&s.h_rows, &s.d_rows, 4 * S); + pair(&s.h_first, &s.d_first, S * (int64_t)s.groups.size()); + s.h_grp = ::rad::carve(h, oh, (int64_t)s.groups.size()); + s.d_grp = ::rad::carve(d, od, (int64_t)s.groups.size()); + for (size_t gi = 0; gi < s.groups.size(); ++gi) { + Group& g = s.groups[gi]; + pair(&g.h_slot, &g.d_slot, T); + pair(&g.h_used, &g.d_used, S); + pair(&g.h_sidx, &g.d_sidx, S * g.sidx_pitch); + } + /* THE ROTARY PLANES AND THE ENCODER-ROW TARGETS, only for a program with an encoder: nothing + * else can move a rotary position off the token index, and a text-only deployment should not + * upload twelve bytes a token of copies of `positions` every step. */ + pair(&s.h_rope, &s.d_rope, mm_on_ ? 3 * T : 0); + pair(&s.h_mmrow, &s.d_mmrow, mm_on_ ? T : 0); + /* Host-only: derived metadata is copied into the arena the buffer plan already placed. Carved + * in the pair anyway, so the device offsets stay the host's -- a few kilobytes of slab nobody + * reads. */ + { + int32_t* unused = nullptr; + char* hd = ::rad::carve(h, oh, derived_bytes_); + (void)::rad::carve(d, od, derived_bytes_); + s.h_derived = hd; + pair(&s.h_convslot, &unused, S * (int64_t)kvgeom_.g.size()); + } + /* ---- the block tables, LAST ------------------------------------------------------------ + * + * A group's table is carved for the worst step -- max_seqs rows of max_ctx/block_size entries + * -- because the slab has to hold one. At a long context and a small block that is over a + * megabyte per paged group, and a model may declare several: the tables are nearly the whole + * slab. A build fills n_seq rows of `pitch`, THIS step's longest table, and the device reads + * them at that pitch (block_table_pitch below). + * + * ON THE CARD each group's rows have a FIXED place in this region, so the rows a build leaves + * alone are still there for the next one (BtMirror). IN THE HOST SPAN the region is the + * build's payload and range list instead, sized by what changed: the carve's host half only + * says where the payload starts. */ + { + int64_t bt_n = 0; + s.bt_base = od; + for (Group& g : s.groups) { + g.bt_fix = bt_n; + bt_n += align_up(S * g.max_blocks * (int64_t)sizeof(int32_t), k_carve_align) / + (int64_t)sizeof(int32_t); + } + pair(&s.bt_h0, &s.bt_d0, bt_n); + for (Group& g : s.groups) g.d_bt = s.bt_d0 ? s.bt_d0 + g.bt_fix : nullptr; + } + s.host_bytes = oh; + s.dev_bytes = od; +} + +int BatchBuilder::alloc_set(Set& s, const std::vector& groups) { + s.groups.resize(groups.size()); + for (size_t gi = 0; gi < groups.size(); ++gi) { + const KVGeom::G& e = kvgeom_.g[gi]; + s.groups[gi].g = (rad_kvgroup)gi; + s.groups[gi].block_size = e.block_size; + int64_t mb = 1; + if (e.paged) { + int64_t span = (e.kind == RAD_KV_WINDOW && e.window > 0 && e.window < max_ctx_) + ? e.window : max_ctx_; + mb = (span + e.block_size - 1) / e.block_size + 1; + } + s.groups[gi].max_blocks = mb; + s.groups[gi].sidx_pitch = e.sidx_width > 0 ? e.sidx_width : 1; + } + + carve(s, nullptr); + + /* ONE SLAB PER RANK, on that rank's card. rad_dev_alloc has no device argument and uses the + * current one, so the bind is part of the allocation. */ + s.dev.assign(ranks_.size(), nullptr); + for (size_t r = 0; r < ranks_.size(); ++r) { + RAD_TRY(rad_dev_set(ranks_[r].device)); + s.dev[r] = rad_dev_alloc(s.dev_bytes, RAD_MEM_DEVICE); + if (!s.dev[r]) { + RAD_ERR("step batch staging: could not reserve %s on rank %zu's card", + humanb(s.dev_bytes).c_str(), r); + return RAD_E_NOMEM; + } + } + RAD_TRY(rad_dev_set(ranks_[0].device)); + + /* THE RING HOLDS THREE WORST-CASE BUILDS, which is the most a host running ahead of the card + * can have in flight before a long-context prefill has to wait for its own upload two builds + * back; a decode build's span is its fixed prefix and a few rows of tables, so hundreds fit. */ + int64_t worst_pay = 0; + for (const Group& g : s.groups) worst_pay += max_seqs_ * g.max_blocks * (int64_t)sizeof(int32_t); + const int64_t worst_ranges = worst_pay / k_range_max + max_seqs_ * (int64_t)s.groups.size() + 1; + ranges_.reserve((size_t)worst_ranges); + ring_.bytes = 3 * (s.host_bytes + worst_ranges * (int64_t)sizeof(RadCopyRange) + k_carve_align); + ring_.host = static_cast(rad_dev_alloc(ring_.bytes, RAD_MEM_HOST_PINNED)); + if (!ring_.host) { + RAD_ERR("step batch staging: could not reserve %s of pinned host staging", + humanb(ring_.bytes).c_str()); + return RAD_E_NOMEM; + } + ring_.head = 0; + ring_.first = 0; + ring_.live = 0; + + /* Local: the host waits on these only to know an upload has READ its span, which a card-wide + * release says as well as a system-wide one. */ + ev_.assign(kFlights, std::vector(ranks_.size(), nullptr)); + ev_free_.clear(); + ev_free_.reserve(kFlights); + for (int f = 0; f < kFlights; ++f) { + for (size_t r = 0; r < ranks_.size(); ++r) { + RAD_TRY(rad_dev_set(ranks_[r].device)); + if (rad_event_create_as(&ev_[(size_t)f][r], RAD_EVENT_LOCAL | RAD_EVENT_HOST_WAIT) < 0) + return RAD_E_DEVICE; + } + ev_free_.push_back(kFlights - 1 - f); + } + RAD_TRY(rad_dev_set(ranks_[0].device)); + + for (Out& o : out_) { + o.kv.assign(ranks_.size(), std::vector(s.groups.size())); + o.batch.assign(ranks_.size(), RadBatch{}); + } + pitch_.assign(s.groups.size(), 1); + bt_mirror_.assign(s.groups.size(), BtMirror{}); + for (BtMirror& m : bt_mirror_) { + m.seq.assign((size_t)max_seqs_, 0); + m.len.assign((size_t)max_seqs_, -1); + } + ranges_.clear(); + return RAD_OK; +} + +void BatchBuilder::forget_tables() { + for (BtMirror& m : bt_mirror_) { + m.pitch = -1; + std::fill(m.len.begin(), m.len.end(), -1); + } +} + +void BatchBuilder::free_set(Set& s) { + for (size_t f = 0; f < ev_.size(); ++f) + for (size_t r = 0; r < ev_[f].size(); ++r) { + if (r < ranks_.size()) rad_dev_set(ranks_[r].device); + if (ev_[f][r]) rad_event_destroy(ev_[f][r]); + } + ev_.clear(); + ev_free_.clear(); + for (size_t r = 0; r < s.dev.size(); ++r) { + if (r < ranks_.size()) rad_dev_set(ranks_[r].device); + if (s.dev[r]) rad_dev_free(s.dev[r], RAD_MEM_DEVICE); + } + if (!ranks_.empty()) rad_dev_set(ranks_[0].device); + s.dev.clear(); + if (ring_.host) { rad_dev_free(ring_.host, RAD_MEM_HOST_PINNED); ring_.host = nullptr; } + ring_.first = 0; + ring_.live = 0; + s.groups.clear(); + for (Out& o : out_) { o.kv.clear(); o.batch.clear(); } +} + +/* A SPAN OF THE RING, contiguous, of `need` bytes. A span that would run past the end starts over + * at zero. Every flight overlapping the span is retired first -- its uploads have run, on every + * rank -- oldest first, which is the order they were issued in and so the order the card + * finishes them. */ +int BatchBuilder::reserve(int64_t need, int64_t* off) { + if (need > ring_.bytes) { + RAD_ERR("step batch staging: a build of %s does not fit the %s ring", + humanb(need).c_str(), humanb(ring_.bytes).c_str()); + return RAD_E_FULL; + } + int64_t at = ring_.head; + if (at + need > ring_.bytes) at = 0; + auto retire_oldest = [&]() -> int { + const Flight& f = ring_.fifo[ring_.first]; + for (RadEvent e : ev_[(size_t)f.ev]) RAD_TRY(rad_event_sync(e)); + ev_free_.push_back(f.ev); + ring_.first = (ring_.first + 1) % kFlights; + --ring_.live; + return RAD_OK; + }; + for (;;) { + bool clash = false; + for (int k = 0; k < ring_.live && !clash; ++k) { + const Flight& f = ring_.fifo[(ring_.first + k) % kFlights]; + clash = f.begin < at + need && at < f.end; + } + if (!clash) break; + RAD_TRY(retire_oldest()); + } + /* And a flight needs an event row: out of rows is out of flights. */ + while (ev_free_.empty() || ring_.live == kFlights) RAD_TRY(retire_oldest()); + *off = at; + return RAD_OK; +} + +/* THE SAME ARRAY ON ANOTHER RANK'S SLAB. Every slab is carved by the same walk() from the same + * sizes, so an array's offset is rank-independent: the byte offset off rank 0's base, re-applied + * to rank r's. */ +template +static inline T* on_rank(void* base_r, void* base_0, T* p0) { + return p0 ? (T*)((char*)base_r + ((char*)p0 - (char*)base_0)) : nullptr; +} + +/* ------------------------------------------------------------------ init */ +int BatchBuilder::init(Program& prog, const Config& cfg, const ChunkGeometry& geo, + const KVGeom& kvg, const std::vector& ranks) { + prog_ = &prog; + cfg_ = cfg; + geo_ = geo; + kvgeom_ = kvg; + ranks_ = ranks; + if (ranks_.empty()) return RAD_E_INVAL; + /* A null stream is the default stream and is legal; a null Program is not -- a derived + * buffer would have no arena to land in. */ + for (const RankIO& r : ranks_) + if (!r.prog) return RAD_E_INVAL; + max_tok_ = cfg.max_tok; + max_seqs_ = cfg.max_seqs; + + if (max_tok_ <= 0 || max_seqs_ <= 0) return RAD_E_INVAL; + if ((int)kvgeom_.g.size() > RAD_SCHED_MAX_KV_GROUPS) { + RAD_ERR("%d KV groups exceeds the %d this build stages for", + (int)kvgeom_.g.size(), RAD_SCHED_MAX_KV_GROUPS); + return RAD_E_FULL; + } + if (kvgeom_.g.size() != prog.kv_groups.size()) return RAD_E_INVAL; + + /* The block-table staging rectangle. A sequence never holds more blocks than its context (or + * its window, which is the whole point of declaring one: a 4K-window layer in a 128K context + * needs a row 32x shorter). The +1 is because a window's blocks are not aligned to the + * window's start, so it can straddle one extra block. */ + max_ctx_ = cfg.max_ctx > 0 ? cfg.max_ctx : prog.meta.n_ctx_train; + if (max_ctx_ <= 0) max_ctx_ = cfg.max_tok; + + /* The conv rolling window: width-1 entries of history plus room for the whole speculative + * window, because a verify writes num_spec+1 conv outputs before anything is accepted, and a + * rejection then reads back at the slot the last accepted token left (spec §10). */ + conv_window_.assign(prog.kv_groups.size(), 1); + conv_group_ = -1; + n_conv_ = 0; + for (size_t i = 0; i < prog.kv_groups.size(); ++i) { + const KVGroupInfo& g = prog.kv_groups[i]; + if (g.decl.kind != RAD_KV_CONV) continue; + ++n_conv_; + conv_group_ = n_conv_ == 1 ? (int32_t)i : -1; /* -1 once there is more than one */ + if (g.decl.conv_width > 0) + conv_window_[i] = (int32_t)(g.decl.conv_width - 1 + + (cfg.n_spec > 0 ? cfg.n_spec : 0) + 1); + } + + /* ------------------------------------------------------------ derived buffers */ + derived_.clear(); + derived_bytes_ = 0; + for (size_t bi = 1; bi < prog.buffers.size(); ++bi) { + BufferInfo& b = prog.buffers[bi]; + if (b.decl.kind != RAD_BUF_DERIVED) continue; + + int idx = derive_index(b.decl.derive); + if (idx < 0) { + std::string known; + for (int i = 0; i < derive_count(); ++i) { + if (i) known += ", "; + known += derive_row(i)->name; + } + RAD_ERR("buffer '%s' declares derivation '%s', which the core does not compute. " + "Known: %s", b.name.c_str(), b.decl.derive ? b.decl.derive : "(null)", + known.c_str()); + return RAD_E_NOTFOUND; + } + if (b.decl.dtype != RAD_I32) { + RAD_ERR("derived buffer '%s' is %s; every derivation the core computes is i32", + b.name.c_str(), rad_dtype_name(b.decl.dtype)); + return RAD_E_DTYPE; + } + + int64_t n = 1; + for (uint32_t d = 0; d < b.decl.rank; ++d) n *= b.decl.shape[d]; + if (n <= 0) { + RAD_ERR("derived buffer '%s' has an empty declared extent", b.name.c_str()); + return RAD_E_SHAPE; + } + + Derived d; + d.handle = (rad_buf)bi; + d.name = derive_row(idx)->name; + d.fn_index = idx; + d.capacity = n; + d.buf = &b; + d.off = derived_bytes_; + + /* WHICH CONV GROUP THIS ONE IS ABOUT. `conv_state_index` is the derivation that reads a + * rolling window, and a model may declare several of different depths -- so the buffer + * names its group and 0 means "the only one of its kind". With more than one conv group + * and no name the answer is a guess between two windows, and the wrong depth produces a + * plausible cursor pointing at history the kernel never wrote. Refused instead. */ + if (std::strcmp(d.name, "conv_state_index") == 0) { + if (b.decl.kv != 0) { + if (b.decl.kv >= prog.kv_groups.size() || + prog.kv_groups[b.decl.kv].decl.kind != RAD_KV_CONV) { + RAD_ERR("derived buffer '%s' names KV group %u, which is not a RAD_KV_CONV " + "group", b.name.c_str(), (unsigned)b.decl.kv); + return RAD_E_INVAL; + } + d.conv_grp = (int32_t)b.decl.kv; + } else if (n_conv_ == 1) { + d.conv_grp = conv_group_; + } else { + RAD_ERR("derived buffer '%s' runs 'conv_state_index' and names no KV group, but " + "%d RAD_KV_CONV groups are declared. Set RadBufDecl::kv -- a cursor " + "computed against the wrong window's depth points at history that was " + "never written.", b.name.c_str(), n_conv_); + return RAD_E_INVAL; + } + } + derived_.push_back(d); + derived_bytes_ = align_up(derived_bytes_ + n * (int64_t)sizeof(int32_t), k_carve_align); + } + + /* Two layers declaring the same derivation get two BufferInfos and two arena slots -- that is + * what the buffer plan produced -- but they share ONE computation: run_derivations computes + * each distinct derivation once per step and copies the result to every destination. The cost + * §8 is about is the recomputation, not the bytes. + * + * SORTED BY (derivation, GROUP), because two buffers running one derivation over different + * conv groups are different answers and the sharing rule below is "same as the previous". */ + std::sort(derived_.begin(), derived_.end(), + [](const Derived& a, const Derived& b) { + return a.fn_index != b.fn_index ? a.fn_index < b.fn_index + : a.conv_grp < b.conv_grp; + }); + + mm_on_ = prog.encoder.modalities != 0; + RAD_TRY(alloc_set(set_, prog.kv_groups)); + out_next_ = 0; + out_last_ = -1; + if (mm_on_) RAD_TRY(alloc_media()); + + /* THE RESERVATION AND WHAT ACTUALLY CROSSES ARE DIFFERENT NUMBERS, so the line says both. + * Nearly all of the slab is block-table rectangles carved for the worst step, and a step + * copies only the rows it filled -- an operator reading the reservation alone would price + * the per-step cost far above what it is. */ + RAD_INFO("step batch: %s pinned staging ring + %s device slab a rank, %d KV group(s), " + "%d derived buffer(s); of the slab, %s is block tables carved for the worst step " + "and only the filled rows cross", + humanb(ring_.bytes).c_str(), humanb(set_.dev_bytes).c_str(), + (int)prog.kv_groups.size(), (int)derived_.size(), + humanb(set_.dev_bytes - set_.bt_base).c_str()); + return RAD_OK; +} + +/* ------------------------------------------------------------------ media staging */ +int BatchBuilder::alloc_media() { + const RadEncoderDecl& e = prog_->encoder; + n_embd_ = e.n_embd; + enc_patches_ = e.max_patches; + enc_dim_ = e.patch_dim; + /* The most segments one pass can hold: a segment is at least one output row, `merge` patches. */ + enc_segs_ = e.max_patches / (e.merge > 0 ? e.merge : 1) + 1; + const int64_t mm_bytes = max_tok_ * n_embd_ * (int64_t)sizeof(uint16_t); + const int64_t pix_bytes = enc_patches_ * enc_dim_ * (int64_t)sizeof(uint16_t); + const int64_t crd_bytes = 4 * enc_patches_ * (int64_t)sizeof(int32_t); + const int64_t cu_bytes = (enc_segs_ + 1) * (int64_t)sizeof(int32_t); + mm_dev_.assign(ranks_.size(), nullptr); + enc_pix_dev_.assign(ranks_.size(), nullptr); + enc_coord_dev_.assign(ranks_.size(), nullptr); + enc_cu_dev_.assign(ranks_.size(), nullptr); + for (size_t r = 0; r < ranks_.size(); ++r) { + RAD_TRY(rad_dev_set(ranks_[r].device)); + mm_dev_[r] = rad_dev_alloc(mm_bytes, RAD_MEM_DEVICE); + enc_pix_dev_[r] = rad_dev_alloc(pix_bytes, RAD_MEM_DEVICE); + enc_coord_dev_[r] = rad_dev_alloc(crd_bytes, RAD_MEM_DEVICE); + enc_cu_dev_[r] = rad_dev_alloc(cu_bytes, RAD_MEM_DEVICE); + if (!mm_dev_[r] || !enc_pix_dev_[r] || !enc_coord_dev_[r] || !enc_cu_dev_[r]) { + RAD_ERR("media staging: could not reserve %s on rank %zu's card", + humanb(mm_bytes + pix_bytes + crd_bytes + cu_bytes).c_str(), r); + return RAD_E_NOMEM; + } + } + RAD_TRY(rad_dev_set(ranks_[0].device)); + mm_host_ = static_cast(rad_dev_alloc(mm_bytes, RAD_MEM_HOST_PINNED)); + enc_pix_host_ = static_cast(rad_dev_alloc(pix_bytes, RAD_MEM_HOST_PINNED)); + enc_coord_host_ = static_cast(rad_dev_alloc(crd_bytes, RAD_MEM_HOST_PINNED)); + enc_cu_host_ = static_cast(rad_dev_alloc(cu_bytes, RAD_MEM_HOST_PINNED)); + if (!mm_host_ || !enc_pix_host_ || !enc_coord_host_ || !enc_cu_host_) { + RAD_ERR("media staging: could not reserve %s of pinned host staging", + humanb(mm_bytes + pix_bytes + crd_bytes + cu_bytes).c_str()); + return RAD_E_NOMEM; + } + if (rad_event_create_as(&mm_ev_, RAD_EVENT_LOCAL | RAD_EVENT_HOST_WAIT) < 0) return RAD_E_DEVICE; + RAD_INFO("media staging: %s a rank for a step's encoder rows and %s for an encoder pass of " + "%lld patches", humanb(mm_bytes).c_str(), + humanb(pix_bytes + crd_bytes + cu_bytes).c_str(), (long long)enc_patches_); + return RAD_OK; +} + +void BatchBuilder::free_media() { + for (size_t r = 0; r < mm_dev_.size(); ++r) { + if (r < ranks_.size()) rad_dev_set(ranks_[r].device); + if (mm_dev_[r]) rad_dev_free(mm_dev_[r], RAD_MEM_DEVICE); + if (enc_pix_dev_[r]) rad_dev_free(enc_pix_dev_[r], RAD_MEM_DEVICE); + if (enc_coord_dev_[r]) rad_dev_free(enc_coord_dev_[r], RAD_MEM_DEVICE); + if (enc_cu_dev_[r]) rad_dev_free(enc_cu_dev_[r], RAD_MEM_DEVICE); + } + if (!ranks_.empty()) rad_dev_set(ranks_[0].device); + mm_dev_.clear(); enc_pix_dev_.clear(); enc_coord_dev_.clear(); enc_cu_dev_.clear(); + if (mm_host_) rad_dev_free(mm_host_, RAD_MEM_HOST_PINNED); + if (enc_pix_host_) rad_dev_free(enc_pix_host_, RAD_MEM_HOST_PINNED); + if (enc_coord_host_) rad_dev_free(enc_coord_host_, RAD_MEM_HOST_PINNED); + if (enc_cu_host_) rad_dev_free(enc_cu_host_, RAD_MEM_HOST_PINNED); + mm_host_ = nullptr; enc_pix_host_ = nullptr; enc_coord_host_ = nullptr; enc_cu_host_ = nullptr; + if (mm_ev_) { rad_event_destroy(mm_ev_); mm_ev_ = nullptr; } + mm_ev_live_ = false; +} + +/* THE ENCODER ROWS OF ONE ENTRY. A row reads its embedding at token `ctx_len + j + shift` -- the + * draft head's history pass shifts its tokens one ahead, and its embeddings with them -- and the + * rows that land in a media run take that run's encoder row instead. Consecutive tokens of one run + * are consecutive rows of its item, so a run is one copy. */ +int64_t BatchBuilder::stage_mm_rows(const StepEntry& e, int64_t k, int64_t shift, int64_t n_rows, + int32_t* rows) { + const mm::PromptMedia& pm = *e.req->media; + const int64_t prompt = (int64_t)e.req->prompt.size(); + int64_t added = 0; + for (int32_t j = 0; j < e.n_tokens; ) { + const int64_t ti = (int64_t)e.ctx_len + j + shift; + if (ti >= prompt) break; /* media is only ever in the prompt */ + const mm::RopeLayout::Run* run = pm.rope.run_at(ti); + if (!run) { ++j; continue; } + const mm::Item& it = *pm.items[(size_t)run->item].item; + if (!it.encoded || (int64_t)it.embd.size() < it.n_rows() * n_embd_) { + RAD_ERR("step batch: request %llu reaches a media item that has not been encoded", + (unsigned long long)e.seq); + return RAD_E_STATE; + } + /* The rest of this run inside this entry, and inside the prompt. */ + int64_t take = std::min((int64_t)run->tok + run->n - ti, e.n_tokens - j); + take = std::min(take, prompt - ti); + const int64_t row = (int64_t)run->row0 + (ti - run->tok); + std::memcpy(mm_host_ + (n_rows + added) * n_embd_, it.embd.data() + row * n_embd_, + (size_t)(take * n_embd_) * sizeof(uint16_t)); + for (int64_t q = 0; q < take; ++q) rows[n_rows + added + q] = (int32_t)(k + j + q); + added += take; + j += (int32_t)take; + } + return added; +} + +void BatchBuilder::fini() { + free_media(); + free_set(set_); + derived_.clear(); +} + +/* ------------------------------------------------------------------ derivations */ +int BatchBuilder::run_derivations(const StepPlan& plan, Set& s) { + if (derived_.empty()) return RAD_OK; + + DeriveInput in; + in.plan = &plan; + in.cu_seqlens = s.h_cu; + in.positions = s.h_pos; + in.n_tok = plan.n_tok; + in.n_seq = (int64_t)plan.e.size(); + in.state_chunk = geo_.state_chunk; + + /* derived_ is sorted by derivation, so "the same one as the previous entry" is the whole + * sharing rule and it needs no map. IT IS A PAIR NOW: two buffers running the same derivation + * over DIFFERENT KV GROUPS are different answers, and sharing them would give one group the + * other's cursors. */ + int last_fn = -1; + int32_t last_grp = -1; + const Derived* last = nullptr; + for (Derived& d : derived_) { + int32_t* host = (int32_t*)(s.h_derived + d.off); + + /* THE GROUP'S OWN SLOTS AND ITS OWN WINDOW. `conv_state_index` computes a cursor inside a + * rolling window, so the depth has to be that group's: one number shared across groups + * fits only one of them, and the wrong depth produces a plausible cursor pointing at + * history the kernel never wrote. */ + const int32_t grp = d.conv_grp; + in.conv_slot = (grp >= 0) ? s.h_convslot + (int64_t)grp * max_seqs_ : nullptr; + in.conv_window = (grp >= 0 && grp < (int32_t)conv_window_.size()) ? conv_window_[grp] : 1; + + if (d.fn_index == last_fn && d.conv_grp == last_grp && last) { + d.produced = last->produced; + std::memcpy(host, s.h_derived + last->off, (size_t)d.produced * sizeof(int32_t)); + } else { + const DeriveRow* row = derive_row(d.fn_index); + int64_t n = 0; + int st = row->fn(in, host, d.capacity, &n); + if (st < 0) { + RAD_ERR("derivation '%s' for buffer '%s' failed: %s (declared capacity %lld)", + row->name, d.buf->name.c_str(), rad_strerror(st), (long long)d.capacity); + return st; + } + d.produced = n; + last_fn = d.fn_index; + last_grp = d.conv_grp; + last = &d; + } + + /* INTO EVERY RANK'S ARENA, on that rank's stream. A derived buffer is an ordinary + * transient the core fills, so it lives in the per-rank arena the buffer plan placed -- + * copying only into rank 0's leaves every other rank reading whatever its arena held. */ + for (const RankIO& io : ranks_) { + if (d.handle >= io.prog->buffers.size()) return RAD_E_STATE; + void* dst = io.prog->buffers[d.handle].ptr; + if (!dst) { + RAD_ERR("derived buffer '%s' has no arena slot; the buffer plan has not run", + d.buf->name.c_str()); + return RAD_E_STATE; + } + RAD_TRY(rad_memcpy_async(dst, host, d.produced * (int64_t)sizeof(int32_t), + io.stream)); + } + } + return RAD_OK; +} + + +/* ------------------------------------------------------------------ per-group fill */ +int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set& s, Out& o) { + const int64_t n_seq = (int64_t)plan.e.size(); + int32_t* const pay = s.bt_h0; /* the payload: the table entries this build restages */ + int64_t np = 0; + ranges_.clear(); + /* `n` entries of the payload from word `src` to word `dst` of the card's table region, as + * ranges of at most k_range_max bytes. A run that continues the last range extends it, which + * is what makes a whole restage of consecutive rows a handful of ranges and not one a row. */ + auto stage = [&](int64_t dst, int64_t src, int64_t n) { + int64_t db = s.bt_base + dst * (int64_t)sizeof(int32_t); + int64_t sb = s.bt_base + src * (int64_t)sizeof(int32_t); + int64_t nb = n * (int64_t)sizeof(int32_t); + if (!ranges_.empty()) { + RadCopyRange& b = ranges_.back(); + if (b.src + b.bytes == sb && b.dst + b.bytes == db && b.bytes < k_range_max) { + const int64_t t = std::min(nb, k_range_max - b.bytes); + b.bytes += t; db += t; sb += t; nb -= t; + } + } + while (nb > 0) { + const int64_t t = std::min(nb, k_range_max); + ranges_.push_back(RadCopyRange{ sb, db, t }); + db += t; sb += t; nb -= t; + } + }; + + /* Every group's row, not just the first: a sequence with no state in a group must read -1 + * there, and a stale slot from the previous step is the worst possible value. */ + for (int64_t gi = 0; gi < (int64_t)kvgeom_.g.size(); ++gi) + for (int64_t i = 0; i < n_seq; ++i) s.h_convslot[gi * max_seqs_ + i] = -1; + + for (size_t gi = 0; gi < s.groups.size(); ++gi) { + Group& g = s.groups[gi]; + const KVGeom::G& L = kvgeom_.g[gi]; + + /* THIS STEP's pitch, which build() measured before it sized the span. RadKVGroupBatch + * carries it, so the device reads the rows at the width they were staged. A new pitch + * moves every row, so nothing the card holds is where this build reads it. */ + const int64_t pitch = pitch_[gi]; + BtMirror& m = bt_mirror_[gi]; + if (L.paged && m.pitch != pitch) { + m.pitch = pitch; + std::fill(m.len.begin(), m.len.end(), -1); + } + + int64_t t = 0; + for (int64_t i = 0; i < n_seq; ++i) { + const StepEntry& e = plan.e[(size_t)i]; + + int64_t first = 0; + if (L.paged) { + /* The block table is the MANAGER's, read by sequence id. Request::blocks is not + * the source of truth: two allocators disagreeing about what a sequence owns is + * the bug where a freed sequence's blocks are handed out from under it. */ + const std::vector& bt = kv.block_table(e.seq, (int32_t)gi); + first = kv.first_block_pos(e.seq, (int32_t)gi); + for (int32_t j = 0; j < e.n_tokens; ++j) + g.h_slot[t + j] = kvgeom_.slot((int)gi, bt, first, (int64_t)e.ctx_len + j); + /* THE ROW, FROM WHAT THE CARD ALREADY HOLDS OF IT. The same sequence in the same + * row keeps every entry below the lowest one the manager changed and below the end + * of both the old and the new table; a decode step's row is then nothing, or the + * one block it appended. Anything else -- a new sequence, one that moved rows -- is + * the whole row, and its copies in other rows stop being current, since its marks + * are taken here. The marks are taken for every row either way. */ + const int64_t nb = std::min((int64_t)bt.size(), pitch); + const int64_t chg = kv.take_table_changes(e.seq, (int32_t)gi); + int64_t lo = 0, hi = pitch; + if (m.len[(size_t)i] >= 0 && m.seq[(size_t)i] == e.seq) { + lo = std::min(std::min(chg, m.len[(size_t)i]), nb); + hi = std::max(nb, m.len[(size_t)i]); + } else { + for (int64_t k = 0; k < max_seqs_; ++k) + if (m.seq[(size_t)k] == e.seq) m.len[(size_t)k] = -1; + } + if (lo < hi) { + int32_t* w = pay + np; + const int64_t nc = nb > lo ? nb - lo : 0; + std::memcpy(w, bt.data() + lo, (size_t)nc * sizeof(int32_t)); + std::fill(w + nc, w + (hi - lo), -1); + stage(g.bt_fix + i * pitch + lo, np, hi - lo); + np += hi - lo; + } + m.seq[(size_t)i] = e.seq; + m.len[(size_t)i] = nb; + } else { + /* A linear or conv group owns one state instance per sequence, so every token of + * the sequence maps to it and the "block table" row is that slot -- a kernel that + * only reads block tables then needs no second path. */ + int32_t st = kv.state_slot(e.seq, (int32_t)gi); + for (int32_t j = 0; j < e.n_tokens; ++j) g.h_slot[t + j] = st; + pay[np + i] = st; + /* EVERY conv group, at its own row. This array feeds `DeriveInput::conv_slot` + * and NOTHING ELSE -- a conv KERNEL reads its slot from + * RadKVGroupBatch::state_index, which is filled per group a few lines below and + * always has been. See the note at conv_window_ in init(). */ + if (kvgeom_.g[gi].kind == RAD_KV_CONV) + s.h_convslot[(int64_t)gi * max_seqs_ + i] = st; + } + s.h_first[(int64_t)gi * max_seqs_ + i] = (int32_t)first; + t += e.n_tokens; + + /* THE TOKENS THIS SEQUENCE ACTUALLY HOLDS, WHICH IS NOT min(length, window). + * + * `seqused` is a count from index 0 of the BLOCK TABLE, and the table of a windowed + * group is REBASED at `first_block_pos` once the window slides -- kvgeom_.slot() above + * subtracts exactly that. So the count the kernel needs is the held span, and the held + * span is a whole number of BLOCKS: recycling leaves `window_blocks` of them, whose + * last one is partially filled by however far past a block boundary the sequence has + * got. `min(length, window)` reports the full window every time and therefore claims + * up to block_size - 1 positions that were never written this pass -- and they are the + * ones at the END of the table, which every attention kernel reads as the NEWEST + * context. Their bytes are whatever the recycled block held. + * + * A NON-CAUSAL windowed group is where this bites: every query row attends to those + * stale slots at full weight, and acceptance falls off a cliff at exactly the context + * where the window first slides. A causal group hides the same defect, because a stale + * slot past the query is masked anyway. + * + * No clamp to `window` any more: block granularity means the held span can exceed the + * window by less than a block, and dropping that from the FRONT of the count would + * drop the NEWEST tokens rather than the oldest. Attending to a few extra old + * positions is what paging a sliding window costs, and it is what vLLM does too. */ + int64_t used = (int64_t)e.ctx_len + e.n_tokens - first; + if (used < 0) used = 0; + g.h_used[i] = (int32_t)used; + if (L.paged) { + for (int64_t j = 0; j < g.sidx_pitch; ++j) g.h_sidx[i * g.sidx_pitch + j] = -1; + } else { + kv.state_index_row(e.seq, (int32_t)gi, g.h_sidx + i * g.sidx_pitch, + (int)g.sidx_pitch); + } + } + /* A state group's rows are one slot a sequence: restaged whole, since they are n_seq + * words and one range. */ + if (!L.paged) { + stage(g.bt_fix, np, n_seq); + np += n_seq; + } + + { + const char* d0 = static_cast(s.dev[0]); + AdvGroup& a = s.h_grp[gi]; + a.block_size = (int32_t)L.block_size; + a.paged = L.paged ? 1 : 0; + a.pitch = (int32_t)pitch; + a.pad = 0; + a.slot_off = (const char*)g.d_slot - d0; + a.used_off = (const char*)g.d_used - d0; + a.bt_off = (const char*)g.d_bt - d0; + a.first_off = (const char*)(s.d_first + (int64_t)gi * max_seqs_) - d0; + } + + for (size_t r = 0; r < ranks_.size(); ++r) { + void* base = s.dev[r]; + RadKVGroupBatch& b = o.kv[r][gi]; + b.group = g.g; + b.slot_mapping = on_rank(base, s.dev[0], g.d_slot); + b.block_table = on_rank(base, s.dev[0], g.d_bt); + b.block_table_pitch = pitch; + b.seqused = on_rank(base, s.dev[0], g.d_used); + b.state_index = on_rank(base, s.dev[0], g.d_sidx); + b.state_index_pitch = g.sidx_pitch; + b.block_size = L.block_size; + b.max_blocks = pitch; + + /* The bytes cross in build()'s one slab copy: a group's arrays are carved out of + * the same slab as everything else and there is nothing group-shaped about them. */ + } + } + pay_words_ = np; + return RAD_OK; +} + +/* ------------------------------------------------------------------ build */ +const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv, int step) { + if (plan.e.empty()) return nullptr; + if ((int64_t)plan.e.size() > max_seqs_ || plan.n_tok > max_tok_) { + RAD_ERR("step plan of %d sequences / %lld tokens exceeds the pools sized at %lld / %lld", + (int)plan.e.size(), (long long)plan.n_tok, + (long long)max_seqs_, (long long)max_tok_); + return nullptr; + } + if (plan.spec_is_tree) { + /* spec_parent is in the ABI and its pool is allocated, but no drafter in v1 emits a tree, + * so the parent chain and the positions a tree implies are not written. Saying so beats + * filling the array with the linear-chain answer, which would verify a tree against the + * wrong causal mask and produce fluent wrong text. */ + RAD_ERR("tree-layout speculation was requested but is not implemented in this build"); + return nullptr; + } + + Set& s = set_; + const int64_t n_seq = (int64_t)plan.e.size(); + + /* THE CONTEXT BOUND, rounded (see bound_bucket), before anything that derives from it. */ + int32_t max_ctx = 0, max_q = 0; + for (const StepEntry& e : plan.e) { + if (e.ctx_len > max_ctx) max_ctx = e.ctx_len; + if (e.n_tokens > max_q) max_q = e.n_tokens; + } + const int64_t ctx_bound = std::min(bound_bucket(max_ctx, k_bound_tokens), max_ctx_); + + /* THE BLOCK-TABLE PITCH OF EVERY GROUP FIRST, because it sizes the build's span of the ring: + * the span is the fixed prefix and exactly the rows build_groups will pack. The pitch is a + * property of THIS STEP, not of the deployment -- a rectangle wide enough for max_ctx would be + * megabytes staged and copied on every decode step to carry a few hundred live entries. + * + * IT IS A FUNCTION OF THE CONTEXT BOUND, so the two move on the same step. Both are in a + * recorded pass's key, and rounded separately they cross their buckets on different steps -- + * every crossing of either is a pass recorded again, so twice the recordings for nothing. A + * row holds the sequence's context plus this step's tokens plus the scheduler's draft + * lookahead, which is at most two speculative windows, and the pitch is that rounded up to + * the bound's own grid. A table longer than that (none is, today) takes its own rounded + * length, which is correct and only costs the alignment. */ + const int64_t reach = ctx_bound + max_q + 2 * ((int64_t)std::max(plan.n_spec, 0) + 1); + int64_t pay_need = 0; /* the payload if every row were restaged whole */ + for (size_t gi = 0; gi < s.groups.size(); ++gi) { + int64_t pitch = 1; + if (kvgeom_.g[gi].paged) { + int64_t need = 1; + for (int64_t i = 0; i < n_seq; ++i) { + const int64_t n = (int64_t)kv.block_table(plan.e[(size_t)i].seq, (int32_t)gi).size(); + if (n > need) need = n; + } + const int64_t bs = kvgeom_.g[gi].block_size > 0 ? kvgeom_.g[gi].block_size : 1; + const int64_t gq = (k_bound_tokens + bs - 1) / bs; + pitch = ((reach + bs - 1) / bs + gq - 1) / gq * gq; + if (need > pitch) pitch = bound_bucket(need, gq); + if (pitch > s.groups[gi].max_blocks) pitch = s.groups[gi].max_blocks; + } + pitch_[gi] = pitch; + pay_need += n_seq * pitch * (int64_t)sizeof(int32_t); + } + /* THE SPAN: the fixed prefix, the payload, and the range list behind it, each at its bound -- + * a range a row or state group plus one a k_range_max of payload. What the build turns out to + * use is usually far less, and only that is held once it is known. */ + const int64_t max_ranges = pay_need / k_range_max + n_seq * (int64_t)s.groups.size() + 1; + int64_t off = 0; + const int64_t need = align_up(s.bt_base + align_up(pay_need, 16) + + max_ranges * (int64_t)sizeof(RadCopyRange), k_carve_align); + RAD_TRY_NULL(reserve(need, &off)); + carve(s, ring_.host + off); + Out& o = out_[out_next_]; + + const int64_t n_tok = plan.n_tok; + + /* ---------------------------------------------------------- tokens, positions, boundaries */ + int64_t k = 0; + /* PER HALF as well as overall: a mixed step`s max_q is its prefill chunk, and a block that + * issues the decode rows separately must not select their kernel band with it. */ + int32_t max_q_dec = 0, max_q_pf = 0; + int n_ck = 0; + int64_t n_out = 0, n_dout = 0; + int32_t rope_mixed = 0; + int64_t n_mm = 0; + s.h_cu[0] = 0; + for (int64_t i = 0; i < n_seq; ++i) { + const StepEntry& e = plan.e[(size_t)i]; + s.h_rows[i] = e.dev ? 1 : 0; + s.h_rows[max_seqs_ + i] = e.dev_tok; + s.h_rows[2 * max_seqs_ + i] = e.dev_out; + s.h_rows[3 * max_seqs_ + i] = e.dev_aux; + } + for (int64_t i = 0; i < n_seq; ++i) { + const StepEntry& e = plan.e[(size_t)i]; + /* The advance indexes the card's StepSlots by this, and there are max_seqs of them. */ + if (e.card < 0 || e.card >= max_seqs_) { + RAD_ERR("step plan row %lld: sequence %llu has card index %d, outside the %lld step " + "slots", (long long)i, (unsigned long long)e.seq, (int)e.card, + (long long)max_seqs_); + return nullptr; + } + /* THE MTP HEAD READS ONE POSITION AHEAD. Its index i pairs the trunk`s hidden state at i + * with the EMBEDDING OF THE TOKEN AT i + 1, and predicts i + 2 (rad_block_mtp_fp8.h). The + * shift is applied once, here, so that no kernel and no plugin carries it -- and + * token_at() reaches the drafter`s own earlier rounds through `draft` exactly as a verify + * step reaches its proposal. StepPlan::tok_shift says how far, because it is the HEAD's + * indexing and not the draft round's: DFlash2 is a draft pass that shifts by nothing. */ + const int64_t shift = plan.tok_shift; + for (int32_t j = 0; j < e.n_tokens; ++j) { + s.h_tok[k + j] = token_at(e, (int64_t)e.ctx_len + j + shift); + s.h_pos[k + j] = e.ctx_len + j; + } + /* THE ROTARY POSITION OF EACH ROW, at the row's own position -- the draft head's rows + * rotate at the index they write, not at the token they embed. Planes of n_tok. */ + if (mm_on_) { + const mm::RopeLayout* rl = + (e.req && e.req->media && !e.req->media->rope.empty()) ? &e.req->media->rope : nullptr; + for (int32_t j = 0; j < e.n_tokens; ++j) { + int32_t v[3]; + const int64_t p = (int64_t)e.ctx_len + j; + if (rl) rl->at(p, v); + else v[0] = v[1] = v[2] = (int32_t)p; + s.h_rope[k + j] = v[0]; + s.h_rope[n_tok + k + j] = v[1]; + s.h_rope[2 * n_tok + k + j] = v[2]; + if (v[1] != v[0] || v[2] != v[0]) rope_mixed = 1; + } + if (e.req && e.req->media && !e.req->media->items.empty()) { + /* The staging is the last upload's until that upload has run. */ + if (mm_ev_live_) { + if (rad_event_sync(mm_ev_) < 0) return nullptr; + mm_ev_live_ = false; + } + const int64_t got = stage_mm_rows(e, k, shift, n_mm, s.h_mmrow); + if (got < 0) return nullptr; + n_mm += got; + } + } + if (e.ckpt_tok >= 0 && e.ckpt_slot >= 0) { + /* checkpoint_tok indexes THIS STEP's tokens, so it is the sequence's base plus the + * offset the scheduler chose -- which the chunk split guarantees is the last token of + * a checkpoint interval (§7.3). */ + s.h_cktok[n_ck] = (int32_t)(k + e.ckpt_tok); + s.h_ckslot[n_ck] = e.ckpt_slot; + ++n_ck; + } + /* Which of this step's tokens the sampler wants logits for. `produces_token` is the + * scheduler's answer to "is this entry's last token the sequence's last" -- false for the + * middle chunk of a long prefill, which therefore contributes no row and does not touch + * the lm_head at all. At a speculative verify every drafted position needs a distribution + * to accept against, so the entry contributes 1 + n_spec rows and not one. */ + /* AN MTP PASS NAMES ITS OWN ROWS, and they are rows of the PREVIOUS step: the head + * gathers the trunk`s hidden state for the positions it continues from, and which those + * are is not a function of this batch at all. One per token of the pass, consecutive from + * `hidden_row` -- which is a single row for a draft round and a whole chunk for a history + * pass. See StepEntry::hidden_row. */ + if (e.hidden_row >= 0) { + const int32_t nr = e.hidden_n > 0 ? e.hidden_n : e.n_tokens; + for (int32_t j = 0; j < nr; ++j) s.h_out[n_out++] = e.hidden_row + j; + } else if (e.produces_token) { + const int32_t first = (int32_t)(k + e.n_tokens) - 1 - e.n_spec; + for (int32_t j = 0; j <= e.n_spec; ++j) s.h_out[n_out++] = first + j; + } + if (e.draft_out) s.h_dout[n_dout++] = (int32_t)(k + e.n_tokens - 1); + /* RADIANCE_DFLASH_TRACE prints what a drafter pass actually consumes -- the pass kind, the + * absolute positions, and the token ids at them. A block-diffusion drafter reads an ANCHOR + * the target has already chosen followed by mask ids, and every way of getting that wrong + * (an anchor one token stale, a mask id that is an ordinary token, a position base that + * disagrees with the KV the context pass wrote) produces the same symptom from outside: + * acceptance near zero and output still exactly correct. So it is printed rather than + * reasoned about. */ + static const bool trace = std::getenv("RADIANCE_DFLASH_TRACE") != nullptr; + if (trace && plan.draft_pass != 0) { + std::string ln = fmt("df %s seq %d pos %d..%d tok", + plan.draft_pass > 0 ? "query " : "context", + (int)e.seq, (int)e.ctx_len, (int)(e.ctx_len + e.n_tokens - 1)); + for (int32_t j = 0; j < e.n_tokens && j < 12; ++j) + ln += fmt(" %d", (int)s.h_tok[k + j]); + RAD_INFO("%s", ln.c_str()); + } + k += e.n_tokens; + s.h_cu[i + 1] = (int32_t)k; + s.h_sid[i] = e.card; + s.h_q[i] = e.n_tokens; + s.h_ctx[i] = e.ctx_len; + s.h_acc[i] = e.n_accepted; + if (e.is_prefill) { if (e.n_tokens > max_q_pf) max_q_pf = e.n_tokens; } + else { if (e.n_tokens > max_q_dec) max_q_dec = e.n_tokens; } + } + if (k != n_tok) { + RAD_ERR("step plan token count %lld does not match its entries (%lld)", + (long long)n_tok, (long long)k); + return nullptr; + } + + /* THE SCORED ROWS (Request::score), after every row the sampler reads: a row at each token of + * a scoring entry's prefill chunk, in entry order, which is the order Engine::score_rows walks + * to map them back to a request and a position. They come after so that nothing indexing the + * sampled rows -- the sampler, the card's acceptance (dev_out) -- sees them at all. A trunk + * pass only: a draft pass's rows are the head's, not the model's. */ + if (cfg_.kld() && plan.draft_pass == 0 && plan.tok_shift == 0) { + int64_t at = 0; + for (int64_t i = 0; i < n_seq; ++i) { + const StepEntry& e = plan.e[(size_t)i]; + if (e.req && e.req->score && e.is_prefill && e.hidden_row < 0) + for (int32_t j = 0; j < e.n_tokens; ++j) s.h_out[n_out++] = (int32_t)(at + j); + at += e.n_tokens; + } + if (n_out > max_tok_ + max_seqs_) { + RAD_ERR("step batch: %lld logits rows past the %lld the KL mode sized for", + (long long)n_out, (long long)(max_tok_ + max_seqs_)); + return nullptr; + } + } + + /* THE PROMPT THAT FOLLOWS: the last sequence's next tokens, up to a step of them, after this + * step's own (RadBatch::n_ahead). Only on a trunk pass whose last entry is a prefill chunk with + * more of its sequence still to run -- a draft pass's tokens are shifted and it reads no such + * data -- and bounded by the tokens the request has, so a re-prefill after preemption reads + * its own output as the prompt's continuation, as token_at does. */ + int64_t n_ahead = 0; + if (n_seq > 0 && plan.draft_pass == 0 && plan.tok_shift == 0) { + const StepEntry& e = plan.e[(size_t)(n_seq - 1)]; + if (e.req && e.is_prefill) { + const int64_t next = (int64_t)e.ctx_len + e.n_tokens; + const int64_t have = (int64_t)e.req->prompt.size() + (int64_t)e.req->output.size(); + n_ahead = std::min(std::max(have - next, 0), max_tok_); + for (int64_t j = 0; j < n_ahead; ++j) s.h_tok[n_tok + j] = token_at(e, next + j); + } + } + + /* From here the manager's change marks are taken, so a build that stops before its upload + * is issued on every rank leaves the card's tables unknown to the next one. */ + if (int st = build_groups(plan, kv, s, o); st < 0) { + forget_tables(); + RAD_ERR("step batch: build_groups -> %s", rad_strerror(st)); + return nullptr; + } + const int64_t rng_at = s.bt_base + align_up(pay_words_ * (int64_t)sizeof(int32_t), 16); + const int n_rng = (int)ranges_.size(); + if (n_rng > max_ranges) { + forget_tables(); + RAD_ERR("step batch: %d upload ranges past the bound of %lld", n_rng, + (long long)max_ranges); + return nullptr; + } + RadCopyRange* const rng = reinterpret_cast(ring_.host + off + rng_at); + std::memcpy(rng, ranges_.data(), (size_t)n_rng * sizeof(RadCopyRange)); + const int64_t used = align_up(rng_at + n_rng * (int64_t)sizeof(RadCopyRange), k_carve_align); + + /* ---------------------------------------------------------- ONE COPY PER RANK + * + * carve() lays out the host span and every rank's device slab in the same order, at the same + * sizes, aligning the OFFSET and not the pointer. So below bt_base the device slab is a + * byte-for-byte mirror of the host span, and a whole step's staging -- the token and position + * arrays, the per-sequence arrays, and every KV group's slot map, seqused and state index -- + * crosses in one transfer, with the block-table entries that changed riding the same dispatch + * as ranges. + * + * One copy per ARRAY would carry only the prefix the step used, which is the right trade when + * the arrays are full and the wrong one when they are not. A decode step has about two + * kilobytes of live staging spread over dozens of arrays -- one per array, per KV group, per + * rank -- and at that size the bytes are the smallest part of the cost: each transfer costs a + * dispatch plus the dependent gap behind it, which together dominate the DMA. + * + * The over-copy is the unused tail of the arrays sized by max_num_batched_tokens. At a full + * prefill chunk it is nothing at all -- the same bytes cross either way and only the launch + * count differs -- and at decode a few microseconds of DMA buys back dozens of dispatches. + * + * It also removes the need for a gate on `num_accepted`: the kernels read that operand + * whenever the DEPLOYMENT speculates, not only when the step drafted, so copying it + * conditionally leaves them reading the arena on exactly the step that had something to roll + * back. Everything in the slab crosses on every step. + * + * AND IT STAYS ON THE COMPUTE STREAM, which is not an oversight. Moving it to a third, + * staging stream -- so that a producer on the second lane could see its batch without + * queueing behind compute -- is substantially SLOWER at every concurrency, byte-identical. + * Sharing the queue is load-bearing: the split has to pay for two orderings the queue gives + * away, and the one that hurts is the copy waiting on the event that says the step which last + * read this slab is done -- it cannot start until the previous step has drained, where riding + * the compute stream lets it issue in line. That is three cross-stream round-trips a step a + * rank against a prize of a few percent. Do not rebuild the staging stream. */ + for (size_t r = 0; r < ranks_.size(); ++r) { + const int st = rad_memcpy_ranges_async(s.dev[r], ring_.host + off, s.bt_base, rng, n_rng, + ranks_[r].stream); + if (st < 0) { + forget_tables(); + RAD_ERR("step batch: rank %zu's upload -> %s", r, rad_strerror(st)); + return nullptr; + } + } + + /* Derived metadata reads the host staging, so it runs after the fills and before the event. */ + RAD_TRY_NULL(run_derivations(plan, s)); + + /* ---------------------------------------------------------- encoder rows + * Behind the slab on every rank's stream, so the rows are on the card before any kernel of the + * pass reads them: rank 0 takes the staged rows, every other rank the zeros that make the + * vocabulary reduction count each row once. */ + if (n_mm > 0) { + const int64_t bytes = n_mm * n_embd_ * (int64_t)sizeof(uint16_t); + for (size_t r = 0; r < ranks_.size(); ++r) { + const int st = r == 0 ? rad_memcpy_async(mm_dev_[r], mm_host_, bytes, ranks_[r].stream) + : rad_memset_async(mm_dev_[r], 0, bytes, ranks_[r].stream); + if (st < 0) { + RAD_ERR("step batch: rank %zu's encoder rows -> %s", r, rad_strerror(st)); + return nullptr; + } + } + if (rad_event_record(mm_ev_, ranks_[0].stream) < 0) return nullptr; + mm_ev_live_ = true; + } + + /* ---------------------------------------------------------- the batch, one per rank */ + for (size_t r = 0; r < ranks_.size(); ++r) { + void* const base = s.dev[r]; + void* const b0 = s.dev[0]; + RadBatch& B = o.batch[r]; + B.phase = plan.phase; + B.step = step; + B.n_tok = n_tok; + B.n_seq = n_seq; + B.token_ids = on_rank(base, b0, s.d_tok); + B.positions = on_rank(base, b0, s.d_pos); + B.cu_seqlens = on_rank(base, b0, s.d_cu); + B.seq_ids = on_rank(base, b0, s.d_sid); + B.n_out = n_out; + B.out_ids = n_out ? on_rank(base, b0, s.d_out) : nullptr; + B.n_draft_out = n_dout; + B.draft_out_ids = n_dout ? on_rank(base, b0, s.d_dout) : nullptr; + B.q_lens = on_rank(base, b0, s.d_q); + B.ctx_lens = on_rank(base, b0, s.d_ctx); + B.max_q_len = max_q; + B.n_seq_decode = plan.n_seq_decode; + B.n_tok_decode = plan.n_tok_decode; + B.max_q_len_decode = max_q_dec; + B.max_q_len_prefill = max_q_pf; + B.max_ctx_len = (int32_t)ctx_bound; + B.n_kv_groups = (int)o.kv[r].size(); + B.kv = o.kv[r].data(); + B.draft_pass = plan.draft_pass; + B.n_spec = plan.n_spec; + /* PASSED WHENEVER THE DEPLOYMENT SPECULATES, not only on the steps that drafted. A step that + * declines to draft still FOLLOWS one that did, and the linear kernels need to know how much + * of that step survived before they can start. Gating this on the step's own draft count + * makes the kernels fall back to their absent-operand default of 1 on exactly the step that + * had something to roll back. */ + B.num_accepted = cfg_.n_spec > 0 ? on_rank(base, b0, s.d_acc) : nullptr; + B.spec_parent = nullptr; /* a linear chain; the tree case is refused above */ + B.rope_pos = mm_on_ ? on_rank(base, b0, s.d_rope) : nullptr; + B.rope_mixed = rope_mixed; + B.n_mm_rows = n_mm; + B.mm_rows = n_mm ? on_rank(base, b0, s.d_mmrow) : nullptr; + B.mm_embd = n_mm ? mm_dev_[r] : nullptr; + B.enc = 0; + B.enc_n_patch = 0; + B.enc_pixels = nullptr; + B.enc_coord = nullptr; + B.enc_n_seg = 0; + B.enc_cu = nullptr; + B.enc_max_seg = 0; + B.n_checkpoints = n_ck; + B.checkpoint_tok = n_ck ? on_rank(base, b0, s.d_cktok) : nullptr; + B.checkpoint_slot = n_ck ? on_rank(base, b0, s.d_ckslot) : nullptr; + B.n_ahead = n_ahead; + } + /* THE FLIGHT, behind everything that reads this span: the upload, and the derivation copies + * run_derivations issued above. */ + const int ev = ev_free_.back(); + ev_free_.pop_back(); + for (size_t r = 0; r < ranks_.size(); ++r) { + if (rad_event_record(ev_[(size_t)ev][r], ranks_[r].stream) < 0) { + RAD_ERR("step batch: could not record rank %zu's staging event", r); + ev_free_.push_back(ev); + return nullptr; + } + } + ring_.fifo[(ring_.first + ring_.live) % kFlights] = Flight{ off, off + used, ev }; + ++ring_.live; + last_n_seq_ = n_seq; + last_n_tok_ = n_tok; + ring_.head = off + used; + out_last_ = out_next_; + out_next_ = (out_next_ + 1) % kOut; + return &o.batch[0]; +} + +/* The batch the last build produced for one rank. Same numbers as build()'s return; different + * device pointers, because each rank reads its own slab. */ +const RadBatch* BatchBuilder::batch_for(int rank) const { + if (out_last_ < 0) return nullptr; + const Out& o = out_[out_last_]; + if (rank < 0 || (size_t)rank >= o.batch.size()) return nullptr; + return &o.batch[(size_t)rank]; +} + +AdvanceArgs BatchBuilder::advance_args(int rank) const { + AdvanceArgs a; + if (rank < 0 || (size_t)rank >= set_.dev.size()) return a; + const Set& s = set_; + const char* d0 = static_cast(s.dev[0]); + auto off = [&](const void* p) { return (int64_t)((const char*)p - d0); }; + a.n_seq = (int32_t)last_n_seq_; + a.n_groups = (int32_t)s.groups.size(); + a.slab = static_cast(s.dev[(size_t)rank]); + a.tok_off = off(s.d_tok); + a.pos_off = off(s.d_pos); + a.ctx_off = off(s.d_ctx); + a.acc_off = off(s.d_acc); + a.out_off = off(s.d_out); + a.sid_off = off(s.d_sid); + a.cu_off = off(s.d_cu); + a.q_off = off(s.d_q); + a.row_off = off(s.d_rows); + a.row_pitch = (int32_t)max_seqs_; + a.grp_off = off(s.d_grp); + if (mm_on_) { + a.rope_off = off(s.d_rope); + a.rope_pitch = (int32_t)last_n_tok_; + } + return a; +} + +/* ------------------------------------------------------------------ the encoder pass */ +const RadBatch* BatchBuilder::build_encoder(const std::vector& parts, int step) { + if (!mm_on_ || parts.empty()) return nullptr; + int64_t n_patch = 0, n_seg = 0, max_seg = 0; + enc_cu_host_[0] = 0; + for (const EncoderPart& p : parts) { + const mm::Item& it = *p.item; + const int64_t seg_p = (int64_t)it.grid_h * it.grid_w; + const int64_t np = seg_p * p.n_seg; + if (it.patch_dim != enc_dim_ || n_patch + np > enc_patches_ || + n_seg + p.n_seg > enc_segs_ || p.seg0 + p.n_seg > it.n_seg) { + RAD_ERR("encoder pass: %lld patches in %lld segments do not fit the declared pass of " + "%lld patches of %lld elements", (long long)(n_patch + np), + (long long)(n_seg + p.n_seg), (long long)enc_patches_, (long long)enc_dim_); + return nullptr; + } + std::memcpy(enc_pix_host_ + n_patch * enc_dim_, + it.pixels.data() + (int64_t)p.seg0 * seg_p * enc_dim_, + (size_t)(np * enc_dim_) * sizeof(uint16_t)); + n_patch += np; + for (int32_t q = 0; q < p.n_seg; ++q) { + enc_cu_host_[n_seg + 1] = enc_cu_host_[n_seg] + (int32_t)seg_p; + ++n_seg; + } + if (seg_p > max_seg) max_seg = seg_p; + } + /* Coordinates in planes of n_patch, which is what makes planes 0 and 1 a dense [2, n_patch]. */ + { + std::vector tmp; + int64_t at = 0; + for (const EncoderPart& p : parts) { + const mm::Item& it = *p.item; + const int64_t seg_p = (int64_t)it.grid_h * it.grid_w; + const int64_t np = seg_p * p.n_seg; + tmp.resize((size_t)(4 * np)); + it.coords((int64_t)p.seg0 * seg_p, np, tmp.data()); + for (int c = 0; c < 4; ++c) + std::memcpy(enc_coord_host_ + c * n_patch + at, tmp.data() + c * np, + (size_t)np * sizeof(int32_t)); + at += np; + } + } + for (size_t r = 0; r < ranks_.size(); ++r) { + RadStream st = ranks_[r].stream; + if (rad_memcpy_async(enc_pix_dev_[r], enc_pix_host_, + n_patch * enc_dim_ * (int64_t)sizeof(uint16_t), st) < 0 || + rad_memcpy_async(enc_coord_dev_[r], enc_coord_host_, + 4 * n_patch * (int64_t)sizeof(int32_t), st) < 0 || + rad_memcpy_async(enc_cu_dev_[r], enc_cu_host_, + (n_seg + 1) * (int64_t)sizeof(int32_t), st) < 0) { + RAD_ERR("encoder pass: rank %zu's upload failed", r); + return nullptr; + } + } + Out& o = out_[out_next_]; + for (size_t r = 0; r < ranks_.size(); ++r) { + RadBatch& B = o.batch[r]; + B = RadBatch{}; + B.phase = RAD_PHASE_PREFILL; + B.step = step; + B.n_kv_groups = (int)o.kv[r].size(); + B.kv = o.kv[r].data(); + B.enc = 1; + B.enc_n_patch = n_patch; + B.enc_pixels = enc_pix_dev_[r]; + B.enc_coord = static_cast(enc_coord_dev_[r]); + B.enc_n_seg = n_seg; + B.enc_cu = static_cast(enc_cu_dev_[r]); + B.enc_max_seg = (int32_t)max_seg; + } + out_last_ = out_next_; + out_next_ = (out_next_ + 1) % kOut; + return &o.batch[0]; +} + +} /* namespace rad */ diff --git a/core/sched/batch.h b/core/sched/batch.h new file mode 100644 index 00000000..d9b7633d --- /dev/null +++ b/core/sched/batch.h @@ -0,0 +1,385 @@ +/* batch.h -- the step batch, built ONCE PER STEP BY THE CORE and shared by every layer and every + * KV group (spec §8). + * + * vLLM builds this per KV-cache group, per layer, in Python, and that shape is what this file + * exists to avoid: a model whose linear-attention layers fall into several KV-cache groups runs + * the metadata builder once per group, and every run after the first produces values identical to + * it -- dozens of tiny dispatches a step for numbers already computed, and host time on the step + * path is time the GPU spends idle. + * + * So: one build, one owner, every consumer reads the same buffers. + * + * Everything here comes out of pools sized at max_tok / max_seqs at init. Nothing on this path + * allocates. Staging is PINNED HOST memory crossing in one async copy a rank, out of a RING so + * that a build is never written while an earlier build's copy is still reading it -- the cost of + * getting that wrong is a torn block table, which shows up as a sequence reading another + * sequence's KV and reads as a model quality problem -- and so that the host can stage several + * passes ahead of the card without waiting for any of them. + */ +#pragma once +#include "advance.h" +#include "device/device.h" +#include "geometry.h" +#include "mem_iface.h" +#include "metrics.h" + +namespace rad { + +/* One sequence's participation in one step. The scheduler fills these; the builder turns them + * into device arrays and touches nothing else. */ +struct StepEntry { + const Request* req = nullptr; + uint64_t seq = 0; /* the KV manager's key -- the request id */ + int32_t slot = -1; /* scheduler slot: where the scheduler keeps the request */ + int32_t card = -1; /* the card's StepSlot index, [0, max_seqs): the sequence + * identity in this batch (SchedReq::card) */ + int32_t n_tokens = 0; /* query length this step */ + int32_t ctx_len = 0; /* computed tokens BEFORE this step -- the first token's position */ + int32_t n_spec = 0; /* draft tokens included in n_tokens (decode only) */ + /* HOW MANY TOKENS THE PREVIOUS STEP COMMITTED, and it is ONE-BASED: the token that step was + * given plus however many of its drafts survived. Both linear kernels read it that way -- + * gdn_conv_update reads its rolling window at `num_accepted - 1` and gdn_recurrent_update + * takes the state the (num_accepted)th token left -- so 1 is the ordinary decode step that + * drafted nothing, which is exactly what they assume when the operand is absent. Zero is not + * a value either of them can read; the scheduler's own `SchedReq::n_accepted` counts DRAFTS, + * which is one less. */ + int32_t n_accepted = 1; + int32_t conv_cursor = 0; /* read offset inside the rolling conv window (§10) */ + int32_t ckpt_tok = -1; /* token index WITHIN this entry to snapshot at, or -1 */ + int32_t ckpt_slot = -1; + /* THE SNAPSHOT THIS ENTRY RESUMES FROM, or -1. Set on the first step after a prefix hit and + * never again: the recurrent half of a hit is carried by this and by nothing else, because + * the adopted blocks describe the attention layers only. */ + int32_t ckpt_restore = -1; + const int32_t* draft = nullptr; /* the drafter's proposal, appended after the committed tail */ + int32_t n_draft = 0; + /* WHICH LOGITS ROW OF THE STEP JUST RUN holds the hidden state this entry continues from, + * or -1 for the ordinary rule. It exists for the MTP drafter's history pass: the trunk step + * produced 1 + n_spec rows for a verifying sequence, and the head gathers the run of them + * starting here. Filled into `out_ids`, so the head's gather picks them out of the same + * buffer. + * + * A pass that gathers its OWN output names rows of itself through the same field -- the + * DFlash2 query pass does, because the rows it wants logits for are the mask positions of the + * block it just ran. Which buffer out_ids indexes is the architecture block's business; this + * is only the list. */ + int32_t hidden_row = -1; + /* HOW MANY ROWS FROM `hidden_row`, or 0 for the rule that predates it: one a token. The MTP + * history pass wants exactly its n_tokens and says 0; the DFlash2 query pass runs `block` + * tokens and wants the block-1 mask rows, so it says block-1 and starts one row in. */ + int32_t hidden_n = 0; + /* THIS ENTRY'S LAST ROW IS DRAFT ROUND 1 (RadBatch::draft_out_ids): set on a history-pass + * entry whose sequence drafts, whose rows end with the position round 1 continues from. */ + bool draft_out = false; + bool is_prefill = false; + bool produces_token = false; /* this entry's last token is the sequence's last */ + /* A DEVICE ROW: the card fills its tokens, positions, rollback count and slots from the slot's + * StepSlot before the pass runs (advance.h), and what the host staged for them is replaced. + * `ctx_len` is then an upper bound, which is what the host-side ceilings read. The other three + * are advance.h's row descriptor: the verify step's token row of the row's first verified + * position, its first sampled row (-1 for none), and the mode's own number. A verify step's + * entries always carry them, for its acceptance. */ + bool dev = false; + int32_t dev_tok = 0; + int32_t dev_out = -1; + int32_t dev_aux = 0; +}; + +struct StepPlan { + std::vector e; + int64_t n_tok = 0; + int phase = RAD_PHASE_DECODE; + /* THE DRAFT PASS, straight through to RadBatch::draft_pass. 0 is a trunk step; r > 0 runs + * only the draft head, r < 0 is a history pass. */ + int draft_pass = 0; + /* HOW FAR AHEAD OF ITS POSITION A ROW READS ITS TOKEN. The MTP head pairs the trunk's hidden + * state at index i with the embedding of the token at i + 1 (rad_block_mtp_fp8.h), so its + * passes say 1 and the shift is applied once, here, rather than in a kernel. It is NOT a + * property of "being a draft pass": DFlash2's query block embeds the token at its own + * position -- the anchor at the row that holds it and a mask everywhere after -- and says 0. + * Deriving it from `draft_pass` instead feeds such a drafter the token one past its anchor. */ + int tok_shift = 0; + int n_spec = 0; /* the batch-wide speculative window */ + bool spec_is_tree = false; /* a tree drafter fills spec_parent; a chain leaves it null */ + /* THE SPLIT, for a block that issues over each half separately. Sorted above, so the decode + * rows are sequences [0, n_seq_decode) and the prefill chunks are the rest. */ + int64_t n_seq_decode = 0; + int64_t n_tok_decode = 0; + int32_t max_q_len = 0; + int32_t max_ctx_len = 0; + + void reset() { + e.clear(); + n_tok = 0; phase = RAD_PHASE_DECODE; draft_pass = 0; tok_shift = 0; n_spec = 0; + spec_is_tree = false; max_q_len = 0; max_ctx_len = 0; n_seq_decode = 0; n_tok_decode = 0; + } +}; + +/* ------------------------------------------------------------------ the builder */ +class BatchBuilder { +public: + /* `prog` is non-const because derived buffers are written into the arena, and the arena + * pointer lands in BufferInfo::ptr after the buffer plan runs. */ + /* What the builder needs about one rank: which card its slab lives on, which stream its + * upload rides, and which Program holds the arena a derived buffer is copied into. */ + struct RankIO { + int device = 0; + RadStream stream = nullptr; + Program* prog = nullptr; + }; + + int init(Program& prog, const Config& cfg, const ChunkGeometry& geo, + const KVGeom& kvg, const std::vector& ranks); + void fini(); + + /* Build the batch for this step. The returned pointer is stable until the kOut-th next call + * and is the pointer the rank threads share -- because the ranks share an address space, the + * batch is shared by pointer rather than broadcast (spec §1). Null on a device failure, which + * is fatal for the step. */ + const RadBatch* build(const StepPlan& plan, const IKVManager& kv, int step); + + /* The batch the LAST build produced for one rank. Same contents as build()'s return + * except for the device pointers, which name that rank's staging slab. */ + const RadBatch* batch_for(int rank) const; + + /* THE ADVANCE'S VIEW OF THE LAST BUILD on one rank: the slab and every offset in it. The mode, + * the round, the slot state and the inputs are the caller's (advance.h). */ + AdvanceArgs advance_args(int rank) const; + + /* THE LONGEST SEQUENCE A BATCH CAN DESCRIBE, in tokens: what the block-table rows were sized + * for at init. A position at or past it has no column to be addressed through. */ + int64_t max_ctx() const { return max_ctx_; } + + /* AN ENCODER PASS (RadBatch::enc): the patches of whole segments of one or more media items, + * staged into every rank's encoder input -- each rank runs the tower on its own card, so none + * waits on another's output. Returns rank 0's batch like build(); batch_for() serves the rest. + * The caller synchronises every rank's stream before the next encoder build, which it has to + * anyway to read the pass's rows back. */ + struct EncoderPart { + const mm::Item* item = nullptr; + int32_t seg0 = 0, n_seg = 0; + }; + const RadBatch* build_encoder(const std::vector& parts, int step); + bool has_encoder() const { return mm_on_; } + int64_t encoder_patches() const { return enc_patches_; } + + +private: + struct Group { + rad_kvgroup g = 0; + int64_t block_size = 0; + int64_t max_blocks = 0; + int32_t* h_slot = nullptr; int32_t* d_slot = nullptr; + /* The group's block tables on the card: a fixed place in the table region, `bt_fix` + * int32 past its start, max_seqs rows of this build's pitch. They have no host twin -- a + * build stages only what changed. */ + int64_t bt_fix = 0; + int32_t* d_bt = nullptr; + int32_t* h_used = nullptr; int32_t* d_used = nullptr; + int32_t* h_sidx = nullptr; int32_t* d_sidx = nullptr; + int64_t sidx_pitch = 1; /* columns per sequence in h_sidx/d_sidx */ + }; + + /* THE LAYOUT OF A BUILD: every array's place on the card and in host staging, at the same + * offset in both, so that one copy moves a whole build. + * + * THE DEVICE SLAB IS ONE PER RANK AND IS NEVER DOUBLE BUFFERED. A build's upload and every + * kernel that reads it are on that rank's compute stream, so the next build's upload is + * ordered behind the kernels of the last one by the queue itself: nothing on the card can + * read a slab another build is writing. What does need more than one copy is the HOST side, + * which the upload reads when the stream reaches it and not when it is issued -- and the host + * may be several passes ahead of the card. That staging is carved out of a ring (see Ring), + * so any number of builds can be in flight and a build only waits when the ring is full. + * + * `h_*` are re-carved for every build at its place in the ring; `d_*` are rank 0's slab and + * never move. */ + struct Set { + int64_t host_bytes = 0, dev_bytes = 0; + /* THE BLOCK TABLES ARE NOT PART OF THE FIXED LAYOUT'S COPY. `bt_base` is where they + * start, and everything below it crosses whole every build. On the card the region past + * it is every group's tables at a fixed place; in the host span it is the build's + * PAYLOAD -- the table entries that changed, packed -- followed by the list of ranges + * saying where each run of it lands (see BtMirror). `dev_bytes` is the ALLOCATION, which + * holds every group's worst table. */ + int32_t* bt_h0 = nullptr; int32_t* bt_d0 = nullptr; + int64_t bt_base = 0; + /* ONE DEVICE SLAB PER RANK, and this is not an optimisation. + * + * The batch is built once and shared BY POINTER (spec §1), which is right for the host + * side and wrong for the device side. A single slab on rank 0's card, filled by async + * copies on rank 0's stream and read by every rank's kernels off its own stream, has + * nothing ordering the other ranks' reads after rank 0's copies. A slab per rank makes + * each rank's upload an ordinary same-stream dependency and puts the metadata on the card + * that reads it, instead of behind PCIe. The carve is identical on every rank, so d_* + * below are rank 0's pointers AND the offset basis for the rest. */ + std::vector dev; + + int32_t *h_tok = nullptr, *h_pos = nullptr, *h_cu = nullptr, *h_sid = nullptr; + int32_t *h_q = nullptr, *h_ctx = nullptr, *h_acc = nullptr, *h_parent = nullptr; + int32_t *h_cktok = nullptr, *h_ckslot = nullptr; + int32_t *h_out = nullptr; /* [n_out] which of this step's tokens want logits */ + int32_t *h_dout = nullptr; /* [n_draft_out] a history pass's round-1 rows */ + int32_t *d_tok = nullptr, *d_pos = nullptr, *d_cu = nullptr, *d_sid = nullptr; + int32_t *d_q = nullptr, *d_ctx = nullptr, *d_acc = nullptr, *d_parent = nullptr; + int32_t *d_cktok = nullptr, *d_ckslot = nullptr; + int32_t *d_out = nullptr; + int32_t *d_dout = nullptr; + /* The advance's inputs (advance.h): [4][max_seqs] row descriptors, [groups][max_seqs] + * first positions, and one AdvGroup a group. */ + int32_t *h_rows = nullptr, *d_rows = nullptr; + int32_t *h_first = nullptr, *d_first = nullptr; + AdvGroup *h_grp = nullptr, *d_grp = nullptr; + + char* h_derived = nullptr; /* derivation staging, byte-addressed */ + /* [3][n_tok] rotary positions and [n_tok] encoder-row targets (RadBatch::rope_pos, + * mm_rows): carved only when the program declared an encoder, empty otherwise. */ + int32_t *h_rope = nullptr, *d_rope = nullptr; + int32_t *h_mmrow = nullptr, *d_mmrow = nullptr; + /* [n_kv_groups][max_seqs]: EVERY conv group's state slot per sequence, not just one, since + * a model may have more than one conv group -- see init(). */ + int32_t* h_convslot = nullptr; + + std::vector groups; + }; + + /* THE HOST STAGING RING. A build takes the bytes it will upload -- the fixed prefix and the + * block-table rows it fills -- as one contiguous span, fills it, and records an event per rank + * behind the upload. A span is reusable once every rank's upload of it has run, which is what + * `reserve` waits for when the ring is full; at steady state it never is, because a decode + * build's span is a small fraction of the ring. */ + struct Flight { + int64_t begin = 0, end = 0; + int ev = -1; /* row of ev_ holding one event per rank */ + }; + static constexpr int kFlights = 64; + struct Ring { + char* host = nullptr; + int64_t bytes = 0; + int64_t head = 0; /* where the next span starts */ + Flight fifo[kFlights]; /* live flights, oldest at `first`, `live` of them */ + int first = 0, live = 0; + }; + + /* What a build hands the ranks: the ABI views and the batch, ONE PER RANK, since they differ + * only in the device pointers. kOut of them so a batch stays valid while later ones are + * built: a step's own batch is read after its draft passes and the next step's batch are. */ + static constexpr int kOut = RAD_SCHED_MAX_SPEC + 4; + struct Out { + std::vector> kv; + std::vector batch; + }; + + struct Derived { + rad_buf handle = 0; + /* WHICH conv group this derivation is about, or -1 for none. From RadBufDecl::kv, or the + * only conv group when the plugin left that 0 and there IS only one. */ + int32_t conv_grp = -1; + const char* name = nullptr; + int fn_index = -1; + int64_t off = 0; /* byte offset into a set's derived region */ + int64_t capacity = 0; /* elements */ + int64_t produced = 0; + BufferInfo* buf = nullptr; + }; + + Program* prog_ = nullptr; + Config cfg_{}; + ChunkGeometry geo_{}; + KVGeom kvgeom_{}; + std::vector ranks_; + + int64_t max_tok_ = 0, max_seqs_ = 0, max_ctx_ = 0; + /* Per KV GROUP, indexed by group, and 0 for a group that is not RAD_KV_CONV. + * + * THIS AND `h_convslot` FEED `DeriveInput` AND NOTHING ELSE. A conv KERNEL reads its slot from + * RadKVGroupBatch::state_index, which is per group. What reads these two is the + * `conv_state_index` DERIVATION, which no architecture plugin currently calls -- + * rad_block_gdn_fp8.h takes `cv->state_index` straight off the group batch. Keeping them per + * group is what makes the derivation correct, and usable, for a model with a second conv + * group. */ + std::vector conv_window_; + int32_t conv_group_ = -1; /* the ONLY conv group, when there is exactly one; else -1 */ + int32_t n_conv_ = 0; + + Set set_; + Ring ring_; + /* [flight][rank]: the events a flight records behind its uploads, reused as flights retire. */ + std::vector> ev_; + std::vector ev_free_; + Out out_[kOut]; + int out_next_ = 0; + int out_last_ = -1; /* the Out build() just filled */ + /* Per group, this build's block-table pitch: sized before the span is reserved. */ + std::vector pitch_; + + /* WHAT EVERY RANK'S SLAB HOLDS IN ITS BLOCK-TABLE REGION, so a build stages only what changed. + * + * A sequence's table is its whole context in blocks, thousands of entries a group at long + * context, and restaging every row whole every build cost the scheduler time in proportion + * to context times sequences times the several builds of a speculative step -- and the card + * as much in upload. But the slab is one per rank and outlives the build, the uploads reach it + * in the order the builds were made, and a group's tables have a fixed place in it, so it + * already holds the last build's rows. A row that still holds the same sequence at the same + * pitch is restaged from the lowest entry the manager changed (take_table_changes) to the end + * of what it or the card holds; any other row is restaged whole. + * + * `len[i]` is how many entries of row i are the table of `seq[i]`, and the rest of the row is + * -1, which is what a whole restage leaves; -1 in `len` is "unknown". A sequence is current in + * at most one row: its change marks are consumed where it is written, so a copy of it left + * in another row goes unknown. A layout change -- the group's pitch -- and a build that fails + * after taking marks make every row unknown. */ + struct BtMirror { + int64_t pitch = -1; + std::vector seq; + std::vector len; + }; + std::vector bt_mirror_; + /* This build's upload ranges, host-side, until build() writes them behind the payload. */ + std::vector ranges_; + int64_t pay_words_ = 0; /* the payload build_groups wrote, in int32 */ + void forget_tables(); + int64_t last_n_seq_ = 0; + + int64_t derived_bytes_ = 0; + std::vector derived_; + + /* THE MEDIA STAGING, allocated only when the program declared an encoder (mm_on_). + * + * The encoder rows a pass overwrites its embeddings with are NOT in the slab: the slab's + * prefix crosses whole on every build, and max_tok rows of an embedding are megabytes a decode + * step would copy for nothing. They have a device region of their own on every rank, filled + * only by a build that carries them -- rank 0 from pinned staging, every other rank with zeros + * (RadBatch::mm_embd says why). The staging is refilled only once the last upload out of it + * has run, which `mm_ev_` records. */ + bool mm_on_ = false; + int64_t n_embd_ = 0; + std::vector mm_dev_; + uint16_t* mm_host_ = nullptr; + RadEvent mm_ev_ = nullptr; + bool mm_ev_live_ = false; + /* ...and the encoder's inputs: patches, their coordinates and the segment boundaries, the + * largest pass the plugin declared. One copy a rank, since each runs the tower itself. */ + int64_t enc_patches_ = 0, enc_dim_ = 0, enc_segs_ = 0; + std::vector enc_pix_dev_, enc_coord_dev_, enc_cu_dev_; + uint16_t* enc_pix_host_ = nullptr; + int32_t* enc_coord_host_ = nullptr; + int32_t* enc_cu_host_ = nullptr; + int64_t last_n_tok_ = 0; + int alloc_media(); + void free_media(); + /* The encoder rows of one entry: the media tokens among its positions, their rows copied into + * the staging from `n_rows` on. Returns how many it added, or negative. */ + int64_t stage_mm_rows(const StepEntry& e, int64_t k, int64_t shift, int64_t n_rows, + int32_t* rows); + + int alloc_set(Set& s, const std::vector& groups); + void free_set(Set& s); + /* Point every h_* at host staging based at `base`, and every d_* at rank 0's slab. */ + void carve(Set& s, char* base); + /* A span of `need` bytes of the ring, waiting for old uploads when it is full. */ + int reserve(int64_t need, int64_t* off); + int run_derivations(const StepPlan& plan, Set& s); + int build_groups(const StepPlan& plan, const IKVManager& kv, Set& s, Out& o); +}; + +} /* namespace rad */ diff --git a/core/sched/derive.cpp b/core/sched/derive.cpp new file mode 100644 index 00000000..1cf0c09d --- /dev/null +++ b/core/sched/derive.cpp @@ -0,0 +1,117 @@ +/* derive.cpp -- the derivation table. One row per name; adding one is adding a row. + */ +#include "derive.h" + +#include + +namespace rad { + +/* ------------------------------------------------------------------ seq_start_index */ +/* [n_seq+1] -- where each sequence's tokens begin in this step's flat token array, and the total. + * This is cu_seqlens, exposed as a declared buffer so a plugin can name it as an operand instead + * of reaching into RadBatch. It costs a copy of n_seq+1 int32 and it means an op's operand list + * says what it reads. */ +static int d_seq_start_index(const DeriveInput& in, int32_t* out, int64_t cap, int64_t* n_out) { + int64_t n = in.n_seq + 1; + if (n > cap) return RAD_E_FULL; + std::memcpy(out, in.cu_seqlens, (size_t)n * sizeof(int32_t)); + *n_out = n; + return RAD_OK; +} + +/* ------------------------------------------------------------------ conv_state_index */ +/* [n_seq] -- the entry of the conv state cache this sequence's update reads from. + * + * libr4d treats the conv state as a rolling window of `width-1 + num_spec` entries and reads at + * the slot the last accepted token left, so a speculative rejection is a change of READ OFFSET + * rather than a recompute (spec §10). The window base is the sequence's state slot; the offset is + * the cursor the scheduler advances by 1 + num_accepted per verify. Both numbers live in the + * request's bookkeeping, which is why this is a scheduler-side derivation and not a kernel one. */ +static int d_conv_state_index(const DeriveInput& in, int32_t* out, int64_t cap, int64_t* n_out) { + if (in.n_seq > cap) return RAD_E_FULL; + if (!in.conv_slot) return RAD_E_STATE; + const int32_t W = in.conv_window > 0 ? in.conv_window : 1; + for (int64_t i = 0; i < in.n_seq; ++i) { + const StepEntry& e = in.plan->e[(size_t)i]; + int32_t slot = in.conv_slot[i]; + out[i] = slot < 0 ? -1 : (int32_t)(slot * W + (e.conv_cursor % W)); + } + *n_out = in.n_seq; + return RAD_OK; +} + +/* ------------------------------------------------------- the linear-state chunk walk */ +/* The chunked linear-attention kernels tile a sequence in fixed chunks measured from the + * sequence's own origin, not from the start of the step's token array. In a varlen batch those two + * disagree, so the boundaries have to be derived: a chunk may never cross a sequence boundary, and + * a chunk boundary must land on an absolute multiple of the chunk length or the recurrent state + * carried into the next chunk is the state of a partial tile. + * + * The scheduler already guarantees a prefill chunk ends on a multiple of the quantum (geometry.h), + * so in a pure prefill step the interior boundaries are exactly the multiples; the walk still runs + * because a mixed step's decode rows start at arbitrary positions. */ +template +static int chunk_walk(const DeriveInput& in, int32_t* out, int64_t cap, int64_t* n_out) { + const int64_t C = in.state_chunk > 0 ? in.state_chunk : 1; + int64_t k = 0; + + if (!WantSeq) { + if (cap < 1) return RAD_E_FULL; + out[k++] = 0; + } + for (int64_t i = 0; i < in.n_seq; ++i) { + int64_t b = in.cu_seqlens[i], e = in.cu_seqlens[i + 1]; + if (e <= b) continue; + int64_t p0 = in.positions[b]; + /* First interior boundary: the next absolute multiple of C strictly after p0. */ + int64_t next = ((p0 / C) + 1) * C; + for (int64_t abs = next; abs < p0 + (e - b); abs += C) { + if (k >= cap) return RAD_E_FULL; + out[k++] = WantSeq ? (int32_t)i : (int32_t)(b + (abs - p0)); + } + if (k >= cap) return RAD_E_FULL; + out[k++] = WantSeq ? (int32_t)i : (int32_t)e; + } + *n_out = k; + return RAD_OK; +} + +/* [n_chunks+1] token indices: chunk c covers [out[c], out[c+1]). out[0] is 0 and the last entry is + * n_tok, so the array reads exactly like cu_seqlens does. */ +static int d_state_chunk_bounds(const DeriveInput& in, int32_t* out, int64_t cap, int64_t* n_out) { + return chunk_walk(in, out, cap, n_out); +} + +/* [n_chunks] -- which sequence each chunk belongs to. Recoverable from the bounds by a search + * against cu_seqlens, but the search is per chunk in every layer that wants it, and this is one + * pass shared by all of them. */ +static int d_state_chunk_seq(const DeriveInput& in, int32_t* out, int64_t cap, int64_t* n_out) { + return chunk_walk(in, out, cap, n_out); +} + +/* ------------------------------------------------------------------ the table */ +static const DeriveRow g_rows[] = { + { "seq_start_index", d_seq_start_index, + "[n_seq+1] first token index of each sequence in this step, and the total" }, + { "conv_state_index", d_conv_state_index, + "[n_seq] conv rolling-window entry to read, base slot * window + accepted cursor" }, + { "state_chunk_bounds", d_state_chunk_bounds, + "[n_chunks+1] token indices bounding each linear-state chunk; never crosses a sequence" }, + { "state_chunk_seq", d_state_chunk_seq, + "[n_chunks] the sequence each chunk belongs to" }, +}; + +int derive_index(const char* name) { + if (!name) return -1; + for (int i = 0; i < (int)(sizeof g_rows / sizeof g_rows[0]); ++i) + if (std::strcmp(g_rows[i].name, name) == 0) return i; + return -1; +} + +const DeriveRow* derive_row(int i) { + return (i >= 0 && i < (int)(sizeof g_rows / sizeof g_rows[0])) ? &g_rows[i] : nullptr; +} + +int derive_count() { return (int)(sizeof g_rows / sizeof g_rows[0]); } + +} /* namespace rad */ diff --git a/core/sched/derive.h b/core/sched/derive.h new file mode 100644 index 00000000..50f69655 --- /dev/null +++ b/core/sched/derive.h @@ -0,0 +1,51 @@ +/* derive.h -- per-step metadata the core computes ONCE, by name, into the arena. + * + * An architecture plugin that needs linear-state chunk boundaries or conv-state indices declares + * them at build time as a RAD_BUF_DERIVED buffer and names the derivation. The core computes it + * once per step; it is NOT recomputed per layer, and layers that share a geometry share the buffer. + * + * Sharing like this is what vLLM has no natural place for: it has to establish "same step" through + * a module-level counter, because nothing there is an object that belongs to a step, and a marker + * held per metadata-builder instead removes nothing -- every KV-cache group is still the first one + * its own builder sees. Here the step batch IS that place. + * + * Adding a derivation is a row in the table in derive.cpp. The core is not the thing you edit to + * add a kernel; it is the thing you edit to add a shape of per-step metadata, and that list is + * short and shared. + */ +#pragma once +#include "batch.h" + +namespace rad { + +/* Everything a derivation may read. All host memory, already staged for this step: a derivation + * that needed a device read would be a synchronisation on the step path. */ +struct DeriveInput { + const StepPlan* plan = nullptr; + const int32_t* cu_seqlens = nullptr; /* [n_seq+1] */ + const int32_t* positions = nullptr; /* [n_tok] absolute position per token */ + const int32_t* conv_slot = nullptr; /* [n_seq] the conv group's state slot, -1 if none */ + int64_t n_tok = 0; + int64_t n_seq = 0; + int64_t state_chunk = 1; /* the resolved linear-state chunk length */ + int32_t conv_window = 1; /* conv_width - 1 + max_spec */ +}; + +/* Writes at most `cap` int32 elements to `out` and reports how many. Returns RAD_OK or negative; + * negative aborts the step, because a plugin issuing an op against a half-filled derived buffer is + * the silent-wrong-output failure this engine exists to remove. */ +typedef int (*DeriveFn)(const DeriveInput& in, int32_t* out, int64_t cap, int64_t* n_out); + +struct DeriveRow { + const char* name; + DeriveFn fn; + const char* doc; +}; + +/* -1 if the name is not a derivation the core knows. Reported at declare, by name, with the known + * list -- the same treatment a misspelled op gets (spec §2.3). */ +int derive_index(const char* name); +const DeriveRow* derive_row(int index); +int derive_count(); + +} /* namespace rad */ diff --git a/core/sched/draft.cpp b/core/sched/draft.cpp new file mode 100644 index 00000000..4dbe8b94 --- /dev/null +++ b/core/sched/draft.cpp @@ -0,0 +1,39 @@ +/* draft.cpp -- the static draft-depth policy. See draft.h for why it is static. + */ +#include "draft.h" + +namespace rad { + +int DraftController::configure(const Params& p) { + if (p.max_depth < 0 || p.max_depth > RAD_SCHED_MAX_SPEC) { + RAD_ERR("draft depth %d is outside 0..%d -- the verify kernel band is %d query rows", + p.max_depth, RAD_SCHED_MAX_SPEC, RAD_SCHED_MAX_SPEC); + return RAD_E_INVAL; + } + p_ = p; + tot_drafted_ = tot_accepted_ = 0; + for (int j = 0; j < RAD_SCHED_MAX_SPEC; ++j) { reach_[j] = 0; hit_[j] = 0; } + seen_ = 0; + return RAD_OK; +} + +void DraftController::observe(int drafted, int accepted) { + if (drafted <= 0) return; + if (drafted > RAD_SCHED_MAX_SPEC) drafted = RAD_SCHED_MAX_SPEC; + if (accepted < 0) accepted = 0; + if (accepted > drafted) accepted = drafted; + tot_drafted_ += drafted; + tot_accepted_ += accepted; + + /* Position j was EVALUATED only if every position before it was accepted, so this verify + * produces exactly: 0..accepted-1 evaluated and accepted, and -- when the prefix was not the + * whole draft -- position `accepted` evaluated and rejected. Nothing past that was reached. */ + const int last = accepted < drafted ? accepted : drafted - 1; + for (int j = 0; j <= last; ++j) { + ++reach_[j]; + if (j < accepted) ++hit_[j]; + } + if (drafted > seen_) seen_ = drafted; +} + +} /* namespace rad */ diff --git a/core/sched/draft.h b/core/sched/draft.h new file mode 100644 index 00000000..6ca63c82 --- /dev/null +++ b/core/sched/draft.h @@ -0,0 +1,81 @@ +/* draft.h -- the speculative draft-depth controller. + * + * IT IS STATIC. The depth is `--num-speculative-tokens` and nothing moves it. + * + * No dynamic policy sits here, and the reason is structural rather than a tuning failure. The + * dynamic policy this engine is otherwise modelled on -- a confidence-product gate against a + * decayed per-position acceptance estimate, plus a batch-size ceiling schedule -- gates on the + * DRAFTER's own top-1 confidences, per slot, on device, after the drafter has run. The scheduler + * decides the depth BEFORE the drafter runs and cannot see them; the only substitute available + * here is measured acceptance, which is the right quantity in expectation but arrives one step + * late and pooled across sequences. Against a draft head whose cost is nearly flat in depth (one + * extra verify row on a step that is weight-bound, not compute-bound) that estimate has nothing to + * buy: the best depth is a property of the model pair, it is known before the serve starts, and it + * is a flag. A controller that can only pick a worse depth than the constant contributes only the + * risk that it picks one. + * + * What survives is the accounting, because the acceptance rate is a reported metric (spec §14) + * and because a verify that accepts nothing has to be visible. + */ +#pragma once +#include "rad_core.h" + +namespace rad { + +/* libr4d's decode kernel serves up to 64 query rows precisely because a verify step falls in that + * band (spec §10), so 64 is the largest window any batch can carry. */ +enum { RAD_SCHED_MAX_SPEC = 64 }; + +class DraftController { +public: + struct Params { + int max_depth = 0; /* the deployment's window; 0 disables speculation entirely */ + }; + + int configure(const Params& p); + const Params& params() const { return p_; } + + /* The draft depth for the next step. 0 means "do not speculate". Constant by construction. */ + int next_depth() const { return p_.max_depth; } + + /* One verify's outcome: `drafted` tokens were proposed and a prefix of `accepted` of them was + * taken. Feeds the reported metrics and nothing else. */ + void observe(int drafted, int accepted); + + /* Metrics (spec §14). Cumulative and exact. */ + int64_t drafted() const { return tot_drafted_; } + int64_t accepted() const { return tot_accepted_; } + float acceptance() const { + return tot_drafted_ ? (float)((double)tot_accepted_ / (double)tot_drafted_) : 0.0f; + } + + /* PER-POSITION ACCEPTANCE, and it is a diagnostic rather than a policy input. + * + * The pooled ratio above cannot tell a drafter that decays from one that falls off a cliff, + * and the difference is the difference between "this is what the head is worth" and "round + * three is broken". A drafter whose accepted-tokens-per-step stops rising past some depth has + * a hazard that goes to zero there; pooled over the whole window that reads as a uniformly + * mediocre drafter, which is a different diagnosis and a different fix. + * + * `reached` is "every earlier position was accepted, so this one was evaluated"; `hits` is + * "and it was accepted too". Their ratio is the conditional hazard. A position the draft + * never reached is charged nothing, which is why a rejection at position 0 does not libel + * every position behind it. */ + int64_t reached(int j) const { + return (j >= 0 && j < RAD_SCHED_MAX_SPEC) ? reach_[j] : 0; + } + int64_t hits(int j) const { + return (j >= 0 && j < RAD_SCHED_MAX_SPEC) ? hit_[j] : 0; + } + /* The deepest position any draft has ever reached; how much of the two arrays is meaningful. */ + int depth_seen() const { return seen_; } + +private: + Params p_; + int64_t tot_drafted_ = 0, tot_accepted_ = 0; + int64_t reach_[RAD_SCHED_MAX_SPEC] = {}; + int64_t hit_ [RAD_SCHED_MAX_SPEC] = {}; + int seen_ = 0; +}; + +} /* namespace rad */ diff --git a/core/sched/geometry.cpp b/core/sched/geometry.cpp new file mode 100644 index 00000000..e686c19b --- /dev/null +++ b/core/sched/geometry.cpp @@ -0,0 +1,164 @@ +/* geometry.cpp -- reconciling the linear-state chunk geometry with the attention block size. + * See geometry.h for why this is computed and not configured. + */ +#include "geometry.h" + +#include + +namespace rad { + +static int64_t gcd64(int64_t a, int64_t b) { + while (b) { int64_t t = a % b; a = b; b = t; } + return a < 0 ? -a : a; +} +static int64_t lcm64(int64_t a, int64_t b) { + if (a <= 0) return b; + if (b <= 0) return a; + return a / gcd64(a, b) * b; +} + +/* WHICH PARAMETER OF THIS OP IS ITS SEQUENCE-CHUNK LENGTH, asked of the op's own schema. The + * scheduler must cut its steps on a multiple of it or a linear-state chunk straddles a sequence + * boundary, so this is the one parameter the core reads by MEANING rather than carrying opaquely. + * + * The schema names it (RAD_PROLE_SEQ_CHUNK), so the core holds no vocabulary of its own. Matching + * a list of likely parameter spellings here instead would silently miss any op that spells it + * differently, and a missed contributor is a quantum that does not divide the kernel's tile. */ +static const char* chunk_key_of(const RadOpSchema* s) { + if (!s) return nullptr; + for (int i = 0; i < s->n_params; ++i) + if (s->params[i].role == RAD_PROLE_SEQ_CHUNK) return s->params[i].key; + return nullptr; +} + +/* One contributor, appended to the explanation. Kept to a line each so the refusal prints as a + * short list and not a wall. */ +static void note(std::string& why, const char* what, int64_t v, const char* from) { + if (!why.empty()) why += "; "; + why += fmt("%s=%lld from %s", what, (long long)v, from); +} + +int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry* out) { + if (!out) return RAD_E_INVAL; + ChunkGeometry g; + + /* ---------------------------------------------------------------- attention block size */ + /* One lcm across every paged group. In practice every paged group on a given kernel set has + * the same block size -- libr4d's is 16 for all of them -- but a hybrid model with a + * sliding-window group served by a different kernel is exactly the case §7.2 is written for, + * and lcm is the answer that is right for both. */ + bool has_linear = false; + for (const KVGroupInfo& kg : prog.kv_groups) { + if (kg.decl.kind == RAD_KV_FULL || kg.decl.kind == RAD_KV_WINDOW) { + if (kg.block_size > 0) { + g.attn_block = lcm64(g.attn_block, kg.block_size); + note(g.why, "attn_block", kg.block_size, kg.name.c_str()); + } + } else { + has_linear = true; + } + } + + /* ---------------------------------------------------------------- linear-state chunk */ + /* Two sources, both already resolved: what the plugin declared the op with, and what the + * kernel that won selection constrains. The first is the model's statement, the second is the + * kernel's, and a chunk that is a multiple of both satisfies both. */ + for (const OpInfo& op : prog.ops) { + const char* ckey = chunk_key_of(op.schema); + if (!ckey) continue; + for (const Band& b : op.bands) { + for (int d = 0; d < RAD_N_DOMAINS; ++d) { + const Resolved& r = b.dom[d]; + if (!r) continue; + + long long v = 0; + if (r.geom.get_i(ckey, &v) && v > 0) { + g.state_chunk = lcm64(g.state_chunk, (int64_t)v); + note(g.why, ckey, v, op.op.c_str()); + } + + const RadKernelInfo* ki = r.row ? r.row->info : nullptr; + if (!ki) continue; + for (int i = 0; i < ki->n_constraints; ++i) { + const RadConstraint& c = ki->constraints[i]; + if (!c.key || std::strcmp(c.key, ckey) != 0 || c.ival <= 0) continue; + switch (c.op) { + /* DIV and EQ are both "a legal chunk is a multiple of this". GE is folded + * in the same way rather than as a separate floor: a multiple of N is + * >= N, so one number carries both facts and the arithmetic stays lcm. */ + case RAD_C_DIV: + case RAD_C_EQ: + case RAD_C_GE: + g.state_chunk = lcm64(g.state_chunk, (int64_t)c.ival); + note(g.why, c.key, c.ival, ki->name); + break; + case RAD_C_LE: + g.max_chunk = g.max_chunk ? (g.max_chunk < c.ival ? g.max_chunk + : (int64_t)c.ival) + : (int64_t)c.ival; + break; + default: break; + } + } + } + } + } + + /* ---------------------------------------------------------------- reconcile */ + g.quantum = lcm64(g.attn_block, g.state_chunk); + if (g.quantum < 1) g.quantum = 1; + + if (g.max_chunk > 0 && g.quantum > g.max_chunk) { + /* Two kernels that cannot both be fed. Naming it is the whole value: the alternative is a + * chunk that is legal for one of them and silently wrong for the other. */ + out->why = fmt("chunk quantum %lld exceeds the %lld a resolved kernel accepts (%s)", + (long long)g.quantum, (long long)g.max_chunk, g.why.c_str()); + out->quantum = g.quantum; + out->min_max_tok = g.quantum; + return RAD_E_SHAPE; + } + + /* The checkpoint interval is the operator's number rounded up to a legal chunk length, so that + * "split at the interval" is always also "split at a quantum". Rounding UP rather than down + * because down can reach zero and because a longer interval costs retention, not correctness. + * + * No linear state means no checkpoints: the interval is a property of a state kind that this + * model does not have, and pretending otherwise would split chunks for nothing. */ + if (has_linear && cfg.checkpoint_interval > 0) + g.checkpoint_interval = align_up(cfg.checkpoint_interval, g.quantum); + else + g.checkpoint_interval = 0; + + /* One full quantum has to fit in one step. Below that, every chunk is short, no chunk ever + * ends on a boundary, and the checkpoint lands wherever the step happened to end -- which is + * precisely the vLLM failure §7.3 exists to remove. Refusing is the honest response. */ + g.min_max_tok = g.quantum; + + *out = g; + + if (cfg.max_tok < g.min_max_tok) { + RAD_ERR("--max-num-batched-tokens is %lld but this model's chunk geometry needs at least " + "%lld: %s", (long long)cfg.max_tok, (long long)g.min_max_tok, g.why.c_str()); + RAD_ERR("a smaller budget cannot end a chunk on a linear-state boundary, so every " + "checkpoint would land in request-unique tokens and the linear prefix hit rate " + "would be zero. Refusing rather than serving that."); + return RAD_E_INVAL; + } + + /* AND THE CHUNK AN OPERATOR ACTUALLY GETS, which is not --max-num-batched-tokens whenever the + * checkpoint interval is smaller: `plan_chunk` splits at the interval so a checkpoint is + * always written, and that clamp comes FIRST. Printing only the budget would hide it -- every + * budget above the interval runs the same chunk length, so a sweep over them reads as + * "prefill is flat against the chunk" when nothing about the chunk changed. The clamp itself + * is correct; a budget that silently does nothing is what has to be visible. */ + const int64_t eff = (g.checkpoint_interval > 0 && g.checkpoint_interval < cfg.max_tok) + ? g.checkpoint_interval : cfg.max_tok; + RAD_INFO("chunk geometry: quantum %lld (attn block %lld, state chunk %lld), checkpoint " + "interval %lld, max_tok %lld -> prefill chunks of at most %lld%s", + (long long)g.quantum, (long long)g.attn_block, (long long)g.state_chunk, + (long long)g.checkpoint_interval, (long long)cfg.max_tok, (long long)eff, + eff < cfg.max_tok ? " (the checkpoint interval, not the budget)" : ""); + return RAD_OK; +} + +} /* namespace rad */ diff --git a/core/sched/geometry.h b/core/sched/geometry.h new file mode 100644 index 00000000..77596dfc --- /dev/null +++ b/core/sched/geometry.h @@ -0,0 +1,62 @@ +/* geometry.h -- the chunk geometry, COMPUTED from the resolved kernels rather than documented as + * a minimum an operator has to know. + * + * vLLM makes a hybrid model's operator pass a minimum `--max-num-batched-tokens` by hand, because + * it inflates the attention block size until it matches the mamba page and then asserts the batch + * budget covers it. The constraint is real; the fact that a human has to carry the number is not. + * Here declare has already resolved every kernel, so the constraints that produce it are in hand: + * the attention block size comes off the resolved attention kernel (§7.2) and the linear-state + * chunk length off whichever resolved kernels mark a parameter RAD_PROLE_SEQ_CHUNK, and the + * reconciliation is arithmetic. + * + * If the resolved geometry needs more tokens than the operator budgeted, that is said at startup + * with the number and the engine refuses -- rather than running something subtly wrong, which here + * means chunks that never land on a checkpoint boundary and a linear prefix hit rate of zero. + */ +#pragma once +#include "rad_core.h" + +namespace rad { + +struct ChunkGeometry { + /* The attention block size, reconciled across every paged KV group. Taken from the resolved + * kernel; libr4d's paged attention is compiled for 16 and rejects anything else. */ + int64_t attn_block = 1; + + /* The length a linear-state scan tiles at -- libr4d's gated delta net is the one that has + * one, at 64. Scanned off the constraints of every op whose schema marks a parameter + * RAD_PROLE_SEQ_CHUNK, and off the geometry the architecture plugin declared them with. */ + int64_t state_chunk = 1; + + /* What a NON-FINAL prefill chunk must be a multiple of: lcm(attn_block, state_chunk). A chunk + * that ends here ends on an attention block boundary and on a linear chunk boundary at once, + * so neither kernel is handed a partial tile it has to special-case. */ + int64_t quantum = 1; + + /* The linear-state checkpoint interval (§7.3), rounded UP from the operator's request to a + * multiple of `quantum`, so splitting at an interval is automatically a legal chunk split. + * Zero when the model has no linear state and checkpointing means nothing. */ + int64_t checkpoint_interval = 0; + + /* The smallest --max-num-batched-tokens this geometry can be served with. */ + int64_t min_max_tok = 1; + + /* An upper bound some kernel placed on the chunk length, or 0. Used only to detect a + * contradiction, which is a kernel-set bug worth naming rather than clamping around. */ + int64_t max_chunk = 0; + + /* Every contributor by name, for the startup line and for the refusal. Built once. */ + std::string why; + + bool checkpoints() const { return checkpoint_interval > 0; } +}; + +/* Resolve the geometry from the declared program and the operator's budgets. + * + * Returns RAD_OK, or RAD_E_INVAL when cfg.max_tok cannot serve the geometry -- in which case the + * required number is in out->min_max_tok and the reason in out->why, and the caller is expected to + * print both and stop. Returns RAD_E_SHAPE when two kernels' constraints cannot be satisfied at + * once, which is a kernel-set bug and not an operator one. */ +int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry* out); + +} /* namespace rad */ diff --git a/core/sched/mem_iface.h b/core/sched/mem_iface.h new file mode 100644 index 00000000..b66c8c5d --- /dev/null +++ b/core/sched/mem_iface.h @@ -0,0 +1,410 @@ +/* mem_iface.h -- the seam between core/sched and core/mem. + * + * core/mem owns the concrete `KVManager` and `PrefixCache`. The scheduler binds to the pure-virtual + * mirrors below rather than to those classes directly, for two reasons and neither is abstraction + * for its own sake: + * + * - it lets tests/sched_test.cpp drive the scheduler against a block pool it can make + * arbitrarily small, which is the only way to test admission refusal and preemption at all; + * - it costs one indirect call per SEQUENCE per step (at most max_seqs, a few hundred), not one + * per token, so it is off the part of the step path that is actually hot. + * + * `KVBinding` / `PCBinding` at the bottom adapt the concrete classes and require no change on + * their side. They are templates so that they are only type-checked where the engine instantiates + * them -- so a method core/mem does not provide is a compile error at exactly one line rather + * than a comment nobody reads. + * + * The interface below mirrors core/mem/kv.h and core/mem/prefix.h. + * + * `CacheHit` comes from core/mem/prefix.h and is NOT redefined here. Two identical definitions of + * a struct that crosses a component boundary is an ODR violation that costs nothing today and + * becomes a silent layout mismatch the first time one side adds a field. + */ +#pragma once +#include +#include "mem/prefix.h" +#include "rad_core.h" +#include "mm/processor.h" + +#include + +namespace rad { + +/* ------------------------------------------------------------------ the KV manager */ +/* Keyed by SEQUENCE ID, which is the request id. The manager owns the block tables; Request::blocks + * is not the source of truth and the scheduler does not read it. Two allocators disagreeing about + * what a sequence owns is not a leak, it is the bug where a freed sequence's state slot is handed + * to the next request while the first still reads it. */ +struct IKVManager { + virtual ~IKVManager() = default; + + virtual int add_sequence(uint64_t seq) = 0; + virtual bool has_sequence(uint64_t seq) const = 0; + virtual void free_sequence(uint64_t seq) = 0; + + /* Grow the sequence's mapping to cover `n_tokens` in every group. RAD_E_FULL when a group's + * free list is empty, which is a scheduling signal and not an error: the caller preempts a + * victim and retries. */ + virtual int ensure(uint64_t seq, int64_t n_tokens) = 0; + + /* Adopt blocks a prefix-cache hit found. `n_tokens` must be a whole multiple of the group's + * block size -- a partial block is never shared, because the next token written into it would + * corrupt the cache entry. */ + virtual int adopt(uint64_t seq, int32_t group, const std::vector& blocks, + int64_t n_tokens) = 0; + + /* Free the blocks and mark the sequence for re-prefill. */ + virtual int preempt(uint64_t seq) = 0; + + /* Could a sequence of this length EVER fit, in an empty pool? If not, preempting the whole + * server would not help and the request is failed immediately rather than the engine + * deadlocking on it (spec §17). */ + virtual bool can_ever_fit(int64_t n_tokens) const = 0; + + virtual const std::vector& block_table(uint64_t seq, int32_t group) const = 0; + virtual int32_t state_slot(uint64_t seq, int32_t group) const = 0; + + /* THE WHOLE state_index ROW FOR A SEQUENCE, and how wide it is. One entry, normally: the + * sequence's state. A group whose kernel asked for scratch beside the state names that too, + * and the manager owns the mapping from column to physical slot because it owns the pool -- + * the scheduler stages the row and does not read it. Returns the width written, 0 for a + * paged group. `max` bounds the write. */ + virtual int state_index_row(uint64_t seq, int32_t group, int32_t* out, int max) const = 0; + virtual int64_t state_index_width(int32_t group) const = 0; + + virtual int64_t free_blocks(int32_t group) const = 0; + virtual int64_t total_blocks(int32_t group) const = 0; + /* What anything is HOLDING, as against what may be handed out right now. See + * KVManager::held_blocks: on an elastic pool the two differ by whatever the cache has + * released, and an occupancy figure built from the second reads an idle server as full. */ + virtual int64_t held_blocks(int32_t group) const = 0; + + /* THE SAME POOL IN BYTES. Blocks and tokens are both un-summable across groups -- a stateful + * group has neither, and two paged groups share one token axis -- so bytes are the only + * measure a reader can add up to "how much of the card is the KV cache holding". Asked of the + * manager rather than derived here, because the manager owns the plan that knows whether a + * group is counted in blocks or in states. */ + virtual int64_t pool_bytes(int32_t group) const = 0; + virtual int64_t pool_bytes_used(int32_t group) const = 0; + /* What the carve gave the group, which an elastic pool may have released part of. */ + virtual int64_t pool_bytes_carved(int32_t group) const = 0; + + /* HOW MANY TOKENS ONE BLOCK OF THIS GROUP COVERS, or 0 for a stateful group. The pool's + * capacity in blocks is already here; the live request table wants it in TOKENS, because that + * is the unit a request is measured in and the only one the two can be compared in. */ + virtual int64_t block_tokens(int32_t group) const = 0; + + /* SPECULATIVE REJECTION ROLLBACK (spec §10). A verify writes KV for 1 + n_spec + * positions and the sampler accepts a prefix of them; the sequence's length must come back to + * the accepted position and the blocks past it must go to the free list. `ensure` is monotone + * and cannot express it. + * + * It is a slot-table edit and nothing else -- crucially it does NOT touch the linear or conv + * groups, whose rollback is a change of read offset the kernels perform themselves. Without + * this the pool leaks one block per rejected block-crossing, which is a slow leak and + * therefore the worst kind. */ + virtual int rollback(uint64_t seq, int64_t n_tokens) = 0; + + /* THE ABSOLUTE TOKEN POSITION that block_table(seq, group)[0] covers. Zero for a + * FULL group and non-zero for a WINDOW group, whose blocks below the window are recycled: the + * step batch's slot mapping is `(pos - first_block_pos) / block_size`, and with the offset + * missing every sliding-window sequence writes its KV to the wrong slot the moment it passes + * its window. KVManager::Seq already tracks this privately as `first_block_pos`. */ + virtual int64_t first_block_pos(uint64_t seq, int32_t group) const = 0; + + /* THE ENTRIES OF block_table(seq, group) THAT CHANGED since the previous call: everything + * below the returned index is unchanged, and INT64_MAX says nothing changed. Reading clears + * it, so the batch builder is its one caller: it keeps the device's copy of a table and + * stages only what moved. 0 is always a correct answer -- it restages the whole table. */ + virtual int64_t take_table_changes(uint64_t seq, int32_t group) const = 0; +}; + +/* ------------------------------------------------------------------ the prefix cache */ +struct IPrefixCache { + virtual ~IPrefixCache() = default; + + /* Longest cached prefix, plus the checkpoint covering the linear state for a prefix of it. + * `blocks_out` receives the block ids per cached group, in cached_groups() order, ready for + * IKVManager::adopt. */ + /* GIVE BACK WHATEVER THE TIERS HOLD FOR THIS PROMPT, before the lookup that would otherwise + * stop at it. `Wait` when part of it is still being read off disk: the request is not + * admitted this step -- the ones behind it may be -- and is asked again on the next. Admitting + * it anyway would stop its hit at the first entry not yet read, and the hit length is what + * its prefill is chunked against, so the same prompt would run different shapes depending on + * how far a read had got. + * + * The scheduler calls it and must not know what a tier is: a restore allocates blocks and + * runs a device scatter, so it is the engine's to perform and is installed as a callable + * rather than reached through this header. A failure is not an error here -- it leaves a + * shorter prefix, and a shorter prefix is always safe. */ + enum class Restore { Done, Wait }; + virtual Restore restore(const Request&) { return Restore::Done; } + /* A step's admissions begin: what the last step's lookups handed out has been read. */ + virtual void begin_step() {} + + virtual CacheHit lookup(const Request& r, + std::vector>* blocks_out) const = 0; + virtual const std::vector& cached_groups() const = 0; + + /* PUBLISH what this sequence computed, so the next request sharing the prefix can adopt it. + * Without this the cache is only ever read: every lookup misses, `cached_tokens` is always + * zero, and a chat client re-prefills its whole history on every turn, which for a long + * conversation is seconds a message. `blocks[i]` is the block table of cached_groups()[i], and + * `n_tokens` how many of them are backed. Takes a KV reference on every newly indexed block, + * so it must be called BEFORE the sequence's own blocks are released. */ + virtual int insert(const Request& r, const std::vector>& blocks, + int64_t n_tokens) = 0; + + /* Release the least recently used entries, and with them their KV references. The cache holds + * blocks no live sequence needs, so this is what the scheduler tries BEFORE preempting a + * running request: a cached prefix is a saving, a running request is work already done. */ + virtual int64_t evict(int64_t n_entries) = 0; + + /* FORGET EVERYTHING, wherever it is. Not a loop over evict(): with idle tiers an eviction moves + * an entry whose host copy has landed off the card and keeps it, so a reset built out of + * evictions would leave every such conversation behind. Returns how many entries went. */ + virtual int64_t reset() { + int64_t dropped = 0; + for (int guard = 0; guard < 65536; ++guard) { + const int64_t n = evict(1024); + if (n <= 0) break; + dropped += n; + } + return dropped; + } + + /* HOW MANY ENTRIES THE CACHE HAS THROWN AWAY, which is the leading indicator of the failure + * mode that matters operationally: once the pool is utilised past the reserve the scheduler + * keeps free (a quarter of it), the cache begins evicting prefixes that are about to be + * reused, and an agent's next turn re-prefills its whole context -- turning a cached turn of + * a few seconds into a full prefill of a very long prompt. `prefix_hit_rate` only falls AFTER + * that has happened; this count rises first. */ + virtual int64_t evictions() const = 0; + virtual int64_t ckpt_evictions() const = 0; + + /* WHAT IT IS HOLDING ON ITS OWN RIGHT NOW, in tokens of context, as against the counters + * above which are cumulative. A finished turn's blocks stay held so the next turn can reuse + * them, so on any server serving conversations MOST of a full KV pool is this rather than the + * live sequences -- and with one number for the pool there is no way to see that, which makes + * a working cache indistinguishable from a leak. + * + * ON ITS OWN is the whole of it. A cached block a running sequence is also reading is not + * memory the cache is keeping back from anybody, and counting those would make a single 200K + * request look like a cache refusing to release 200K. */ + virtual int64_t held_tokens() const = 0; + + /* The next position strictly after `pos` at which the scheduler must split a chunk so that a + * checkpoint lands on a boundary. */ + virtual int64_t next_checkpoint_after(int64_t pos) const = 0; + + /* Reserve the snapshot slot the scheduler is about to WRITE. Retention is budgeted (§7.3: + * ~96 MiB a snapshot, so 64 of them is 6 GiB), which makes RAD_E_FULL an ordinary condition + * and not a failure -- the scheduler simply does not write a checkpoint at that boundary and + * the next hit replays from the previous one. */ + virtual int reserve_checkpoint(const Request& r, int64_t pos, int32_t* slot_out) = 0; + + /* The state that reservation named is now IN its slot. A reservation is made when the chunk is + * PLANNED and the state exists only after the step that computes it, so a lookup in between + * would adopt a slot holding the previous tenant's history. Until this is called, the + * reservation is a promise and lookup will not offer it. */ + virtual void commit_checkpoint(const Request& r, int64_t pos) = 0; +}; + +/* ------------------------------------------------------------------ block geometry */ +/* Everything the step batch needs to turn a token position into a KV slot, read off the declared + * program rather than off the manager: block size is KVGroupInfo::block_size, which the build + * component already took from the resolved attention kernel's constraints (§7.2). Duplicating it + * through a second interface would be a second place for it to be wrong. */ +struct KVGeom { + struct G { + int kind = RAD_KV_FULL; + int64_t block_size = 1; + int64_t window = 0; + bool paged = true; + /* Columns in this group's state_index row. The MANAGER decides it -- it depends on what + * the group's kernel wants beside the state -- so KVGeom::of leaves it at 1 and the + * scheduler fills it in from the configured pool. */ + int64_t sidx_width = 1; + }; + std::vector g; + + static KVGeom of(const std::vector& groups) { + KVGeom k; + k.g.reserve(groups.size()); + for (const KVGroupInfo& gi : groups) { + G e; + e.kind = gi.decl.kind; + e.paged = (e.kind == RAD_KV_FULL || e.kind == RAD_KV_WINDOW); + e.block_size = gi.block_size > 0 ? gi.block_size : 1; + e.window = gi.decl.window; + k.g.push_back(e); + } + return k; + } + + /* Flat KV slot for absolute token position `pos`, given the sequence's block table for this + * group and the position its first block covers. */ + int32_t slot(int gi, const std::vector& bt, int64_t first_pos, int64_t pos) const { + const G& e = g[(size_t)gi]; + int64_t bi = (pos - first_pos) / e.block_size; + if (bi < 0 || bi >= (int64_t)bt.size()) return -1; + return (int32_t)(bt[(size_t)bi] * e.block_size + (pos % e.block_size)); + } +}; + +/* ------------------------------------------------------------------ binding the concrete classes */ +/* Templates, so nothing here is type-checked until the engine instantiates it against the real + * classes. That instantiation is where a mismatch with core/mem is reported. */ +template +struct KVBinding final : IKVManager { + KV* m; + explicit KVBinding(KV* k) : m(k) {} + + int add_sequence(uint64_t s) override { return m->add_sequence(s); } + bool has_sequence(uint64_t s) const override { return m->has_sequence(s); } + void free_sequence(uint64_t s) override { m->free_sequence(s); } + int ensure(uint64_t s, int64_t n) override { return m->ensure(s, n); } + int adopt(uint64_t s, int32_t g, const std::vector& b, int64_t n) override { + return m->adopt(s, g, b, n); + } + int preempt(uint64_t s) override { return m->preempt(s); } + bool can_ever_fit(int64_t n) const override { return m->can_ever_fit(n); } + const std::vector& block_table(uint64_t s, int32_t g) const override { + return m->block_table(s, g); + } + int32_t state_slot(uint64_t s, int32_t g) const override { return m->state_slot(s, g); } + int state_index_row(uint64_t s, int32_t g, int32_t* o, int n) const override { + return m->state_index_row(s, g, o, n); + } + int64_t state_index_width(int32_t g) const override { return m->state_index_width(g); } + int64_t free_blocks(int32_t g) const override { return m->free_blocks(g); } + int64_t total_blocks(int32_t g) const override { return m->total_blocks(g); } + int64_t held_blocks(int32_t g) const override { return m->held_blocks(g); } + int64_t pool_bytes(int32_t g) const override { return m->pool_bytes(g); } + int64_t pool_bytes_used(int32_t g) const override { return m->pool_bytes_used(g); } + int64_t pool_bytes_carved(int32_t g) const override { return m->pool_bytes_carved(g); } + int64_t block_tokens(int32_t g) const override { + const KVGroupPlan* p = m->plan(g); + return p && p->paged() ? p->block_size : 0; + } + int rollback(uint64_t s, int64_t n) override { return m->rollback(s, n); } + int64_t first_block_pos(uint64_t s, int32_t g) const override { + return m->first_block_pos(s, g); + } + int64_t take_table_changes(uint64_t s, int32_t g) const override { + return m->take_table_changes(s, g); + } +}; + +/* The prefix cache's own lookup takes tokens and content-hashed multimodal keys rather than a + * Request, because the placeholder ids inside a media run are identical for every picture: hashing + * the ids alone would serve one request another's image. Each run is keyed by its item's content + * key (core/mm, taken over the processed patches) and its segment, so the same picture at the same + * place hits -- and skips the encoder along with the prefill -- and two pictures never alias. */ +inline void media_keys(const Request& r, std::vector* out) { + out->clear(); + if (!r.media) return; + const mm::PromptMedia& pm = *r.media; + for (const mm::RopeLayout::Run& run : pm.rope.runs) { + const mm::Item& it = *pm.items[(size_t)run.item].item; + MMContentKey k; + k.tok_begin = run.tok; + k.tok_end = run.tok + run.n; + k.hash = it.key_hi ^ (it.key_lo * 0x9e3779b97f4a7c15ull) ^ + ((uint64_t)(uint32_t)run.row0 * 0xc2b2ae3d27d4eb4full); + out->push_back(k); + } +} + +template +struct PCBinding final : IPrefixCache { + PC* m; + /* Scratch for a request's media keys, reused so a text request's lookup allocates nothing. */ + mutable std::vector mm_; + explicit PCBinding(PC* p) : m(p) {} + + CacheHit lookup(const Request& r, + std::vector>* out) const override { + media_keys(r, &mm_); + return m->lookup(r.prompt, mm_, out); + } + + /* Installed by the engine when the idle tiers are on; empty otherwise. */ + std::function restore_fn; + Restore restore(const Request& r) override { + return restore_fn ? restore_fn(r) : Restore::Done; + } + void begin_step() override { m->begin_step(); } + const std::vector& cached_groups() const override { return m->cached_groups(); } + + /* prompt ++ output, for the same reason reserve_checkpoint chains both: the next turn of a + * conversation sends the reply back as part of its prompt, so a cache that indexed only the + * prompt would stop hitting at the first assistant token and re-prefill everything after it. */ + int insert(const Request& r, const std::vector>& blocks, + int64_t n_tokens) override { + std::vector toks; + toks.reserve(r.prompt.size() + r.output.size()); + toks.insert(toks.end(), r.prompt.begin(), r.prompt.end()); + toks.insert(toks.end(), r.output.begin(), r.output.end()); + if (n_tokens > (int64_t)toks.size()) n_tokens = (int64_t)toks.size(); + /* r.id is the session, and it is the SAME id reserve_checkpoint keys its snapshots by -- + * so the tiers' session view and the checkpoint index are talking about one thing. */ + media_keys(r, &mm_); + return m->insert(r.id, toks, mm_, blocks, n_tokens); + } + int64_t evict(int64_t n) override { return m->evict_lru(n); } + int64_t reset() override { + const int64_t n = m->size(); + m->clear(); + return n; + } + int64_t evictions() const override { return m->stats().evictions; } + int64_t ckpt_evictions() const override { return m->stats().ckpt_evictions; } + int64_t held_tokens() const override { return m->unshared_tokens(); } + + int64_t next_checkpoint_after(int64_t p) const override { return m->next_checkpoint_after(p); } + int reserve_checkpoint(const Request& r, int64_t pos, int32_t* slot_out) override { + /* The cache keys a snapshot by the CHAINED HASH of the prefix it covers, and the chain is + * built here rather than inside the cache because the cache does not hold the tokens -- + * that is the whole reason this interface passes a Request. It must be the SAME chain + * lookup() walks, or a checkpoint reserved at `pos` and a later hit at `pos` name two + * different entries and the linear cache silently never hits. + * + * The prefix is prompt ++ output: a checkpoint written during decode covers tokens the + * request has generated, and keying it on the prompt alone would alias every continuation + * of the same prompt onto one snapshot -- which is one session's recurrent state served to + * another. Whole blocks only; a partial block is never keyed, because the next token + * written into it would change what the key stands for. */ + return m->reserve_checkpoint(r.id, pos, prefix_hash(r, pos), slot_out); + } + + void commit_checkpoint(const Request& r, int64_t pos) override { + m->commit_checkpoint(prefix_hash(r, pos)); + } + +private: + /* The chain reserve_checkpoint keys on, factored out so commit cannot drift from it: two + * copies of this walk that agreed when written would be two copies that could stop agreeing, + * and the symptom would be a checkpoint that is written and never found. */ + BlockHash prefix_hash(const Request& r, int64_t pos) const { + media_keys(r, &mm_); + const int64_t bs = m->block_size(); + BlockHash h{}; + if (bs <= 0) return h; + const int64_t np = (int64_t)r.prompt.size(), no = (int64_t)r.output.size(); + const int64_t have = np + no; + const int64_t n_blocks = (pos < have ? pos : have) / bs; + std::vector blk((size_t)bs); + for (int64_t b = 0; b < n_blocks; ++b) { + const int64_t base = b * bs; + for (int64_t j = 0; j < bs; ++j) { + const int64_t k = base + j; + blk[(size_t)j] = k < np ? r.prompt[(size_t)k] : r.output[(size_t)(k - np)]; + } + h = chain_block_hash(h, blk.data(), (int32_t)bs, mm_.data(), (int32_t)mm_.size(), base); + } + return h; + } +}; + +} /* namespace rad */ diff --git a/core/sched/metrics.h b/core/sched/metrics.h new file mode 100644 index 00000000..4e31f644 --- /dev/null +++ b/core/sched/metrics.h @@ -0,0 +1,135 @@ +/* metrics.h -- the scheduler's snapshot, for the server's /metrics endpoint (spec §14). + * + * A plain struct of numbers with no strings built and nothing formatted. Formatting belongs to + * whoever is exporting -- Prometheus wants vLLM-compatible names, the live view wants a terminal + * line, and a scheduler that rendered either would have to be edited to add the other. Fixed + * arrays, so a scrape allocates nothing and cannot contend with the step path for the allocator. + */ +#pragma once +#include "rad_core.h" + +namespace rad { + +enum { RAD_SCHED_MAX_KV_GROUPS = 16 }; + +struct SchedMetrics { + int64_t step = 0; + + /* Queue state, instantaneous. */ + int64_t queue_depth = 0; /* requests waiting, including preempted ones */ + int64_t running = 0; + int64_t preempted_waiting = 0; /* of queue_depth, how many are awaiting recompute */ + + /* Cumulative counters. Monotonic, so a scraper can rate() them. */ + int64_t admitted = 0; + int64_t finished = 0; + int64_t failed = 0; + int64_t cancelled = 0; + int64_t preemptions = 0; + int64_t steps = 0; + + /* STEPS BY SHAPE, AND WHAT SPECULATION DID NOT REACH. `steps_mixed` over `steps` says how + * often the load produces a step carrying both a prefill chunk and decode rows; an agentic + * load produces them often enough to be worth measuring. + * + * `decode_rows_unspeculated` counts every decode row that took no draft, whatever the reason + * -- depth 0, a request that may not speculate, a drafter with nothing to propose. Counting + * ROWS rather than any one reason keeps it the answer to "how much of my decode is running + * unspeculated" as the set of reasons changes. Without it the loss is invisible: throughput + * falls and every explanation fits. */ + int64_t steps_prefill = 0; + int64_t steps_mixed = 0; + int64_t steps_decode = 0; + int64_t decode_rows_unspeculated = 0; + /* STEPS ISSUED AHEAD: a step whose forward pass went onto the card behind the step before it, + * before that step committed (Scheduler::step_next). Every other step waits for the host's + * commit and staging with the card idle, so steps_ahead against steps is how much of the run + * kept the card fed through the host's part of it. */ + int64_t steps_ahead = 0; + + /* HOW LONG THE ENGINE SPENT INSIDE A STEP, cumulative nanoseconds, and the decode half of it + * separately. Neither is a derived rate -- they are counters, and that is the point. + * + * A STEP TIME IS NOT WALL TIME OVER A STEP COUNT, and a gauge that computes it that way is + * wrong in two directions at once. An engine that idles between requests -- which is every + * agent, every chat client, every tool loop -- charges the idle gap to the steps around it, + * inflating the step time by however long nothing was running. And a prefill chunk costs an + * order of magnitude more than a decode step, so a load that mixes them averages two + * populations and calls the result the step time. Both faults are invisible without an + * instrument: the number is plausible, it moves with load, and nothing contradicts it. + * + * With these, `step_ns_decode / steps_decode` is a decode step time that needs no window, no + * saturation assumption and no second endpoint. Charged from the scheduler's own + * `step_start_`, which is the same clock `decode_tps` already uses -- so this adds no + * synchronisation and no timing mode (spec §16). */ + int64_t step_ns = 0; + int64_t step_ns_decode = 0; + + /* Per KV group. `name` points into the Program, which outlives any scrape. */ + int n_kv_groups = 0; + struct Group { + const char* name = ""; + int64_t blocks_total = 0; + int64_t blocks_free = 0; + float utilisation = 0.0f; /* 1 - free/total */ + /* Tokens one block covers, 0 for a stateful group. A pool measured in blocks cannot be + * compared with a request measured in tokens, and every reader wants that comparison. */ + int64_t block_tokens = 0; + /* AND THE SAME GROUP IN BYTES, which is the measure that survives being added to the next + * group's. Neither blocks nor tokens does: a stateful group has no token axis, and two + * paged groups share one, so a token of context takes a slot in both and summing them + * reports a pool the card does not have. */ + int64_t bytes_total = 0; + int64_t bytes_used = 0; + /* WHAT IT WAS CARVED TO ADDRESS, as against bytes_total, which is what the card is + * actually holding for it. The two differ by what the elastic pool has released: the + * cache releases the VRAM behind blocks nothing holds, and the difference between these + * two numbers is exactly what it gave back. Equal otherwise. */ + int64_t bytes_carved = 0; + } kv[RAD_SCHED_MAX_KV_GROUPS]; + + /* Prefix caching (§7.3). Attention and linear are reported separately because they hit at + * different granularities and a single number would hide exactly the effect the decoupling + * was for. */ + int64_t prompt_tokens = 0; + int64_t attn_cached_tokens = 0; + int64_t linear_cached_tokens = 0; + float attn_hit_rate = 0.0f; + /* Cumulative, from the prefix cache itself. Rising evictions under a steady workload + * mean the pool cannot hold the working set and turn-2 latency is about to collapse. */ + int64_t prefix_evictions = 0; + int64_t prefix_ckpt_evictions = 0; + /* WHAT THE CACHE IS HOLDING ON ITS OWN NOW, in tokens of context: the part of the pool that + * an eviction would actually free, because no live sequence is reading it. The pool figure + * above counts a held block whoever holds it, and on a server serving conversations most of + * it is this rather than the running requests -- so without it a working cache and a leak are + * the same picture. Blocks shared with a running sequence are NOT in it; counting them would + * make one long request read as a cache that would not release its context. Same token axis + * as the paged groups, so it is comparable with kv_tokens_used. */ + int64_t prefix_held_tokens = 0; + float linear_hit_rate = 0.0f; + int64_t checkpoints_written = 0; + + /* Throughput: tokens over wall time in a 1-second decaying window (Scheduler::step_finished); + * the counters beside them are exact. */ + int64_t prefill_tokens = 0; + int64_t decode_tokens = 0; + float prefill_tps = 0.0f; + float decode_tps = 0.0f; + + /* Speculation (§10). */ + int64_t draft_tokens = 0; + int64_t draft_accepted = 0; + float draft_acceptance = 0.0f; + int draft_depth = 0; /* what the controller would choose right now */ + /* Per draft POSITION, so a cliff can be told from a decay: `reached` is how often every + * earlier position was accepted and this one was therefore evaluated, `accepted` how often it + * was then taken. Their ratio is the conditional hazard, which is the number that says what a + * deeper draft would actually buy. `draft_depth_seen` bounds how much of the arrays is real. */ + enum { RAD_METRICS_MAX_SPEC = 64 }; + int draft_depth_seen = 0; + int64_t draft_pos_reached [RAD_METRICS_MAX_SPEC] = {}; + int64_t draft_pos_accepted[RAD_METRICS_MAX_SPEC] = {}; +}; + +} /* namespace rad */ diff --git a/core/sched/scheduler.cpp b/core/sched/scheduler.cpp new file mode 100644 index 00000000..5776b9b6 --- /dev/null +++ b/core/sched/scheduler.cpp @@ -0,0 +1,2197 @@ +/* scheduler.cpp -- one decision per step. See scheduler.h for the shape and spec §7.1 for why. + */ +#include "scheduler.h" +#include "mm/processor.h" + +#include "server/sink.h" + +#include +#include +#include +#include +#include + +namespace rad { + +/* Wall-clock microseconds on a monotonic base. Used only by the live request table -- the step + * path measures with its own steady_clock points and never calls this. */ +static int64_t mono_us() { + return (int64_t)std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()).count(); + +} +/* ------------------------------------------------------------------ ordering */ +/* Priority first, arrival second, and arrival is what makes preemption fair without a special + * case: a preempted request re-enters the queue carrying its ORIGINAL arrival number, which is + * smaller than every request admitted after it, so it lands at the front of its priority class + * rather than at the back of the queue. It has already been served once and its blocks were taken + * from it; sending it to the back would be charging it twice. */ +bool Scheduler::ahead_of(int32_t a, int32_t b) const { + const SchedReq& x = *reqs_[(size_t)a]; + const SchedReq& y = *reqs_[(size_t)b]; + if (x.req->priority != y.req->priority) return x.req->priority > y.req->priority; + return x.arrival < y.arrival; +} + +void Scheduler::queue_insert(std::vector& q, int32_t slot) { + auto it = std::lower_bound(q.begin(), q.end(), slot, + [&](int32_t a, int32_t b) { return ahead_of(a, b); }); + q.insert(it, slot); /* capacity is reserved, so this moves and does not allocate */ +} + +void Scheduler::queue_erase(std::vector& q, int32_t slot) { + auto it = std::find(q.begin(), q.end(), slot); + if (it != q.end()) q.erase(it); +} + +/* ------------------------------------------------------------------ init */ +int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCache* pc, + const std::vector& ranks, const ChunkGeometry* geo) { + if (!kv || !pc) return RAD_E_INVAL; + prog_ = &prog; + cfg_ = cfg; + kv_ = kv; + pc_ = pc; + + /* The engine resolves this once and hands it over, because the prefix cache needs the + * checkpoint interval out of it before this runs. A caller that passes nothing (the tests) + * resolves its own -- harmless, it is a pure function of prog and cfg. What must not happen is + * two independent reads of the operator's RAW interval: the cache is given the resolved + * number, so there is one answer to "where does a chunk split". */ + if (geo) geo_ = *geo; + else RAD_TRY(chunk_geometry_resolve(prog, cfg, &geo_)); + + kvgeom_ = KVGeom::of(prog.kv_groups); + for (size_t i = 0; i < kvgeom_.g.size(); ++i) { + const int64_t w = kv->state_index_width((int32_t)i); + if (w > 0) kvgeom_.g[i].sidx_width = w; + } + has_linear_state_ = false; + for (const auto& g : kvgeom_.g) if (!g.paged) has_linear_state_ = true; + + /* A hit can only leave a drafter's own cache short where a PAGED group is not prefix-cached; + * see scheduler.h at hit_holes_draft_. With the cache off, cached_groups() is empty and this + * is true -- which costs nothing, because a run with no cache takes no hits and every + * sequence's first block pass sits at ctx_len 0 anyway. */ + { + /* PAGED AS THE CACHE COUNTS IT, which is KVGroupPlan::paged() and reaches here through + * block_tokens(). NOT kvgeom_'s `paged` flag: that one is also true for an empty + * placeholder group (0 layers, no plan), which a model is free to declare, so counting it + * overstates the paged groups and pins this predicate true. That is exactly the drift the + * comment in scheduler.h warns about. */ + size_t n_paged = 0; + for (size_t i = 0; i < kvgeom_.g.size(); ++i) + if (kv->block_tokens((int32_t)i) > 0) ++n_paged; + hit_holes_draft_ = pc->cached_groups().size() < n_paged; + RAD_INFO("draft floor: %zu paged group(s), %zu prefix-cached -> a hit %s", + n_paged, pc->cached_groups().size(), + hit_holes_draft_ ? "LEAVES a hole in a drafter's own KV" : "leaves no hole"); + } + + DraftController::Params dp; + dp.max_depth = cfg.n_spec; + RAD_TRY(draft_.configure(dp)); + + RAD_TRY(builder_.init(prog, cfg, geo_, kvgeom_, ranks)); + /* The builder's bound and not a second derivation of it: it is what the block tables were + * sized for, so it is the one number that says which positions exist. */ + ctx_limit_ = builder_.max_ctx(); + n_deferred_ = 0; + closed_ = false; + + /* Everything the step path touches is reserved here. A vector that grows during a step is an + * allocator call on the path this whole component exists to keep clear. */ + plan_.e.reserve((size_t)cfg.max_seqs); + running_.reserve((size_t)cfg.max_seqs); + waiting_.reserve((size_t)cfg.max_seqs * 4 + 64); + free_slots_.reserve((size_t)cfg.max_seqs); + free_cards_.resize((size_t)cfg.max_seqs); + for (int64_t c = 0; c < cfg.max_seqs; ++c) + free_cards_[(size_t)c] = (int32_t)(cfg.max_seqs - 1 - c); /* 0 is taken first */ + reqs_.reserve((size_t)cfg.max_seqs); + completed_.reserve((size_t)cfg.max_seqs); + by_id_.reserve((size_t)cfg.max_seqs * 2); + hit_blocks_.resize(prog.kv_groups.size()); + for (auto& v : hit_blocks_) v.reserve(64); + return RAD_OK; +} + +void Scheduler::fini() { + for (auto& s : reqs_) + if (s && s->req && (s->running || s->pending_free)) kv_->free_sequence(s->req->id); + builder_.fini(); + reqs_.clear(); + free_slots_.clear(); + free_cards_.clear(); + by_id_.clear(); + running_.clear(); + waiting_.clear(); +} + +/* ------------------------------------------------------------------ arrival */ +int Scheduler::add(std::unique_ptr r) { + std::lock_guard lk(mu_); + return add_locked(std::move(r)); +} + +/* ONE LOCK FOR ALL OF THEM, so the step that admits the first finds every one waiting. Taken one + * at a time, a step can begin between two of them and admit a prefix of the set, and which prefix + * depends on thread timing -- so the batch a request's sequences decode in, and with it their + * tie-level rounding, would vary between identical runs. */ +void Scheduler::add_all(std::unique_ptr* rs, size_t n, int* rc) { + std::lock_guard lk(mu_); + for (size_t i = 0; i < n; ++i) rc[i] = add_locked(std::move(rs[i])); +} + +int Scheduler::add_locked(std::unique_ptr r) { + if (!r) return RAD_E_INVAL; + if (r->prompt.empty()) return RAD_E_INVAL; + if (by_id_.count(r->id)) return RAD_E_DUPLICATE; + /* NO ENGINE BEHIND THE QUEUE ANY MORE. Accepting would leave the caller waiting on a step + * that is never coming, so the sink is failed here -- it is the one thing the caller is + * listening to -- and the refusal says why. */ + if (closed_) { + RAD_WARN("request %llu refused: %s", (unsigned long long)r->id, closed_reason_); + server::sink_fail(r->sink, RAD_E_STATE); + return RAD_E_STATE; + } + + int32_t slot; + if (!free_slots_.empty()) { slot = free_slots_.back(); free_slots_.pop_back(); } + else { slot = (int32_t)reqs_.size(); reqs_.emplace_back(); } + if (!reqs_[(size_t)slot]) reqs_[(size_t)slot] = std::make_unique(); + + SchedReq& s = *reqs_[(size_t)slot]; + s.req = std::move(r); + s.arrival = ++arrival_; + s.arrived_us = mono_us(); + s.first_tok_us = 0; + s.slot = slot; + s.card = -1; + s.running = false; + s.drafter_reset(); + s.sched_tokens = 0; + s.entry = -1; + s.entry_next = -1; + s.pending_free = false; + s.reap_pending = false; + s.ckpt_src = -1; + s.hit_attn = 0; + s.hit_owed = false; + s.req->state = ReqState::Waiting; + + /* The output vector is the one thing the step path appends to, so its capacity is settled + * here, on the arrival thread, and never again. Bounded by what the context can still hold: + * max_tokens is the caller's number, and reserving it as given lets one request ask this + * thread for gigabytes it could never fill. */ + int64_t out_cap = s.req->max_tokens > 0 ? (int64_t)s.req->max_tokens : 1; + const int64_t ctx_room = ctx_limit_ - (int64_t)s.req->prompt.size(); + if (ctx_limit_ > 0 && out_cap > ctx_room) out_cap = ctx_room > 1 ? ctx_room : 1; + s.req->output.reserve((size_t)out_cap + (size_t)RAD_SCHED_MAX_SPEC); + + by_id_[s.req->id] = slot; + /* Keep enough headroom that a step which preempts every running request cannot grow the + * queue's storage while it holds the lock. */ + if (waiting_.capacity() < waiting_.size() + (size_t)cfg_.max_seqs + 1) + waiting_.reserve(waiting_.size() + (size_t)cfg_.max_seqs + 1); + queue_insert(waiting_, slot); + return RAD_OK; +} + +Request* Scheduler::find(uint64_t id) { + std::lock_guard lk(mu_); + auto it = by_id_.find(id); + return it == by_id_.end() ? nullptr : reqs_[(size_t)it->second]->req.get(); +} + +int Scheduler::set_draft(uint64_t id, const int32_t* tokens, int n) { + std::lock_guard lk(mu_); + auto it = by_id_.find(id); + if (it == by_id_.end()) return RAD_E_NOTFOUND; + SchedReq& s = *reqs_[(size_t)it->second]; + if (n < 0) return RAD_E_INVAL; + + /* THE NEXT STEP ALREADY VERIFIES THESE. It was planned with the count the drafter issued, and + * the card already put the tokens in its batch; the host copy is what that step's commit + * emits the accepted ones from, so it takes exactly those, unclamped. */ + if (next_open_ && s.entry_next >= 0) { + if (n != s.draft_next) { + RAD_ERR("request %llu: %d draft(s) published for a step planned to verify %d", + (unsigned long long)id, n, s.draft_next); + return RAD_E_STATE; + } + for (int i = 0; i < n; ++i) s.draft[i] = tokens[i]; + s.n_draft = n; + s.req->n_draft = n; + s.req->draft = n ? s.draft : nullptr; + return RAD_OK; + } + + /* An ineligible request is given no proposal at all rather than a refusal: it decodes one + * token a step, exactly as it would on a server started without a drafter. See + * Request::may_speculate for the two reasons, and step() for the gate that catches the n-gram + * fallback as well. */ + if (!s.req->may_speculate) { + s.n_draft = 0; s.req->n_draft = 0; s.req->draft = nullptr; + return RAD_OK; + } + + int cap = draft_.next_depth(); + if (n > cap) n = cap; + if (n > RAD_SCHED_MAX_SPEC) n = RAD_SCHED_MAX_SPEC; + for (int i = 0; i < n; ++i) s.draft[i] = tokens[i]; + s.n_draft = n; + s.req->n_draft = n; + s.req->draft = s.draft; + return RAD_OK; +} + +/* ------------------------------------------------------------------ cancellation */ +/* ------------------------------------------------------------------ the sink + * + * THE TOKENS HAVE TO REACH THE CONNECTION, and this is where they leave the engine. `Request::sink` + * is the server's per-request channel (core/server/sink.h) and it is a `void*` on Request precisely + * so that core/sched does not depend on the server's types; the inline helpers there are the call + * sites. A null sink is legal and means nobody is listening -- an offline or benchmark request. + * + * Appending to `Request::output` is not enough on its own: without a push the engine generates + * correctly, step after step, while the HTTP thread waits in `Sink::wait()` until the client times + * out. `sink_push`, `sink_finish` and `sink_prompt_stats` are called from here and nowhere else. + * + * A push returns false ONLY on overflow, and an overflowing sink has already failed the request -- + * a stream missing tokens in the middle is worse than one that stops and says so -- so the return + * is what tells the scheduler to stop generating for it. */ +static server::Finish finish_of(ReqState st, const std::string& reason) { + if (st == ReqState::Cancelled) return server::Finish::Cancelled; + if (st == ReqState::Failed) return server::Finish::Error; + if (reason == "length") return server::Finish::Length; + return server::Finish::Stop; +} + +/* THE CACHE IS NOT ALLOWED TO OWN THE WHOLE POOL, and that is a policy decision rather than an + * optimisation. Every block the cache indexes is a block it holds a reference on, so a cache free + * to grow without limit drives the pool to full occupancy and keeps it there: admission then pays + * eviction on every chunk of every prefill, `kv_cache_usage_perc` pins at 1.0, the scheduler + * spends its time reclaiming rather than running, and a long enough run of distinct large prompts + * wedges. + * + * So a reserve is kept free. It is a fraction of the pool rather than a token count because the + * thing being protected is the ability to admit ANY sequence, and how big that is depends on the + * deployment. Trimming happens after a publish, off the step path, where the blocks were just + * added -- not during admission, where the cost lands on a request that did nothing wrong. */ + +/* Drop every entry, in VRAM or off it -- IPrefixCache::reset, because an eviction does not + * mean "forgotten" for an entry the idle tiers hold a copy of. */ +int64_t Scheduler::reset_prefix_cache() { + std::lock_guard lk(mu_); + if (!pc_ || !cfg_.prefix_cache) return RAD_E_UNSUPPORTED; + const int64_t dropped = pc_->reset(); + RAD_INFO("prefix cache: reset, %lld entries dropped", (long long)dropped); + return dropped; +} + +void Scheduler::trim_prefix_cache() { + if (!pc_ || !cfg_.prefix_cache) return; + const std::vector& cg = pc_->cached_groups(); + if (cg.empty()) return; + const int32_t g = cg[0]; + const int64_t total = kv_->total_blocks(g); + if (total <= 0) return; + const int64_t reserve = total / 4; /* a quarter of the pool stays free */ + for (int guard = 0; guard < 4096; ++guard) { + /* FREE AGAINST THE CARVE, not free_blocks(). On an elastic pool free_blocks() is bounded + * by the live mark, so a pool that has handed its unused top back reads as nearly full + * however little anything holds -- and this loop would then drain the whole cache to + * make room the pool can grow back into on demand. */ + if (total - kv_->held_blocks(g) >= reserve) return; + if (pc_->evict(256) <= 0) return; /* nothing left to give back */ + } + RAD_WARN("prefix cache: could not free %lld of %lld blocks in group %d after 4096 rounds; the " + "pool is held by live sequences rather than by the cache", + (long long)reserve, (long long)total, (int)g); +} + +void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool defer_free, + bool publish) { + /* PUBLISH BEFORE FREEING. This is the only moment the sequence's whole prefix is both + * computed and still owned, and it is what makes the cache a cache rather than a permanently + * empty lookup: insert() takes its own KV references, so the blocks survive the free below. + * A cancelled or failed request is published too -- its prompt was computed either way, and + * an agent client that hangs up mid-answer is exactly who asks for that prefix again. */ + if (publish && cfg_.prefix_cache && pc_ && kv_->has_sequence(s.req->id) && + s.req->n_computed > 0) { + const std::vector& cg = pc_->cached_groups(); + pub_blocks_.assign(cg.size(), {}); + bool ok = !cg.empty(); + for (size_t i = 0; i < cg.size(); ++i) { + /* A rebased table does not describe the prefix from position zero, so it cannot be + * published. cached_groups() already excludes windowed groups, which is where a + * moving floor comes from; this is the belt to that. */ + if (kv_->first_block_pos(s.req->id, cg[i]) != 0) { ok = false; break; } + pub_blocks_[i] = kv_->block_table(s.req->id, cg[i]); + } + if (ok) { + const int rc = pc_->insert(*s.req, pub_blocks_, s.req->n_computed); + if (rc < 0) + RAD_DEBUG("prefix cache: request %llu not published: %s", + (unsigned long long)s.req->id, rad_strerror(rc)); + trim_prefix_cache(); + } + } + + if (defer_free) { + if (!s.pending_free) ++n_deferred_; + s.pending_free = true; + } else if (kv_->has_sequence(s.req->id)) { + /* A preempted request has already had its blocks taken but the manager still knows the + * sequence, and it may still own a state slot. Asking first is what keeps this from + * depending on free_sequence() being idempotent. */ + kv_->free_sequence(s.req->id); + } + if (!defer_free) drop_card(s); + s.running = false; + s.req->state = st; + if (s.req->finish_reason.empty() && reason) s.req->finish_reason = reason; + queue_erase(running_, s.slot); + queue_erase(waiting_, s.slot); + s.n_draft = 0; + + /* Terminal, and idempotent on the sink's side: the first call wins, so a cancel racing a + * natural stop does not produce two finish reasons. This is the last thing the producer does + * to the sink, and the HTTP thread is waiting on exactly it. */ + server::sink_finish(s.req->sink, finish_of(st, s.req->finish_reason)); +} + +int Scheduler::cancel(uint64_t id) { + std::lock_guard lk(mu_); + auto it = by_id_.find(id); + if (it == by_id_.end()) return RAD_E_NOTFOUND; + SchedReq& s = *reqs_[(size_t)it->second]; + if (s.req->state == ReqState::Finished || s.req->state == ReqState::Cancelled) + return RAD_OK; + + /* Blocks go back NOW, not when the step that would have finished this request runs. A + * cancelled request that keeps its pool share until completion is a pool that shrinks under + * exactly the load that generates cancellations (spec §14). + * + * The one exception is a request whose tokens are in the step the device is still executing. + * Its blocks are released at commit instead -- one step later, not one request later. Handing + * a live block to a new sequence mid-step is a race, and it is the kind that presents as a + * model quality problem rather than as a crash. + * + * AND A DRAFTER'S SNAPSHOT IS THE OTHER. The drafter builds its passes one at a time after + * commit, releasing this lock between them, so a cancel can land after one pass was built + * and before the next. Freeing then leaves the next pass naming a sequence with no blocks: + * its block-table row is all -1 while its length is not, and attention reads block -1. The + * blocks are released once the drafter is done with the sequence (sweep_deferred). */ + const bool in_flight = in_step(s) || block_holds(id); + close_request(s, ReqState::Cancelled, "cancelled", in_flight); + ++m_.cancelled; + completed_.push_back(id); + return RAD_OK; +} + +void Scheduler::take_completed(std::vector* out) { + if (!out) return; + out->clear(); + std::lock_guard lk(mu_); + if (!next_open_) { out->swap(completed_); return; } + /* A REQUEST THE NEXT STEP STILL CARRIES IS HELD BACK. That step's sampler is staged for it + * after this one commits, so its sampler state has to outlive the finish by one step; it is + * handed out once the step that carries it has committed. */ + size_t keep = 0; + for (uint64_t id : completed_) { + auto it = by_id_.find(id); + const bool held = it != by_id_.end() && reqs_[(size_t)it->second]->entry_next >= 0; + if (held) completed_[keep++] = id; + else out->push_back(id); + } + completed_.resize(keep); +} + +void Scheduler::release_locked(SchedReq& s) { + if (s.pending_free) { free_kv(s); s.pending_free = false; --n_deferred_; } + if (s.reap_pending) { s.reap_pending = false; --n_deferred_; } + by_id_.erase(s.req->id); + s.req.reset(); + free_slots_.push_back(s.slot); +} + +void Scheduler::free_kv(SchedReq& s) { + kv_->free_sequence(s.req->id); + drop_card(s); +} + +void Scheduler::drop_card(SchedReq& s) { + if (s.card < 0) return; + free_cards_.push_back(s.card); + s.card = -1; +} + +bool Scheduler::block_holds(uint64_t id) const { + for (const BlockSeq& d : block_) if (d.seq == id) return true; + for (const SerialSeq& m : serial_) if (m.seq == id) return true; + return false; +} + +const Request* Scheduler::live_req(int32_t slot, uint64_t id) const { + if (slot < 0 || (size_t)slot >= reqs_.size() || !reqs_[(size_t)slot]) return nullptr; + const SchedReq& s = *reqs_[(size_t)slot]; + return (s.req && s.req->id == id) ? s.req.get() : nullptr; +} + +void Scheduler::sweep_deferred() { + if (n_deferred_ <= 0) return; + for (auto& up : reqs_) { + if (!up) continue; + SchedReq& s = *up; + if (!s.req || (!s.reap_pending && !s.pending_free)) continue; + if (in_step(s)) continue; + if (block_holds(s.req->id)) continue; + if (s.reap_pending) { release_locked(s); continue; } + /* A free deferred on a drafter snapshot, for a request nobody has reaped yet. The Request + * stays until the reap; only the blocks go back. */ + free_kv(s); + s.pending_free = false; + --n_deferred_; + } +} + +bool Scheduler::has_deferred() const { + std::lock_guard lk(mu_); + return n_deferred_ > 0; +} + +void Scheduler::release_deferred() { + std::lock_guard lk(mu_); + sweep_deferred(); +} + +void Scheduler::shutdown(const char* reason) { + std::lock_guard lk(mu_); + closed_ = true; + closed_reason_ = reason ? reason : "the engine has stopped"; + /* Copied first: close_request erases from both queues. */ + std::vector live(running_); + live.insert(live.end(), waiting_.begin(), waiting_.end()); + for (int32_t slot : live) { + SchedReq& s = *reqs_[(size_t)slot]; + if (!s.req) continue; + close_request(s, ReqState::Failed, closed_reason_, /*defer_free=*/false, + /*publish=*/false); + ++m_.failed; + completed_.push_back(s.req->id); + } + /* Nothing will commit again, so no entry of the last step still owns its slot. */ + step_open_ = false; + next_open_ = false; + for (auto& up : reqs_) if (up) { up->entry = -1; up->entry_next = -1; } + block_.clear(); + serial_.clear(); + sweep_deferred(); +} + +int Scheduler::reap(uint64_t id) { + std::lock_guard lk(mu_); + auto it = by_id_.find(id); + if (it == by_id_.end()) return RAD_E_NOTFOUND; + int32_t slot = it->second; + SchedReq& s = *reqs_[(size_t)slot]; + if (s.req->state == ReqState::Running || s.req->state == ReqState::Waiting || + s.req->state == ReqState::Preempted) + return RAD_E_STATE; + /* NOT WHILE ANYTHING STILL POINTS AT THE SLOT, and two things can. The server reaps as soon as + * the sink is finished, and cancel() finishes the sink at once, so a client that hangs up + * mid-generation gets here at an arbitrary point in the step loop. + * + * - a StepEntry, if the device is still running the step this request is in. Destroying the + * Request there segfaults commit() on `r.state`; returning the slot there is worse, + * because a request admitted before the commit lands would be handed the entry and the + * tokens. + * - the DRAFTER'S SNAPSHOT. block_begin takes it under the lock and block_context, + * block_query and block_end read it again after releasing and retaking the lock; a + * Request freed in that window leaves BatchBuilder::build reading tokens off freed + * memory. Keeping it alive rather than dropping the row is what + * preserves the drafter's row mapping -- the engine already sized its readback from + * block_begin's answer, so a query pass with one fewer row would attribute one + * sequence's drafts to another. + * + * Both are the same one-step window `pending_free` covers, and both close the same way. */ + if (in_step(s) || block_holds(id)) { + if (!s.reap_pending) ++n_deferred_; + s.reap_pending = true; + return RAD_OK; + } + release_locked(s); + return RAD_OK; +} + +int Scheduler::queue_snapshot(uint64_t* out, int max) const { + std::lock_guard lk(mu_); + int n = 0; + for (int32_t slot : waiting_) { + if (n >= max) break; + out[n++] = reqs_[(size_t)slot]->req->id; + } + return n; +} + + +/* WHAT EVERY REQUEST IS DOING RIGHT NOW. Copied out under the step lock rather than handed out as + * pointers: a caller holding a SchedReq* across a step is holding one that commit() may reap. + * + * Oldest first. A dashboard's reader is looking for the one that is stuck, and the one that is + * stuck is the one that has been here longest. */ +int Scheduler::requests(ReqStat* out, int max) const { + std::lock_guard lk(mu_); + return requests_locked(out, max); +} + +int Scheduler::requests_locked(ReqStat* out, int max) const { + const int64_t now = mono_us(); + const int32_t n_groups = prog_ ? (int32_t)prog_->kv_groups.size() : 0; + + int n = 0; + for (const auto& p : reqs_) { + if (n >= max) break; + if (!p || !p->req) continue; + const SchedReq& s = *p; + const Request& r = *s.req; + ReqStat& o = out[n++]; + o.id = r.id; + o.state = (int)r.state; + o.running = s.running; + o.prompt_tokens = (int64_t)r.prompt.size(); + o.computed_tokens = r.n_computed; + o.cached_tokens = r.n_cached; + o.output_tokens = (int64_t)r.output.size(); + o.max_tokens = r.max_tokens; + o.ctx_tokens = s.seq_len(); + /* BLOCKS ADD UP AND TOKENS DO NOT. Each paged group was carved its own blocks, so a count + * of them is a sum; but the paged groups SHARE ONE TOKEN AXIS -- one token of context + * takes a slot in every one of them -- so summing their tokens reports a request holding + * as many times its own context as there are paged groups. Against a pool capacity that + * is correctly one group's, two 100K requests then read as 95% of a pool that is 72% + * full. The token figure is the largest group's, which is the context the request is + * holding, and it is comparable with SchedMetrics::kv_tokens_used by construction. */ + o.kv_blocks = o.kv_tokens = 0; + for (int32_t g = 0; g < n_groups; ++g) { + const int64_t bt = kv_->block_tokens(g); + if (bt <= 0) continue; /* stateful groups are not paged */ + const int64_t held = (int64_t)kv_->block_table(r.id, g).size(); + o.kv_blocks += held; + if (held * bt > o.kv_tokens) o.kv_tokens = held * bt; + } + o.n_draft = s.n_draft; + o.slot = s.slot; + o.age_s = (double)(now - s.arrived_us) / 1e6; + o.ttft_s = s.first_tok_us ? (double)(s.first_tok_us - s.arrived_us) / 1e6 : -1.0; + /* Since its FIRST token, not since admission: a request that waited thirty seconds in the + * queue did not decode slowly, and dividing by the wait would say it did. */ + const double dec = s.first_tok_us ? (double)(now - s.first_tok_us) / 1e6 : 0.0; + o.decode_tps = dec > 1e-3 ? (double)r.output.size() / dec : 0.0; + } + std::sort(out, out + n, [](const ReqStat& a, const ReqStat& b) { return a.id < b.id; }); + return n; +} + +/* ------------------------------------------------------------------ drafting */ +/* PROMPT-LOOKUP DRAFTING, and it needs no second model. Take the last few committed tokens of a + * sequence, find where that pattern last occurred in the SAME sequence, and propose whatever + * followed it. On the workloads this engine is for -- a coder model quoting the file it was given, + * a model rewriting a diff, JSON with repeated keys -- that guess is right often enough to pay, + * and when it is wrong the verify step still emits the target's own token, so it can only cost + * bandwidth. It is here rather than behind the drafter plugin interface because it is not a model: + * there is nothing to load, nothing to place, and no second forward pass. + * + * Longest pattern first: a longer match is a stronger prediction, and dropping to a shorter one + * only when the longer finds nothing is what keeps the acceptance rate from collapsing on common + * bigrams. Most recent occurrence first, for the same reason. + * + * A draft head, when one is declared, replaces this by calling set_draft() before step() -- which + * is why this only fills a proposal that is still empty. */ +int Scheduler::draft_ngram(SchedReq& s, int depth) const { + /* RADIANCE_NO_DRAFT separates the two halves of speculation. With it set the deployment is + * still speculative -- the state pool is laid out for it and the linear kernels take the + * path that defers the state -- but no step ever carries a draft, so every step is an + * ordinary one-token decode and the output must match a non-speculative run exactly. It + * answers 'is the deferred state right' without 'is the rollback right' on top of it. */ + static const bool none = [] { const char* e = getenv("RADIANCE_NO_DRAFT"); return e && *e == '1'; }(); + if (none) return 0; + if (depth <= 0 || !s.req) return 0; + const Request& r = *s.req; + const int64_t np = (int64_t)r.prompt.size(), no = (int64_t)r.output.size(); + const int64_t n = np + no; + if (n < 2) return 0; + auto at = [&](int64_t i) -> int32_t { + return i < np ? r.prompt[(size_t)i] : r.output[(size_t)(i - np)]; + }; + for (int k = kNgramMax; k >= kNgramMin; --k) { + if (n < (int64_t)k + 1) continue; + for (int64_t j = n - k - 1; j >= 0; --j) { + bool hit = true; + for (int t = 0; t < k && hit; ++t) hit = (at(j + t) == at(n - k + t)); + if (!hit) continue; + int d = 0; + while (d < depth && j + k + d < n) { s.draft[d] = at(j + k + d); ++d; } + return d; + } + } + return 0; +} + +/* ------------------------------------------------------------------ chunking */ +/* A prefill chunk splits at the linear-state checkpoint interval so that a checkpoint is always + * WRITTEN. vLLM writes one only when a scheduler step happens to end on a boundary, which is why + * a checkpoint landing in request-unique tokens silently drops caching to zero (spec §7.3). + * + * The order of the two clamps matters. The checkpoint clamp comes first because the interval is a + * multiple of the quantum, so a chunk clamped to an interval is already quantum-aligned and the + * second clamp is a no-op on it. Reversing them would round a chunk PAST the checkpoint down and + * then miss the boundary, which is the exact failure this is written to avoid. */ +int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budget, + int64_t* checkpoint_pos) const { + if (checkpoint_pos) *checkpoint_pos = -1; + int64_t remaining = n_target - n_computed; + if (remaining <= 0 || budget <= 0) return 0; + + int64_t want = remaining < budget ? remaining : budget; + + if (geo_.checkpoints()) { + const int64_t I = geo_.checkpoint_interval; + int64_t next = ((n_computed / I) + 1) * I; /* strictly after n_computed */ + if (n_computed + want > next) want = next - n_computed; + if (n_computed + want == next && checkpoint_pos) *checkpoint_pos = next; + } + + if (want < remaining) { + /* A non-final chunk has to end on a quantum boundary measured from the SEQUENCE origin, + * not from the start of the step, or the next chunk hands the linear kernel a partial + * tile and the attention kernel a partial block. The final chunk of a request is allowed + * to be short: that is the accepted cost of owning the boundaries. */ + const int64_t Q = geo_.quantum; + int64_t end = n_computed + want; + int64_t aligned = end / Q * Q; + if (aligned <= n_computed) { + if (checkpoint_pos) *checkpoint_pos = -1; + return 0; /* the budget left cannot hold one quantum */ + } + if (aligned < end) { + want = aligned - n_computed; + if (checkpoint_pos) *checkpoint_pos = -1; + } + } + return want; +} + +/* ------------------------------------------------------------------ preemption */ +void Scheduler::preempt_back() { + int32_t slot = running_.back(); + SchedReq& s = *reqs_[(size_t)slot]; + Request& r = *s.req; + + /* Preemption by RECOMPUTE: the blocks go back to the pool and the request restarts from zero. + * Its generated output is simply the tail of its token sequence, so recompute needs no special + * path -- it re-prefills prompt ++ output through the same chunker. */ + kv_->preempt(r.id); + drop_card(s); + r.n_computed = 0; + r.n_cached = 0; + r.n_accepted = 0; + r.state = ReqState::Preempted; + s.drafter_reset(); + /* AND THE REQUEST'S OWN COPY OF THE WINDOW. The sampler stages 1 + Request::n_draft rows for + * a request (Sampler::build_step), and a drafter may have set it for the step this preemption + * just took away. Left standing, the recompute's first sampled step stages rows its batch does + * not have, and every request after it in the step samples another's logits row. */ + r.n_draft = 0; + r.draft = nullptr; + s.running = false; + + running_.pop_back(); + queue_insert(waiting_, slot); /* original arrival -> the front of its priority class */ + ++m_.preemptions; +} + +/* ------------------------------------------------------------------ admission */ +/* Admission checks the KV budget BEFORE a request enters running. A request admitted without the + * blocks to run it is a request that will be preempted on its first step, which costs a full + * recompute for nothing. */ +int Scheduler::admit_one(SchedReq& s, int64_t budget) { + Request& r = *s.req; + + if (!kv_->has_sequence(r.id)) RAD_TRY(kv_->add_sequence(r.id)); + + /* A FRESH ATTEMPT: nothing looked up yet, nothing counted yet. A request that kept an + * earlier attempt's hit (n_computed > 0) keeps what that attempt found as well. */ + if (r.n_computed == 0) { + s.ckpt_src = -1; + s.hit_attn = 0; + s.hit_owed = true; + } + + if (r.n_computed == 0 && cfg_.prefix_cache) { + /* BEFORE the lookup, because the lookup stops at the first block the tiers hold -- an + * honest shorter hit, but a shorter one. This is where a cold session gets its + * context back instead of re-prefilling it: it costs a copy, and the alternative + * costs a prefill. */ + if (pc_->restore(r) == IPrefixCache::Restore::Wait) return kAdmitWait; + CacheHit h = pc_->lookup(r, &hit_blocks_); + int32_t reuse = h.n_attn_tokens; + if (geo_.checkpoints() && h.n_linear_tokens < reuse) { + /* A hit landing between checkpoints reuses the attention blocks and must replay the + * linear layers forward from the last checkpoint (§7.3). RadBatch carries ONE query + * length for every group, so this build cannot run the linear layers over a longer + * range than the attention layers: that would need per-group q_lens on + * RadKVGroupBatch. Without them, the conservative and correct answer is to recompute + * from the checkpoint. */ + reuse = h.n_linear_tokens; + } + int32_t last = (int32_t)r.prompt.size() - 1; /* one token must remain to produce logits */ + if (reuse > last) reuse = last; + if (reuse < 0) reuse = 0; + + /* A HIT ON A HYBRID MODEL IS ONLY LEGAL BECAUSE OF THE CHECKPOINT. Reuse skips recomputing + * the prefix, which the adopted blocks cover for the paged attention groups and NOTHING + * covers for a recurrent group -- its state lives in a per-sequence slot. So a hit that + * skips tokens must also restore that state, which is what `ckpt_src` carries into the + * entry below and what KVManager::checkpoint_restore performs. + * + * Refusing to reuse without one is therefore not conservatism, it is the only correct + * answer: `reuse` is already clamped to `h.n_linear_tokens` above, so a hit that found no + * valid checkpoint clamps to zero on its own. What must never happen is reuse > 0 with no + * snapshot to resume from -- that is every recurrent layer continuing from whatever the + * slot last held, and it reads as fluent text rather than as a failure. */ + if (reuse > 0 && has_linear_state_ && h.checkpoint_slot < 0) reuse = 0; + + /* Claim the cached blocks. Without this the hit is only an accounting entry: the sequence + * would skip computing those tokens and then attend to blocks it does not own. adopt() + * takes a whole block multiple, which `reuse` is -- it is a multiple of the checkpoint + * interval, which geometry.h made a multiple of the quantum, which is a multiple of the + * block size. */ + if (reuse > 0) { + const std::vector& cg = pc_->cached_groups(); + for (size_t i = 0; i < cg.size() && i < hit_blocks_.size(); ++i) { + int64_t nb = reuse / kvgeom_.g[(size_t)cg[i]].block_size; + if ((int64_t)hit_blocks_[i].size() > nb) hit_blocks_[i].resize((size_t)nb); + if (kv_->adopt(r.id, cg[i], hit_blocks_[i], reuse) < 0) { + /* AND WHAT THE EARLIER GROUPS ADOPTED GOES BACK. Left in the table, those + * blocks would be the first blocks of a sequence that now starts from zero, + * and the recompute would write its KV into the cache's own blocks. */ + kv_->preempt(r.id); + reuse = 0; + break; + } + } + } + + r.n_computed = reuse; + r.n_cached = reuse; + s.ckpt_src = (reuse > 0 && reuse == h.n_linear_tokens) ? h.checkpoint_slot : -1; + s.hit_attn = h.n_attn_tokens; + } + + int64_t target = s.seq_len(); + int64_t ckpt = -1; + int64_t want = plan_chunk(r.n_computed, target, budget, &ckpt); + int rc = RAD_OK; + if (want <= 0) rc = RAD_E_FULL; + else if (s.card < 0 && free_cards_.empty()) rc = RAD_E_FULL; + else if (kv_->ensure(r.id, r.n_computed + want) < 0) rc = RAD_E_NOMEM; + if (rc < 0) { + /* A HIT THAT RESUMES FROM A SNAPSHOT IS NOT KEPT ACROSS A FAILED ATTEMPT. The slot is + * named by id only, and until this request's first step restores from it nothing stops + * the cache retiring it and handing it to another sequence's checkpoint -- so a later + * attempt that trusted the id would restore somebody else's recurrent state, which reads + * as fluent text about the wrong conversation. Giving the hit back costs the next attempt + * a lookup; the attention-only hit of a model with no recurrent state holds only + * refcounted blocks and is kept. */ + if (s.ckpt_src >= 0) undo_hit(s); + return rc; + } + + /* Counted once per admission, here, where it is known to have happened. */ + if (s.hit_owed) { + m_.prompt_tokens += (int64_t)r.prompt.size(); + if (cfg_.prefix_cache) { + m_.attn_cached_tokens += s.hit_attn; + m_.linear_cached_tokens += r.n_cached; + } + s.hit_owed = false; + } + + if (s.card < 0) { s.card = free_cards_.back(); free_cards_.pop_back(); } + r.state = ReqState::Running; + s.running = true; + s.sched_tokens = (int32_t)want; + s.pending_ckpt = ckpt; + ++m_.admitted; + return RAD_OK; +} + +void Scheduler::undo_hit(SchedReq& s) { + Request& r = *s.req; + /* preempt() rather than free_sequence(): the sequence stays known to the manager, at zero + * tokens and holding nothing, which is exactly where a fresh attempt starts from. */ + if (kv_->has_sequence(r.id)) kv_->preempt(r.id); + r.n_computed = 0; + r.n_cached = 0; + s.ckpt_src = -1; + s.hit_attn = 0; +} + +/* ------------------------------------------------------------------ the step */ +const RadBatch* Scheduler::step() { + std::lock_guard lk(mu_); + + /* The drafter's snapshots describe the step before this one and nothing reads them from here + * on. block_end() and serial_end() clear them already; this covers a drafter that stopped + * part way through, so a stale snapshot cannot keep deferring a release. */ + block_.clear(); + serial_.clear(); + /* And the snapshots the last step's admissions were handed have been read by its forward, + * which committed before this was called. */ + if (pc_) pc_->begin_step(); + + plan_.reset(); + step_prefill_tok_ = 0; + step_decode_tok_ = 0; + + int64_t budget = cfg_.max_tok; + bool preempted_here = false; + + /* A STEP THAT ALSO CARRIES A PREFILL TAKES A DRAFT LIKE ANY OTHER, and that rests on how the + * linear blocks issue a mixed step. + * + * The blocks issue the RECURRENT path over the decode rows of a mixed step and the CHUNKED + * path over the prefill ones, so a verifying decode row carries num_accepted and rolls back + * exactly as it does in a pure decode step. Were a mixed step prefill-shaped for every + * sequence in it, a verifying row would take the chunked path -- which has no num_accepted + * operand, because a chunk has nothing to reject -- and its recurrent state and conv window + * would advance over all 1 + n_spec tokens with no way back. The rejected tokens stay folded + * into the state and the model is then conditioned on text it never emitted: fluent, and + * drifting, so it surfaces as concurrent requests disagreeing with the same requests run + * alone rather than as anything failing. */ + const int depth = draft_.next_depth(); + + /* ---------------------------------------------------------- running requests first */ + /* Continuous batching: a request already holding blocks is served before a new one is let in, + * because the alternative is admitting work that then preempts work already half done. */ + for (size_t i = 0; i < running_.size(); ) { + if ((int64_t)plan_.e.size() >= cfg_.max_seqs || budget <= 0) break; + + int32_t slot = running_[i]; + SchedReq& s = *reqs_[(size_t)slot]; + Request& r = *s.req; + + const int64_t target = s.seq_len(); + const bool prefill = (r.n_computed < (int64_t)r.prompt.size()) || + (r.n_computed + 1 < target); + + int64_t ckpt = -1; + int64_t want; + if (prefill) { + want = plan_chunk(r.n_computed, target, budget, &ckpt); + } else { + /* A verify step is 1 + n_draft query rows, which is why attention kernels take a + * query length rather than assuming one (spec §10). */ + /* THE LAST GATE, and it has to be here rather than only at set_draft, because the + * n-gram fallback below fills any proposal a drafter left empty -- so refusing a + * draft upstream and stopping there hands the request a different draft instead of + * none. Request::may_speculate says why a request can be ineligible. */ + if (!r.may_speculate) s.n_draft = 0; + else if (s.n_draft == 0) s.n_draft = (int32_t)draft_ngram(s, depth); + if (s.n_draft > depth) s.n_draft = depth; + /* NO VERIFIED POSITION AT OR PAST THE CONTEXT. The step computes positions n_computed + * .. n_computed + n_draft, and nothing past ctx_limit_ - 1 has a rotary row or a + * block-table column. commit() finishes a sequence before its length reaches the + * limit, so there is always room for the one token itself. */ + const int64_t spare = ctx_limit_ - 1 - (int64_t)r.n_computed; + if (ctx_limit_ > 0 && s.n_draft > spare) s.n_draft = spare > 0 ? (int32_t)spare : 0; + want = 1 + s.n_draft; + if (want > budget) want = 0; + } + if (want <= 0) break; /* the budget is spent; the rest of running_ waits a step */ + + /* KV first, and preempt from the BACK on refusal -- the lowest priority, latest arrival + * running request, which is the one that would be re-admitted last anyway. */ + /* BOUNDED, because this loop is the scheduler thread and an unbounded one is a server that + * stops stepping with nothing in the log to say why. Reclaiming from the cache is tried + * first (a cached prefix is a saving; a running request is work in flight), but only so + * many times -- past that the shortfall is not the cache's to fix and preemption is. */ + static const int kMaxEvictRounds = 256; + int evict_rounds = 0; + bool failed = false; + while (kv_->ensure(r.id, r.n_computed + want) < 0) { + /* THE CACHE GIVES ITS BLOCKS BACK BEFORE A RUNNING REQUEST DOES. Everything the prefix + * cache holds is a saving on work that has already been done once; everything a + * running request holds is work in flight. Evicting first is therefore strictly the + * cheaper order, and it is also what keeps publishing from turning into a leak -- the + * cache retains a reference on every block it indexes and nothing else ever releases + * one. Batched rather than one at a time so a large shortfall does not walk the LRU + * list a hundred times. */ + if (++evict_rounds <= kMaxEvictRounds && pc_ && cfg_.prefix_cache && + pc_->evict(256) > 0) + continue; + if (!kv_->can_ever_fit(r.n_computed + want) || running_.size() - 1 <= i) { + /* Nothing left to take. §17: if the smallest running request cannot fit, it is + * failed rather than the engine deadlocking on a pool that cannot grow. */ + /* §17: either an empty pool could not serve this length at all, or there is no + * lower-priority request left to take blocks from. Failing the request beats + * deadlocking on a pool that cannot grow. */ + RAD_WARN("request %llu failed: the KV pool cannot hold %lld tokens%s", + (unsigned long long)r.id, (long long)(r.n_computed + want), + kv_->can_ever_fit(r.n_computed + want) + ? " and nothing lower-priority is left to preempt" + : " at any occupancy"); + close_request(s, ReqState::Failed, "kv_exhausted"); + ++m_.failed; + completed_.push_back(r.id); + failed = true; + break; + } + preempt_back(); + preempted_here = true; + } + if (failed) continue; /* close_request removed it from running_; i now indexes the next */ + + StepEntry e; + e.req = &r; + e.seq = r.id; + e.slot = slot; + e.card = s.card; + e.n_tokens = (int32_t)want; + e.ctx_len = (int32_t)r.n_computed; + e.n_spec = prefill ? 0 : s.n_draft; + /* AND THE REQUEST SAYS THE SAME NUMBER. Sampler::build_step sizes its per-row staging from + * `Request::n_draft` -- one row per sampled position, so 1 + n_draft of them -- while the + * batch sizes its logits rows from `n_spec`. The two are the same window and must be kept + * equal by one writer: setting only the scheduler`s copy leaves the sampler staging one + * row for a step that produces several, and setting only the request`s leaves it staging + * rows for a window a later clamp to the controller`s depth took away. Set here, once, + * where the window is decided. */ + r.n_draft = e.n_spec; + r.draft = e.n_spec ? s.draft : nullptr; + /* ONE-BASED, AND A PREFILL ROW IS 1 AND NOT 0. See StepEntry: the value is "how many + * tokens the previous step committed", the rolling windows are read at `n_accepted - 1`, + * and zero is not a value any of them can read. A prefill has nothing to roll back, which + * is offset zero, which is ONE -- the same thing the kernels assume when the operand is + * absent, and what ple_conv's contract states for exactly this case. + * + * IT IS NOT ONLY THE FIRST CHUNK THAT IS AFFECTED. `has_init` is the context length, so + * every chunk after the first of a chunked prefill is WARM, and a warm window read at -1 + * is one element before the slot: ple_conv takes the previous channel's last sample and + * ngram_ids hashes a token the slot never held. A 200K prompt is a hundred chunks. */ + e.n_accepted = prefill ? 1 : r.n_accepted + 1; + e.conv_cursor = s.conv_cursor; + e.draft = s.draft; + e.n_draft = s.n_draft; + e.is_prefill = prefill; + e.produces_token = (r.n_computed + want >= target); + /* The snapshot a hit resumes from, consumed once: the state is in the slot for the whole + * sequence after this, and restoring it again on a later chunk would rewind it. */ + e.ckpt_restore = s.ckpt_src; + s.ckpt_src = -1; + if (ckpt > 0) { + /* The checkpoint is the state AFTER the last token of the chunk, and that token sits + * at the interval boundary because the split put it there. */ + int32_t cs = -1; + if (pc_->reserve_checkpoint(r, ckpt, &cs) >= 0 && cs >= 0) { + e.ckpt_tok = (int32_t)(want - 1); + e.ckpt_slot = cs; + ++m_.checkpoints_written; + } + } + s.entry = (int32_t)plan_.e.size(); + s.sched_tokens = (int32_t)want; + plan_.e.push_back(e); + plan_.n_tok += want; + if (!prefill && s.n_draft > plan_.n_spec) plan_.n_spec = s.n_draft; + budget -= want; + ++i; + } + + /* ---------------------------------------------------------- admission */ + /* Skipped entirely in a step that preempted: the pool just refused a request that already had + * blocks, so it will refuse a new one, and the front of the queue is now the request we just + * took them from. Probing would cost a lookup per step and admit nothing. */ + if (!preempted_here) { + /* `at` walks the queue and `took_` is what it admitted: a request waiting on a read off + * disk stays where it is and the one behind it is asked, so the queue is compacted after + * the walk rather than cut at its front. */ + took_.clear(); + size_t at = 0; + while (at < waiting_.size() && + (int64_t)plan_.e.size() < cfg_.max_seqs && budget > 0) { + int32_t slot = waiting_[at]; + SchedReq& s = *reqs_[(size_t)slot]; + /* A SEQUENCE THE CONTEXT CANNOT HOLD IS NEVER RUN. Its prompt alone reaches the last + * position this deployment can address, so there is no room to generate into, and + * prefilling it would write positions the block tables and rotary tables do not + * have. The server refuses such a prompt at the door; this is the scheduler's own + * bound for any caller that did not. close_request takes it out of waiting_, so the + * same index now names the next request. */ + if (ctx_limit_ > 0 && s.seq_len() >= ctx_limit_) { + RAD_WARN("request %llu failed: %lld tokens leave no room in a %lld-token context", + (unsigned long long)s.req->id, (long long)s.seq_len(), + (long long)ctx_limit_); + close_request(s, ReqState::Failed, "context_length_exceeded"); + ++m_.failed; + completed_.push_back(s.req->id); + continue; + } + /* ITS MEDIA FIRST. A request whose items are not encoded keeps its place and the one + * behind it is asked, exactly as for a context still being read off disk; the engine + * runs the encoder before the next step (encodes_pending). */ + if (s.req->media && !media_ready(s)) { ++at; continue; } + const int as = admit_one(s, budget); + if (as == kAdmitWait) { ++at; continue; } + if (as < 0) break; /* head of line: do not admit behind it */ + + Request& r = *s.req; + StepEntry e; + e.req = &r; + e.seq = r.id; + e.slot = slot; + e.card = s.card; + e.n_tokens = s.sched_tokens; + e.ctx_len = (int32_t)r.n_computed; + e.n_spec = 0; + /* The sampler sizes its staging off the Request's own window, so it is said here as + * well: a request coming back from preemption may still carry a proposal a drafter + * set before it was taken off the device. */ + r.n_draft = 0; + r.draft = nullptr; + e.n_accepted = 1; /* one-based; a prefill rolls nothing back */ + e.conv_cursor = s.conv_cursor; + e.draft = s.draft; + e.n_draft = 0; + e.is_prefill = true; + e.produces_token = (r.n_computed + s.sched_tokens >= s.seq_len()); + /* THE ADMISSION PATH IS THE ONE THAT MATTERS for a restore -- admit_one set ckpt_src + * moments ago and this is the entry it applies to. Consumed once: the state is in the + * slot for the rest of the sequence, and restoring it again on a later chunk would + * rewind the recurrence to where the hit started. */ + e.ckpt_restore = s.ckpt_src; + s.ckpt_src = -1; + if (s.pending_ckpt > 0) { + int32_t cs = -1; + if (pc_->reserve_checkpoint(r, s.pending_ckpt, &cs) >= 0 && cs >= 0) { + e.ckpt_tok = s.sched_tokens - 1; + e.ckpt_slot = cs; + ++m_.checkpoints_written; + } + } + s.entry = (int32_t)plan_.e.size(); + plan_.e.push_back(e); + plan_.n_tok += s.sched_tokens; + budget -= s.sched_tokens; + took_.push_back(at); + ++at; + } + if (!took_.empty()) { + for (size_t i : took_) queue_insert(running_, waiting_[i]); + size_t w = 0, k = 0; + for (size_t i = 0; i < waiting_.size(); ++i) { + if (k < took_.size() && took_[k] == i) { ++k; continue; } + waiting_[w++] = waiting_[i]; + } + waiting_.resize(w); + } + } + + if (plan_.e.empty()) return nullptr; + + /* THE DECODE ROWS FIRST, and both halves therefore contiguous. + * + * A mixed step is prefill-shaped for every sequence in it only because the two kinds of row + * are interleaved: the running loop walks `running_` in priority order and a request part way + * through its prompt sits wherever its priority put it. Sorted, each half is a contiguous run + * of sequences, and a block can issue the recurrent path over one and the chunked path over + * the other -- cu_seqlens holds absolute row offsets, so a sub-array of it needs no rebasing + * and no kernel change (RadBatch::n_seq_decode). + * + * Stable, so the order within each half is still the order the scheduler chose. `s.entry` is + * the index into this vector and every entry's was assigned before the sort, so all of them + * are rewritten here -- a stale entry index is a request reading another request's result. + * + * A pure step sorts to itself and pays one pass over at most max_seqs entries. */ + std::stable_partition(plan_.e.begin(), plan_.e.end(), + [](const StepEntry& e) { return !e.is_prefill; }); + for (size_t i = 0; i < plan_.e.size(); ++i) { + StepEntry& e = plan_.e[i]; + if (e.slot >= 0 && (size_t)e.slot < reqs_.size()) reqs_[(size_t)e.slot]->entry = (int32_t)i; + } + + /* Phase, from what actually got scheduled. The run phase uses it to index bucket tables, so a + * step with one prefill chunk in it is MIXED and not DECODE -- calling it decode would pick + * the skinny-GEMM band for a thousand-row GEMM. */ + bool any_pf = false; int64_t n_dec = 0; + for (const StepEntry& e : plan_.e) { if (e.is_prefill) any_pf = true; else ++n_dec; } + plan_.phase = any_pf && n_dec ? RAD_PHASE_MIXED + : any_pf ? RAD_PHASE_PREFILL + : RAD_PHASE_DECODE; + + /* WHAT THE STEP SHAPE COSTS, AND WHAT SPECULATION DID NOT REACH. `steps_mixed` over `steps` + * says how often the load produces a step carrying both kinds of row; an agentic load produces + * them often enough that it is worth letting such a step draft. + * + * `decode_rows_unspeculated` is every decode row that took no draft, whatever the reason: + * the controller at depth 0, a request that may not speculate, a drafter with nothing to + * propose. It counts ROWS rather than any one reason, so it stays the answer to "how much of + * my decode is running unspeculated" whatever the current set of reasons is. */ + switch (plan_.phase) { + case RAD_PHASE_PREFILL: ++m_.steps_prefill; break; + case RAD_PHASE_MIXED: ++m_.steps_mixed; break; + default: ++m_.steps_decode; break; + } + for (const StepEntry& e : plan_.e) + if (!e.is_prefill && e.n_spec == 0) ++m_.decode_rows_unspeculated; + plan_.n_seq_decode = n_dec; + plan_.n_tok_decode = 0; + for (int64_t i = 0; i < n_dec; ++i) plan_.n_tok_decode += plan_.e[(size_t)i].n_tokens; + /* THE ROWS THE CARD'S ACCEPTANCE READS (advance.h), in the final order: each entry's token row + * of its first verified position, its first sampled row, and its draft count. Sampled rows + * go to the entries that produce a token, 1 + n_spec each, which is the order the builder + * writes out_ids in and the engine reads them back in. */ + { + int64_t k = 0; + int32_t row = 0; + for (StepEntry& e : plan_.e) { + e.dev_tok = (int32_t)(k + e.n_tokens - 1 - e.n_spec); + e.dev_out = e.produces_token ? row : -1; + e.dev_aux = e.n_spec; + if (e.produces_token) row += 1 + e.n_spec; + k += e.n_tokens; + } + } + /* DIAGNOSTIC, not a policy: RADIANCE_FORCE_MIXED=1 labels a pure-decode step MIXED, which is + * the one thing that changes about it -- every sequence still carries one token. It exists to + * ask whether the ops an architecture block issues for MIXED are correct at decode lengths, + * without needing a concurrent workload to produce a real mixed step. */ + static const bool force_mixed = [] { + const char* v = std::getenv("RADIANCE_FORCE_MIXED"); + const bool on = v && *v && *v != '0'; + /* SAID OUT LOUD. A diagnostic whose only evidence is the output it changes cannot be told + * apart from one that never took -- and "identical output" is exactly the result this + * flag is used to look for, so a silent no-op reads as a pass. */ + if (on) RAD_WARN("RADIANCE_FORCE_MIXED is set: every pure-decode step is labelled MIXED"); + return on; + }(); + if (force_mixed && plan_.phase == RAD_PHASE_DECODE) plan_.phase = RAD_PHASE_MIXED; + + step_start_ = std::chrono::steady_clock::now(); + const RadBatch* b = builder_.build(plan_, *kv_, step_); + if (!b) { + /* Staging failed. Nothing was computed, so nothing is committed and n_computed did not + * advance: the next step re-schedules the same chunks and the KV allocations already made + * cover them. Leaving the step OPEN would deadlock the engine on a commit that will never + * come, which is worse than losing a step. + * + * THE ONE THING THE RETRY CANNOT RE-SCHEDULE IS A RESTORE. An entry admitted off a + * checkpoint carried the slot to resume from, and that was consumed here; the next step + * would run the sequence on as if its recurrent state were in place. Such a request goes + * back to the queue and gives its hit back, so the next admission looks it up again. */ + for (StepEntry& e : plan_.e) { + SchedReq& s = *reqs_[(size_t)e.slot]; + s.entry = -1; + if (e.ckpt_restore < 0 || !s.req) continue; + undo_hit(s); + s.running = false; + s.req->state = ReqState::Waiting; + queue_erase(running_, s.slot); + queue_insert(waiting_, s.slot); + } + plan_.reset(); + step_open_ = false; + return nullptr; + } + ++step_; + step_open_ = true; + return b; +} + +/* ------------------------------------------------------------------ media */ +bool Scheduler::media_ready(SchedReq& s) { + bool ready = true; + for (mm::Placed& p : s.req->media->items) { + mm::Item& it = *p.item; + if (it.encoded) continue; + ready = false; + if (!it.queued) { + it.queued = true; + enc_want_.push_back(p.item); + } + } + return ready; +} + +bool Scheduler::encodes_pending() const { + std::lock_guard lk(mu_); + return !enc_want_.empty(); +} + +void Scheduler::take_encodes(std::vector>* out) { + std::lock_guard lk(mu_); + out->clear(); + out->swap(enc_want_); +} + +/* ------------------------------------------------------------------ the next step */ +void Scheduler::expect_draft(uint64_t id, int n) { + std::lock_guard lk(mu_); + auto it = by_id_.find(id); + if (it == by_id_.end()) return; + reqs_[(size_t)it->second]->draft_next = n > 0 ? n : 0; +} + +const RadBatch* Scheduler::step_next() { + std::lock_guard lk(mu_); + const RadBatch* b = step_next_locked(); + if (!b) + for (const StepEntry& e : plan_.e) + if (e.slot >= 0 && (size_t)e.slot < reqs_.size() && reqs_[(size_t)e.slot]) + reqs_[(size_t)e.slot]->draft_next = 0; + return b; +} + +const RadBatch* Scheduler::step_next_locked() { + if (!step_open_ || next_open_ || plan_.e.empty()) return nullptr; + /* An admission is a decision about the pool and the queue that the full step makes. */ + if (!waiting_.empty()) return nullptr; + + plan_next_.reset(); + for (const StepEntry& e : plan_.e) { + if (e.slot < 0 || (size_t)e.slot >= reqs_.size()) return nullptr; + SchedReq& s = *reqs_[(size_t)e.slot]; + if (!s.req || s.req->state != ReqState::Running || !s.running) return nullptr; + Request& r = *s.req; + /* A chunk in the middle of a prompt continues as a prefill, from where the host knows it + * is. And a grammar that cannot rewind decides, when this step commits, whether the next + * may speculate; one that can -- and a request with no grammar -- answers as it did. */ + if (!e.produces_token || !r.speculation_fixed) return nullptr; + + /* THE FURTHEST CONTEXT THE ROW CAN REACH: every position this step verifies committed, + * counted from where the host knows the sequence is -- the last commit -- and not from + * this step's own bound, which would add a window of slack every step it is issued + * ahead. The card's acceptance says where it really is; this is what the pool, the + * block tables and every host-side ceiling are sized for. */ + const int64_t ctx_up = r.n_computed + e.n_tokens; + const int32_t d = s.draft_next; + const int64_t want = 1 + d; + if (ctx_limit_ > 0 && ctx_up + want > ctx_limit_) return nullptr; + if (kv_->ensure(r.id, ctx_up + want) < 0) return nullptr; + + StepEntry n; + n.req = &r; + n.seq = r.id; + n.slot = e.slot; + n.card = e.card; + n.n_tokens = (int32_t)want; + n.ctx_len = (int32_t)ctx_up; + n.n_spec = d; + n.n_accepted = 1; /* the card's: StepSlot::n_acc */ + n.conv_cursor = s.conv_cursor; + n.draft = s.draft; /* published before this step commits (set_draft) */ + n.n_draft = d; + n.is_prefill = false; + n.produces_token = true; + n.dev = true; + plan_next_.e.push_back(n); + plan_next_.n_tok += want; + if (d > plan_next_.n_spec) plan_next_.n_spec = d; + } + plan_next_.phase = RAD_PHASE_DECODE; + plan_next_.n_seq_decode = (int64_t)plan_next_.e.size(); + plan_next_.n_tok_decode = plan_next_.n_tok; + { + int64_t k = 0; + int32_t row = 0; + for (StepEntry& e : plan_next_.e) { + e.dev_tok = (int32_t)(k + e.n_tokens - 1 - e.n_spec); + e.dev_out = row; + e.dev_aux = e.n_spec; + row += 1 + e.n_spec; + k += e.n_tokens; + } + } + const RadBatch* b = builder_.build(plan_next_, *kv_, step_); + if (!b) { plan_next_.reset(); return nullptr; } + for (size_t i = 0; i < plan_next_.e.size(); ++i) + reqs_[(size_t)plan_next_.e[i].slot]->entry_next = (int32_t)i; + next_open_ = true; + return b; +} + +void Scheduler::promote_next() { + std::lock_guard lk(mu_); + if (!next_open_) return; + std::swap(plan_, plan_next_); + plan_next_.reset(); + step_prefill_tok_ = 0; + step_decode_tok_ = 0; + for (size_t i = 0; i < plan_.e.size(); ++i) { + SchedReq& s = *reqs_[(size_t)plan_.e[i].slot]; + s.entry = (int32_t)i; + s.entry_next = -1; + s.draft_next = 0; + s.sched_tokens = plan_.e[i].n_tokens; + if (s.req) { s.req->n_draft = plan_.e[i].n_spec; s.req->draft = s.draft; } + } + ++m_.steps_decode; + ++m_.steps_ahead; + for (const StepEntry& e : plan_.e) + if (e.n_spec == 0) ++m_.decode_rows_unspeculated; + step_start_ = std::chrono::steady_clock::now(); + ++step_; + step_open_ = true; + next_open_ = false; +} + +/* ------------------------------------------------------------------ commit */ +int Scheduler::commit(const StepResult& res) { + std::lock_guard lk(mu_); + if (!step_open_) return RAD_E_STATE; + if (res.n_seq != (int)plan_.e.size()) { + RAD_ERR("commit of %d sequences against a step of %d", res.n_seq, (int)plan_.e.size()); + return RAD_E_INVAL; + } + step_open_ = false; + + const int32_t W = conv_window(); + + /* A MIXED STEP DOES NOT RUN THE CHUNKED PATH OVER A SEQUENCE THAT WAS ONLY DECODING, so the + * scratch beside its state is not invalidated here. + * + * The blocks issue the recurrent path over the decode rows of a mixed step and the chunked + * path over the prefill ones (RadBatch::n_seq_decode), so those rows leave exactly the replay + * factors a decode step leaves, and discarding them would throw away the rollback the next + * verify needs. Invalidation would only be correct if a mixed step were prefill-shaped for + * everyone in it: the chunked path commits the state directly and leaves no replay factors, + * so anything in the scratch would then describe tokens the state already had. + * + * The one thing that must stay true for that is the ordering: the recurrent path is issued + * over sequences [0, n_seq_decode) and nothing else, so a decode row that sorted into the + * prefill half would silently take the chunked path and leave stale factors behind it. That + * is what the sort in step() and its test are for. */ + for (int i = 0; i < res.n_seq; ++i) { + const StepEntry& e = plan_.e[(size_t)i]; + SchedReq& s = *reqs_[(size_t)e.slot]; + Request& r = *s.req; + if (r.state != ReqState::Running) { + /* Cancelled between step and commit. Its blocks were held until the device finished + * with them; that is now. Its SLOT may also be owed back, if the server reaped it in + * the same window -- the sweep at the end of this function does that, once every + * entry has been retired. */ + s.entry = -1; + /* Unless the drafter's snapshot still names it, or the next step carries it: the + * sweep below, or that step's commit, releases it once nothing does. */ + if (s.pending_free && !block_holds(r.id) && !(next_open_ && s.entry_next >= 0)) { + free_kv(s); + s.pending_free = false; + --n_deferred_; + } + continue; + } + + /* `ignore_eos` drops the token's termination and nothing else: max_tokens and the stop + * strings below still end the request. See Request::ignore_eos. */ + bool eos = res.eos && res.eos[i] && !r.ignore_eos; + + bool overflowed = false; + + /* THE SNAPSHOT THE ENGINE JUST TOOK IS NOW READABLE. Marking it here rather than at + * reservation is the difference between a checkpoint and a promise: reserve_checkpoint + * runs when the chunk is PLANNED, and a lookup between then and now would adopt a slot + * still holding the previous tenant's state. Stream ordering does the rest -- a later + * restore is enqueued on the same stream behind this save, so validity does not have to + * wait on the copy landing, only on it being issued. */ + if (e.ckpt_slot >= 0 && e.ckpt_tok >= 0 && pc_) + pc_->commit_checkpoint(r, (int64_t)e.ctx_len + e.ckpt_tok + 1); + + if (e.is_prefill) { + r.n_computed += e.n_tokens; + step_prefill_tok_ += e.n_tokens; + /* Once, when the prompt is fully placed: the admission accounting the usage block + * reports. `n_cached` is what the prefix cache supplied and is not recomputed here. */ + if (r.n_computed >= (int64_t)r.prompt.size()) + server::sink_prompt_stats(r.sink, (int32_t)r.prompt.size(), r.n_cached); + if (e.produces_token && res.token) { + if (!s.first_tok_us) s.first_tok_us = mono_us(); + r.output.push_back(res.token[i]); + overflowed = !server::sink_push(r.sink, res.token[i]); + /* The conv window absorbed this chunk; the cursor advances by one committed + * position, exactly as it does in decode. */ + s.conv_cursor = (int32_t)((s.conv_cursor + 1) % (W ? W : 1)); + } + } else { + int32_t a = res.n_accepted ? res.n_accepted[i] : 0; + if (a < 0) a = 0; + if (a > e.n_spec) a = e.n_spec; + /* A ROW ISSUED AHEAD was staged at the furthest context it could reach; it really + * continued from the committed end, which is where the host's sequence is. */ + const int64_t ctx0 = e.dev ? r.n_computed : (int64_t)e.ctx_len; + + /* PAGED KV rolls back: free the blocks past the accepted position, because the KV + * written for the rejected tokens is garbage a later step would attend to. + * + * LINEAR STATE DOES NOT. The recurrent state and the conv window have already absorbed + * the rejected tokens and there is nothing to undo: libr4d's conv update treats the + * state cache as a rolling window of width-1 + num_spec entries and reads at the slot + * the last accepted token left, so a rejection is a change of READ OFFSET rather than + * a recompute (spec §10). The two kinds roll back differently and conflating them is + * how you get a model that is subtly wrong only after a rejection. */ + int64_t valid = ctx0 + 1 + a; + /* NOT WHILE THE NEXT STEP IS WRITING PAST IT. A step already issued behind this one + * continues the sequence from `valid` and writes its keys and values there and on; + * its own commit rolls back to the end it reaches. */ + if (a < e.n_spec && !(next_open_ && s.entry_next >= 0)) { + int st = kv_->rollback(r.id, valid); + if (st < 0) RAD_WARN("kv rollback for request %llu: %s", + (unsigned long long)r.id, rad_strerror(st)); + } + s.conv_cursor = (int32_t)((s.conv_cursor + 1 + a) % (W ? W : 1)); + r.n_accepted = a; + + /* The accepted drafts FIRST and then the verified token, in generation order: the + * sink is a stream and a reordering here is a reordering in the client's text. + * + * AND THE BUDGET IS CHECKED PER TOKEN, because a verify step emits 1 + a of them at + * once. Pushing them all and trimming `output` afterwards leaves the SINK holding the + * overshoot -- the client has already been streamed tokens it did not ask for, so the + * same prompt at the same max_tokens comes back longer with speculation than without. + * The same tokens in the same order, just more of them, which is the one way greedy + * speculation is allowed to differ and should not. */ + int64_t room = r.max_tokens > 0 + ? r.max_tokens - (int64_t)r.output.size() : (int64_t)1 << 62; + /* AND THE CONTEXT BOUNDS IT WHATEVER max_tokens SAYS, including "no limit": a + * sequence may not grow past the positions this deployment can address. */ + if (ctx_limit_ > 0 && ctx_limit_ - s.seq_len() < room) room = ctx_limit_ - s.seq_len(); + auto emit = [&](int32_t t) { + if (room <= 0) return; + --room; + if (!s.first_tok_us) s.first_tok_us = mono_us(); + r.output.push_back(t); + if (!server::sink_push(r.sink, t)) overflowed = true; + }; + for (int32_t j = 0; j < a; ++j) emit(s.draft[j]); + if (res.token) emit(res.token[i]); + r.n_computed = valid; + step_decode_tok_ += 1 + a; + + if (e.n_spec > 0) { + draft_.observe(e.n_spec, a); + m_.draft_tokens += e.n_spec; + m_.draft_accepted += a; + } + } + s.n_draft = 0; + r.n_draft = 0; + s.entry = -1; + + /* A REQUEST THE NEXT STEP CARRIES FINISHES NOW AND KEEPS ITS BLOCKS: that step is writing + * them. Its commit finds the request no longer running and gives them back. */ + const bool carried = next_open_ && s.entry_next >= 0; + + /* Finish. The emit above already stops at max_tokens, so `output` cannot run past it -- + * the resize below is the belt to that braces, kept because a >= test that can only ever + * be == is the kind of thing a later change makes wrong quietly. */ + if (overflowed) { + /* The sink has already failed the request -- a consumer that far behind is gone -- + * so all that is left is to stop generating for it and give its blocks back. */ + close_request(s, ReqState::Failed, "sink_overflow", carried); + ++m_.failed; + completed_.push_back(r.id); + } else if (server::sink_cancelled(r.sink)) { + /* The client hung up. Spec §14: the blocks go back now rather than at the end of a + * generation nobody will read. */ + close_request(s, ReqState::Cancelled, "cancelled", carried); + ++m_.cancelled; + completed_.push_back(r.id); + } else if (r.max_tokens > 0 && (int64_t)r.output.size() >= r.max_tokens) { + r.output.resize((size_t)r.max_tokens); + close_request(s, ReqState::Finished, "length", carried); + ++m_.finished; + completed_.push_back(r.id); + } else if (ctx_limit_ > 0 && s.seq_len() >= ctx_limit_) { + /* The context is full. The same finish as max_tokens, because to the caller it is + * the same thing: the generation ran out of room. */ + close_request(s, ReqState::Finished, "length", carried); + ++m_.finished; + completed_.push_back(r.id); + } else if (eos) { + close_request(s, ReqState::Finished, "stop", carried); + ++m_.finished; + completed_.push_back(r.id); + } + } + + m_.prefill_tokens += step_prefill_tok_; + m_.decode_tokens += step_decode_tok_; + ++m_.steps; + + /* Every entry is retired now, so anything whose reap or free was deferred on THIS step is + * releasable, and so is anything deferred on the last drafter snapshot, which block_end() or + * serial_end() has cleared since. Every pass that named them was issued before this step's + * readback, which waited for the compute stream. */ + sweep_deferred(); + return RAD_OK; +} + +/* ------------------------------------------------------------------ the end of a step */ +/* THE STEP IS NOT OVER AT COMMIT, and timing it there is wrong by the whole draft pass. + * + * The drafter for the NEXT step runs after commit, because that is the first moment both of its + * inputs exist -- the token the sampler chose, and which drafted position it came from. Its rounds + * are real forward passes through the draft head. Timed at commit they fall between that commit + * and the next step(), a gap the engine loop charges to nothing at all: the reported step time + * comes out short by the draft pass and `decode_tps` -- which divides by the same interval -- + * comes out correspondingly high, which is the direction of error nobody reports. + * + * So the engine says when the iteration is genuinely finished and the accounting happens here. + * Separate from commit() rather than folded into it because they answer different questions: + * commit() retires a step's tokens, and this closes the engine's loop around it. A caller that + * only drives commit() -- the scheduler tests -- gets correct counters and no timing, which is + * the honest answer for a step that never ran on a device. + * + * THE RATE IS TOKENS OVER WALL TIME ACROSS A WINDOW, NOT AN AVERAGE OF STEP RATES. A step's + * interval is host time, and the host does not wait on the card at every step: a prefill chunk + * that samples nothing is committed while the card is still on it, and a later step's wait pays + * for it. Averaged as rates, those short intervals dominate -- a 2048-token chunk committed 70 ms + * after it began reads 30K tok/s -- while the step that absorbed the wait counts once, and the + * same skew reads decode high. Summed, all of the time is there: each kind's tokens and the wall + * time since the last step ended -- which also covers a step issued ahead, whose start precedes + * its predecessor's end, without counting that overlap twice -- or since this step began, when + * the engine sat idle in between; all three decayed with one time constant. + * + * A STEP WITH NO TOKENS OF A KIND STILL ADDS ITS TIME. Skipping it instead would freeze the rate + * at whatever it last was, so a server that prefilled once long ago would report that prefill + * throughput for the rest of its life, and a busy engine can read as an idle one. + * + * Not a device measurement: enabling per-op timing restores synchronisations that change the + * mover's slot supply, so a profiled run is not comparable anyway (spec §16). This is the number + * an operator can always have. */ +void Scheduler::step_finished() { + std::lock_guard lk(mu_); + if (step_start_.time_since_epoch().count() == 0) return; /* no step has run */ + + const auto step_end = std::chrono::steady_clock::now(); + const int64_t ns = + std::chrono::duration_cast(step_end - step_start_).count(); + m_.step_ns += ns; + if (plan_.phase == RAD_PHASE_DECODE) m_.step_ns_decode += ns; + + const auto from = step_start_ - last_step_at_ < std::chrono::milliseconds(500) + ? last_step_at_ : step_start_; + const double wall = std::chrono::duration(step_end - from).count(); + /* The window ages by the time that PASSED, idle included, so a phase that ended -- a prefill + * burst before a decode run -- leaves it at the window's own rate; only the busy part is + * added as time the tokens took. */ + const double aged = std::chrono::duration(step_end - last_step_at_).count(); + if (wall > 0) { + constexpr double kWindowS = 1.0; + const double f = std::exp(-aged / kWindowS); + tps_win_prefill_ = tps_win_prefill_ * f + (double)step_prefill_tok_; + tps_win_decode_ = tps_win_decode_ * f + (double)step_decode_tok_; + tps_win_time_ = tps_win_time_ * f + wall; + /* AT LEAST HALF A SECOND OF TIME UNDER THE RATE. After an idle spell the window starts + * over, and a burst's first chunk is committed as soon as it is issued: 2048 tokens over + * those few milliseconds is exactly the spike this replaces. Held to half a second the + * first reads are low instead, and the steady window (about a second) is not touched. */ + const double t = std::max(tps_win_time_, 0.5); + m_.prefill_tps = (float)(tps_win_prefill_ / t); + m_.decode_tps = (float)(tps_win_decode_ / t); + /* An exponential decay approaches zero and never arrives, and 7e-14 tok/s is a number + * nobody wants to read. Below a twentieth of a token a second it IS zero. */ + if (m_.prefill_tps < 0.05f) m_.prefill_tps = 0.0f; + if (m_.decode_tps < 0.05f) m_.decode_tps = 0.0f; + } + last_step_at_ = step_end; + /* So a second call, or one on a loop iteration that ran no step, charges nothing. */ + step_start_ = {}; +} + +/* ------------------------------------------------------------------ the serial drafter */ +/* Which sequences may take a serial draft after the step just committed, and what each of them + * needs. Called while plan() still describes that step, because everything here is a coordinate + * INTO it: the head reads the trunk's hidden states out of the buffer the step just filled. + * + * THE HEAD'S INDEXING, which StepPlan::tok_shift carries: head index i reads hidden(i) and the + * token at i + 1, writes its K and V at KV position i, and predicts i + 2. So after a step that + * committed `n_computed` positions, the newest index the head can serve is n_computed - 1 -- + * its hidden state is the last row the trunk produced and the token one on is the one the + * sampler just chose. That is draft round 1, and each round after it steps one position further out. + */ +int Scheduler::serial_begin(int* rounds, SerialRow* out, int max) { + std::lock_guard lk(mu_); + serial_.clear(); + if (!rounds || *rounds <= 0 || !out || max <= 0) return 0; + + /* MAY ANYTHING DRAFT AT ALL? The controller decides depth from measured acceptance, and 0 means + * it has turned drafting off. That is the whole test: a step carrying a prefill chunk is not + * itself a reason to refuse, because its decode rows still take the recurrent path. + * + * Neither answer stops the HISTORY pass. The head's own K and V have to be filled whether or + * not this particular step drafts -- a sequence three chunks into a long prompt is exactly the + * case where nothing can draft yet and the history is exactly what will be needed. */ + const int depth = draft_.next_depth(); + bool may_draft = depth > 0; + if (depth > 0 && *rounds > depth) *rounds = depth; + if (*rounds > RAD_SCHED_MAX_SPEC) *rounds = RAD_SCHED_MAX_SPEC; + + int n_draft_rows = 0; + int64_t cu = 0; /* this entry's first token in the step just run */ + for (size_t i = 0; i < plan_.e.size(); ++i) { + const StepEntry& e = plan_.e[i]; + const int64_t base = cu; + cu += e.n_tokens; + + if ((int)serial_.size() >= max) continue; + if (e.slot < 0 || (size_t)e.slot >= reqs_.size()) continue; + SchedReq& s = *reqs_[(size_t)e.slot]; + if (!s.req || s.req->state != ReqState::Running || !s.running) continue; + Request& r = *s.req; + + /* THE VERIFIED POSITIONS: the last 1 + n_spec of the entry. Round 1 continues from the + * last committed one, which is the first of them plus however many drafts were accepted + * -- a number the card has and the host does not yet, so the host bounds it by all of + * them. A chunk in the middle of a prompt verified nothing and continues nothing. */ + const int64_t vstart = (int64_t)e.ctx_len + e.n_tokens - 1 - e.n_spec; + const int64_t head_max = vstart + e.n_spec; + bool can_draft = may_draft && e.produces_token; + + /* THE LOOKAHEAD KV. Round k writes the head's K and V at position head + k - 1, which runs + * past the committed end, so the blocks have to exist before the round does -- for the + * furthest head acceptance could leave. They are the same blocks the next verify step + * writes the trunk's own K and V into, so this reservation is one the next step would + * have made anyway. + * + * A ROW THAT CANNOT HAVE THEM STILL OWES ITS HISTORY. The history pass writes positions + * the sequence already holds blocks for, so a refused lookahead is a reason not to draft + * and not a reason to skip the row: skipping it would leave the positions this step added + * unwritten in the head's layer for good. The same goes for a row too near the end of the + * context for its rounds, whose last positions do not exist. */ + if (can_draft && ctx_limit_ > 0 && head_max + *rounds > ctx_limit_) can_draft = false; + if (can_draft && kv_->ensure(r.id, head_max + *rounds) < 0) can_draft = false; + + /* THE HISTORY THIS STEP OWES, in two parts. Before the verified positions, the positions + * the step computed whose next token the host holds -- a prefill chunk's prompt -- from + * the watermark on, clamped to the rows this step produced: a prefix-cache hit adopts + * blocks whose head layer somebody else wrote, and there are no hidden states here to + * redo those from. Then the verified positions themselves, all 1 + n_spec of them, whose + * next tokens are the sampler's picks and exist only on the card. + * + * ALL OF THEM, AND THE LAST ROW IS DRAFT ROUND 1. The card fills the rows past the last + * committed position with that position again (advance.h, ADV_HIST), so the final row of + * the run always holds exactly round 1's inputs -- the committed position, the trunk's + * hidden state there and the token it chose after it -- and a drafting row takes its + * round-1 proposal from it (RadBatch::draft_out_ids) instead of from a pass of its own. + * + * THE VERIFIED PART HAS A FIXED SHAPE. The repeats write the committed position's key and + * value again, identical to the first; nothing past it is written, so no query can reach + * a rejected draft's state. */ + const int64_t owed_end = e.produces_token ? vstart : (int64_t)e.ctx_len + e.n_tokens; + int64_t hs = s.draft_filled > e.ctx_len ? s.draft_filled : (int64_t)e.ctx_len; + if (hs > owed_end) hs = owed_end; + const int64_t lead = owed_end - hs; + const int64_t verified = e.produces_token ? e.n_spec + 1 : 0; + const int64_t hist_n = lead + verified; + + if (!can_draft && hist_n <= 0) continue; /* nothing owed and nothing to draft */ + + SerialSeq m{}; + m.seq = r.id; + m.slot = e.slot; + m.card = e.card; + m.hist_row = (int32_t)(base + (hs - e.ctx_len)); + m.hist_n = (int32_t)hist_n; + m.hist_pos = hs; + m.dev = e.produces_token; + m.dev_tok = (int32_t)(base + (vstart - e.ctx_len)); + m.dev_out = e.dev_out; + m.lead = (int32_t)lead; + m.base_pos = head_max; + m.draft_idx = can_draft ? n_draft_rows : -1; + serial_.push_back(m); + + if (can_draft) { + out[n_draft_rows].seq = m.seq; + out[n_draft_rows].slot = m.slot; + out[n_draft_rows].card = m.card; + ++n_draft_rows; + } + } + return n_draft_rows; +} + +const RadBatch* Scheduler::serial_batch(int round, int step) { + /* RADIANCE_DEBUG_STAGE, below. Read before the lock so the timer covers the wait for it. */ + static const bool stg = std::getenv("RADIANCE_DEBUG_STAGE") != nullptr; + const auto t_stage0 = stg ? std::chrono::steady_clock::now() + : std::chrono::steady_clock::time_point{}; + std::lock_guard lk(mu_); + if (round < 0 || serial_.empty()) return nullptr; + /* Round 1 has no pass of its own: the history pass carries it (RadBatch::draft_out_ids). */ + if (round == 1) return nullptr; + + serial_plan_.reset(); + serial_plan_.phase = RAD_PHASE_DECODE; + /* Negative is the history pass; positive is draft round r. The sign is what the plugin reads + * to decide whether the pass ends in the lm_head (rad_runtime.h). */ + serial_plan_.draft_pass = round == 0 ? -1 : round; + serial_plan_.tok_shift = 1; /* the head's own indexing; see StepPlan::tok_shift */ + serial_plan_.e.reserve(serial_.size()); + + /* THE DRAFTING SEQUENCES FIRST, in draft order, then the ones that only owe history. Every + * round's rows are the drafting sequences in that order, and at depth 1 the history pass is a + * group's last pass -- so its first rows are where the advance that takes the last proposal + * (ADV_TAKE) reads them, whichever pass that is. */ + for (int part = 0; part < 2; ++part) + for (size_t i = 0; i < serial_.size(); ++i) { + const SerialSeq& m = serial_[i]; + if ((m.draft_idx >= 0) != (part == 0)) continue; + if (round == 0 && m.hist_n <= 0) continue; /* nothing owed for this sequence */ + if (round > 0 && m.draft_idx < 0) continue; /* history only: no token to propose */ + const Request* rq = serial_req(m); + /* Cannot happen while reap() defers on block_holds(), and this is what says so: a whole + * round skipped is a lost draft, which costs acceptance for one step and nothing else. */ + if (!rq) return nullptr; + + StepEntry e; + e.req = rq; + e.seq = m.seq; + e.slot = m.slot; + e.card = m.card; + e.n_tokens = round == 0 ? m.hist_n : 1; + /* A round's position is the card's; the host stages the furthest it can be, which is what + * every host-side ceiling reads. The history's are known here exactly. */ + e.ctx_len = (int32_t)(round == 0 ? m.hist_pos : m.base_pos + (round - 1)); + e.n_spec = 0; + /* One-based and constant: a head pass commits exactly the tokens it was handed. The head + * issues no linear-state op, so nothing reads it; it is set rather than left at a value + * the kernels cannot take. */ + e.n_accepted = 1; + e.conv_cursor = 0; + /* NO DRAFT ARRAY. A history row's tokens past its lead, and every round's token, are the + * card's (advance.h); token_at() stages a 0 in their place, and the positions before the + * lead are the prompt, which it stages exactly. */ + e.draft = nullptr; + e.n_draft = 0; + e.is_prefill = false; + e.produces_token = round > 0; + /* The history pass gathers the trunk's hidden states, a whole run of them. Later rounds + * read the head's own output, which it left in the same buffer. */ + e.hidden_row = round == 0 ? m.hist_row : -1; + e.draft_out = round == 0 && m.draft_idx >= 0; + e.dev = m.dev; + e.dev_tok = m.dev_tok; + e.dev_out = m.dev_out; + e.dev_aux = round == 0 ? m.lead : 0; + serial_plan_.e.push_back(e); + serial_plan_.n_tok += e.n_tokens; + } + if (serial_plan_.e.empty()) return nullptr; + + /* RADIANCE_DEBUG_STAGE: THE BATCH HALF, AND IT IS NOT THE COST. Splits a draft pass into the + * plan loop above and `builder_.build`, which stages the block tables and slots, and reports + * the average of each. Both are small fractions of what a pass spends ISSUING it + * (engine_draft.cpp has the five-way split): staging a draft batch is effectively free, and + * the block-table rectangle it copies -- sized for the worst step, not this one -- is not on + * any critical path worth shrinking. + * + * Off by default and it costs two clock reads when it is on, so it can stay. */ + if (!stg) return builder_.build(serial_plan_, *kv_, step); + + static double acc_plan = 0.0, acc_build = 0.0; + static long n_calls = 0; + const auto t1 = std::chrono::steady_clock::now(); + const RadBatch* b = builder_.build(serial_plan_, *kv_, step); + const auto t2 = std::chrono::steady_clock::now(); + acc_plan += std::chrono::duration(t1 - t_stage0).count(); + acc_build += std::chrono::duration(t2 - t1).count(); + if (++n_calls % 400 == 0) + std::fprintf(stderr, "D stage: %ld draft batches, plan %.1f us, build %.1f us a call\n", + n_calls, acc_plan / (double)n_calls, acc_build / (double)n_calls); + return b; +} + +/* The watermark moves to what actually ran, and it is read off the COMMITTED sequence: the history + * pass wrote the head's K and V at the last committed index, n_computed - 1, from the trunk's own + * hidden state and the committed token, so after it the head's history is exact up to + * n_computed. The rounds past it write SPECULATIVELY -- correct only for the drafts that turn out + * to be accepted -- and are deliberately not counted: redoing them next step costs one head pass + * over a couple of tokens and removes the whole question. A row that only owed history is exact + * up to where the history reached; that is n_computed too when it covered the verified positions, + * and its host-known end when it did not. */ +void Scheduler::serial_end(int rounds_done) { + std::lock_guard lk(mu_); + for (const SerialSeq& m : serial_) { + if (m.slot < 0 || (size_t)m.slot >= reqs_.size()) continue; + SchedReq& s = *reqs_[(size_t)m.slot]; + if (!s.req || s.req->id != m.seq) continue; + const int64_t filled = m.dev ? s.req->n_computed + : m.hist_pos + m.hist_n; + const bool counts = m.dev ? (rounds_done >= 1 || m.draft_idx < 0) : true; + if (counts && filled > s.draft_filled) s.draft_filled = filled; + } + /* THE SNAPSHOT ENDS HERE. Every pass that names these rows has been built, so nothing reads + * them again, and holding them any longer would keep deferring the release of a request that + * was cancelled or reaped while the rounds ran. */ + serial_.clear(); +} + +/* ------------------------------------------------------------------- the block drafter */ +/* Which sequences the drafter runs over after the step just committed, and which of those may also + * propose. Called while plan() still describes that step, because the context pass MIRRORS it. + * + * The mirror is exact, including a verify step's rejected suffix. That is not sloppiness, it is + * what keeps the pass free of coordinates: the drafter reads the trunk's tapped hidden states + * positionally out of a buffer of its own, so batch row i must be buffer row i, and trimming + * one entry would slide every entry after it. The rejected positions are all inside [n_computed, + * n_computed + block), which the query pass overwrites before anything reads it -- and the one + * ensure() below covers them, because n_computed + block is at least the trunk step's own end. + */ +int Scheduler::block_begin(int block, int depth, int window, int32_t mask, BlockRow* out, int max) { + std::lock_guard lk(mu_); + block_.clear(); + block_len_ = 0; + block_depth_ = 0; + if (block < 2 || depth <= 0 || depth > block || !out || max <= 0) return 0; + block_len_ = (int32_t)block; + block_depth_ = (int32_t)depth; + block_mask_.assign((size_t)(block - 1), mask); + + /* NOT the drafter's declared `depth` above -- this is how many tokens the draft POLICY wants + * out of this step, which is zero when it has backed off. The two were both called `depth`. */ + const bool may_draft = draft_.next_depth() > 0; + /* THE QUERY PASS IS `block` TOKENS A DRAFTING SEQUENCE, and the builder's staging arrays are + * sized at max_tok. A decode step is one token a sequence, so nothing before this could ever + * put more rows in a batch than sequences -- this pass can, and eight rows a sequence against + * a small token budget is exactly the shape that would run off the end of h_tok. */ + if ((int64_t)max * block > cfg_.max_tok) max = (int)(cfg_.max_tok / block); + if (max <= 0) return 0; + + int n_draft_rows = 0; + for (size_t i = 0; i < plan_.e.size(); ++i) { + const StepEntry& e = plan_.e[i]; + + BlockSeq d{}; + d.seq = e.seq; + d.slot = e.slot; + d.card = e.card; + d.ctx_len = e.ctx_len; + d.n_tokens = e.n_tokens; + + /* EVERY ENTRY OF THE TRUNK STEP GETS A ROW, IN ORDER, whether or not its sequence is + * still running. The drafter reads the trunk's hidden states positionally out of a buffer + * of its own, so the context pass's row i has to be the trunk's row i; a sequence the + * commit just finished that was left out would put every sequence after it onto its + * neighbour's hidden states. It stays as a placeholder row that stores nothing -- see + * BlockSeq::mirror. */ + SchedReq* sp = (e.slot >= 0 && (size_t)e.slot < reqs_.size()) ? reqs_[(size_t)e.slot].get() + : nullptr; + if (!sp || !sp->req || sp->req->id != e.seq || sp->req->state != ReqState::Running || + !sp->running) { + d.mirror = true; + block_.push_back(d); + continue; + } + SchedReq& s = *sp; + Request& r = *s.req; + d.base_pos = r.n_computed; + + /* MAY IT PROPOSE? It needs a token to anchor on -- which is the one the sampler just + * chose, so the entry has to have produced one -- and it needs a draft cache that covers + * what the block's attention will read. The high end is this step's own context pass, + * which has not run yet and is about to cover everything up to the trunk's end. The low + * end is draft_lo, which is non-zero only after a prefix-cache hit THAT LEFT A HOLE. */ + const bool have_tok = e.produces_token && !r.output.empty() && r.n_computed >= 1; + /* Where this sequence's draft cache will start once the context pass about to run has + * written: its own floor, or -- for a sequence that has never had one -- wherever this + * step's first row sits, which is 0 for an ordinary prefill and the hit length for a + * prefix-cache hit. The binding query row is the LOWEST one, at n_computed, and it reads + * back to n_computed - window + 1. */ + const int64_t lo = draft_floor(s, (int64_t)e.ctx_len); + const bool reach = lo <= 0 ? true + : (window > 0 && r.n_computed - window + 1 >= lo); + + /* RADIANCE_DEBUG_DRAFT: WHICH GATE DECLINED. A drafter that quietly stops proposing reads + * downstream as "acceptance collapsed" -- the accept% metric is conditional on having + * drafted at all, so it stays healthy while tok/step falls to 1. No counter distinguishes + * the two, and nothing else tells the five gates below apart. */ + const bool ok_room = n_draft_rows < max; + /* The query block writes positions n_computed .. n_computed + block - 1, and none of them + * may be at or past the end of the context. */ + const bool ok_ctx = ctx_limit_ <= 0 || r.n_computed + block <= ctx_limit_; + const bool ok_kv = ok_room && ok_ctx && kv_->ensure(r.id, r.n_computed + block) >= 0; + static const bool dbg = [] { const char* v = std::getenv("RADIANCE_DEBUG_DRAFT"); + return v && *v && *v != '0'; }(); + if (dbg) { + static int64_t n_call = 0, n_depth = 0, n_tok = 0, n_reach = 0, n_room = 0, n_kv = 0, n_ok = 0; + ++n_call; + if (!may_draft) ++n_depth; + else if (!have_tok) ++n_tok; + else if (!reach) ++n_reach; + else if (!ok_room) ++n_room; + else if (!ok_kv) ++n_kv; + else ++n_ok; + if ((n_call % 256) == 0) + RAD_INFO("draft gates over %lld asks: ok %lld | declined depth %lld tok %lld " + "reach %lld room %lld kv %lld (window %d, floor %lld, ctx_len %lld)", + (long long)n_call, (long long)n_ok, (long long)n_depth, (long long)n_tok, + (long long)n_reach, (long long)n_room, (long long)n_kv, + window, (long long)lo, (long long)e.ctx_len); + } + if (may_draft && have_tok && reach && ok_kv) { + d.can_draft = true; + out[n_draft_rows].seq = d.seq; + out[n_draft_rows].slot = d.slot; + out[n_draft_rows].card = d.card; + ++n_draft_rows; + } + block_.push_back(d); + } + return n_draft_rows; +} + +const Request* Scheduler::block_req(const BlockSeq& d) const { return live_req(d.slot, d.seq); } +const Request* Scheduler::serial_req(const SerialSeq& m) const { return live_req(m.slot, m.seq); } + +const RadBatch* Scheduler::block_context(int step) { + std::lock_guard lk(mu_); + if (block_.empty()) return nullptr; + + block_plan_.reset(); + block_plan_.phase = RAD_PHASE_DECODE; + block_plan_.draft_pass = -1; /* the sign is what the plugin reads (rad_runtime.h) */ + block_plan_.e.reserve(block_.size()); + + for (const BlockSeq& d : block_) { + const Request* rq = block_req(d); + /* Cannot happen while reap() defers on block_holds(), and this is what says so: a whole + * round skipped is a lost draft, which costs acceptance for one step and nothing else. + * A placeholder row may have lost its Request before block_begin ran -- the server reaps + * a finished request as soon as its sink is done -- and needs none: this pass reads no + * token ids, and its KV is gone, so the builder stages it as padding. */ + if (!rq && !d.mirror) return nullptr; + StepEntry e; + e.req = rq; + e.seq = d.seq; + e.slot = d.slot; + e.card = d.card; + e.n_tokens = d.n_tokens; + e.ctx_len = d.ctx_len; + e.n_spec = 0; + e.n_accepted = 1; /* one-based; nothing in this pass reads it */ + /* The context pass touches no token ids at all -- it starts from the tapped hidden states + * -- so there is nothing to shift and no draft to reach into. */ + e.produces_token = false; + block_plan_.e.push_back(e); + block_plan_.n_tok += e.n_tokens; + } + if (block_plan_.e.empty()) return nullptr; + return builder_.build(block_plan_, *kv_, step); +} + +/* One entry a drafting sequence, `block` tokens: the anchor at the sequence's next position, then + * `block - 1` masks. `out_ids` names THE LAST `depth` ROWS. + * + * AT block = depth + 1 that is rows 1..depth, the mask rows: the anchor row predicts nothing and + * each mask row predicts the token at ITS OWN position (vLLM's _prepare_dflash_inputs_kernel: + * is_sample = query_off >= 1, sample_pos = query_pos). AT block = depth it is every row, anchor + * included, and each predicts the token AFTER it -- the ordinary next-token relation, which is + * what a drafter whose reference reads `hidden[:, -block_size:, :]` was trained in. One rule, + * both conventions; rad_builder.h argues why the plugin is what states which. */ +const RadBatch* Scheduler::block_query(int step) { + std::lock_guard lk(mu_); + if (block_.empty() || block_len_ < 2 || block_depth_ <= 0) return nullptr; + const int32_t block = block_len_, steps = block - 1, depth = block_depth_; + + block_plan_.reset(); + block_plan_.phase = RAD_PHASE_DECODE; + block_plan_.draft_pass = 1; + block_plan_.tok_shift = 0; /* the anchor sits at its own row; see StepPlan */ + block_plan_.e.reserve(block_.size()); + + int32_t row = 0; + for (const BlockSeq& d : block_) { + if (!d.can_draft) continue; + const Request* rq = block_req(d); + if (!rq) return nullptr; /* see block_context */ + StepEntry e; + e.req = rq; + e.seq = d.seq; + e.slot = d.slot; + e.card = d.card; + e.n_tokens = block; + e.ctx_len = (int32_t)d.base_pos; + e.n_spec = 0; + e.n_accepted = 1; + /* token_at() walks prompt ++ output ++ draft: index base_pos is the token the sampler just + * chose (the anchor) and everything past it falls into the mask array. */ + e.draft = block_mask_.data(); + e.n_draft = steps; + e.produces_token = false; + /* THE LAST `depth` ROWS OF THE BLOCK. At block = depth + 1 that skips the anchor; at + * block = depth it starts on it, because there the anchor row is a predicting row. + * + * RADIANCE_DFLASH_ANCHOR=1 slides the head one row EARLIER, onto the anchor, and so does + * nothing at block = depth where it already sits there. The anchor is an ordinary row: a + * real token, embedded, with the whole context behind it -- so its hidden state predicts + * the token at base_pos + 1, which is exactly what draft[0] is verified against. A healthy + * backbone therefore accepts at position 0 most of the time, and a broken one does not. It + * is the same measurement the hazard counter already makes, pointed at a row whose answer + * is known. Debug-only: it drafts `depth` tokens for `depth` positions starting one too + * early, so positions 1.. are deliberately misaligned and only position 0 means anything. */ + static const bool anchor_head = std::getenv("RADIANCE_DFLASH_ANCHOR") != nullptr; + int32_t head0 = block - depth; + if (anchor_head && head0 > 0) head0 = 0; + e.hidden_row = row + head0; + e.hidden_n = depth; + block_plan_.e.push_back(e); + block_plan_.n_tok += block; + row += block; + } + if (block_plan_.e.empty()) return nullptr; + return builder_.build(block_plan_, *kv_, step); +} + +/* The filled range moves over what the context pass wrote. The query pass's own K and V are + * SPECULATIVE -- correct only for the positions that turn out to be accepted -- and are + * deliberately not counted: the next step's context pass rewrites them from the trunk's real + * hidden states, which is one pass over a handful of rows and removes the whole question. */ +void Scheduler::block_end() { + std::lock_guard lk(mu_); + for (const BlockSeq& d : block_) { + if (d.mirror) continue; /* finished; it has no draft cache to track */ + if (d.slot < 0 || (size_t)d.slot >= reqs_.size() || !reqs_[(size_t)d.slot]) continue; + SchedReq& s = *reqs_[(size_t)d.slot]; + if (!s.req || s.req->id != d.seq) continue; + if (s.draft_hi == 0 && s.draft_lo == 0) s.draft_lo = draft_floor(s, d.ctx_len); + const int64_t hi = (int64_t)d.ctx_len + d.n_tokens; + if (hi > s.draft_hi) s.draft_hi = hi; + } + /* THE SNAPSHOT ENDS HERE. Both passes are built, so nothing reads these rows again, and + * holding them any longer would keep deferring the release of a request that was cancelled + * or reaped while the passes ran. */ + block_.clear(); +} + +int32_t Scheduler::conv_window() const { + int32_t W = 1; + for (const KVGroupInfo& g : prog_->kv_groups) + if (g.decl.kind == RAD_KV_CONV && g.decl.conv_width > 0) + W = (int32_t)(g.decl.conv_width - 1 + (cfg_.n_spec > 0 ? cfg_.n_spec : 0) + 1); + return W; +} + +/* ------------------------------------------------------------------ metrics */ +SchedMetrics Scheduler::metrics() const { + std::lock_guard lk(mu_); + return metrics_locked(); +} + +void Scheduler::publish(bool idle) { + const int64_t now = mono_us(); + if (idle && now - pub_at_us_ < 20000) return; + { + std::lock_guard lk(mu_); + scratch_m_ = metrics_locked(); + scratch_reqs_.resize(reqs_.size()); + scratch_reqs_.resize((size_t)requests_locked(scratch_reqs_.data(), (int)scratch_reqs_.size())); + } + if (!pub_mu_.try_lock()) return; + pub_m_ = scratch_m_; + pub_reqs_.swap(scratch_reqs_); + pub_mu_.unlock(); + pub_at_us_ = now; +} + +SchedMetrics Scheduler::observed_metrics() const { + std::lock_guard lk(pub_mu_); + return pub_m_; +} + +int Scheduler::observed_requests(ReqStat* out, int max) const { + std::lock_guard lk(pub_mu_); + const int n = std::min(max, (int)pub_reqs_.size()); + std::copy(pub_reqs_.begin(), pub_reqs_.begin() + n, out); + return n; +} + +SchedMetrics Scheduler::metrics_locked() const { + SchedMetrics m = m_; + m.step = step_; + m.running = (int64_t)running_.size(); + m.queue_depth = (int64_t)waiting_.size(); + m.preempted_waiting = 0; + for (int32_t slot : waiting_) + if (reqs_[(size_t)slot]->req->state == ReqState::Preempted) ++m.preempted_waiting; + + /* AND AN IDLE ENGINE RUNS NO STEPS AT ALL, so the window never moves and the last rate would + * stand forever. Decayed on the way out rather than mutated in place: the stored window is a + * property of the steps that ran, and this is the honest reading of "tokens a second over the + * recent past" when the recent past contains no tokens -- to 37% after half a second of + * silence, to nothing after a few. + * + * NOT WHILE A STEP IS OPEN: a 2048-token prefill chunk runs for a third of a second, and a + * read halfway through it is not a read of an idle engine. */ + const bool open = step_start_.time_since_epoch().count() != 0; + const double idle = open ? 0.0 + : std::chrono::duration(std::chrono::steady_clock::now() - last_step_at_).count(); + if (idle > 0.05) { + const float f = (float)std::exp(-idle / 0.5); + m.prefill_tps *= f; + m.decode_tps *= f; + if (m.prefill_tps < 0.05f) m.prefill_tps = 0.0f; + if (m.decode_tps < 0.05f) m.decode_tps = 0.0f; + } + + + const std::vector& gs = prog_->kv_groups; + m.n_kv_groups = (int)gs.size(); + if (m.n_kv_groups > RAD_SCHED_MAX_KV_GROUPS) m.n_kv_groups = RAD_SCHED_MAX_KV_GROUPS; + for (int i = 0; i < m.n_kv_groups; ++i) { + /* AGAINST THE CARVE AND WHAT IS HELD OF IT, not against the live mark. An elastic pool + * grows back on demand, so a block it has released is not occupied and is not + * unavailable; counting it as either makes an idle server read almost full and makes + * every decision downstream that watches kv_util read the pool's own arbitration as + * pressure from the workload. */ + const int64_t tot = kv_->total_blocks(i); + const int64_t fr = tot - kv_->held_blocks(i); + m.kv[i].name = gs[(size_t)i].name.c_str(); + m.kv[i].blocks_total = tot; + m.kv[i].blocks_free = fr; + m.kv[i].utilisation = tot > 0 ? (float)(1.0 - (double)fr / (double)tot) : 0.0f; + m.kv[i].block_tokens = kv_->block_tokens(i); + m.kv[i].bytes_total = kv_->pool_bytes(i); + m.kv[i].bytes_used = kv_->pool_bytes_used(i); + m.kv[i].bytes_carved = kv_->pool_bytes_carved(i); + } + + if (pc_) { m.prefix_evictions = pc_->evictions(); + m.prefix_ckpt_evictions = pc_->ckpt_evictions(); + m.prefix_held_tokens = pc_->held_tokens(); } + m.attn_hit_rate = m.prompt_tokens + ? (float)((double)m.attn_cached_tokens / (double)m.prompt_tokens) : 0.0f; + m.linear_hit_rate = m.prompt_tokens + ? (float)((double)m.linear_cached_tokens / (double)m.prompt_tokens) : 0.0f; + m.draft_acceptance = draft_.acceptance(); + m.draft_depth = draft_.next_depth(); + /* THE LOOP BOUND IS THE ARRAY'S OWN EXTENT, not a constant that happens to equal it. Clamping + * against RAD_SCHED_MAX_SPEC is correct -- depth_seen() is capped at it and both arrays are + * that long -- but the bound and the extent merely being the same number leaves gcc unable to + * rule out the boundary index through the inlined accessors, which guard with + * `j < RAD_SCHED_MAX_SPEC ? reach_[j] : 0`, and it warns. Writing the cap as the extent makes + * the two provably the same rather than coincidentally equal. */ + const int kPos = (int)(sizeof m.draft_pos_reached / sizeof m.draft_pos_reached[0]); + m.draft_depth_seen = draft_.depth_seen(); + if (m.draft_depth_seen > kPos) m.draft_depth_seen = kPos; + for (int j = 0; j < m.draft_depth_seen && j < kPos; ++j) { + m.draft_pos_reached [j] = draft_.reached(j); + m.draft_pos_accepted[j] = draft_.hits(j); + } + return m; +} + +} /* namespace rad */ diff --git a/core/sched/scheduler.h b/core/sched/scheduler.h new file mode 100644 index 00000000..e07f4b24 --- /dev/null +++ b/core/sched/scheduler.h @@ -0,0 +1,676 @@ +/* scheduler.h -- continuous batching, chunked prefill, a priority queue, preemption by recompute. + * ONE scheduler decision per step, producing ONE RadBatch (spec §7.1). + * + * Host time spent here is time the GPU spends idle, so this component is written to be cheap and + * to build things once. Everything on the step path comes out of a pool sized at max_tok / + * max_seqs; the only allocation the scheduler performs is on arrival and completion, which are + * the HTTP thread's problem and not the step's. + * + * Two things it owns that vLLM's does not: + * + * - CHUNK BOUNDARIES, and it uses that. A prefill chunk splits at a linear-state checkpoint + * interval, so a checkpoint is always WRITTEN rather than landing wherever a step happened to + * end. vLLM writes one only when a step's end coincides with a boundary, which is why a + * checkpoint landing in request-unique tokens silently drops linear caching to zero. The cost + * of doing it this way is an occasional short chunk; the benefit is that hit rate is a + * property of the workload rather than of scheduling luck (§7.3). + * + * - DRAFT DEPTH, controlled against measured acceptance (draft.h, §10). + */ +#pragma once +#include "batch.h" +#include "draft.h" +#include "metrics.h" + +#include +#include +#include +#include + +namespace rad { + +/* The scheduler's own per-request state. Request (rad_core.h) is shared across components and + * frozen; anything only the scheduler needs lives here, so adding a scheduling concept never + * touches a struct three other components read. */ +struct SchedReq { + std::unique_ptr req; + uint64_t arrival = 0; /* monotonic; the tiebreak below priority, and what makes a + * preempted request re-enter AHEAD of everything admitted after + * it rather than at the back of the queue */ + int32_t slot = -1; + /* THE CARD'S INDEX FOR THIS SEQUENCE: which StepSlot the advance reads and writes (advance.h), + * and so the sequence identity a batch carries. It is NOT `slot`. A slot is taken on arrival, + * so a queue behind the admission limit -- or a burst arriving while the last one's requests + * are still held for their final commit -- numbers slots past max_seqs, and the card has + * max_seqs StepSlots. The card index is taken on admission from a pool of exactly that many + * and given back with the sequence's KV (free_kv, preempt_back), so it lives as long as any + * step in flight can still name it and never longer. */ + int32_t card = -1; + bool running = false; + + /* WALL CLOCK, for the live request table. `arrival` above is a monotonic COUNTER -- it + * orders the queue and cannot say how long anything has been in it. */ + int64_t arrived_us = 0; + int64_t first_tok_us = 0; /* 0 until the first output token: this request's TTFT */ + + /* The drafter's proposal for the next step, and the conv-window read cursor a rejection + * moves rather than rolls back (§10). */ + int32_t draft[RAD_SCHED_MAX_SPEC] = {}; + int32_t n_draft = 0; + int32_t conv_cursor = 0; + + /* HOW MUCH OF A SERIAL DRAFTER`S OWN ATTENTION HISTORY IS VALID: positions [0, draft_filled) + * of the head`s layer hold K and V computed from the tokens the sequence actually has. The + * head attends to its own layer and nothing else in the engine writes it -- a prefill fills + * the trunk`s layers and leaves the head`s untouched -- so the drafter runs a history pass + * over whatever the last step added before it drafts. Zero on admission and on preemption, + * which is what makes a recomputed sequence refill it rather than trust a stale watermark. */ + int64_t draft_filled = 0; + + /* THE RANGE OF A BLOCK DRAFTER'S OWN KV CACHE THAT HOLDS REAL K AND V, as [draft_lo, + * draft_hi). Two numbers rather than a serial head's one because the low end CAN move: such a + * drafter has a KV group of its own, and whether a hit leaves that group short depends on + * whether prefix.cpp caches it -- see hit_holes_draft_. A WINDOWED drafter's group is skipped + * (a hit's blocks do not describe a cache whose floor moves), so a sequence that hits at + * position P has trunk K and V from 0 and draft K and V only from P, and drafting waits until + * the drafter's window has slid past P rather than attending to blocks nobody wrote. + * + * A FULL-ATTENTION DRAFTER'S GROUP IS CACHED LIKE THE TRUNK'S and the floor stays 0. Treating + * one as windowed disables drafting outright: a windowless drafter has no window to slide, so + * "wait until the window has passed P" is a condition that can never come true, and a workload + * that hits the prefix cache on every turn would then never draft again. + * Both zero on admission and on preemption, which is what makes a recomputed sequence refill + * rather than trust a stale watermark. */ + int64_t draft_lo = 0; + int64_t draft_hi = 0; + + /* EVERY PIECE OF DRAFTER STATE THAT DESCRIBES THE SEQUENCE IN THIS SLOT, cleared together. + * + * A slot is RECYCLED: add() takes one off `free_slots_` and the SchedReq in it is the last + * request's object, so anything not reset here is inherited by a sequence that has nothing to + * do with it. Both watermarks above say "zero on admission and on preemption", and a list of + * fields spelled out at each call site is what lets one of them go unreset; hence one function, + * called from both. + * + * WHAT A SURVIVING WATERMARK COSTS. `draft_filled` carried into the next request at the + * previous one's total length makes its prefill compute `hs = max(draft_filled, ctx_len)` = + * the stale watermark, `he` clamps up to meet it, and the history pass comes out EMPTY -- so + * the MTP head's layer of the attention cache is never written for the whole prompt and the + * head drafts against whatever the pool last held. The drafts are then wrong, so acceptance + * moves, so the committed lengths move, so the arithmetic of every later step moves: the same + * greedy prompt yields a different completion per request, reproducible request-for-request + * across processes, and only ever with speculation on. */ + void drafter_reset() { + n_draft = 0; + draft_next = 0; + conv_cursor = 0; + draft_filled = 0; + draft_lo = 0; + draft_hi = 0; + } + + int32_t sched_tokens = 0; /* tokens given to this request in the current step */ + int32_t entry = -1; /* its index in the current StepPlan, or -1 */ + /* Its index in the NEXT step, already issued while this one runs (step_next), or -1; and the + * drafts the drafter issued for it, which that step verifies. */ + int32_t entry_next = -1; + int32_t draft_next = 0; + + /* Cancelled while its tokens were in the step the device is still running, or while a + * drafter's snapshot still names it. Its blocks are released at commit rather than now, + * because handing a block to another sequence while a kernel is still writing it is a data + * race whose symptom is one sequence's KV appearing in another's attention -- and it would + * present as a model quality problem. A drafter pass built after the free would be worse + * still: its block-table row is all -1 with a non-zero length, and attention reads block -1, + * which is below the layer's region of the pool. */ + bool pending_free = false; + /* REAPED WHILE ITS TOKENS WERE IN THE STEP THE DEVICE IS STILL RUNNING, which is the same + * window `pending_free` covers and a strictly worse thing to get wrong. The server reaps a + * generation as soon as its sink is finished, and cancelling a request finishes the sink + * immediately -- so a client that disconnects mid-decode has its Request destroyed and its + * slot handed back while commit() still holds a StepEntry pointing at that slot. commit() then + * dereferences a null `req`, or worse, finds the slot re-admitted and commits one client's + * tokens into another's output. The release is deferred to commit instead. */ + bool reap_pending = false; + int64_t pending_ckpt = -1; /* absolute position this step's chunk checkpoints at */ + + /* The checkpoint the linear state should be SEEDED from on admission. Neither Request nor + * KVManager::ensure carries it, so the scheduler holds the answer here and hands it to the + * sequence's first entry as StepEntry::ckpt_restore. + * + * NEVER HELD ACROSS A STEP. A checkpoint slot is only the cache's until the cache retires it, + * and between two steps the retention policy, another admission's reservation or an idle + * tier can retire it, reallocate it and save a different sequence into it -- nothing pins it. + * So an admission that fails after the lookup gives the hit back (admit_one) and the next + * attempt looks it up again, rather than restoring whatever the slot holds by then. */ + int32_t ckpt_src = -1; + + /* The prefix hit this admission attempt found, in tokens, and whether its accounting is still + * owed. Counted once, when the admission SUCCEEDS: a request at the head of the queue that + * does not fit is retried every step, and counting each attempt would inflate the prompt and + * hit totals by however long it waited. */ + int32_t hit_attn = 0; + bool hit_owed = false; + + /* The whole sequence is prompt ++ output; n_computed indexes into it. */ + int64_t seq_len() const { + return (int64_t)req->prompt.size() + (int64_t)req->output.size(); + } +}; + +class Scheduler { +public: + /* What the sampler hands back after a step. The scheduler needs three numbers per sequence and + * no logits: how many drafted tokens survived, the token sampled at the accepted position, and + * whether the sequence ended. Everything else is the sampler's business. */ + struct StepResult { + int n_seq = 0; + const int32_t* n_accepted = nullptr; /* [n_seq] drafted tokens accepted, 0..n_spec */ + const int32_t* token = nullptr; /* [n_seq] token sampled at the accepted position */ + const uint8_t* eos = nullptr; /* [n_seq] 1 when the sequence ended */ + }; + + /* `geo` is the already-resolved chunk geometry. The engine resolves it once and passes it, + * because PrefixCache::configure needs the checkpoint interval out of it and runs first; + * pass nullptr to resolve one here instead. */ + int init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCache* pc, + const std::vector& ranks, + const ChunkGeometry* geo = nullptr); + + /* The batch the last build produced for one rank; see BatchBuilder::batch_for. */ + const RadBatch* batch_for(int rank) const { return builder_.batch_for(rank); } + /* The advance's view of that build on one rank; see BatchBuilder::advance_args. */ + AdvanceArgs advance_args(int rank) const { return builder_.advance_args(rank); } + void fini(); + + /* ---------------------------------------------------------- off the step path */ + int add(std::unique_ptr r); + /* `n` requests under one hold of the queue lock, each accepted or refused as add() would, with + * its result in rc[i]. For the sequences of one API request, which have to reach the same + * step. */ + void add_all(std::unique_ptr* rs, size_t n, int* rc); + /* Cancellation propagates to the scheduler and frees blocks IMMEDIATELY rather than at + * completion (spec §14). A cancelled request holding its blocks until the step that would + * have finished it is a pool that shrinks under exactly the load that cancels. */ + int cancel(uint64_t id); + Request* find(uint64_t id); + + /* Requests that reached a terminal state since the last call, oldest first, SWAPPED OUT under + * the lock into `out` (whose old contents are discarded). The engine drains this to drop its + * per-request sampler state; it is the only consumer. The server does not read it -- it + * learns of a terminal request through the sink and calls reap(), which is what finally + * releases the Request object. + * + * A swap rather than a reference: an HTTP thread's cancel() appends to this list under the + * lock, and a caller walking a reference to it without the lock walks a vector another thread + * may be reallocating. Handing the same vector back and forth also keeps both capacities, so + * a steady state allocates nothing. */ + void take_completed(std::vector* out); + int reap(uint64_t id); + + /* ---------------------------------------------------------- the lock, for the engine + * + * EVERY MUTATION OF THE KV MANAGER AND THE PREFIX CACHE HAPPENS UNDER THIS LOCK. Neither has + * a lock of its own, and both are reached from two kinds of thread: the step path, and HTTP + * threads running cancel(), reap() and reset_prefix_cache(), which publish into the cache, + * evict from it and free sequences. The engine's own passes between steps -- the idle tiers, + * the elastic rebalance, the checkpoint copies -- mutate the same structures, so they run + * inside this too. Taken once per pass that has work, never per sequence. + * + * NOTHING RUN UNDER IT MAY CALL BACK INTO THE SCHEDULER: the mutex is not recursive, and + * every public method here takes it. */ + template auto locked(Fn&& fn) { + std::lock_guard lk(mu_); + return fn(); + } + /* The same lock, held for the rest of the caller's scope. */ + [[nodiscard]] std::unique_lock hold() { return std::unique_lock(mu_); } + + /* ---------------------------------------------------------- work the device still owes + * + * A request cancelled while a drafter pass was being built keeps its blocks until the passes + * that name them are done (see SchedReq::pending_free). commit() releases them once nothing + * refers to them; an engine that has gone idle runs no commit, so it drains its streams and + * calls release_deferred() instead. has_deferred() is the cheap test for whether that is + * needed at all. */ + bool has_deferred() const; + void release_deferred(); + + /* THE ENGINE HAS STOPPED AND WILL RUN NO MORE STEPS. Every request still queued or running is + * failed with `reason` so its connection is answered rather than left waiting on a step that + * will never come, and any request submitted afterwards is refused the same way. */ + void shutdown(const char* reason); + + /* The waiting queue in SERVICE order, by request id -- what the live view shows and what a + * test asserts a preempted request re-entered at the front of. Returns how many were written. */ + int queue_snapshot(uint64_t* out, int max) const; + + /* ---------------------------------------------------------- who is in flight + * + * WHAT EVERY REQUEST IS DOING RIGHT NOW, for the dashboard and for anyone debugging a stall. + * The aggregate metrics answer "is the engine busy"; they cannot answer "which of these eight + * is stuck", and a request that has been in `Waiting` for forty seconds because its prompt + * does not fit is invisible in every number above. + * + * A snapshot under the step lock, copied out: holding a pointer into the scheduler's storage + * across a step is holding a pointer to a request that may be reaped. */ + struct ReqStat { + uint64_t id = 0; + int state = 0; /* ReqState, as an int -- the caller has the enum */ + bool running = false; + int64_t prompt_tokens = 0; + int64_t computed_tokens = 0; /* of the prompt, how much is in the KV: prefill progress */ + int64_t cached_tokens = 0; /* of those, how many came from the prefix cache */ + int64_t output_tokens = 0; + int64_t max_tokens = 0; + int64_t ctx_tokens = 0; /* prompt ++ output */ + /* THIS REQUEST'S SHARE OF THE PAGED POOLS, summed over every paged group: the blocks it + * holds and the tokens they cover. `ctx_tokens` is what it is USING; this is what it has + * TAKEN, and they differ by a partial block and by whatever a rejected draft left. */ + int64_t kv_blocks = 0; + int64_t kv_tokens = 0; + int32_t n_draft = 0; /* the proposal standing for the next step */ + int32_t slot = -1; + double age_s = 0; + double ttft_s = -1; /* negative until the first token */ + double decode_tps = 0; /* this request's own, since its first token */ + }; + /* Newest first is wrong here: a dashboard wants the oldest at the top, because the oldest is + * the one that is stuck. Returns how many were written. */ + int requests(ReqStat* out, int max) const; + + /* The drafter's proposal for a request's next step. n is clamped to the controller's depth. */ + int set_draft(uint64_t id, const int32_t* tokens, int n); + + /* ---------------------------------------------------------- media the encoder owes + * A REQUEST CARRYING MEDIA IS ADMITTED ONLY ONCE EVERY ITEM IS ENCODED. Until then it keeps + * its place in the queue, the requests behind it are admitted around it, and its items wait + * here for the engine, which runs the encoder between steps and marks them done (take_encodes). + * Encoding before admission rather than chunk by chunk keeps the encoder off the step path: + * a step never waits for a tower, and the batch builder only ever copies rows that exist. */ + bool encodes_pending() const; + void take_encodes(std::vector>* out); + /* An encoder pass over whole segments; see BatchBuilder::build_encoder. */ + const RadBatch* build_encoder(const std::vector& parts, int step) { + std::lock_guard lk(mu_); + return builder_.build_encoder(parts, step); + } + int64_t encoder_patches() const { return builder_.encoder_patches(); } + + /* Drop every prefix-cache entry, returning how many were dropped, or RAD_E_UNSUPPORTED when + * this engine has no prefix cache. Under the step lock: releasing the cache's references is + * safe against a running step -- a block a live sequence holds stays allocated because the + * sequence holds its own reference -- but the map itself is not, and the step path inserts + * into it. See IScheduler::reset_prefix_cache for why the endpoint exists. */ + int64_t reset_prefix_cache(); + + /* ---------------------------------------------------------- the step path */ + /* One decision, one batch. Null when there is nothing to run, which is not an error. */ + const RadBatch* step(); + + /* ---------------------------------------------------- THE NEXT STEP, BEFORE THIS ONE COMMITS + * + * A decode step's successor does not need anything the host learns from the step: every row + * continues where the card's acceptance leaves it (sched/advance.h), with the drafts the + * drafter proposed on the card, and the host can bound how far that is. So the engine issues + * the next step's forward pass while this one is still running, and the card goes straight + * from one to the other. + * + * expect_draft after the drafter is issued: how many drafts it proposes for a sequence, + * which is how many the next step verifies. + * step_next plans and builds that step: every row of this one, as a device row, at + * the furthest context it can reach. Null -- and the engine plans with step() + * after this one commits -- whenever the step needs a decision only a + * committed state can make: a request waiting for admission, a prefill chunk + * to continue, a grammar, the context's end, or a pool that cannot grow. + * promote_next once this step has committed: the next step becomes the open one. + * + * While the next step is open, commit() leaves each continuing request's blocks where they + * are -- the next step is writing past the committed end -- and a request that finishes keeps + * them until the next step has run. */ + void expect_draft(uint64_t id, int n); + const RadBatch* step_next(); + const RadBatch* step_next_locked(); + void promote_next(); + bool next_open() const { return next_open_; } + /* Fold the step's outcome back in: append tokens, roll back rejected speculation, retire + * finished requests, feed the draft controller. */ + int commit(const StepResult& r); + /* THE ENGINE'S LOOP IS ROUND, AND THE STEP ENDS HERE -- after the drafter, not at commit. + * A serial draft head runs as extra steps AFTER the trunk step that fed it (see below), so + * closing the step at commit would leave those rounds in no step at all: their time is charged + * to nothing, `decode_tps` reads high and the reported step time reads short. The definition in + * scheduler.cpp is the argument. Call it once per loop iteration that ran a step; a caller that + * does not is left with correct counters and no timing. */ + void step_finished(); + + /* ---------------------------------------------------- the SERIAL drafter (spec §10) + * + * A serial draft head (RAD_DRAFT_SERIAL) runs as EXTRA STEPS of its own, after the + * trunk step that fed it. It cannot run inside that step: round 1 consumes the token the + * sampler chose and the hidden state of the position that token came from, and which position + * that is depends on how many drafts the verify accepted -- neither is known until the trunk + * step has been sampled and committed. + * + * So the engine drives it, and these three calls are the scheduler's half: + * + * serial_begin BEFORE commit(), right after the step is issued, while plan() describes it. + * Says which sequences may draft, reserves the lookahead KV they may write + * into -- for the furthest position acceptance could reach, since how far it + * reached is the card's to decide -- and clamps `rounds` to the controller's + * current depth. + * serial_batch one batch per pass: 0 the history, which also carries round 1 for the + * rows that draft (RadBatch::draft_out_ids), then the rounds from 2. Every row + * that continues a sampled verify is a DEVICE row (advance.h): the card fills + * its positions from the acceptance it computed, and its tokens from the sampled + * ids and each round's proposal, so no pass waits on the host. + * serial_end AFTER commit(), with the rounds that ran: moves the history watermark to + * the last position the committed acceptance says the history pass wrote. + * set_draft the engine publishes each row's tokens through the ordinary door, so a head's + * draft and a prompt-lookup draft are the same thing to the next step. A row + * the head declined leaves n_draft at 0 and the n-gram drafter fills in. + */ + struct SerialRow { + uint64_t seq = 0; + int32_t slot = -1; + int32_t card = -1; + }; + int serial_begin(int* rounds, SerialRow* out, int max); + const RadBatch* serial_batch(int round, int step); + /* Round 0 is the HISTORY pass -- null when no row needs one -- and round 1 is always null, + * because round 0 carries it. Call serial_end() once the step has committed so the watermark + * moves. */ + void serial_end(int rounds_done); + + /* ----------------------------------------------------- the BLOCK drafter (spec §10) + * + * A block-diffusion drafter (RAD_DRAFT_BLOCK), and the shape is the whole point: ONE pass + * over a block of `block` positions proposes all of them, so depth costs nothing and there is + * no chain of rounds. What replaces it is TWO passes with different shapes, and the scheduler's + * half is telling each of them which rows it runs over. + * + * block_begin right after commit(), while plan() still describes the step just run. + * Reserves the block of draft KV the query pass will write, and answers + * which sequences may draft. + * block_context the CONTEXT pass, draft_pass -1. Its entries MIRROR that trunk step's -- + * same sequence, same ctx_len, same n_tokens -- because the drafter reads + * the trunk's tapped hidden states positionally out of a buffer of its own, + * and a mirror is what makes row i of the batch row i of it. No gather, + * no offset, and no special case for a rejected suffix: those positions are + * inside the block the query pass is about to overwrite. + * block_query the QUERY pass, draft_pass +1. One entry a drafting sequence, `block` + * tokens: the anchor at the sequence's own next position and a mask at each + * of the `block - 1` after it. `out_ids` names THE LAST `depth` ROWS, which + * is the one rule both trained conventions reduce to: at block = depth + 1 + * the anchor row predicts nothing and each mask row predicts the token at + * ITS OWN position, and at block = depth every row predicts the token AFTER + * it and the anchor is not wasted. rad_builder.h argues the pair. + * block_end moves the filled range over what actually ran. + * + * The proposal does not come back through the sampler: the drafter writes it to the buffer it + * declared as its proposal, and the engine publishes it through set_draft() like any other. + */ + struct BlockRow { + uint64_t seq = 0; + int32_t slot = -1; + int32_t card = -1; + }; + /* `block` is the drafter's trained block in ROWS and `depth` how many tokens it proposes out + * of them -- the head takes the last `depth` -- and `window` is its attention window (0 for + * none); `mask` is the token id its masked query slots embed. Returns how many sequences may + * draft, and fills `out` with those -- in the order block_query() will emit them. */ + int block_begin(int block, int depth, int window, int32_t mask, BlockRow* out, int max); + const RadBatch* block_context(int step); + const RadBatch* block_query(int step); + void block_end(); + + const StepPlan& plan() const { return plan_; } + const ChunkGeometry& geometry() const { return geo_; } + DraftController& draft() { return draft_; } + SchedMetrics metrics() const; + + /* THE OBSERVERS' COPY. A dashboard, a scraper or an admin call reads what the engine thread + * last published and never the scheduler's own state, because that state is behind the lock + * every step takes: a reader holding it for as long as its own work takes delays the step by + * exactly that long, and an observer must not be able to slow what it observes. + * + * publish() is the engine thread's, once a step and at most every 20 ms while idle. It builds + * the copy under the scheduler's lock -- the engine thread's own lock, so nothing waits -- and + * swaps it in only if no reader is copying out at that moment; a swap it skips is made at the + * next call. The readers take only the copy's lock, which the engine thread never waits on. */ + void publish(bool idle); + SchedMetrics observed_metrics() const; + int observed_requests(ReqStat* out, int max) const; + + /* Visible for tests: the chunk the scheduler would give a request at `n_computed` under a + * token budget, and the checkpoint position it will land on (-1 for none). */ + int64_t plan_chunk(int64_t n_computed, int64_t n_target, int64_t budget, + int64_t* checkpoint_pos) const; + +private: + Program* prog_ = nullptr; + Config cfg_{}; + ChunkGeometry geo_{}; + KVGeom kvgeom_{}; + /* Does this model carry recurrent state a prefix hit would have to restore? See admit_one. */ + bool has_linear_state_ = false; + IKVManager* kv_ = nullptr; + IPrefixCache* pc_ = nullptr; + + /* DOES A PREFIX-CACHE HIT LEAVE A HOLE IN A BLOCK DRAFTER'S OWN KV? Only if some PAGED group + * is not prefix-cached. prefix.cpp skips a WINDOWED group -- "a hit's blocks do not describe + * a cache whose floor moves" -- so a windowed drafter really does start at the hit position + * and really must wait for its window to slide past it. A FULL-attention drafter's group is + * cached exactly like the trunk's: the hit hands over blocks the PREVIOUS sequence's own + * context pass wrote, so the content is there and the floor is 0. + * + * Read off IPrefixCache::cached_groups() rather than re-deriving prefix.cpp's rule, which + * also skips on a block-size mismatch. A bound like this lives in exactly one place; a second + * copy is free to drift out of step with the first. */ + bool hit_holes_draft_ = true; + BatchBuilder builder_; + DraftController draft_; + + /* Where this sequence's block-drafter cache begins, as the guard in block_begin reads it + * and block_end records it. One rule, one place. */ + int64_t draft_floor(const SchedReq& s, int64_t ctx_len) const { + if (s.draft_hi != 0 || s.draft_lo != 0) return s.draft_lo; + return hit_holes_draft_ ? ctx_len : 0; + } + + /* The built-in prompt-lookup drafter (scheduler.cpp). Fills s.draft and returns how many + * tokens it proposed; 0 when the sequence has no repeated pattern to extend. The pattern + * lengths it tries, longest first. */ + int draft_ngram(SchedReq& s, int depth) const; + enum { kNgramMin = 2, kNgramMax = 4 }; + + mutable std::mutex mu_; + + SchedMetrics metrics_locked() const; + int requests_locked(ReqStat* out, int max) const; + /* The published copy and its lock (publish()). The scratch pair is the engine thread's, filled + * under mu_ and then swapped with the published pair, so a publication allocates nothing once + * the vectors have grown to the request count. */ + mutable std::mutex pub_mu_; + SchedMetrics pub_m_; + std::vector pub_reqs_; + SchedMetrics scratch_m_; + std::vector scratch_reqs_; + int64_t pub_at_us_ = 0; + + std::vector> reqs_; /* by slot */ + std::vector free_slots_; + std::vector free_cards_; /* card indices not held by any sequence; see SchedReq::card */ + std::unordered_map by_id_; + + /* Both kept sorted by (priority desc, arrival asc). running_ is sorted so the preemption + * victim is the back; waiting_ so admission takes the front. */ + std::vector running_; + std::vector waiting_; + std::vector completed_; + + /* Requests whose release is waiting on something that still refers to them -- a deferred + * reap or a deferred free. A count, so the sweeps that look for them cost nothing on the + * steps where there are none, which is nearly all of them. */ + int n_deferred_ = 0; + /* Items a waiting request needs encoded, in the order its requests reached the queue's head; + * each at most once (Item::queued). mu_ held. */ + std::vector> enc_want_; + /* Are all of this request's items encoded; the ones that are not are queued for the encoder. */ + bool media_ready(SchedReq& s); + + /* Set by shutdown(); add() refuses from then on. */ + bool closed_ = false; + const char* closed_reason_ = ""; + + /* THE LONGEST SEQUENCE THIS DEPLOYMENT CAN ADDRESS, prompt and output together. The batch + * builder sizes its block tables for it and the rotary tables are this long, so no position + * at or past it may be scheduled -- whatever max_tokens a request carries, including none. */ + int64_t ctx_limit_ = 0; + + /* Scratch for a prefix-cache hit's block ids, one row per cached group. Reserved at init so + * an admission does not reach the allocator. */ + std::vector> hit_blocks_; + /* Scratch for publishing a finished sequence into the prefix cache. Reused so close_request + * does not allocate per completion. */ + std::vector> pub_blocks_; + + StepPlan plan_; + StepPlan plan_next_; + bool next_open_ = false; + /* Is a step the card may still be running holding this request? */ + bool in_step(const SchedReq& s) const { + return (step_open_ && s.entry >= 0) || (next_open_ && s.entry_next >= 0); + } + + /* The serial drafter's rows, valid between serial_begin() and serial_end(). `base_pos` + * is the position round 1 writes at: the emitted token's own position, which is exactly the + * committed length because that token has not been fed to the model yet. */ + struct SerialSeq { + uint64_t seq = 0; + int32_t slot = -1; + int32_t card = -1; + int32_t hist_row = -1; /* the trunk row the history pass starts at */ + int32_t hist_n = 0; /* how many positions it has to fill, 0 for none */ + int64_t hist_pos = 0; /* the head index that first row is */ + /* THE VERIFY STEP THIS ROW CONTINUES FROM, as the card's advance reads it (advance.h): + * whether it sampled, the token row of its first verified position, its first sampled + * row, and how many history positions come before the verified ones. */ + bool dev = false; + int32_t dev_tok = 0; + int32_t dev_out = -1; + int32_t lead = 0; + /* ITS INDEX AMONG THE DRAFTING ROWS, or -1 for a row that only owes history. A sequence + * in the middle of a long prompt has hidden states worth turning into the head`s K and V + * and no token to draft from yet, and so does every sequence when a prefill is queued + * behind this step -- so the two sets are not the same set. */ + int32_t draft_idx = -1; + /* NO Request* HERE, for the reason BlockSeq gives: serial_ is taken under the lock in + * serial_begin and read again by serial_batch, once a round, after the lock has been + * released and retaken -- and a client can disconnect in any of those windows. */ + /* THE FURTHEST POSITION ROUND 1 CAN WRITE AT: the verify step's last position, reached + * when every draft is accepted. The card knows the real one; this bounds it. */ + int64_t base_pos = 0; + }; + std::vector serial_; + StepPlan serial_plan_; + + /* The block drafter's rows, valid between block_begin() and block_end(). One entry for EVERY + * entry of the trunk step just run, in its order; `can_draft` says whether it also gets a + * query pass. `ctx_len`/`n_tokens` mirror that step's entry, which is the whole contract with + * the drafter's own source buffer. */ + struct BlockSeq { + uint64_t seq = 0; + int32_t slot = -1; + int32_t card = -1; + int32_t ctx_len = 0; + int32_t n_tokens = 0; + int64_t base_pos = 0; /* the anchor's position: the sequence's next one */ + bool can_draft = false; + /* A ROW KEPT ONLY TO HOLD ITS PLACE. The trunk step finished this sequence -- it ended, + * failed or was cancelled at commit -- so its KV is gone and it drafts nothing. It is + * still a row of the context pass, because the drafter reads the trunk's hidden states + * positionally: dropping it would slide every later sequence onto its neighbour's rows. + * With no blocks behind it the pass stores nothing for it (a negative slot is padding). */ + bool mirror = false; + /* NO Request* HERE, DELIBERATELY. block_ is taken under the lock in block_begin and read + * again in block_context, block_query and block_end, and the lock is RELEASED between + * them -- so a client that disconnects in that window can have its Request destroyed + * under the second pass, leaving BatchBuilder::build reading tokens off freed memory. + * The snapshot is a WEAK reference: `slot` plus `seq`, resolved through block_req(). */ + }; + std::vector block_; + StepPlan block_plan_; + int32_t block_len_ = 0; + int32_t block_depth_ = 0; /* tokens proposed; the head takes the LAST this many */ + /* `block` - 1 copies of the drafter's mask token, which is what a query entry's `draft` array + * points at: token_at() walks prompt ++ output ++ draft, so the mask positions fall straight + * out of the accessor every other pass already uses. */ + std::vector block_mask_; + int step_ = 0; + uint64_t arrival_ = 0; + + SchedMetrics m_{}; + std::chrono::steady_clock::time_point step_start_{}; + /* When the last step ended. An idle engine runs no steps, so the throughput window has + * nothing adding time to it, and metrics() decays what it reports by this. */ + std::chrono::steady_clock::time_point last_step_at_ = std::chrono::steady_clock::now(); + int64_t step_prefill_tok_ = 0, step_decode_tok_ = 0; + /* The throughput window (step_finished): each kind's tokens and the wall time the steps + * covered, both decayed with the same time constant, so their ratio is tokens over time. */ + double tps_win_prefill_ = 0.0, tps_win_decode_ = 0.0, tps_win_time_ = 0.0; + bool step_open_ = false; + + /* arrival; mu_ held */ + int add_locked(std::unique_ptr r); + + /* ordering */ + bool ahead_of(int32_t a, int32_t b) const; + void queue_insert(std::vector& q, int32_t slot); + static void queue_erase(std::vector& q, int32_t slot); + + /* lifecycle */ + /* `publish` is false only when the engine is shutting down: a sequence the device may have + * left half-computed is not worth indexing, and nothing will ever hit it. */ + void close_request(SchedReq& s, ReqState st, const char* reason, bool defer_free = false, + bool publish = true); + /* What reap() does once nothing points at the slot any more: give the blocks back, forget the + * id, destroy the Request and return the slot. Called by reap() directly, or by the sweep in + * commit() for a request whose reap arrived while something still pointed at it. */ + void release_locked(SchedReq& s); + /* The sequence's KV back to the manager and its card index back to the pool, together: + * both are what a step in flight still addresses, so both wait for the same moment. */ + void free_kv(SchedReq& s); + void drop_card(SchedReq& s); + /* Is this request still referenced by a drafter's snapshot? block_ and serial_ outlive the + * lock. */ + bool block_holds(uint64_t id) const; + /* Release every deferred reap and every deferred free whose request nothing refers to any + * more. At most one step late: the reference that blocked it is either the step just + * committed or a drafter snapshot that block_end() / serial_end() has since cleared. */ + void sweep_deferred(); + /* Give back a prefix hit an admission attempt took and then could not use: the adopted + * blocks, the checkpoint it would have restored, and the position it would have resumed at. + * The next attempt looks the prompt up again. */ + void undo_hit(SchedReq& s); + /* The live Request behind a snapshot row, or null if it went away. */ + const Request* block_req(const BlockSeq& d) const; + const Request* serial_req(const SerialSeq& m) const; + /* Both snapshots resolve the same way; the two wrappers exist because the row types differ. */ + const Request* live_req(int32_t slot, uint64_t id) const; + void preempt_back(); + /* Give blocks back from the prefix cache until the pool has headroom again. */ + void trim_prefix_cache(); + /* RAD_OK, a negative status when the request cannot be admitted now -- nothing behind it is + * either -- or kAdmitWait when its context is still being read off disk and the next request + * may go ahead of it. */ + int admit_one(SchedReq& s, int64_t budget); + static constexpr int kAdmitWait = 1; + /* The queue positions one step's admission took, kept to reuse the allocation. */ + std::vector took_; + + /* The conv rolling window, width-1 + num_spec + 1 entries (spec §10). */ + int32_t conv_window() const; +}; + +} /* namespace rad */ diff --git a/core/server/adapters.h b/core/server/adapters.h new file mode 100644 index 00000000..2c95c305 --- /dev/null +++ b/core/server/adapters.h @@ -0,0 +1,695 @@ +/* core/server/adapters.h -- bind the real components onto the server's interfaces. + * + * iface.h deliberately knows nothing about core/sched or core/text, so that the HTTP layer can be + * compiled and tested against fakes with no engine present. This file is where the two sides + * actually meet, and it is included by exactly one translation unit: whoever wires the engine + * (core/engine.cpp). Nothing in core/server/ includes it, so the server's own build stays + * independent of those components' headers. + * + * rad::server::SchedulerBridge sched(&engine_scheduler); + * rad::server::TokenizerBridge tok(vocab); + * rad::server::Deps d; d.sched = &sched; d.tok = &tok; ... + * + * Every impedance mismatch between what the server wants and what those components provide is + * resolved here, in one place, with the reason written down -- rather than being smeared across + * either component as a special case for the other. + */ +#pragma once +#include "iface.h" +#include "mem/kvtier.h" + +#if !defined(RAD_SERVER_NO_ENGINE_BRIDGE) && \ + __has_include("sched/scheduler.h") && __has_include("text/tokenizer.h") +#define RAD_SERVER_HAVE_ENGINE_BRIDGE 1 + +#include "sample/gbnf.h" +#include "sample/grammar.h" +#include "sample/sampler.h" +#include "sched/scheduler.h" +#include "rad_builder.h" +#include "text/chat.h" +#include "text/chatfmt.h" +#include "text/chatparse.h" +#include "text/tokenizer.h" +#include "mm/processor.h" + +#include + +#include +#include +#include + +namespace rad { +namespace server { + +/* ================================================================== scheduler */ + +class SchedulerBridge final : public IScheduler { +public: + /* `sampler` is the rank-0 sampler, and it is optional only so that a caller with no engine + * behind it still compiles. Every rank declares the same chain against the same hierarchy, so + * whether a stage resolved is not a per-rank fact and asking one of them is asking all. */ + /* `tiers` is rank 0's IdleTiers, and it is given whether or not a tier can move anything: + * the object holds the session table either way, and a server with no --prefix-cache-host-mib is + * one whose every stored session is in VRAM rather than one with no sessions. Null only when + * there is no engine behind this at all. */ + explicit SchedulerBridge(Scheduler* s, const Sampler* sampler = nullptr, + const IdleTiers* tiers = nullptr) + : s_(s), sampler_(sampler), tiers_(tiers) {} + + int admit(const SamplingParams& sp, std::string* why) const override { + if (!sampler_) return RAD_OK; + return sampler_->check_request(sp, why); + } + + /* Request ids are the server's to allocate: Scheduler::add refuses a duplicate id and does + * not mint one, which is the right split -- the id has to exist before submission so that a + * connection dropped during submission still has something to cancel. */ + uint64_t submit(Request&& r) override { + auto p = std::make_unique(std::move(r)); + p->id = next_.fetch_add(1, std::memory_order_relaxed); + const uint64_t id = p->id; + int st = s_->add(std::move(p)); + if (st < 0) { + /* Failing here means the request never entered the queue, so nothing will ever finish + * its sink. Tell the sink itself, or the HTTP thread waits forever. */ + RAD_WARN("server: scheduler refused request %llu: %s", + (unsigned long long)id, rad_strerror(st)); + return 0; + } + return id; + } + + void submit_all(std::vector& rs, std::vector* ids) override { + const size_t n = rs.size(); + std::vector> ps(n); + std::vector rc(n, RAD_OK); + ids->assign(n, 0); + for (size_t i = 0; i < n; ++i) { + ps[i] = std::make_unique(std::move(rs[i])); + ps[i]->id = next_.fetch_add(1, std::memory_order_relaxed); + (*ids)[i] = ps[i]->id; + } + s_->add_all(ps.data(), n, rc.data()); + for (size_t i = 0; i < n; ++i) { + if (rc[i] >= 0) continue; + RAD_WARN("server: scheduler refused request %llu: %s", + (unsigned long long)(*ids)[i], rad_strerror(rc[i])); + (*ids)[i] = 0; + } + } + + void cancel(uint64_t id) override { s_->cancel(id); } + void reap(uint64_t id) override { s_->reap(id); } + + int64_t reset_prefix_cache() override { return s_->reset_prefix_cache(); } + + /* THE STORED CONVERSATIONS. Idle time is computed here rather than carried, because the tiers + * keep a monotonic timestamp and a browser wants "how long ago" -- converting at the edge + * means one clock is authoritative and the other never has to be trusted. */ + TierCounters tier_counters() const override { + TierCounters c; + if (!tiers_) return c; + const IdleTiers::Stats& s = tiers_->stats(); + c.to_host = s.to_host; c.dropped = s.dropped; c.to_disk = s.to_disk; + c.promoted = s.promoted; + c.host_freed = s.host_freed; c.host_drops = s.host_drops; c.failures = s.failures; + c.fetched = s.fetched; c.ck_fetched = s.ck_fetched; + c.host_bytes = s.host_bytes; c.disk_bytes = s.disk_bytes; + c.ck_to_host = s.ck_to_host; c.ck_to_disk = s.ck_to_disk; c.ck_promoted = s.ck_promoted; + c.ck_drops = s.ck_drops; c.ck_starved = s.ck_starved; + c.ck_bytes = tiers_->ckpt_bytes(); + c.ck_host_slots = tiers_->ckpt_arena().capacity(); + c.ck_disk_slots = tiers_->ckpt_disk_slots(); + c.host_on = tiers_->host_on(); + c.disk_on = tiers_->disk_on(); + return c; + } + + int sessions(std::vector* out, SessionOccupancy* occ) const override { + out->clear(); + if (!tiers_) return 0; + IdleTiers::Occupancy held; + const std::vector v = tiers_->sessions(occ ? &held : nullptr); + if (occ) { + occ->host_bytes = held.host_bytes; occ->disk_bytes = held.disk_bytes; + occ->host_cap_bytes = held.host_cap_bytes; occ->disk_cap_bytes = held.disk_cap_bytes; + } + const uint64_t now = rad_mono_ns(); + out->reserve(v.size()); + for (const IdleTiers::SessionInfo& s : v) { + SessionStat o; + o.id = s.id; + o.model = s.model; + o.n_tokens = s.n_tokens; + o.bytes = s.bytes; + o.idle_s = now > s.last_used_ns ? (double)(now - s.last_used_ns) / 1e9 : 0.0; + o.age_s = now > s.first_seen_ns ? (double)(now - s.first_seen_ns) / 1e9 : 0.0; + o.on_device = s.on_device; + o.on_host = s.on_host; + o.on_disk = s.on_disk; + o.moving = s.moving; + o.snapshots = s.snapshots; + o.snap_device = s.snap_device; + o.snap_host = s.snap_host; + o.snap_disk = s.snap_disk; + o.snap_bytes = s.snap_bytes; + o.resume_tokens = s.resume_tokens; + out->push_back(std::move(o)); + } + return (int)out->size(); + } + + /* THE STATE NAME IS DERIVED, not stored: ReqState has no `Prefill`, because to the scheduler + * prefill is not a state -- it is a running request whose prompt is not yet all in the KV. + * That distinction is the single most useful thing this table shows, so it is made here + * rather than left for every reader to reconstruct from two integers. */ + int requests(std::vector* out) const override { + std::vector raw(256); + const int n = s_->observed_requests(raw.data(), (int)raw.size()); + out->clear(); + out->reserve((size_t)n); + for (int i = 0; i < n; ++i) { + const Scheduler::ReqStat& r = raw[(size_t)i]; + RequestStat o; + o.id = r.id; + switch ((ReqState)r.state) { + case ReqState::Waiting: o.state = "waiting"; break; + case ReqState::Preempted: o.state = "preempted"; break; + case ReqState::Running: + o.state = r.computed_tokens < r.prompt_tokens ? "prefill" : "decode"; + break; + default: o.state = "done"; break; + } + o.prompt_tokens = r.prompt_tokens; + o.computed_tokens = r.computed_tokens; + o.cached_tokens = r.cached_tokens; + o.output_tokens = r.output_tokens; + o.max_tokens = r.max_tokens; + o.ctx_tokens = r.ctx_tokens; + o.kv_blocks = r.kv_blocks; + o.kv_tokens = r.kv_tokens; + o.n_draft = r.n_draft; + o.slot = r.slot; + o.age_s = r.age_s; + o.ttft_s = r.ttft_s; + o.decode_tps = r.decode_tps; + out->push_back(std::move(o)); + } + return n; + } + + /* Both read the copy the engine thread publishes (Scheduler::publish), never the + * scheduler's live state: every caller is an observer. */ + SchedMetrics metrics() const override { + const rad::SchedMetrics m = s_->observed_metrics(); + SchedMetrics o; + o.waiting = m.queue_depth; + o.running = m.running; + o.preempted = m.preempted_waiting; + + /* One KV utilisation number, and it is the MAXIMUM over groups rather than the mean. A + * hybrid model has a full-attention group and a linear-state group with different + * geometries (spec §7.2), and exhausting either one preempts -- so the number a dashboard + * should be watching is the closest one to the wall, not the average of it with the one + * that has room. + * + * AND THE TOKEN CAPACITY IS NOT A SUM, for the same reason, which is easier to get wrong + * because the units look additive. PAGED GROUPS SHARE ONE TOKEN AXIS: on Qwen4-Exp + * `kv_attn` and `kv_qsa_bkey` are both 129216 blocks of 4 tokens, and one token of context + * takes a slot in BOTH of them (26.00 KiB + 3.25 KiB a block, 7.31 KiB a token together). + * Adding them would report 1,033,728 tokens of capacity for a pool that holds 516,864 -- + * off by exactly the number of paged groups, an error that is invisible on a one-group + * model. + * + * So the figure is the BINDING group's: the one nearest the wall, which is the one that + * decides when the next sequence is preempted, and the same group `kv_util` reports. */ + o.kv_util = 0.0; + int bind = -1; + for (int i = 0; i < m.n_kv_groups; ++i) { + if (m.kv[i].block_tokens <= 0) continue; /* a linear state has no token axis */ + if (bind < 0 || m.kv[i].utilisation > m.kv[bind].utilisation) bind = i; + } + for (int i = 0; i < m.n_kv_groups; ++i) + o.kv_util = std::max(o.kv_util, (double)m.kv[i].utilisation); + if (bind >= 0) { + const int64_t bt = m.kv[bind].block_tokens; + o.kv_tokens_total = m.kv[bind].blocks_total * bt; + o.kv_tokens_used = (m.kv[bind].blocks_total - m.kv[bind].blocks_free) * bt; + } + + /* AND THE WHOLE POOL IN BYTES, WHICH IS THE ONE FIGURE THAT IS A SUM. The paragraph above + * is about why tokens are not: the groups share a token axis. Bytes do not overlap -- each + * group was carved its own extent of the card -- so every group is added here, the + * recurrent ones included, and the answer is how much VRAM the KV cache is holding. */ + for (int i = 0; i < m.n_kv_groups; ++i) { + o.kv_bytes_total += m.kv[i].bytes_total; + o.kv_bytes_used += m.kv[i].bytes_used; + o.kv_bytes_carved += m.kv[i].bytes_carved; + } + + /* vLLM's gpu_prefix_cache_hit_rate is a single number and attention caching is what it + * has always meant. The linear-checkpoint hit rate is a different measurement at a + * different granularity (spec §7.3) and averaging the two would hide exactly the effect + * the decoupling exists to expose, so it is not folded in here. */ + o.prefix_hit_rate = m.attn_hit_rate; + o.prefix_evictions = m.prefix_evictions; + /* WHAT ONLY THE CACHE IS HOLDING -- see SchedMetrics::prefix_held_tokens. Clamped to what + * the pool reports held: they are counted at different moments in a step and a cached + * figure above the used one would draw a negative live share. */ + o.kv_tokens_cached = std::min(m.prefix_held_tokens, o.kv_tokens_used); + o.prefix_ckpt_evictions = m.prefix_ckpt_evictions; + + o.prefill_tps = m.prefill_tps; + o.decode_tps = m.decode_tps; + o.draft_acceptance = m.draft_acceptance; + o.prefill_tokens = m.prefill_tokens; o.decode_tokens = m.decode_tokens; + o.draft_tokens = m.draft_tokens; o.draft_accepted = m.draft_accepted; + o.linear_hit_rate = m.linear_hit_rate; + o.attn_cached_tokens = m.attn_cached_tokens; + o.linear_cached_tokens = m.linear_cached_tokens; + o.checkpoints_written = m.checkpoints_written; + o.draft_depth_seen = m.draft_depth_seen; + if (o.draft_depth_seen > SchedMetrics::MAX_DRAFT_POS) + o.draft_depth_seen = SchedMetrics::MAX_DRAFT_POS; + for (int j = 0; j < o.draft_depth_seen; ++j) { + o.draft_pos_reached [j] = m.draft_pos_reached [j]; + o.draft_pos_accepted[j] = m.draft_pos_accepted[j]; + } + o.preemptions = m.preemptions; + o.total_requests = m.admitted; + o.steps = m.steps; + o.steps_prefill = m.steps_prefill; o.steps_mixed = m.steps_mixed; + o.steps_decode = m.steps_decode; + o.steps_ahead = m.steps_ahead; + o.decode_rows_unspeculated = m.decode_rows_unspeculated; + o.step_ns = m.step_ns; o.step_ns_decode = m.step_ns_decode; + return o; + } + +private: + /* DECLARED IN CONSTRUCTION ORDER. Members initialise in declaration order whatever the + * initialiser list says, so a list that disagrees with it draws a -Wreorder warning and + * becomes a use-before-initialisation the first time one of these is derived from another. */ + Scheduler* s_; + const Sampler* sampler_ = nullptr; + const IdleTiers* tiers_ = nullptr; + /* Ids start at 1: zero is the "no request" value the sink and the metrics use. */ + std::atomic next_{1}; +}; + +/* ================================================================== text */ + +class DetokenizerBridge final : public IDetokenizer { +public: + DetokenizerBridge(std::shared_ptr v, std::vector stops, + const std::vector& preserved) + : d_(std::move(v), std::move(stops), /*render_special=*/false, preserved) {} + std::string push(int32_t t) override { return d_.push(t); } + std::string flush() override { return d_.flush(); } + bool stopped() const override { return d_.stopped(); } +private: + Detokenizer d_; +}; + +class TokenizerBridge final : public ITokenizer { +public: + explicit TokenizerBridge(std::shared_ptr v) : vocab_(std::move(v)) { + tok_.init(vocab_); + } + + std::vector encode(const std::string& text, bool add_special, + bool parse_special) const override { + std::vector out; + int st = tok_.encode(text, out, add_special, parse_special); + if (st < 0) { + /* The caller checks for an empty result and answers 400. Returning a partial + * tokenisation would be worse than returning none: it is a prompt that is silently + * not the prompt that was sent. */ + RAD_WARN("server: tokenise failed: %s", rad_strerror(st)); + out.clear(); + } + return out; + } + + std::string decode(const std::vector& ids) const override { + /* Sanitised for the same reason Detokenizer::push is: a token array naming byte-fallback + * ids need not decode to well-formed UTF-8, and this text is echoed back inside a JSON + * string, where a malformed byte costs the client the whole response. */ + return utf8_sanitize(tok_.decode(ids, /*render_special=*/false)); + } + int32_t eos() const override { return vocab_->eos(); } + int32_t bos() const override { return vocab_->bos(); } + + VocabInfo vocab_info() const override { + VocabInfo i; + i.n_tokens = vocab_->n_tokens(); + i.bos = vocab_->bos(); i.eos = vocab_->eos(); i.eot = vocab_->eot(); + i.unk = vocab_->unk(); i.pad = vocab_->pad(); + i.add_bos = vocab_->add_bos(); i.add_eos = vocab_->add_eos(); + switch (vocab_->kind()) { + case RAD_TOK_BPE: i.kind = "bpe"; break; + case RAD_TOK_UNIGRAM: i.kind = "unigram"; break; + case RAD_TOK_WORDPIECE: i.kind = "wordpiece"; break; + case RAD_TOK_RWKV: i.kind = "rwkv"; break; + default: i.kind = "unknown"; break; + } + return i; + } + + /* Vocab::text, sanitised: a byte-level BPE piece is a mapped codepoint sequence that is valid + * UTF-8, but a byte-fallback vocabulary's piece need not be, and this goes into a JSON string + * where one malformed byte costs the client the whole response. */ + std::string piece(int32_t id) const override { + if (id < 0 || id >= vocab_->n_tokens()) return std::string(); + return utf8_sanitize(vocab_->text(id)); + } + + std::unique_ptr detokenizer( + const std::vector& stops, + const std::vector& preserved = {}) const override { + return std::unique_ptr(new DetokenizerBridge(vocab_, stops, preserved)); + } + +private: + std::shared_ptr vocab_; + Tokenizer tok_; +}; + +/* ================================================================== chat + * + * THE ONE PLACE THE TWO CHAT INTERFACES MEET. core/text's ChatTemplate renders the prompt and the + * generation prompt; the model's reply format (chatfmt.h) says how the reply is spelled, and + * everything that depends on the spelling -- the grammar, its trigger words, the tokens the + * decoder must render, and the parser that reads the reply back -- is derived from that one + * description here. Two decisions worth stating: + * + * * `preserved_tokens` IS CARRIED, and the reason is not the one it has upstream. Upstream it + * stops a sampler that bans special tokens from banning the ones a tool-call format is made + * of; this sampler has no ban stage at all (core/sample/sampler.h), so there is nothing to + * preserve them FROM. It is carried because the DECODER suppresses control tokens, and a + * format can be built out of them -- MiniCPM5 writes ` name="city">Berlin`, every tag gone, and comes back to the client as prose. + * These, and only these, are decoded as text. If a ban stage is ever added it wants this + * same field, for the original reason. + * + * * THE PARSER IS BUILT PER RENDER and handed over behind IReplyParser. A server-wide parser + * cannot be correct: which arguments are JSON depends on the schemas THIS request sent, and + * whether the reply starts inside a reasoning block depends on THIS generation prompt. + */ +class ReplyReaderBridge final : public IReplyReader { +public: + ReplyReaderBridge(std::unique_ptr s, const std::string* format_name) + : s_(std::move(s)), name_(format_name), + keep_(log_level() >= Log::Trace) {} + + void feed(std::string_view text, std::vector* out) override { + if (keep_) raw_.append(text); + s_->feed(text, out ? &ev_ : nullptr); + move_out(out); + } + + void finish(std::vector* out) override { + s_->finish(out ? &ev_ : nullptr); + move_out(out); + /* A reply that left the grammar still came back whole -- a call to a function that is + * not a tool, text inside a call, a call after a closing sentence -- but it is worth a + * line: it is either a model writing its format loosely or a format described wrongly, + * and nothing in the response says which. */ + if (!s_->strict() && !warned_) { + warned_ = true; + RAD_WARN("server: a reply left the '%s' reply format and was read by its recovery " + "rules; at trace level the reply is logged", name_->c_str()); + if (keep_) RAD_TRACE("server: the reply was <<<%s>>>", raw_.c_str()); + } + } + + ParsedMessage message() const override { + const ReplyMessage& r = s_->message(); + ParsedMessage m; + m.content = r.content; + m.reasoning = r.reasoning; + m.tool_calls.reserve(r.calls.size()); + for (const ReplyCall& c : r.calls) m.tool_calls.push_back({ std::string(), c.name, c.arguments }); + return m; + } + +private: + void move_out(std::vector* out) { + if (!out) return; + for (ReplyEvent& e : ev_) { + ReplyDelta d; + switch (e.kind) { + case ReplyEvent::Reasoning: d.kind = ReplyDelta::Reasoning; break; + case ReplyEvent::Content: d.kind = ReplyDelta::Content; break; + case ReplyEvent::CallBegin: d.kind = ReplyDelta::CallBegin; break; + case ReplyEvent::CallArgs: d.kind = ReplyDelta::CallArgs; break; + case ReplyEvent::CallEnd: d.kind = ReplyDelta::CallEnd; break; + } + d.call = e.call; + d.text = std::move(e.text); + out->push_back(std::move(d)); + } + ev_.clear(); + } + + std::unique_ptr s_; + const std::string* name_; + std::vector ev_; + bool keep_ = false, warned_ = false; + std::string raw_; /* the reply, kept only when trace logging is on */ +}; + +class ReplyParserBridge final : public IReplyParser { +public: + explicit ReplyParserBridge(std::shared_ptr p) : p_(std::move(p)) {} + std::unique_ptr open() const override { + return std::unique_ptr(new ReplyReaderBridge(p_->open(), &p_->format().name)); + } +private: + std::shared_ptr p_; +}; + +class ChatTemplateBridge final : public IChatTemplate { +public: + /* Returns RAD_OK, or the status ChatTemplate::load_from_vocab gave. A server whose template + * did not compile must not be wired: the endpoint answering 501 is a better outcome than one + * answering 200 with ChatML-shaped nonsense. + * + * `declared` is the architecture plugin's reply format (rad_arch_chat_format), or null to + * derive it from the template. A declaration the parser cannot run is refused here, at + * startup, rather than at the first request that needs it. */ + int init(const Vocab& v, const RadChatFormat* declared = nullptr, + const std::string& plugin = std::string()) { + /* The spellings, resolved once. See ReplyOptions::terminators. */ + terminators_.clear(); + for (int32_t id : v.eog()) { + const std::string s = v.text(id); + if (!s.empty()) terminators_.push_back(s); + } + const int st = t_.load_from_vocab(v); + if (st < 0) return st; + + ChatFormat f; + std::string why; + declared_ = declared != nullptr; + if (declared) { + if (chat_format_from_abi(declared, &f, &why) < 0 || chat_format_check(f, &why) < 0) { + RAD_ERR("chat: plugin '%s' declares a reply format the parser cannot run: %s", + plugin.c_str(), why.c_str()); + return RAD_E_INVAL; + } + if (f.name.empty()) f.name = "plugin:" + plugin; + } else { + const std::string bos = v.bos() >= 0 ? v.text(v.bos()) : std::string(); + const std::string eos = v.eos() >= 0 ? v.text(v.eos()) : std::string(); + std::string refused; + if (chat_format_from_template(v.chat_template(), bos, eos, &f, &refused, &why) < 0) { + RAD_WARN("chat: this model's reply format cannot be described (%s). Replies are " + "returned as content with no reasoning split, and requests with tools " + "are refused.", why.c_str()); + f = ChatFormat{}; + f.name = "content"; + tool_refusal_ = why; + } else if (!refused.empty()) { + tool_refusal_ = refused; + } else if (t_.caps().tools && !f.has_tools()) { + tool_refusal_ = "the template analysis found no tool-call format in it"; + } + } + if (ReplyFormat::compile(f, &fmt_, &why) < 0) { + RAD_ERR("chat: the reply format '%s' cannot be run: %s", f.name.c_str(), why.c_str()); + return RAD_E_INVAL; + } + RAD_INFO("chat: reply format %s", chat_format_describe(f).c_str()); + if (t_.caps().tools && !tool_refusal_.empty()) + RAD_WARN("chat: tool calls are refused for this model: %s", tool_refusal_.c_str()); + return RAD_OK; + } + + bool ready() const { return t_.ready() && fmt_ != nullptr; } + bool supports_tools() const override { return t_.caps().tools; } + bool supports_reasoning() const override { return t_.caps().preserve_reasoning; } + std::string tool_refusal() const override { return tool_refusal_; } + const std::string& source() const { return t_.source(); } + + int apply(const json& messages, const json& tools, const ChatRenderOptions& opt, + ChatRender* out, std::string* why) const override { + ChatOptions o; + o.add_generation_prompt = opt.add_generation_prompt; + o.enable_thinking = opt.enable_thinking; + o.parallel_tool_calls = opt.parallel_tool_calls; + o.tool_choice = opt.tool_choice; + o.reasoning_format = opt.reasoning_format; + o.grammar = opt.grammar; + o.json_schema = opt.json_schema; + o.template_kwargs = opt.template_kwargs; + + ChatPrompt p; + const int st = t_.apply(messages, tools, o, &p); + if (st < 0) { + /* THE TEMPLATE'S OWN SENTENCE WHERE THERE IS ONE. A jinja `raise_exception` names the + * field and the values it accepts; the generic line below names neither, and a caller + * reading a 400 has no other way to find out. */ + if (why) + *why = !p.error.empty() + ? p.error + : st == RAD_E_UNSUPPORTED + ? "the model's chat template refused this request" + : "the messages could not be rendered by this model's chat " + "template"; + return st; + } + + const ChatFormat& f = fmt_->format(); + /* Calls are parsed only when the request offered tools to call. With none, or with + * `tool_choice: "none"` (which arrives here with the tools already cleared), call syntax + * in the reply is prose to this request. */ + const bool calls = opt.tool_choice != "none" && tools.is_array() && !tools.empty(); + const bool doc = !opt.json_schema.empty(); + + out->prompt = std::move(p.prompt); + out->additional_stops = std::move(p.additional_stops); + out->generation_prompt = p.generation_prompt; + out->preserved_tokens = declared_ ? chat_format_markers(f) : p.preserved_tokens; + out->grammar_triggers.clear(); + + if (calls || doc) { + /* The grammar, and the words that trigger it, come from the reply format: the same + * description the parser reads the reply back with. */ + const nlohmann::ordered_json schema = + doc ? nlohmann::ordered_json::parse(opt.json_schema, nullptr, false) + : nlohmann::ordered_json(); + ChatGrammarRequest gq; + gq.tools = calls ? &tools : nullptr; + gq.json_schema = doc && schema.is_object() ? &schema : nullptr; + gq.generation_prompt = p.generation_prompt; + gq.parallel_tool_calls = opt.parallel_tool_calls; + gq.extract_reasoning = opt.reasoning_format != "none"; + ChatGrammar g; + std::string gerr; + if (chat_format_grammar(f, gq, &g, &gerr) < 0) { + if (why) *why = "the grammar for this request could not be built: " + gerr; + return RAD_E_INVAL; + } + out->grammar = std::move(g.text); + out->grammar_lazy = g.lazy; + for (const std::string& w : g.trigger_words) + out->grammar_triggers.push_back({ kTriggerWord, w }); + } else { + out->grammar = std::move(p.grammar); + out->grammar_lazy = p.grammar_lazy; + for (const auto& t : p.grammar_triggers) + out->grammar_triggers.push_back({ t.type, t.value }); + } + + ReplyOptions ro; + ro.generation_prompt = p.generation_prompt; + ro.extract_reasoning = opt.reasoning_format != "none"; + ro.tools = calls ? &tools : nullptr; + ro.parallel_tool_calls = opt.parallel_tool_calls; + ro.response_format = doc; + ro.terminators = terminators_; + std::shared_ptr rp; + std::string perr; + const int ps = ReplyParser::create(fmt_, ro, &rp, &perr); + if (ps < 0) { + if (why) *why = perr; + return ps; + } + out->parser = std::make_shared(std::move(rp)); + return RAD_OK; + } + +private: + /* A lazy grammar's trigger is a literal word; SamplingParams::GrammarTrigger numbers the + * kinds the way llama.cpp's common_grammar_trigger_type does. */ + static constexpr int kTriggerWord = 1; + + ChatTemplate t_; + std::vector terminators_; + std::shared_ptr fmt_; + bool declared_ = false; + std::string tool_refusal_; +}; + +/* ================================================================== grammar + * + * Compiles at ADMISSION, not at first token, so a schema that cannot be compiled is a 400 naming + * it rather than a request that starts and then dies on the step path -- and so the scheduler + * thread never compiles one. + */ +class GrammarBridge final : public IGrammarCompiler { +public: + explicit GrammarBridge(const VocabView* v) : v_(v) {} + + int from_json_schema(const json& schema, std::string& out, std::string& err) const override { + return grammar_from_json_schema(schema.dump(), "root", &out, &err); + } + + /* The whole compile -- parse, checks and mask plan -- on the admission thread. The program + * goes back to ride on the request; the sampler finds it by its text when the request starts, + * for as long as the request holds it. */ + int compile(const std::string& gbnf, std::shared_ptr* out, + std::string& err) const override { + if (gbnf.empty()) return RAD_OK; + if (!v_) { err = "no vocabulary attached"; return RAD_E_STATE; } + return gbnf_compile(gbnf, "root", v_, out, &err); + } + +private: + const VocabView* v_; +}; + +/* MEDIA, through the processor the container describes (core/mm). Present only when the program + * declared an encoder: `accepts` answers from what that encoder said it serves, so a request for + * video against an image-only tower is refused by the server with a reason rather than processed + * into patches nothing can encode. */ +class MultimodalBridge final : public IMultimodal { +public: + MultimodalBridge(const mm::Processor* p, uint32_t modalities) : p_(p), mod_(modalities) {} + + bool accepts(MediaKind k) const override { + if (!p_ || !mm::decoder_available()) return false; + if (k == MediaKind::Image) return (mod_ & RAD_MM_IMAGE) != 0; + if (k == MediaKind::Video) return (mod_ & RAD_MM_VIDEO) != 0; + return false; + } + + int prepare(MediaKind k, const std::vector& bytes, std::shared_ptr* out, + std::string* why) override { + if (!accepts(k)) { if (why) *why = "this kind of media is not served"; return RAD_E_UNSUPPORTED; } + return k == MediaKind::Image ? p_->image(bytes.data(), bytes.size(), out, why) + : p_->video(bytes.data(), bytes.size(), out, why); + } + +private: + const mm::Processor* p_; + uint32_t mod_; +}; + +} /* namespace server */ +} /* namespace rad */ + +#endif /* the engine components are present */ diff --git a/core/server/admin.cpp b/core/server/admin.cpp new file mode 100644 index 00000000..a9f40eff --- /dev/null +++ b/core/server/admin.cpp @@ -0,0 +1,347 @@ +/* core/server/admin.cpp -- vLLM's non-generation endpoints. + * + * /version /ping /load /tokenize /detokenize /get_tokenizer_info /server_info /reset_prefix_cache. + * + * Separate from server.cpp because none of it touches the step path: no admission, no Sink, no + * cancellation, nothing that outlives the handler. They are questions ABOUT the server, answered + * on the HTTP thread and finished before they return, and mixing them into the file that owns the + * streaming lifetime would make that file harder to read for no shared code at all. + * + * WHAT IS DELIBERATELY NOT HERE. vLLM's surface also carries /pooling, /classify, /score and + * /rerank (an embedding or cross-encoder model, which this engine does not load), /sleep, /wake_up + * and /is_sleeping (there is no sleep mode: weights are placed once, see spec §5), the LoRA + * adapter endpoints (no LoRA), /invocations (a SageMaker envelope around the others) and + * /v1/responses (a stateful conversation store, which is a component and not an endpoint). Each + * would be a lie in the shape of a 200, so each is absent and answers 404 rather than pretending. + */ +#include "server.h" + +#include "rad_internal.h" + +#include + +namespace rad { +namespace server { + +namespace { + +/* The body every "how loaded is this server" answer shares. /health and /ping are the same + * question asked by a load balancer and by a human, and vLLM answers both, so both exist here and + * neither is a redirect to the other -- a probe that follows a redirect is a probe that reports + * the redirect's latency. */ +/* `queue_cap` AND NOT `queue_depth`. The value is the CEILING -- `opt_.queue_depth` or + * max_seqs * 8 -- and it never changes while the server runs. Spelling it "queue_depth" would + * collide head-on with `radiance:http_queue_depth`, which is the OCCUPANCY ("admitted by the HTTP + * layer and not yet finished"): one name for two opposite quantities on the same server, so a + * dashboard graphing both plots a flat ceiling beside a number that moves and calls them the same + * thing. `queue_depth` therefore means occupancy everywhere it appears, and the occupancy is + * carried here too under its own names -- `in_flight` on /health and /server_info, `server_load` + * on /load. */ +json health_body(const std::string& model, bool stopping, int64_t in_flight, int64_t depth) { + json o; + o["status"] = stopping ? "stopping" : "ok"; + o["model"] = model; + o["in_flight"] = in_flight; + o["queue_cap"] = depth; + return o; +} + +/* nlohmann parses "3" and "[1,2]" happily, and both are the wrong shape for every endpoint here. + * Checking is_object() at the door means each handler's field reads can be plain rather than each + * one re-deciding what a non-object body means. Bounded like the generation endpoints' bodies + * (parse_json_bounded): /detokenize takes a token array, which is the body that grows most. */ +bool parse_object(const std::string& body, int64_t max_ctx, json* out, ApiError* err) { + *out = json::object(); + if (body.empty()) return true; /* {} -- every field takes its default */ + bool over = false, deep = false; + json j = parse_json_bounded(body, max_ctx, &over, &deep); + if (deep) { + *err = err_bad("body", "the request body nests more than " + + std::to_string(kJsonMaxDepth) + " levels deep"); + return false; + } + if (over) { + *err = err_bad("body", "the request body holds more than " + + std::to_string(json_value_budget(max_ctx)) + " JSON values"); + return false; + } + if (j.is_discarded()) { + *err = err_bad("body", "the request body is not valid JSON"); + return false; + } + if (!j.is_object()) { + *err = err_bad("body", "the request body must be a JSON object"); + return false; + } + *out = std::move(j); + return true; +} + +bool get_bool_or(const json& b, const char* key, bool def) { + auto it = b.find(key); + return it != b.end() && it->is_boolean() ? it->get() : def; +} + +} /* namespace */ + +/* ================================================================== /version */ +/* vLLM answers {"version": "..."} and a client that checks compatibility reads exactly that key, + * so it keeps the name and the shape. The rest is what this engine is, and it is here rather than + * in /server_info because a client deciding whether to talk to us at all should not have to ask + * for the whole configuration to find out which ABI the kernels were built against. */ +HttpResponse Server::handle_version(const HttpRequest&) { + json o; + o["version"] = opt_.version; + o["engine"] = "radiance"; + o["abi_version"] = (int)RAD_ABI_VERSION; + metrics_.observe_http(200); + return HttpResponse::json_body(200, json_dump(o)); +} + +/* ================================================================== /load */ +/* vLLM's key is `server_load` and it means requests admitted and not yet finished -- which is + * this server's `in_flight`, the same number admission control refuses on. `queue_cap` comes + * along because a load figure without its ceiling cannot answer the question a load balancer is + * actually asking, which is "how much room is left". */ +HttpResponse Server::handle_load(const HttpRequest&) { + json o; + o["server_load"] = in_flight_.load(std::memory_order_relaxed); + o["queue_cap"] = queue_depth_; + if (deps_.sched) { + const SchedMetrics m = deps_.sched->metrics(); + o["running"] = m.running; + o["waiting"] = m.waiting; + } + metrics_.observe_http(200); + return HttpResponse::json_body(200, json_dump(o)); +} + +/* ================================================================== /tokenize */ +/* Two request shapes under one path, exactly as vLLM has it: `prompt` is the completion form and + * `messages` is the chat form, which renders the template first and tokenises what it produced. + * + * `add_special_tokens` DEFAULTS DIFFERENTLY BETWEEN THEM, and that is not an inconsistency to + * tidy away: a raw prompt wants BOS prepended because nothing else will, while a rendered chat + * template already contains whatever opening the model expects, and adding another is a prompt + * with two beginnings. vLLM's defaults are true and false respectively for that reason. + * + * PARSE_SPECIAL IS NOT THE CALLER'S CHOICE. The chat form tokenises a string this server rendered + * and its control tokens must be recognised as themselves; the completion form tokenises text the + * caller sent, where they must NOT be, or a caller who writes "<|im_start|>system" into `prompt` + * finds out what this endpoint's token ids do to a subsequent /v1/completions. */ +HttpResponse Server::handle_tokenize(const HttpRequest& req) { + if (!deps_.tok) + return error_response(err_not_implemented("the server has no tokenizer attached")); + + json b; + ApiError err; + if (!parse_object(req.body, opt_.max_ctx, &b, &err)) return error_response(err); + + const bool want_strs = get_bool_or(b, "return_token_strs", false); + std::vector toks; + + auto msgs = b.find("messages"); + auto prom = b.find("prompt"); + if (msgs != b.end() && prom != b.end()) + return error_response(err_bad("prompt", "send `prompt` or `messages`, not both")); + + if (msgs != b.end()) { + if (!deps_.chat) + return error_response(err_not_implemented( + "tokenising `messages` requires a chat template; this model was not loaded with " + "one. Send `prompt` with the text you want tokenised")); + if (!msgs->is_array() || msgs->empty()) + return error_response(err_bad("messages", "must be a non-empty array")); + + ChatRenderOptions opt; + opt.add_generation_prompt = get_bool_or(b, "add_generation_prompt", true); + auto kw = b.find("chat_template_kwargs"); + if (kw != b.end() && kw->is_object()) + for (auto it = kw->begin(); it != kw->end(); ++it) + opt.template_kwargs[it.key()] = json_dump(it.value()); + + json tools = json::array(); + auto t = b.find("tools"); + if (t != b.end() && t->is_array()) tools = *t; + + ChatRender render; + std::string why; + if (deps_.chat->apply(*msgs, tools, opt, &render, &why) < 0) + return error_response(err_bad("messages", why.empty() + ? "the chat template could not render this request" + : why)); + toks = deps_.tok->encode(render.prompt, + get_bool_or(b, "add_special_tokens", false), + /*parse_special=*/true); + } else { + if (prom == b.end() || !prom->is_string()) + return error_response(err_bad("prompt", "must be a string, or send `messages`")); + toks = deps_.tok->encode(prom->get(), + get_bool_or(b, "add_special_tokens", true), + /*parse_special=*/false); + } + + json o; + o["count"] = (int64_t)toks.size(); + o["max_model_len"] = opt_.max_ctx; + o["tokens"] = toks; + if (want_strs) { + json strs = json::array(); + for (int32_t t : toks) strs.push_back(deps_.tok->piece(t)); + o["token_strs"] = std::move(strs); + } else { + o["token_strs"] = nullptr; + } + metrics_.observe_http(200); + return HttpResponse::json_body(200, json_dump(o)); +} + +/* ================================================================== /detokenize */ +/* vLLM's response key is `prompt` -- not `text` -- because the endpoint's purpose is to show what + * a token array would arrive as. The name is odd and it is the name clients read. */ +HttpResponse Server::handle_detokenize(const HttpRequest& req) { + if (!deps_.tok) + return error_response(err_not_implemented("the server has no tokenizer attached")); + + json b; + ApiError err; + if (!parse_object(req.body, opt_.max_ctx, &b, &err)) return error_response(err); + + auto t = b.find("tokens"); + if (t == b.end() || !t->is_array()) + return error_response(err_bad("tokens", "must be an array of integers")); + + std::vector toks; + toks.reserve(t->size()); + for (const auto& v : *t) { + if (!v.is_number_integer()) + return error_response(err_bad("tokens", "must be an array of integers")); + int32_t id = 0; + if (!token_id(v, &id)) + return error_response(err_bad("tokens", "a token id must be in [0, 2147483647], " + "got " + v.dump())); + toks.push_back(id); + } + + json o; + o["prompt"] = deps_.tok->decode(toks); + metrics_.observe_http(200); + return HttpResponse::json_body(200, json_dump(o)); +} + +/* ================================================================== /get_tokenizer_info */ +/* vLLM returns the HuggingFace tokenizer config verbatim, which this engine does not have: a .rad + * container carries a normalised vocabulary and not the JSON it was built from. So this answers + * the questions that config is actually READ for -- how big is the vocabulary, which ids end a + * generation, is a chat template available -- and says nothing it would have to invent. */ +HttpResponse Server::handle_tokenizer_info(const HttpRequest&) { + if (!deps_.tok) + return error_response(err_not_implemented("the server has no tokenizer attached")); + + const ITokenizer::VocabInfo v = deps_.tok->vocab_info(); + json o; + o["tokenizer_class"] = v.kind; + o["vocab_size"] = v.n_tokens; + o["model_max_length"] = opt_.max_ctx; + o["bos_token_id"] = v.bos >= 0 ? json(v.bos) : json(nullptr); + o["eos_token_id"] = v.eos >= 0 ? json(v.eos) : json(nullptr); + o["eot_token_id"] = v.eot >= 0 ? json(v.eot) : json(nullptr); + o["unk_token_id"] = v.unk >= 0 ? json(v.unk) : json(nullptr); + o["pad_token_id"] = v.pad >= 0 ? json(v.pad) : json(nullptr); + o["add_bos_token"] = v.add_bos; + o["add_eos_token"] = v.add_eos; + o["chat_template"] = deps_.chat != nullptr; + o["supports_tools"] = deps_.chat && deps_.chat->supports_tools(); + o["supports_reasoning"] = deps_.chat && deps_.chat->supports_reasoning(); + metrics_.observe_http(200); + return HttpResponse::json_body(200, json_dump(o)); +} + +/* ================================================================== /server_info */ +/* vLLM returns the repr() of its config object, which is a Python string a client can only print. + * This returns the same information as JSON, in two halves: what the SERVER decided, which is + * this component's own state, and what the ENGINE decided, which arrives pre-rendered because the + * server knows nothing about devices, containers or placement (ServerOptions::engine_info). + * + * `endpoints` is the router's own table rather than a list kept beside it. A hand-written list is + * a list that goes stale the first time somebody adds a route, and this endpoint exists precisely + * so that a client does not have to guess what is served. */ +HttpResponse Server::handle_server_info(const HttpRequest&) { + json srv; + srv["model"] = opt_.model_id; + srv["version"] = opt_.version; + srv["max_model_len"] = opt_.max_ctx; + srv["max_num_seqs"] = opt_.max_seqs; + srv["queue_cap"] = queue_depth_; + srv["default_max_tokens"] = opt_.default_max_tokens; + srv["max_n"] = opt_.max_n; + srv["uptime_s"] = unix_now() - started_at_; + srv["in_flight"] = in_flight_.load(std::memory_order_relaxed); + + json caps; + caps["chat"] = deps_.chat != nullptr; + caps["tools"] = deps_.chat && deps_.chat->supports_tools(); + caps["reasoning"] = deps_.chat && deps_.chat->supports_reasoning(); + caps["grammar"] = deps_.grammar != nullptr; + caps["embedding"] = deps_.embed != nullptr; + caps["image"] = deps_.mm && deps_.mm->accepts(MediaKind::Image); + caps["video"] = deps_.mm && deps_.mm->accepts(MediaKind::Video); + caps["audio"] = deps_.mm && deps_.mm->accepts(MediaKind::Audio); + caps["logprobs"] = opt_.supports_logprobs; + + json o; + o["server"] = std::move(srv); + o["capabilities"] = std::move(caps); + o["endpoints"] = router_.routes(); + + /* Spliced rather than re-parsed field by field: the engine owns what it says about itself and + * this component is a pipe for it. A blob that is not an object is dropped with a warning + * instead of corrupting the response -- an unparseable /server_info is worse than one that is + * missing a section. */ + if (!opt_.engine_info.empty()) { + json e = json::parse(opt_.engine_info, nullptr, false); + if (e.is_discarded() || !e.is_object()) + RAD_WARN("server: engine_info is not a JSON object; /server_info omits it"); + else + o["engine"] = std::move(e); + } + metrics_.observe_http(200); + return HttpResponse::json_body(200, json_dump(o)); +} + +/* ================================================================== /reset_prefix_cache */ +/* 501 when there is no prefix cache to reset, and that is the point: vLLM answers 200 with an + * empty body whether or not anything happened, so a benchmark that thinks it started cold has no + * way to find out it did not. This says how many entries went. */ +HttpResponse Server::handle_reset_prefix_cache(const HttpRequest&) { + if (!deps_.sched) + return error_response(err_not_implemented("the server has no engine attached")); + + const int64_t n = deps_.sched->reset_prefix_cache(); + if (n < 0) + return error_response(err_not_implemented( + "this engine has no prefix cache (started with --no-prefix-cache, or the model " + "declares no cacheable KV group)")); + + json o; + o["entries_dropped"] = n; + metrics_.observe_http(200); + return HttpResponse::json_body(200, json_dump(o)); +} + +/* ================================================================== /health, /ping */ +/* NOT counted in the HTTP status metrics, and neither is /metrics. A load balancer probing every + * second would otherwise dominate `request_success_total` and make the 2xx/5xx ratio a statement + * about the probe rather than about the service. */ +HttpResponse Server::handle_health(const HttpRequest& req) { return handle_ping(req); } + +HttpResponse Server::handle_ping(const HttpRequest&) { + const bool stopping = stopping_.load(); + return HttpResponse::json_body( + stopping ? 503 : 200, + json_dump(health_body(opt_.model_id, stopping, + in_flight_.load(std::memory_order_relaxed), queue_depth_))); +} + +} /* namespace server */ +} /* namespace rad */ diff --git a/core/server/dashboard.cpp b/core/server/dashboard.cpp new file mode 100644 index 00000000..8edf61b7 --- /dev/null +++ b/core/server/dashboard.cpp @@ -0,0 +1,3004 @@ +/* core/server/dashboard.cpp -- the web view of a running engine. + * + * Two routes: `/` serves a page, `/stats` serves the JSON it polls. Nothing else, and no + * framework: the page is a string literal in this file, so there is no asset directory to install, + * no build step that can go stale against the binary, and no network fetch at all. This engine is + * deployed on machines with no route to a CDN, and a dashboard that renders blank without one is + * a dashboard that does not exist. + * + * WHY IT IS NOT JUST /metrics. Prometheus exposition is the right answer for an operator who has + * a Prometheus, and this server serves it. It is the wrong answer for the question + * being asked here -- "what is this process doing right now" -- because getting to that answer + * costs a scrape config, a time-series database and a Grafana dashboard somebody has to build. + * The engine already has a terminal view for exactly this (liveview.h, spec §16); this is the + * same snapshot in a browser, which is where it can be looked at from another machine. + * + * THE PER-POSITION DRAFT PANEL IS THE POINT. Everything else here is visible in some other tool. + * The conditional acceptance at each draft position is not: it is in SchedMetrics and in /metrics + * as a labelled gauge, and no ordinary reading of either shows that one late position collapsed + * while the pooled rate stayed plausible. As a bar chart it is the first thing seen. + */ +#include "server.h" + +#include "rad_internal.h" + +#include + +#include + +namespace rad { +namespace server { + +/* ================================================================== /stats */ +/* One object, polled. It carries the scheduler's metrics, the per-position draft table and + * whatever the engine's snapshot function could see -- and it is deliberately NOT a stable + * public API: /metrics is that, with vLLM's names, and this is free to say whatever the page + * needs. A client automating against radiance should scrape /metrics. + * + * DERIVED RATES ARE THE PAGE'S JOB, not this handler's. Tokens a second and milliseconds a step + * are differences of counters over wall time, and the browser has both endpoints of the interval + * while this handler has neither -- computing them here would mean holding per-client state for + * something the client can subtract. */ + +/* ------------------------------------------------------------------ /sessions + * + * ITS OWN ROUTE, not a field in /stats. The dashboard polls /stats every second and a stored + * session changes on the scale of its idle thresholds -- tens of seconds at the fastest. Folding + * a table of conversations into the per-second poll would carry the same bytes a hundred times + * for each change in them, and the view that reads it is not even on screen most of the time. */ +HttpResponse Server::handle_sessions(const HttpRequest&) { + json o; + std::vector v; + SessionOccupancy occ; + if (deps_.sched) deps_.sched->sessions(&v, &occ); + + int64_t dev = 0, host = 0, disk = 0, bytes = 0; + int64_t sdev = 0, shost = 0, sdisk = 0; + json a = json::array(); + for (const SessionStat& s : v) { + json e; + e["id"] = s.id; + e["model"] = s.model; + e["tokens"] = s.n_tokens; + e["bytes"] = s.bytes; + e["idle_s"] = s.idle_s; + e["age_s"] = s.age_s; + e["on_device"] = s.on_device; + e["on_host"] = s.on_host; + e["on_disk"] = s.on_disk; + e["moving"] = s.moving; + /* THE RECURRENT HALF. On a hybrid model a session's attention blocks are only part of + * what it needs back; the rest is its linear-state snapshots, which are a different size + * of object in a different store. Counted where the BYTES are, so a snapshot that stayed + * on the device while its blocks went to disk shows as exactly that. */ + e["snapshots"] = s.snapshots; + e["snap_device"] = s.snap_device; + e["snap_host"] = s.snap_host; + e["snap_disk"] = s.snap_disk; + e["snap_bytes"] = s.snap_bytes; + e["resume_tokens"] = s.resume_tokens; + a.push_back(std::move(e)); + dev += s.on_device; host += s.on_host; disk += s.on_disk; + sdev += s.snap_device; shost += s.snap_host; sdisk += s.snap_disk; + bytes += s.bytes; + } + o["sessions"] = std::move(a); + /* SAID HERE SO A READER DOES NOT HAVE TO INFER IT. Two sessions sharing a system prompt share + * the blocks for it, so these per-session sizes overlap and adding them up over-counts -- on + * a server carrying long agent transcripts by more than an order of magnitude. The field + * names say so rather than pretending the sums are totals. */ + o["blocks_sum_overlapping"] = { { "device", dev }, { "host", host }, { "disk", disk } }; + o["snapshots"] = { { "device", sdev }, { "host", shost }, { "disk", sdisk } }; + o["bytes_sum_overlapping"] = bytes; + const SchedMetrics sm = deps_.sched ? deps_.sched->metrics() : SchedMetrics{}; + /* AND THE ONE FIGURE THAT IS NOT A SUM, because a view about what the conversations cost has + * to be able to say what the card is actually holding. The pool counts a block once however + * many sessions name it, which is the number an operator is asking for and the only one the + * per-session rows cannot be made to yield. One group's, the binding one -- see + * SchedMetrics::kv_tokens_used for why tokens across paged groups are not additive. */ + o["pool"] = { { "tokens_used", sm.kv_tokens_used }, + { "tokens_total", sm.kv_tokens_total }, + { "unshared_tokens", sm.kv_tokens_cached }, + { "bytes_used", sm.kv_bytes_used }, + { "bytes_total", sm.kv_bytes_total } }; + const IScheduler::TierCounters c = + deps_.sched ? deps_.sched->tier_counters() : IScheduler::TierCounters{}; + o["moved"] = { { "to_host", c.to_host }, { "dropped", c.dropped }, { "to_disk", c.to_disk }, + { "promoted", c.promoted }, { "host_freed", c.host_freed }, + { "host_drops", c.host_drops }, { "failures", c.failures }, + { "fetched", c.fetched } }; + /* THE SNAPSHOT COUNTERS ARE NOT OPTIONAL ON A HYBRID MODEL, because a server that moves every + * block it has and no snapshots at all looks identical in the block counters to one where + * tiering works -- and the difference is a full linear replay on every restored session. + * `starved` is the one to read when `to_host` stays at zero: it means the snapshot arena had + * no room, which --prefix-cache-host-mib fixes. */ + o["snapshots_moved"] = { { "to_host", c.ck_to_host }, { "to_disk", c.ck_to_disk }, + { "promoted", c.ck_promoted }, { "fetched", c.ck_fetched }, + { "drops", c.ck_drops }, + { "starved", c.ck_starved }, { "bytes_each", c.ck_bytes }, + { "host_slots", c.ck_host_slots }, + { "disk_slots", c.ck_disk_slots } }; + /* AND WHETHER ANY OF IT IS BEING READ. Moving a snapshot and restoring it proves the bytes + * travelled; this is the number that says a lookup then SERVED one. A hybrid server can move + * snapshots all day and still replay from token zero if the checkpoint the restore put back + * is not the one a hit can reach. */ + o["linear"] = { { "hit_rate", sm.linear_hit_rate }, + { "cached_tokens", sm.linear_cached_tokens }, + { "checkpoints_written", sm.checkpoints_written } }; + /* WHETHER ANYTHING MOVES, which is not whether anything is STORED. A session is recorded + * whether or not it can be demoted, so a non-empty table says only that something is held; + * these say whether a tier exists that can move it. */ + o["tiers"] = { { "host", c.host_on }, { "disk", c.disk_on } }; + /* WHAT IS OFF THE CARD, counted once -- see SessionOccupancy. */ + o["occupancy"] = { { "host_bytes", occ.host_bytes }, { "disk_bytes", occ.disk_bytes }, + { "host_cap_bytes", occ.host_cap_bytes }, + { "disk_cap_bytes", occ.disk_cap_bytes } }; + /* THE ATTENTION HIT RATE, for a model with no recurrent state, where it is the whole answer + * to how much of the prompt the cache served. On a hybrid model `linear.hit_rate` is. */ + o["prefix_hit_rate"] = sm.prefix_hit_rate; + o["enabled"] = c.host_on || c.disk_on; + return HttpResponse::json_body(200, json_dump(o)); +} + +HttpResponse Server::handle_stats(const HttpRequest&) { + json o; + o["model"] = opt_.model_id; + o["version"] = opt_.version; + o["uptime_s"] = unix_now() - started_at_; + o["in_flight"] = in_flight_.load(std::memory_order_relaxed); + o["queue_cap"] = queue_depth_; + o["now_ms"] = (int64_t)std::time(nullptr) * 1000; + + if (deps_.sched) { + const SchedMetrics m = deps_.sched->metrics(); + o["running"] = m.running; + o["waiting"] = m.waiting; + o["preempted"] = m.preempted; + o["kv_util"] = m.kv_util; + o["kv_tokens_used"] = m.kv_tokens_used; + o["kv_tokens_total"] = m.kv_tokens_total; + /* AND THE PART OF `used` THAT NO RUNNING REQUEST IS READING. Held is held, so a finished + * turn's blocks are in the figure above for exactly as long as the cache keeps them -- + * and on a server carrying conversations that is most of a full pool. Without the split + * a cache doing its job and a pool that never releases draw the same bar. */ + o["kv_tokens_cached"] = m.kv_tokens_cached; + /* THE POOL IN BYTES BESIDE THE POOL IN TOKENS, because they answer different questions and + * only one of them is about the card. Tokens say how much context fits; bytes say how much + * VRAM is being held, which is what a reader comparing the cache against the weights and + * against the card's total is asking. The two are not a unit conversion of each other: + * tokens are the binding paged group's and bytes are every group's, recurrent included. */ + o["kv_bytes_used"] = (double)m.kv_bytes_used; + o["kv_bytes_total"] = (double)m.kv_bytes_total; + o["kv_bytes_carved"] = (double)m.kv_bytes_carved; + o["prefix_hit_rate"] = m.prefix_hit_rate; + /* The leading indicator beside the lagging one: past ~75% kv utilisation the cache + * begins dropping prefixes the next turn wants, and the hit rate only falls once + * that has happened. An agent turn that re-prefills from scratch costs orders of + * magnitude more than one that resumes from the cache. */ + o["prefix_evictions"] = (double)m.prefix_evictions; + /* THE LINEAR HALF, WHICH THE ATTENTION HIT RATE SAYS NOTHING ABOUT. On a hybrid model a + * prompt can be 100% attention-cached and still re-run every recurrent layer over its + * whole prefix, because the two hit at different granularities. Without these a + * deployment cannot tell whether linear checkpointing is working at all. Zero throughout + * on a model with no recurrent state. */ + o["linear_hit_rate"] = m.linear_hit_rate; + o["linear_cached_tokens"] = (double)m.linear_cached_tokens; + o["checkpoints_written"] = (double)m.checkpoints_written; + o["prefill_tps"] = m.prefill_tps; + o["decode_tps"] = m.decode_tps; + o["draft_accept"] = m.draft_acceptance; + o["preemptions"] = m.preemptions; + o["total_requests"] = m.total_requests; + o["steps"] = m.steps; + o["steps_prefill"] = m.steps_prefill; + o["steps_mixed"] = m.steps_mixed; + o["steps_decode"] = m.steps_decode; + /* WHAT THE STEPS COST, so the page does not have to divide wall clock by a step count. + * That is the derivation this handler's header calls the page's job, and it is the one + * derivation the page cannot do: the browser's two endpoints bracket the engine's IDLE + * time as well as its work, and an agent client is idle between turns. See + * SchedMetrics::step_ns. */ + o["step_ns"] = m.step_ns; + o["step_ns_decode"] = m.step_ns_decode; + o["rows_unspec"] = m.decode_rows_unspeculated; + + /* THE CONDITIONAL RATE AT EACH POSITION, with the reach count beside it. Both are needed + * and neither alone means anything: a position with a rate of 0.0 and a reach of 3 is + * noise, and one with a rate of 0.0 and a reach of 40000 is a broken draft round. */ + json pos = json::array(); + for (int j = 0; j < m.draft_depth_seen && j < SchedMetrics::MAX_DRAFT_POS; ++j) { + json p; + p["reached"] = m.draft_pos_reached[j]; + p["accepted"] = m.draft_pos_accepted[j]; + p["rate"] = m.draft_pos_reached[j] > 0 + ? (double)m.draft_pos_accepted[j] / (double)m.draft_pos_reached[j] : 0.0; + pos.push_back(std::move(p)); + } + o["draft_positions"] = std::move(pos); + + /* THE LIVE REQUEST TABLE. Counters and timestamps, not rates the page could not check: + * `decode_tps` is this request's own average since its first token, which is the number + * that stays meaningful when a request has been running for four minutes. */ + std::vector rq; + deps_.sched->requests(&rq); + json reqs = json::array(); + for (const RequestStat& q : rq) { + json j; + j["id"] = q.id; + j["state"] = q.state; + j["prompt"] = q.prompt_tokens; + j["computed"] = q.computed_tokens; + j["cached"] = q.cached_tokens; + j["output"] = q.output_tokens; + j["max"] = q.max_tokens; + j["ctx"] = q.ctx_tokens; + j["kv_tokens"] = q.kv_tokens; + j["kv_blocks"] = q.kv_blocks; + j["draft"] = q.n_draft; + j["slot"] = q.slot; + j["age_s"] = q.age_s; + if (q.ttft_s >= 0) j["ttft_s"] = q.ttft_s; + j["tps"] = q.decode_tps; + reqs.push_back(std::move(j)); + } + o["requests"] = std::move(reqs); + } + + /* The engine's half. Absent when nothing supplied a snapshot function, in which case the page + * omits the panels rather than drawing zeroes -- an empty VRAM bar reads as "no memory used", + * which is a much worse answer than no bar. */ + if (deps_.live) { + LiveSnapshot s; + deps_.live(s); + + json cards = json::array(); + for (const CardStat& c : s.cards) { + json k; + k["index"] = c.index; + k["name"] = c.name; + k["vram_used"] = c.vram_used; + k["vram_total"] = c.vram_total; + /* 0 means "not sampled" for these three; the page shows nothing rather than a zero. */ + if (c.util > 0) k["util"] = c.util; + if (c.power_w > 0) k["power_w"] = c.power_w; + if (c.temp_c > 0) k["temp_c"] = c.temp_c; + cards.push_back(std::move(k)); + } + o["cards"] = std::move(cards); + + /* THE EXPERT PANEL'S DATA. The plane is the picture; everything beside it is what the + * picture cannot say -- how much of the model is resident in BYTES, whether the residency + * is spread across layers or piled into the first ones, and whether the move traffic is + * discovery or thrash. Counted in the engine (liveview.h), not here and not in the page: + * three tallies of one snapshot is three chances to disagree. */ + if (s.experts.n_layers > 0 && s.experts.n_experts > 0) { + json e; + e["n_layers"] = s.experts.n_layers; + e["n_experts"] = s.experts.n_experts; + e["tier"] = s.experts.tier; + e["n_units"] = s.experts.n_units; + e["bytes"] = s.experts.total_bytes; + e["movable"] = s.experts.movable; + e["heat"] = s.experts.heat_enabled; + /* One row per tier, named -- the page must not hold its own copy of the enum's order, + * which is the kind of duplication that survives a reordering and then lies. */ + json tiers = json::array(); + for (int t = 0; t < kTierCount; ++t) { + json r; + r["name"] = tier_name((Tier)t); + r["units"] = s.experts.units[t]; + r["bytes"] = s.experts.bytes[t]; + tiers.push_back(std::move(r)); + } + e["tiers"] = std::move(tiers); + e["layer_units"] = s.experts.layer_units; + e["layer_resident"] = s.experts.layer_resident; + e["promotions"] = s.experts.promotions; + e["demotions"] = s.experts.demotions; + e["distinct_promoted"] = s.experts.distinct_promoted; + e["readmits"] = s.experts.readmits; + e["routed"] = s.experts.routed; + e["routed_res"] = s.experts.routed_resident; + e["dispatches"] = s.experts.dispatches; + e["refused"] = s.experts.refused; + e["no_candidate"] = s.experts.no_candidate; + e["no_record"] = s.experts.no_record; + e["starved_slab"] = s.experts.starved_slab; + e["flex_bytes"] = (double)s.experts.flex_bytes; + e["flex_capacity"] = (double)s.experts.flex_capacity; + e["starved_pool"] = s.experts.starved_pool; + e["quarantined"] = s.experts.quarantined; + e["stage_layers"] = s.experts.stage_layers; + e["staged_units"] = s.experts.staged_units; + e["staged_bytes"] = (double)s.experts.staged_bytes; + e["stage_overflow"] = s.experts.stage_overflow; + o["experts"] = std::move(e); + } + + /* THE LINK. Cumulative byte counters and nothing derived: both ends of the poll interval + * are in the browser and neither is here, exactly as for step time above. */ + if (s.link.present) { + json l; + l["world"] = s.link.world; + l["ar_calls"] = s.link.ar_calls; + l["ar_bytes"] = s.link.ar_bytes; + l["h2d_bytes"] = s.link.h2d_bytes; + l["d2h_bytes"] = s.link.d2h_bytes; + l["ssd_reads"] = s.link.ssd_reads; + l["ssd_bytes"] = s.link.ssd_bytes; + l["prefetched"] = s.link.prefetched; + l["prefetch_bytes"] = s.link.prefetch_bytes; + l["staged_bytes"] = s.link.staged_bytes; + l["stream_bytes"] = s.link.stream_bytes; + o["link"] = std::move(l); + } + if (s.passes.present) { + json p; + p["played"] = s.passes.played; + p["recorded"] = s.passes.recorded; + p["audited"] = s.passes.audited; + p["issued_unkeyed"] = s.passes.issued_unkeyed; + p["issued_refused"] = s.passes.issued_refused; + p["issued_first"] = s.passes.issued_first; + p["dispatched"] = s.passes.dispatched; + p["unordered"] = s.passes.unordered; + o["passes"] = std::move(p); + } + } + + /* No metrics_.observe_http here, and the same reasoning as /health: a page polling twice a + * second would make request_success_total a statement about the dashboard. */ + return HttpResponse::json_body(200, json_dump(o)); +} + + +/* ================================================================== /graph */ +/* THE DECLARED COMPUTE GRAPH: every op, its bucket table, the kernel that resolved each band, the + * library it came from, the constraints it matched on and the chain it stands in for. + * + * `--debug-graph` prints all of this, but printing it is not the same as being able to look at it: + * the text dump answers the question on a terminal, at startup, on the machine the engine is on. + * This is the same walk (dump_graph_json shares every helper with the text one) served from the + * process that is actually running, which is where the question is usually asked. Static after + * declare, so it is rendered once and handed over. */ +HttpResponse Server::handle_graph(const HttpRequest&) { + if (!opt_.graph_json) + return error_response(err_not_implemented( + "the server was not given a declared graph; this build has no engine attached")); + HttpResponse r; + r.status = 200; + r.body = opt_.graph_json(); + return r; +} + +/* ================================================================== the page */ +/* One string. It is long, and every alternative is worse: a file on disk is a file that can be + * missing or stale against the binary, a generated header is a build step, and a framework is a + * network fetch. It parses no untrusted input -- every value it renders comes from /stats on the + * same origin and goes in through textContent or a numeric attribute, never innerHTML. + * + * IT IS BUILT ONCE AND UPDATED IN PLACE. A dashboard that rebuilds its DOM twice a second lays + * the document out twice a second, drops the reader's text selection every time, and flickers -- + * and it does that on the machine the engine is being watched from. Elements are created when + * their SHAPE changes (a different draft depth, a different card count) and after that only + * textContent and one style property are written. + * + * The design rules are the terminal view's (spec §16) in a browser: a number nobody sampled is + * blank rather than zero, a section with no data is hidden rather than empty, and nothing moves + * that is not actually changing. Black, one weight, one accent -- the numbers are the content and + * everything else on the page is there to not compete with them. */ +static const char* const kPage = R"HTML( + + + +radiance + +
+
+ +

radiance

+ + + + +
+
+ + +
+
–ms
+ decode step + +
+
–tok/s
+ decode + +
+
–tok/s
+ prefill + +
+ +
–
+ requests in flight + +
+ +
–
+ kv cache in vram + +
+
–%
+ acceptance + +
+
+ +
+
+
+
Requests +
+
+
+ + + +
+
nothing in flight
+
+
+
+ + + + + +
+ +
+
+
Batch +
+
+
+
+ decode + prefill + waiting + preempted + free +
+
+
Admission queue
+
–
+
+
+
+
+
+ +
+
Memory
+
+
+ + +
+
+ +
+ + + + + +
+ + +)HTML"; + +HttpResponse Server::handle_dashboard(const HttpRequest&) { + HttpResponse r; + r.status = 200; + r.content_type = "text/html; charset=utf-8"; + r.body = kPage; + /* No caching: the page and the binary ship together, so a browser holding yesterday's copy + * against today's /stats is a shape mismatch with no symptom other than blank panels. */ + r.set_header("Cache-Control", "no-store"); + return r; +} + +} /* namespace server */ +} /* namespace rad */ diff --git a/core/server/http.cpp b/core/server/http.cpp new file mode 100644 index 00000000..2427425c --- /dev/null +++ b/core/server/http.cpp @@ -0,0 +1,475 @@ +#include "http.h" +#include "rad_internal.h" + +/* httplib pulls in , and a great deal else. It is included in exactly this + * translation unit so that nothing above the transport seam pays for it. */ +#include "cpp-httplib/httplib.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rad { +namespace server { + +bool CiLess::operator()(const std::string& a, const std::string& b) const { + return std::lexicographical_compare( + a.begin(), a.end(), b.begin(), b.end(), + [](unsigned char x, unsigned char y) { return std::tolower(x) < std::tolower(y); }); +} + +std::string HttpRequest::header(const std::string& k, const std::string& def) const { + auto it = headers.find(k); + return it == headers.end() ? def : it->second; +} + +std::string HttpRequest::param(const std::string& k, const std::string& def) const { + auto it = params.find(k); + if (it != params.end()) return it->second; + auto q = query.find(k); + return q == query.end() ? def : q->second; +} + +HttpResponse HttpResponse::json_body(int status, std::string body) { + HttpResponse r; + r.status = status; + r.body = std::move(body); + return r; +} + +HttpResponse HttpResponse::text(int status, std::string body) { + HttpResponse r; + r.status = status; + r.content_type = "text/plain; charset=utf-8"; + r.body = std::move(body); + return r; +} + +/* ------------------------------------------------------------------ target parsing */ + +/* `+` IS A SPACE IN A QUERY STRING AND A PLUS SIGN IN A PATH. The two halves of a target are + * decoded by different rules: the form encoding that gives `+` its second meaning applies to + * `application/x-www-form-urlencoded` data, which is what a query string is and what a path is + * not. Decoding a path the query's way renames a route -- /v1/models/gpt+4 becomes a request for + * "gpt 4", which resolves to nothing and reports the name it was not asked about. */ +std::string url_decode(const std::string& s, bool plus_is_space) { + std::string out; + out.reserve(s.size()); + auto hex = [](char c) -> int { + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + if (c >= 'A' && c <= 'F') return c - 'A' + 10; + return -1; + }; + for (size_t i = 0; i < s.size(); ++i) { + if (s[i] == '%' && i + 2 < s.size()) { + int h = hex(s[i + 1]), l = hex(s[i + 2]); + if (h >= 0 && l >= 0) { out.push_back((char)(h * 16 + l)); i += 2; continue; } + } + out.push_back(plus_is_space && s[i] == '+' ? ' ' : s[i]); + } + return out; +} + +void parse_target(const std::string& target, std::string* path, + std::map* query) { + size_t q = target.find('?'); + if (path) *path = url_decode(target.substr(0, q), /*plus_is_space=*/false); + if (!query || q == std::string::npos) return; + size_t i = q + 1; + while (i < target.size()) { + size_t amp = target.find('&', i); + if (amp == std::string::npos) amp = target.size(); + std::string kv = target.substr(i, amp - i); + size_t eq = kv.find('='); + if (eq == std::string::npos) (*query)[url_decode(kv)] = ""; + else (*query)[url_decode(kv.substr(0, eq))] = url_decode(kv.substr(eq + 1)); + i = amp + 1; + } +} + +/* ------------------------------------------------------------------ routing */ + +static std::vector split_path(const std::string& p) { + std::vector out; + size_t i = 0; + while (i < p.size()) { + while (i < p.size() && p[i] == '/') ++i; + size_t j = i; + while (j < p.size() && p[j] != '/') ++j; + if (j > i) out.push_back(p.substr(i, j - i)); + i = j; + } + return out; +} + +void Router::add(std::string method, std::string path, Handler h) { + routes_.push_back(Route{std::move(method), split_path(path), std::move(h)}); +} + +std::vector Router::routes() const { + std::vector out; + for (auto& r : routes_) { + std::string p; + for (auto& s : r.segs) { p += '/'; p += s; } + out.push_back(r.method + " " + (p.empty() ? "/" : p)); + } + return out; +} + +static std::string error_body(const char* type, const std::string& msg) { + /* Hand-rolled rather than routed through nlohmann, because this is the one error path that + * must work even if the JSON layer is what failed. */ + std::string esc; + for (char c : msg) { + if (c == '"' || c == '\\') { esc.push_back('\\'); esc.push_back(c); } + else if (c == '\n') esc += "\\n"; + else if ((unsigned char)c < 0x20) esc += "?"; + else esc.push_back(c); + } + return std::string("{\"error\":{\"message\":\"") + esc + "\",\"type\":\"" + type + + "\",\"param\":null,\"code\":null}}"; +} + +HttpResponse Router::dispatch(HttpRequest req) const { + auto segs = split_path(req.path); + bool path_matched = false; + + for (const auto& r : routes_) { + if (r.segs.size() != segs.size()) continue; + std::map caps; + bool ok = true; + for (size_t i = 0; i < segs.size(); ++i) { + if (!r.segs[i].empty() && r.segs[i][0] == ':') caps[r.segs[i].substr(1)] = segs[i]; + else if (r.segs[i] != segs[i]) { ok = false; break; } + } + if (!ok) continue; + path_matched = true; + if (r.method != req.method) continue; + + req.params.insert(caps.begin(), caps.end()); + return r.h(req); + } + + if (path_matched) + return HttpResponse::json_body( + 405, error_body("invalid_request_error", + req.method + " is not allowed on " + req.path)); + return HttpResponse::json_body( + 404, error_body("not_found_error", "no route for " + req.method + " " + req.path)); +} + +HttpResponse Router::call(const std::string& method, const std::string& path, + const std::string& body) const { + HttpRequest r; + r.method = method; + parse_target(path, &r.path, &r.query); + r.body = body; + if (!body.empty()) r.headers["Content-Type"] = "application/json"; + return dispatch(std::move(r)); +} + +/* ------------------------------------------------------------------ the worker pool */ + +/* A WORKER FOR EVERY CONNECTION, UP TO A BOUND, STARTED THE MOMENT THE CONNECTION HAS NONE. + * + * httplib's own ThreadPool starts an extra worker only when it counts no idle one, and a worker + * counts as idle from the moment it is woken until it has taken its job. Two connections arriving + * inside that window leave the second queued with no worker started for it -- and a generation + * holds its worker for minutes, so that connection waits for the next one to arrive or for a + * generation to end. This pool compares the queue with the number of workers free to take from + * it, so a connection waits only once the pool is at its bound. + * + * `keep` workers stay up; the rest exit after kIdleExit with nothing to do. Past `most` workers, + * `queued` connections may wait (0: any number) and further ones are refused, which httplib + * answers by closing the socket. */ +class ConnectionPool final : public httplib::TaskQueue { +public: + ConnectionPool(size_t keep, size_t most, size_t queued) + : keep_(keep), most_(std::max(most, keep)), queued_(queued) { + std::lock_guard lk(m_); + for (size_t i = 0; i < keep_; ++i) start(); + } + ~ConnectionPool() override { shutdown(); } + + bool enqueue(std::function fn) override { + { + std::lock_guard lk(m_); + if (stop_) return false; + if (jobs_.size() >= free_) { /* no free worker is left for this job */ + const bool started = threads_.size() < most_ && start(); + if (!started && queued_ && jobs_.size() - free_ >= queued_) return false; + } + jobs_.push_back(std::move(fn)); + } + cv_.notify_one(); + return true; + } + + /* Runs what is queued, then joins every worker. Idempotent: httplib calls it and then + * destroys the pool, which calls it again. */ + void shutdown() override { + std::list live; + { + std::lock_guard lk(m_); + stop_ = true; + live.swap(threads_); + } + cv_.notify_all(); + for (auto& t : live) t.join(); + std::lock_guard lk(m_); + reap(); + } + +private: + static constexpr std::chrono::seconds kIdleExit{5}; + + /* With m_ held. False when the system will not give us a thread; the job then waits. */ + bool start() { + reap(); + try { + threads_.emplace_back([this] { work(); }); + } catch (const std::system_error& e) { + RAD_WARN("server: cannot start an HTTP worker (%s); the connection waits", e.what()); + return false; + } + ++free_; + return true; + } + + /* With m_ held: join the workers that exited idle. They left m_ before exiting, so this + * waits only for their last instructions. */ + void reap() { + for (auto& t : finished_) t.join(); + finished_.clear(); + } + + void work() { + std::unique_lock lk(m_); + for (;;) { + while (jobs_.empty() && !stop_) { + if (threads_.size() <= keep_) { cv_.wait(lk); continue; } + if (cv_.wait_for(lk, kIdleExit) == std::cv_status::timeout && jobs_.empty() && + !stop_ && threads_.size() > keep_) { + /* Hand this thread's handle to finished_, for the next start() to join. */ + for (auto it = threads_.begin(); it != threads_.end(); ++it) { + if (it->get_id() != std::this_thread::get_id()) continue; + finished_.push_back(std::move(*it)); + threads_.erase(it); + break; + } + --free_; + return; + } + } + if (jobs_.empty()) { --free_; return; } /* stopping, and nothing is left to run */ + std::function fn = std::move(jobs_.front()); + jobs_.pop_front(); + --free_; + lk.unlock(); + fn(); + lk.lock(); + ++free_; + } + } + + const size_t keep_, most_, queued_; + std::mutex m_; + std::condition_variable cv_; + std::list> jobs_; + std::list threads_; /* every worker not yet exited */ + std::vector finished_; /* exited idle, not yet joined */ + size_t free_ = 0; /* workers not running a job */ + bool stop_ = false; +}; + +/* ------------------------------------------------------------------ the httplib binding */ + +struct HttpTransport::Impl { + httplib::Server svr; + std::atomic port{0}; +}; + +HttpTransport::HttpTransport() : impl_(new Impl) {} +HttpTransport::~HttpTransport() { stop(); } + +void HttpTransport::stop() { if (impl_) impl_->svr.stop(); } + +/* Not before the accept loop is running: until then httplib's stop() has nothing to stop and + * does nothing, so a caller that took the port as "up" and then stopped would wait forever. */ +int HttpTransport::port() const { + return impl_ && impl_->svr.is_running() ? impl_->port.load() : 0; +} + +static void apply(const HttpResponse& r, httplib::Response& res) { + res.status = r.status; + for (auto& h : r.headers) res.set_header(h.first, h.second); +} + +int HttpTransport::serve(const Router& router, const TransportOptions& o) { + auto& svr = impl_->svr; + + /* A REQUEST LINE LONGER THAN httplib's LINE LIMIT (CPPHTTPLIB_MAX_LINE_LENGTH) GETS NO STATUS. + * Its line reader gives up before the request exists, and no handler, error handler or logger + * runs, so there is nothing here that could answer 414: the connection is closed unanswered. + * With the build's CPPHTTPLIB_REQUEST_URI_MAX_LENGTH equal to that limit, httplib's own 414 + * cannot fire either, because a target that long never fits in a line that is read. */ + svr.set_read_timeout(o.read_timeout_s, 0); + svr.set_write_timeout(o.write_timeout_s, 0); + svr.set_keep_alive_timeout(o.keep_alive_timeout_s); + svr.set_payload_max_length(o.max_body_bytes); + + int nt = o.n_threads > 0 ? o.n_threads : (int)std::thread::hardware_concurrency(); + if (nt < 4) nt = 4; + const size_t most = (size_t)std::max(o.max_threads, nt); + const size_t queued = (size_t)std::max(o.max_queued, 0); + svr.new_task_queue = [nt, most, queued] { return new ConnectionPool((size_t)nt, most, queued); }; + + /* A handler must never throw across the transport: an exception here closes the connection + * with no body at all, which is the least diagnosable failure a client can get. */ + svr.set_exception_handler([](const httplib::Request&, httplib::Response& res, + std::exception_ptr ep) { + std::string what = "unhandled exception in handler"; + try { std::rethrow_exception(ep); } + catch (const std::exception& e) { what = e.what(); } + catch (...) {} + RAD_ERR("server: %s", what.c_str()); + res.status = 500; + res.set_content(error_body("internal_server_error", what), "application/json"); + }); + + const std::string api_key = o.api_key; + const bool cors = o.cors; + + /* What a request must pass before its body is read, so a refused one never has it buffered. */ + auto gate = [api_key, cors](const httplib::Request& hreq, httplib::Response& hres) -> bool { + if (cors) { + hres.set_header("Access-Control-Allow-Origin", "*"); + hres.set_header("Access-Control-Allow-Headers", "Content-Type, Authorization"); + hres.set_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); + } + /* THE PROBE PATHS ARE EXEMPT, AND THE DASHBOARD PAGE. A load balancer cannot carry a + * bearer token, so an authenticated /health is a server that reports itself down. The + * page is the one static document the server has: it holds no data, and a browser opening + * it cannot send a header, so it loads and then sends the key on every fetch of data it + * makes. Everything else is guarded. vLLM's middleware guards only paths under /v1, + * leaving /tokenize open, which hands an unauthenticated caller the vocabulary and the + * chat template. This does not. */ + const std::string& p = hreq.path; + if (!api_key.empty() && p != "/health" && p != "/ping" && p != "/" && p != "/dashboard") { + std::string got = hreq.get_header_value("Authorization"); + const std::string want = "Bearer " + api_key; + if (got != want) { + hres.status = 401; + hres.set_content(error_body("authentication_error", "invalid api key"), + "application/json"); + return false; + } + } + return true; + }; + + auto bridge = [&router](const httplib::Request& hreq, std::string body, + httplib::Response& hres) { + HttpRequest req; + req.method = hreq.method; + req.path = hreq.path; + req.body = std::move(body); + for (auto& h : hreq.headers) req.headers[h.first] = h.second; + for (auto& p : hreq.params) req.query[p.first] = p.second; + req.closed = [&hreq] { return hreq.is_connection_closed(); }; + + HttpResponse res = router.dispatch(std::move(req)); + apply(res, hres); + + if (!res.streaming()) { + hres.set_content(std::move(res.body), res.content_type); + if (res.on_close) res.on_close(true); + return; + } + + /* Streaming. The provider owns the handler's state via the shared_ptr, because httplib + * keeps it alive past this function; `releaser` is what tells us whether the peer went + * away, and it is the hook cancellation hangs off. */ + auto st = std::make_shared(std::move(res)); + hres.set_chunked_content_provider( + st->content_type, + [st](size_t /*offset*/, httplib::DataSink& sink) -> bool { + std::string chunk; + bool more = st->next(chunk); + if (!chunk.empty()) { + if (!sink.write(chunk.data(), chunk.size())) return false; /* peer gone */ + } + if (!more) sink.done(); + return more; + }, + [st](bool ok) { if (st->on_close) st->on_close(ok); }); + }; + + for (const auto& sig : router.routes()) { + size_t sp = sig.find(' '); + std::string method = sig.substr(0, sp); + std::string path = sig.substr(sp + 1); + /* ":name" is httplib's own wildcard spelling too, so the pattern carries across. */ + if (method == "GET") { + svr.Get(path, [gate, bridge](const httplib::Request& q, httplib::Response& s) { + if (gate(q, s)) bridge(q, q.body, s); + }); + continue; + } + /* A POST BODY IS READ STRAIGHT INTO THE STRING THE HANDLER PARSES. Left to httplib it + * lands in its own Request first, which only hands it out const, so it would be copied + * into ours: a body at the size limit held twice before a byte of it is looked at. A + * multipart body is not read at all -- no endpoint takes one, and httplib discards what a + * handler leaves unread -- so the handler sees an empty body and refuses it. */ + svr.Post(path, [gate, bridge](const httplib::Request& q, httplib::Response& s, + const httplib::ContentReader& read) { + if (!gate(q, s)) return; + std::string body; + if (!q.is_multipart_form_data() && + !read([&body](const char* p, size_t n) { body.append(p, n); return true; })) { + /* httplib has already set 413 for a body over the limit; anything else is a peer + * that stopped sending partway, which has to be answered as something. */ + if (s.status < 0) { + s.status = 400; + s.set_content(error_body("invalid_request_error", + "the request body could not be read"), + "application/json"); + } + return; + } + bridge(q, std::move(body), s); + }); + } + svr.Options(".*", [cors](const httplib::Request&, httplib::Response& res) { + if (cors) { + res.set_header("Access-Control-Allow-Origin", "*"); + res.set_header("Access-Control-Allow-Headers", "Content-Type, Authorization"); + res.set_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); + } + res.status = 204; + }); + + /* Bound once: asking for a named port and then for any port would leave the first socket + * bound and unused. */ + const int port = o.port == 0 ? svr.bind_to_any_port(o.host.c_str()) + : svr.bind_to_port(o.host.c_str(), o.port) ? o.port : -1; + if (port <= 0) { + RAD_ERR("server: cannot bind %s:%d", o.host.c_str(), o.port); + return RAD_E_IO; + } + impl_->port.store(port); + RAD_INFO("server: listening on http://%s:%d (%d threads, up to %zu)", o.host.c_str(), port, + nt, most); + return svr.listen_after_bind() ? RAD_OK : RAD_E_IO; +} + +} /* namespace server */ +} /* namespace rad */ diff --git a/core/server/http.h b/core/server/http.h new file mode 100644 index 00000000..e3e27dcf --- /dev/null +++ b/core/server/http.h @@ -0,0 +1,153 @@ +/* core/server/http.h -- the transport seam. + * + * Everything above this line (routing, OpenAI translation, metrics) is written against these + * plain structs and never sees a socket. That is what lets tests/server_test.cpp drive the real + * handlers in-process: `Router::dispatch` is the same call the transport makes, minus the port. + * The alternative -- testing by binding a loopback socket -- tests cpp-httplib, which is already + * tested, and makes the suite depend on a free port. + */ +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace rad { +namespace server { + +/* Header names are case-insensitive per RFC 9110, and clients disagree about capitalisation of + * Authorization and Content-Type in particular. */ +struct CiLess { + bool operator()(const std::string& a, const std::string& b) const; +}; + +struct HttpRequest { + std::string method = "GET"; + std::string path; /* no query string */ + std::string body; + std::map headers; + std::map query; + std::map params; /* from a ":name" route segment */ + + /* True once the peer is gone. The transport supplies it; in-process it is absent and the + * waiting paths simply never see a drop. A dropped connection is a cancellation (spec §14), + * so every path that waits polls this. */ + std::function closed; + + std::string header(const std::string& k, const std::string& def = "") const; + std::string param(const std::string& k, const std::string& def = "") const; + bool peer_gone() const { return closed && closed(); } +}; + +struct HttpResponse { + int status = 200; + std::string content_type = "application/json; charset=utf-8"; + std::string body; + std::vector> headers; + + /* Streaming. When `next` is set, `body` is ignored and the transport pulls chunks until next() + * returns false. A chunk may legitimately be empty (nothing produced this poll), in which case + * nothing is written but the connection is checked. */ + std::function next; + + /* Runs exactly once when the connection ends, with `ok` false if the peer went away before the + * stream finished. This is where a dropped stream becomes a scheduler cancellation. */ + std::function on_close; + + bool streaming() const { return next != nullptr; } + + void set_header(std::string k, std::string v) { headers.emplace_back(std::move(k), std::move(v)); } + + static HttpResponse json_body(int status, std::string body); + static HttpResponse text(int status, std::string body); +}; + +using Handler = std::function; + +/* Exact-match routing plus a single ":name" wildcard segment, which is all the OpenAI surface + * needs (/v1/models/:id). No regex, no priority rules, nothing to reason about. */ +class Router { +public: + void add(std::string method, std::string path, Handler h); + void get(std::string path, Handler h) { add("GET", std::move(path), std::move(h)); } + void post(std::string path, Handler h) { add("POST", std::move(path), std::move(h)); } + + /* 404 with a body naming the path, 405 when the path exists under another method. By value, + * so the transport can move a request -- body included -- into the handler rather than copy + * a body that may be hundreds of megabytes. */ + HttpResponse dispatch(HttpRequest req) const; + + /* Convenience for tests and for anything that speaks in whole request lines. */ + HttpResponse call(const std::string& method, const std::string& path, + const std::string& body = "") const; + + std::vector routes() const; + +private: + struct Route { + std::string method; + std::vector segs; /* ":name" segments are wildcards */ + Handler h; + }; + std::vector routes_; +}; + +/* Split "/v1/models/foo?x=1" into path and decoded query parameters. */ +void parse_target(const std::string& target, std::string* path, + std::map* query); +/* Percent-decode. `plus_is_space` is the form encoding, which applies to a query string and + * not to a path -- see the definition. */ +std::string url_decode(const std::string& s, bool plus_is_space = true); + +/* ================================================================== the cpp-httplib binding */ + +/* ONE WORKER PER CONNECTION, for the connection's whole life: httplib reads a request, runs the + * handler and writes the response on the same thread, and a generation's handler runs until the + * generation ends. So the pool bounds are connection counts, and Server::run derives them from + * the admission ceiling rather than from the core count. */ +struct TransportOptions { + std::string host = "0.0.0.0"; + int port = 8000; /* 0 -> any free port; see HttpTransport::port */ + int n_threads = 0; /* kept alive while idle. 0 -> hardware_concurrency, + * floor 4 */ + int64_t max_threads = 0; /* what the pool may grow to. 0 -> n_threads */ + int64_t max_queued = 0; /* accepted connections that may wait for a worker once + * it has grown to max_threads; past that they are + * closed. 0 -> unbounded */ + /* The longest the peer may go silent while its REQUEST is being read. It bounds nothing about + * generation, which is written, not read. A connection that sends part of a request and then + * goes quiet holds a worker until this runs out, so it is short. */ + int read_timeout_s = 30; + int write_timeout_s = 600; + int keep_alive_timeout_s = 5; /* an idle connection's hold on a worker between requests */ + size_t max_body_bytes = 512ull << 20; /* images arrive base64 inside the JSON body */ + std::string api_key; /* "" disables the check */ + bool cors = true; +}; + +class HttpTransport { +public: + HttpTransport(); + ~HttpTransport(); + HttpTransport(const HttpTransport&) = delete; + HttpTransport& operator=(const HttpTransport&) = delete; + + /* Blocks until stop(). Returns RAD_OK, or negative if the bind failed. */ + int serve(const Router& r, const TransportOptions& o); + void stop(); + + /* The port serve() bound, which is the only way to learn it when it was asked for port 0. + * 0 until the server is accepting connections, so a non-zero answer also means stop() will + * take effect. */ + int port() const; + +private: + struct Impl; + std::unique_ptr impl_; +}; + +} /* namespace server */ +} /* namespace rad */ diff --git a/core/server/iface.h b/core/server/iface.h new file mode 100644 index 00000000..bf0363f5 --- /dev/null +++ b/core/server/iface.h @@ -0,0 +1,518 @@ +/* core/server/iface.h -- everything the server needs from components it does not own. + * + * The server is written against pure-virtual interfaces rather than against core/sched and + * core/text directly, for two reasons worth stating. The first is that the HTTP layer then carries + * no header dependency on those components and can be compiled without them. The second is that a + * test can drive every endpoint against a fake scheduler in-process, which is the only way to + * check cancellation and the streaming wire format without binding a port and loading a model. + * + * The cost is one virtual call per operation. That is paid on the admission path and on the HTTP + * thread, never inside rad_arch_step and never per token on the step path, so it is free where it + * would matter. The concrete types (rad::Scheduler, rad::Tokenizer, ...) are bound to these by + * the adapters in adapters.h: one line each at the wiring site. + */ +#pragma once +#include "rad_core.h" + +#include + +#include +#include +#include +#include +#include + +namespace rad { +namespace server { + +/* ordered_json, not json, and the reason is not cosmetic: a tool's parameter schema is rendered + * into the prompt in the order the caller wrote it, and property order in a JSON schema changes + * what the model emits. An unordered map would silently re-sort every caller's tool definitions. */ +using json = nlohmann::ordered_json; + +/* ================================================================== the scheduler + * + * ASSUMED of core/sched. `submit` takes the request by value and returns the id it assigned; + * `cancel` is idempotent and must free the request's KV blocks immediately rather than at the + * next completion (spec §14), because an agent client abandoning a long generation is the normal + * case, not an edge case. + */ +struct SchedMetrics { + int64_t waiting = 0; + int64_t running = 0; + int64_t preempted = 0; + double kv_util = 0.0; /* 0..1 of the paged KV pool */ + /* The paged pools in TOKENS. A percentage answers "how close to preemption"; tokens answer + * "how much context fits", and an operator sizing a deployment is asking the second. */ + int64_t kv_tokens_used = 0; + int64_t kv_tokens_total = 0; + /* AND HOW MUCH OF `used` NO RUNNING REQUEST IS READING, which is the difference between a + * cache doing its job and a leak. A finished turn's blocks stay held so the next turn can + * reuse them, so on a server carrying conversations this is most of the pool -- and with one + * number for the whole of it there is no way to tell that from a pool that never releases. + * It is the cache's UNSHARED holding: a block a running request is also reading belongs to + * that request in this split, because evicting it would free nothing. */ + int64_t kv_tokens_cached = 0; + /* AND THE PAGED AND STATEFUL POOLS TOGETHER, IN BYTES: how much of the card the KV cache is + * holding, which is the question an operator watching VRAM is actually asking and the one + * neither figure above can answer. Tokens cannot be summed across groups -- two paged groups + * share one token axis and a recurrent group has none -- so the totals above are one group's, + * the binding one. Bytes are disjoint allocations and add up, so these are every group. + * + * USED IS WHAT IS HELD, not what a live request is reading. A finished turn's blocks stay held + * by the prefix cache so the next turn can reuse them, and they are occupying VRAM for exactly + * as long; they stop counting when they reach the free list, which is where an eviction, a + * cancellation and an idle-tier demotion all put them. */ + int64_t kv_bytes_used = 0; + int64_t kv_bytes_total = 0; + /* What the pool was carved to address, which an elastic pool may not be holding. */ + int64_t kv_bytes_carved = 0; + + double prefix_hit_rate = 0.0; /* 0..1 */ + /* Cumulative prefix-cache evictions. `prefix_hit_rate` falls only AFTER a prefix that + * would have been reused is gone; this rises as it happens, which is the difference + * between an alert and a post-mortem. */ + int64_t prefix_evictions = 0; + int64_t prefix_ckpt_evictions = 0; + /* PREFIX CACHING, DECOUPLED (spec §7.3). `prefix_hit_rate` above is the ATTENTION one, because + * that is what vLLM's single number has always meant. The linear side hits at a different + * granularity -- whole checkpoints, not blocks -- and averaging the two would hide exactly the + * effect the decoupling exists to expose. So both are carried, and the token counts beside + * them, and the checkpoints actually written. Without all of it a deployment cannot tell + * whether linear checkpointing is working at all. */ + double linear_hit_rate = 0.0; + int64_t attn_cached_tokens = 0; + int64_t linear_cached_tokens = 0; + int64_t checkpoints_written = 0; + double prefill_tps = 0.0; + double decode_tps = 0.0; + /* AND THE EXACT COUNTS BEHIND THEM. The two rates above are EWMAs, which is the right thing + * for a dashboard and the wrong thing for anything that has to compare two runs: a gauge + * describes whatever mix the engine happened to be in when it was read. These cumulative + * totals are the comparable form, and the only one: `vllm:generation_tokens_total` is charged + * when a request FINISHES and is therefore identically zero over any steady-state window. */ + int64_t prefill_tokens = 0; + int64_t decode_tokens = 0; + double draft_acceptance = 0.0; /* 0..1, spec §10 */ + /* The exact pair the ratio is computed from, for the same reason. */ + int64_t draft_tokens = 0; + int64_t draft_accepted = 0; + /* THE PER-POSITION DRAFT HAZARD. `draft_acceptance` above is pooled over the whole window and + * cannot distinguish a drafter that decays with depth from one whose later rounds are broken: + * both read as one small number. These carry the conditional rate at each position -- of the + * verifies that reached j because every earlier position was accepted, the fraction that took + * j as well -- and the reach counts that say how much evidence each one has. */ + static const int MAX_DRAFT_POS = 64; + int draft_depth_seen = 0; + int64_t draft_pos_reached [MAX_DRAFT_POS] = {}; + int64_t draft_pos_accepted[MAX_DRAFT_POS] = {}; + int64_t preemptions = 0; + int64_t total_requests = 0; + /* ENGINE STEPS. One forward pass of the model plus whatever draft rounds followed it, which + * with speculation is more than one token -- so tokens a second cannot answer "how long is a + * step" and the two questions have to be asked separately. */ + int64_t steps = 0; + /* STEPS BY SHAPE. A step carrying a prefill chunk cannot roll back a rejected draft, so + * nothing in it speculates, decode rows included. These say how often the load produces that + * shape and how many decode rows paid for it. */ + int64_t steps_prefill = 0; + int64_t steps_mixed = 0; + int64_t steps_decode = 0; + int64_t steps_ahead = 0; /* issued behind the step before, ahead of its commit */ + int64_t decode_rows_unspeculated = 0; + /* WHAT THE STEPS COST: cumulative nanoseconds spent inside a step, and the decode half of it + * separately. A step time is not wall clock over a step count -- the engine idles between an + * agent's turns and a prefill chunk costs an order of magnitude more than a decode step, and + * a gauge that divides charges both to the decode step. `step_ns_decode / steps_decode` is + * what a decode step cost, whatever the load was doing around it. */ + int64_t step_ns = 0; + int64_t step_ns_decode = 0; +}; + + +/* WHAT ONE REQUEST IS DOING RIGHT NOW. The aggregate metrics answer "is the engine busy"; they + * cannot answer "which of these eight is stuck", and a request sitting in Waiting because its + * prompt will never fit is invisible in every one of them. */ + +/* ONE STORED CONVERSATION. Not a request: a request is in flight and is gone when it answers, + * while this is what the engine is still HOLDING on a session's behalf between turns -- which is + * the thing that decides whether the next turn costs a copy or a re-prefill. + * + * THE SIZES OVERLAP AND THE TOTAL IS NOT A SUM. Sessions that share a system prompt share the + * blocks for it, which is the entire point of a prefix cache; a view that hid that would make a + * server look like it was storing several times what it holds. Anything rendering these says so. + * + * A SESSION IS ROUTINELY SPLIT ACROSS TIERS, because a maintenance pass is bounded and moves a + * long conversation over several of them. So "where is it" is three counts and not a label. */ +struct SessionStat { + uint64_t id = 0; + std::string model; /* the container it was built against */ + int64_t n_tokens = 0; + int64_t bytes = 0; + double idle_s = 0; /* since its last turn */ + double age_s = 0; /* since it was first seen */ + int64_t on_device = 0, on_host = 0, on_disk = 0; /* blocks */ + /* LINEAR STATE, on a hybrid model, and counted apart from blocks because the two are not + * interchangeable. A session showing every block on disk and no snapshot anywhere will come + * back and re-run every recurrent layer over its whole transcript -- which the hit rate will + * report as a hit. Zero everywhere on a model that has no recurrent state. */ + int64_t snapshots = 0; + int64_t snap_device = 0, snap_host = 0, snap_disk = 0; + int64_t snap_bytes = 0; + /* The prefix a return skips: the deepest snapshot's position (IdleTiers::SessionInfo). */ + int64_t resume_tokens = 0; + bool moving = false; /* a transfer is outstanding */ +}; + +/* WHAT THE STORED CONVERSATIONS OCCUPY OFF THE CARD, blocks and snapshots each counted once -- + * the one total the per-session rows cannot be summed into. Caps are 0 for a tier that is off. */ +struct SessionOccupancy { + int64_t host_bytes = 0, disk_bytes = 0; + int64_t host_cap_bytes = 0, disk_cap_bytes = 0; +}; + +struct RequestStat { + uint64_t id = 0; + std::string state; /* waiting | prefill | decode | preempted | done */ + int64_t prompt_tokens = 0; + int64_t computed_tokens = 0; + int64_t cached_tokens = 0; + int64_t output_tokens = 0; + int64_t max_tokens = 0; + int64_t ctx_tokens = 0; + int64_t kv_blocks = 0; /* summed over the paged groups: they are disjoint allocations */ + /* The context it is holding, on the token axis the paged groups share -- NOT their sum. See + * the note at the definition: the two figures are in different units on purpose. */ + int64_t kv_tokens = 0; + int32_t n_draft = 0; + int32_t slot = -1; + double age_s = 0; + double ttft_s = -1; /* negative until the first token */ + double decode_tps = 0; +}; + +class IScheduler { +public: + virtual ~IScheduler() = default; + virtual uint64_t submit(Request&& r) = 0; + /* THE SEQUENCES OF ONE API REQUEST, all admitted before a step can see any of them: a prompt + * array or `n` > 1 submitted one call at a time can have a step begin between two calls, so + * the batch they decode in -- and its tie-level rounding -- would depend on thread timing. + * ids[i] is what submit() would have returned for rs[i]. This default is that loop, for a + * scheduler whose steps cannot interleave with submission. */ + virtual void submit_all(std::vector& rs, std::vector* ids) { + ids->clear(); + for (Request& r : rs) ids->push_back(submit(std::move(r))); + } + virtual void cancel(uint64_t id) = 0; + virtual SchedMetrics metrics() const = 0; + + /* "I am finished with this request's sink; you may drop the Request." core/sched keeps a + * terminal request alive precisely because the HTTP thread still holds its sink, so somebody + * has to say when that stops being true, and the HTTP thread is the only one who knows. + * Called at most once per submitted id, after the response has been written. Default no-op, + * for a scheduler that frees at completion. */ + virtual void reap(uint64_t /*id*/) {} + + /* CAN THIS REQUEST'S SAMPLING PARAMETERS BE SERVED AT ALL? + * + * A sampler op that does not resolve is deliberately not a declare failure -- a deployment + * that never sends `typical_p` does not need a typical kernel (core/sample/sampler.h). It + * becomes a failure when a request asks for it, and Sampler::check_request exists to say so + * by name. This is what the step loop relies on when it treats an unresolved stage as + * unreachable: without the check here, such a request is admitted, runs, and is cancelled + * mid-step with the reason in the log and a dead stream at the client. + * + * Asked once per submission, on the HTTP thread, before the first Request is built. Returns + * RAD_OK, or a negative status with `why` set. The default admits everything so a test's fake + * scheduler needs no change; the real answer comes from SchedulerBridge. */ + virtual int admit(const SamplingParams& /*sp*/, std::string* /*why*/) const { return RAD_OK; } + + /* DROP EVERY PREFIX-CACHE ENTRY, returning how many were dropped -- or a negative status when + * this build has no prefix cache, which is a 501 rather than a lie about having cleared one. + * + * vLLM has this endpoint and it exists for the same reason: the second run of a benchmark is + * not measuring what the first one measured, and an operator who cannot say "start cold" + * cannot compare two numbers. Releasing the cache's references is safe against a running step + * -- a block a live sequence holds stays allocated -- but it still takes the scheduler's lock, + * because the alternative is an HTTP thread walking the map a step is inserting into. */ + virtual int64_t reset_prefix_cache() { return RAD_E_UNSUPPORTED; } + + /* The live request table. Fills `out` and returns how many, oldest first; the default answers + * "this scheduler does not keep one", which is an empty table and not a wrong one. */ + virtual int requests(std::vector* /*out*/) const { return 0; } + + /* The stored conversations: what the engine is still holding between turns, and where. The + * default answers "this build has no idle tiers", which is an empty table and not a wrong + * one -- with the tiers off, everything the cache holds is in VRAM by definition. */ + virtual int sessions(std::vector* /*out*/, SessionOccupancy* /*occ*/) const { + return 0; + } + + /* WHAT THE TIERS HAVE ACTUALLY DONE. Without it the session table looks the same whether the + * tiers are working, switched off, or trying and failing every pass -- three very different + * situations that all render as "everything is in VRAM". */ + struct TierCounters { + /* `to_host` and `to_disk` count COPIES; `dropped` is VRAM given up after one and + * `host_freed` host slots given up after the disk copy. A conversation that returns before + * anything wants its VRAM is copied and never dropped. `host_drops` is entries lost with + * no disk tier to hold them. */ + int64_t to_host = 0, dropped = 0, to_disk = 0, promoted = 0; + int64_t host_freed = 0, host_drops = 0, failures = 0; + /* Entries and snapshots read off disk into host memory ahead of the restore that wanted + * them; `promoted` counts the restore itself. */ + int64_t fetched = 0, ck_fetched = 0; + int64_t host_bytes = 0, disk_bytes = 0; + /* THE LINEAR HALF, MOVED. Separate counters because a hybrid server can move every block + * it has and no snapshots at all -- the arena too small, the device slots contended -- + * and no block counter can tell that apart from tiering working. */ + int64_t ck_to_host = 0, ck_to_disk = 0, ck_promoted = 0, ck_drops = 0, ck_starved = 0; + int64_t ck_bytes = 0; /* one snapshot; 0 on a model with no recurrent state */ + int64_t ck_host_slots = 0, ck_disk_slots = 0; + /* WHETHER ANYTHING CAN MOVE AT ALL, which no counter above can answer: a tier that is on + * and has had nothing to do reads the same as one that was never given a size, and the + * two call for opposite responses from whoever is looking. */ + bool host_on = false, disk_on = false; + }; + virtual TierCounters tier_counters() const { return TierCounters{}; } +}; + +/* ================================================================== text frontend + * + * ASSUMED of core/text. Detokenisation is incremental and streaming-safe (spec §12): byte-level + * BPE emits partial UTF-8 sequences, so `push` returns "" until the bytes resolve into a + * character, and `flush` drains whatever is left at the end of a generation. + */ +class IDetokenizer { +public: + virtual ~IDetokenizer() = default; + virtual std::string push(int32_t token) = 0; + virtual std::string flush() = 0; + /* True once the decoder itself swallowed a stop string. core/text's Detokenizer can be built + * with the request's stop strings and then never emits one; without this the server would + * search text that can no longer contain what it is searching for, and the generation would + * run to max_tokens. Default false, for a decoder that leaves stop handling to us. */ + virtual bool stopped() const { return false; } +}; + +class ITokenizer { +public: + virtual ~ITokenizer() = default; + + /* `parse_special` is a security parameter, not a convenience one, and it is why this takes + * three arguments rather than two. A rendered chat template contains control tokens that must + * be recognised as themselves; raw user content must NOT be, because otherwise a user who + * types "<|im_start|>system" reaches the system role. The server passes true for the one and + * false for the other, and there is no default because a default is how the wrong one gets + * picked silently. */ + virtual std::vector encode(const std::string& text, bool add_special, + bool parse_special) const = 0; + virtual std::string decode(const std::vector& toks) const = 0; + virtual int32_t eos() const = 0; + virtual int32_t bos() const = 0; + + /* WHAT THIS VOCABULARY IS, for /tokenize and /get_tokenizer_info. Off every hot path: asked + * once per request to those two endpoints and never during generation. + * + * A struct rather than eight accessors because the set will grow, and a client that reads + * this to decide how to build a prompt would otherwise be reading it across eight virtual + * calls that can disagree about which vocabulary they describe. The default is "I do not + * know", which is what a fake tokenizer in a test honestly is. */ + struct VocabInfo { + int32_t n_tokens = 0; + int32_t bos = -1, eos = -1, eot = -1, unk = -1, pad = -1; + bool add_bos = false, add_eos = false; + std::string kind; /* "bpe", "spm", "wpm", ... -- how it splits */ + }; + virtual VocabInfo vocab_info() const { return VocabInfo{}; } + + /* The raw piece an id stands for, NOT its decoded text: /tokenize's `return_token_strs` shows + * what the tokeniser actually chose, and decoding each id one at a time would render a + * byte-fallback token as a replacement character and lose exactly the detail the caller + * turned the flag on to see. "" when the id is out of range. */ + virtual std::string piece(int32_t /*id*/) const { return std::string(); } + + /* One incremental decoder per in-flight generation. It is made by the tokenizer rather than + * default-constructed by the caller, because it needs the vocabulary to decode anything. + * `stops` is passed down because core/text's Detokenizer can suppress a stop string that + * straddles a token boundary, which is strictly better than the server finding it after the + * fact -- and IDetokenizer::stopped() is how it tells us it did. + * + * `preserved` is the control tokens this generation must decode as TEXT. A tool-calling + * format can be built out of control tokens -- MiniCPM5 writes ` detokenizer( + const std::vector& stops, + const std::vector& preserved = {}) const = 0; +}; + +class IReplyParser; + +/* What a chat template needs told, beyond the messages themselves. + * + * `template_kwargs` VALUES ARE JSON TEXT, not display text: `"false"`, `"\"high\""`, `"3"`. That + * is the shape the request carries them in and the shape the template context wants them in, and + * converting in between would mean this layer deciding that the string "false" is a boolean -- + * which is exactly the guess that makes `enable_thinking: "false"` silently enable thinking. */ +struct ChatRenderOptions { + bool add_generation_prompt = true; + bool enable_thinking = true; + bool parallel_tool_calls = true; + std::string tool_choice = "auto"; /* auto | none | required */ + std::string grammar; /* the caller's GBNF, or "" */ + std::string json_schema; /* a response_format schema, as JSON text, or "" */ + std::string reasoning_format = "auto"; + std::map template_kwargs; +}; + +/* What it gives back. A STRING IS NOT ENOUGH, and that is the whole reason this struct exists: a + * tool-calling template emits a prompt AND the grammar that makes the model's call parseable AND + * the triggers that keep that grammar off the prose AND the stop strings the format ends on. A + * seam that returns only the prompt drops the other three silently, which is a chat endpoint that + * accepts `tools` and then produces calls no client can read. */ +struct ChatRender { + std::string prompt; + + std::string grammar; /* the template's, merged with the caller's */ + bool grammar_lazy = false; + std::vector grammar_triggers; + std::vector additional_stops; + + /* The assistant prefix already inside `prompt`. The grammar describes the whole turn, so it + * has to be advanced over this before it constrains the first generated token. */ + std::string generation_prompt; + + /* The reply parser this render implies: the model's reply format bound to THESE tools and + * THIS generation prompt, so it cannot be a server-wide singleton. It reads calls only when + * the request sent tools. Null when nothing needs parsing. */ + std::shared_ptr parser; + + /* The tokens that parser must be able to SEE. See ITokenizer::detokenizer. */ + std::vector preserved_tokens; +}; + +class IChatTemplate { +public: + virtual ~IChatTemplate() = default; + + /* Render. Returns RAD_OK, or a negative status with `why` naming what the template refused -- + * which becomes the 400's message, so it has to read like something a caller can act on. */ + virtual int apply(const json& messages, const json& tools, const ChatRenderOptions& opt, + ChatRender* out, std::string* why) const = 0; + + virtual bool supports_tools() const = 0; + virtual bool supports_reasoning() const = 0; + + /* WHY THIS MODEL'S TOOL CALLS CANNOT BE READ, or "" when they can. A template may declare tool + * support in a format the reply parser does not describe; such a model still chats, and a + * request that sends tools is refused with this sentence rather than answered with calls + * nobody can read back. */ + virtual std::string tool_refusal() const { return std::string(); } +}; + +/* A reply taken apart: what core/text's reply parser gives back once the reply is complete. */ +struct ToolCall { + std::string id; /* "" from the parser; the server assigns one */ + std::string name; + std::string arguments; /* JSON text; unterminated when the reply stopped inside the call */ +}; + +struct ParsedMessage { + std::string content; + std::string reasoning; /* "" unless the template supports reasoning */ + std::vector tool_calls; +}; + +/* One increment of a reply that is being read as it is generated. What has been delivered is + * never revised: the concatenated increments of each kind ARE the finished values, which is what + * lets the streaming endpoint forward each one as it comes. */ +struct ReplyDelta { + enum Kind : uint8_t { + Reasoning, /* text: a reasoning delta */ + Content, /* text: a content delta */ + CallBegin, /* text: the function name; `call` is the new call's index */ + CallArgs, /* text: an arguments delta for call `call` */ + CallEnd, /* call `call` is closed */ + }; + Kind kind = Content; + uint32_t call = 0; + std::string text; +}; + +/* One choice's reply, read once, in order, as it is generated. feed() appends generated text + * and finish() says there is no more; each appends the increments it completes. The cost is + * linear in the reply however it is cut up -- the text is never read from the top again. */ +class IReplyReader { +public: + virtual ~IReplyReader() = default; + virtual void feed(std::string_view text, std::vector* out) = 0; + virtual void finish(std::vector* out) = 0; + /* The whole reply, once finish() has run. */ + virtual ParsedMessage message() const = 0; +}; + +/* A request's reply format. Each choice opens its own reader, and a request that sent no tools + * gets a parser that reads no calls: call syntax in its reply is text to that request. */ +class IReplyParser { +public: + virtual ~IReplyParser() = default; + virtual std::unique_ptr open() const = 0; +}; + +/* JSON-schema -> GBNF (spec §13). Errors are values: RAD_OK, or negative with `err` naming the + * part of the schema that could not be compiled. */ +class IGrammarCompiler { +public: + virtual ~IGrammarCompiler() = default; + virtual int from_json_schema(const json& schema, std::string& out, std::string& err) const = 0; + + /* Compile this GBNF, here, on the admitting thread, and hand back the program for the request + * to carry (SamplingParams::grammar_program). Compiling is where a grammar is found not to + * run -- left recursion, a construct the mask engine cannot serve, a bound it outgrows -- and + * where its mask plan is built, which is host work in the tens to hundreds of milliseconds. + * The alternative is doing both on the scheduler thread, where the only thing left to do about + * a failure is kill the request three tokens into its answer, and every other request's step + * waits for the build. A grammar that cannot be compiled is a 400 that names why. */ + virtual int compile(const std::string& gbnf, std::shared_ptr* out, + std::string& err) const = 0; +}; + +/* ================================================================== optional backends */ + +/* /v1/embeddings. Absent, the endpoint is 501 naming that this model was not loaded with an + * embedding head -- not an empty 200. */ +class IEmbedder { +public: + virtual ~IEmbedder() = default; + virtual int embed(const std::vector& tokens, std::vector& out) = 0; + virtual int64_t dim() const = 0; +}; + +/* Multimodal preprocessing (spec §11). The server pulls the bytes out of a content part; the + * processor behind this decodes them, resizes and cuts them for the encoder, and says which + * tokens take the part's place in the prompt -- placeholder runs, the markers around them and, + * for a video, the timestamps between its frames. */ +enum class MediaKind { Image, Video, Audio }; + +/* The placeholder a chat template renders where a media part sat. Both the template and the + * server have to agree on the spelling or the prompt silently loses its images, so it is declared + * once, here, rather than twice. llama.cpp's mtmd uses the same string, which is not an accident: + * the templates are the same templates. */ +#define RAD_MEDIA_MARKER "<__media__>" + +class IMultimodal { +public: + virtual ~IMultimodal() = default; + virtual bool accepts(MediaKind k) const = 0; + /* Decode and process one part. `bytes` is the decoded file, not a URL: the server never + * fetches a remote URL on a request's behalf. On success `*out` carries the patches and the + * token run that replaces the marker; on failure `why` says what is wrong with the media. */ + virtual int prepare(MediaKind k, const std::vector& bytes, + std::shared_ptr* out, std::string* why) = 0; +}; + + +} /* namespace server */ +} /* namespace rad */ diff --git a/core/server/json_partial.cpp b/core/server/json_partial.cpp new file mode 100644 index 00000000..1b26b5c5 --- /dev/null +++ b/core/server/json_partial.cpp @@ -0,0 +1,178 @@ +#include "json_partial.h" + +namespace rad { +namespace server { + +namespace { + +struct Scanner { + std::string_view s; + size_t i = 0; + + void ws() { + while (i < s.size() && (s[i] == ' ' || s[i] == '\t' || s[i] == '\n' || s[i] == '\r')) ++i; + } + bool eof() const { return i >= s.size(); } + char peek() const { return s[i]; } + + bool lit(std::string_view w) { + if (s.size() - i < w.size()) return false; + if (s.compare(i, w.size(), w) != 0) return false; + i += w.size(); + return true; + } + + bool str() { + if (eof() || s[i] != '"') return false; + ++i; + while (!eof()) { + char c = s[i]; + if (c == '\\') { + if (i + 1 >= s.size()) return false; + char e = s[i + 1]; + if (e == 'u') { + if (i + 5 >= s.size()) return false; + i += 6; + } else { + i += 2; + } + continue; + } + if (c == '"') { ++i; return true; } + ++i; + } + return false; /* unterminated */ + } + + bool num() { + size_t start = i; + if (!eof() && s[i] == '-') ++i; + size_t d0 = i; + while (!eof() && s[i] >= '0' && s[i] <= '9') ++i; + if (i == d0) { i = start; return false; } + if (!eof() && s[i] == '.') { + ++i; + size_t d1 = i; + while (!eof() && s[i] >= '0' && s[i] <= '9') ++i; + if (i == d1) { i = start; return false; } + } + if (!eof() && (s[i] == 'e' || s[i] == 'E')) { + ++i; + if (!eof() && (s[i] == '+' || s[i] == '-')) ++i; + size_t d2 = i; + while (!eof() && s[i] >= '0' && s[i] <= '9') ++i; + if (i == d2) { i = start; return false; } + } + return true; + } + + bool value(int depth) { + /* A hard depth cap, because the input is model output and a runaway "[[[[[..." would + * otherwise recurse until the stack ends. 256 is far past any real tool schema. */ + if (depth > 256) return false; + ws(); + if (eof()) return false; + char c = peek(); + if (c == '"') return str(); + if (c == '{') return obj(depth + 1); + if (c == '[') return arr(depth + 1); + if (c == 't') return lit("true"); + if (c == 'f') return lit("false"); + if (c == 'n') return lit("null"); + return num(); + } + + bool obj(int depth) { + ++i; /* '{' */ + ws(); + if (eof()) return false; + if (peek() == '}') { ++i; return true; } + for (;;) { + ws(); + if (!str()) return false; + ws(); + if (eof() || peek() != ':') return false; + ++i; + if (!value(depth)) return false; + ws(); + if (eof()) return false; + if (peek() == ',') { ++i; continue; } + if (peek() == '}') { ++i; return true; } + return false; + } + } + + bool arr(int depth) { + ++i; /* '[' */ + ws(); + if (eof()) return false; + if (peek() == ']') { ++i; return true; } + for (;;) { + if (!value(depth)) return false; + ws(); + if (eof()) return false; + if (peek() == ',') { ++i; continue; } + if (peek() == ']') { ++i; return true; } + return false; + } + } +}; + +} /* namespace */ + +bool json_complete(std::string_view s) { + Scanner sc{s}; + if (!sc.value(0)) return false; + sc.ws(); + return sc.eof(); +} + +size_t utf8_trunc(std::string_view s) { + size_t n = s.size(); + if (n == 0) return 0; + /* Walk back over at most three continuation bytes to find the lead byte, then decide whether + * the sequence it starts is complete. */ + size_t k = n; + size_t back = 0; + while (k > 0 && back < 4) { + unsigned char c = (unsigned char)s[k - 1]; + if ((c & 0xC0) == 0x80) { --k; ++back; continue; } + size_t need = 1; + if ((c & 0x80) == 0x00) need = 1; + else if ((c & 0xE0) == 0xC0) need = 2; + else if ((c & 0xF0) == 0xE0) need = 3; + else if ((c & 0xF8) == 0xF0) need = 4; + else return n; /* not a lead byte: not our truncation to fix */ + size_t have = n - (k - 1); + return have >= need ? n : k - 1; + } + return n; +} + +size_t json_stable_prefix(std::string_view s) { + size_t n = utf8_trunc(s); + if (n == 0) return 0; + + /* Back out of an unfinished escape. Count the run of backslashes immediately before the cut: + * an odd run means the last one is an opening escape whose payload has not arrived. */ + size_t bs = 0; + while (bs < n && s[n - 1 - bs] == '\\') ++bs; + if (bs % 2 == 1) return n - 1; + + /* Back out of an unfinished "\uXXXX". `k` is how many characters have arrived after the 'u', + * so the escape is complete at k == 4 and short before it. Only six bytes ever need looking + * at, which is why this is a loop and not a parser. */ + for (size_t k = 0; k <= 4 && n >= k + 2; ++k) { + if (s[n - 1 - k] != 'u') continue; + if (s[n - 2 - k] != '\\') break; + size_t bs2 = 0, j = n - 2 - k; + while (j > 0 && s[j - 1] == '\\') { ++bs2; --j; } + if (bs2 % 2 == 1) break; /* the backslash was itself escaped */ + if (k < 4) return n - 2 - k; /* fewer than four hex digits have arrived */ + break; + } + return n; +} + +} /* namespace server */ +} /* namespace rad */ diff --git a/core/server/json_partial.h b/core/server/json_partial.h new file mode 100644 index 00000000..909e709e --- /dev/null +++ b/core/server/json_partial.h @@ -0,0 +1,40 @@ +/* core/server/json_partial.h -- what may be sent, and what may be called a tool call. + * + * Two questions about text that is still arriving, and they are different questions: + * + * 1. "Is this a tool call?" -- answered by `json_complete`. Nothing is ever reported to a + * client as `finish_reason: "tool_calls"` unless the arguments parse whole. A malformed call + * is returned as ordinary content, because a client that gets a truncated arguments object + * and is told it is a tool call will call the tool with the wrong arguments. + * + * 2. "How much of it can I put on the wire right now?" -- answered by `json_stable_prefix`. + * A streamed fragment is itself JSON-encoded into the SSE payload, so it must end on a UTF-8 + * boundary: cutting a multi-byte code point in half turns one delta into mojibake and the + * next into a decode error. + * + * This is a scanner, not a parser: it allocates nothing and builds no DOM. + */ +#pragma once + +#include +#include + +namespace rad { +namespace server { + +/* Does `s` parse as exactly one complete JSON value, with only whitespace after it? */ +bool json_complete(std::string_view s); + +/* Largest n <= s.size() such that s[0,n) ends on a UTF-8 code point boundary. Bytes that are not + * valid UTF-8 at all are left alone -- this backs out of a truncation, it does not validate. */ +size_t utf8_trunc(std::string_view s); + +/* Largest prefix of `s` that is safe to emit as one streaming fragment: a UTF-8 boundary, and not + * in the middle of a "\uXXXX" escape or on a lone trailing backslash. The escape rule buys + * nothing for a client that only concatenates, and costs four bytes of latency; it is here + * because a client that pretty-prints each delta is a client that would otherwise print a broken + * escape, and the class of bug that produces is unbisectable from the server side. */ +size_t json_stable_prefix(std::string_view s); + +} /* namespace server */ +} /* namespace rad */ diff --git a/core/server/liveview.cpp b/core/server/liveview.cpp new file mode 100644 index 00000000..f10c53be --- /dev/null +++ b/core/server/liveview.cpp @@ -0,0 +1,372 @@ +#include "liveview.h" +#include "iface.h" +#include "rad_internal.h" + +#include +#include +#include +#include +#include + +namespace rad { +namespace server { + +static_assert((int)kLiveTiers == kTierCount, + "liveview.h restates rad::kTierCount; the tier enum grew and the snapshot did not"); + +void snapshot_from(const SchedMetrics& m, LiveSnapshot* out) { + out->waiting = m.waiting; + out->running = m.running; + out->preempted = m.preempted; + out->kv_util = m.kv_util; + out->prefix_hit_rate = m.prefix_hit_rate; + out->prefix_evictions = m.prefix_evictions; + out->prefill_tps = m.prefill_tps; + out->decode_tps = m.decode_tps; + out->draft_acceptance = m.draft_acceptance; + out->total_requests = m.total_requests; + out->preemptions = m.preemptions; + /* The step counter is the one field a stalled loop moves and everything else does not: + * throughput decays toward zero on its own, but a step count frozen between two draws says + * the loop itself stopped. It comes from the same metrics as the rest. */ + out->step = m.steps; +} + +/* ------------------------------------------------------------------ small formatting */ + +namespace { + +/* Tier -> colour. The order matches rad::Tier: VRAM, HostPinned, HostPageable, SSD, Mapped. Green is + * resident and fast, red is on a disk; the gradient is the point, so a glance at the plane says + * how much of the model is where without reading a number. */ +const char* tier_colour(uint8_t t) { + switch (t) { + case 0: return "\033[32m"; /* VRAM */ + case 1: return "\033[33m"; /* host, pinned */ + case 2: return "\033[35m"; /* host, pageable */ + case 4: return "\033[36m"; /* the container's mapping */ + default: return "\033[31m"; /* SSD */ + } +} +char tier_glyph(uint8_t t) { + switch (t) { + case 0: return '#'; + case 1: return '+'; + case 2: return '-'; + default: return '.'; + } +} + +std::string bar(double frac, int width, bool colour) { + if (frac < 0) frac = 0; + if (frac > 1) frac = 1; + int fill = (int)std::lround(frac * width); + std::string s; + if (colour) s += frac > 0.9 ? "\033[31m" : (frac > 0.7 ? "\033[33m" : "\033[32m"); + s.append((size_t)fill, '='); + if (colour) s += "\033[0m"; + s.append((size_t)(width - fill), ' '); + return s; +} + +std::string gib(int64_t bytes) { + char b[48]; + snprintf(b, sizeof b, "%.1fG", (double)bytes / (1024.0 * 1024.0 * 1024.0)); + return b; +} + +std::string f2(double v) { + char b[32]; + snprintf(b, sizeof b, "%.2f", v); + return b; +} + +/* Tokens a second, never scaled by a prefix: rates are read against each other digit by digit, + * and 6.12k beside 5.98k hides the difference 6116 beside 5979 shows. */ +std::string tps(double v) { + char b[32]; + snprintf(b, sizeof b, v >= 99.95 ? "%.0f" : "%.1f", v); + return b; +} + +/* ---- the terminal form's figures. + * + * THE WEB PAGE'S RULES (dashboard.cpp), so the two views of one snapshot print one figure. Three + * significant figures and at most two decimals, ROUNDED BEFORE THE UNIT IS CHOSEN -- choosing the + * unit first prints 1023.7 MiB as "1024 MiB". Sizes in binary units, because the card and every + * --*-mib flag count in them. Counters exact and grouped in threes by a narrow space past four + * digits, as SI writes them. A share never rounds onto 0% or 100%. + * + * The piped form above keeps its own formatting: it is parsed as well as read, and its keys and + * value shapes are what a log consumer already matches. */ + +/* The digits of 0 <= a < 999.5; the thresholds are where the rounded value gains a digit. */ +std::string sig3(double a) { + char b[32]; + snprintf(b, sizeof b, "%.*f", a >= 99.95 ? 0 : a >= 9.995 ? 1 : 2, a); + return b; +} + +/* A value on a unit ladder: steps up while the value would round to four digits. `exact` prints + * the first rung as a whole number -- "5.00 B" is a precision that does not exist. */ +std::string ladder(double v, double base, const char* const* units, int n_units, bool exact, + const char* sep) { + if (!std::isfinite(v)) return "-"; + const char* u = units[0]; + std::string n; + if (v == 0.0) { + n = "0"; + } else { + double a = std::fabs(v); + int i = 0; + while (a >= 999.5 && i < n_units - 1) { a /= base; ++i; } + u = units[i]; + n = (i == 0 && exact) ? std::to_string(std::llround(a)) : sig3(a); + if (v < 0) n = "-" + n; + } + return *u ? n + sep + u : n; +} + +const char* const kIec[] = { "B", "KiB", "MiB", "GiB", "TiB", "PiB" }; +const char* const kPfx[] = { "", "k", "M", "G", "T", "P" }; + +std::string size_iec(int64_t bytes) { return ladder((double)bytes, 1024.0, kIec, 6, true, " "); } + +/* Used and total of one quantity, the unit said once when it is the same unit. */ +std::string size_of(int64_t used, int64_t total) { + std::string a = size_iec(used), b = size_iec(total); + const size_t ia = a.rfind(' '), ib = b.rfind(' '); + if (ia != std::string::npos && ib != std::string::npos && a.substr(ia) == b.substr(ib)) + return a.substr(0, ia) + " / " + b; + return a + " / " + b; +} + +/* A continuous quantity -- watts, degrees -- to three figures and an SI prefix. Not tokens a + * second: tps() prints those whole. */ +std::string num_si(double v) { return ladder(v, 1000.0, kPfx, 6, false, ""); } + +/* A counter, exact, grouped in threes by U+202F past four digits. */ +std::string grouped(int64_t n) { + std::string d = std::to_string(n < 0 ? -n : n), o; + for (size_t i = 0; i < d.size(); ++i) { + if (i && d.size() > 4 && (d.size() - i) % 3 == 0) o += " "; + o += d[i]; + } + return n < 0 ? "-" + o : o; +} + +/* A share of one to one decimal. Only exactly 0 reads 0 and only exactly 1 reads 100. */ +std::string share(double f) { + if (!std::isfinite(f)) return "-"; + char b[32]; + snprintf(b, sizeof b, "%.1f", 100.0 * f); + if (f > 0 && strcmp(b, "0.0") == 0) return "<0.1%"; + if (f < 1 && strcmp(b, "100.0") == 0) return ">99.9%"; + return std::string(b) + "%"; +} + +} /* namespace */ + +/* ------------------------------------------------------------------ construction */ + +LiveView::LiveView(Source src, int interval_ms, FILE* out) + : src_(std::move(src)), interval_ms_(interval_ms), out_(out ? out : stdout) { + tty_ = isatty(fileno(out_)) != 0; + if (tty_) { + struct winsize ws; + if (ioctl(fileno(out_), TIOCGWINSZ, &ws) == 0 && ws.ws_col > 20) cols_ = ws.ws_col; + } +} + +LiveView::~LiveView() { stop(); } + +void LiveView::start() { + if (running_.exchange(true)) return; + thread_ = std::thread([this] { loop(); }); +} + +void LiveView::stop() { + if (!running_.exchange(false)) return; + if (thread_.joinable()) thread_.join(); + if (tty_) { + /* Leave the terminal as we found it: cursor visible, no leftover attributes. */ + fputs("\033[?25h\033[0m\n", out_); + fflush(out_); + } +} + +void LiveView::loop() { + if (tty_) fputs("\033[?25l", out_); /* hide the cursor; the redraw is what moves it */ + LiveSnapshot s; + while (running_.load()) { + s = LiveSnapshot{}; + if (src_) src_(s); + std::string frame = tty_ ? render_screen(s) : render_line(s); + fwrite(frame.data(), 1, frame.size(), out_); + fflush(out_); + std::this_thread::sleep_for(std::chrono::milliseconds(interval_ms_)); + } +} + +/* ------------------------------------------------------------------ the piped form + * + * One ordinary line per interval, key=value, no escape sequences, no cursor movement. This is + * what a log file or a `| tee` gets, and it is greppable and diffable by construction. + */ +std::string LiveView::render_line(const LiveSnapshot& s) const { + std::string o = "live"; + o += " step=" + std::to_string(s.step); + o += " run=" + std::to_string(s.running); + o += " wait=" + std::to_string(s.waiting); + if (s.preempted) o += " preempt=" + std::to_string(s.preempted); + o += " kv=" + f2(s.kv_util); + o += " prefix_hit=" + f2(s.prefix_hit_rate); + if (s.prefix_evictions) o += " prefix_evict=" + std::to_string(s.prefix_evictions); + o += " prefill_tps=" + tps(s.prefill_tps); + o += " decode_tps=" + tps(s.decode_tps); + if (s.draft_acceptance > 0.0) o += " draft_accept=" + f2(s.draft_acceptance); + + for (const auto& c : s.cards) { + o += " gpu" + std::to_string(c.index) + "="; + o += f2(c.util); + o += "/vram:" + gib(c.vram_used) + "of" + gib(c.vram_total); + if (c.power_w > 0) { o += "/pw:" + f2(c.power_w); } + if (c.temp_c > 0) { o += "/t:" + f2(c.temp_c); } + } + + if (s.experts.n_units > 0) { + /* THE SNAPSHOT'S OWN TALLY, not a second walk of the plane. Walking it would count CELLS, + * which is not the same as counting UNITS: the plane is a rectangle and a model need not + * fill it -- a draft head carrying fewer experts than the trunk leaves empty cells, and + * those cells would be charged to whatever tier their row was initialised at. The engine + * counts the units it actually placed (liveview.h) and both renderers read that. */ + o += " experts vram=" + std::to_string(s.experts.units[0]); + o += " pinned=" + std::to_string(s.experts.units[1]); + o += " host=" + std::to_string(s.experts.units[2]); + o += " ssd=" + std::to_string(s.experts.units[3]); + o += " resident=" + f2(s.experts.n_units + ? 100.0 * (double)s.experts.units[0] / (double)s.experts.n_units + : 0.0) + "%"; + /* THE HIT RATE, which residency does not imply: a plan holding most of the units still + * misses on most tokens if the hot ones are the ones outside. */ + if (s.experts.routed > 0) + o += " hit=" + f2(100.0 * (double)s.experts.routed_resident / + (double)s.experts.routed) + "%"; + if (s.experts.promotions || s.experts.demotions) { + o += " promo=" + std::to_string(s.experts.promotions); + o += " demo=" + std::to_string(s.experts.demotions); + o += " readmit=" + std::to_string(s.experts.readmits); + } + } + /* THE LINK, and the THREE things sharing it: the collective, the mover, and the MoE GEMM + * reading an expert that was not resident. Cumulative, so a `| tee` of this line is a time + * series a reader can difference -- which is the only form that says which of them is + * filling the bus. */ + if (s.link.present && + (s.link.ar_bytes || s.link.h2d_bytes || s.link.d2h_bytes || s.link.stream_bytes)) { + o += " link ar=" + std::to_string(s.link.ar_bytes); + o += " h2d=" + std::to_string(s.link.h2d_bytes); + o += " d2h=" + std::to_string(s.link.d2h_bytes); + if (s.link.stream_bytes) o += " stream=" + std::to_string(s.link.stream_bytes); + if (s.link.ssd_bytes) o += " ssd=" + std::to_string(s.link.ssd_bytes); + } + o += "\n"; + return o; +} + +/* ------------------------------------------------------------------ the terminal form */ + +std::string LiveView::render_screen(const LiveSnapshot& s) const { + const int W = cols_; + std::string o; + o.reserve(4096); + o += "\033[H\033[2J"; /* home, clear */ + + o += "\033[1mradiance\033[0m "; + o += s.model.empty() ? "-" : s.model; + o += " step " + grouped(s.step); + o += " requests " + grouped(s.total_requests) + "\n\n"; + + for (const auto& c : s.cards) { + char head[96]; + snprintf(head, sizeof head, " gpu%d %-14.14s ", c.index, c.name.c_str()); + o += head; + o += "util [" + bar(c.util, std::max(10, W / 4), true) + "] "; + o += share(c.util) + " "; + double vf = c.vram_total > 0 ? (double)c.vram_used / (double)c.vram_total : 0.0; + o += "vram [" + bar(vf, std::max(10, W / 6), true) + "] "; + o += size_of(c.vram_used, c.vram_total); + if (c.power_w > 0) o += " " + num_si(c.power_w) + " W"; + if (c.temp_c > 0) o += " " + num_si(c.temp_c) + " \u00b0C"; + o += "\n"; + } + if (!s.cards.empty()) o += "\n"; + + o += " running " + std::to_string(s.running) + + " waiting " + std::to_string(s.waiting); + if (s.preempted) o += " preempted " + std::to_string(s.preempted); + o += "\n"; + o += " kv [" + bar(s.kv_util, std::max(10, W / 4), true) + "] " + + share(s.kv_util) + " prefix hit " + share(s.prefix_hit_rate); + /* THE NUMBER THAT PREDICTS THE CLIFF, beside the one that reports it afterwards. Past + * ~75% kv the cache starts dropping prefixes the next turn wants and an agent's turn goes + * from seconds to minutes; the hit rate only falls once that has already happened. Shown + * only when non-zero -- a cache that has never evicted has nothing to say. */ + if (s.prefix_evictions) o += " evicted " + grouped(s.prefix_evictions); + o += "\n"; + o += " prefill " + tps(s.prefill_tps) + " tok/s decode " + tps(s.decode_tps) + " tok/s"; + if (s.draft_acceptance > 0.0) + o += " draft accept " + share(s.draft_acceptance); + o += "\n"; + + if (s.experts.n_layers > 0 && s.experts.n_experts > 0) { + o += "\n experts by tier " + grouped(s.experts.n_units) + " units " + + size_iec(s.experts.total_bytes) + "\n "; + /* RESIDENCY, ABSOLUTE AND PROPORTIONAL, so it can be read off the legend rather than by + * counting glyphs in the plane. Units and their share, plus the bytes -- a tier's unit + * count and its byte share are not the same ratio, because the tiers hold different + * weight classes. */ + char tl[192]; + for (int t = 0; t < 4; ++t) { + if (!s.experts.units[t]) continue; + snprintf(tl, sizeof tl, "%s%c %-6s\033[0m %s %s %s ", + tier_colour((uint8_t)t), tier_glyph((uint8_t)t), + t == 0 ? "vram" : t == 1 ? "pinned" : t == 2 ? "host" : "ssd", + grouped(s.experts.units[t]).c_str(), + share((double)s.experts.units[t] / (double)s.experts.n_units).c_str(), + size_iec(s.experts.bytes[t]).c_str()); + o += tl; + } + o += "\n"; + + /* The plane is usually wider than the terminal (128 experts x 48 layers is normal), so it + * is downsampled by taking the worst tier in each column group. Worst, not average: the + * question the plane answers is "what is going to be slow", and one SSD expert in a group + * of four is what makes that group slow. */ + const int avail = W - 8; + const int stride = std::max(1, (s.experts.n_experts + avail - 1) / std::max(1, avail)); + for (int l = 0; l < s.experts.n_layers; ++l) { + char lb[16]; + snprintf(lb, sizeof lb, " %3d ", l); + o += lb; + for (int e = 0; e < s.experts.n_experts; e += stride) { + uint8_t worst = 0; + for (int k = 0; k < stride && e + k < s.experts.n_experts; ++k) { + size_t idx = (size_t)l * s.experts.n_experts + e + k; + if (idx < s.experts.tier.size()) worst = std::max(worst, s.experts.tier[idx]); + } + o += tier_colour(worst); + o += tier_glyph(worst); + } + o += "\033[0m\n"; + } + if (s.experts.promotions || s.experts.demotions) { + o += " moves +" + grouped(s.experts.promotions) + + " -" + grouped(s.experts.demotions) + "\n"; + } + } + return o; +} + +} /* namespace server */ +} /* namespace rad */ diff --git a/core/server/liveview.h b/core/server/liveview.h new file mode 100644 index 00000000..3f260243 --- /dev/null +++ b/core/server/liveview.h @@ -0,0 +1,192 @@ +/* core/server/liveview.h -- the live view (spec §16). + * + * Per-card utilisation and VRAM, throughput, draft acceptance, and the expert plane coloured by + * tier. It is a terminal view and nothing else: no web page, no port, no JSON. + * + * The rule that shapes the implementation is the last sentence of §16 -- piped or redirected it + * prints ordinary lines instead. So there are two renderers, chosen once by isatty(), and the + * non-interactive one emits no escape sequence at all. A log file full of cursor-home sequences + * is a log file you cannot grep, and the failure is silent: it looks fine on the terminal where + * it was written. + * + * The view owns no data. A snapshot function supplied by the engine fills a LiveSnapshot; this + * component only draws it, which keeps the server free of any device dependency. + */ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace rad { +namespace server { + +struct SchedMetrics; + +struct CardStat { + int index = 0; + std::string name; + double util = 0.0; /* 0..1 */ + int64_t vram_used = 0; + int64_t vram_total = 0; + double power_w = 0.0; /* 0 = not sampled */ + double temp_c = 0.0; /* 0 = not sampled */ +}; + +/* rad::kTierCount, restated. This header deliberately does not include the program description -- + * a tier arrives here as a byte -- so the size is written out and liveview.cpp static_asserts the + * two against each other. A fifth tier that fits in four slots is an out-of-bounds write that + * costs nothing until it costs everything. */ +enum { kLiveTiers = 5 }; + +/* THE EXPERT PLANE, and what the placement engine has been doing to it. + * + * The plane itself -- one cell per (layer, expert), valued by rad::Tier -- is the picture. The + * counters beside it are the things the picture cannot say. Residency per tier says how much of + * the model is actually in VRAM; the per-layer counts say whether that residency is SPREAD, since + * a fill that walks the model in order can starve the last layers and the draft head while the + * global count still looks healthy; and the move counters say whether the traffic on the link is + * the engine discovering a working set or re-admitting what it just evicted. + * + * Counted ONCE, here, rather than by each renderer: the terminal view and the web page are two + * drawings of the same snapshot and two independent tallies are two chances to disagree. + */ +struct ExpertPlane { + int n_layers = 0; + int n_experts = 0; + std::vector tier; /* row-major, size n_layers * n_experts */ + + /* Residency, by rad::Tier. Sized by kTierCount and not by 4: folding an unknown tier into the + * SSD bucket would report a weight as on disk when it is not. `bytes` is this rank's shard, + * which is the number that has to add up against the VRAM bar beside it. */ + int64_t units[kLiveTiers] = {0}; + int64_t bytes[kLiveTiers] = {0}; + int64_t n_units = 0; /* expert units in the plan; NOT n_layers * n_experts, which + * counts cells a ragged model never had */ + int64_t total_bytes = 0; + int64_t movable = 0; /* how many of them the heat engine is allowed to relocate */ + + /* Per layer, so a starved layer is visible as a number and not only as a dark band. */ + std::vector layer_units; + std::vector layer_resident; + + /* What the mover did. Cumulative since start: a rate over a poll interval is the reader's + * subtraction, and a counter is the only form that survives being read twice. */ + int64_t promotions = 0, demotions = 0; + /* Is the churn PROGRESS or THRASH? Same move count, opposite meanings -- see HeatStats. */ + int64_t distinct_promoted = 0, readmits = 0; + /* Why a dispatch moved nothing. `refused` is the guard declining, which is the healthy steady + * state; the starved counts are the mover having nowhere to put the bytes. */ + int64_t dispatches = 0, refused = 0, no_candidate = 0; + /* DID THE ROUTER FIND THE EXPERT IN VRAM. `routed` is expert selections seen by the heat + * engine and `routed_resident` the subset that was already there; the difference is what the + * MoE GEMM had to stream across the link, which LinkStat::stream_bytes prices. A residency + * percentage says how much of the model is close; this says how much of the WORK is. */ + int64_t routed = 0, routed_resident = 0; + int64_t no_record = 0, starved_slab = 0, starved_pool = 0, quarantined = 0; + /* The prefill stager's copies (Mover::stage_units), rank 0: layers staged, units and bytes + * copied onto the card, and pooled units a buffer had no room for. */ + int64_t stage_layers = 0, staged_units = 0, staged_bytes = 0, stage_overflow = 0; + /* HOW MUCH OF THE SLAB IS BORROWED. `flex_bytes` is what the slab holds in VRAM the KV cache + * lent it; `flex_capacity` is how much the cache is lending right now. The pair is what says + * whether the boundary between the two pools is moving, and whether what was lent is being + * used -- a gap between them is lent VRAM holding nothing. */ + int64_t flex_bytes = 0, flex_capacity = 0; + bool heat_enabled = false; /* false = the plan is static and none of the above will move */ +}; + +/* WHAT IS ON THE INTERCONNECT, and in what proportion. + * + * Three things share it and they are never discussed together: the tensor-parallel all-reduce, + * which is a property of the model's width and the batch; the expert mover's promotions and + * demotions, which are a property of the placement policy; and the MoE GEMM streaming an expert + * the router asked for and placement had not put in VRAM, which is what the policy is spending + * the moves to avoid. All three are cumulative byte counts from the same wall clock, so a reader + * who subtracts two polls gets rates that can be compared -- which is the whole question "is the + * link busy because the model is wide, or because placement is thrashing". + * + * `ar_bytes` is the message payload summed over issues; Ctx::ar_bytes documents exactly what that + * is and is not. `h2d`/`d2h` are the mover's own measured copy sizes. + */ +struct LinkStat { + bool present = false; /* false when nothing measured any of it */ + int world = 1; + int64_t ar_calls = 0, ar_bytes = 0; + int64_t h2d_bytes = 0, d2h_bytes = 0; + int64_t ssd_reads = 0, ssd_bytes = 0; + /* The MoE GEMM reading a routed expert that was not resident. Not a move and not a + * collective: the third consumer of the link, and the one a promotion is spent to remove. */ + int64_t stream_bytes = 0; + int64_t prefetched = 0, prefetch_bytes = 0; + /* The prefill stager's copies of the next layer's pooled experts (core/place/stager.h). Part + * of `h2d_bytes`, like `prefetch_bytes`: the mover counts every copy it makes there, and a + * reader that wants the promotions alone takes both out. */ + int64_t staged_bytes = 0; +}; + +/* HOW THE RANKS RAN THEIR PASSES, summed over ranks: Ctx::PassCounts says what each is. A played + * pass costs the host a packet copy; every other kind walks the architecture's issue path, so the + * share that is not `played` is where a step's host time goes. */ +struct PassStat { + bool present = false; + int64_t played = 0, recorded = 0, audited = 0; + int64_t issued_unkeyed = 0, issued_refused = 0, issued_first = 0; + int64_t dispatched = 0, unordered = 0; +}; + +struct LiveSnapshot { + int64_t step = 0; + std::string model; + /* Duplicated rather than referenced so that a snapshot is a value the drawing thread can hold + * without racing the scheduler that produced it. */ + int64_t waiting = 0, running = 0, preempted = 0; + double kv_util = 0.0, prefix_hit_rate = 0.0; + int64_t prefix_evictions = 0; + double prefill_tps = 0.0, decode_tps = 0.0, draft_acceptance = 0.0; + int64_t total_requests = 0, preemptions = 0; + + std::vector cards; + ExpertPlane experts; + LinkStat link; + PassStat passes; +}; + +void snapshot_from(const SchedMetrics& m, LiveSnapshot* out); + +class LiveView { +public: + using Source = std::function; + + /* `out` defaults to stdout. `interval_ms` is the redraw period; 250 ms is fast enough to see + * a stall and slow enough that the view costs nothing measurable. */ + LiveView(Source src, int interval_ms = 250, FILE* out = nullptr); + ~LiveView(); + + void start(); + void stop(); + + + /* Both renderers are public because they are the testable part: a snapshot in, a string out, + * no terminal involved. */ + std::string render_screen(const LiveSnapshot& s) const; + std::string render_line(const LiveSnapshot& s) const; + + +private: + void loop(); + + Source src_; + int interval_ms_; + FILE* out_; + bool tty_ = false; + int cols_ = 100; + std::atomic running_{false}; + std::thread thread_; +}; + +} /* namespace server */ +} /* namespace rad */ diff --git a/core/server/metrics.cpp b/core/server/metrics.cpp new file mode 100644 index 00000000..26d86f92 --- /dev/null +++ b/core/server/metrics.cpp @@ -0,0 +1,409 @@ +#include "metrics.h" +#include "iface.h" + +#include +#include +#include + +namespace rad { +namespace server { + +/* ------------------------------------------------------------------ primitives */ + +Histogram::Histogram(std::vector bounds) : bounds_(std::move(bounds)) { + cnt_.reset(new std::atomic[bounds_.size()]); + for (size_t i = 0; i < bounds_.size(); ++i) cnt_[i].store(0); +} + +void Histogram::observe(double v) { + if (!std::isfinite(v)) return; /* a NaN latency is a bug upstream, not a data point */ + /* Cumulative: every bucket whose bound is >= v counts this observation. Linear because the + * bucket lists are twenty-odd entries and a binary search plus a fixup loop is not faster. */ + for (size_t i = 0; i < bounds_.size(); ++i) + if (v <= bounds_[i]) cnt_[i].fetch_add(1, std::memory_order_relaxed); + n_.fetch_add(1, std::memory_order_relaxed); + double cur = sum_.load(std::memory_order_relaxed); + while (!sum_.compare_exchange_weak(cur, cur + v, std::memory_order_relaxed)) {} +} + +std::vector buckets_ttft() { + return {0.001, 0.005, 0.01, 0.02, 0.04, 0.06, 0.08, 0.1, 0.25, 0.5, 0.75, + 1.0, 2.5, 5.0, 7.5, 10.0, 20.0, 40.0, 80.0, 160.0, 640.0, 2560.0}; +} + +std::vector buckets_tpot() { + return {0.01, 0.025, 0.05, 0.075, 0.1, 0.15, 0.2, 0.3, 0.4, 0.5, + 0.75, 1.0, 2.5, 5.0, 7.5, 10.0, 20.0, 40.0, 80.0}; +} + +std::vector buckets_latency() { + return {0.3, 0.5, 0.8, 1.0, 1.5, 2.0, 2.5, 5.0, 10.0, 15.0, 20.0, + 30.0, 40.0, 50.0, 60.0, 120.0, 240.0, 480.0, 960.0, 1920.0, 7680.0}; +} + +/* vLLM's build_1_2_5_buckets: mantissas 1, 2, 5 at every decade, stopping at the first value past + * max_value. A 32K-context model therefore gets 1..20000 and no more. */ +std::vector buckets_1_2_5(int64_t max_value) { + std::vector out; + if (max_value < 1) max_value = 1; + const int mant[3] = {1, 2, 5}; + for (int exp = 0; exp < 12; ++exp) { + for (int m = 0; m < 3; ++m) { + double v = (double)mant[m] * std::pow(10.0, exp); + if (v > (double)max_value) return out; + out.push_back(v); + } + } + return out; +} + +/* ------------------------------------------------------------------ registry */ + +static std::string esc_label(const std::string& s) { + std::string o; + for (char c : s) { + if (c == '\\' || c == '"') { o.push_back('\\'); o.push_back(c); } + else if (c == '\n') o += "\\n"; + else o.push_back(c); + } + return o; +} + +Metrics::Metrics(std::string model_name, int64_t max_model_len) + : model_(std::move(model_name)), + h_ttft_(buckets_ttft()), + h_tpot_(buckets_tpot()), + h_e2e_(buckets_latency()), + h_decode_(buckets_latency()), + h_prompt_tokens_(buckets_1_2_5(max_model_len > 0 ? max_model_len : 32768)), + h_generation_tokens_(buckets_1_2_5(max_model_len > 0 ? max_model_len : 32768)), + h_params_n_({1, 2, 5, 10, 20}), + h_params_max_tokens_(buckets_1_2_5(max_model_len > 0 ? max_model_len : 32768)) { + labels_ = "{model_name=\"" + esc_label(model_) + "\",engine=\"0\"}"; +} + +static const char* reason_str(SuccessReason r) { + switch (r) { + case SuccessReason::Stop: return "stop"; + case SuccessReason::Length: return "length"; + case SuccessReason::ToolCalls: return "tool_calls"; + case SuccessReason::Abort: return "abort"; + case SuccessReason::Error: return "error"; + default: return "stop"; + } +} + +void Metrics::observe_request(int64_t n_prompt, int64_t n_generated, + double ttft_s, double tpot_s, double e2e_s, double decode_s, + int n_choices, int64_t max_tokens, SuccessReason r) { + c_prompt_tokens_.inc((double)n_prompt); + c_generation_tokens_.inc((double)n_generated); + c_success_[(size_t)r].inc(); + + h_prompt_tokens_.observe((double)n_prompt); + h_generation_tokens_.observe((double)n_generated); + h_params_n_.observe((double)n_choices); + if (max_tokens > 0) h_params_max_tokens_.observe((double)max_tokens); + + if (ttft_s >= 0.0) h_ttft_.observe(ttft_s); + /* TPOT is undefined for a one-token generation -- there is no inter-token interval to + * measure. Recording a zero there would drag every quantile down, so it is simply not an + * observation. */ + if (tpot_s >= 0.0 && n_generated > 1) h_tpot_.observe(tpot_s); + if (e2e_s >= 0.0) h_e2e_.observe(e2e_s); + if (decode_s >= 0.0 && n_generated > 1) h_decode_.observe(decode_s); +} + +void Metrics::observe_rejected() { c_rejected_.inc(); } +void Metrics::observe_disconnect() { c_disconnect_.inc(); } +void Metrics::observe_overflow() { c_overflow_.inc(); } + +void Metrics::observe_http(int status) { + if (status >= 500) c_http_5xx_.inc(); + else if (status >= 400) c_http_4xx_.inc(); + else c_http_2xx_.inc(); +} + +void Metrics::sample(const SchedMetrics& m) { + std::lock_guard lk(sample_mu_); + g_running_.set((double)m.running); + g_waiting_.set((double)m.waiting); + g_preempted_.set((double)m.preempted); + g_kv_util_.set(m.kv_util); + g_prefix_hit_.set(m.prefix_hit_rate); + g_prefill_tps_.set(m.prefill_tps); + g_decode_tps_.set(m.decode_tps); + g_draft_accept_.set(m.draft_acceptance); + const int seen = std::max(0, std::min(m.draft_depth_seen, (int)MAX_DRAFT_POS)); + for (int j = 0; j < seen; ++j) { + const int64_t r = m.draft_pos_reached[j]; + g_draft_pos_reached_[j].set((double)r); + g_draft_pos_[j].set(r ? (double)m.draft_pos_accepted[j] / (double)r : 0.0); + } + /* Published after the gauges it bounds, so a concurrent render never lists a position whose + * gauge has not been written yet. */ + draft_pos_seen_.store(seen, std::memory_order_release); + c_preemptions_.inc(std::max(0.0, (double)m.preemptions - c_preemptions_.get())); + c_steps_.inc(std::max(0.0, (double)m.steps - c_steps_.get())); + c_steps_prefill_.inc(std::max(0.0, (double)m.steps_prefill - c_steps_prefill_.get())); + c_steps_mixed_.inc(std::max(0.0, (double)m.steps_mixed - c_steps_mixed_.get())); + c_steps_decode_.inc(std::max(0.0, (double)m.steps_decode - c_steps_decode_.get())); + c_steps_ahead_.inc(std::max(0.0, (double)m.steps_ahead - c_steps_ahead_.get())); + c_rows_unspec_.inc(std::max(0.0, + (double)m.decode_rows_unspeculated - c_rows_unspec_.get())); + c_step_secs_.inc(std::max(0.0, (double)m.step_ns * 1e-9 - c_step_secs_.get())); + c_step_secs_decode_.inc(std::max(0.0, + (double)m.step_ns_decode * 1e-9 - c_step_secs_decode_.get())); + c_prefill_tokens_.inc(std::max(0.0, (double)m.prefill_tokens - c_prefill_tokens_.get())); + c_decode_tokens_.inc(std::max(0.0, (double)m.decode_tokens - c_decode_tokens_.get())); + c_draft_tokens_.inc(std::max(0.0, (double)m.draft_tokens - c_draft_tokens_.get())); + c_draft_accepted_.inc(std::max(0.0, (double)m.draft_accepted - c_draft_accepted_.get())); + c_attn_cached_.inc(std::max(0.0, (double)m.attn_cached_tokens - c_attn_cached_.get())); + c_linear_cached_.inc(std::max(0.0, (double)m.linear_cached_tokens - c_linear_cached_.get())); + c_checkpoints_.inc(std::max(0.0, (double)m.checkpoints_written - c_checkpoints_.get())); + /* The cache's own cumulative counts, so the delta is taken the same way the others are. + * A prefix cache that is evicting under steady load is one that cannot hold the working + * set, and the next turn of every session it drops re-prefills from scratch. */ + c_prefix_evict_.inc(std::max(0.0, (double)m.prefix_evictions - c_prefix_evict_.get())); + c_prefix_ckpt_evict_.inc(std::max(0.0, + (double)m.prefix_ckpt_evictions - c_prefix_ckpt_evict_.get())); + g_linear_hit_.set(m.linear_hit_rate); +} + +/* ------------------------------------------------------------------ exposition */ + +namespace { + +/* Prometheus wants a bare decimal; %g would emit "1e+06" for a bucket bound, which parses, and + * "inf" for +Inf, which does not. 17 significant digits round-trips a double exactly. */ +std::string num(double v) { + if (std::isinf(v)) return v > 0 ? "+Inf" : "-Inf"; + if (v == (double)(long long)v && std::fabs(v) < 1e15) { + char b[32]; + snprintf(b, sizeof b, "%lld", (long long)v); + return b; + } + char b[64]; + snprintf(b, sizeof b, "%.17g", v); + return b; +} + +struct Writer { + std::string out; + + void help(const char* name, const char* doc, const char* type) { + out += "# HELP "; out += name; out += ' '; out += doc; out += '\n'; + out += "# TYPE "; out += name; out += ' '; out += type; out += '\n'; + } + void gauge(const char* name, const char* doc, const std::string& labels, double v) { + help(name, doc, "gauge"); + out += name; out += labels; out += ' '; out += num(v); out += '\n'; + } + void counter(const char* name, const char* doc, const std::string& labels, double v) { + /* The _total suffix is part of the exposed family name for a counter, which is what the + * Python client does and therefore what the dashboards match on. */ + help(name, doc, "counter"); + out += name; out += labels; out += ' '; out += num(v); out += '\n'; + } + void hist(const char* name, const char* doc, const std::string& labels, const Histogram& h) { + help(name, doc, "histogram"); + for (size_t i = 0; i < h.bounds().size(); ++i) { + out += name; out += "_bucket"; + out += labels.substr(0, labels.size() - 1); /* drop the closing brace */ + out += ",le=\""; out += num(h.bounds()[i]); out += "\"} "; + out += num((double)h.bucket(i)); out += '\n'; + } + out += name; out += "_bucket"; + out += labels.substr(0, labels.size() - 1); + out += ",le=\"+Inf\"} "; + out += num((double)h.count()); out += '\n'; + out += name; out += "_sum"; out += labels; out += ' '; out += num(h.sum()); out += '\n'; + out += name; out += "_count"; out += labels; out += ' '; + out += num((double)h.count()); out += '\n'; + } +}; + +} /* namespace */ + +std::string Metrics::render() const { + Writer w; + w.out.reserve(8192); + const std::string& L = labels_; + + /* ---------------- vLLM-compatible: gauges ---------------- */ + w.gauge("vllm:num_requests_running", + "Number of requests currently running on GPU.", L, g_running_.get()); + w.gauge("vllm:num_requests_waiting", + "Number of requests waiting to be processed.", L, g_waiting_.get()); + w.gauge("vllm:gpu_cache_usage_perc", + "GPU KV-cache usage. 1 means 100 percent usage.", L, g_kv_util_.get()); + w.gauge("vllm:kv_cache_usage_perc", + "KV-cache usage. 1 means 100 percent usage.", L, g_kv_util_.get()); + w.gauge("vllm:gpu_prefix_cache_hit_rate", + "GPU prefix cache block hit rate.", L, g_prefix_hit_.get()); + + /* ---------------- vLLM-compatible: counters ---------------- */ + w.counter("vllm:prompt_tokens_total", + "Number of prefill tokens processed.", L, c_prompt_tokens_.get()); + w.counter("vllm:generation_tokens_total", + "Number of generation tokens processed.", L, c_generation_tokens_.get()); + w.counter("vllm:num_preemptions_total", + "Cumulative number of preemptions from the engine.", L, c_preemptions_.get()); + + w.help("vllm:request_success_total", + "Count of successfully processed requests.", "counter"); + for (size_t i = 0; i < (size_t)SuccessReason::N_; ++i) { + w.out += "vllm:request_success_total"; + w.out += L.substr(0, L.size() - 1); + w.out += ",finished_reason=\""; + w.out += reason_str((SuccessReason)i); + w.out += "\"} "; + w.out += num(c_success_[i].get()); + w.out += '\n'; + } + + /* ---------------- vLLM-compatible: histograms ---------------- */ + w.hist("vllm:time_to_first_token_seconds", + "Histogram of time to first token in seconds.", L, h_ttft_); + w.hist("vllm:time_per_output_token_seconds", + "Histogram of time per output token in seconds.", L, h_tpot_); + /* The name current vLLM uses for the same measurement. Same data, both spellings, so a + * dashboard written against either version works unchanged. */ + w.hist("vllm:inter_token_latency_seconds", + "Histogram of inter-token latency in seconds.", L, h_tpot_); + w.hist("vllm:e2e_request_latency_seconds", + "Histogram of end to end request latency in seconds.", L, h_e2e_); + w.hist("vllm:request_decode_time_seconds", + "Histogram of time spent in the decode phase, in seconds.", L, h_decode_); + w.hist("vllm:request_prompt_tokens", + "Number of prefill tokens processed.", L, h_prompt_tokens_); + w.hist("vllm:request_generation_tokens", + "Number of generation tokens processed.", L, h_generation_tokens_); + w.hist("vllm:request_params_n", + "Histogram of the n request parameter.", L, h_params_n_); + w.hist("vllm:request_params_max_tokens", + "Histogram of the max_tokens request parameter.", L, h_params_max_tokens_); + + /* ---------------- radiance-specific ---------------- + * Under our own prefix, never under vllm:. A dashboard that finds an unfamiliar vllm: name is + * a dashboard that has been lied to about which engine it is looking at. */ + w.gauge("radiance:prefill_tokens_per_second", + "Prefill throughput over the scheduler's recent window.", L, g_prefill_tps_.get()); + w.gauge("radiance:decode_tokens_per_second", + "Decode throughput over the scheduler's recent window.", L, g_decode_tps_.get()); + w.counter("radiance:engine_steps_total", + "Scheduler steps executed. One forward pass of the model, plus whatever draft " + "rounds followed it; with speculation a step emits more than one token.", + L, c_steps_.get()); + /* STEPS BY SHAPE, and how much of the decode ran unspeculated. + * `radiance:decode_rows_unspeculated_total` counts rows that took no draft for ANY reason -- + * depth 0, a request that may not speculate, a drafter with nothing to propose. Its rate + * against engine_steps_total says how much of the decode speculation is not reaching. */ + w.counter("radiance:engine_steps_prefill_total", + "Scheduler steps carrying only prefill chunks.", L, c_steps_prefill_.get()); + w.counter("radiance:engine_steps_mixed_total", + "Scheduler steps carrying both a prefill chunk and a decode row.", + L, c_steps_mixed_.get()); + w.counter("radiance:engine_steps_decode_total", + "Scheduler steps carrying only decode rows.", L, c_steps_decode_.get()); + w.counter("radiance:engine_steps_ahead_total", + "Steps whose forward pass was issued behind the step before, ahead of its commit.", + L, c_steps_ahead_.get()); + w.counter("radiance:decode_rows_unspeculated_total", + "Decode rows that took no draft, for any reason.", + L, c_rows_unspec_.get()); + /* THE STEP TIME, AS A COUNTER AND NOT A RATE. Divide by engine_steps_decode_total for the + * milliseconds a decode step costs. Wall clock over a step count answers that only for a + * window that was saturated and carried no prefill, and says nothing when it was not. */ + w.counter("radiance:engine_step_seconds_total", + "Seconds spent inside a scheduler step, all shapes.", L, c_step_secs_.get()); + w.counter("radiance:engine_step_seconds_decode_total", + "Seconds spent inside a scheduler step carrying only decode rows.", + L, c_step_secs_decode_.get()); + + /* THE EXACT TOTALS, beside the rate gauges above rather than instead of them. A gauge is what + * a dashboard wants; a counter is what a comparison wants, because two runs that settled into + * different mixes of prefill and decode have incomparable rates and perfectly comparable + * totals. These are the only counters that answer it: vllm:generation_tokens_total is charged + * when a request FINISHES, and is therefore identically zero over a window in which nothing + * finishes. */ + w.counter("radiance:prefill_tokens_total", + "Prompt tokens the engine has computed, exact.", L, c_prefill_tokens_.get()); + w.counter("radiance:decode_tokens_total", + "Tokens the engine has generated, exact, counted when the step commits rather " + "than when the request finishes.", L, c_decode_tokens_.get()); + w.counter("radiance:draft_tokens_total", + "Speculative tokens proposed.", L, c_draft_tokens_.get()); + w.counter("radiance:draft_accepted_total", + "Speculative tokens accepted; the pair the acceptance ratio is computed from.", + L, c_draft_accepted_.get()); + + /* PREFIX CACHING, DECOUPLED (spec §7.3). vllm:gpu_prefix_cache_hit_rate is the ATTENTION one, + * because that is what vLLM's single number has always meant. The linear side hits at a + * different granularity -- whole checkpoints, not blocks -- and averaging them would hide the + * effect the decoupling exists to expose. Without these a deployment cannot tell whether + * linear checkpointing is working at all. */ + w.gauge("radiance:linear_prefix_cache_hit_rate", + "Fraction of prompt tokens served from a linear-state checkpoint (spec 7.3).", + L, g_linear_hit_.get()); + w.counter("radiance:attn_cached_tokens_total", + "Prompt tokens served from the paged attention prefix cache.", L, c_attn_cached_.get()); + w.counter("radiance:linear_cached_tokens_total", + "Prompt tokens served from a linear-state checkpoint.", L, c_linear_cached_.get()); + w.counter("radiance:linear_checkpoints_written_total", + "Linear-state checkpoints written.", L, c_checkpoints_.get()); + /* THE LEADING INDICATOR FOR A PREFIX-CACHE COLLAPSE. `gpu_prefix_cache_hit_rate` falls + * only after a reusable prefix is already gone; this rises as it is dropped. Above ~75% + * pool utilisation the cache starts evicting prefixes that the next turn wants, and an + * agent's turn-2 latency goes from seconds to minutes. */ + w.counter("radiance:prefix_cache_evictions_total", + "Prefix-cache entries evicted (attention blocks).", L, c_prefix_evict_.get()); + w.counter("radiance:prefix_cache_ckpt_evictions_total", + "Prefix-cache linear-state checkpoints evicted.", L, c_prefix_ckpt_evict_.get()); + w.gauge("radiance:draft_acceptance_ratio", + "Fraction of speculative draft tokens accepted (spec 10).", L, g_draft_accept_.get()); + /* CONDITIONAL, per draft position: of the verifies that reached position j -- every earlier + * one accepted -- the fraction that took j as well. The pooled ratio above cannot tell a + * drafter that decays from one whose later rounds are broken; these can, and the companion + * `_reached_total` says how much evidence each position carries. */ + const int seen = draft_pos_seen_.load(std::memory_order_acquire); + if (seen > 0) { + const std::string base = L.substr(0, L.size() - 1); + w.help("radiance:draft_position_acceptance_ratio", + "Conditional acceptance at each draft position, given every earlier one was taken.", + "gauge"); + for (int j = 0; j < seen; ++j) + w.out += "radiance:draft_position_acceptance_ratio" + base + ",position=\"" + + std::to_string(j) + "\"} " + num(g_draft_pos_[j].get()) + '\n'; + w.help("radiance:draft_position_reached_total", + "Verifies that evaluated each draft position.", "counter"); + for (int j = 0; j < seen; ++j) + w.out += "radiance:draft_position_reached_total" + base + ",position=\"" + + std::to_string(j) + "\"} " + num(g_draft_pos_reached_[j].get()) + '\n'; + } + w.gauge("radiance:num_requests_preempted", + "Requests currently preempted and awaiting recompute.", L, g_preempted_.get()); + w.gauge("radiance:http_queue_depth", + "Requests admitted by the HTTP layer and not yet finished.", L, queue_depth_.get()); + w.counter("radiance:http_admission_rejected_total", + "Requests refused with 429 because the admission queue was full.", + L, c_rejected_.get()); + w.counter("radiance:client_disconnect_total", + "Streams cancelled because the client went away.", L, c_disconnect_.get()); + w.counter("radiance:stream_overflow_total", + "Requests failed because the HTTP reader could not drain the sink.", + L, c_overflow_.get()); + + w.help("radiance:http_responses_total", "HTTP responses by status class.", "counter"); + w.out += "radiance:http_responses_total" + L.substr(0, L.size() - 1) + ",class=\"2xx\"} " + + num(c_http_2xx_.get()) + '\n'; + w.out += "radiance:http_responses_total" + L.substr(0, L.size() - 1) + ",class=\"4xx\"} " + + num(c_http_4xx_.get()) + '\n'; + w.out += "radiance:http_responses_total" + L.substr(0, L.size() - 1) + ",class=\"5xx\"} " + + num(c_http_5xx_.get()) + '\n'; + + return w.out; +} + +} /* namespace server */ +} /* namespace rad */ diff --git a/core/server/metrics.h b/core/server/metrics.h new file mode 100644 index 00000000..404dbf5b --- /dev/null +++ b/core/server/metrics.h @@ -0,0 +1,158 @@ +/* core/server/metrics.h -- Prometheus /metrics, with vLLM's metric names. + * + * The names are not ours to choose. There is a published Grafana dashboard for vLLM and a great + * deal of alerting built on `vllm:time_to_first_token_seconds_bucket` and friends, and the point + * of matching them is that swapping vLLM for radiance behind an existing deployment changes + * nothing on the observability side. So: the vLLM names, the vLLM bucket boundaries, and the + * vLLM label set (`model_name`, `engine`), copied exactly. Where vLLM renamed something we emit + * both spellings -- `vllm:gpu_cache_usage_perc` is what every dashboard in the wild queries and + * `vllm:kv_cache_usage_perc` is what current vLLM emits, and two gauges cost nothing. + * + * Anything vLLM does not have goes under `radiance:`. Inventing a new `vllm:` name would be worse + * than useless: it would look to a dashboard like a metric it knows and is not. + * + * What is deliberately NOT emitted is as important. `vllm:iteration_tokens_total` and + * `vllm:request_queue_time_seconds` are properties of the scheduler's step loop, not of the HTTP + * boundary, and the server cannot observe them. Emitting a plausible-looking approximation of a + * latency breakdown is how a dashboard ends up lying, so they are absent until the scheduler + * reports them, and their absence is documented rather than papered over. + */ +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace rad { +namespace server { + +struct SchedMetrics; + +/* ------------------------------------------------------------------ primitives */ + +class Counter { +public: + void inc(double v = 1.0) { + double cur = v_.load(std::memory_order_relaxed); + while (!v_.compare_exchange_weak(cur, cur + v, std::memory_order_relaxed)) {} + } + double get() const { return v_.load(std::memory_order_relaxed); } +private: + std::atomic v_{0.0}; +}; + +class Gauge { +public: + void set(double v) { v_.store(v, std::memory_order_relaxed); } + double get() const { return v_.load(std::memory_order_relaxed); } +private: + std::atomic v_{0.0}; +}; + +/* Cumulative buckets, the Prometheus convention: bucket i counts observations <= bounds[i], and + * the implicit +Inf bucket is `count`. Atomics rather than a lock because /metrics is scraped + * from one thread while every HTTP thread observes into it. */ +class Histogram { +public: + explicit Histogram(std::vector bounds); + void observe(double v); + + const std::vector& bounds() const { return bounds_; } + uint64_t bucket(size_t i) const { return cnt_[i].load(std::memory_order_relaxed); } + uint64_t count() const { return n_.load(std::memory_order_relaxed); } + double sum() const { return sum_.load(std::memory_order_relaxed); } + +private: + std::vector bounds_; + std::unique_ptr[]> cnt_; + std::atomic n_{0}; + std::atomic sum_{0.0}; +}; + +/* vLLM's bucket layouts, verbatim. Changing one of these silently invalidates every histogram + * quantile a dashboard computes across a version boundary, so they are constants, not options. */ +std::vector buckets_ttft(); /* vllm:time_to_first_token_seconds */ +std::vector buckets_tpot(); /* vllm:time_per_output_token_seconds */ +std::vector buckets_latency(); /* every vllm:request_*_seconds */ +std::vector buckets_1_2_5(int64_t max_value); /* token-count histograms */ + +/* ------------------------------------------------------------------ the registry */ + +/* The finish reasons `vllm:request_success_total` is broken down by. Fixed, because a label whose + * cardinality depends on user input is a Prometheus outage waiting to happen. */ +enum class SuccessReason { Stop = 0, Length, ToolCalls, Abort, Error, N_ }; + +class Metrics { +public: + Metrics(std::string model_name, int64_t max_model_len); + + /* --- observed at the HTTP boundary, per finished request --- */ + void observe_request(int64_t n_prompt, int64_t n_generated, + double ttft_s, double tpot_s, double e2e_s, double decode_s, + int n_choices, int64_t max_tokens, SuccessReason r); + void observe_rejected(); /* 429: the admission queue was full */ + void observe_disconnect(); /* the client went away mid-stream */ + void observe_overflow(); /* the sink ring filled: the HTTP side could not keep up */ + void observe_http(int status); + + void set_queue_depth(int64_t d) { queue_depth_.set((double)d); } + + /* --- pulled from the scheduler at scrape time --- */ + void sample(const SchedMetrics& m); + + /* Prometheus text exposition format, version 0.0.4. */ + std::string render() const; + + +private: + std::string model_; + std::string labels_; /* {model_name="...",engine="0"} */ + + Gauge g_running_, g_waiting_, g_kv_util_, g_prefix_hit_; + Gauge g_prefill_tps_, g_decode_tps_, g_draft_accept_, g_preempted_; + Gauge queue_depth_; + /* The per-position draft hazard, kept as plain gauges because that is what it is: a + * conditional acceptance rate at each draft position, which is the only number that separates + * a drafter that decays from one whose later rounds are broken. See core/sched/draft.h. */ + enum { MAX_DRAFT_POS = 64 }; + Gauge g_draft_pos_[MAX_DRAFT_POS]; + Gauge g_draft_pos_reached_[MAX_DRAFT_POS]; + std::atomic draft_pos_seen_{0}; + + /* sample() turns the scheduler's cumulative totals into counter increments by reading each + * counter and adding the difference. Two scrapes doing that at once both read the old value + * and both add the whole difference, so they are serialised. */ + std::mutex sample_mu_; + + Counter c_prompt_tokens_, c_generation_tokens_, c_preemptions_; + /* ENGINE STEPS. Tokens a second cannot answer "how long is a step", and with speculation the + * two stop being the same question: a step emits 1 + however many drafts survived. Exposed as + * a counter so two scrapes and a clock give the step time directly. */ + Counter c_steps_; + /* STEPS BY SHAPE, and the decode rows a mixed step cost speculation. Exposed as counters so + * two scrapes give the rate over a window rather than a number dominated by startup. */ + Counter c_steps_prefill_, c_steps_mixed_, c_steps_decode_, c_rows_unspec_, c_steps_ahead_; + /* SECONDS SPENT INSIDE A STEP, and the decode half of it. A step time is not wall clock over + * a step count -- SchedMetrics::step_ns says why -- and without these every scraper has to + * assume a saturated window and no prefill in it. */ + Counter c_step_secs_, c_step_secs_decode_; + /* THE EXACT TOTALS BEHIND THE RATE GAUGES. A gauge answers "how fast right now"; a counter + * answers "how much between these two scrapes", and only the second survives a comparison + * between two runs that settled into different mixes. */ + Counter c_prefill_tokens_, c_decode_tokens_, c_draft_tokens_, c_draft_accepted_; + Counter c_attn_cached_, c_linear_cached_, c_checkpoints_; + Counter c_prefix_evict_, c_prefix_ckpt_evict_; + Gauge g_linear_hit_; + Counter c_success_[(size_t)SuccessReason::N_]; + Counter c_rejected_, c_disconnect_, c_overflow_; + Counter c_http_2xx_, c_http_4xx_, c_http_5xx_; + + Histogram h_ttft_, h_tpot_, h_e2e_, h_decode_; + Histogram h_prompt_tokens_, h_generation_tokens_, h_params_n_, h_params_max_tokens_; +}; + +} /* namespace server */ +} /* namespace rad */ diff --git a/core/server/oai.cpp b/core/server/oai.cpp new file mode 100644 index 00000000..7fc1d885 --- /dev/null +++ b/core/server/oai.cpp @@ -0,0 +1,1807 @@ +#include "oai.h" +#include "json_partial.h" +#include "rad_internal.h" +#include "mm/processor.h" + +#include + +#include +#include +#include +#include +#include + +namespace rad { +namespace server { + +const char* const SSE_DONE = "data: [DONE]\n\n"; + +/* ================================================================== small helpers */ + +int64_t unix_now() { return (int64_t)std::time(nullptr); } + +std::string json_dump(const json& j) { return j.dump(); } + +std::string random_id(const char* prefix) { + static thread_local std::mt19937_64 rng{std::random_device{}()}; + static const char* hex = "0123456789abcdef"; + uint64_t a = rng(), b = rng(); + std::string s = prefix; + for (int i = 0; i < 16; ++i) s.push_back(hex[(a >> (i * 4)) & 0xF]); + for (int i = 0; i < 8; ++i) s.push_back(hex[(b >> (i * 4)) & 0xF]); + return s; +} + +static const char kB64[] = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +std::string base64_encode(const void* data, size_t len) { + const uint8_t* p = (const uint8_t*)data; + std::string out; + out.reserve((len + 2) / 3 * 4); + size_t i = 0; + for (; i + 2 < len; i += 3) { + uint32_t v = (uint32_t)p[i] << 16 | (uint32_t)p[i + 1] << 8 | p[i + 2]; + out.push_back(kB64[(v >> 18) & 63]); out.push_back(kB64[(v >> 12) & 63]); + out.push_back(kB64[(v >> 6) & 63]); out.push_back(kB64[v & 63]); + } + if (i < len) { + uint32_t v = (uint32_t)p[i] << 16; + bool two = (i + 1 < len); + if (two) v |= (uint32_t)p[i + 1] << 8; + out.push_back(kB64[(v >> 18) & 63]); + out.push_back(kB64[(v >> 12) & 63]); + out.push_back(two ? kB64[(v >> 6) & 63] : '='); + out.push_back('='); + } + return out; +} + +bool base64_decode(const std::string& in, std::vector* out) { + auto val = [](char c) -> int { + if (c >= 'A' && c <= 'Z') return c - 'A'; + if (c >= 'a' && c <= 'z') return c - 'a' + 26; + if (c >= '0' && c <= '9') return c - '0' + 52; + if (c == '+') return 62; + if (c == '/') return 63; + return -1; + }; + uint32_t acc = 0; + int bits = 0; + out->clear(); + out->reserve(in.size() * 3 / 4); + for (char c : in) { + if (c == '=' || c == '\n' || c == '\r' || c == ' ' || c == '\t') continue; + int v = val(c); + if (v < 0) return false; + acc = (acc << 6) | (uint32_t)v; + bits += 6; + if (bits >= 8) { + bits -= 8; + out->push_back((uint8_t)((acc >> bits) & 0xFF)); + } + } + return true; +} + +/* THE PARSED TREE IS BOUNDED, NOT ONLY THE BODY. A JSON value costs the tree a 16-byte node plus + * its container's growth slack however few bytes it took on the wire, so `[1,1,1,...]` grows + * about eightfold in parsing, and a body at the transport's size limit becomes gigabytes before + * a single field has been read -- let alone a prompt checked against the context. Nothing a + * request can legitimately carry needs many values per token of context: a token-id prompt is + * one per token and must fit the context, and everything else (messages, tools, schemas, stop + * strings) is small beside it. So past a budget scaled from the context the parse stops keeping + * values, and the request is refused having cost a bounded tree. */ +int64_t json_value_budget(int64_t max_ctx) { + const int64_t kFloor = 1 << 20; /* what a request needs with no context to scale by */ + const int64_t kPerToken = 16; /* a batch of up to this many full-context prompts */ + return kFloor + kPerToken * std::max(max_ctx, 0); +} + +/* AND ITS DEPTH IS BOUNDED, because the parser is the only thing here that walks a tree without + * recursing. Serialising one (`dump`) and destroying a copy made field by field both recurse once + * a level, and a request's schema is serialised on the way to its grammar -- so a body of a few + * hundred kilobytes of brackets, well inside the value budget, would overflow the worker's stack. + * Nothing a request carries nests anywhere near the bound: a schema deep enough to matter is + * refused by the grammar compiler at half of it. */ +json parse_json_bounded(const std::string& body, int64_t max_ctx, bool* over, bool* deep) { + const int64_t budget = json_value_budget(max_ctx); + int64_t n = 0; + *over = false; + *deep = false; + /* Every completed value is counted once: a scalar at `value`, a container at its end. Once + * over or too deep, every event answers false, which tells the parser to keep nothing + * further. */ + json::parser_callback_t keep = [&](int depth, json::parse_event_t ev, json&) { + if (!*deep && depth > kJsonMaxDepth) *deep = true; + if (!*over && (ev == json::parse_event_t::value || + ev == json::parse_event_t::object_end || + ev == json::parse_event_t::array_end)) + *over = ++n > budget; + return !*over && !*deep; + }; + return json::parse(body, keep, /*allow_exceptions=*/false); +} + +bool token_id(const json& v, int32_t* out) { + if (v.is_number_unsigned()) { + if (v.get() > (uint64_t)INT32_MAX) return false; + } else if (!v.is_number_integer() || v.get() < 0 || v.get() > INT32_MAX) { + return false; + } + *out = (int32_t)v.get(); + return true; +} + +/* ================================================================== errors */ + +std::string ApiError::dump() const { + json e; + e["message"] = message; + e["type"] = type; + if (param.empty()) e["param"] = nullptr; else e["param"] = param; + if (code.empty()) e["code"] = nullptr; else e["code"] = code; + json o; + o["error"] = e; + return o.dump(); +} + +ApiError err_bad(const std::string& param, const std::string& why) { + ApiError e; + e.status = 400; + e.param = param; + e.message = param.empty() ? why : (param + ": " + why); + return e; +} + +ApiError err_unsupported(const std::string& param, const std::string& why) { + ApiError e = err_bad(param, why); + e.code = "unsupported_parameter"; + return e; +} + +ApiError err_not_implemented(const std::string& what) { + ApiError e; + e.status = 501; + e.type = "not_implemented_error"; + e.message = what; + return e; +} + +ApiError err_overloaded(const std::string& why) { + ApiError e; + e.status = 429; + e.type = "rate_limit_error"; + e.code = "server_overloaded"; + e.message = why; + return e; +} + +/* ================================================================== key vetting + * + * The three lists below are the whole policy. `kAccepted*` is what we read; `kInert` is the + * OpenAI metadata that genuinely does nothing anywhere and would break the official SDKs if it + * 400'd; `kRejected` is the set we know about and do not implement, each with the reason, so the + * error message tells a caller something they can act on rather than "unsupported". + */ +namespace { + +struct Rejected { const char* key; const char* why; }; + +const char* kAcceptedCommon[] = { + "model", "stream", "stream_options", "n", "seed", "stop", "max_tokens", + "temperature", "top_p", "top_k", "min_p", "typical_p", + "presence_penalty", "frequency_penalty", "repetition_penalty", "repeat_last_n", + "xtc_probability", "xtc_threshold", + "dry_multiplier", "dry_base", "dry_allowed_length", "dry_penalty_last_n", + "dry_sequence_breakers", + "grammar", "priority", "logprobs", "ignore_eos", +}; + +const char* kAcceptedChat[] = { + "messages", "tools", "tool_choice", "response_format", "top_logprobs", + "parallel_tool_calls", "add_generation_prompt", "max_completion_tokens", + "chat_template_kwargs", "reasoning_effort", "enable_thinking", +}; + +const char* kAcceptedCompletion[] = { "prompt", "echo" }; + +const char* kAcceptedEmbedding[] = { "model", "input", "encoding_format", "dimensions" }; + +/* Inert by definition in the OpenAI schema: routing and bookkeeping labels the server is free to + * ignore. Named explicitly so that "we ignore it" is a decision in the source and not an + * accident of a missing branch. */ +const char* kInert[] = { + "user", "metadata", "store", "service_tier", "safety_identifier", "prompt_cache_key", +}; + +const Rejected kRejected[] = { + { "logit_bias", + "SamplingParams has no per-token bias stage and the device sampler (spec 13) does not " + "implement one" }, + { "functions", "the deprecated functions API; send `tools` instead" }, + { "function_call", "the deprecated function_call API; send `tool_choice` instead" }, + { "best_of", "sampling n candidates and returning the best is not implemented" }, + { "suffix", "infilling is not implemented" }, + { "mirostat", "mirostat is not one of the device samplers (spec 13)" }, + { "mirostat_tau", "mirostat is not one of the device samplers (spec 13)" }, + { "mirostat_eta", "mirostat is not one of the device samplers (spec 13)" }, + { "top_n_sigma", "top-n-sigma is not one of the device samplers (spec 13)" }, + { "dynatemp_range", "dynamic temperature is not one of the device samplers (spec 13)" }, + { "dynatemp_exponent", "dynamic temperature is not one of the device samplers (spec 13)" }, + { "lora", "LoRA is explicitly out of scope (spec, Scope)" }, + { "modalities", "output modalities other than text are not implemented" }, + { "audio", "audio output is not implemented" }, + { "prediction", "predicted outputs are not implemented" }, + { "continue_final_message", "assistant prefill is not implemented" }, + { "cache_prompt", "prefix caching is a server-wide setting (spec 7.3), not per request" }, +}; + +bool in_list(const char* const* list, size_t n, const std::string& k) { + for (size_t i = 0; i < n; ++i) if (k == list[i]) return true; + return false; +} +#define ARRN(a) (sizeof(a) / sizeof((a)[0])) + +int vet_keys(const json& body, Endpoint ep, ApiError* err) { + for (auto it = body.begin(); it != body.end(); ++it) { + const std::string& k = it.key(); + if (in_list(kInert, ARRN(kInert), k)) continue; + if (ep == Endpoint::Embedding) { + if (in_list(kAcceptedEmbedding, ARRN(kAcceptedEmbedding), k)) continue; + } else { + if (in_list(kAcceptedCommon, ARRN(kAcceptedCommon), k)) continue; + if (ep == Endpoint::Chat && + in_list(kAcceptedChat, ARRN(kAcceptedChat), k)) continue; + if (ep == Endpoint::Completion && + in_list(kAcceptedCompletion, ARRN(kAcceptedCompletion), k)) continue; + } + for (const auto& r : kRejected) { + if (k == r.key) { *err = err_unsupported(k, r.why); return RAD_E_UNSUPPORTED; } + } + *err = err_unsupported( + k, "unrecognised parameter for this endpoint. A parameter the server does not " + "implement is refused rather than ignored, so that a request that returns 200 " + "means every field of it was honoured"); + return RAD_E_INVAL; + } + return RAD_OK; +} + +/* Typed getters that refuse rather than coerce: OpenAI clients that send "0.7" as a string are + * sending a bug, and silently accepting it hides it until the day the string is "warm". */ +bool get_num(const json& b, const char* k, double* out, ApiError* err) { + auto it = b.find(k); + if (it == b.end() || it->is_null()) return true; + if (!it->is_number()) { *err = err_bad(k, "expected a number"); return false; } + *out = it->get(); + return true; +} +/* EVERY INTEGER FIELD THIS FILE READS IS STORED IN 32 BITS, so a value that does not fit is + * refused here rather than narrowed at the call site. Narrowing is not a clamp: 2^32 becomes 0 + * and 2^31 becomes negative, and for `max_tokens` both of those read downstream as "no limit". + * The unsigned branch matters too -- nlohmann keeps a literal above INT64_MAX as unsigned, and + * reading that as int64 wraps it negative. */ +bool get_int(const json& b, const char* k, int64_t* out, ApiError* err) { + auto it = b.find(k); + if (it == b.end() || it->is_null()) return true; + if (!it->is_number_integer()) { *err = err_bad(k, "expected an integer"); return false; } + const bool fits = it->is_number_unsigned() + ? it->get() <= (uint64_t)INT32_MAX + : it->get() >= INT32_MIN && it->get() <= INT32_MAX; + if (!fits) { + *err = err_bad(k, "must fit in a 32-bit signed integer, got " + it->dump()); + return false; + } + *out = it->get(); + return true; +} +bool get_bool(const json& b, const char* k, bool* out, ApiError* err) { + auto it = b.find(k); + if (it == b.end() || it->is_null()) return true; + if (!it->is_boolean()) { *err = err_bad(k, "expected a boolean"); return false; } + *out = it->get(); + return true; +} +bool get_str(const json& b, const char* k, std::string* out, ApiError* err) { + auto it = b.find(k); + if (it == b.end() || it->is_null()) return true; + if (!it->is_string()) { *err = err_bad(k, "expected a string"); return false; } + *out = it->get(); + return true; +} + +bool range(double v, double lo, double hi, const char* k, ApiError* err) { + if (v < lo || v > hi) { + char b[160]; + snprintf(b, sizeof b, "must be in [%g, %g], got %g", lo, hi, v); + *err = err_bad(k, b); + return false; + } + return true; +} + +/* The body of every generation endpoint: one JSON object, parsed into a bounded tree. */ +int parse_request_object(const std::string& body, const OaiLimits& lim, json* b, ApiError* err) { + bool over = false, deep = false; + *b = parse_json_bounded(body, lim.max_ctx, &over, &deep); + if (deep) { + *err = err_bad("", "the request body nests more than " + std::to_string(kJsonMaxDepth) + + " levels deep"); + return RAD_E_INVAL; + } + if (over) { + char msg[160]; + snprintf(msg, sizeof msg, + "the request body holds more than %lld JSON values, which no request this " + "server can serve needs", (long long)json_value_budget(lim.max_ctx)); + *err = err_bad("", msg); + return RAD_E_INVAL; + } + if (b->is_discarded() || !b->is_object()) { + *err = err_bad("", "request body is not a JSON object"); + return RAD_E_INVAL; + } + return RAD_OK; +} + +} /* namespace */ + +/* ================================================================== sampling params */ + +static int parse_sampling(const json& b, const OaiLimits& lim, OaiRequest* r, ApiError* err) { + double d; + int64_t i64; + bool bl; + + /* THE DEPLOYMENT'S DEFAULTS ARE THE SEED, and every field below reads its current value + * before looking for one in the body -- so a field the request names overrides, and a field + * it omits keeps what the checkpoint asked for. Done here rather than at each call site + * because a sampler default that reached one endpoint and not the other would make the same + * model answer differently through /v1/completions than through /v1/chat/completions. */ + r->sp = lim.default_sampling; + + d = r->sp.temp; + if (!get_num(b, "temperature", &d, err)) return RAD_E_INVAL; + if (!range(d, 0.0, 2.0, "temperature", err)) return RAD_E_INVAL; + r->sp.temp = (float)d; + + d = r->sp.top_p; + if (!get_num(b, "top_p", &d, err)) return RAD_E_INVAL; + if (d <= 0.0 || d > 1.0) { *err = err_bad("top_p", "must be in (0, 1]"); return RAD_E_INVAL; } + r->sp.top_p = (float)d; + + i64 = r->sp.top_k; + if (!get_int(b, "top_k", &i64, err)) return RAD_E_INVAL; + if (i64 < 0) { *err = err_bad("top_k", "must be >= 0 (0 disables it)"); return RAD_E_INVAL; } + r->sp.top_k = (int)i64; + + d = r->sp.min_p; + if (!get_num(b, "min_p", &d, err)) return RAD_E_INVAL; + if (!range(d, 0.0, 1.0, "min_p", err)) return RAD_E_INVAL; + r->sp.min_p = (float)d; + + d = r->sp.typical_p; + if (!get_num(b, "typical_p", &d, err)) return RAD_E_INVAL; + if (d <= 0.0 || d > 1.0) { *err = err_bad("typical_p", "must be in (0, 1]"); return RAD_E_INVAL; } + r->sp.typical_p = (float)d; + + d = r->sp.pres_penalty; + if (!get_num(b, "presence_penalty", &d, err)) return RAD_E_INVAL; + if (!range(d, -2.0, 2.0, "presence_penalty", err)) return RAD_E_INVAL; + r->sp.pres_penalty = (float)d; + + d = r->sp.freq_penalty; + if (!get_num(b, "frequency_penalty", &d, err)) return RAD_E_INVAL; + if (!range(d, -2.0, 2.0, "frequency_penalty", err)) return RAD_E_INVAL; + r->sp.freq_penalty = (float)d; + + d = r->sp.rep_penalty; + if (!get_num(b, "repetition_penalty", &d, err)) return RAD_E_INVAL; + if (d <= 0.0) { *err = err_bad("repetition_penalty", "must be > 0"); return RAD_E_INVAL; } + r->sp.rep_penalty = (float)d; + + i64 = r->sp.penalty_last_n; + if (!get_int(b, "repeat_last_n", &i64, err)) return RAD_E_INVAL; + if (i64 < -1) { *err = err_bad("repeat_last_n", "must be >= -1"); return RAD_E_INVAL; } + r->sp.penalty_last_n = (int)i64; + + d = r->sp.xtc_probability; + if (!get_num(b, "xtc_probability", &d, err)) return RAD_E_INVAL; + if (!range(d, 0.0, 1.0, "xtc_probability", err)) return RAD_E_INVAL; + r->sp.xtc_probability = (float)d; + + d = r->sp.xtc_threshold; + if (!get_num(b, "xtc_threshold", &d, err)) return RAD_E_INVAL; + if (!range(d, 0.0, 1.0, "xtc_threshold", err)) return RAD_E_INVAL; + r->sp.xtc_threshold = (float)d; + + d = r->sp.dry_multiplier; + if (!get_num(b, "dry_multiplier", &d, err)) return RAD_E_INVAL; + r->sp.dry_multiplier = (float)d; + d = r->sp.dry_base; + if (!get_num(b, "dry_base", &d, err)) return RAD_E_INVAL; + if (d < 1.0) { *err = err_bad("dry_base", "must be >= 1"); return RAD_E_INVAL; } + r->sp.dry_base = (float)d; + i64 = r->sp.dry_allowed_length; + if (!get_int(b, "dry_allowed_length", &i64, err)) return RAD_E_INVAL; + r->sp.dry_allowed_length = (int)i64; + i64 = r->sp.dry_penalty_last_n; + if (!get_int(b, "dry_penalty_last_n", &i64, err)) return RAD_E_INVAL; + if (i64 < -1) { *err = err_bad("dry_penalty_last_n", "must be >= -1"); return RAD_E_INVAL; } + r->sp.dry_penalty_last_n = (int)i64; + + /* ABSENT MEANS llama.cpp's FOUR, not none. A client that turns DRY on and names no breakers + * gets what llama-server gives it -- newline, colon, quote and asterisk end a repeat -- and a + * list that is sent replaces them outright, an empty one included. The default costs nothing + * with DRY off: the sampler resolves breakers only for a request that runs DRY. */ + auto dsb = b.find("dry_sequence_breakers"); + if (dsb == b.end() || dsb->is_null()) { + if (r->sp.dry_seq_breakers.empty()) r->sp.dry_seq_breakers = { "\n", ":", "\"", "*" }; + } else { + r->sp.dry_seq_breakers.clear(); + if (!dsb->is_array()) { + *err = err_bad("dry_sequence_breakers", "expected an array of strings"); + return RAD_E_INVAL; + } + for (const auto& s : *dsb) { + if (!s.is_string()) { + *err = err_bad("dry_sequence_breakers", "expected an array of strings"); + return RAD_E_INVAL; + } + r->sp.dry_seq_breakers.push_back(s.get()); + } + } + + /* An unset seed must not mean seed 0, or every request in a deployment that never sets one + * would draw the identical sample. Absent means "pick one", which is what OpenAI's contract + * says and what makes `seed` meaningful when it IS set. */ + auto sit = b.find("seed"); + if (sit != b.end() && !sit->is_null()) { + if (!sit->is_number_integer()) { *err = err_bad("seed", "expected an integer"); return RAD_E_INVAL; } + r->sp.seed = (uint64_t)sit->get(); + } else { + static thread_local std::mt19937_64 rng{std::random_device{}()}; + r->sp.seed = rng(); + } + + /* n. Implemented by fan-out: n independent requests over the same prompt, which the prefix + * cache makes nearly free after the first (spec 7.3). Their seeds are offset from the + * request's, because n identical seeds would produce n identical completions. */ + i64 = 1; + if (!get_int(b, "n", &i64, err)) return RAD_E_INVAL; + if (i64 < 1 || i64 > lim.max_n) { + char msg[128]; + snprintf(msg, sizeof msg, "must be in [1, %d]", lim.max_n); + *err = err_bad("n", msg); + return RAD_E_INVAL; + } + r->n = (int)i64; + + i64 = 0; + if (!get_int(b, "priority", &i64, err)) return RAD_E_INVAL; + r->priority = (int)i64; + + /* max_tokens, with max_completion_tokens as the newer OpenAI spelling of the same field. */ + int64_t mt = 0; + if (!get_int(b, "max_tokens", &mt, err)) return RAD_E_INVAL; + if (b.contains("max_completion_tokens") && !b.at("max_completion_tokens").is_null()) { + if (!get_int(b, "max_completion_tokens", &mt, err)) return RAD_E_INVAL; + } + if (mt < 0) { *err = err_bad("max_tokens", "must be >= 1"); return RAD_E_INVAL; } + r->max_tokens = (int32_t)(mt > 0 ? mt : lim.default_max_tokens); + + /* ignore_eos: generate to max_tokens whatever the model emits. See Request::ignore_eos. */ + if (!get_bool(b, "ignore_eos", &r->ignore_eos, err)) return RAD_E_INVAL; + + /* stop: a string or an array of strings. + * + * BOUNDED IN COUNT AND LENGTH, because every stop string is searched for in each stretch of + * text a choice produces -- by the decoder and again by the server's own scan -- so what one + * request costs per token is its number of stop strings times the longest of them. OpenAI + * allows four. The bounds here are far past anything a client sends and exist so that no + * request can buy that scan without limit. */ + constexpr size_t kMaxStops = 64, kMaxStopBytes = 4096; + auto st = b.find("stop"); + if (st != b.end() && !st->is_null()) { + if (st->is_string()) r->stop.push_back(st->get()); + else if (st->is_array()) { + if (st->size() > kMaxStops) { + *err = err_bad("stop", "at most " + std::to_string(kMaxStops) + + " stop strings are accepted, got " + + std::to_string(st->size())); + return RAD_E_INVAL; + } + for (const auto& s : *st) { + if (!s.is_string()) { + *err = err_bad("stop", "expected a string or an array of strings"); + return RAD_E_INVAL; + } + r->stop.push_back(s.get()); + } + } else { + *err = err_bad("stop", "expected a string or an array of strings"); + return RAD_E_INVAL; + } + for (const auto& s : r->stop) { + if (s.size() > kMaxStopBytes) { + *err = err_bad("stop", "a stop string may be at most " + + std::to_string(kMaxStopBytes) + " bytes, got one of " + + std::to_string(s.size())); + return RAD_E_INVAL; + } + } + } + + bl = false; + if (!get_bool(b, "stream", &bl, err)) return RAD_E_INVAL; + r->stream = bl; + + auto so = b.find("stream_options"); + if (so != b.end() && !so->is_null()) { + if (!so->is_object()) { *err = err_bad("stream_options", "expected an object"); return RAD_E_INVAL; } + bool iu = false; + if (!get_bool(*so, "include_usage", &iu, err)) return RAD_E_INVAL; + r->include_usage = iu; + } + + return RAD_OK; +} + +/* ================================================================== thinking + * + * Three spellings reach this server for one question -- does the model reason before it answers. + * `chat_template_kwargs: {"enable_thinking": false}` is what vLLM's clients send and is the one + * that matters here; `enable_thinking` at the top level is the shorthand several clients grew; + * `reasoning_effort` is OpenAI's own, and "none"/"minimal" is the only value of it this server + * can honour, because the rest ask the model to think HARDER and no chat template exposes a dial + * for that. + * + * THE KWARG ALONE IS NOT ENOUGH, and this is the trap the whole function exists for. The vendored + * llama.cpp chat layer copies chat_template_kwargs into the template context and THEN overwrites + * the key `enable_thinking` with its own boolean field (chat-auto-parser-helpers.cpp). So a + * caller who sends the kwarg and nothing else has it silently overwritten with the default true, + * and sees the model think anyway -- a 200 that did not honour the request, which is the one + * outcome this file's header forbids. Lifting the kwarg into the field is what makes it real. + */ +static int parse_thinking(const json& b, const OaiLimits& lim, ChatRenderOptions* opt, + ApiError* err) { + auto kw = b.find("chat_template_kwargs"); + if (kw != b.end() && !kw->is_null()) { + if (!kw->is_object()) { + *err = err_bad("chat_template_kwargs", "expected an object"); + return RAD_E_INVAL; + } + for (auto it = kw->begin(); it != kw->end(); ++it) { + /* dump(), not get(): the template context wants JSON, so a string value has + * to arrive still quoted. See ChatRenderOptions. */ + opt->template_kwargs[it.key()] = it.value().dump(); + if (it.key() == "enable_thinking") { + if (!it.value().is_boolean()) { + *err = err_bad("chat_template_kwargs.enable_thinking", "expected a boolean"); + return RAD_E_INVAL; + } + opt->enable_thinking = it.value().get(); + } + } + } + + bool think = opt->enable_thinking; + if (!get_bool(b, "enable_thinking", &think, err)) return RAD_E_INVAL; + opt->enable_thinking = think; + + /* REASONING EFFORT IS THE TEMPLATE'S VOCABULARY, NOT OURS, so there is no allow-list here. + * One would be wrong in both directions: OpenAI's ladder is none/minimal/low/medium/high, + * while a model's template may accept a different set -- Qwen3.8's takes xhigh/medium/low and + * raise_exception's on anything else. An allow-list would admit `"high"` only for the template + * to refuse it, and refuse `"xhigh"`, which that template would have taken. + * + * What this layer actually owns is the one mapping that is a SERVER semantic and not a + * template one: "none" and "minimal" mean do not think, which is `enable_thinking = false` + * and is honoured whatever the template's dial is called. Everything else is passed through + * as template context, and a template that does not read it ignores it -- exactly as the + * kwarg path already does. A template that DOES read it and refuses says so in its own words, + * because ChatPrompt::error carries the sentence out (core/text/chat.h). + * + * An explicit chat_template_kwargs entry still wins: emplace does not overwrite. */ + std::string effort; + if (!get_str(b, "reasoning_effort", &effort, err)) return RAD_E_INVAL; + /* The deployment's default, where the request did not say. Last, so every explicit spelling + * above it wins; emplace, so a chat_template_kwargs entry that already set the key stands. */ + if (effort.empty()) effort = lim.default_reasoning_effort; + if (!effort.empty()) { + if (effort == "none" || effort == "minimal") opt->enable_thinking = false; + else opt->template_kwargs.emplace("reasoning_effort", json(effort).dump()); + } + return RAD_OK; +} + +/* ================================================================== grammar / response_format */ + +/* `schema_json`, when non-null, means "hand me the schema instead of compiling it" -- which is + * what the chat endpoint needs. A chat template BUILDS the grammar itself, from the schema and + * from its own tool-call syntax together, and it takes the schema as a schema + * (chat-auto-parser-generator.cpp keys `has_response_format` off `inputs.json_schema`). Handing + * it a pre-compiled GBNF in the `grammar` slot instead means it sees no response format at all, + * emits no grammar, and the compiled one is then overwritten by that empty result -- a + * `response_format` that returns 200 and constrains nothing. /v1/completions has no template, so + * it passes null and the schema is compiled here. */ +static int parse_output_format(const json& b, const OaiDeps& d, OaiRequest* r, ApiError* err, + std::string* schema_json = nullptr) { + std::string gram; + if (!get_str(b, "grammar", &gram, err)) return RAD_E_INVAL; + + auto rf = b.find("response_format"); + const bool has_rf = rf != b.end() && !rf->is_null(); + if (!gram.empty() && has_rf) { + *err = err_bad("response_format", "cannot be combined with an explicit `grammar`"); + return RAD_E_INVAL; + } + if (!gram.empty()) { r->sp.grammar = gram; return RAD_OK; } + if (!has_rf) return RAD_OK; + + if (!rf->is_object()) { *err = err_bad("response_format", "expected an object"); return RAD_E_INVAL; } + std::string type; + if (!get_str(*rf, "type", &type, err)) return RAD_E_INVAL; + if (type.empty() || type == "text") return RAD_OK; + + json schema; + if (type == "json_object") { + schema = json::object(); + schema["type"] = "object"; + } else if (type == "json_schema") { + auto w = rf->find("json_schema"); + if (w == rf->end() || !w->is_object()) { + *err = err_bad("response_format.json_schema", "expected an object"); + return RAD_E_INVAL; + } + auto s = w->find("schema"); + if (s == w->end() || !s->is_object()) { + *err = err_bad("response_format.json_schema.schema", "expected a JSON Schema object"); + return RAD_E_INVAL; + } + schema = *s; + } else { + *err = err_bad("response_format.type", + "must be one of \"text\", \"json_object\", \"json_schema\", got \"" + + type + "\""); + return RAD_E_INVAL; + } + + if (schema_json) { *schema_json = schema.dump(); return RAD_OK; } + + if (!d.grammar) { + *err = err_not_implemented( + "response_format requires the JSON-schema to GBNF compiler (spec 13), which this " + "build was wired without"); + return RAD_E_UNSUPPORTED; + } + std::string out, why; + int s = d.grammar->from_json_schema(schema, out, why); + if (s < 0) { + *err = err_bad("response_format", "schema could not be compiled to a grammar: " + why); + return s; + } + r->sp.grammar = out; + return RAD_OK; +} + +/* ================================================================== multimodal content parts */ + +/* The marker the chat template renders for a media part. Both sides have to agree on it; it is + * declared here and in iface.h so that neither component owns it privately. */ +static const char* const MEDIA_MARKER = RAD_MEDIA_MARKER; + +/* Pull the bytes out of an OpenAI image_url. Only `data:` URLs are accepted: fetching an + * arbitrary http(s) URL on a caller's behalf turns the inference server into an SSRF proxy with + * network access to everything the deployment can reach, and no amount of allowlisting makes + * that a good default. */ +static int decode_media_url(const std::string& url, const std::string& field, + std::vector* out, ApiError* err) { + if (url.rfind("data:", 0) != 0) { + *err = err_bad(field, "only data: URLs are accepted; the server does not fetch remote URLs " + "on a request's behalf"); + return RAD_E_INVAL; + } + size_t comma = url.find(','); + if (comma == std::string::npos) { + *err = err_bad(field, "malformed data: URL"); + return RAD_E_INVAL; + } + const std::string meta = url.substr(5, comma - 5); + if (meta.find("base64") == std::string::npos) { + *err = err_bad(field, "data: URL must be base64 encoded"); + return RAD_E_INVAL; + } + if (!base64_decode(url.substr(comma + 1), out)) { + *err = err_bad(field, "invalid base64"); + return RAD_E_INVAL; + } + return RAD_OK; +} + +/* THE DEEPEST NESTING IN A JSON TEXT, counted without parsing it: brackets outside string + * literals, whether or not the text is valid JSON. */ +static int json_text_depth(const std::string& s) { + int d = 0, most = 0; + bool in_str = false, esc = false; + for (char c : s) { + if (in_str) { + if (esc) esc = false; + else if (c == '\\') esc = true; + else if (c == '"') in_str = false; + continue; + } + if (c == '"') in_str = true; + else if (c == '[' || c == '{') most = std::max(most, ++d); + else if ((c == ']' || c == '}') && d > 0) --d; + } + return most; +} + +/* STRINGS THE CHAT TEMPLATE PARSES AS JSON are bounded like the body is (parse_json_bounded). An + * assistant message's tool-call arguments and a tool message's content arrive as strings, one + * level deep in the request, and the template layer parses them into trees and serialises those + * again when it renders -- recursively, one call a level. Their nesting is checked here, before + * that happens, so a string of brackets cannot take the worker's stack. */ +static int check_template_json(const json& msg, const std::string& role, ApiError* err) { + if (role == "assistant") { + auto tcs = msg.find("tool_calls"); + if (tcs != msg.end() && tcs->is_array()) { + for (const auto& tc : *tcs) { + if (!tc.is_object()) continue; + auto fn = tc.find("function"); + if (fn == tc.end() || !fn->is_object()) continue; + auto args = fn->find("arguments"); + if (args != fn->end() && args->is_string() && + json_text_depth(args->get_ref()) > kJsonMaxDepth) { + *err = err_bad("messages[].tool_calls[].function.arguments", + "nests more than " + std::to_string(kJsonMaxDepth) + + " levels deep"); + return RAD_E_INVAL; + } + } + } + } + if (role == "tool") { + auto c = msg.find("content"); + if (c != msg.end() && c->is_string() && + json_text_depth(c->get_ref()) > kJsonMaxDepth) { + *err = err_bad("messages[].content", "a tool result nests more than " + + std::to_string(kJsonMaxDepth) + + " levels deep"); + return RAD_E_INVAL; + } + } + return RAD_OK; +} + +/* Rewrite content parts in place: text stays, media becomes the marker and its bytes are handed + * to the encoder. `media` collects (kind, bytes) in the order they appear, which is the order the + * markers appear in the rendered prompt. */ +static int lower_content_parts(json& messages, const OaiDeps& d, const OaiLimits& lim, + std::vector>>* media, + ApiError* err) { + if (!messages.is_array()) { *err = err_bad("messages", "expected an array"); return RAD_E_INVAL; } + if (messages.empty()) { *err = err_bad("messages", "must not be empty"); return RAD_E_INVAL; } + + for (auto& msg : messages) { + if (!msg.is_object()) { *err = err_bad("messages[]", "expected an object"); return RAD_E_INVAL; } + std::string role; + auto rit = msg.find("role"); + if (rit == msg.end() || !rit->is_string()) { + *err = err_bad("messages[].role", "expected a string"); + return RAD_E_INVAL; + } + role = rit->get(); + if (role != "system" && role != "developer" && role != "user" && + role != "assistant" && role != "tool") { + *err = err_bad("messages[].role", "unknown role \"" + role + "\""); + return RAD_E_INVAL; + } + RAD_TRY(check_template_json(msg, role, err)); + + auto cit = msg.find("content"); + if (cit == msg.end() || cit->is_null()) { + if (role == "assistant" && msg.contains("tool_calls")) continue; + *err = err_bad("messages[].content", + "required for every message except an assistant message that carries " + "tool_calls"); + return RAD_E_INVAL; + } + if (cit->is_string()) continue; + if (!cit->is_array()) { + *err = err_bad("messages[].content", "expected a string or an array of content parts"); + return RAD_E_INVAL; + } + + for (auto& part : *cit) { + std::string type; + auto tit = part.find("type"); + if (tit == part.end() || !tit->is_string()) { + *err = err_bad("messages[].content[].type", "expected a string"); + return RAD_E_INVAL; + } + type = tit->get(); + + if (type == "text") { + if (!part.contains("text") || !part.at("text").is_string()) { + *err = err_bad("messages[].content[].text", "expected a string"); + return RAD_E_INVAL; + } + continue; + } + /* IMAGE AND VIDEO PARTS, in the two spellings clients send: OpenAI's + * {"type":"image_url","image_url":{"url":...}} (and the bare-string form), the + * Responses API's "input_image", and the video equivalents vLLM's clients use -- + * {"type":"video_url","video_url":{"url":...}} and "input_video". */ + const bool is_image = type == "image_url" || type == "input_image"; + const bool is_video = type == "video_url" || type == "input_video"; + if (is_image || is_video) { + const MediaKind kind = is_image ? MediaKind::Image : MediaKind::Video; + const char* what = is_image ? "image" : "video"; + const bool allowed = is_image ? lim.allow_image : lim.allow_video; + if (!allowed || !d.mm || !d.mm->accepts(kind)) { + *err = err_not_implemented( + std::string(what) + " input requires a vision encoder (spec 11); this " + "model was loaded without one"); + return RAD_E_UNSUPPORTED; + } + const std::string key = is_image ? "image_url" : "video_url"; + const std::string field = "messages[].content[]." + key; + std::string url; + auto iu = part.find(key); + if (iu == part.end() && type == "input_image") iu = part.find("image_url"); + if (iu == part.end() && type == "input_video") iu = part.find("video_url"); + if (iu != part.end() && iu->is_object() && iu->contains("url") && + iu->at("url").is_string()) + url = iu->at("url").get(); + else if (iu != part.end() && iu->is_string()) + url = iu->get(); + else { + *err = err_bad(field, "expected {\"url\": ...}"); + return RAD_E_INVAL; + } + std::vector bytes; + RAD_TRY(decode_media_url(url, field + ".url", &bytes, err)); + media->emplace_back(kind, std::move(bytes)); + /* A MEDIA MARKER, NOT TEXT. The chat layer flattens a message's parts into one + * string and joins TEXT parts with a newline; it joins a marker to its neighbours + * with nothing, which is what the model's own template does with an image part + * (<|vision_end|> runs straight into the text after it). Joined as text, every + * picture would cost one '\n' token the model's own prompt does not have. */ + part.erase(key); + part["type"] = "media_marker"; + part["text"] = MEDIA_MARKER; + continue; + } + if (type == "input_audio") { + if (!lim.allow_audio || !d.mm || !d.mm->accepts(MediaKind::Audio)) { + *err = err_not_implemented( + "audio input requires an audio encoder (spec 11); this model was loaded " + "without one"); + return RAD_E_UNSUPPORTED; + } + auto ia = part.find("input_audio"); + if (ia == part.end() || !ia->is_object() || !ia->contains("data") || + !ia->at("data").is_string()) { + *err = err_bad("messages[].content[].input_audio", + "expected {\"data\": ..., \"format\": ...}"); + return RAD_E_INVAL; + } + auto fit = ia->find("format"); + const std::string fmt = + fit != ia->end() && fit->is_string() ? fit->get() : std::string(); + if (fmt != "wav" && fmt != "mp3") { + *err = err_bad("messages[].content[].input_audio.format", + "must be \"wav\" or \"mp3\""); + return RAD_E_INVAL; + } + std::vector bytes; + if (!base64_decode(ia->at("data").get(), &bytes)) { + *err = err_bad("messages[].content[].input_audio.data", "invalid base64"); + return RAD_E_INVAL; + } + media->emplace_back(MediaKind::Audio, std::move(bytes)); + part.erase("input_audio"); + part["type"] = "media_marker"; + part["text"] = MEDIA_MARKER; + continue; + } + *err = err_bad("messages[].content[].type", + "unsupported content part type \"" + type + "\""); + return RAD_E_INVAL; + } + } + return RAD_OK; +} + +/* Tokenise a rendered prompt that contains media markers, replacing each marker with the token + * run its media part became: the processor's placeholders -- the model's own pad ids, which a + * hashed n-gram embedding reads like any other -- with whatever markers and timestamps the model + * wants around them. The encoder's rows replace the placeholders' embeddings later (spec §11); + * here only the ids and their offsets are fixed, and with them the prompt's rotary layout. + * + * Each media part is processed HERE, on the request's own worker, because decoding a video and + * resizing its frames is the most expensive host work a request can bring: it must not reach the + * scheduler's thread, where every other request's step would wait on it. */ +static int tokenize_with_media(const std::string& rendered, const OaiDeps& d, + std::vector>>& media, + PromptInput* out, ApiError* err) { + out->text = rendered; + auto pm = std::make_shared(); + const std::string marker = MEDIA_MARKER; + size_t pos = 0, mi = 0; + for (;;) { + size_t at = rendered.find(marker, pos); + std::string seg = rendered.substr(pos, at == std::string::npos ? std::string::npos : at - pos); + if (!seg.empty()) { + /* add_special is false for every segment, the first included: the template renders + * whatever special tokens the model wants, and an extra BOS would shift every + * position after it -- the same reason the text-only path gives. */ + auto ids = d.tok->encode(seg, false, /*parse_special=*/true); + out->tokens.insert(out->tokens.end(), ids.begin(), ids.end()); + } + if (at == std::string::npos) break; + if (mi >= media.size()) { + *err = err_bad("messages", + "the chat template rendered more media markers than the request had " + "media parts"); + return RAD_E_INVAL; + } + std::shared_ptr item; + std::string why; + const int s = d.mm->prepare(media[mi].first, media[mi].second, &item, &why); + if (s < 0 || !item) { + *err = err_bad("messages[].content[]", "the media could not be used: " + + (why.empty() ? std::string(rad_strerror(s)) + : why)); + return s < 0 ? s : RAD_E_INVAL; + } + media[mi].second.clear(); + media[mi].second.shrink_to_fit(); + mm::Placed pl; + pl.item = item; + pl.tok = (int32_t)out->tokens.size(); + out->tokens.insert(out->tokens.end(), item->expand.begin(), item->expand.end()); + pm->items.push_back(std::move(pl)); + ++mi; + pos = at + marker.size(); + } + if (mi != media.size()) { + *err = err_bad("messages", + "the chat template dropped a media part: the request carried more media " + "than the rendered prompt has markers for"); + return RAD_E_INVAL; + } + pm->layout(); + out->media = std::move(pm); + return RAD_OK; +} + +/* ================================================================== the context bound + * + * THE CONTEXT CLAMPS max_tokens RATHER THAN REFUSING THE REQUEST. + * + * `max_tokens` is an upper bound -- "stop by here at the latest" -- and the context is a second + * upper bound that holds whether or not the request acknowledges it: a sequence cannot run past + * it however many tokens were asked for. So refusing does not produce more tokens than clamping + * does, it produces none, and the field that caused the refusal could not have been honoured at + * any value the caller might have sent instead. + * + * That matters because a fixed `max_tokens` is what clients actually send. A caller whose default + * is 128k gets a 400 on every prompt long enough to matter -- exactly the requests a long-context + * server exists for -- and the only fix available to them is to compute the server's remaining + * window themselves, which they cannot do without knowing the tokeniser. + * + * A PROMPT THAT DOES NOT FIT ON ITS OWN IS STILL AN ERROR. There is no window left to generate + * into, nothing about the request is servable, and the caller has to shorten the prompt -- so that + * case keeps its refusal and names how much has to go. + * + * This is the one deliberate exception to the rule the key vetting above enforces, that a 200 + * means every field of the request was honoured. It is an exception because those keys are + * SETTINGS -- dropping one serves a different model than the caller asked for -- and this one is a + * BOUND, whose purpose is to stop generation early and which the context was going to stop earlier + * anyway. What the caller gets back still says so: the completion ends with finish_reason + * "length" and `usage` reports the tokens it actually produced. + */ +static int clamp_max_tokens(size_t n_prompt, const OaiLimits& lim, const char* field, + OaiRequest* out, ApiError* err) { + if (lim.max_ctx <= 0) return RAD_OK; /* no bound declared, nothing to clamp against */ + + const int64_t room = lim.max_ctx - (int64_t)n_prompt; + if (room <= 0) { + char msg[256]; + snprintf(msg, sizeof msg, + "%zu prompt tokens does not fit the %lld token context, which leaves nothing to " + "generate into; shorten the prompt by at least %lld tokens", + n_prompt, (long long)lim.max_ctx, (long long)(1 - room)); + *err = err_bad(field, msg); + err->code = "context_length_exceeded"; + return RAD_E_INVAL; + } + + if ((int64_t)out->max_tokens > room) { + /* Debug rather than Warn: on a long-context deployment whose clients send a constant + * max_tokens this fires on every request that is working correctly, and a line printed + * per request is how a server's log stops being read at all. */ + RAD_DEBUG("max_tokens %d does not fit beside %zu prompt tokens in a %lld token context; " + "serving %lld", (int)out->max_tokens, n_prompt, (long long)lim.max_ctx, + (long long)room); + out->max_tokens = (int32_t)room; + } + return RAD_OK; +} + +/* ================================================================== chat */ + +int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim, + OaiRequest* out, ApiError* err) { + json b; + RAD_TRY(parse_request_object(body, lim, &b, err)); + RAD_TRY(vet_keys(b, Endpoint::Chat, err)); + + out->endpoint = Endpoint::Chat; + out->id = random_id("chatcmpl-"); + out->created = unix_now(); + out->model = lim.model_id; + if (!get_str(b, "model", &out->model, err)) return RAD_E_INVAL; + if (out->model.empty()) out->model = lim.model_id; + + RAD_TRY(parse_sampling(b, lim, out, err)); + std::string schema_json; + RAD_TRY(parse_output_format(b, d, out, err, &schema_json)); + + /* logprobs. The wire format is implemented; whether the sampler produces the numbers is a + * property of the build, and if it does not we refuse rather than return nulls that look + * like "the model had no opinion". */ + bool want = false; + if (!get_bool(b, "logprobs", &want, err)) return RAD_E_INVAL; + int64_t top = 0; + if (!get_int(b, "top_logprobs", &top, err)) return RAD_E_INVAL; + if (!want && top > 0) { + *err = err_bad("top_logprobs", "requires logprobs to be true"); + return RAD_E_INVAL; + } + if (top < 0 || top > 20) { *err = err_bad("top_logprobs", "must be in [0, 20]"); return RAD_E_INVAL; } + if (want && !lim.supports_logprobs) { + *err = err_unsupported("logprobs", + "this build's sampler does not return per-token probabilities"); + return RAD_E_UNSUPPORTED; + } + out->want_logprobs = want; + out->n_logprobs = (int)top; + + if (!d.chat) { + *err = err_not_implemented( + "/v1/chat/completions requires a chat template (spec 12); this model was loaded " + "without one. Use /v1/completions"); + return RAD_E_UNSUPPORTED; + } + + auto mit = b.find("messages"); + if (mit == b.end()) { *err = err_bad("messages", "is required"); return RAD_E_INVAL; } + json messages = *mit; + + /* tools and tool_choice. */ + json tools = json::array(); + auto tit = b.find("tools"); + if (tit != b.end() && !tit->is_null()) { + if (!tit->is_array()) { *err = err_bad("tools", "expected an array"); return RAD_E_INVAL; } + for (const auto& t : *tit) { + if (!t.is_object() || !t.contains("type") || t.at("type") != "function" || + !t.contains("function") || !t.at("function").is_object() || + !t.at("function").contains("name") || + !t.at("function").at("name").is_string()) { + *err = err_bad("tools[]", + "expected {\"type\":\"function\",\"function\":{\"name\":...}}"); + return RAD_E_INVAL; + } + } + tools = *tit; + } + + /* FORCING A CALL IS REFUSED, and not because the grammar is out of reach -- the template + * returns one. It is that the grammar it returns for a forced choice does not force anything: + * it admits leading prose (the template invites "optional reasoning BEFORE the function + * call") and then an unbounded run of calls with no terminating state, so the reply is prose + * followed by invented calls and `finish_reason: "length"`. Serving that would be worse than + * refusing it: the caller asked for exactly one call and would get a request that never stops. + * `parallel_tool_calls: false` IS honoured -- that one narrows the grammar's repetition rule, + * which is a change the generator actually makes. */ + std::string tool_choice = "auto", named; + auto tcit = b.find("tool_choice"); + if (tcit != b.end() && !tcit->is_null()) { + if (tcit->is_string()) { + tool_choice = tcit->get(); + } else if (tcit->is_object()) { + auto f = tcit->find("function"); + if (f == tcit->end() || !f->is_object() || !f->contains("name") || + !f->at("name").is_string()) { + *err = err_bad("tool_choice", + "an object tool_choice must be {\"type\":\"function\"," + "\"function\":{\"name\":...}}"); + return RAD_E_INVAL; + } + named = f->at("name").get(); + tool_choice = "required"; + } else { + *err = err_bad("tool_choice", "expected a string or an object"); + return RAD_E_INVAL; + } + } + if (tool_choice == "none") { + tools = json::array(); + } else if (tool_choice == "required") { + *err = err_unsupported( + "tool_choice", + named.empty() + ? "\"auto\" and \"none\" are implemented. \"required\" is not: the grammar this " + "model's template produces for it admits prose before the call and an unbounded " + "run of calls after it, so it does not force one call -- it produces a reply " + "that runs to max_tokens. Send \"auto\" and check the response for a call." + : "a named function is not implemented, for the same reason \"required\" is not: " + "the template's forced-call grammar does not terminate. Send \"auto\" with only " + "that function in `tools`."); + return RAD_E_UNSUPPORTED; + } else if (tool_choice != "auto") { + *err = err_bad("tool_choice", "must be \"none\", \"auto\", \"required\", or an object"); + return RAD_E_INVAL; + } + + /* Honoured by the grammar rather than by a prompt instruction: the auto-parser emits a + * repeatable call section only when this is true (chat-auto-parser-generator.cpp), so false + * genuinely admits one call and not several. */ + bool parallel = true; + if (!get_bool(b, "parallel_tool_calls", ¶llel, err)) return RAD_E_INVAL; + + if (!tools.empty() && !d.chat->supports_tools()) { + *err = err_unsupported("tools", + "this model's chat template does not declare tool support"); + return RAD_E_UNSUPPORTED; + } + if (!tools.empty()) { + const std::string why = d.chat->tool_refusal(); + if (!why.empty()) { + *err = err_unsupported("tools", "this model's tool calls cannot be read back: " + why); + return RAD_E_UNSUPPORTED; + } + } + out->tools_present = !tools.empty(); + + ChatRenderOptions opt; + opt.tool_choice = tool_choice; + opt.parallel_tool_calls = parallel; + if (!get_bool(b, "add_generation_prompt", &opt.add_generation_prompt, err)) return RAD_E_INVAL; + + /* The template's grammar and the caller's are ONE grammar, not two, and the template is the + * one that knows how to combine them -- a tool-calling format has to leave room for the call + * syntax around whatever the caller constrained. So both halves go IN and the merged result + * comes back out: a raw GBNF as `grammar`, a `response_format` as the schema it started as. */ + opt.grammar = out->sp.grammar; + opt.json_schema = schema_json; + + RAD_TRY(parse_thinking(b, lim, &opt, err)); + + std::vector>> media; + RAD_TRY(lower_content_parts(messages, d, lim, &media, err)); + + ChatRender render; + std::string why; + const int rs = d.chat->apply(messages, tools, opt, &render, &why); + if (rs < 0) { + *err = rs == RAD_E_UNSUPPORTED + ? err_unsupported("messages", why.empty() ? "the chat template refused this " + "request" : why) + : err_bad("messages", why.empty() ? "the chat template could not render this " + "request" : why); + return rs; + } + if (render.prompt.empty()) { + *err = err_bad("messages", "the chat template rendered an empty prompt"); + return RAD_E_INVAL; + } + + /* Everything the render decided that the rest of the request has to carry. The grammar can + * come back non-empty when none went in -- that is a tool-calling template constraining its + * own call syntax -- and it arrives LAZY, so the reply is free prose until the model starts + * writing a call. Dropping `grammar_lazy` here would constrain the whole reply to be a tool + * call, which is a model that can no longer answer in words. */ + /* A REQUEST THAT ASKED TO BE CONSTRAINED AND CAME BACK UNCONSTRAINED IS A REFUSAL, not a 200. + * `response_format` and `grammar` are promises about the shape of the answer; a template that + * returns no grammar for one has not kept it, and returning the answer anyway would leave the + * caller parsing free prose against a schema they were told was enforced. */ + if (render.grammar.empty() && !(opt.grammar.empty() && opt.json_schema.empty())) { + *err = err_unsupported(opt.json_schema.empty() ? "grammar" : "response_format", + "this model's chat template produced no grammar for it, so the " + "constraint could not be enforced"); + return RAD_E_UNSUPPORTED; + } + + out->sp.grammar = render.grammar; + out->sp.grammar_lazy = render.grammar_lazy; + out->sp.grammar_triggers = render.grammar_triggers; + out->sp.grammar_prefix = render.generation_prompt; + out->reply_parser = render.parser; + out->preserved_tokens = render.preserved_tokens; + out->parse_tools = out->tools_present && render.parser != nullptr; + + /* The format's own end-of-turn markers join the caller's stop strings rather than living in a + * second list: both end the generation and both report `finish_reason: "stop"` (sink.cpp), so + * a separate list would be a distinction with no observable difference. */ + for (const auto& s : render.additional_stops) + if (std::find(out->stop.begin(), out->stop.end(), s) == out->stop.end()) + out->stop.push_back(s); + + /* Checked HERE, where the answer is still a 400. The grammar being validated may be the + * caller's, or one the template produced for its own tool-call syntax; either way the first + * moment it can fail is when the automaton is built, and building it on the step path would + * mean failing a request that is already streaming. */ + if (!out->sp.grammar.empty() && d.grammar) { + std::string gerr; + if (d.grammar->compile(out->sp.grammar, &out->sp.grammar_program, gerr) < 0) { + *err = err_bad(out->tools_present ? "tools" : "grammar", + "the grammar this request implies cannot be run: " + gerr); + return RAD_E_INVAL; + } + } + + const std::string& rendered = render.prompt; + + PromptInput p; + if (media.empty()) { + /* add_special is false: a chat template renders whatever special tokens the model wants, + * including its BOS. Adding another is a silent off-by-one in every position. */ + p.tokens = d.tok->encode(rendered, false, /*parse_special=*/true); + p.text = rendered; + } else { + RAD_TRY(tokenize_with_media(rendered, d, media, &p, err)); + } + if (p.tokens.empty()) { + *err = err_bad("messages", "the rendered prompt tokenised to nothing"); + return RAD_E_INVAL; + } + RAD_TRY(clamp_max_tokens(p.tokens.size(), lim, "messages", out, err)); + out->prompts.push_back(std::move(p)); + return RAD_OK; +} + +/* ================================================================== completions */ + +int parse_completion_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim, + OaiRequest* out, ApiError* err) { + json b; + RAD_TRY(parse_request_object(body, lim, &b, err)); + RAD_TRY(vet_keys(b, Endpoint::Completion, err)); + + out->endpoint = Endpoint::Completion; + out->id = random_id("cmpl-"); + out->created = unix_now(); + out->model = lim.model_id; + if (!get_str(b, "model", &out->model, err)) return RAD_E_INVAL; + if (out->model.empty()) out->model = lim.model_id; + + RAD_TRY(parse_sampling(b, lim, out, err)); + RAD_TRY(parse_output_format(b, d, out, err)); + + /* Checked HERE for the same reason as on the chat path: a grammar the machine refuses is a + * 400 while the request can still be refused, rather than a compile on the scheduler thread + * that cancels a request the client was told had been accepted. */ + if (!out->sp.grammar.empty() && d.grammar) { + std::string gerr; + if (d.grammar->compile(out->sp.grammar, &out->sp.grammar_program, gerr) < 0) { + *err = err_bad(b.contains("grammar") ? "grammar" : "response_format", + "the grammar this request implies cannot be run: " + gerr); + return RAD_E_INVAL; + } + } + + if (!get_bool(b, "echo", &out->echo, err)) return RAD_E_INVAL; + + /* /v1/completions `logprobs` is an integer count, not a boolean. */ + auto lit = b.find("logprobs"); + if (lit != b.end() && !lit->is_null()) { + if (!lit->is_number_integer()) { + *err = err_bad("logprobs", "expected an integer (the number of alternatives)"); + return RAD_E_INVAL; + } + int64_t nl = lit->get(); + if (nl < 0 || nl > 5) { *err = err_bad("logprobs", "must be in [0, 5]"); return RAD_E_INVAL; } + if (nl > 0 && !lim.supports_logprobs) { + *err = err_unsupported("logprobs", + "this build's sampler does not return per-token probabilities"); + return RAD_E_UNSUPPORTED; + } + out->want_logprobs = nl > 0; + out->n_logprobs = (int)nl; + } + + auto pit = b.find("prompt"); + if (pit == b.end() || pit->is_null()) { + *err = err_bad("prompt", "is required"); + return RAD_E_INVAL; + } + + auto push_text = [&](const std::string& s) { + PromptInput p; + p.text = s; + p.tokens = d.tok->encode(s, true, /*parse_special=*/false); + out->prompts.push_back(std::move(p)); + }; + auto push_ids = [&](const json& arr, ApiError* e) -> bool { + PromptInput p; + for (const auto& v : arr) { + if (!v.is_number_integer()) { + *e = err_bad("prompt", "token arrays must contain integers only"); + return false; + } + int32_t id = 0; + if (!token_id(v, &id)) { + *e = err_bad("prompt", "a token id must be in [0, 2147483647], got " + v.dump()); + return false; + } + p.tokens.push_back(id); + } + p.text = d.tok->decode(p.tokens); + out->prompts.push_back(std::move(p)); + return true; + }; + + if (pit->is_string()) { + push_text(pit->get()); + } else if (pit->is_array()) { + if (pit->empty()) { *err = err_bad("prompt", "must not be empty"); return RAD_E_INVAL; } + if (pit->front().is_string()) { + for (const auto& s : *pit) { + if (!s.is_string()) { + *err = err_bad("prompt", "a prompt array must be all strings or all tokens"); + return RAD_E_INVAL; + } + push_text(s.get()); + } + } else if (pit->front().is_number_integer()) { + if (!push_ids(*pit, err)) return RAD_E_INVAL; + } else if (pit->front().is_array()) { + for (const auto& a : *pit) { + if (!a.is_array()) { + *err = err_bad("prompt", "a batch of token arrays must be all arrays"); + return RAD_E_INVAL; + } + if (!push_ids(a, err)) return RAD_E_INVAL; + } + } else { + *err = err_bad("prompt", "expected a string, an array of strings, an array of token " + "ids, or an array of token id arrays"); + return RAD_E_INVAL; + } + } else { + *err = err_bad("prompt", "expected a string or an array"); + return RAD_E_INVAL; + } + + /* THE LONGEST PROMPT SETS THE CLAMP. This endpoint takes a BATCH of prompts and `max_tokens` + * is one field shared by all of them, so clamping against each in turn would leave the last + * one's room standing as the answer for every prompt before it -- and a short prompt would be + * cut off for a window it was never short of. */ + size_t longest = 0; + for (const auto& p : out->prompts) { + if (p.tokens.empty()) { *err = err_bad("prompt", "tokenised to nothing"); return RAD_E_INVAL; } + if (p.tokens.size() > longest) longest = p.tokens.size(); + } + RAD_TRY(clamp_max_tokens(longest, lim, "prompt", out, err)); + return RAD_OK; +} + +/* ================================================================== embeddings */ + +int parse_embeddings_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim, + OaiRequest* out, ApiError* err) { + json b; + RAD_TRY(parse_request_object(body, lim, &b, err)); + RAD_TRY(vet_keys(b, Endpoint::Embedding, err)); + + out->endpoint = Endpoint::Embedding; + out->id = random_id("embd-"); + out->created = unix_now(); + out->model = lim.model_id; + if (!get_str(b, "model", &out->model, err)) return RAD_E_INVAL; + if (out->model.empty()) out->model = lim.model_id; + + std::string enc = "float"; + if (!get_str(b, "encoding_format", &enc, err)) return RAD_E_INVAL; + if (enc != "float" && enc != "base64") { + *err = err_bad("encoding_format", "must be \"float\" or \"base64\""); + return RAD_E_INVAL; + } + out->base64_embeddings = (enc == "base64"); + + if (b.contains("dimensions") && !b.at("dimensions").is_null()) { + *err = err_unsupported("dimensions", + "Matryoshka truncation is not implemented; the model's embedding " + "dimension is fixed"); + return RAD_E_UNSUPPORTED; + } + + auto it = b.find("input"); + if (it == b.end() || it->is_null()) { *err = err_bad("input", "is required"); return RAD_E_INVAL; } + + auto push_ids = [&](const json& arr, ApiError* e) -> bool { + PromptInput p; + for (const auto& v : arr) { + if (!v.is_number_integer()) { + *e = err_bad("input", "token arrays must contain integers only"); + return false; + } + int32_t id = 0; + if (!token_id(v, &id)) { + *e = err_bad("input", "a token id must be in [0, 2147483647], got " + v.dump()); + return false; + } + p.tokens.push_back(id); + } + out->prompts.push_back(std::move(p)); + return true; + }; + + if (it->is_string()) { + PromptInput p; + p.text = it->get(); + p.tokens = d.tok->encode(p.text, true, /*parse_special=*/false); + out->prompts.push_back(std::move(p)); + } else if (it->is_array()) { + if (it->empty()) { *err = err_bad("input", "must not be empty"); return RAD_E_INVAL; } + if (it->front().is_string()) { + for (const auto& s : *it) { + if (!s.is_string()) { *err = err_bad("input", "expected all strings"); return RAD_E_INVAL; } + PromptInput p; + p.text = s.get(); + p.tokens = d.tok->encode(p.text, true, /*parse_special=*/false); + out->prompts.push_back(std::move(p)); + } + } else if (it->front().is_number_integer()) { + if (!push_ids(*it, err)) return RAD_E_INVAL; + } else if (it->front().is_array()) { + for (const auto& a : *it) { + if (!a.is_array()) { *err = err_bad("input", "expected arrays"); return RAD_E_INVAL; } + if (!push_ids(a, err)) return RAD_E_INVAL; + } + } else { + *err = err_bad("input", "expected a string, an array of strings, or token ids"); + return RAD_E_INVAL; + } + } else { + *err = err_bad("input", "expected a string or an array"); + return RAD_E_INVAL; + } + + for (const auto& p : out->prompts) { + if (p.tokens.empty()) { *err = err_bad("input", "tokenised to nothing"); return RAD_E_INVAL; } + if (lim.max_ctx > 0 && (int64_t)p.tokens.size() > lim.max_ctx) { + *err = err_bad("input", "exceeds the model context"); + err->code = "context_length_exceeded"; + return RAD_E_INVAL; + } + } + return RAD_OK; +} + +/* ================================================================== responses */ + +static json tool_calls_json(const std::vector& tcs) { + json a = json::array(); + for (const auto& t : tcs) { + json f; + f["name"] = t.name; + f["arguments"] = t.arguments; + json c; + c["id"] = t.id; + c["type"] = "function"; + c["function"] = f; + a.push_back(std::move(c)); + } + return a; +} + +static json usage_json(const UsageOut& u) { + json d; + d["cached_tokens"] = u.cached; + json o; + o["prompt_tokens"] = u.prompt; + o["completion_tokens"] = u.completion; + o["total_tokens"] = u.prompt + u.completion; + o["prompt_tokens_details"] = d; + return o; +} + +/* THE USAGE CHUNKS. + * + * `stream_options.include_usage` is parsed, validated and accepted on both endpoints, so both + * streams have to emit it; accepting the field and then not honouring it is the outcome + * core/server/oai.h's header forbids in its opening paragraph. + * + * One contract for both, OpenAI's: an empty choices array, sent after the last content chunk + * and before [DONE]. Only the `object` differs, because it is a different endpoint's stream. */ +static std::string usage_chunk(const OaiRequest& r, const UsageOut& u, const char* object) { + json o; + o["id"] = r.id; + o["object"] = object; + o["created"] = r.created; + o["model"] = r.model; + o["choices"] = json::array(); + o["usage"] = usage_json(u); + return sse_event(o.dump()); +} + +std::string text_usage_chunk(const OaiRequest& r, const UsageOut& u) { + return usage_chunk(r, u, "text_completion"); +} + +std::string chat_usage_chunk(const OaiRequest& r, const UsageOut& u) { + return usage_chunk(r, u, "chat.completion.chunk"); +} + +static json chat_logprobs_json(const std::vector& lp) { + json content = json::array(); + for (const auto& e : lp) { + json bytes = json::array(); + for (unsigned char c : e.text) bytes.push_back((int)c); + json j; + j["token"] = e.text; + j["logprob"] = e.logprob; + j["bytes"] = bytes; + j["top_logprobs"] = json::array(); + content.push_back(std::move(j)); + } + json o; + o["content"] = content; + return o; +} + +std::string chat_completion_body(const OaiRequest& r, const std::vector& choices, + const UsageOut& u) { + json arr = json::array(); + for (const auto& c : choices) { + json m; + m["role"] = "assistant"; + if (c.msg.content.empty() && !c.msg.tool_calls.empty()) m["content"] = nullptr; + else m["content"] = c.msg.content; + if (!c.msg.reasoning.empty()) m["reasoning_content"] = c.msg.reasoning; + if (!c.msg.tool_calls.empty()) m["tool_calls"] = tool_calls_json(c.msg.tool_calls); + + json ch; + ch["index"] = c.index; + ch["message"] = std::move(m); + if (r.want_logprobs) ch["logprobs"] = chat_logprobs_json(c.logprobs); + else ch["logprobs"] = nullptr; + ch["finish_reason"] = finish_reason_oai(c.finish); + arr.push_back(std::move(ch)); + } + json o; + o["id"] = r.id; + o["object"] = "chat.completion"; + o["created"] = r.created; + o["model"] = r.model; + o["choices"] = std::move(arr); + o["usage"] = usage_json(u); + return o.dump(); +} + +std::string text_completion_body(const OaiRequest& r, const std::vector& choices, + const UsageOut& u) { + json arr = json::array(); + for (const auto& c : choices) { + json ch; + ch["text"] = c.text; + ch["index"] = c.index; + if (r.want_logprobs) { + json toks = json::array(), lps = json::array(), offs = json::array(); + int64_t off = 0; + for (const auto& e : c.logprobs) { + toks.push_back(e.text); + lps.push_back(e.logprob); + offs.push_back(off); + off += (int64_t)e.text.size(); + } + json lp; + lp["tokens"] = toks; + lp["token_logprobs"] = lps; + lp["top_logprobs"] = json::array(); + lp["text_offset"] = offs; + ch["logprobs"] = std::move(lp); + } else { + ch["logprobs"] = nullptr; + } + ch["finish_reason"] = finish_reason_oai(c.finish); + arr.push_back(std::move(ch)); + } + json o; + o["id"] = r.id; + o["object"] = "text_completion"; + o["created"] = r.created; + o["model"] = r.model; + o["choices"] = std::move(arr); + o["usage"] = usage_json(u); + return o.dump(); +} + +std::string embeddings_body(const OaiRequest& r, const std::vector>& vecs, + const UsageOut& u) { + json data = json::array(); + for (size_t i = 0; i < vecs.size(); ++i) { + json e; + e["object"] = "embedding"; + if (r.base64_embeddings) + e["embedding"] = base64_encode(vecs[i].data(), vecs[i].size() * sizeof(float)); + else + e["embedding"] = vecs[i]; + e["index"] = (int64_t)i; + data.push_back(std::move(e)); + } + json usage; + usage["prompt_tokens"] = u.prompt; + usage["total_tokens"] = u.prompt; + json o; + o["object"] = "list"; + o["data"] = std::move(data); + o["model"] = r.model; + o["usage"] = std::move(usage); + return o.dump(); +} + +std::string models_body(const std::string& model_id, int64_t created) { + json m; + m["id"] = model_id; + m["object"] = "model"; + m["created"] = created; + m["owned_by"] = "radiance"; + json o; + o["object"] = "list"; + o["data"] = json::array({m}); + return o.dump(); +} + +/* ================================================================== SSE */ + +std::string sse_event(const std::string& json_text) { + return "data: " + json_text + "\n\n"; +} + +std::string sse_error(const ApiError& e) { + /* A failure after the headers have gone out cannot change the status code, so the error has + * to travel in the stream. Clients that ignore it still see the stream end; clients that read + * it get the reason instead of a truncated answer. */ + return "data: " + e.dump() + "\n\n"; +} + +/* ================================================================== the streaming path */ + +ChatDeltaStream::ChatDeltaStream(const OaiRequest& r, int index, const IReplyParser* parser) + : reader_(parser ? parser->open() : nullptr), id_(r.id), model_(r.model), + created_(r.created), index_(index) {} + +std::string ChatDeltaStream::chunk(json delta, const char* finish_reason) { + json ch; + ch["index"] = index_; + ch["delta"] = std::move(delta); + if (finish_reason) ch["finish_reason"] = finish_reason; + else ch["finish_reason"] = nullptr; + json o; + o["id"] = id_; + o["object"] = "chat.completion.chunk"; + o["created"] = created_; + o["model"] = model_; + o["choices"] = json::array({ch}); + return sse_event(o.dump()); +} + +std::string ChatDeltaStream::first_chunk() { + json d; + d["role"] = "assistant"; + d["content"] = ""; + return chunk(std::move(d), nullptr); +} + +/* One SSE chunk per increment, in the order the reader completed them. A call is announced with + * its id, name and empty arguments before any of its arguments flow -- an entry with no name is + * an index the client can never resolve -- and the id is minted here, because the parser reads + * the model's text and the model writes none. */ +std::string ChatDeltaStream::emit(const std::vector& ev) { + std::string out; + for (const ReplyDelta& d : ev) { + json delta; + switch (d.kind) { + case ReplyDelta::Reasoning: + if (d.text.empty()) continue; + last_.reasoning += d.text; + delta["reasoning_content"] = d.text; + break; + case ReplyDelta::Content: + if (d.text.empty()) continue; + last_.content += d.text; + delta["content"] = d.text; + break; + case ReplyDelta::CallBegin: { + ToolCall tc; + tc.id = random_id("call_"); + tc.name = d.text; + last_.tool_calls.push_back(tc); + json f; + f["name"] = tc.name; + f["arguments"] = ""; + json e; + e["index"] = (int64_t)d.call; + e["id"] = tc.id; + e["type"] = "function"; + e["function"] = std::move(f); + delta["tool_calls"] = json::array({e}); + break; + } + case ReplyDelta::CallArgs: { + if (d.text.empty() || d.call >= last_.tool_calls.size()) continue; + last_.tool_calls[d.call].arguments += d.text; + json f; + f["arguments"] = d.text; + json e; + e["index"] = (int64_t)d.call; + e["function"] = std::move(f); + delta["tool_calls"] = json::array({e}); + break; + } + case ReplyDelta::CallEnd: + continue; + } + out += chunk(std::move(delta), nullptr); + } + return out; +} + +std::string ChatDeltaStream::push(std::string_view appended, bool is_final) { + if (finished_) return std::string(); + std::string out; + if (!reader_) { + /* Nothing to parse: the text is the answer, as it arrives. */ + if (!appended.empty()) { + last_.content.append(appended); + json d; + d["content"] = std::string(appended); + out = chunk(std::move(d), nullptr); + } + finished_ = is_final; + return out; + } + ev_.clear(); + if (!appended.empty()) reader_->feed(appended, &ev_); + if (is_final) reader_->finish(&ev_); + out = emit(ev_); + if (is_final) { + finished_ = true; + /* The reader's message is the reply by definition; the deltas above add up to it, and + * the ids are the ones this stream minted. */ + ParsedMessage m = reader_->message(); + for (size_t i = 0; i < m.tool_calls.size() && i < last_.tool_calls.size(); ++i) + m.tool_calls[i].id = last_.tool_calls[i].id; + last_ = std::move(m); + } + return out; +} + +Finish ChatDeltaStream::adjusted_finish(Finish f) const { + if (f != Finish::Stop && f != Finish::StopString) return f; + if (last_.tool_calls.empty()) return f; + /* Only claim tool_calls if every call's arguments actually parse. A truncated arguments + * object reported as a tool call is a tool invoked with the wrong arguments (json_partial.h). */ + for (const auto& tc : last_.tool_calls) + if (tc.name.empty() || !json_complete(tc.arguments)) return f; + return Finish::ToolCalls; +} + +std::string ChatDeltaStream::final_chunk(Finish f) { + /* The generation is over, so whatever the reader was holding is resolved now. A caller that + * already said so gets nothing twice. */ + std::string out = push(std::string_view(), true); + out += chunk(json::object(), finish_reason_oai(adjusted_finish(f))); + return out; +} + +} /* namespace server */ +} /* namespace rad */ diff --git a/core/server/oai.h b/core/server/oai.h new file mode 100644 index 00000000..2cf70071 --- /dev/null +++ b/core/server/oai.h @@ -0,0 +1,265 @@ +/* core/server/oai.h -- the OpenAI schema, in and out. + * + * Two rules shape everything here. + * + * Errors are values. Nothing in this file throws; every entry point returns RAD_OK or a negative + * status and fills an ApiError that already knows its HTTP status, its `param`, and a message + * that names what was wrong. The HTTP layer turns that into a status code and a body. An + * exception crossing the transport is a connection closed with no body, which is the least + * diagnosable thing a client can be handed. + * + * A parameter we do not support is a 400 that names it. Not a silent ignore. A client that sends + * `logit_bias` and gets a 200 has been told its bias was applied, and the resulting bug report + * ("the model ignores my bias") is unanswerable from the server side. The cost of strictness is + * that a client sending a field we have not heard of gets a 400 rather than a shrug; the + * allowlist below is where the genuinely inert OpenAI metadata fields (`user`, `store`, ...) + * are named, so that cost falls only on fields that actually mean something. + */ +#pragma once +#include "iface.h" +#include "rad_core.h" +#include "sink.h" + +#include +#include +#include +#include + +namespace rad { +namespace server { + +/* ================================================================== errors */ + +struct ApiError { + int status = 400; + std::string type = "invalid_request_error"; + std::string message; + std::string param; /* "" when the error is not about one field */ + std::string code; /* "" when there is nothing more specific to say */ + + std::string dump() const; /* the OpenAI error envelope, as a JSON string */ +}; + +ApiError err_bad(const std::string& param, const std::string& why); +ApiError err_unsupported(const std::string& param, const std::string& why); +ApiError err_not_implemented(const std::string& what); + +/* SERIALISE OUT OF LINE. nlohmann's dump() inlines a shared_ptr release that GCC 16 speculatively + * devirtualises onto std::mutex and then reports as an out-of-bounds destroy -- a false positive + * in a vendored header, which appears or not depending on how deeply the CALLING function + * inlined. That makes "is this file warning-clean" a property of how short its handlers are, + * which is not something anybody can act on. One definition, in one translation unit. */ +std::string json_dump(const json& j); +ApiError err_overloaded(const std::string& why); + +/* ================================================================== a parsed request */ + +enum class Endpoint { Chat, Completion, Embedding }; + +struct PromptInput { + std::vector tokens; + std::string text; /* the rendered prompt; needed for `echo` and for the logs */ + /* The media parts, processed and placed; null for a text prompt (Request::media). */ + std::shared_ptr media; +}; + +struct OaiRequest { + Endpoint endpoint = Endpoint::Chat; + std::string model; + std::string id; /* "chatcmpl-..." / "cmpl-..." */ + int64_t created = 0; /* unix seconds */ + + bool stream = false; + bool include_usage = false; /* stream_options.include_usage */ + + int n = 1; + SamplingParams sp; + int32_t max_tokens = 0; + std::vector stop; + /* Generate past end-of-text, to max_tokens. See Request::ignore_eos. */ + bool ignore_eos = false; + int priority = 0; + + std::vector prompts; /* /v1/completions accepts a batch; chat has exactly one */ + bool echo = false; + + int n_logprobs = 0; /* 0 = off */ + bool want_logprobs = false; + + bool tools_present = false; + bool parse_tools = false; + /* The reply parser this request's render produced. Per request and not per server: it is the + * model's format bound to the tools THIS call sent, so two concurrent requests against the + * same model can legitimately need different parsers. */ + std::shared_ptr reply_parser; + + /* The control tokens this request's reply must be decoded AS TEXT, so `tool_parser` can see + * the structure it is looking for. See ITokenizer::detokenizer. */ + std::vector preserved_tokens; + + /* /v1/embeddings */ + bool base64_embeddings = false; + + int n_choices() const { return (int)prompts.size() * n; } +}; + +/* What the server needs to know about itself to validate a request. */ +struct OaiLimits { + std::string model_id = "radiance"; + int64_t max_ctx = 0; /* 0 = unknown, no length check */ + int64_t default_max_tokens = 512; + int max_n = 8; + bool allow_image = false; + bool allow_video = false; + bool allow_audio = false; + bool supports_logprobs = false; + + /* THE DEPLOYMENT'S DEFAULT REASONING EFFORT, empty for "whatever the template's own default + * is". It exists because the template's default is not always a servable one: Qwen3.8's is + * `xhigh`, which on a short task reliably spends the whole token budget inside and + * returns a turn with EMPTY content and finish_reason "length" -- an agent turn that carries + * no answer and no tool call. The per-request field is the right control and most OpenAI + * clients never send it, so without this an operator serving such a client cannot reach the + * dial at all. Seeded only when the request says nothing, so a caller always wins. */ + std::string default_reasoning_effort; + + /* WHAT A REQUEST THAT SENDS NO SAMPLER FIELDS IS SERVED WITH, field by field. + * + * The struct's own defaults are an untruncated sampler -- temperature 1, top_k off, top_p 1 + * -- which is the right thing to fall back to and the wrong thing to serve a checkpoint + * with: a model tuned against a truncated tail, sampled without one, will occasionally draw + * a token from far down its distribution. End-of-turn is one of those tokens, and drawing it + * early ends an agent's turn with prose and no tool call, which reads as the server dropping + * the request. The deployment resolves this from what the checkpoint itself states and hands + * the result over here. + * + * Only the sampler knobs are read: the grammar fields are per request and are filled in + * after this is copied. A request that names a field always wins, exactly as with + * default_reasoning_effort. */ + SamplingParams default_sampling; +}; + +struct OaiDeps { + ITokenizer* tok = nullptr; + IChatTemplate* chat = nullptr; + IGrammarCompiler* grammar = nullptr; + IMultimodal* mm = nullptr; +}; + +/* Parse. `body` is the raw request body; a malformed body is a 400 that says where. */ +int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim, + OaiRequest* out, ApiError* err); +int parse_completion_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim, + OaiRequest* out, ApiError* err); +/* Embeddings: fills `out->prompts` with one entry per input. */ +int parse_embeddings_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim, + OaiRequest* out, ApiError* err); + +/* ================================================================== responses */ + +struct LogprobEntry { + int32_t token = 0; + std::string text; + float logprob = 0.0f; +}; + +struct ChoiceOut { + int index = 0; + std::string text; /* raw generated text */ + ParsedMessage msg; /* chat: content / reasoning / tool_calls after parsing */ + Finish finish = Finish::None; + std::vector logprobs; +}; + +struct UsageOut { + int64_t prompt = 0; + int64_t completion = 0; + int64_t cached = 0; +}; + +std::string chat_completion_body(const OaiRequest& r, const std::vector& choices, + const UsageOut& u); +std::string text_completion_body(const OaiRequest& r, const std::vector& choices, + const UsageOut& u); +std::string embeddings_body(const OaiRequest& r, const std::vector>& vecs, + const UsageOut& u); +std::string models_body(const std::string& model_id, int64_t created); + +/* The usage chunk of each endpoint's stream: an SSE event whose choices array is empty and whose + * only payload is `usage`. Emitted when the request asked for stream_options.include_usage, ONCE + * per stream and after every choice's final chunk -- `n` choices share one prompt and one total, + * so a chunk per choice would count the prompt n times and interleave with the choices. */ +std::string text_usage_chunk(const OaiRequest& r, const UsageOut& u); +std::string chat_usage_chunk(const OaiRequest& r, const UsageOut& u); + +/* ================================================================== streaming + * + * One of these per choice. It feeds the generated text to the choice's reply reader as it grows + * and forwards each increment the reader completes as an SSE chunk. The reader never revises + * what it has delivered, so nothing here diffs, holds back or reconciles: a delta is the next + * piece of the answer, and the chunks a client concatenates are the answer the buffered path + * returns. + */ +class ChatDeltaStream { +public: + ChatDeltaStream(const OaiRequest& r, int index, const IReplyParser* parser); + + /* The `role: assistant` opener OpenAI clients expect before any content. */ + std::string first_chunk(); + + /* Feed the text generated since the last push; returns zero or more SSE `data:` lines. + * `is_final` says the generation is over, which resolves whatever the reader was holding. */ + std::string push(std::string_view appended, bool is_final); + + /* The terminating chunk carrying finish_reason. The usage chunk is the stream's, not the + * choice's: chat_usage_chunk. */ + std::string final_chunk(Finish f); + + /* What the whole generation parsed to -- the non-streaming shape. Complete once push has + * been called with is_final. */ + const ParsedMessage& parsed() const { return last_; } + Finish adjusted_finish(Finish f) const; + +private: + std::string chunk(json delta, const char* finish_reason); + std::string emit(const std::vector& ev); + + std::unique_ptr reader_; + std::string id_, model_; + int64_t created_; + int index_; + bool finished_ = false; + + ParsedMessage last_; + std::vector ev_; +}; + +/* The SSE terminator. Written once at the end of every stream, including a failed one, because a + * client blocked on the reader has no other way to learn the stream is over. */ +extern const char* const SSE_DONE; + +std::string sse_event(const std::string& json_text); +std::string sse_error(const ApiError& e); + +/* ================================================================== small shared helpers */ + +std::string base64_encode(const void* data, size_t len); +bool base64_decode(const std::string& in, std::vector* out); +/* A token id as a request spells it: an integer in [0, INT32_MAX]. False for anything else, and + * the caller refuses the request -- narrowing instead would make 2^32 + 5 an alias of token 5. */ +bool token_id(const json& v, int32_t* out); + +/* Parse a request body into a tree of at most json_value_budget(max_ctx) values, nested at most + * kJsonMaxDepth deep. A syntax error comes back discarded, as json::parse's would; a body with + * more values than the budget sets `*over`, and one nested deeper than the bound sets `*deep`, + * and either comes back holding only what fitted, which the caller refuses. See the definition + * for why the tree is bounded rather than the body alone. */ +json parse_json_bounded(const std::string& body, int64_t max_ctx, bool* over, bool* deep); +int64_t json_value_budget(int64_t max_ctx); +constexpr int kJsonMaxDepth = 1024; + +std::string random_id(const char* prefix); +int64_t unix_now(); + +} /* namespace server */ +} /* namespace rad */ diff --git a/core/server/server.cpp b/core/server/server.cpp new file mode 100644 index 00000000..8468093a --- /dev/null +++ b/core/server/server.cpp @@ -0,0 +1,806 @@ +#include "server.h" +#include "json_partial.h" +#include "rad_internal.h" + +#include + +#include +#include +#include + +namespace rad { +namespace server { + +/* ------------------------------------------------------------------ per-choice state */ + +struct Server::Generation { + std::shared_ptr sink; + std::unique_ptr detok; + std::unique_ptr delta; /* chat streaming only */ + uint64_t id = 0; + int index = 0; + int prompt_index = 0; + std::string text; + std::vector logprobs; + Finish finish = Finish::None; + bool closed = false; /* the server has decided this choice is over */ + size_t scanned = 0; /* how far the stop-string scan has reached */ + size_t stop_cut = std::string::npos; + size_t emitted = 0; /* streaming: text already handed to the delta stream */ + bool retired = false; /* reap() has been said for this id, at most once */ +}; + +struct Server::StreamState { + OaiRequest r; + std::vector gens; + std::function peer_closed; + bool opened = false; + bool done_sent = false; + bool released = false; +}; + +/* ------------------------------------------------------------------ construction */ + +Server::Server(const Deps& d, const ServerOptions& o) + : deps_(d), opt_(o), + metrics_(o.model_id, o.max_ctx > 0 ? o.max_ctx : 32768) { + lim_.model_id = opt_.model_id; + lim_.max_ctx = opt_.max_ctx; + lim_.default_max_tokens = opt_.default_max_tokens; + lim_.max_n = opt_.max_n; + lim_.allow_image = opt_.allow_image; + lim_.allow_video = opt_.allow_video; + lim_.allow_audio = opt_.allow_audio; + lim_.supports_logprobs = opt_.supports_logprobs; + lim_.default_reasoning_effort = opt_.default_reasoning_effort; + lim_.default_sampling = opt_.default_sampling; + + odeps_.tok = deps_.tok; + odeps_.chat = deps_.chat; + odeps_.grammar = deps_.grammar; + odeps_.mm = deps_.mm; + + queue_depth_ = opt_.queue_depth > 0 ? opt_.queue_depth : opt_.max_seqs * 8; + started_at_ = unix_now(); + register_routes(); +} + +Server::~Server() { stop(); } + +/* Sinks the engine may still be writing into must not be freed. `Request::sink` is a raw pointer + * the scheduler holds for the life of the request, so the only safe moment to release one is + * after the scheduler has reported it terminal. At shutdown we wait a bounded time for that and, + * if it never comes, we leak the remainder on purpose and say so. + * + * A deliberate leak of a few KiB at process exit is the cheap failure. Freeing under a running + * step is the expensive one: it corrupts whatever the allocator hands out next, and it surfaces + * as garbage in an unrelated request several steps later, which is precisely the class of bug + * spec §17 exists to keep out of this engine. */ +void Server::drain_graveyard(int timeout_ms) { + const int slice = 5; + for (int waited = 0; waited <= timeout_ms; waited += slice) { + sweep_abandoned(); + { + std::lock_guard lk(grave_m_); + if (grave_.empty()) return; + } + std::this_thread::sleep_for(std::chrono::milliseconds(slice)); + } + std::lock_guard lk(grave_m_); + if (grave_.empty()) return; + RAD_ERR("server: %zu cancelled requests are still held by the scheduler after %d ms. " + "Stop the scheduler before destroying the server. Leaking their sinks rather than " + "freeing memory a running step may still write to.", + grave_.size(), timeout_ms); + /* Hand the remainder to storage that outlives the process's teardown of this object. */ + static std::vector>>* leaked = + new std::vector>>(); + leaked->push_back(std::move(grave_)); + grave_.clear(); +} + +/* WHAT IS SERVED. One table, and /server_info answers with it rather than with a copy -- a list + * kept beside this one is a list that goes stale on the next route added. + * + * Method spellings follow vLLM's, including the ones that look wrong: /tokenize and /detokenize + * are POST because their input is a body, /reset_prefix_cache is POST because it changes state, + * and /ping answers both GET and POST because different load balancers send different ones and + * neither is worth a 405 on a health probe. */ +void Server::register_routes() { + router_.post("/v1/chat/completions", [this](const HttpRequest& q) { return handle_chat(q); }); + router_.post("/v1/completions", [this](const HttpRequest& q) { return handle_completion(q); }); + router_.post("/v1/embeddings", [this](const HttpRequest& q) { return handle_embeddings(q); }); + router_.get ("/v1/models", [this](const HttpRequest& q) { return handle_models(q); }); + router_.get ("/v1/models/:id", [this](const HttpRequest& q) { return handle_models(q); }); + + router_.get ("/metrics", [this](const HttpRequest& q) { return handle_metrics(q); }); + router_.get ("/health", [this](const HttpRequest& q) { return handle_health(q); }); + router_.get ("/ping", [this](const HttpRequest& q) { return handle_ping(q); }); + router_.post("/ping", [this](const HttpRequest& q) { return handle_ping(q); }); + router_.get ("/load", [this](const HttpRequest& q) { return handle_load(q); }); + router_.get ("/version", [this](const HttpRequest& q) { return handle_version(q); }); + router_.get ("/server_info", [this](const HttpRequest& q) { return handle_server_info(q); }); + + router_.post("/tokenize", [this](const HttpRequest& q) { return handle_tokenize(q); }); + router_.post("/detokenize", [this](const HttpRequest& q) { return handle_detokenize(q); }); + router_.get ("/get_tokenizer_info", [this](const HttpRequest& q) { return handle_tokenizer_info(q); }); + + router_.post("/reset_prefix_cache", [this](const HttpRequest& q) { return handle_reset_prefix_cache(q); }); + + /* The dashboard. `/` rather than only `/dashboard` because a person who has the host and port + * of a running engine types exactly that, and answering it with a 404 is answering the + * question "is this thing alive" with "no". */ + router_.get ("/", [this](const HttpRequest& q) { return handle_dashboard(q); }); + router_.get ("/dashboard", [this](const HttpRequest& q) { return handle_dashboard(q); }); + router_.get ("/stats", [this](const HttpRequest& q) { return handle_stats(q); }); + router_.get ("/graph", [this](const HttpRequest& q) { return handle_graph(q); }); + router_.get ("/sessions", [this](const HttpRequest& q) { return handle_sessions(q); }); +} + +/* WORKERS FOR EVERYTHING ADMISSION CAN LET IN, AND A RESERVE BESIDE THEM. + * + * A generation holds its connection's worker for as long as it runs -- a stream writes from it, a + * blocking request waits on its sink in it -- so a pool no larger than the admission ceiling runs + * out of workers before admission refuses anyone. The 429 can then never happen, and every + * connection after that waits in the pool's queue behind generations that may run for minutes, + * /health included. So the pool may grow to the ceiling plus a reserve no admitted generation can + * occupy: that is what keeps a probe, the dashboard, a request about to be told 429 and a + * client's idle keep-alive connections answerable while every admitted request is running. The + * same number bounds the connections that may wait once even the reserve is busy. */ +static const int64_t kSpareWorkers = 64; + +int Server::run() { + TransportOptions t; + t.host = opt_.host; + t.port = opt_.port; + t.n_threads = opt_.n_threads; + t.max_threads = queue_depth_ + kSpareWorkers; + t.max_queued = kSpareWorkers; + t.api_key = opt_.api_key; + t.cors = opt_.cors; + return transport_.serve(router_, t); +} + +void Server::stop() { + stopping_.store(true); + transport_.stop(); + drain_graveyard(2000); +} + +/* ------------------------------------------------------------------ admission */ + +bool Server::admit(int64_t n) { + int64_t cur = in_flight_.fetch_add(n, std::memory_order_acq_rel) + n; + if (cur > queue_depth_) { + in_flight_.fetch_sub(n, std::memory_order_acq_rel); + return false; + } + metrics_.set_queue_depth(cur); + return true; +} + +void Server::release(int64_t n) { + int64_t cur = in_flight_.fetch_sub(n, std::memory_order_acq_rel) - n; + metrics_.set_queue_depth(cur); +} + +void Server::sweep_abandoned() { + std::lock_guard lk(grave_m_); + size_t before = grave_.size(); + grave_.erase(std::remove_if(grave_.begin(), grave_.end(), + [this](const std::shared_ptr& s) { + if (!s->done()) return false; + deps_.sched->reap(s->id); + return true; + }), + grave_.end()); + if (grave_.size() > 256 && grave_.size() >= before) + RAD_WARN("server: %zu cancelled requests the scheduler has not reported terminal; " + "IScheduler::cancel must finish them, not just unschedule them", + grave_.size()); +} + +/* ------------------------------------------------------------------ errors */ + +HttpResponse Server::error_response(const ApiError& e) { + metrics_.observe_http(e.status); + HttpResponse r = HttpResponse::json_body(e.status, e.dump()); + if (e.status == 429) r.set_header("Retry-After", std::to_string(opt_.retry_after_s)); + return r; +} + +/* ------------------------------------------------------------------ submission */ + +int Server::submit_all(const OaiRequest& r, std::vector* gens, ApiError* err) { + const int n_choices = r.n_choices(); + gens->reserve((size_t)n_choices); + + /* THE SAMPLER GETS A SAY BEFORE ANYTHING IS QUEUED. A stage that did not resolve is not a + * declare failure -- it becomes one when a request asks for it. Refusing here makes that a + * 400 naming the parameter, instead of an admitted request that the step loop cancels three + * steps in with a dead stream at the client. + * + * Once, not per choice: `n` varies only the seed, and no check here reads it. */ + { + std::string why; + if (deps_.sched->admit(r.sp, &why) < 0) { + *err = err_unsupported("sampling", why.empty() + ? "these sampling parameters cannot be served" : why); + return RAD_E_INVAL; + } + } + + int idx = 0; + std::vector rqs; + rqs.reserve(r.prompts.size() * (size_t)r.n); + const size_t first = gens->size(); + for (size_t p = 0; p < r.prompts.size(); ++p) { + for (int k = 0; k < r.n; ++k, ++idx) { + Generation g; + g.index = idx; + g.prompt_index = (int)p; + g.sink = std::make_shared(); + g.sink->set_has_logprobs(opt_.supports_logprobs); + g.detok = deps_.tok->detokenizer(r.stop, r.preserved_tokens); + if (!g.detok) { + *err = err_not_implemented("the tokenizer did not supply an incremental decoder"); + return RAD_E_UNSUPPORTED; + } + + Request rq; + rq.prompt = r.prompts[p].tokens; + rq.sp = r.sp; + /* n identical seeds would give n identical completions, which is not what `n` means. + * Offsetting is enough: the sampler's stream is seeded, not chained. */ + rq.sp.seed = r.sp.seed + (uint64_t)k; + rq.max_tokens = r.max_tokens; + rq.stop = r.stop; + rq.ignore_eos = r.ignore_eos; + rq.priority = r.priority; + rq.stream = r.stream; + rq.media = r.prompts[p].media; + rq.sink = g.sink.get(); + rqs.push_back(std::move(rq)); + gens->push_back(std::move(g)); + } + } + std::vector ids; + deps_.sched->submit_all(rqs, &ids); + for (size_t i = 0; i < ids.size(); ++i) { + Generation& g = (*gens)[first + i]; + g.id = ids[i]; + g.sink->id = g.id; + } + return RAD_OK; +} + +void Server::cancel_all(std::vector& gens, bool count_disconnect) { + for (auto& g : gens) { + if (g.sink->done()) continue; + g.sink->request_cancel(); + deps_.sched->cancel(g.id); + } + if (count_disconnect) metrics_.observe_disconnect(); +} + +/* Every exit from a request goes through here exactly once. A generation the engine has finished + * is reaped -- that is the server telling the scheduler it may drop the Request, which it cannot + * know on its own because we are the ones holding the sink. One the engine has not finished moves + * to the graveyard, and is reaped by the sweep when it does. */ +void Server::retire(std::vector& gens) { + std::vector> pending; + for (auto& g : gens) { + if (g.retired) continue; + g.retired = true; + if (g.sink->done()) deps_.sched->reap(g.id); + else pending.push_back(g.sink); + } + if (pending.empty()) return; + std::lock_guard lk(grave_m_); + for (auto& s : pending) grave_.push_back(std::move(s)); +} + +/* ------------------------------------------------------------------ draining */ + +bool Server::all_done(const std::vector& gens) const { + for (const auto& g : gens) if (!g.closed) return false; + return true; +} + +bool Server::pump(std::vector& gens, const OaiRequest& r) { + bool progress = false; + SinkToken buf[128]; + + size_t maxstop = 0; + for (const auto& s : r.stop) maxstop = std::max(maxstop, s.size()); + + for (auto& g : gens) { + if (g.closed) continue; + + size_t n; + while ((n = g.sink->read(buf, 128)) > 0) { + progress = true; + for (size_t i = 0; i < n; ++i) { + std::string piece = g.detok->push(buf[i].token); + if (!piece.empty()) g.text += piece; + if (r.want_logprobs) + g.logprobs.push_back(LogprobEntry{buf[i].token, piece, buf[i].logprob}); + } + } + + /* The decoder may have swallowed the stop string itself, in which case our own scan below + * can never find it -- it is searching text the stop string was already removed from. */ + if (maxstop && !g.closed && g.stop_cut == std::string::npos && g.detok->stopped()) { + g.stop_cut = g.text.size(); + g.finish = Finish::StopString; + g.closed = true; + progress = true; + g.sink->request_cancel(); + deps_.sched->cancel(g.id); + continue; + } + + /* Stop strings. The scheduler is given Request::stop and may stop first, but a stop + * string straddles token boundaries and only the detokenised text can be searched, so the + * authoritative cut is made here. Scanning restarts (maxstop-1) bytes behind the previous + * end so a match spanning two drains is still found. */ + if (maxstop && g.stop_cut == std::string::npos && !g.text.empty()) { + size_t start = g.scanned >= maxstop ? g.scanned - maxstop + 1 : 0; + for (const auto& s : r.stop) { + if (s.empty()) continue; + size_t at = g.text.find(s, start); + if (at != std::string::npos && (g.stop_cut == std::string::npos || at < g.stop_cut)) + g.stop_cut = at; + } + g.scanned = g.text.size(); + if (g.stop_cut != std::string::npos) { + g.text.resize(g.stop_cut); + g.finish = Finish::StopString; + g.closed = true; + progress = true; + /* The client will never see another token of this choice, so the blocks it holds + * are dead weight the moment we decide that (spec §14). */ + g.sink->request_cancel(); + deps_.sched->cancel(g.id); + continue; + } + } + + if (g.sink->done()) { + std::string tail = g.detok->flush(); + if (!tail.empty()) { g.text += tail; progress = true; } + g.finish = g.sink->finish_reason(); + if (g.sink->overflowed()) metrics_.observe_overflow(); + g.closed = true; + progress = true; + } + } + return progress; +} + +/* ------------------------------------------------------------------ metrics bookkeeping */ + +static SuccessReason to_reason(Finish f) { + switch (f) { + case Finish::Length: return SuccessReason::Length; + case Finish::ToolCalls: return SuccessReason::ToolCalls; + case Finish::Cancelled: return SuccessReason::Abort; + case Finish::Error: return SuccessReason::Error; + default: return SuccessReason::Stop; + } +} + +void Server::record(const OaiRequest& r, const std::vector& gens, Finish overall) { + int64_t n_prompt = 0; + for (const auto& p : r.prompts) n_prompt += (int64_t)p.tokens.size(); + + int64_t n_gen = 0; + double ttft = -1.0, tpot = -1.0, decode = -1.0, e2e = 0.0; + for (const auto& g : gens) { + int64_t produced = g.sink->n_produced(); + n_gen += produced; + e2e = std::max(e2e, (double)g.sink->age_ns() * 1e-9); + int64_t tf = g.sink->t_first_token_ns(), tl = g.sink->t_last_token_ns(); + if (tf >= 0) { + double t = (double)tf * 1e-9; + ttft = ttft < 0 ? t : std::min(ttft, t); + if (produced > 1 && tl > tf) { + double d = (double)(tl - tf) * 1e-9; + decode = decode < 0 ? d : std::max(decode, d); + double per = d / (double)(produced - 1); + tpot = tpot < 0 ? per : std::max(tpot, per); + } + } + } + metrics_.observe_request(n_prompt, n_gen, ttft, tpot, e2e, decode, + r.n, r.max_tokens, to_reason(overall)); +} + +/* ------------------------------------------------------------------ non-streaming */ + +HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r) { + std::vector gens; + ApiError err; + if (submit_all(r, &gens, &err) < 0) { + retire(gens); + release(r.n_choices()); + return error_response(err); + } + + for (;;) { + pump(gens, r); + if (all_done(gens)) break; + + /* A client that hangs up before the answer is ready is a cancellation, not something to + * finish computing for nobody. */ + if (req.peer_gone()) { + cancel_all(gens, true); + retire(gens); + release(r.n_choices()); + metrics_.observe_http(499); + HttpResponse res = HttpResponse::text(499, "client closed request\n"); + return res; + } + if (stopping_.load()) { + cancel_all(gens, false); + retire(gens); + release(r.n_choices()); + return error_response(err_overloaded("the server is shutting down")); + } + /* Wait on whichever choice is still running. Bounded, so the peer check above runs. */ + for (auto& g : gens) if (!g.closed) { g.sink->wait(); break; } + } + + Finish overall = Finish::Stop; + UsageOut usage; + for (const auto& p : r.prompts) usage.prompt += (int64_t)p.tokens.size(); + std::vector choices; + choices.reserve(gens.size()); + + for (auto& g : gens) { + usage.completion += g.sink->n_produced(); + if (g.prompt_index * r.n == g.index) usage.cached += g.sink->n_cached(); + + ChoiceOut c; + c.index = g.index; + c.finish = g.finish; + c.logprobs = std::move(g.logprobs); + + if (r.endpoint == Endpoint::Chat) { + /* Parse whenever there is a parser, not only when tools were sent: the same parser + * separates the reasoning block from the answer, and a request with no tools still + * wants `reasoning_content` split out rather than glued to the front of the reply. + * It is the same reader the streaming path feeds a piece at a time, fed the whole + * reply at once, so the two agree by construction. With no tools in the request the + * parser reads no calls and the tool bookkeeping below finds none. */ + if (r.reply_parser) { + std::unique_ptr rd = r.reply_parser->open(); + rd->feed(g.text, nullptr); + rd->finish(nullptr); + c.msg = rd->message(); + /* Only claim a tool call when the arguments actually parse (json_partial.h). */ + bool complete = r.parse_tools && !c.msg.tool_calls.empty(); + for (const auto& tc : c.msg.tool_calls) + if (tc.name.empty() || !json_complete(tc.arguments)) complete = false; + if (complete && (c.finish == Finish::Stop || c.finish == Finish::StopString)) + c.finish = Finish::ToolCalls; + else if (!c.msg.tool_calls.empty() && !complete) { + /* A half-finished call is content, not a call. The client gets what the model + * actually produced instead of a tool invocation with truncated arguments. */ + c.msg.tool_calls.clear(); + c.msg.content = g.text; + } + } else { + c.msg.content = g.text; + } + for (auto& tc : c.msg.tool_calls) if (tc.id.empty()) tc.id = random_id("call_"); + } else { + c.text = r.echo ? r.prompts[g.prompt_index].text + g.text : g.text; + } + if (c.finish == Finish::Error || c.finish == Finish::Cancelled) overall = c.finish; + choices.push_back(std::move(c)); + } + + /* An engine-side failure is not a 200 with an empty answer. */ + for (auto& g : gens) { + if (g.finish == Finish::Error) { + int st = g.sink->status(); + retire(gens); + release(r.n_choices()); + record(r, gens, Finish::Error); + ApiError e; + e.status = 500; + e.type = "internal_server_error"; + e.message = std::string("the engine failed this request: ") + rad_strerror(st); + return error_response(e); + } + } + + record(r, gens, overall); + retire(gens); + release(r.n_choices()); + + std::string body = r.endpoint == Endpoint::Chat + ? chat_completion_body(r, choices, usage) + : text_completion_body(r, choices, usage); + metrics_.observe_http(200); + return HttpResponse::json_body(200, std::move(body)); +} + +/* ------------------------------------------------------------------ streaming */ + +static std::string text_chunk(const OaiRequest& r, int index, const std::string& delta, + const char* finish_reason) { + nlohmann::ordered_json ch; + ch["text"] = delta; + ch["index"] = index; + ch["logprobs"] = nullptr; + if (finish_reason) ch["finish_reason"] = finish_reason; else ch["finish_reason"] = nullptr; + nlohmann::ordered_json o; + o["id"] = r.id; + o["object"] = "text_completion"; + o["created"] = r.created; + o["model"] = r.model; + o["choices"] = nlohmann::ordered_json::array({ch}); + return sse_event(o.dump()); +} + +HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r) { + auto st = std::make_shared(); + st->r = r; + st->peer_closed = req.closed; + + ApiError err; + if (submit_all(st->r, &st->gens, &err) < 0) { + retire(st->gens); + release(r.n_choices()); + return error_response(err); + } + if (st->r.endpoint == Endpoint::Chat) + for (auto& g : st->gens) + g.delta.reset(new ChatDeltaStream(st->r, g.index, st->r.reply_parser.get())); + + HttpResponse res; + res.status = 200; + res.content_type = "text/event-stream; charset=utf-8"; + res.set_header("Cache-Control", "no-cache"); + res.set_header("Connection", "keep-alive"); + /* nginx buffers proxied responses by default, which turns a token stream into one large + * delivery at the end. This header is the documented opt-out and costs nothing elsewhere. */ + res.set_header("X-Accel-Buffering", "no"); + + Server* self = this; + + res.next = [self, st](std::string& out) -> bool { + out.clear(); + if (st->done_sent) return false; + + if (!st->opened) { + st->opened = true; + if (st->r.endpoint == Endpoint::Chat) { + for (auto& g : st->gens) out += g.delta->first_chunk(); + } else if (st->r.echo) { + /* `echo`, ON THE STREAMING PATH. The buffered path applies it by prepending the + * prompt to the choice's text; this is the equivalent, and without it the same + * request would answer differently depending on `stream`. + * + * The prompt goes out as the first content chunk, before any token, which is what + * "echo" means and what a client reassembling the deltas needs: concatenating the + * stream gives the same string the buffered response returns. + * Empty prompts emit nothing rather than an empty chunk. */ + for (auto& g : st->gens) { + const std::string& p = st->r.prompts[(size_t)g.prompt_index].text; + if (!p.empty()) out += text_chunk(st->r, g.index, p, nullptr); + } + } + return true; + } + + if (st->peer_closed && st->peer_closed()) { + return false; + } + + const bool progress = self->pump(st->gens, st->r); + size_t maxstop = 0; + for (const auto& s : st->r.stop) maxstop = std::max(maxstop, s.size()); + + for (auto& g : st->gens) { + /* Hold back the longest stop string minus one byte while the choice is still running: + * otherwise the first half of a stop sequence is already on the wire by the time we + * recognise it, and it cannot be taken back. + * + * ONLY WHILE IT IS RUNNING. Every hold-back rule here waits for bytes that may still + * arrive, and a closed choice has none coming, so its whole text is the answer. That + * includes a tail the escape rule would keep -- a trailing `\` or a partial `\uXXXX` + * is ordinary text in a completion, and holding it back at the end drops it. */ + size_t safe = g.text.size(); + if (!g.closed) { + if (maxstop > 1) safe = safe > maxstop - 1 ? safe - (maxstop - 1) : 0; + safe = json_stable_prefix(std::string_view(g.text.data(), safe)); + if (safe <= g.emitted) continue; + } + + if (st->r.endpoint == Endpoint::Chat) { + /* Only what is new: the reader keeps its own place in the reply, which is what + * makes a long reply cost its length rather than its length squared. */ + out += g.delta->push(std::string_view(g.text).substr(g.emitted, safe - g.emitted), + g.closed); + } else if (safe > g.emitted) { + out += text_chunk(st->r, g.index, g.text.substr(g.emitted, safe - g.emitted), + nullptr); + } + g.emitted = safe; + } + + if (self->all_done(st->gens)) { + UsageOut u; + for (const auto& p : st->r.prompts) u.prompt += (int64_t)p.tokens.size(); + for (auto& g : st->gens) { + u.completion += g.sink->n_produced(); + if (g.prompt_index * st->r.n == g.index) u.cached += g.sink->n_cached(); + } + Finish overall = Finish::Stop; + for (auto& g : st->gens) { + if (st->r.endpoint == Endpoint::Chat) { + out += g.delta->final_chunk(g.finish); + Finish adj = g.delta->adjusted_finish(g.finish); + if (adj == Finish::Error || adj == Finish::Cancelled) overall = adj; + else if (adj == Finish::ToolCalls) overall = adj; + } else { + out += text_chunk(st->r, g.index, "", finish_reason_oai(g.finish)); + if (g.finish == Finish::Error) overall = Finish::Error; + } + /* A failed generation cannot become a non-200 -- the headers left long ago -- so + * it travels as an error event before [DONE]. Silence would look like a normal + * end of stream and the client would use a truncated answer. */ + if (g.finish == Finish::Error) { + ApiError e; + e.status = 500; + e.type = "internal_server_error"; + e.message = std::string("the engine failed this request: ") + + rad_strerror(g.sink->status()); + out += sse_error(e); + } + } + /* THE USAGE CHUNK. `stream_options.include_usage` is parsed and validated on both + * endpoints, so both have to honour it -- accepting a field and then ignoring it is + * the outcome oai.h's header forbids. + * + * After the per-generation final chunks and before [DONE], which is where OpenAI puts + * it, and once for the request rather than once per choice: `n` completions share one + * prompt and one total, so emitting it per generation would count the prompt n times + * and interleave usage between the choices' final chunks. */ + if (st->r.include_usage) + out += st->r.endpoint == Endpoint::Chat ? chat_usage_chunk(st->r, u) + : text_usage_chunk(st->r, u); + + out += SSE_DONE; + st->done_sent = true; + self->record(st->r, st->gens, overall); + self->retire(st->gens); + self->metrics_.observe_http(200); + if (!st->released) { st->released = true; self->release(st->r.n_choices()); } + return false; + } + + if (!progress && out.empty()) { + /* Nothing to send: sleep on the first live sink rather than spinning. The bounded + * wait is what makes the peer-closed check above run a few times a second. */ + for (auto& g : st->gens) if (!g.closed) { g.sink->wait(); break; } + } + return true; + }; + + res.on_close = [self, st](bool ok) { + if (!st->done_sent) { + /* Either the peer went away or the write failed. Both are cancellations, and the + * blocks have to go back now rather than when the generation would have ended. */ + self->cancel_all(st->gens, true); + self->record(st->r, st->gens, Finish::Cancelled); + self->retire(st->gens); + RAD_DEBUG("server: stream %s abandoned by the client (write %s)", + st->r.id.c_str(), ok ? "ok" : "failed"); + } + if (!st->released) { st->released = true; self->release(st->r.n_choices()); } + }; + + return res; +} + +/* ------------------------------------------------------------------ endpoints */ + +HttpResponse Server::handle_chat(const HttpRequest& req) { + if (!deps_.sched || !deps_.tok) + return error_response(err_not_implemented("the server has no engine attached")); + + OaiRequest r; + ApiError err; + if (parse_chat_request(req.body, odeps_, lim_, &r, &err) < 0) return error_response(err); + + sweep_abandoned(); + if (!admit(r.n_choices())) { + metrics_.observe_rejected(); + return error_response(err_overloaded( + "the admission queue is full; retry after " + std::to_string(opt_.retry_after_s) + + "s. The server refuses rather than queueing without bound")); + } + return r.stream ? streaming_completion(req, r) : blocking_completion(req, r); +} + +HttpResponse Server::handle_completion(const HttpRequest& req) { + if (!deps_.sched || !deps_.tok) + return error_response(err_not_implemented("the server has no engine attached")); + + OaiRequest r; + ApiError err; + if (parse_completion_request(req.body, odeps_, lim_, &r, &err) < 0) return error_response(err); + + sweep_abandoned(); + if (!admit(r.n_choices())) { + metrics_.observe_rejected(); + return error_response(err_overloaded( + "the admission queue is full; retry after " + std::to_string(opt_.retry_after_s) + + "s. The server refuses rather than queueing without bound")); + } + return r.stream ? streaming_completion(req, r) : blocking_completion(req, r); +} + +HttpResponse Server::handle_embeddings(const HttpRequest& req) { + if (!deps_.tok) + return error_response(err_not_implemented("the server has no tokenizer attached")); + if (!deps_.embed) + return error_response(err_not_implemented( + "/v1/embeddings requires an embedding head; this model was not loaded with one")); + + OaiRequest r; + ApiError err; + if (parse_embeddings_request(req.body, odeps_, lim_, &r, &err) < 0) return error_response(err); + + std::vector> vecs; + UsageOut u; + vecs.reserve(r.prompts.size()); + for (const auto& p : r.prompts) { + std::vector v; + int s = deps_.embed->embed(p.tokens, v); + if (s < 0) { + ApiError e; + e.status = 500; + e.type = "internal_server_error"; + e.message = std::string("the embedding pass failed: ") + rad_strerror(s); + return error_response(e); + } + u.prompt += (int64_t)p.tokens.size(); + vecs.push_back(std::move(v)); + } + metrics_.observe_http(200); + return HttpResponse::json_body(200, embeddings_body(r, vecs, u)); +} + +HttpResponse Server::handle_models(const HttpRequest& req) { + const std::string id = req.param("id"); + if (!id.empty() && id != opt_.model_id) { + ApiError e; + e.status = 404; + e.type = "not_found_error"; + e.param = "model"; + e.message = "no such model: " + id; + return error_response(e); + } + metrics_.observe_http(200); + return HttpResponse::json_body(200, models_body(opt_.model_id, started_at_)); +} + +HttpResponse Server::handle_metrics(const HttpRequest&) { + if (deps_.sched) metrics_.sample(deps_.sched->metrics()); + metrics_.set_queue_depth(in_flight_.load(std::memory_order_relaxed)); + HttpResponse r; + r.status = 200; + /* The exposition format version is part of the content type; Prometheus uses it to decide how + * to parse, and omitting it makes some scrapers fall back to OpenMetrics and fail. */ + r.content_type = "text/plain; version=0.0.4; charset=utf-8"; + r.body = metrics_.render(); + return r; +} + +} /* namespace server */ +} /* namespace rad */ diff --git a/core/server/server.h b/core/server/server.h new file mode 100644 index 00000000..03e45c32 --- /dev/null +++ b/core/server/server.h @@ -0,0 +1,204 @@ +/* core/server/server.h -- the OpenAI-compatible server (spec §14). + * + * Threading, in the spec's terms (§1): HTTP threads feed a request queue, one scheduler thread + * produces one step. This object owns the HTTP thread pool and the admission queue; it does not + * own the step loop and never calls into it. Output comes back per request through a Sink the + * scheduler pushes into (sink.h), which `Request::sink` points at. + * + * Backpressure is admission control, not buffering. A full queue is a 429 with Retry-After. The + * alternative -- accepting everything and letting the waiting list grow -- turns a load spike + * into an out-of-memory kill twenty minutes later, at which point every in-flight request dies + * rather than the marginal ones being refused up front. + * + * Cancellation is not an edge case. An agent client that abandons a long generation is the normal + * case, so a dropped connection is detected on the streaming path (a failed write, or a closed + * socket seen while waiting) and turned into IScheduler::cancel, which frees the request's KV + * blocks immediately rather than at completion. + */ +#pragma once +#include +#include "http.h" +#include "iface.h" +#include "liveview.h" +#include "metrics.h" +#include "oai.h" +#include "sink.h" + +#include +#include +#include +#include +#include + +namespace rad { +namespace server { + +struct Deps { + IScheduler* sched = nullptr; /* required */ + ITokenizer* tok = nullptr; /* required */ + IChatTemplate* chat = nullptr; /* absent -> /v1/chat/completions is 501 */ + IGrammarCompiler* grammar = nullptr; /* absent -> response_format is 501 */ + IEmbedder* embed = nullptr; /* absent -> /v1/embeddings is 501 */ + IMultimodal* mm = nullptr; /* absent -> image and audio parts are 501 */ + + /* WHAT ONLY THE ENGINE CAN SEE: per-card VRAM, the expert plane. The server holds interfaces + * and no device handle, so this dependency is a function rather than an object -- there is + * nothing to name it after. Absent, the dashboard shows the scheduler's half and omits the + * cards rather than drawing zeroes. + * + * The SAME function the live view is built with (liveview.h), so the terminal view and the + * web page cannot drift into disagreeing about what the engine is doing. */ + LiveView::Source live; +}; + +struct ServerOptions { + std::string model_id = "radiance"; + std::string host = "0.0.0.0"; + int port = 8000; + int n_threads = 0; + + /* How many requests may be admitted and unfinished at once. Beyond this the answer is 429. + * Defaults to 8x max_seqs: enough that the scheduler always has a full batch to choose from + * and a queue to prefill out of, and small enough that the memory held by waiting requests is + * bounded by a number the operator picked. */ + int64_t queue_depth = 0; + int64_t max_seqs = 256; + int retry_after_s = 1; + + int64_t max_ctx = 0; + int64_t default_max_tokens = 512; + int max_n = 8; + + bool supports_logprobs = false; + /* The deployment default for `reasoning_effort`, empty for the template's own. See + * OaiLimits::default_reasoning_effort for why a server-side default is needed at all. */ + std::string default_reasoning_effort; + /* What a request that sends no sampler fields is served with. See + * OaiLimits::default_sampling; only the sampler knobs are read from it. */ + SamplingParams default_sampling; + bool allow_image = false; + bool allow_video = false; + bool allow_audio = false; + + /* WHAT /server_info AND /version REPORT ABOUT THE ENGINE BEHIND THIS SERVER. + * + * `engine_info` is a JSON OBJECT as text, spliced in verbatim under "engine". The server + * cannot derive any of it -- it deliberately knows nothing about the device layer, the + * container or the placement plan -- and a struct with a field per fact would be a struct + * this component has to grow every time the engine learns something new about itself. */ + std::string version = RAD_VERSION; + std::string engine_info; + /* The declared compute graph, as JSON, for the Model view. A PROVIDER, called per request, + * rather than a string rendered once after declare. + * + * The declaration itself does not change while the server runs, but the dump also carries what + * the run phase has DONE with it -- `OpInfo::issued` -- and a snapshot taken before the first + * step reports every op in the model as never issued, permanently, which makes /graph useless + * for finding a dead declaration. + * + * Regenerating reads the Program from the HTTP thread while the step path writes that one + * field. It is a monotonic false -> true bool, so the worst case is a graph fetched mid-step + * showing an op as unissued one step before it flips. Registry::select is asked with + * record = false and mutates nothing else. */ + std::function graph_json; + + std::string api_key; + bool cors = true; +}; + +class Server { +public: + Server(const Deps& d, const ServerOptions& o); + /* Lifetime rule, and it is load-bearing: stop the scheduler before destroying the Server. + * `Request::sink` is a raw pointer into storage this object owns, and a request the scheduler + * has not finished is a request still writing into it. The destructor waits a bounded time + * for anything it cancelled and then deliberately leaks the rest rather than free memory a + * running step may touch. */ + ~Server(); + + /* Every endpoint, registered. Tests drive this directly -- same handlers, no socket. */ + const Router& router() const { return router_; } + + int run(); /* binds, serves, blocks. RAD_OK or negative. */ + void stop(); + int port() const { return transport_.port(); } /* 0 until run() is accepting */ + + int64_t in_flight() const { return in_flight_.load(std::memory_order_relaxed); } + +private: + struct Generation; + struct StreamState; + + void register_routes(); + + HttpResponse handle_chat(const HttpRequest& req); + HttpResponse handle_completion(const HttpRequest& req); + HttpResponse handle_embeddings(const HttpRequest& req); + HttpResponse handle_models(const HttpRequest& req); + HttpResponse handle_metrics(const HttpRequest& req); + + /* ------------------------------------------------------------------ admin.cpp + * vLLM's non-generation surface. Separate because none of it touches the scheduler's step + * path, the admission queue or a Sink: these are questions about the server, answered on the + * HTTP thread and finished before they return. */ + HttpResponse handle_health(const HttpRequest& req); + HttpResponse handle_ping(const HttpRequest& req); + HttpResponse handle_version(const HttpRequest& req); + HttpResponse handle_load(const HttpRequest& req); + HttpResponse handle_tokenize(const HttpRequest& req); + HttpResponse handle_detokenize(const HttpRequest& req); + HttpResponse handle_tokenizer_info(const HttpRequest& req); + HttpResponse handle_server_info(const HttpRequest& req); + HttpResponse handle_sessions(const HttpRequest& req); + HttpResponse handle_reset_prefix_cache(const HttpRequest& req); + + /* ------------------------------------------------------------------ dashboard.cpp */ + HttpResponse handle_dashboard(const HttpRequest& req); + HttpResponse handle_stats(const HttpRequest& req); + HttpResponse handle_graph(const HttpRequest& req); + + HttpResponse error_response(const ApiError& e); + + /* Admission. Returns false when the queue is full; the caller answers 429. */ + bool admit(int64_t n); + void release(int64_t n); + void sweep_abandoned(); + /* Wait, bounded, for the scheduler to finish everything it was told to cancel. */ + void drain_graveyard(int timeout_ms); + + /* Turn a parsed request into `n_choices` submitted engine requests. */ + int submit_all(const OaiRequest& r, std::vector* gens, ApiError* err); + void cancel_all(std::vector& gens, bool count_disconnect); + void retire(std::vector& gens); + + /* Drain sinks into decoded text. Returns true if anything new arrived. */ + bool pump(std::vector& gens, const OaiRequest& r); + bool all_done(const std::vector& gens) const; + + HttpResponse blocking_completion(const HttpRequest& req, OaiRequest& r); + HttpResponse streaming_completion(const HttpRequest& req, OaiRequest& r); + + void record(const OaiRequest& r, const std::vector& gens, Finish overall); + + Deps deps_; + ServerOptions opt_; + OaiLimits lim_; + OaiDeps odeps_; + Router router_; + Metrics metrics_; + HttpTransport transport_; + + std::atomic in_flight_{0}; + int64_t queue_depth_ = 0; + std::atomic stopping_{false}; + int64_t started_at_ = 0; + + /* Sinks whose HTTP side is gone but whose engine side may still be mid-step. Held until the + * scheduler reports the request terminal, because Request::sink is a raw pointer and freeing + * it under a running step is a use-after-free in the one place it is unbisectable. */ + std::mutex grave_m_; + std::vector> grave_; +}; + +} /* namespace server */ +} /* namespace rad */ diff --git a/core/server/sink.cpp b/core/server/sink.cpp new file mode 100644 index 00000000..d32a7ef4 --- /dev/null +++ b/core/server/sink.cpp @@ -0,0 +1,130 @@ +#include "sink.h" + +#include +#include + +namespace rad { +namespace server { + +static int64_t now_ns() { + using namespace std::chrono; + return duration_cast(steady_clock::now().time_since_epoch()).count(); +} + +const char* finish_reason_oai(Finish f) { + switch (f) { + case Finish::Stop: + case Finish::StopString: return "stop"; + case Finish::Length: return "length"; + case Finish::ToolCalls: return "tool_calls"; + case Finish::Cancelled: return "abort"; /* vLLM's spelling; dashboards key off it */ + case Finish::Error: return "error"; + case Finish::None: return ""; + } + return ""; +} + +static size_t round_pow2(size_t n) { + size_t p = 1; + while (p < n) p <<= 1; + return p; +} + +Sink::Sink(size_t capacity) { + size_t cap = round_pow2(capacity < 16 ? 16 : capacity); + ring_.resize(cap); + mask_ = cap - 1; + t_start_ns_ = now_ns(); +} + +Sink::~Sink() { + /* Only a sink the producer actually terminated can have a notify in flight; one that was + * never handed to the scheduler quiesces trivially. */ + if (finish_.load(std::memory_order_acquire) == (int)Finish::None) return; + for (int spins = 0; !quiesced_.load(std::memory_order_acquire); ++spins) { + /* The window is a handful of instructions wide, so a short spin covers it; the sleep is + * there so a descheduled producer cannot burn a core. */ + if (spins > 256) std::this_thread::sleep_for(std::chrono::microseconds(20)); + } +} + +int64_t Sink::age_ns() const { return now_ns() - t_start_ns_; } + +void Sink::notify() { + /* Deliberately not holding m_. See the header: this can lose a wake-up, and the consumer's + * bounded wait is what pays for that. Taking the lock here would put the scheduler thread + * behind whatever an HTTP thread happens to be doing. */ + cv_.notify_one(); +} + +bool Sink::push(int32_t token, float logprob) { + const uint64_t h = head_.load(std::memory_order_relaxed); + const uint64_t t = tail_.load(std::memory_order_acquire); + if (h - t > mask_) { + /* The consumer is not draining. Failing loudly beats a stream with a hole in it. */ + overflow_.store(true, std::memory_order_release); + fail(RAD_E_FULL); + return false; + } + ring_[h & mask_] = SinkToken{token, logprob}; + head_.store(h + 1, std::memory_order_release); + + const int64_t t_now = now_ns() - t_start_ns_; + if (h == 0) t_first_.store(t_now, std::memory_order_release); + t_last_.store(t_now, std::memory_order_release); + + notify(); + return true; +} + +void Sink::finish(Finish f) { + int expected = (int)Finish::None; + /* First terminal state wins: a cancel racing an EOS must not be reported twice. */ + if (finish_.compare_exchange_strong(expected, (int)f, std::memory_order_acq_rel)) { + notify(); + /* The last write the producer ever makes to this object, and the one the destructor + * waits on. It has to come after the notify, not before it: the point is to publish that + * the condition variable is no longer being touched. */ + quiesced_.store(true, std::memory_order_release); + } +} + +void Sink::fail(int rad_status) { + status_.store(rad_status, std::memory_order_release); + finish(Finish::Error); +} + +void Sink::set_prompt_stats(int32_t n_prompt, int32_t n_cached) { + n_prompt_.store(n_prompt, std::memory_order_release); + n_cached_.store(n_cached, std::memory_order_release); +} + +size_t Sink::read(SinkToken* out, size_t max) { + const uint64_t t = tail_.load(std::memory_order_relaxed); + const uint64_t h = head_.load(std::memory_order_acquire); + size_t n = (size_t)(h - t); + if (n > max) n = max; + for (size_t i = 0; i < n; ++i) out[i] = ring_[(t + i) & mask_]; + if (n) tail_.store(t + n, std::memory_order_release); + return n; +} + +bool Sink::wait(int timeout_ms) { + auto ready = [&] { + return head_.load(std::memory_order_acquire) != tail_.load(std::memory_order_relaxed) + || finish_.load(std::memory_order_acquire) != (int)Finish::None + || cancel_.load(std::memory_order_acquire); + }; + if (ready()) return true; + std::unique_lock lk(m_); + cv_.wait_for(lk, std::chrono::milliseconds(timeout_ms), ready); + return ready(); +} + +void Sink::request_cancel() { + cancel_.store(true, std::memory_order_release); + notify(); +} + +} /* namespace server */ +} /* namespace rad */ diff --git a/core/server/sink.h b/core/server/sink.h new file mode 100644 index 00000000..2abd295b --- /dev/null +++ b/core/server/sink.h @@ -0,0 +1,173 @@ +/* core/server/sink.h -- the per-request channel from the scheduler thread to the HTTP thread. + * + * `Request::sink` is the void* hook for this (rad_core.h). Exactly one scheduler thread writes it + * and exactly one HTTP thread reads it, so it is a single-producer single-consumer ring and needs + * no lock on the data path: a relaxed load of the head, a store into a slot, a release store of + * the head. The producer never allocates and never blocks, which is the requirement -- a step + * that can be delayed by a slow HTTP client is a step that has coupled every request in the batch + * to the worst one. + * + * The wake-up is the one place a mutex appears, and only on the consumer's side of it. The + * producer calls notify_one() without holding the lock, which can lose a wake-up in the window + * between the consumer testing the predicate and sleeping; the consumer therefore waits with a + * bounded timeout (RAD_SINK_POLL_MS) rather than indefinitely. The cost is named: a lost wake-up + * adds at most that many milliseconds to one token's latency. The benefit is that the scheduler + * thread never takes a lock an HTTP thread might be holding, and the same timeout doubles as the + * interval at which the streaming path polls whether the client is still there. + * + * Tokens, not text: detokenisation is stateful and per-request (spec §12) and belongs on the HTTP + * thread. Pushing an int32 keeps the producer's write to eight bytes and no allocation. + */ +#pragma once +#include "rad_core.h" + +#include +#include +#include +#include +#include + +namespace rad { +namespace server { + +/* How long the consumer sleeps before re-testing. Also the connection-liveness poll interval. */ +static constexpr int RAD_SINK_POLL_MS = 25; + +enum class Finish : int { + None = 0, /* still running */ + Stop, /* EOS */ + StopString, /* a stop string matched */ + Length, /* max_tokens */ + ToolCalls, /* the parser found a complete tool call and the model stopped */ + Cancelled, /* client went away, or /cancel */ + Error, /* the engine failed the request; `status` says why */ +}; + +/* The OpenAI `finish_reason` string. Cancelled has no OpenAI spelling; vLLM reports "abort" and + * dashboards key off that, so we match vLLM rather than inventing one. */ +const char* finish_reason_oai(Finish f); + +struct SinkToken { + int32_t token = 0; + float logprob = 0.0f; /* 0 when the sampler does not supply one; see Sink::has_logprobs */ +}; + +class Sink { +public: + /* `capacity` is rounded up to a power of two. 8192 tokens is ~64 KiB and is far more than any + * HTTP consumer can fall behind by without being dead: at 100 tok/s that is 80 seconds of + * slack. Overflow is not silently dropped -- it fails the request, because a stream missing + * tokens in the middle is worse than a stream that stops and says so. */ + explicit Sink(size_t capacity = 8192); + + /* Waits for the producer to be finished touching this object before letting it go. + * + * Observing `done()` is not enough. The producer publishes the terminal state and only then + * wakes the consumer, so between those two instructions the consumer can already be inside + * this destructor -- and destroying a condition_variable while another thread is inside + * notify_one() on it is a use-after-free in pthread_cond_signal. The producer therefore sets + * a quiesced flag as its genuinely last act, and this waits for that flag rather than for the + * state. The window is a handful of instructions wide, so only a data-race detector reports + * it. */ + ~Sink(); + + /* ------------------------------------------------------------------ producer: scheduler */ + + /* Returns false only on overflow, which also marks the request failed. */ + bool push(int32_t token, float logprob = 0.0f); + + /* Terminal. Idempotent -- the first call wins, so a cancel racing a natural stop does not + * produce two finish reasons. */ + void finish(Finish f); + void fail(int rad_status); + + /* The scheduler polls this to learn that the client hung up, and frees the blocks (spec §14). + * It is also told by IScheduler::cancel(); this is the cheap path that needs no lookup. */ + bool cancel_requested() const { return cancel_.load(std::memory_order_acquire); } + + /* Admission accounting, set once by the scheduler when the prompt is placed. */ + void set_prompt_stats(int32_t n_prompt, int32_t n_cached); + + /* ------------------------------------------------------------------ consumer: HTTP */ + + /* Copies up to `max` tokens out. Returns how many. Never blocks. */ + size_t read(SinkToken* out, size_t max); + + /* Sleeps until there is something to read, the request is terminal, or `timeout_ms` elapses. + * Returns true if there is now something to look at. */ + bool wait(int timeout_ms = RAD_SINK_POLL_MS); + + bool done() const { return finish_.load(std::memory_order_acquire) != (int)Finish::None; } + Finish finish_reason() const { return (Finish)finish_.load(std::memory_order_acquire); } + int status() const { return status_.load(std::memory_order_acquire); } + bool overflowed() const { return overflow_.load(std::memory_order_acquire); } + + /* The HTTP thread calls this when the peer disappears. It does NOT free anything itself -- + * the server calls IScheduler::cancel(id) as well; this only stops the producer sooner. */ + void request_cancel(); + + /* Timings, in steady-clock nanoseconds since the sink was constructed. -1 until observed. */ + int64_t t_first_token_ns() const { return t_first_.load(std::memory_order_acquire); } + int64_t t_last_token_ns() const { return t_last_.load(std::memory_order_acquire); } + int64_t age_ns() const; + + int64_t n_produced() const { return (int64_t)head_.load(std::memory_order_acquire); } + int32_t n_prompt() const { return n_prompt_.load(std::memory_order_acquire); } + int32_t n_cached() const { return n_cached_.load(std::memory_order_acquire); } + + /* The engine sets this at wiring time if its sampler returns per-token probabilities. Without + * it the logprobs field of a response is null rather than zeros (spec: nothing unimplemented + * returns success). */ + void set_has_logprobs(bool v) { has_logprobs_ = v; } + bool has_logprobs() const { return has_logprobs_; } + + /* The engine's request id, so a dropped connection can reach IScheduler::cancel. */ + uint64_t id = 0; + +private: + void notify(); + + std::vector ring_; + size_t mask_ = 0; + + std::atomic head_{0}; /* produced count; producer writes, both read */ + std::atomic tail_{0}; /* consumed count; consumer writes, both read */ + + std::atomic finish_{(int)Finish::None}; + std::atomic status_{RAD_OK}; + std::atomic overflow_{false}; + std::atomic cancel_{false}; + std::atomic quiesced_{false}; /* the producer will not touch this object again */ + + std::atomic t_first_{-1}; + std::atomic t_last_{-1}; + int64_t t_start_ns_ = 0; + + std::atomic n_prompt_{0}; + std::atomic n_cached_{0}; + bool has_logprobs_ = false; + + std::mutex m_; + std::condition_variable cv_; +}; + +/* The scheduler's call sites, so core/sched needs one include and no casts of its own. A null + * sink is legal and means nobody is listening -- an offline or benchmark request. */ +inline bool sink_push(void* s, int32_t token, float logprob = 0.0f) { + return s ? static_cast(s)->push(token, logprob) : true; +} +inline void sink_finish(void* s, Finish f) { + if (s) static_cast(s)->finish(f); +} +inline void sink_fail(void* s, int rad_status) { + if (s) static_cast(s)->fail(rad_status); +} +inline bool sink_cancelled(const void* s) { + return s && static_cast(s)->cancel_requested(); +} +inline void sink_prompt_stats(void* s, int32_t n_prompt, int32_t n_cached) { + if (s) static_cast(s)->set_prompt_stats(n_prompt, n_cached); +} + +} /* namespace server */ +} /* namespace rad */ diff --git a/core/text/chat.cpp b/core/text/chat.cpp new file mode 100644 index 00000000..4a12c7cc --- /dev/null +++ b/core/text/chat.cpp @@ -0,0 +1,238 @@ +#include "text/chat.h" +#include "text/tokenizer.h" + +/* The lifted headers live here and nowhere else in core/. See chat.h for why. */ +#include "llama/common/chat.h" +/* For jinja::enable_debug only -- see RADIANCE_DEBUG_JINJA below. */ +#include "llama/common/jinja/runtime.h" +#include "shim/log.h" + +#include + +#include +#include + +namespace rad { + +using ojson = nlohmann::ordered_json; + + +struct ChatTemplate::Impl { + common_chat_templates_ptr tmpls; + ChatCaps caps; + std::string src; + bool add_bos = false, add_eos = false; +}; + +ChatTemplate::ChatTemplate() : impl_(std::make_unique()) {} +ChatTemplate::~ChatTemplate() = default; + +const char* ChatTemplate::chatml_source() { + /* Byte-identical to CHATML_TEMPLATE_SRC in the lift. Duplicated rather than exported because + * exporting it would mean editing the lifted header; the string is stable upstream, and if it + * ever moves this is the single place that has to follow it. */ + return + "{%- for message in messages -%}\n" + " {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>\n' -}}\n" + "{%- endfor -%}\n" + "{%- if add_generation_prompt -%}\n" + " {{- '<|im_start|>assistant\n' -}}\n" + "{%- endif -%}"; +} + +int ChatTemplate::load(const std::string& jinja_source, const std::string& bos, + const std::string& eos, bool add_bos, bool add_eos) { + /* The vendored files' LOG_DBG goes to stderr behind this switch. It has to be set HERE, where + * the template is first touched: the auto-parser analyses the template inside apply() and + * again when the reply format is derived (chatfmt.cpp), and a switch set any later comes too + * late to trace a format the analyzer could not crack. */ + rad_vendor_log::verbose() = (int)log_level() >= (int)Log::Debug; + + /* THE TEMPLATE ENGINE'S OWN TRACE, and there is no other way to get at this one. + * common_chat_templates_init runs a capability PROBE: it renders the template with a + * synthetic tool and a synthetic tool call and watches which values were read. It SWALLOWS + * every exception -- "ignore exceptions during capability analysis" -- so a template that + * genuinely has no tool support and a template that THROWS on the probe both arrive here as + * tools=0, and the difference is the difference between a model that cannot call tools and a + * gap in the engine. Loud: every statement of every render, the serving ones included. */ + if (const char* dbg = std::getenv("RADIANCE_DEBUG_JINJA"); dbg && *dbg && *dbg != '0') + jinja::enable_debug(true); + + const bool fallback = jinja_source.empty(); + if (fallback) { + /* A model with no template is a model whose prompt format we are guessing. ChatML is the + * best guess there is and it is still a guess, so it is said out loud once rather than + * discovered later from output that reads fine and is formatted wrong. */ + RAD_WARN("chat: the model declares no chat template; falling back to ChatML. " + "If the model was not trained on ChatML its replies will be subtly wrong."); + } + const std::string src = fallback ? std::string(chatml_source()) : jinja_source; + + try { + /* model = nullptr: everything common_chat_templates_init() would read off a llama_model + * is passed in as an override instead. See vendor/shim/llama.h. */ + impl_->tmpls = common_chat_templates_init(nullptr, src, bos, eos); + } catch (const std::exception& e) { + RAD_ERR("chat: template did not compile: %s", e.what()); + impl_->tmpls.reset(); + return RAD_E_FORMAT; + } + if (!impl_->tmpls) return RAD_E_FORMAT; + + impl_->src = src; + impl_->add_bos = add_bos; + impl_->add_eos = add_eos; + + const std::map m = common_chat_templates_get_caps(impl_->tmpls.get()); + auto get = [&](const char* k, bool dflt) { + auto it = m.find(k); + return it == m.end() ? dflt : it->second; + }; + impl_->caps.tools = get("supports_tools", true); + impl_->caps.tool_calls = get("supports_tool_calls", true); + impl_->caps.system_role = get("supports_system_role", true); + impl_->caps.parallel_tool_calls = get("supports_parallel_tool_calls", true); + impl_->caps.preserve_reasoning = get("supports_preserve_reasoning", false); + impl_->caps.string_content = get("supports_string_content", true); + impl_->caps.typed_content = get("supports_typed_content", false); + impl_->caps.object_arguments = get("supports_object_arguments", false); + + RAD_INFO("chat: template loaded (%zu bytes)%s; tools=%d tool_calls=%d system=%d thinking=%d", + src.size(), fallback ? " [ChatML fallback]" : "", + (int)impl_->caps.tools, (int)impl_->caps.tool_calls, + (int)impl_->caps.system_role, + (int)common_chat_templates_support_enable_thinking(impl_->tmpls.get())); + return RAD_OK; +} + +int ChatTemplate::load_from_vocab(const Vocab& v) { + /* The template references bos_token and eos_token by TEXT, not by id, so what goes in is the + * piece -- and a control token's piece is its literal spelling, which is what Vocab::text() + * returns for it. */ + const std::string bos = v.bos() >= 0 ? v.text(v.bos()) : std::string(); + const std::string eos = v.eos() >= 0 ? v.text(v.eos()) : std::string(); + return load(v.chat_template(), bos, eos, v.add_bos(), v.add_eos()); +} + +bool ChatTemplate::ready() const { return impl_ && impl_->tmpls != nullptr; } +const ChatCaps& ChatTemplate::caps() const { return impl_->caps; } +const std::string& ChatTemplate::source() const { return impl_->src; } + +/* HOW DEEPLY A CLIENT'S SCHEMA MAY NEST, in objects and arrays. The tools' parameter schemas and + * a response format's schema reach the JSON-schema converter, which recurses once per level and + * names each rule after its whole path, so its output grows with the square of the depth; a few + * thousand levels exhaust the memory or the stack of the thread rendering the request. At this + * depth it still converts in tens of milliseconds, far deeper than a schema describing data + * nests. grammar.cpp bounds the same converter on the path that bypasses the template. */ +static constexpr size_t kMaxSchemaDepth = 512; + +/* Walked with an explicit stack, because the values it exists to catch are the ones too deep to + * recurse over. */ +static size_t json_depth(const ojson& root) { + std::vector> todo{ { &root, 1 } }; + size_t deepest = 0; + while (!todo.empty()) { + const auto [j, d] = todo.back(); + todo.pop_back(); + if (!j->is_structured()) continue; + deepest = std::max(deepest, d); + for (const auto& c : *j) todo.push_back({ &c, d + 1 }); + } + return deepest; +} + +int ChatTemplate::apply(const ojson& messages, const ojson& tools, const ChatOptions& opt, + ChatPrompt* out) const { + if (!ready()) { + RAD_ERR("chat: apply() before load()"); + return RAD_E_STATE; + } + if (!out) return RAD_E_INVAL; + + /* Checked before either schema reaches the converter. The response format arrives as text; + * one that does not parse is left for the template to refuse in its own words. */ + { + const ojson schema = opt.json_schema.empty() + ? ojson() + : ojson::parse(opt.json_schema, nullptr, /*allow_exceptions=*/false); + if (json_depth(tools) > kMaxSchemaDepth || json_depth(schema) > kMaxSchemaDepth) { + out->error = "a tool or response schema nests more than " + + std::to_string(kMaxSchemaDepth) + " levels deep"; + RAD_WARN("chat: %s", out->error.c_str()); + return RAD_E_INVAL; + } + } + + common_chat_templates_inputs in; + try { + in.messages = common_chat_msgs_parse_oaicompat(messages); + if (!tools.is_null() && tools.is_array() && !tools.empty()) + in.tools = common_chat_tools_parse_oaicompat(tools); + in.tool_choice = common_chat_tool_choice_parse_oaicompat(opt.tool_choice); + } catch (const std::exception& e) { + /* A malformed request, not a broken engine. It must come back as a 400 rather than as a + * throw through the request loop. */ + RAD_WARN("chat: request did not parse: %s", e.what()); + out->error = e.what(); + return RAD_E_INVAL; + } + if (!in.tools.empty() && !impl_->caps.tools) { + RAD_WARN("chat: the model's template declares no tool support; refusing the request " + "rather than dropping the tools silently"); + out->error = "this model's chat template declares no tool support"; + return RAD_E_UNSUPPORTED; + } + + in.grammar = opt.grammar; + in.json_schema = opt.json_schema; + in.add_generation_prompt = opt.add_generation_prompt; + in.use_jinja = true; + in.parallel_tool_calls = opt.parallel_tool_calls; + in.enable_thinking = opt.enable_thinking; + in.chat_template_kwargs = opt.template_kwargs; + in.add_bos = opt.add_bos || impl_->add_bos; + in.add_eos = opt.add_eos || impl_->add_eos; + in.reasoning_format = common_reasoning_format_from_name(opt.reasoning_format); + + common_chat_params p; + try { + p = common_chat_templates_apply(impl_->tmpls.get(), in); + } catch (const std::exception& e) { + RAD_ERR("chat: template refused the request: %s", e.what()); + out->error = e.what(); + return RAD_E_UNSUPPORTED; + } + + out->prompt = std::move(p.prompt); + out->generation_prompt = std::move(p.generation_prompt); + out->grammar = std::move(p.grammar); + out->grammar_lazy = p.grammar_lazy; + out->preserved_tokens = std::move(p.preserved_tokens); + out->additional_stops = std::move(p.additional_stops); + out->supports_thinking = p.supports_thinking; + out->thinking_start_tag = std::move(p.thinking_start_tag); + out->thinking_end_tag = std::move(p.thinking_end_tag); + out->format = (int)p.format; + out->parser = std::move(p.parser); + out->grammar_triggers.clear(); + for (const common_grammar_trigger& t : p.grammar_triggers) + out->grammar_triggers.push_back({ (int)t.type, t.value }); + + RAD_DEBUG("chat: rendered %zu bytes, format %s, grammar %zu bytes%s, %zu extra stop(s)", + out->prompt.size(), common_chat_format_name(p.format), + out->grammar.size(), out->grammar_lazy ? " (lazy)" : "", + out->additional_stops.size()); + if ((int)log_level() >= (int)Log::Trace) { + /* THE PROMPT ITSELF, at Trace and nowhere else. A chat endpoint that answers fluently in + * the wrong format looks exactly like a chat endpoint that works, and the only way to tell + * the two apart is to read what the template actually produced -- control tokens included, + * which is why this prints the raw bytes rather than the detokenised form. It is at Trace + * because it is user content and does not belong in an ordinary server log. */ + RAD_TRACE("chat: prompt <<<%s>>>", out->prompt.c_str()); + if (!out->grammar.empty()) RAD_TRACE("chat: grammar <<<%s>>>", out->grammar.c_str()); + for (const auto& s : out->additional_stops) RAD_TRACE("chat: extra stop <<<%s>>>", s.c_str()); + } + return RAD_OK; +} + +} /* namespace rad */ diff --git a/core/text/chat.h b/core/text/chat.h new file mode 100644 index 00000000..7aba4d0b --- /dev/null +++ b/core/text/chat.h @@ -0,0 +1,136 @@ +/* chat.h -- rendering a message list to a prompt, and what the template can do. + * + * This is a thin face over the lifted `common_chat_*` API (vendor/llama/common/chat.*, jinja/, + * see vendor/UPSTREAM). It does three things the lift does not: + * + * 1. ERRORS ARE VALUES. Upstream throws -- a bad template, a message the template rejects, a + * malformed OAI request are all std::runtime_error, and a throw crossing the server's + * request loop is not a failure mode this project accepts. Everything here returns a + * negative RAD_E_* and logs once. + * 2. It takes the template out of the .rad instead of out of a llama_model. RadVocabHeader + * carries the chat template, the BOS/EOS spellings and the add_bos/add_eos flags, which is + * exactly the four things common_chat_templates_init() would otherwise read off a model. + * 3. It keeps the lifted headers out of the rest of core/. Only chat.cpp, chatfmt.cpp and + * chatparse.cpp include them, the last only to resolve schema types when a request's tools + * are bound, so a vendor refresh cannot ripple into the server. + * + * Messages and tools arrive as OpenAI-shaped JSON, because that is what the server has and the + * lift already knows how to read it. Converting to a struct here and back inside would be a + * translation nobody asked for. + */ +#pragma once +#include "rad_internal.h" + +#include +#include +#include +#include + +#include + +namespace rad { + +class Vocab; + +/* What the template supports, PROBED rather than assumed -- jinja/caps.cpp renders the template + * against synthetic inputs and watches what it does with them (spec §12, "template capability + * probe"). The server reports this on /props, and the message adapter uses it to decide whether + * to hand the template a string content or a typed content array. */ +struct ChatCaps { + bool tools = true; + bool tool_calls = true; + bool system_role = true; + bool parallel_tool_calls = true; + bool preserve_reasoning = false; + bool string_content = true; + bool typed_content = false; + bool object_arguments = false; + +}; + +struct ChatOptions { + bool add_generation_prompt = true; + bool enable_thinking = true; + bool parallel_tool_calls = false; + std::string tool_choice = "auto"; /* auto | none | required */ + std::string reasoning_format = "auto"; /* none | auto | deepseek | deepseek-legacy */ + std::string grammar; /* a user-supplied GBNF, or empty */ + std::string json_schema; /* response_format json_schema, or empty */ + bool add_bos = false; + bool add_eos = false; + std::map template_kwargs; +}; + +/* Everything the scheduler and the sampler need for one request, produced in one pass. */ +struct ChatPrompt { + std::string prompt; + std::string generation_prompt; /* the assistant prefix already inside `prompt` */ + + std::string grammar; /* GBNF; empty when the request is unconstrained */ + bool grammar_lazy = false; + /* Triggers for a lazy grammar: the grammar starts applying only once one of these is seen. + * Kept as (type, text) so the sampler can tell a literal word from a pattern. */ + struct GrammarTrigger { int type; std::string value; }; + std::vector grammar_triggers; + + std::vector preserved_tokens; /* must survive the sampler's bans */ + std::vector additional_stops; + + bool supports_thinking = false; + std::string thinking_start_tag, thinking_end_tag; + + /* The auto-parser's own verdict on this render: `format` is a common_chat_format value and + * deliberately opaque here, `parser` the PEG grammar it derived. The engine reads replies + * with chatparse.h instead; these are kept for the differential tests that compare the two. */ + int format = 0; + std::string parser; + + /* WHY THE TEMPLATE REFUSED, in the template's own words. + * + * A jinja `raise_exception` carries the one sentence that says what the caller got wrong -- + * "Unexpected reasoning effort high. Supported types are xhigh (default), medium, and low." + * -- and it is carried out to the caller here rather than only into the log, so a 400 names + * the field at fault instead of saying only that the template refused the request. Filled + * only on a failure return; empty otherwise. + * + * It is the TEMPLATE'S text and therefore model-controlled, not attacker-controlled: it comes + * from the container's own jinja, which the operator chose along with the weights. */ + std::string error; +}; + +class ChatTemplate { +public: + ChatTemplate(); + ~ChatTemplate(); + + /* Compile a Jinja source. `bos`/`eos` are the token TEXTS, which templates reference as + * `bos_token` / `eos_token`. An empty source loads the ChatML fallback and says so at Warn: + * a model with no template is a model whose prompt format we are guessing, and guessing + * quietly is how a chat endpoint produces fluent nonsense. */ + int load(const std::string& jinja_source, const std::string& bos, const std::string& eos, + bool add_bos = false, bool add_eos = false); + /* The same, from a loaded vocab: template, bos text, eos text and the add flags all come off + * RadVocabHeader. This is the path the engine uses. */ + int load_from_vocab(const Vocab& v); + + bool ready() const; + const ChatCaps& caps() const; + const std::string& source() const; + + /* Render. `messages` and `tools` are OpenAI-shaped JSON (`tools` may be null or an empty + * array). Returns RAD_OK, or RAD_E_INVAL when the request does not parse, or + * RAD_E_UNSUPPORTED when the template refuses what was asked of it -- a system message to a + * template with no system role, tools to a template that has none. */ + int apply(const nlohmann::ordered_json& messages, const nlohmann::ordered_json& tools, + const ChatOptions& opt, ChatPrompt* out) const; + + /* ChatML, the fallback. Named rather than inlined so the server can report which template it + * is running. */ + static const char* chatml_source(); + +private: + struct Impl; + std::unique_ptr impl_; +}; + +} /* namespace rad */ diff --git a/core/text/chatfmt.cpp b/core/text/chatfmt.cpp new file mode 100644 index 00000000..a00f0c93 --- /dev/null +++ b/core/text/chatfmt.cpp @@ -0,0 +1,712 @@ +#include "text/chatfmt.h" +#include "text/chat.h" + +#include "rad_builder.h" + +/* The analyser and the grammar builder, at load and admission time only -- never while a reply + * is being read. */ +#include "llama/common/chat.h" +#include "llama/common/chat-auto-parser.h" +#include "llama/common/json-schema-to-grammar.h" +#include "shim/log.h" + +#include + +#include +#include +#include +#include +#include +#include + +namespace rad { + +using ojson = nlohmann::ordered_json; + +namespace { + +bool is_ws(unsigned char c) { return c == ' ' || (c >= '\t' && c <= '\r'); } + +std::string trim_ws(const std::string& s) { + size_t a = 0, b = s.size(); + while (a < b && is_ws((unsigned char)s[a])) ++a; + while (b > a && is_ws((unsigned char)s[b - 1])) --b; + return s.substr(a, b - a); +} + +/* `inner` occurs inside `outer` somewhere other than at its start. */ +bool occurs_inside(const std::string& inner, const std::string& outer) { + return !inner.empty() && outer.size() > inner.size() && outer.find(inner, 1) != std::string::npos; +} + +bool starts_with(const std::string& s, const std::string& p) { + return s.size() >= p.size() && s.compare(0, p.size(), p) == 0; +} + +std::string show(const std::string& s) { return nlohmann::json(s).dump(); } + +} /* namespace */ + +/* ================================================================== validity */ + +int chat_format_check(const ChatFormat& f, std::string* why) { + auto no = [&](const std::string& s) { + if (why) *why = s; + return RAD_E_UNSUPPORTED; + }; + + if (!f.reasoning_open.empty() && f.reasoning_close.empty()) + return no("reasoning_open " + show(f.reasoning_open) + " has no reasoning_close"); + if (f.has_reasoning() && trim_ws(f.reasoning_close).empty()) + return no("reasoning_close is only whitespace"); + if ((uint32_t)f.reasoning_in_prompt > (uint32_t)ChatThink::Never) + return no("reasoning_in_prompt is not a RAD_CHAT_THINK_* value"); + + if (!f.has_tools()) { + for (const std::string* s : { &f.section_open, &f.section_close, &f.call_separator, + &f.call_open, &f.call_close, &f.name_suffix, &f.call_end, + &f.arg_prefix, &f.arg_name_suffix, &f.arg_value_prefix, + &f.arg_value_suffix }) + if (!s->empty()) return no("tool-call delimiters are set but name_prefix is empty"); + if (!f.reasoning_breaks.empty()) return no("reasoning_breaks without tool calls"); + if (!f.triggers.empty()) return no("grammar triggers without tool calls"); + return RAD_OK; + } + + if (!f.section_open.empty() || !f.section_close.empty()) + return no("a section around all calls (section_open/section_close) is not read by the " + "streaming parser"); + if (!f.call_separator.empty()) + return no("a separator between calls (call_separator " + show(f.call_separator) + + ") is not read by the streaming parser; tagged calls separate on whitespace"); + if (f.call_open.empty() && !f.call_close.empty()) + return no("call_close without call_open"); + if (f.name_suffix.empty() || trim_ws(f.name_suffix).empty()) + return no("name_suffix must end the function name with something besides whitespace"); + if (is_ws((unsigned char)f.name_suffix[0])) + return no("name_suffix " + show(f.name_suffix) + " may not begin with whitespace"); + if (f.call_end.empty()) return no("call_end is empty: a call must close with its own tag"); + if (f.arg_prefix.empty()) return no("arg_prefix is empty"); + if (f.arg_value_suffix.empty()) return no("arg_value_suffix is empty"); + if (f.arg_name_suffix.empty() && f.arg_value_prefix.empty()) + return no("nothing ends an argument name: arg_name_suffix and arg_value_prefix are empty"); + if (!f.arg_name_suffix.empty() && !f.arg_value_prefix.empty()) + return no("arg_name_suffix and arg_value_prefix are both set; the streaming parser reads " + "one delimiter between an argument's name and its value"); + if (f.string_value != ChatValue::Raw && f.string_value != ChatValue::Cdata) + return no("string_value must be RAD_CHAT_VALUE_RAW or RAD_CHAT_VALUE_CDATA"); + if ((uint32_t)f.other_value > (uint32_t)ChatValue::Json) + return no("other_value is not a RAD_CHAT_VALUE_* value"); + + /* A wrapped format's content is scanned for the wrapper's core and for name_prefix alone, + * which opens a call written without its wrapper; the two must not be confusable. */ + if (!f.call_open.empty()) { + const std::string co = trim_ws(f.call_open); + if (co.empty()) return no("call_open is only whitespace"); + if (starts_with(co, f.name_prefix) || starts_with(f.name_prefix, co) || + occurs_inside(co, f.name_prefix) || occurs_inside(f.name_prefix, co)) + return no("call_open " + show(f.call_open) + " and name_prefix " + + show(f.name_prefix) + " cannot be told apart"); + } + const std::string opener = f.call_open.empty() ? f.name_prefix : f.call_open; + for (const std::string& b : f.reasoning_breaks) + if (b != opener) + return no("reasoning break " + show(b) + " is not the call opener " + show(opener)); + if (!f.reasoning_breaks.empty() && !f.has_reasoning()) + return no("reasoning_breaks without a reasoning block"); + for (const std::string& t : f.triggers) + if (t.empty()) return no("an empty grammar trigger"); + + /* The delimiter sets scanned together must be read in the order they START, which an + * automaton reports correctly only when no delimiter occurs inside another. */ + if (f.has_reasoning()) { + const std::string close = trim_ws(f.reasoning_close); + for (const std::string& b : f.reasoning_breaks) + if (occurs_inside(close, b) || occurs_inside(b, close) || starts_with(b, close) || + starts_with(close, b)) + return no("reasoning break " + show(b) + " overlaps reasoning_close " + + show(close)); + } + /* Inside a call the next tag is an argument or the close, and the close is recognised by its + * core as well: the whitespace around it is optional when a reply leaves the format. */ + const std::string end = trim_ws(f.call_end); + if (end.empty()) return no("call_end is only whitespace"); + for (const std::string* e : { &f.call_end, &end }) + if (starts_with(f.arg_prefix, *e) || starts_with(*e, f.arg_prefix) || + occurs_inside(f.arg_prefix, *e) || occurs_inside(*e, f.arg_prefix)) + return no("arg_prefix " + show(f.arg_prefix) + " and call_end " + show(f.call_end) + + " cannot be told apart"); + return RAD_OK; +} + +/* ================================================================== the plugin's declaration */ + +int chat_format_from_abi(const RadChatFormat* in, ChatFormat* out, std::string* why) { + if (!in || !out) { + if (why) *why = "no format"; + return RAD_E_INVAL; + } + if (in->struct_size < offsetof(RadChatFormat, name) + sizeof(in->name)) { + if (why) *why = "struct_size " + std::to_string(in->struct_size) + " is too small"; + return RAD_E_INVAL; + } + RadChatFormat c; + std::memset(&c, 0, sizeof c); + std::memcpy(&c, in, std::min(in->struct_size, sizeof c)); + + auto s = [](const char* p) { return p ? std::string(p) : std::string(); }; + auto list = [](const char* const* v, uint32_t n, std::vector* o) { + o->clear(); + for (uint32_t i = 0; v && i < n; ++i) + if (v[i]) o->emplace_back(v[i]); + }; + + ChatFormat f; + f.name = s(c.name); + f.reasoning_open = s(c.reasoning_open); + f.reasoning_close = s(c.reasoning_close); + list(c.reasoning_breaks, c.n_reasoning_breaks, &f.reasoning_breaks); + f.reasoning_in_prompt = (ChatThink)c.reasoning_in_prompt; + f.section_open = s(c.section_open); + f.section_close = s(c.section_close); + f.call_separator = s(c.call_separator); + f.call_open = s(c.call_open); + f.call_close = s(c.call_close); + f.name_prefix = s(c.name_prefix); + f.name_suffix = s(c.name_suffix); + f.call_end = s(c.call_end); + f.arg_prefix = s(c.arg_prefix); + f.arg_name_suffix = s(c.arg_name_suffix); + f.arg_value_prefix = s(c.arg_value_prefix); + f.arg_value_suffix = s(c.arg_value_suffix); + f.string_value = (ChatValue)c.string_value; + f.other_value = (ChatValue)c.other_value; + f.value_newlines = c.value_newlines != 0; + list(c.triggers, c.n_triggers, &f.triggers); + *out = std::move(f); + return RAD_OK; +} + +/* ================================================================== the template's format */ + +int chat_format_from_template(const std::string& jinja, const std::string& bos, + const std::string& eos, ChatFormat* out, + std::string* tools_refused, std::string* why) { + std::string dummy; + if (!tools_refused) tools_refused = &dummy; + if (!why) why = &dummy; + tools_refused->clear(); + const std::string src = jinja.empty() ? std::string(ChatTemplate::chatml_source()) : jinja; + + ChatFormat f; + f.name = "template"; + try { + common_chat_template tmpl(src, bos, eos); + + /* A template llama.cpp reads with a hand-written handler is one the analysis never + * describes, and its markers would be read as if it had. */ + autoparser::generation_params probe; + probe.messages = ojson::array({ ojson{ { "role", "user" }, { "content", "hi" } } }); + probe.add_generation_prompt = true; + if (common_chat_try_specialized_template(tmpl, src, probe)) { + *why = "the chat template is one llama.cpp reads with a hand-written handler, whose " + "reply format the template analysis does not describe"; + return RAD_E_UNSUPPORTED; + } + + autoparser::autoparser a; + a.analyze_template(tmpl); + + if (a.reasoning.mode != autoparser::reasoning_mode::NONE && !a.reasoning.end.empty()) { + f.reasoning_open = a.reasoning.start; + f.reasoning_close = a.reasoning.end; + } + if (a.content.mode != autoparser::content_mode::PLAIN) { + *why = "the template wraps its answer in content markers, which the streaming parser " + "does not read"; + return RAD_E_UNSUPPORTED; + } + + const auto& t = a.tools; + const bool calls = t.format.mode != autoparser::tool_format::NONE && + a.jinja_caps.supports_tool_calls; + std::string refuse; + if (calls) { + if (t.format.mode == autoparser::tool_format::JSON_NATIVE) + refuse = "the template writes each call as a JSON object"; + else if (t.format.mode == autoparser::tool_format::TAG_WITH_JSON) + refuse = "the template writes a call's arguments as one JSON object inside a tag"; + else if (t.call_id.pos != autoparser::call_id_position::NONE) + refuse = "the template writes a call id"; + else if (!t.arguments.start.empty() || !t.arguments.end.empty()) + refuse = "the template wraps a call's arguments in " + show(t.arguments.start) + + " .. " + show(t.arguments.end); + else if (!t.arguments.separator.empty()) + refuse = "the template separates arguments with " + show(t.arguments.separator); + } + if (calls && refuse.empty()) { + ChatFormat c = f; + c.section_open = t.format.section_start; + c.section_close = t.format.section_end; + c.call_open = t.format.per_call_start; + c.call_close = t.format.per_call_end; + c.name_prefix = t.function.name_prefix; + c.name_suffix = t.function.name_suffix; + c.call_end = t.function.close; + c.arg_prefix = t.arguments.name_prefix; + c.arg_name_suffix = t.arguments.name_suffix; + c.arg_value_prefix = t.arguments.value_prefix; + c.arg_value_suffix = t.arguments.value_suffix; + c.string_value = ChatValue::Cdata; + c.other_value = ChatValue::Json; + c.value_newlines = true; + /* What opens a call is what both the lazy grammar waits for and what ends an + * unclosed reasoning block -- the section or per-call opener. A format with neither + * gets no grammar and no break: its calls open with the function name prefix, which + * a model also writes in prose. */ + const std::string& marker = !t.format.section_start.empty() ? t.format.section_start + : t.format.per_call_start; + if (!marker.empty()) { + c.triggers.push_back(marker); + if (c.has_reasoning()) c.reasoning_breaks.push_back(marker); + } + std::string bad; + if (chat_format_check(c, &bad) == RAD_OK) f = std::move(c); + else refuse = bad; + } + if (!refuse.empty()) *tools_refused = refuse; + } catch (const std::exception& e) { + *why = std::string("the chat template could not be analysed: ") + e.what(); + return RAD_E_FORMAT; + } + *out = std::move(f); + return RAD_OK; +} + +std::string chat_format_describe(const ChatFormat& f) { + std::string s = f.name + ":"; + if (f.has_reasoning()) + s += " reasoning " + show(f.reasoning_open) + ".." + show(f.reasoning_close); + else + s += " no reasoning"; + if (f.has_tools()) { + s += "; calls " + show(f.call_open) + show(f.name_prefix) + "NAME" + show(f.name_suffix) + + " " + show(f.arg_prefix) + "ARG" + show(f.arg_name_suffix) + show(f.arg_value_prefix) + + "VALUE" + show(f.arg_value_suffix) + " " + show(f.call_end) + show(f.call_close); + if (!f.triggers.empty()) { + s += "; grammar on"; + for (const std::string& t : f.triggers) s += " " + show(t); + } else { + s += "; no grammar"; + } + } else { + s += "; no tool calls"; + } + return s; +} + +std::vector chat_format_markers(const ChatFormat& f) { + std::vector out; + for (const std::string* s : { &f.reasoning_open, &f.reasoning_close, &f.section_open, + &f.section_close, &f.call_open, &f.call_close, &f.name_prefix, + &f.name_suffix, &f.call_end, &f.arg_prefix, &f.arg_name_suffix, + &f.arg_value_prefix, &f.arg_value_suffix }) { + const std::string t = trim_ws(*s); + if (!t.empty() && std::find(out.begin(), out.end(), t) == out.end()) out.push_back(t); + } + return out; +} + +/* ================================================================== grammar + * + * The grammar is built as an expression tree and rendered by the rules the vendored PEG-to-GBNF + * pass uses, so a format derived from a template yields the same text the vendored generator + * produces for it: sequences and alternations are flattened as they are built, a sequence or + * alternation nested in a sequence is parenthesised, only an alternation nested in an + * alternation is, and a repeated sequence or alternation is. */ +namespace { + +struct G { + enum K : uint8_t { Eps, Lit, Seq, Alt, Rep, Leaf, Wrap } k = Eps; + std::string s; /* Lit: the text; Leaf: rendered GBNF */ + std::vector kids; + int min = 0, max = -1; + bool compound = false; /* Leaf/Wrap: renders like a sequence for parenthesising */ +}; + +G eps() { return G{}; } +G lit(const std::string& s) { G g; g.k = G::Lit; g.s = s; return g; } +G leaf(const std::string& s) { G g; g.k = G::Leaf; g.s = s; return g; } +G space() { return leaf("space"); } +G rule_ref(const std::string& name) { return leaf(name); } + +/* A tag or an atomic around a node: it renders as the node, is parenthesised as the node would + * be, but a sequence built around it does not flatten into it. */ +G wrap(G inner) { G g; g.k = G::Wrap; g.kids.push_back(std::move(inner)); return g; } + +G seq(std::vector parts) { + G g; g.k = G::Seq; + for (G& p : parts) { + if (p.k == G::Seq) for (G& c : p.kids) g.kids.push_back(std::move(c)); + else g.kids.push_back(std::move(p)); + } + return g; +} +G alt(std::vector parts) { + G g; g.k = G::Alt; + for (G& p : parts) { + if (p.k == G::Alt) for (G& c : p.kids) g.kids.push_back(std::move(c)); + else g.kids.push_back(std::move(p)); + } + return g; +} +G rep(G child, int min, int max) { + G g; g.k = G::Rep; g.min = min; g.max = max; g.kids.push_back(std::move(child)); return g; +} +G opt(G child) { return rep(std::move(child), 0, 1); } + +const G& effective(const G& g) { return g.k == G::Wrap ? effective(g.kids[0]) : g; } + +std::string render(const G& g); + +std::string render_rep_suffix(int min, int max) { + if (min == 0 && max == 1) return "?"; + if (min == 0 && max == -1) return "*"; + if (min == 1 && max == -1) return "+"; + if (max == -1) return "{" + std::to_string(min) + ",}"; + if (min == max) return min == 1 ? "" : "{" + std::to_string(min) + "}"; + return "{" + std::to_string(min) + "," + std::to_string(max) + "}"; +} + +std::string render(const G& g) { + switch (g.k) { + case G::Eps: return ""; + case G::Lit: return gbnf_format_literal(g.s); + case G::Leaf: return g.s; + case G::Wrap: return render(g.kids[0]); + case G::Seq: { + std::string s; + for (const G& c : g.kids) { + const std::string r = render(c); + if (r.empty()) continue; + if (!s.empty()) s += " "; + const G& e = effective(c); + if (e.k == G::Seq || e.k == G::Alt) s += "(" + r + ")"; + else s += r; + } + return s; + } + case G::Alt: { + std::string s; + for (const G& c : g.kids) { + if (!s.empty()) s += " | "; + const std::string r = render(c); + if (effective(c).k == G::Alt) s += "(" + r + ")"; + else s += r; + } + return s; + } + case G::Rep: { + std::string r = render(g.kids[0]); + const G& e = effective(g.kids[0]); + if (e.k == G::Seq || e.k == G::Alt) r = "(" + r + ")"; + return r + render_rep_suffix(g.min, g.max); + } + } + return ""; +} + +/* A character in a GBNF class, escaped as the vendored generator escapes it. */ +std::string class_char(uint32_t c) { + if (c == '-' || c == ']' || c == '[' || c == '\\') return std::string("\\") + (char)c; + if (c == '\n') return "\\n"; + if (c == '\t') return "\\t"; + if (c == '\r') return "\\r"; + if (c >= 0x20 && c <= 0x7E) return std::string(1, (char)c); + static const char* hex = "0123456789ABCDEF"; + std::string s; + if (c <= 0xFF) { s = "\\x"; for (int i = 1; i >= 0; --i) s += hex[(c >> (4 * i)) & 15]; } + else if (c <= 0xFFFF) { s = "\\u"; for (int i = 3; i >= 0; --i) s += hex[(c >> (4 * i)) & 15]; } + else { s = "\\U"; for (int i = 7; i >= 0; --i) s += hex[(c >> (4 * i)) & 15]; } + return s; +} + +std::vector codepoints(const std::string& s) { + std::vector out; + for (size_t i = 0; i < s.size();) { + const unsigned char c = (unsigned char)s[i]; + uint32_t cp = c; + size_t n = 1; + if (c >= 0xF0) { cp = c & 0x07; n = 4; } + else if (c >= 0xE0) { cp = c & 0x0F; n = 3; } + else if (c >= 0xC0) { cp = c & 0x1F; n = 2; } + if (i + n > s.size()) break; + for (size_t k = 1; k < n; ++k) cp = (cp << 6) | ((unsigned char)s[i + k] & 0x3F); + out.push_back(cp); + i += n; + } + return out; +} + +/* A rule name as the vendored builder spells it: every run of characters outside + * [a-zA-Z0-9-] becomes one '-'. */ +std::string rule_name(const std::string& s) { + std::string out; + bool run = false; + for (char ch : s) { + const bool ok = (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || + (ch >= '0' && ch <= '9') || ch == '-'; + if (ok) { out += ch; run = false; } + else if (!run) { out += '-'; run = true; } + } + return out; +} + +std::string utf8(const std::vector& cps) { + std::string s; + for (uint32_t c : cps) { + if (c < 0x80) s += (char)c; + else if (c < 0x800) { s += (char)(0xC0 | (c >> 6)); s += (char)(0x80 | (c & 0x3F)); } + else if (c < 0x10000) { + s += (char)(0xE0 | (c >> 12)); s += (char)(0x80 | ((c >> 6) & 0x3F)); + s += (char)(0x80 | (c & 0x3F)); + } else { + s += (char)(0xF0 | (c >> 18)); s += (char)(0x80 | ((c >> 12) & 0x3F)); + s += (char)(0x80 | ((c >> 6) & 0x3F)); s += (char)(0x80 | (c & 0x3F)); + } + } + return s; +} + +/* "Any text not containing one of these", as a repetition over the trie of the delimiters: + * for each proper prefix, that prefix followed by a character that does not continue it. */ +std::string until_pattern(const std::vector& delims) { + if (delims.empty()) return ".*"; + struct Node { std::map kids; bool word = false; }; + std::vector t(1); + for (const std::string& d : delims) { + size_t cur = 0; + for (uint32_t c : codepoints(d)) { + auto it = t[cur].kids.find(c); + if (it == t[cur].kids.end()) { + t.emplace_back(); + t[cur].kids[c] = t.size() - 1; + cur = t.size() - 1; + } else { + cur = it->second; + } + } + t[cur].word = true; + } + std::string pattern; + std::vector prefix; + std::function walk = [&](size_t n) { + if (!t[n].word && !t[n].kids.empty()) { + std::string cls; + for (const auto& kv : t[n].kids) cls += class_char(kv.first); + if (!pattern.empty()) pattern += " | "; + if (!prefix.empty()) pattern += gbnf_format_literal(utf8(prefix)) + " [^" + cls + "]"; + else pattern += "[^" + cls + "]"; + } + for (const auto& kv : t[n].kids) { + prefix.push_back(kv.first); + walk(kv.second); + prefix.pop_back(); + } + }; + walk(0); + return "(" + pattern + ")*"; +} + +/* The rules the vendored generator emits for its generic JSON parser whenever an argument or a + * document is typed by a schema. Nothing references them -- the schema's own rules do the + * constraining -- but the vendored grammar carries them, and so does this one, so the two can be + * compared byte for byte. */ +void add_json_rules(const common_grammar_builder& b) { + b.add_rule("json-array", "\"[\" space (\"]\" | json-value (\",\" space json-value)* space " + "\"]\") space"); + b.add_rule("json-bool", "(\"true\" | \"false\") space"); + b.add_rule("json-null", "\"null\" space"); + b.add_rule("json-number", "\"-\"? (\"0\" | [1-9] [0-9]*) (\".\" [0-9]+)? ((\"e\" | \"E\") " + "[+-]? [0-9]+)? space"); + b.add_rule("json-object", "\"{\" space (\"}\" | json-string space \":\" space json-value " + "(space \",\" space json-string space \":\" space json-value)* " + "space \"}\") space"); + b.add_rule("json-string", "\"\\\"\" ( [^\"\\\\] | \"\\\\\" ( [\"\\\\/ bfnrt] | \"u\" " + "[0-9a-fA-F]{4} ) )* \"\\\"\" space"); + b.add_rule("json-value", "json-object | json-array | json-string | json-number | json-bool | " + "json-null"); +} + +G optspace(const std::string& tag) { + size_t a = 0, b = tag.size(); + while (a < b && is_ws((unsigned char)tag[a])) ++a; + while (b > a && is_ws((unsigned char)tag[b - 1])) --b; + std::vector parts{ eps() }; + for (size_t i = 0; i < a; ++i) parts.push_back(opt(lit(std::string(1, tag[i])))); + parts.push_back(lit(tag.substr(a, b - a))); + for (size_t i = b; i < tag.size(); ++i) parts.push_back(opt(lit(std::string(1, tag[i])))); + return seq(std::move(parts)); +} + +/* The reasoning block as the vendored generator builds it. */ +G reasoning_expr(const ChatFormat& f, const std::vector& breaks) { + const std::string end = trim_ws(f.reasoning_close); + if (!breaks.empty()) { + std::vector stops{ end }; + stops.insert(stops.end(), breaks.begin(), breaks.end()); + G unclosed = seq({ wrap(leaf(until_pattern(stops))), eps() }); + G closed = seq({ wrap(leaf(until_pattern({ end }))), optspace(f.reasoning_close) }); + if (!f.reasoning_open.empty()) + return opt(alt({ seq({ optspace(f.reasoning_open), unclosed }), + seq({ optspace(f.reasoning_open), closed }) })); + return opt(alt({ unclosed, closed })); + } + if (!f.reasoning_open.empty()) + return opt(seq({ optspace(f.reasoning_open), wrap(leaf(until_pattern({ end }))), + optspace(f.reasoning_close) })); + return opt(seq({ wrap(leaf(until_pattern({ end }))), optspace(f.reasoning_close) })); +} + +} /* namespace */ + +int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, ChatGrammar* out, + std::string* why) { + *out = ChatGrammar{}; + const ojson none; + const ojson& tools = req.tools ? *req.tools : none; + const bool has_tools = f.has_tools() && tools.is_array() && !tools.empty(); + const bool has_rf = req.json_schema && req.json_schema->is_object() && !req.json_schema->empty(); + if (!has_rf && !(has_tools && !f.triggers.empty())) return RAD_OK; + + const std::string opener = f.call_open.empty() ? f.name_prefix : f.call_open; + std::vector breaks; + if (has_tools && req.extract_reasoning && f.has_reasoning()) breaks = f.reasoning_breaks; + + try { + out->text = build_grammar([&](const common_grammar_builder& b) { + for (const auto& tool : tools) { + if (!tool.is_object() || !tool.contains("type") || tool.at("type") != "function" || + !tool.contains("function")) + continue; + const auto& fn = tool.at("function"); + auto schema = fn.contains("parameters") ? fn.at("parameters") : ojson::object(); + b.resolve_refs(schema); + } + if (has_rf) { + auto schema = *req.json_schema; + b.resolve_refs(schema); + } + + if (has_rf) { + /* The whole reply: what follows the generation prompt, the reasoning block, and + * the document, fenced or not. */ + b.add_rule("response-format", b.add_schema("response-format-schema", + *req.json_schema)); + add_json_rules(b); + std::string gp = req.generation_prompt; + if (f.has_reasoning() && !f.reasoning_open.empty()) { + const size_t at = gp.find(f.reasoning_open); + if (at != std::string::npos) gp = gp.substr(0, at); + } + std::vector root{ gp.empty() ? eps() : lit(gp), space() }; + if (f.has_reasoning() && req.extract_reasoning) root.push_back(reasoning_expr(f, breaks)); + root.push_back(space()); + root.push_back(alt({ seq({ lit("```json"), space(), rule_ref("response-format"), space(), + lit("```") }), + rule_ref("response-format") })); + b.add_rule("root", render(seq(std::move(root)))); + return; + } + + /* The lazy call grammar: only what follows a trigger. */ + const std::string name_end = f.arg_name_suffix.empty() ? f.arg_value_prefix + : f.arg_name_suffix; + std::vector choices; + bool typed = false; + for (const auto& tool : tools) { + if (!tool.is_object() || !tool.contains("type") || tool.at("type") != "function" || + !tool.contains("function")) + continue; + const auto& fn = tool.at("function"); + const std::string name = fn.at("name"); + auto params = fn.contains("parameters") ? fn.at("parameters") : ojson::object(); + const auto properties = params.contains("properties") ? params.at("properties") + : ojson::object(); + std::set required; + if (params.contains("required")) params.at("required").get_to(required); + common_schema_info info; + info.resolve_refs(params); + + std::vector req_arms, opt_arms; + for (const auto& [pname, pschema] : properties.items()) { + G value; + if (f.other_value != ChatValue::Json || info.resolves_to_string(pschema)) { + value = wrap(rule_ref("until-suffix")); + } else { + typed = true; + const std::string sch = b.add_schema( + "tool-" + name + "-arg-" + pname + "-schema", pschema); + value = alt({ seq({ wrap(leaf(sch)), space() }), wrap(rule_ref("until-suffix")) }); + } + G arm = wrap(seq({ wrap(seq({ lit(f.arg_prefix), wrap(lit(pname)), + lit(f.arg_name_suffix) })), + lit(f.arg_value_prefix), value, + wrap(lit(f.arg_value_suffix)) })); + const std::string rule = rule_name("tool-" + name + "-arg-" + pname); + b.add_rule(rule, render(arm)); + (required.count(pname) ? req_arms : opt_arms).push_back(rule_ref(rule)); + } + std::vector any = req_arms; + any.insert(any.end(), opt_arms.begin(), opt_arms.end()); + /* The generic arm for an undeclared name. A tool that declares no parameters + * takes no arguments at all, so its arm is never reached and not emitted. */ + if (!any.empty()) { + G arm = wrap(seq({ wrap(seq({ lit(f.arg_prefix), + wrap(leaf(until_pattern({ name_end }))), + lit(f.arg_name_suffix) })), + lit(f.arg_value_prefix), wrap(rule_ref("until-suffix")), + wrap(lit(f.arg_value_suffix)) })); + const std::string rule = rule_name("tool-" + name + "-arg-undeclared"); + b.add_rule(rule, render(arm)); + any.push_back(rule_ref(rule)); + } + G any_arg = alt(any); + G args = eps(); + if (!req_arms.empty()) args = seq({ any_arg, rep(seq({ space(), any_arg }), 0, -1) }); + else if (!opt_arms.empty()) args = seq({ eps(), rep(seq({ space(), any_arg }), 0, -1) }); + + G open = wrap(seq({ lit(f.name_prefix), wrap(lit(name)), lit(f.name_suffix) })); + G func = seq({ open, eps(), space(), args, space(), wrap(lit(f.call_end)) }); + b.add_rule(rule_name("tool-" + name), render(func)); + choices.push_back(rule_ref(rule_name("tool-" + name))); + } + if (typed) add_json_rules(b); + if (!choices.empty()) b.add_rule("until-suffix", until_pattern({ f.arg_value_suffix })); + + G choice = alt(choices); + G calls; + if (!f.call_open.empty()) { + G wrapped = seq({ lit(f.call_open), space(), choice, space(), lit(f.call_close) }); + calls = req.parallel_tool_calls + ? seq({ wrapped, rep(seq({ space(), wrapped }), 0, -1), space() }) + : seq({ wrapped, space() }); + } else { + G next = seq({ space(), opt(wrap(leaf(until_pattern({ opener })))), choice }); + calls = req.parallel_tool_calls + ? seq({ lit(""), space(), choice, rep(next, 0, -1), space(), lit("") }) + : seq({ lit(""), space(), choice, space(), lit("") }); + } + b.add_rule("tool-call", render(calls)); + b.add_rule("root", "tool-call"); + }); + } catch (const std::exception& e) { + if (why) *why = e.what(); + return RAD_E_INVAL; + } + out->lazy = !has_rf; + if (out->lazy) out->trigger_words = f.triggers; + return RAD_OK; +} + +} /* namespace rad */ diff --git a/core/text/chatfmt.h b/core/text/chatfmt.h new file mode 100644 index 00000000..7c8b59c5 --- /dev/null +++ b/core/text/chatfmt.h @@ -0,0 +1,175 @@ +/* chatfmt.h -- how a model spells a turn: reasoning, tool calls, arguments. As DATA. + * + * Everything the engine knows about a model's reply syntax is in one plain struct, ChatFormat, + * and everything that depends on that syntax is DERIVED from it: the streaming reply parser + * (chatparse.h), the lazy tool-call grammar and the literal words that trigger it (below), and the + * tokens the decoder must render as text so the parser can see the structure. A new model is + * supported by stating its format once. + * + * TWO PRODUCERS, IN ORDER OF PRECEDENCE. + * + * 1. The architecture plugin, through the optional `rad_arch_chat_format` export + * (abi/rad_builder.h). A plugin that knows its model's syntax says so and nothing is guessed. + * 2. Analysis of the chat template. llama.cpp's differential analyser renders the template with + * and without a reasoning block, a call and its arguments, and diffs the renders to find the + * delimiters (vendor/llama/common/chat-diff-analyzer.cpp). Its derived MARKERS are read here; + * its PEG parser is not used. + * + * If neither yields a format the parser can run, the model still chats -- the reply is content -- + * but a request that sends tools is refused, naming why. There is no second parser to fall back + * to: a reply format the engine cannot describe is a reply it cannot read, and saying so at + * admission is better than returning a call as prose. + * + * THE FAMILY THIS DESCRIBES is the tagged one, which covers every model this engine serves: + * + * Qwen3.6 / Qwen3.8 \n\n\nVALUE\n\n + * \n + * MiniCPM5 VALUE + * + * A call's name is written between a prefix and a suffix and it ends with its own close; each + * argument is a name between a prefix and a suffix and a value ending at its own suffix; calls may + * be wrapped one by one. Arguments are typed by the tool's JSON schema: a string-typed argument is + * the raw text (optionally CDATA-wrapped), any other type is JSON, and text that does not parse as + * JSON is taken raw -- a model writing into an XML tag writes Python as often as JSON. + * + * The analyser also recognises formats outside this family (a JSON object per call, JSON + * arguments inside a tag, call ids). For those chat_format_from_template keeps the reasoning split + * and names why tool calls are refused, and a model that needs one gets it by adding the shape to + * the parser, not by a fallback. */ +#pragma once +#include "rad_internal.h" + +#include + +#include +#include +#include +#include + +struct RadChatFormat; + +namespace rad { + +/* How a value is written between its delimiters. The numbering is the ABI's (RAD_CHAT_VALUE_*). */ +enum class ChatValue : uint32_t { + Raw = 0, /* the text, verbatim */ + Cdata = 1, /* the text, unless wrapped in , which is punctuation and removed */ + Json = 2, /* a JSON value; text that does not parse as one is taken raw */ +}; + +/* Whether the reply starts inside a reasoning block. The numbering is the ABI's. */ +enum class ChatThink : uint32_t { + /* Search the rendered generation prompt for `reasoning_open`: whatever follows its first + * occurrence is the start of the reply's own text. A template that opens the block for the + * model (Qwen writes "\n" at the end of the prompt) and one that closes it again when + * thinking is off ("\n\n\n\n") are both read correctly this way. */ + FromPrompt = 0, + Always = 1, /* the reply is inside a reasoning block from its first byte */ + Never = 2, /* the model opens its own block, if any */ +}; + +struct ChatFormat { + std::string name; /* for logs: "plugin:" or "template" */ + + /* ------------------------------------------------------------------ reasoning + * A block runs from `reasoning_open` to `reasoning_close`. Whitespace at either end of either + * tag is optional when matching, so "\n" also matches "". An empty close means + * the format has no reasoning block. An empty open with a close means the reply starts in one + * and the close ends it. */ + std::string reasoning_open; + std::string reasoning_close; + /* Literals that end an UNCLOSED block when a call starts there. A model that forgets to close + * its reasoning and goes straight to a call must not have the call swallowed as reasoning. + * Must name the call opener (`call_open`) when non-empty. */ + std::vector reasoning_breaks; + ChatThink reasoning_in_prompt = ChatThink::FromPrompt; + + /* ------------------------------------------------------------------ tool calls + * `name_prefix` is what opens a call (after `call_open`, when there is one). Empty means the + * format has no tool calls. */ + std::string section_open, section_close; /* around ALL calls; not read yet, must be empty */ + /* Between two calls beyond whitespace. Tagged calls are self-delimiting, so this is empty; + * a JSON-array format would say ", ". Not read yet, must be empty. */ + std::string call_separator; + /* Around EACH call: "\n", "". When set, a call written without it -- + * name_prefix alone -- is still read as a call, leniently (chatparse.h). */ + std::string call_open, call_close; + std::string name_prefix, name_suffix; /* "\n" */ + std::string call_end; /* "\n" */ + + std::string arg_prefix; /* "\n" (MiniCPM: empty, the value prefix ends it) */ + std::string arg_value_prefix; /* "" (MiniCPM: "\">") */ + std::string arg_value_suffix; /* "\n" */ + + ChatValue string_value = ChatValue::Cdata; /* a string-typed argument: Raw or Cdata */ + ChatValue other_value = ChatValue::Json; /* any other type: Json */ + /* One newline at each end of a value is punctuation: the template writes the value on its own + * lines, and exactly the first and last newline belong to the tags. */ + bool value_newlines = true; + + /* The literal words that start constrained decoding of a call. Empty means no lazy grammar: + * the reply is unconstrained and the parser reads whatever arrives. */ + std::vector triggers; + + bool has_reasoning() const { return !reasoning_close.empty(); } + bool has_tools() const { return !name_prefix.empty(); } +}; + +/* Can the streaming parser run this format? RAD_OK, or RAD_E_UNSUPPORTED with *why naming the + * field. A format with no tool calls is valid (reasoning split only); a format with tool calls + * must describe them completely enough that every delimiter is unambiguous. */ +int chat_format_check(const ChatFormat& f, std::string* why); + +/* The plugin's declaration, copied out of the ABI struct. Fields past the plugin's + * `struct_size` read as their zero. Returns RAD_E_INVAL with *why when the struct is unusable. */ +int chat_format_from_abi(const RadChatFormat* in, ChatFormat* out, std::string* why); + +/* Derive the format from a chat template by the vendored differential analysis. + * + * RAD_OK with *out filled. A template whose tool calls the analysis found but this family cannot + * express still yields its reasoning split, with the tool fields empty and *tools_refused saying + * why -- the model chats, and a request with tools is refused with that sentence. RAD_E_UNSUPPORTED + * with *why when the template routes to one of llama.cpp's hand-written handlers, whose formats + * the analysis does not describe at all; RAD_E_FORMAT when the template does not compile. An + * empty source is the ChatML fallback, which has neither reasoning nor calls. */ +int chat_format_from_template(const std::string& jinja, const std::string& bos, + const std::string& eos, ChatFormat* out, + std::string* tools_refused, std::string* why); + +/* Human-readable one-liner for the startup log. */ +std::string chat_format_describe(const ChatFormat& f); + +/* ================================================================== grammar + * + * The GBNF that constrains a reply to the format, generated from the description. For a tool + * request it is LAZY: the reply is free until one of `triggers` appears, and from there the + * grammar admits the call syntax with each argument constrained by its schema. For a response + * format it is the whole reply. Rule names and structure follow the vendored generator so the + * two produce the same grammar for a template-analysed format. */ +struct ChatGrammarRequest { + const nlohmann::ordered_json* tools = nullptr; /* the request's tools, or null */ + const nlohmann::ordered_json* json_schema = nullptr; /* a response format's schema, or null */ + std::string generation_prompt; + bool parallel_tool_calls = true; + bool extract_reasoning = true; /* reasoning_format != "none" */ +}; + +struct ChatGrammar { + std::string text; /* empty when the request is unconstrained */ + bool lazy = false; + std::vector trigger_words; +}; + +/* RAD_OK, or RAD_E_INVAL with *why when a tool or schema cannot be expressed. */ +int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, ChatGrammar* out, + std::string* why); + +/* The markers the decoder must render as text for the parser to see them: a format built from + * control tokens reaches the parser with its structure gone otherwise, because the decoder + * suppresses control tokens. Every non-empty delimiter, whitespace-trimmed, deduplicated, in the + * order the vendored analyser lists them -- a marker that is not a single token is harmless, the + * decoder only compares it with the spellings of control tokens. */ +std::vector chat_format_markers(const ChatFormat& f); + +} /* namespace rad */ diff --git a/core/text/chatparse.cpp b/core/text/chatparse.cpp new file mode 100644 index 00000000..68cf5afc --- /dev/null +++ b/core/text/chatparse.cpp @@ -0,0 +1,1818 @@ +#include "text/chatparse.h" +#include "text/chatfmt.h" + +/* Bind time only: the schema resolution that decides which arguments are strings. The same + * function the grammar generator uses, so the parser and the grammar never disagree about a + * type. Nothing from vendor/ runs while a reply is being read. */ +#include "llama/common/json-schema-to-grammar.h" + +#include + +#include +#include +#include +#include +#include + +namespace rad { + +using ojson = nlohmann::ordered_json; + +namespace { + +/* The whitespace set std::isspace accepts in the C locale, which is the set the format's grammar + * skips between tags. */ +inline bool is_ws(unsigned char c) { return c == ' ' || (c >= '\t' && c <= '\r'); } + +/* The whitespace a reasoning block may consist of and still count as empty. */ +inline bool is_blank(unsigned char c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t'; } + +/* ================================================================== delimiter automaton + * + * A deterministic Aho-Corasick automaton over a handful of delimiters. The state is the longest + * suffix of the text scanned so far that is a prefix of some delimiter, so its depth is exactly + * how many trailing bytes might still become one -- the bytes a streaming scan must hold -- and a + * state whose string IS a delimiter is a match. + * + * That last step is exact only because chat_format_check refuses delimiter sets in which one + * delimiter occurs inside another at a non-zero offset. Then a match ends at the first byte where + * any delimiter completes, and no earlier-starting match can still be in progress: the automaton + * reports matches in the order of their START, which is the order the grammar reads them in. */ +class Dfa { +public: + void build(const std::vector& pats) { + pats_ = pats; + struct Node { int next[256]; int depth; int word; }; + std::vector t(1); + std::fill(std::begin(t[0].next), std::end(t[0].next), -1); + t[0].depth = 0; t[0].word = -1; + for (size_t i = 0; i < pats.size(); ++i) { + int cur = 0; + for (unsigned char c : pats[i]) { + if (t[(size_t)cur].next[c] < 0) { + Node n; + std::fill(std::begin(n.next), std::end(n.next), -1); + n.depth = t[(size_t)cur].depth + 1; + n.word = -1; + t.push_back(n); + t[(size_t)cur].next[c] = (int)t.size() - 1; + } + cur = t[(size_t)cur].next[c]; + } + if (cur != 0 && t[(size_t)cur].word < 0) t[(size_t)cur].word = (int)i; + } + const size_t n = t.size(); + tr_.assign(n * 256, 0); + depth_.assign(n, 0); + word_.assign(n, -1); + std::vector fail(n, 0), order; + order.reserve(n); + for (int c = 0; c < 256; ++c) { + const int v = t[0].next[c]; + if (v > 0) { fail[(size_t)v] = 0; tr_[(size_t)c] = (uint16_t)v; order.push_back(v); } + } + for (size_t k = 0; k < order.size(); ++k) { + const int u = order[k]; + for (int c = 0; c < 256; ++c) { + const int v = t[(size_t)u].next[c]; + const uint16_t via = tr_[(size_t)fail[(size_t)u] * 256 + (size_t)c]; + if (v > 0) { + fail[(size_t)v] = via; + tr_[(size_t)u * 256 + (size_t)c] = (uint16_t)v; + order.push_back(v); + } else { + tr_[(size_t)u * 256 + (size_t)c] = via; + } + } + } + for (size_t i = 0; i < n; ++i) { + depth_[i] = (uint16_t)t[i].depth; + word_[i] = (int16_t)t[i].word; + } + std::fill(std::begin(first_), std::end(first_), false); + n_first_ = 0; + for (const std::string& p : pats) + if (!p.empty() && !first_[(unsigned char)p[0]]) { + first_[(unsigned char)p[0]] = true; + only_ = (unsigned char)p[0]; + ++n_first_; + } + } + + uint16_t step(uint16_t s, unsigned char c) const { return tr_[(size_t)s * 256 + c]; } + size_t depth(uint16_t s) const { return depth_[s]; } + int word(uint16_t s) const { return word_[s]; } + const std::string& pattern(int i) const { return pats_[(size_t)i]; } + + /* The first byte in [p, e) that can begin a delimiter. Plain text between delimiters is + * skipped here without running the automaton at all. */ + const char* skip(const char* p, const char* e) const { + if (n_first_ == 1) { + const void* q = std::memchr(p, only_, (size_t)(e - p)); + return q ? (const char*)q : e; + } + if (n_first_ == 0) return e; + while (p < e && !first_[(unsigned char)*p]) ++p; + return p; + } + +private: + std::vector pats_; + std::vector tr_; + std::vector depth_; + std::vector word_; + bool first_[256] = {}; + int n_first_ = 0; + unsigned char only_ = 0; +}; + +/* ================================================================== JSON + * + * A JSON value, recognised one byte at a time with an explicit stack. It accepts exactly what the + * format's grammar accepts as a JSON-typed argument, quirks included, because the answer decides + * whether the argument is typed or text: + * + * * no whitespace before the value, any whitespace after it and inside it; + * * a number may not be followed by a character that could have continued it -- `01`, `1.`, + * `1-` are not numbers -- while `true` and `null` may be followed by anything; + * * a string may hold raw control characters, and any escape but the JSON ones fails it. + * + * push() answers More while the bytes are still a JSON value or its trailing whitespace, Fail at + * the first byte that cannot be, and Done at the first byte after a complete value -- which is + * NOT consumed. */ +class JsonScan { +public: + enum Res : uint8_t { More, Fail, Done }; + + void reset() { st_ = Value; stack_.clear(); lit_ = nullptr; lpos_ = 0; need_ = 0; } + + Res push(unsigned char c) { + for (;;) { + switch (st_) { + case Value: + return start_value(c); + case ValueWs: + if (is_ws(c)) return More; + st_ = Value; + continue; + case Str: + if (need_ > 0) { + if ((c & 0xC0) != 0x80) return Fail; + --need_; + return More; + } + if (c == '"') { st_ = key_ ? KeyAfter : After; return More; } + if (c == '\\') { st_ = StrEsc; return More; } + if (c < 0x80) return More; + if (!(c & 0x40)) return Fail; + if (!(c & 0x20)) { need_ = 1; return More; } + if (!(c & 0x10)) { need_ = 2; return More; } + if (!(c & 0x08)) { need_ = 3; return More; } + return Fail; + case StrEsc: + if (c == '"' || c == '\\' || c == '/' || c == 'b' || c == 'f' || c == 'n' || + c == 'r' || c == 't') { st_ = Str; return More; } + if (c == 'u') { st_ = StrHex; need_ = 4; return More; } + return Fail; + case StrHex: + if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))) + return Fail; + if (--need_ == 0) st_ = Str; + return More; + case NumMinus: + if (c == '0') { st_ = NumZero; return More; } + if (c >= '1' && c <= '9') { st_ = NumInt; return More; } + return Fail; + case NumZero: + if (c == '.') { st_ = NumDot; return More; } + if (c == 'e' || c == 'E') { st_ = NumE; return More; } + if (num_continues(c)) return Fail; + st_ = After; + continue; + case NumInt: + if (c >= '0' && c <= '9') return More; + if (c == '.') { st_ = NumDot; return More; } + if (c == 'e' || c == 'E') { st_ = NumE; return More; } + if (num_continues(c)) return Fail; + st_ = After; + continue; + case NumDot: + if (c >= '0' && c <= '9') { st_ = NumFrac; return More; } + return Fail; + case NumFrac: + if (c >= '0' && c <= '9') return More; + if (c == 'e' || c == 'E') { st_ = NumE; return More; } + if (num_continues(c)) return Fail; + st_ = After; + continue; + case NumE: + if (c == '+' || c == '-') { st_ = NumSign; return More; } + if (c >= '0' && c <= '9') { st_ = NumExp; return More; } + return Fail; + case NumSign: + if (c >= '0' && c <= '9') { st_ = NumExp; return More; } + return Fail; + case NumExp: + if (c >= '0' && c <= '9') return More; + if (num_continues(c)) return Fail; + st_ = After; + continue; + case Lit: + if ((unsigned char)lit_[lpos_] != c) return Fail; + if (lit_[++lpos_] == '\0') st_ = After; + return More; + case After: + if (is_ws(c)) return More; + if (stack_.empty()) return Done; + if (stack_.back() == '{') { + if (c == ',') { st_ = ObjKeyWs; return More; } + if (c == '}') { stack_.pop_back(); st_ = After; return More; } + return Fail; + } + if (c == ',') { st_ = ValueWs; return More; } + if (c == ']') { stack_.pop_back(); st_ = After; return More; } + return Fail; + case ObjOpen: + if (is_ws(c)) return More; + if (c == '}') { stack_.pop_back(); st_ = After; return More; } + if (c == '"') { st_ = Str; key_ = true; need_ = 0; return More; } + return Fail; + case ObjKeyWs: + if (is_ws(c)) return More; + if (c == '"') { st_ = Str; key_ = true; need_ = 0; return More; } + return Fail; + case KeyAfter: + if (is_ws(c)) return More; + if (c == ':') { st_ = ValueWs; return More; } + return Fail; + case ArrOpen: + if (is_ws(c)) return More; + if (c == ']') { stack_.pop_back(); st_ = After; return More; } + st_ = Value; + continue; + } + return Fail; + } + } + +private: + enum St : uint8_t { + Value, ValueWs, Str, StrEsc, StrHex, NumMinus, NumZero, NumInt, NumDot, NumFrac, NumE, + NumSign, NumExp, Lit, After, ObjOpen, ObjKeyWs, KeyAfter, ArrOpen, + }; + /* Deeper than any schema describes. The recognizer does not recurse, so this bounds memory + * rather than the stack; a value nested past it is read as text. */ + static constexpr size_t kMaxDepth = 1u << 16; + + static bool num_continues(unsigned char c) { + return (c >= '0' && c <= '9') || c == '.' || c == 'e' || c == 'E' || c == '+' || c == '-'; + } + + Res start_value(unsigned char c) { + switch (c) { + case '{': + if (stack_.size() >= kMaxDepth) return Fail; + stack_.push_back('{'); st_ = ObjOpen; return More; + case '[': + if (stack_.size() >= kMaxDepth) return Fail; + stack_.push_back('['); st_ = ArrOpen; return More; + case '"': st_ = Str; key_ = false; need_ = 0; return More; + case '-': st_ = NumMinus; return More; + case '0': st_ = NumZero; return More; + case 't': st_ = Lit; lit_ = "true"; lpos_ = 1; return More; + case 'f': st_ = Lit; lit_ = "false"; lpos_ = 1; return More; + case 'n': st_ = Lit; lit_ = "null"; lpos_ = 1; return More; + default: + if (c >= '1' && c <= '9') { st_ = NumInt; return More; } + return Fail; + } + } + + St st_ = Value; + std::vector stack_; + const char* lit_ = nullptr; + size_t lpos_ = 0; + int need_ = 0; + bool key_ = false; +}; + +/* ================================================================== JSON text helpers */ + +/* A string's JSON encoding without its quotes, byte for byte what nlohmann::json::dump writes: + * the two-character escapes where JSON has one, \u00XX in lower-case hex for the other control + * characters, and everything else -- DEL and UTF-8 included -- verbatim. */ +void json_escape_into(std::string& out, const char* p, size_t n) { + static const char hex[] = "0123456789abcdef"; + const char* run = p; + const char* e = p + n; + for (; p < e; ++p) { + const unsigned char c = (unsigned char)*p; + if (c >= 0x20 && c != '"' && c != '\\') continue; + out.append(run, (size_t)(p - run)); + run = p + 1; + switch (c) { + case '"': out += "\\\""; break; + case '\\': out += "\\\\"; break; + case '\b': out += "\\b"; break; + case '\f': out += "\\f"; break; + case '\n': out += "\\n"; break; + case '\r': out += "\\r"; break; + case '\t': out += "\\t"; break; + default: + out += "\\u00"; + out += hex[c >> 4]; + out += hex[c & 15]; + } + } + out.append(run, (size_t)(e - run)); +} + +std::string json_quote(std::string_view s) { + std::string out = "\""; + json_escape_into(out, s.data(), s.size()); + out += '"'; + return out; +} + +/* How many trailing bytes of `s` from `from` on form an unfinished UTF-8 sequence. A delta + * becomes a JSON string on the wire, and half a code point there is a malformed payload. */ +size_t utf8_tail(const std::string& s, size_t from) { + const size_t n = s.size(); + for (size_t back = 1; back <= 3 && back <= n - from; ++back) { + const unsigned char c = (unsigned char)s[n - back]; + if ((c & 0xC0) == 0x80) continue; + size_t need = 1; + if ((c & 0xE0) == 0xC0) need = 2; + else if ((c & 0xF0) == 0xE0) need = 3; + else if ((c & 0xF8) == 0xF0) need = 4; + return back < need ? back : 0; + } + return 0; +} + +/* The value transforms the format's grammar applies, on a whole value. Used for values short + * enough to be held entire and for the held ends of long ones. */ +std::string_view strip_leading_newline(std::string_view v) { + if (!v.empty() && v.front() == '\n') v.remove_prefix(1); + else if (v.size() >= 2 && v[0] == '\r' && v[1] == '\n') v.remove_prefix(2); + return v; +} + +std::string_view strip_trailing_newline(std::string_view v) { + if (!v.empty() && v.back() == '\n') { + v.remove_suffix(1); + if (!v.empty() && v.back() == '\r') v.remove_suffix(1); + } + return v; +} + +constexpr std::string_view kCdOpen = ""; +/* A response-format document may be fenced as a Markdown code block. */ +constexpr std::string_view kFenceOpen = "```json"; +constexpr std::string_view kFenceClose = "```"; + +/* A CDATA section is punctuation, not content, and its two ends are stripped independently. A + * value still arriving holds back what could yet become the opener, and a trailing `]` or `]]` + * that could be the start of the closer. */ +void unwrap_cdata(std::string_view& v, bool partial) { + if (v.size() < kCdOpen.size()) { + if (partial && !v.empty() && kCdOpen.compare(0, v.size(), v) == 0) v = std::string_view(); + return; + } + if (v.compare(0, kCdOpen.size(), kCdOpen) != 0) return; + v.remove_prefix(kCdOpen.size()); + if (v.size() >= kCdClose.size() && + v.compare(v.size() - kCdClose.size(), kCdClose.size(), kCdClose) == 0) { + v.remove_suffix(kCdClose.size()); + return; + } + if (!partial) return; + size_t hold = 0; + while (hold + 1 < kCdClose.size() && v.size() > hold && v[v.size() - 1 - hold] == ']') ++hold; + v.remove_suffix(hold); +} + +/* The name of an argument, as the grammar reads it: one leading whitespace character and every + * trailing one are not part of it. */ +std::string_view trim_arg_name(std::string_view v) { + if (!v.empty() && is_ws((unsigned char)v.front())) v.remove_prefix(1); + while (!v.empty() && is_ws((unsigned char)v.back())) v.remove_suffix(1); + return v; +} + +std::string_view trim_trailing_ws(std::string_view v) { + while (!v.empty() && is_ws((unsigned char)v.back())) v.remove_suffix(1); + return v; +} + +/* ================================================================== an argument value + * + * The bytes of one value as the delimiters bound it, turned into its JSON encoding in the + * arguments object. Two encodings: a STRING (quoted, escaped) and RAW JSON text, which is either + * a value that parsed as JSON or a non-string argument that did not and is passed through -- + * with a Python-style container's single quotes normalised to double ones. + * + * The transforms touch only the ends of a value -- one newline at each end, the CDATA opener and + * closer -- so the middle streams straight through and only a short head and tail are held: the + * first kHead bytes until the head is decided, and the last kTail after that. */ +class ValueOut { +public: + enum Mode : uint8_t { String, Raw }; + static constexpr size_t kHead = 16; /* a newline pair and the CDATA opener, and the tail */ + static constexpr size_t kTail = 5; /* a newline pair and the CDATA closer */ + + void begin(Mode m, bool cdata, bool newlines, std::string& out) { + mode_ = m; cdata_ = cdata; newlines_ = newlines; + buf_.clear(); head_ = false; opened_ = false; + raw_started_ = false; container_ = false; + in_single_ = in_double_ = bs_ = false; + if (mode_ == String) out += '"'; + } + + void add(const char* p, size_t n, std::string& out) { + buf_.append(p, n); + if (!head_) { + if (buf_.size() < kHead) return; + std::string_view v(buf_); + size_t drop = 0; + if (newlines_) drop = v.size() - strip_leading_newline(v).size(); + if (cdata_ && v.compare(drop, kCdOpen.size(), kCdOpen) == 0) { + opened_ = true; + drop += kCdOpen.size(); + } + buf_.erase(0, drop); + head_ = true; + } + if (buf_.size() > kTail) { + const size_t k = buf_.size() - kTail; + emit(buf_.data(), k, out); + buf_.erase(0, k); + } + } + + void finish(bool partial, std::string& out) { + std::string_view v(buf_); + if (!head_) { + if (newlines_) v = strip_trailing_newline(strip_leading_newline(v)); + if (cdata_) unwrap_cdata(v, partial); + } else { + if (newlines_) v = strip_trailing_newline(v); + if (opened_) { + if (v.size() >= kCdClose.size() && + v.compare(v.size() - kCdClose.size(), kCdClose.size(), kCdClose) == 0) { + v.remove_suffix(kCdClose.size()); + } else if (partial) { + size_t hold = 0; + while (hold + 1 < kCdClose.size() && v.size() > hold && + v[v.size() - 1 - hold] == ']') + ++hold; + v.remove_suffix(hold); + } + } + } + emit(v.data(), v.size(), out); + if (bs_) { out += '\\'; bs_ = false; } + buf_.clear(); + } + + size_t held() const { return buf_.size() + (bs_ ? 1 : 0); } + +private: + void emit(const char* p, size_t n, std::string& out) { + if (n == 0) return; + if (mode_ == String) { json_escape_into(out, p, n); return; } + if (!raw_started_) { + raw_started_ = true; + container_ = p[0] == '[' || p[0] == '{'; + } + if (!container_) { out.append(p, n); return; } + for (size_t i = 0; i < n; ++i) normalise(p[i], out); + } + + /* Python-style quoting to JSON, one character at a time: a single-quoted string becomes a + * double-quoted one, with the quotes inside it re-escaped to match. A backslash is held until + * the character after it arrives, since the pair is read together. */ + void normalise(char c, std::string& out) { + if (bs_) { + bs_ = false; + if (in_single_) { + if (c == '\'') { out += '\''; return; } + if (c == '"') { out += "\\\""; return; } + out += '\\'; out += c; return; + } + if (in_double_) { out += '\\'; out += c; return; } + out += '\\'; + /* Outside a string the backslash stands alone and the next character is read + * normally. */ + } else if (c == '\\') { + bs_ = true; + return; + } + if (c == '"') { + if (in_single_) out += "\\\""; + else { in_double_ = !in_double_; out += '"'; } + } else if (c == '\'') { + if (in_double_) out += '\''; + else if (in_single_) { in_single_ = false; out += '"'; } + else { in_single_ = true; out += '"'; } + } else { + out += c; + } + } + + Mode mode_ = String; + bool cdata_ = true, newlines_ = true; + std::string buf_; + bool head_ = false, opened_ = false; + bool raw_started_ = false, container_ = false; + bool in_single_ = false, in_double_ = false, bs_ = false; +}; + +/* ================================================================== the answer text + * + * Content is trimmed at the end: trailing spaces and newlines, then one turn terminator. Trimming + * the END of a stream means holding what might be the end -- the trailing whitespace, and a + * terminator or the part of one that has arrived -- until something that is not whitespace + * follows it. The terminator automaton tracks the longest suffix that could still become one. */ +class ContentOut { +public: + void init(const Dfa* terms, const std::vector* list) { terms_ = terms; list_ = list; } + + void add(const char* p, size_t n, std::string& full) { + for (size_t i = 0; i < n; ++i) { + const unsigned char c = (unsigned char)p[i]; + if (c == ' ' || c == '\n') { + if (ws_ == 0) + term_ = terms_ && terms_->word(ts_) >= 0 ? terms_->depth(ts_) : 0; + ++ws_; + } else { + ws_ = 0; + } + if (terms_) ts_ = terms_->step(ts_, c); + } + pend_.append(p, n); + const size_t hold = ws_ ? ws_ + term_ : (terms_ ? terms_->depth(ts_) : 0); + if (pend_.size() > hold) { + full.append(pend_, 0, pend_.size() - hold); + pend_.erase(0, pend_.size() - hold); + } + } + + /* The exact trim: trailing spaces and newlines, then the first terminator in the list that + * ends what is left. */ + void finish(std::string& full) { + while (!pend_.empty() && (pend_.back() == '\n' || pend_.back() == ' ')) pend_.pop_back(); + if (list_) + for (const std::string& t : *list_) + if (!t.empty() && pend_.size() >= t.size() && + pend_.compare(pend_.size() - t.size(), t.size(), t) == 0) { + pend_.erase(pend_.size() - t.size()); + break; + } + full += pend_; + pend_.clear(); + } + + size_t held_space() const { return std::min(ws_, pend_.size()); } + size_t held_other() const { return pend_.size() - held_space(); } + +private: + const Dfa* terms_ = nullptr; + const std::vector* list_ = nullptr; + std::string pend_; + size_t ws_ = 0, term_ = 0; + uint16_t ts_ = 0; +}; + +} /* namespace */ + +/* ================================================================== the compiled format */ + +struct ReplyFormat::Impl { + ChatFormat f; + /* Each tag split into its core and the whitespace around it that is optional to match. */ + std::string open_core, open_trail, close_core, close_trail, ns_core, ns_trail, end_core, + end_trail, co_core, co_trail; + /* What begins a call in content. The first is the format's own opener: call_open's core, or + * name_prefix when calls are not wrapped. A wrapped format also takes name_prefix alone, + * second: a model writes the call without its wrapper often enough that its calls must not + * be lost to it, and a wrapper written without its trailing whitespace is read too. */ + std::vector openers; + std::string name_end; /* what ends an argument name */ + /* The same two, whitespace-trimmed. A loose call is one the grammar never opened, so the + * model wrote it unconstrained, and its argument tags are read with the whitespace around + * them optional -- as its name and its close are. */ + std::string name_end_core, value_core; + Dfa think, think_breaks, text, arg_name, value, junk, arg_name_loose, value_loose; + size_t longest = 0; /* the longest delimiter */ +}; + +ReplyFormat::ReplyFormat() : impl_(std::make_unique()) {} +ReplyFormat::~ReplyFormat() = default; +const ChatFormat& ReplyFormat::format() const { return impl_->f; } + +static void split_ws(const std::string& tag, std::string* core, std::string* trail) { + size_t a = 0, b = tag.size(); + while (a < b && is_ws((unsigned char)tag[a])) ++a; + while (b > a && is_ws((unsigned char)tag[b - 1])) --b; + *core = tag.substr(a, b - a); + *trail = tag.substr(b); +} + +int ReplyFormat::compile(const ChatFormat& f, std::shared_ptr* out, + std::string* why) { + const int st = chat_format_check(f, why); + if (st < 0) return st; + std::shared_ptr r(new ReplyFormat()); + Impl& m = *r->impl_; + m.f = f; + split_ws(f.reasoning_open, &m.open_core, &m.open_trail); + split_ws(f.reasoning_close, &m.close_core, &m.close_trail); + split_ws(f.name_suffix, &m.ns_core, &m.ns_trail); + split_ws(f.call_end, &m.end_core, &m.end_trail); + split_ws(f.call_open, &m.co_core, &m.co_trail); + if (f.call_open.empty()) m.openers = { f.name_prefix }; + else m.openers = { m.co_core, f.name_prefix }; + m.name_end = f.arg_name_suffix.empty() ? f.arg_value_prefix : f.arg_name_suffix; + + if (f.has_reasoning()) { + m.think.build({ m.close_core }); + std::vector b{ m.close_core }; + for (const std::string& s : f.reasoning_breaks) b.push_back(s); + m.think_breaks.build(b); + } + if (f.has_tools()) { + m.text.build(m.openers); + m.arg_name.build({ m.name_end }); + m.value.build({ f.arg_value_suffix }); + std::string trail; + split_ws(m.name_end, &m.name_end_core, &trail); + split_ws(f.arg_value_suffix, &m.value_core, &trail); + m.arg_name_loose.build({ m.name_end_core }); + m.value_loose.build({ m.value_core }); + m.junk.build({ f.arg_prefix, m.end_core }); + } + const std::string* const delims[] = { &f.reasoning_open, &f.reasoning_close, &f.call_open, + &f.call_close, &f.name_prefix, &f.name_suffix, + &f.call_end, &f.arg_prefix, &m.name_end, + &f.arg_value_suffix }; + for (const std::string* s : delims) m.longest = std::max(m.longest, s->size()); + for (const std::string& s : f.reasoning_breaks) m.longest = std::max(m.longest, s.size()); + *out = std::move(r); + return RAD_OK; +} + +/* ================================================================== the bound request */ + +namespace { +struct Param { + bool typed = false; /* read as JSON when it parses as JSON */ +}; +struct Tool { + std::string name; + std::unordered_map params; + /* The declared names in the order the grammar tries them: required ones, then the rest, + * each in schema order. */ + std::vector arms; + bool has_props = false; + bool has_required = false; +}; +} /* namespace */ + +struct ReplyParser::Impl { + std::shared_ptr fmt; + ReplyOptions opt; + std::string tail; /* the part of the generation prompt the reply continues */ + bool calls = false; /* the request sent tools and the format has calls */ + bool breaks = false; /* an unclosed reasoning block ends at a call */ + bool pure = false; /* no reasoning, calls or document: every byte is content */ + std::vector tools; + std::unordered_map by_name; + std::vector terminators; + Dfa terms; +}; + +ReplyParser::ReplyParser() : impl_(std::make_unique()) {} +ReplyParser::~ReplyParser() = default; +const ChatFormat& ReplyParser::format() const { return impl_->fmt->format(); } + +size_t ReplyParser::hold_bound() const { + size_t term = 0; + for (const std::string& t : impl_->terminators) term = std::max(term, t.size()); + return impl_->fmt->impl().longest + std::max(term, kFenceOpen.size()) + ValueOut::kHead + 1 + + 3 * 3; +} + +/* Read the tools the way the grammar generator reads them, so a name or a type means the same + * thing to the parser as to the grammar that constrained the reply. */ +static int bind_tools(const ReplyFormat::Impl& F, const ojson& tools, ReplyParser::Impl* P, + std::string* why) { + for (const auto& tool : tools) { + if (!tool.is_object() || !tool.contains("type") || tool.at("type") != "function" || + !tool.contains("function")) + continue; + try { + const auto& func = tool.at("function"); + Tool t; + t.name = func.at("name").get(); + auto params = func.contains("parameters") ? func.at("parameters") : ojson::object(); + const auto properties = params.contains("properties") ? params.at("properties") + : ojson::object(); + std::set required; + if (params.contains("required")) params.at("required").get_to(required); + common_schema_info info; + info.resolve_refs(params); + std::vector optional; + for (const auto& [pname, pschema] : properties.items()) { + Param p; + p.typed = F.f.other_value == ChatValue::Json && !info.resolves_to_string(pschema); + t.has_props = true; + if (required.count(pname)) { + t.has_required = true; + t.arms.push_back(pname); + } else { + optional.push_back(pname); + } + /* A name the argument's own delimiter could end early would be read as a + * different name. */ + const std::string probe = pname + F.name_end; + if (probe.find(F.name_end) != pname.size()) { + *why = "parameter '" + pname + "' of tool '" + t.name + "' contains '" + + F.name_end + "', which this model's tool-call format uses to end an " + "argument name"; + return RAD_E_INVAL; + } + t.params.emplace(pname, p); + } + t.arms.insert(t.arms.end(), optional.begin(), optional.end()); + if (t.name.find(F.ns_core) != std::string::npos || + (t.name + F.f.name_suffix).find(F.f.name_suffix) != t.name.size()) { + *why = "tool '" + t.name + "' has a name containing '" + F.ns_core + + "', which this model's tool-call format uses to end a function name"; + return RAD_E_INVAL; + } + if (!P->by_name.count(t.name)) P->by_name.emplace(t.name, P->tools.size()); + P->tools.push_back(std::move(t)); + } catch (const std::exception& e) { + *why = std::string("a tool definition could not be read: ") + e.what(); + return RAD_E_INVAL; + } + } + return RAD_OK; +} + +int ReplyParser::create(std::shared_ptr fmt, const ReplyOptions& opt, + std::shared_ptr* out, std::string* why) { + std::string dummy; + if (!why) why = &dummy; + if (!fmt) { *why = "no reply format"; return RAD_E_INVAL; } + std::shared_ptr r(new ReplyParser()); + Impl& P = *r->impl_; + const ReplyFormat::Impl& F = fmt->impl(); + P.fmt = fmt; + P.opt = opt; + P.opt.tools = nullptr; + + const bool want_calls = opt.tools && opt.tools->is_array() && !opt.tools->empty(); + if (want_calls && !F.f.has_tools()) { + *why = "this model's reply format has no tool calls"; + return RAD_E_UNSUPPORTED; + } + if (want_calls) { + const int st = bind_tools(F, *opt.tools, &P, why); + if (st < 0) return st; + } + /* A response format replaces the call grammar outright; the calls are not parsed. */ + P.calls = want_calls && !opt.response_format; + P.breaks = want_calls && F.f.has_reasoning() && !F.f.reasoning_breaks.empty(); + P.pure = !F.f.has_reasoning() && !want_calls && !opt.response_format; + + if (F.f.has_reasoning()) { + switch (F.f.reasoning_in_prompt) { + case ChatThink::FromPrompt: + if (!F.f.reasoning_open.empty() && !opt.generation_prompt.empty()) { + const size_t at = opt.generation_prompt.find(F.f.reasoning_open); + if (at != std::string::npos) P.tail = opt.generation_prompt.substr(at); + } + break; + case ChatThink::Always: P.tail = F.f.reasoning_open; break; + case ChatThink::Never: break; + } + } + for (const std::string& t : opt.terminators) + if (!t.empty()) P.terminators.push_back(t); + P.terms.build(P.terminators); + *out = std::move(r); + return RAD_OK; +} + +/* ================================================================== the stream */ + +namespace { +enum class St : uint8_t { + LeadWs, /* whitespace before the reply proper: dropped */ + ThinkOpen, /* the core of reasoning_open */ + ThinkOpenWs, /* the optional whitespace that ends reasoning_open */ + Think, /* reasoning text */ + ThinkCloseWs, /* the optional whitespace that ends reasoning_close */ + Text, /* content, watching for the call opener when calls are on */ + OpenCoTail, /* the whitespace that ends call_open, after its core */ + OpenWs, /* after call_open: whitespace */ + OpenPrefix, /* name_prefix, after call_open */ + OpenName, /* the function name, to the core of name_suffix */ + OpenTail, /* the whitespace that ends name_suffix */ + OpenPeek, /* a loose call's name is read: whitespace, then an argument or the close */ + OpenPeekArg, /* ... and the first argument's name, which must close as a name */ + Body, /* inside a call: whitespace, then an argument or the call's end */ + BodyLit, /* arg_prefix or call_end */ + ArgName, /* an argument name, to its end */ + ValText, /* a string (or raw) value, to arg_value_suffix */ + ValJson, /* a JSON-typed value */ + ValJsonEnd, /* arg_value_suffix, exactly, after a complete JSON value */ + EndTail, /* the whitespace that ends call_end */ + Junk, /* text inside a call that is no argument: content */ + AfterEnd, /* after call_end: whitespace, then call_close */ + AfterEndLit, /* call_close */ + AfterCall, /* after a call: whitespace, dropped */ + RfWs, /* before the document: whitespace, dropped */ + RfFence, /* "```json" */ + RfFenceWs, /* whitespace after the fence, dropped */ + RfJson, /* the document */ + RfClose, /* "```" */ + RfEnd, /* after the closing fence */ + RfRaw, /* a reply that is not the document it was asked for: content */ +}; + +/* A function name the grammar does not know is still read as a call, up to this long. */ +constexpr size_t kMaxLooseName = 1024; +/* And what a loose opener may hold in all before it is known to be a call. */ +constexpr size_t kMaxLooseHold = 2 * kMaxLooseName; +} /* namespace */ + +struct ReplyStream::Impl { + const ReplyParser::Impl& P; + const ReplyFormat::Impl& F; + explicit Impl(const ReplyParser::Impl& p) : P(p), F(p.fmt->impl()) { + content.init(P.terminators.empty() ? nullptr : &P.terms, &P.terminators); + st = P.pure ? St::Text : St::LeadWs; + } + + ReplyMessage msg; + ContentOut content; + bool think_text = false; /* the reasoning has had a non-blank byte */ + std::string think_pend; /* its leading blanks, until then */ + std::vector* out = nullptr; + + St st; + bool strict = true, finished = false, fed_tail = false; + bool post_call = false; /* content after a call */ + + /* delimiter scan */ + uint16_t ds = 0; + std::string hold; + /* literal match */ + std::string lhold; + size_t lpos = 0, trail = 0; + /* a call being opened */ + St origin = St::Text; + /* LOOSE: opened by what the format's grammar does not open a call with -- name_prefix alone, + * or call_open without its trailing whitespace. Such an opener is also ordinary text often + * enough ("the `` syntax") that it becomes a call only once what follows the + * name tag is an argument or the call's close; until then it is held, and if it is not a + * call it is content, as the grammar says, and the reply is still within it. WRAPPED: the + * call was opened with call_open, so its close is followed by call_close. */ + bool loose = false, wrapped = false; + size_t tag_end = 0; /* where a loose call's name tag ends in `att` */ + bool name_lt = false; /* a loose call's argument name holds a '<' */ + std::string att, name; + int tool = -1; + /* the open call */ + size_t argc = 0, calls = 0; + int depth = 0; /* unclosed braces in the arguments so far */ + bool in_str = false, esc = false; + const Param* param = nullptr; + /* a value */ + ValueOut val; + ValueOut::Mode vmode = ValueOut::String; + JsonScan js; + std::string vheld; + size_t vs_pos = 0; + bool fenced = false; + + /* published offsets, for the deltas */ + size_t sent_r = 0, sent_c = 0, sent_a = 0; + int cur = -1; /* the channel last published: 0 r, 1 c, 2 args */ + + /* bytes to read again, ahead of the rest */ + struct Seg { const char* p; size_t n; }; + std::vector stack; + std::deque owned; + std::string refeed; + + void lenient() { strict = false; } + + /* ------------------------------------------------------------ output channels */ + + void event(ReplyEvent::Kind k, uint32_t call, std::string_view text) { + if (!out) return; + if ((k == ReplyEvent::Reasoning || k == ReplyEvent::Content || k == ReplyEvent::CallArgs) && + !out->empty() && out->back().kind == k && out->back().call == call) { + out->back().text.append(text); + return; + } + ReplyEvent e; + e.kind = k; + e.call = call; + e.text.assign(text); + out->push_back(std::move(e)); + } + + void publish(int ch, bool all) { + std::string* s; size_t* sent; ReplyEvent::Kind k; uint32_t call = 0; + if (ch == 0) { s = &msg.reasoning; sent = &sent_r; k = ReplyEvent::Reasoning; } + else if (ch == 1) { s = &msg.content; sent = &sent_c; k = ReplyEvent::Content; } + else { + if (msg.calls.empty()) return; + s = &msg.calls.back().arguments; sent = &sent_a; k = ReplyEvent::CallArgs; + call = (uint32_t)msg.calls.size() - 1; + } + const size_t end = all ? s->size() : s->size() - utf8_tail(*s, *sent); + if (end > *sent) { + event(k, call, std::string_view(*s).substr(*sent, end - *sent)); + *sent = end; + } + } + + void touch(int ch) { + if (cur != ch && cur >= 0) publish(cur, false); + cur = ch; + } + + void think_out(const char* p, size_t n) { + if (n == 0) return; + touch(0); + if (think_text) { msg.reasoning.append(p, n); return; } + for (size_t i = 0; i < n; ++i) + if (!is_blank((unsigned char)p[i])) { think_text = true; break; } + think_pend.append(p, n); + if (think_text) { msg.reasoning += think_pend; think_pend.clear(); } + } + + void text_out(const char* p, size_t n) { + if (n == 0) return; + if (post_call && (!F.f.call_open.empty() || !P.opt.parallel_tool_calls)) lenient(); + touch(1); + content.add(p, n, msg.content); + } + + void args_out(std::string_view s) { + std::string& a = msg.calls.back().arguments; + for (char ch : s) { + if (esc) { esc = false; continue; } + if (ch == '\\' && in_str) { esc = true; continue; } + if (ch == '"') { in_str = !in_str; continue; } + if (!in_str) { if (ch == '{') ++depth; else if (ch == '}') --depth; } + } + touch(2); + a.append(s); + } + + /* The value encoder writes into a scratch string; the arguments see it through args_out so + * the brace count stays right. */ + std::string scratch; + void flush_scratch() { if (!scratch.empty()) { args_out(scratch); scratch.clear(); } } + + /* ------------------------------------------------------------ scanning */ + + /* Scan text under `d` from the current state, handing plain text to `sink`. Returns the + * position after a matched delimiter with *hit its index, or `e` with *hit = -1. */ + template + const char* scan(const Dfa& d, const char* p, const char* e, int* hit, Sink&& sink) { + *hit = -1; + while (p < e) { + if (ds == 0) { + const char* q = d.skip(p, e); + if (q > p) sink(p, (size_t)(q - p)); + p = q; + if (p == e) break; + } + const unsigned char c = (unsigned char)*p++; + const uint16_t ns = d.step(ds, c); + const size_t keep = d.depth(ns); + const size_t win = hold.size() + 1; + if (keep < win) { + const size_t rel = win - keep; + if (rel <= hold.size()) { + sink(hold.data(), rel); + hold.erase(0, rel); + hold.push_back((char)c); + } else { + if (!hold.empty()) sink(hold.data(), hold.size()); + hold.clear(); + const char cc = (char)c; + sink(&cc, 1); + } + } else { + hold.push_back((char)c); + } + ds = ns; + if (d.word(ds) >= 0) { + *hit = d.word(ds); + ds = 0; + hold.clear(); + return p; + } + } + return p; + } + + void read_again(std::string_view bytes) { refeed.append(bytes); } + + /* ------------------------------------------------------------ calls */ + + bool declared_prefix(std::string_view n) const { + for (const Tool& t : P.tools) { + const std::string full = t.name + F.f.name_suffix; + if (full.size() >= n.size() && full.compare(0, n.size(), n) == 0) return true; + } + return false; + } + + /* The call opener has matched at `att`; whether a call follows is decided below. */ + void begin_attempt(St from) { + origin = from; + name.clear(); + tool = -1; + lpos = 0; + loose = false; + wrapped = !F.f.call_open.empty(); + if (!P.calls) { fail_attempt(); return; } + st = F.f.call_open.empty() ? St::OpenName : St::OpenWs; + } + + /* An opener matched in content. In a wrapped format the first is call_open's core, whose + * trailing whitespace decides whether the grammar opened a call; the second is name_prefix + * without the wrapper, which is always loose. */ + void begin_text_attempt(int which) { + origin = St::Text; + name.clear(); + tool = -1; + lpos = 0; + trail = 0; + att = F.openers[(size_t)which]; + if (F.f.call_open.empty()) { + loose = false; + wrapped = false; + st = St::OpenName; + } else if (which == 0) { + loose = false; + wrapped = true; + st = St::OpenCoTail; + } else { + loose = true; + wrapped = false; + st = St::OpenName; + } + } + + /* The whitespace a loose opener may be followed by: whatever sorts at or below a space, as a + * model's stray control characters do. */ + static bool loose_ws(unsigned char c) { return c <= ' '; } + + /* Not a call after all: the opener's first byte is text of the region it was found in, and + * everything after it is read again from there. */ + void fail_attempt() { + /* The grammar committed to a call at its own opener, so a call that does not follow + * leaves it; a loose opener that turns out to be text is text, within it. */ + if (!loose) lenient(); + loose = false; + st = origin; + ds = 0; + hold.clear(); + if (origin == St::Think) think_out(att.data(), 1); + else text_out(att.data(), 1); + read_again(std::string_view(att).substr(1)); + att.clear(); + } + + void begin_call(bool exact) { + if (!exact || tool < 0) lenient(); + if (!P.opt.parallel_tool_calls && calls > 0) lenient(); + if (cur >= 0) publish(cur, false); + if (cur == 2) publish(2, true); + const std::string_view nm = trim_trailing_ws(std::string_view(name).substr( + 0, name.size() - F.ns_core.size())); + ReplyCall c; + c.name.assign(nm); + msg.calls.push_back(std::move(c)); + sent_a = 0; + cur = -1; + event(ReplyEvent::CallBegin, (uint32_t)msg.calls.size() - 1, msg.calls.back().name); + depth = 0; in_str = false; esc = false; + args_out("{"); + argc = 0; + ++calls; + att.clear(); + post_call = false; + st = St::Body; + } + + /* The core of call_end has matched. The whitespace the format writes after it is part of the + * tag, so the call closes when that has arrived too -- a reply that ends in between leaves the + * call open, as the grammar does -- and a reply that goes straight on without it has closed + * the call all the same. */ + void end_core_done() { + trail = 0; + if (F.end_trail.empty() || loose) end_call(); + else st = St::EndTail; + } + + /* The call's close tag: the arguments object is closed with as many braces as it has open + * outside strings. A string-typed value is always closed by its own suffix before this can + * match, so no quote is ever pending here; a raw value that left a string open is passed + * through as the model wrote it. */ + void end_call() { + std::string close((size_t)std::max(depth, 0), '}'); + args_out(close); + publish(2, true); + msg.calls.back().closed = true; + event(ReplyEvent::CallEnd, (uint32_t)msg.calls.size() - 1, {}); + cur = -1; + lpos = 0; + lhold.clear(); + if (F.f.call_open.empty()) st = St::AfterCall; + else if (wrapped) st = St::AfterEnd; + else after_loose_call(); + } + + /* A loose call whose argument name runs into a tag was a call only as far as its arguments + * before it: the call ends there, and the argument's opener and all after it are content. */ + void end_loose_call_at_arg(bool closed_name) { + std::string replay = F.f.arg_prefix + name; + if (closed_name) replay += name_end(); + name.clear(); + name_lt = false; + wrapped = false; + end_call(); + read_again(replay); + } + + /* After a loose call the text goes on as content, whitespace included: the grammar never + * opened the call, so nothing of its punctuation claims the spacing around it. */ + void after_loose_call() { + loose = false; + post_call = true; + ds = 0; + hold.clear(); + st = St::Text; + } + + const Tool* cur_tool() const { + return tool >= 0 ? &P.tools[(size_t)tool] : nullptr; + } + + /* The argument name is complete. */ + void begin_value() { + const std::string_view nm = trim_arg_name( + std::string_view(name).substr(0, name.size() - name_end().size())); + std::string key = argc > 0 ? "," : ""; + key += json_quote(nm); + key += ':'; + args_out(key); + ++argc; + param = nullptr; + if (const Tool* t = cur_tool()) { + auto it = t->params.find(std::string(nm)); + /* The grammar binds a declared name to its own arm by the raw spelling; a name that + * only trims to a declared one is read by the generic arm, as text. */ + if (it != t->params.end() && nm.size() + name_end().size() == name.size()) + param = &it->second; + } + name.clear(); + if (param && param->typed) { + js.reset(); + vheld.clear(); + st = St::ValJson; + } else { + start_text_value(ValueOut::String); + } + } + + /* What ends an argument name and a value in the call being read: the tags as the format + * writes them, or their cores in a loose call. */ + const std::string& name_end() const { return loose ? F.name_end_core : F.name_end; } + const std::string& value_suffix() const { return loose ? F.value_core : F.f.arg_value_suffix; } + + /* A CDATA section is punctuation around any value the format lets carry one, typed or not. */ + bool cdata() const { return F.f.string_value == ChatValue::Cdata; } + + void start_text_value(ValueOut::Mode m) { + vmode = m; + val.begin(m, cdata(), F.f.value_newlines, scratch); + flush_scratch(); + ds = 0; + hold.clear(); + st = St::ValText; + } + + /* A JSON-typed value that parsed and then met its suffix: the value is the JSON text and the + * whitespace after it. */ + void json_value_done(std::string_view text) { + val.begin(ValueOut::Raw, cdata(), F.f.value_newlines, scratch); + val.add(text.data(), text.size(), scratch); + val.finish(false, scratch); + flush_scratch(); + } + + /* ------------------------------------------------------------ the machine + * + * One step consumes at least one byte, or queues bytes to be read again. */ + const char* step(const char* p, const char* e) { + int hit = -1; + switch (st) { + case St::LeadWs: + while (p < e && is_ws((unsigned char)*p)) ++p; + if (p < e) st = after_lead(); + return p; + + case St::ThinkOpen: { + const unsigned char c = (unsigned char)*p; + if (lpos < F.open_core.size() && (unsigned char)F.open_core[lpos] == c) { + lhold.push_back((char)c); + if (++lpos == F.open_core.size()) { lhold.clear(); trail = 0; st = St::ThinkOpenWs; } + return p + 1; + } + /* No block: what was held is read again as whatever follows one. */ + st = after_think(); + read_again(lhold); + lhold.clear(); + return p; + } + + case St::ThinkOpenWs: + if (trail >= F.open_trail.size()) { st = St::Think; ds = 0; hold.clear(); return p; } + if (*p == F.open_trail[trail]) { ++trail; return p + 1; } + ++trail; + return p; + + case St::Think: { + const Dfa& d = P.breaks ? F.think_breaks : F.think; + p = scan(d, p, e, &hit, [this](const char* q, size_t n) { think_out(q, n); }); + if (hit == 0) { trail = 0; st = St::ThinkCloseWs; } + else if (hit > 0) { att = d.pattern(hit); begin_attempt(St::Think); } + return p; + } + + case St::ThinkCloseWs: + if (trail >= F.close_trail.size()) { st = after_think(); return p; } + if (*p == F.close_trail[trail]) { ++trail; return p + 1; } + ++trail; + return p; + + case St::Text: + if (!P.calls) { + text_out(p, (size_t)(e - p)); + return e; + } + p = scan(F.text, p, e, &hit, [this](const char* q, size_t n) { text_out(q, n); }); + if (hit >= 0) begin_text_attempt(hit); + return p; + + case St::OpenCoTail: + if (trail < F.co_trail.size() && *p == F.co_trail[trail]) { + att.push_back(*p); + if (++trail == F.co_trail.size()) st = St::OpenWs; + return p + 1; + } + /* call_open's core without its whitespace: a loose opener. */ + loose = trail < F.co_trail.size(); + st = St::OpenWs; + return p; + + case St::OpenWs: + if (loose) { + while (p < e && loose_ws((unsigned char)*p)) att.push_back(*p++); + } else { + while (p < e && is_ws((unsigned char)*p)) att.push_back(*p++); + } + if (p < e) { lpos = 0; st = St::OpenPrefix; } + return p; + + case St::OpenPrefix: { + const char c = *p; + att.push_back(c); + if (c != F.f.name_prefix[lpos]) { fail_attempt(); return p + 1; } + if (++lpos == F.f.name_prefix.size()) { name.clear(); st = St::OpenName; } + return p + 1; + } + + case St::OpenName: { + const char c = *p; + att.push_back(c); + name.push_back(c); + const size_t k = F.ns_core.size(); + if (name.size() >= k && name.compare(name.size() - k, k, F.ns_core) == 0) { + const std::string nm = name.substr(0, name.size() - k); + auto it = P.by_name.find(nm); + tool = it == P.by_name.end() ? -1 : (int)it->second; + if (tool < 0 && (nm.empty() || nm.find('<') != std::string::npos)) { + fail_attempt(); + return p + 1; + } + /* The call exists from the moment its opening tag is complete: a reply that ends + * right there is a call with no arguments yet. A loose call waits for what + * follows the tag. */ + trail = 0; + lpos = 0; + lhold.clear(); + tag_end = att.size(); + if (loose) st = St::OpenPeek; + else if (F.ns_trail.empty()) begin_call(true); + else st = St::OpenTail; + return p + 1; + } + if (name.size() > kMaxLooseName || (c == '<' && !declared_prefix(name))) { + fail_attempt(); + return p + 1; + } + return p + 1; + } + + case St::OpenTail: + if (trail < F.ns_trail.size() && *p == F.ns_trail[trail]) { + att.push_back(*p); + if (++trail == F.ns_trail.size()) begin_call(true); + return p + 1; + } + begin_call(trail == F.ns_trail.size()); + return p; + + case St::OpenPeek: { + if (lpos == 0) { + while (p < e && loose_ws((unsigned char)*p) && att.size() <= kMaxLooseHold) + att.push_back(*p++); + if (att.size() > kMaxLooseHold) { fail_attempt(); return p; } + if (p == e) return p; + } + const char c = *p; + att.push_back(c); + const std::string& ap = F.f.arg_prefix; + const std::string& fc = F.end_core; + const bool a_ok = lpos < ap.size() && ap[lpos] == c && ap.compare(0, lpos, lhold) == 0; + const bool f_ok = lpos < fc.size() && fc[lpos] == c && fc.compare(0, lpos, lhold) == 0; + if (!a_ok && !f_ok) { fail_attempt(); return p + 1; } + lhold.push_back(c); + ++lpos; + if (a_ok && lpos == ap.size()) { + lhold.clear(); + st = St::OpenPeekArg; + } else if (f_ok && lpos == fc.size()) { + begin_call(false); + end_call(); + } + return p + 1; + } + + case St::OpenPeekArg: { + /* The first argument's name, which is where prose that merely looks like a call + * shows itself: a name that runs into a tag is no name. On one that closes, the call + * is read -- the bytes after the name tag replayed through the call itself. */ + const char c = *p; + att.push_back(c); + lhold.push_back(c); + const std::string& ne = F.name_end_core; + if (lhold.size() > kMaxLooseName) { fail_attempt(); return p + 1; } + if (lhold.size() >= ne.size() && + lhold.compare(lhold.size() - ne.size(), ne.size(), ne) == 0) { + const std::string_view nm(lhold.data(), lhold.size() - ne.size()); + if (nm.empty() || nm.find('<') != std::string_view::npos) { + fail_attempt(); + return p + 1; + } + const std::string replay = att.substr(tag_end); + lhold.clear(); + begin_call(false); + read_again(replay); + } + return p + 1; + } + + case St::Body: + while (p < e && is_ws((unsigned char)*p)) ++p; + if (p < e) { lpos = 0; lhold.clear(); st = St::BodyLit; } + return p; + + case St::BodyLit: { + const char c = *p; + const std::string& ap = F.f.arg_prefix; + const std::string& fc = F.end_core; + const bool a_ok = lpos < ap.size() && ap[lpos] == c && ap.compare(0, lpos, lhold) == 0; + const bool f_ok = lpos < fc.size() && fc[lpos] == c && fc.compare(0, lpos, lhold) == 0; + if (!a_ok && !f_ok) { + lenient(); + st = St::Junk; + ds = 0; + hold.clear(); + lhold.push_back(c); + read_again(lhold); + lhold.clear(); + return p + 1; + } + lhold.push_back(c); + ++lpos; + if (a_ok && lpos == ap.size()) { start_arg(); return p + 1; } + if (f_ok && lpos == fc.size()) { finish_call_strictness(); end_core_done(); return p + 1; } + return p + 1; + } + + case St::ArgName: + p = scan(loose ? F.arg_name_loose : F.arg_name, p, e, &hit, + [this](const char* q, size_t n) { + name.append(q, n); + if (loose && std::memchr(q, '<', n)) name_lt = true; + }); + if (name_lt) { end_loose_call_at_arg(hit >= 0); return p; } + if (hit >= 0) { name += name_end(); begin_value(); } + return p; + + case St::ValText: + p = scan(loose ? F.value_loose : F.value, p, e, &hit, [this](const char* q, size_t n) { + val.add(q, n, scratch); + flush_scratch(); + }); + if (hit >= 0) { + val.finish(false, scratch); + if (vmode == ValueOut::String) scratch += '"'; + flush_scratch(); + st = St::Body; + } + return p; + + case St::ValJson: { + for (; p < e; ++p) { + const unsigned char c = (unsigned char)*p; + const JsonScan::Res r = js.push(c); + if (r == JsonScan::More) { vheld.push_back((char)c); continue; } + if (r == JsonScan::Fail) { + /* Not JSON: the argument is its text, read again from its first byte. */ + vheld.push_back((char)c); + start_text_value(ValueOut::Raw); + read_again(vheld); + vheld.clear(); + return p + 1; + } + vs_pos = 0; + st = St::ValJsonEnd; + return p; + } + return p; + } + + case St::ValJsonEnd: { + const std::string& vs = value_suffix(); + const char c = *p; + vheld.push_back(c); + if (c == vs[vs_pos]) { + if (++vs_pos == vs.size()) { + json_value_done(std::string_view(vheld).substr(0, vheld.size() - vs.size())); + vheld.clear(); + st = St::Body; + } + return p + 1; + } + /* JSON followed by something else: the grammar reads the argument as text, all of + * it, from its first byte. */ + start_text_value(ValueOut::String); + read_again(vheld); + vheld.clear(); + return p + 1; + } + + case St::EndTail: + if (trail < F.end_trail.size() && *p == F.end_trail[trail]) { + if (++trail == F.end_trail.size()) end_call(); + return p + 1; + } + /* The close's own whitespace is missing: still the close, read leniently. */ + lenient(); + end_call(); + return p; + + case St::Junk: + p = scan(F.junk, p, e, &hit, [this](const char* q, size_t n) { text_out(q, n); }); + if (hit == 0) start_arg(); + else if (hit == 1) end_core_done(); + return p; + + case St::AfterEnd: + while (p < e && is_ws((unsigned char)*p)) ++p; + if (p < e) { + lpos = 0; + lhold.clear(); + st = F.f.call_close.empty() ? St::AfterCall : St::AfterEndLit; + } + return p; + + case St::AfterEndLit: { + const char c = *p; + if (c == F.f.call_close[lpos]) { + lhold.push_back(c); + if (++lpos == F.f.call_close.size()) { + lhold.clear(); + if (loose) after_loose_call(); + else st = St::AfterCall; + } + return p + 1; + } + lenient(); + if (loose) after_loose_call(); + else st = St::AfterCall; + read_again(lhold); + lhold.clear(); + return p; + } + + case St::AfterCall: + while (p < e && is_ws((unsigned char)*p)) ++p; + if (p < e) { post_call = true; ds = 0; hold.clear(); st = St::Text; } + return p; + + case St::RfWs: + while (p < e && is_ws((unsigned char)*p)) ++p; + if (p < e) { + if (*p == '`') { lpos = 0; lhold.clear(); st = St::RfFence; } + else { js.reset(); fenced = false; st = St::RfJson; } + } + return p; + + case St::RfFence: { + const char c = *p; + if (c == kFenceOpen[lpos]) { + lhold.push_back(c); + if (++lpos == kFenceOpen.size()) { lhold.clear(); st = St::RfFenceWs; } + return p + 1; + } + lenient(); + st = St::RfRaw; + read_again(lhold); + lhold.clear(); + return p; + } + + case St::RfFenceWs: + while (p < e && is_ws((unsigned char)*p)) ++p; + if (p < e) { js.reset(); fenced = true; st = St::RfJson; } + return p; + + case St::RfJson: { + const char* run = p; + for (; p < e; ++p) { + const JsonScan::Res r = js.push((unsigned char)*p); + if (r == JsonScan::More) continue; + text_out(run, (size_t)(p - run)); + if (r == JsonScan::Fail || !fenced) { lenient(); st = St::RfRaw; return p; } + lpos = 0; + lhold.clear(); + st = St::RfClose; + return p; + } + text_out(run, (size_t)(p - run)); + return p; + } + + case St::RfClose: { + const char c = *p; + if (c == kFenceClose[lpos]) { + lhold.push_back(c); + if (++lpos == kFenceClose.size()) { lhold.clear(); st = St::RfEnd; } + return p + 1; + } + lenient(); + st = St::RfRaw; + read_again(lhold); + lhold.clear(); + return p; + } + + case St::RfEnd: + lenient(); + st = St::RfRaw; + return p; + + case St::RfRaw: + text_out(p, (size_t)(e - p)); + return e; + } + return e; + } + + St after_lead() const { + if (F.f.has_reasoning() && P.opt.extract_reasoning) + return F.open_core.empty() ? St::Think : St::ThinkOpen; + return after_think(); + } + St after_think() const { return P.opt.response_format ? St::RfWs : St::Text; } + + /* An argument opener matched. The generic argument arm exists only for a tool that declares + * parameters; a tool that declares none takes none. */ + void start_arg() { + const Tool* t = cur_tool(); + if (t && !t->has_props) lenient(); + name.clear(); + name_lt = false; + ds = 0; + hold.clear(); + st = St::ArgName; + } + + /* The reply ended inside an argument name. A name is only a name once it is closed -- except + * that where the format writes nothing between a name and its value's own prefix + * (arg_name_suffix empty), the grammar's opening tag for a DECLARED argument is complete as + * soon as the declared name is: the reply `has_required && argc == 0) lenient(); + } + + /* ------------------------------------------------------------ driving */ + + void run(std::string_view in) { + stack.push_back({ in.data(), in.size() }); + while (!stack.empty()) { + Seg s = stack.back(); + stack.pop_back(); + const char* p = s.p; + const char* e = s.p + s.n; + while (p < e) { + p = step(p, e); + if (!refeed.empty()) { + if (p < e) stack.push_back({ p, (size_t)(e - p) }); + owned.push_back(std::move(refeed)); + refeed.clear(); + stack.push_back({ owned.back().data(), owned.back().size() }); + break; + } + } + } + owned.clear(); + } + + void feed_tail() { + if (fed_tail) return; + fed_tail = true; + if (!P.tail.empty()) run(P.tail); + } + + /* Would the grammar still be waiting for more, rather than have failed, on what an opener + * has held? Asked only at the end of the reply. */ + bool open_viable() const { + switch (st) { + case St::OpenWs: + case St::OpenPrefix: + return true; + case St::OpenName: + return declared_prefix(name); + case St::OpenTail: + return tool >= 0; + default: + return true; + } + } + + /* The reply ended inside a loose opener, so it was never a call: its bytes are content, read + * again from its second byte -- which may hold another opener, and so on. */ + bool in_loose_attempt() const { + switch (st) { + case St::OpenWs: case St::OpenPrefix: case St::OpenName: case St::OpenPeek: + case St::OpenPeekArg: + return loose; + default: + return false; + } + } + + void finish_all() { + while (in_loose_attempt()) { + fail_attempt(); + std::string again = std::move(refeed); + refeed.clear(); + run(again); + } + switch (st) { + case St::OpenWs: case St::OpenPrefix: case St::OpenName: case St::OpenTail: + if (!open_viable()) lenient(); + break; + case St::BodyLit: { + const Tool* t = cur_tool(); + const bool args_ok = !t || t->has_props; + const bool end_ok = !t || !t->has_required || argc > 0; + const bool a = args_ok && F.f.arg_prefix.compare(0, lhold.size(), lhold) == 0; + const bool f = end_ok && F.end_core.compare(0, lhold.size(), lhold) == 0; + if (t && !a && !f) lenient(); + break; + } + case St::ArgName: + finish_arg_name(); + break; + case St::ValText: + /* A partly-matched suffix at the end means the value itself was complete. */ + val.finish(hold.empty(), scratch); + flush_scratch(); + break; + case St::ValJson: + val.begin(ValueOut::Raw, cdata(), F.f.value_newlines, scratch); + val.add(vheld.data(), vheld.size(), scratch); + val.finish(true, scratch); + flush_scratch(); + break; + case St::ValJsonEnd: + json_value_done(std::string_view(vheld).substr(0, vheld.size() - vs_pos)); + break; + default: + break; + } + hold.clear(); + ds = 0; + if (!think_text) think_pend.clear(); + content.finish(msg.content); + if (cur >= 0) publish(cur, true); + publish(0, true); + publish(1, true); + publish(2, true); + } +}; + +ReplyStream::ReplyStream() = default; +ReplyStream::~ReplyStream() = default; + +std::unique_ptr ReplyParser::open() const { + std::unique_ptr s(new ReplyStream()); + s->impl_ = std::make_unique(*impl_); + return s; +} + +void ReplyStream::feed(std::string_view bytes, std::vector* out) { + Impl& m = *impl_; + if (m.finished) return; + m.out = out; + m.feed_tail(); + if (!bytes.empty()) m.run(bytes); + if (m.cur >= 0) m.publish(m.cur, false); + m.out = nullptr; +} + +void ReplyStream::finish(std::vector* out) { + Impl& m = *impl_; + if (m.finished) return; + m.out = out; + m.feed_tail(); + m.finish_all(); + m.finished = true; + m.out = nullptr; +} + +const ReplyMessage& ReplyStream::message() const { return impl_->msg; } +bool ReplyStream::strict() const { return impl_->strict; } + +ReplyHeld ReplyStream::held() const { + const Impl& m = *impl_; + ReplyHeld h; + h.delimiter = m.hold.size() + m.lhold.size() + m.val.held() + m.content.held_other() + + (m.msg.reasoning.size() - m.sent_r) + (m.msg.content.size() - m.sent_c) + + (m.msg.calls.empty() ? 0 : m.msg.calls.back().arguments.size() - m.sent_a); + h.space = m.content.held_space() + m.think_pend.size(); + h.structure = m.att.size() + m.name.size() + m.vheld.size(); + return h; +} + +ReplyMessage reply_parse(const ReplyParser& p, std::string_view text, bool* strict) { + std::unique_ptr s = p.open(); + s->feed(text, nullptr); + s->finish(nullptr); + if (strict) *strict = s->strict(); + return s->message(); +} + +} /* namespace rad */ diff --git a/core/text/chatparse.h b/core/text/chatparse.h new file mode 100644 index 00000000..6ae4496d --- /dev/null +++ b/core/text/chatparse.h @@ -0,0 +1,185 @@ +/* chatparse.h -- reading a model's reply back as it streams: reasoning, content, tool calls. + * + * ONE PASS, ONE PARSER. A reply is fed as it is generated, in pieces of any size, and every byte + * is examined a bounded number of times: the whole reply costs O(its length), whether it arrives + * in one piece or one byte at a time. Nothing is re-parsed, nothing is matched with a regular + * expression, and there is no second pass that repairs what the first one missed -- the malformed + * shapes a model actually writes are states of this machine, not fallbacks around it. + * + * It is driven by a ChatFormat (chatfmt.h) and built from three pieces: + * + * * DELIMITER RECOGNITION is a deterministic Aho-Corasick automaton over the delimiters that can + * end the current region -- "" and the call opener inside reasoning, the call opener + * in content, the value suffix inside a value. In the automaton's root state the scan skips + * straight to the next byte that can begin a delimiter (memchr for the common one-byte case), + * so a long run of prose or file content costs a memchr and a copy. + * * THE TAG STRUCTURE is a transducer over those regions: call opener, name, arguments, close. + * * A JSON-TYPED ARGUMENT is recognised by an incremental JSON scanner with an explicit stack. + * + * WHAT IT PRODUCES is exactly what the format's grammar says the reply means, including the + * places where the grammar is lenient on purpose: an argument the schema does not declare is + * still an argument, a non-string argument that is not valid JSON is taken as text, a reasoning + * block the model never closed ends where a call begins, prose before, between and after calls is + * content. Where the reply leaves the grammar altogether -- a call to a function that is not a + * tool, text inside a call, a missing close -- it recovers locally and says so (strict()). + * + * That includes a call written WITHOUT its wrapper. In a format whose calls are wrapped (Qwen's + * `\n`) the grammar, and constrained decoding with it, begins only at the wrapper, so a + * call the model writes as a bare ``, or with the wrapper run straight into it, is + * unconstrained -- and it is the one most likely to be lost. In content, name_prefix alone and + * call_open without its trailing whitespace also open a call, with every tag's surrounding + * whitespace optional inside it. Because such an opener is also ordinary text, it becomes a call + * only once the name tag is closed and an argument or the call's close follows; until then it is + * held (a bounded number of bytes), and if it is not a call it is content. + * + * THE STREAMING CONTRACT: what has been emitted is final. A delta is never taken back, so every + * emitted prefix of content, reasoning or arguments is a prefix of the finished value, and the + * concatenated deltas ARE the finished values. That forces some bytes to be held until their + * meaning is known, and the holds are bounded: + * + * * a possible delimiter prefix -- at most the longest delimiter, less one byte; + * * an unfinished UTF-8 sequence -- at most three bytes, because a delta goes into a JSON string; + * * whitespace whose fate depends on what follows -- the trailing whitespace of content, which + * is trimmed if nothing follows it, and the whitespace that opens a reasoning block, which is + * dropped if the block holds nothing else; + * * a tag's own name while it is being read, since a name is only a name once it is closed; + * * a JSON-typed argument value until its closing delimiter: `30` and `30 seconds` differ from + * their first byte (a number, or the string "30 seconds"), so the value is emitted whole once + * its type is known. A value that stops being JSON part-way is streamed as text from there. + * + * Streaming emits in the reply's order; a call's arguments are streamed as they are parsed. */ +#pragma once +#include "rad_internal.h" + +#include + +#include +#include +#include +#include +#include + +namespace rad { + +struct ChatFormat; + +/* One increment of a parsed reply. Consecutive increments of the same kind are merged. */ +struct ReplyEvent { + enum Kind : uint8_t { + Reasoning, /* text: a reasoning delta */ + Content, /* text: a content delta */ + CallBegin, /* text: the function name; `call` is the new call's index */ + CallArgs, /* text: an arguments delta for call `call` */ + CallEnd, /* call `call` closed */ + }; + Kind kind = Content; + uint32_t call = 0; + std::string text; +}; + +struct ReplyCall { + std::string name; + std::string arguments; /* JSON text, as the OpenAI API carries it */ + bool closed = false; +}; + +/* A reply, taken apart. After finish() it is the whole reply; before, what has been emitted. */ +struct ReplyMessage { + std::string content; + std::string reasoning; + std::vector calls; +}; + +/* What held bytes are waiting on, by kind. See the header comment for the bound on each. */ +struct ReplyHeld { + size_t delimiter = 0; /* a possible delimiter prefix, and an unfinished UTF-8 sequence */ + size_t space = 0; /* whitespace that may yet be trimmed */ + size_t structure = 0; /* a tag name being read, or a JSON value awaiting its type */ +}; + +/* The per-request inputs. */ +struct ReplyOptions { + /* The assistant prefix the template already rendered. It decides whether the reply starts + * inside a reasoning block (ChatFormat::reasoning_in_prompt). */ + std::string generation_prompt; + /* reasoning_format "none" keeps a reasoning block inline in the content. */ + bool extract_reasoning = true; + /* The request's tools, OpenAI-shaped; null or empty parses no calls, and call syntax in the + * reply is then content. Read once, when the parser is created. */ + const nlohmann::ordered_json* tools = nullptr; + bool parallel_tool_calls = true; + /* A response_format was requested: the reply is one JSON document, optionally fenced as + * ```json ... ```, and the document is the content. */ + bool response_format = false; + /* The model's turn terminators. The decoder renders one only when the format needs it, and + * one left on the end of content is not part of the answer. */ + std::vector terminators; +}; + +class ReplyStream; + +/* A format compiled once: its automata and its delimiters. Shared by every request. */ +class ReplyFormat { +public: + ~ReplyFormat(); + /* RAD_OK, or RAD_E_UNSUPPORTED with *why when chat_format_check refuses the format. */ + static int compile(const ChatFormat& f, std::shared_ptr* out, + std::string* why); + const ChatFormat& format() const; + + struct Impl; + const Impl& impl() const { return *impl_; } +private: + ReplyFormat(); + std::unique_ptr impl_; +}; + +/* One request's parser: the format bound to the tools the request sent and the prompt it + * rendered. Immutable once made; each choice opens its own stream from it. */ +class ReplyParser { +public: + ~ReplyParser(); + /* RAD_OK, or RAD_E_INVAL with *why when a tool cannot be read unambiguously in this format -- + * a function or parameter name containing the delimiter that ends it -- and + * RAD_E_UNSUPPORTED when the request sends tools and the format has no tool calls. */ + static int create(std::shared_ptr fmt, const ReplyOptions& opt, + std::shared_ptr* out, std::string* why); + std::unique_ptr open() const; + const ChatFormat& format() const; + /* The most bytes ReplyHeld::delimiter can reach for this request: a delimiter or terminator + * prefix in each place one can be pending at once, a value's undecided head, and an + * unfinished UTF-8 sequence on each output. A constant of the format, not of the reply. */ + size_t hold_bound() const; + + struct Impl; + const Impl& impl() const { return *impl_; } +private: + ReplyParser(); + std::unique_ptr impl_; +}; + +class ReplyStream { +public: + ~ReplyStream(); + + /* Append bytes. The increments they complete are appended to *out (which may be null). */ + void feed(std::string_view bytes, std::vector* out); + /* The reply is complete. Whatever was held is resolved and emitted. Idempotent. */ + void finish(std::vector* out); + + const ReplyMessage& message() const; + /* False once the reply left the format's grammar and was read by a recovery rule. */ + bool strict() const; + ReplyHeld held() const; + + struct Impl; +private: + friend class ReplyParser; + ReplyStream(); + std::unique_ptr impl_; +}; + +/* Parse a complete reply in one call. */ +ReplyMessage reply_parse(const ReplyParser& p, std::string_view text, bool* strict = nullptr); + +} /* namespace rad */ diff --git a/core/text/gguf.cpp b/core/text/gguf.cpp new file mode 100644 index 00000000..820d5eac --- /dev/null +++ b/core/text/gguf.cpp @@ -0,0 +1,458 @@ +#include "text/gguf.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rad { + +/* ------------------------------------------------------------------ dtype geometry */ +/* Transcribed from ggml.c `type_traits` at llama.cpp 06938ac12 by running ggml_blck_size() and + * ggml_type_size() over the whole enum, so it is the values the producer actually used rather + * than the values the format documentation claims. Rows 42..44 are local to that checkout and + * are carried so a file written by it is readable; upstream stops at 41. */ +static const GgufDtype k_dtypes[] = { + { 1, 4, "f32" }, /* 0 */ + { 1, 2, "f16" }, /* 1 */ + { 32, 18, "q4_0" }, /* 2 */ + { 32, 20, "q4_1" }, /* 3 */ + { 0, 0, nullptr }, /* 4 removed */ + { 0, 0, nullptr }, /* 5 removed */ + { 32, 22, "q5_0" }, /* 6 */ + { 32, 24, "q5_1" }, /* 7 */ + { 32, 34, "q8_0" }, /* 8 */ + { 32, 36, "q8_1" }, /* 9 */ + { 256, 84, "q2_K" }, /* 10 */ + { 256, 110, "q3_K" }, /* 11 */ + { 256, 144, "q4_K" }, /* 12 */ + { 256, 176, "q5_K" }, /* 13 */ + { 256, 210, "q6_K" }, /* 14 */ + { 256, 292, "q8_K" }, /* 15 */ + { 256, 66, "iq2_xxs" }, /* 16 */ + { 256, 74, "iq2_xs" }, /* 17 */ + { 256, 98, "iq3_xxs" }, /* 18 */ + { 256, 50, "iq1_s" }, /* 19 */ + { 32, 18, "iq4_nl" }, /* 20 */ + { 256, 110, "iq3_s" }, /* 21 */ + { 256, 82, "iq2_s" }, /* 22 */ + { 256, 136, "iq4_xs" }, /* 23 */ + { 1, 1, "i8" }, /* 24 */ + { 1, 2, "i16" }, /* 25 */ + { 1, 4, "i32" }, /* 26 */ + { 1, 8, "i64" }, /* 27 */ + { 1, 8, "f64" }, /* 28 */ + { 256, 56, "iq1_m" }, /* 29 */ + { 1, 2, "bf16" }, /* 30 */ + { 0, 0, nullptr }, /* 31 removed */ + { 0, 0, nullptr }, /* 32 removed */ + { 0, 0, nullptr }, /* 33 removed */ + { 256, 54, "tq1_0" }, /* 34 */ + { 256, 66, "tq2_0" }, /* 35 */ + { 0, 0, nullptr }, /* 36 removed */ + { 0, 0, nullptr }, /* 37 removed */ + { 0, 0, nullptr }, /* 38 removed */ + { 32, 17, "mxfp4" }, /* 39 */ + { 64, 36, "nvfp4" }, /* 40 */ + { 128, 18, "q1_0" }, /* 41 */ + { 32, 34, "rad4_q8" }, /* 42 */ + { 32, 20, "rad4_q4" }, /* 43 */ + { 256, 144, "rad4_q4k"}, /* 44 */ +}; +static const size_t k_n_dtypes = sizeof(k_dtypes) / sizeof(k_dtypes[0]); + +const GgufDtype* gguf_dtype(uint32_t t) { + if (t >= k_n_dtypes || k_dtypes[t].blck == 0) return nullptr; + return &k_dtypes[t]; +} + +uint32_t gguf_to_rad_dtype(uint32_t t) { + /* Only the types whose bytes mean the same thing on both sides. Everything block-quantised + * is deliberately absent: reinterpreting a q4_K block as RAD_I4 would produce a tensor that + * loads and computes and is wrong, which is the failure mode this project exists to remove. */ + switch (t) { + case 0: return RAD_F32; + case 1: return RAD_F16; + case 24: return RAD_I8; + case 25: return RAD_I16; + case 26: return RAD_I32; + case 27: return RAD_I64; + case 30: return RAD_BF16; + default: return RAD_DT_INVALID; + } +} + +/* ------------------------------------------------------------------ cursor */ +/* A bounds-checked forward cursor over the mmap. Every read returns false at the end of the + * file instead of faulting, because a truncated GGUF is a thing that happens to people and + * "SIGSEGV in the loader" is not a diagnosis. */ +namespace { +struct Cursor { + const uint8_t* p = nullptr; + uint64_t off = 0, end = 0; + + bool raw(void* dst, size_t n) { + if (n > end - off) return false; + std::memcpy(dst, p + off, n); + off += n; + return true; + } + template bool pod(T* v) { return raw(v, sizeof(T)); } + + bool str(std::string* out) { + uint64_t n = 0; + if (!pod(&n)) return false; + if (n > end - off) return false; + out->assign(reinterpret_cast(p + off), (size_t)n); + off += n; + return true; + } + bool skip(uint64_t n) { + if (n > end - off) return false; + off += n; + return true; + } +}; + +size_t gguf_scalar_bytes(uint32_t t) { + switch (t) { + case GGUF_U8: case GGUF_I8: case GGUF_BOOL: return 1; + case GGUF_U16: case GGUF_I16: return 2; + case GGUF_U32: case GGUF_I32: case GGUF_F32: return 4; + case GGUF_U64: case GGUF_I64: case GGUF_F64: return 8; + default: return 0; /* STR and ARR are not fixed-width */ + } +} + +/* The smallest a KV and a tensor record can be encoded in, which is what a count in the header is + * checked against: a key or name length and a type, then one value byte, or a dimension count + * and an offset. */ +constexpr uint64_t kMinKvBytes = sizeof(uint64_t) + sizeof(uint32_t) + 1; +constexpr uint64_t kMinTensorBytes = sizeof(uint64_t) + 2 * sizeof(uint32_t) + sizeof(uint64_t); + +/* A count read from the file sizes a reservation only up to a point. Past it the table grows as + * entries are actually read, so its memory follows the file's content rather than what the file + * claims about it. */ +size_t reserve_hint(uint64_t n) { return (size_t)std::min(n, 1u << 16); } + +/* Widen one fixed-width scalar into the KV's integer or float lane. */ +bool read_scalar(Cursor& c, uint32_t t, GgufKV& kv) { + switch (t) { + case GGUF_U8: { uint8_t v; if (!c.pod(&v)) return false; kv.i.push_back(v); return true; } + case GGUF_I8: { int8_t v; if (!c.pod(&v)) return false; kv.i.push_back(v); return true; } + case GGUF_BOOL: { int8_t v; if (!c.pod(&v)) return false; kv.i.push_back(v ? 1 : 0); return true; } + case GGUF_U16: { uint16_t v; if (!c.pod(&v)) return false; kv.i.push_back(v); return true; } + case GGUF_I16: { int16_t v; if (!c.pod(&v)) return false; kv.i.push_back(v); return true; } + case GGUF_U32: { uint32_t v; if (!c.pod(&v)) return false; kv.i.push_back(v); return true; } + case GGUF_I32: { int32_t v; if (!c.pod(&v)) return false; kv.i.push_back(v); return true; } + case GGUF_U64: { uint64_t v; if (!c.pod(&v)) return false; kv.i.push_back((int64_t)v); return true; } + case GGUF_I64: { int64_t v; if (!c.pod(&v)) return false; kv.i.push_back(v); return true; } + case GGUF_F32: { float v; if (!c.pod(&v)) return false; kv.f.push_back(v); return true; } + case GGUF_F64: { double v; if (!c.pod(&v)) return false; kv.f.push_back(v); return true; } + case GGUF_STR: { std::string s; if (!c.str(&s)) return false; kv.s.push_back(std::move(s)); return true; } + default: return false; + } +} +} /* namespace */ + +/* ------------------------------------------------------------------ open */ +GgufFile::~GgufFile() { close(); } + +void GgufFile::close() { + if (base_) { + ::munmap(const_cast(base_), (size_t)file_bytes_); + base_ = nullptr; + } + kv_.clear(); + tensors_.clear(); + kv_index_.clear(); + tensor_index_.clear(); + file_bytes_ = 0; + data_off_ = 0; + version_ = 0; + alignment_ = 32; + path_.clear(); +} + +int GgufFile::open(const char* path) { + close(); + path_ = path ? path : ""; + + int fd = ::open(path_.c_str(), O_RDONLY); + if (fd < 0) { + RAD_ERR("gguf: open %s: %s", path_.c_str(), std::strerror(errno)); + return RAD_E_IO; + } + struct stat st{}; + if (::fstat(fd, &st) != 0 || st.st_size <= 0) { + ::close(fd); + RAD_ERR("gguf: stat %s: %s", path_.c_str(), std::strerror(errno)); + return RAD_E_IO; + } + void* m = ::mmap(nullptr, (size_t)st.st_size, PROT_READ, MAP_PRIVATE, fd, 0); + ::close(fd); /* the mapping keeps its own reference; the fd is not needed */ + if (m == MAP_FAILED) { + RAD_ERR("gguf: mmap %s (%lld bytes): %s", path_.c_str(), + (long long)st.st_size, std::strerror(errno)); + return RAD_E_IO; + } + base_ = static_cast(m); + file_bytes_ = (uint64_t)st.st_size; + + Cursor c{ base_, 0, file_bytes_ }; + + char magic[4] = { 0, 0, 0, 0 }; + uint64_t n_tensors = 0, n_kv = 0; + if (!c.raw(magic, 4) || !c.pod(&version_) || !c.pod(&n_tensors) || !c.pod(&n_kv)) { + RAD_ERR("gguf: %s is too short to hold a header", path_.c_str()); + close(); + return RAD_E_FORMAT; + } + if (std::memcmp(magic, "GGUF", 4) != 0) { + RAD_ERR("gguf: %s is not a GGUF file (magic %02x%02x%02x%02x)", path_.c_str(), + (unsigned)(uint8_t)magic[0], (unsigned)(uint8_t)magic[1], + (unsigned)(uint8_t)magic[2], (unsigned)(uint8_t)magic[3]); + close(); + return RAD_E_FORMAT; + } + /* v1 laid its counts out as 32-bit and nothing produces it any more; v2 and v3 differ only + * in the sign of a tensor dimension, which we read as int64 either way. */ + if (version_ < 2 || version_ > 3) { + RAD_ERR("gguf: %s is version %u; this reader handles 2 and 3", path_.c_str(), version_); + close(); + return RAD_E_FORMAT; + } + /* Both counts index heap tables, so a corrupt one has to be refused before it is trusted as + * a loop bound. What is left of the file has to hold every entry at its smallest encoding. */ + const uint64_t rest = c.end - c.off; + if (n_kv > rest / kMinKvBytes || n_tensors > rest / kMinTensorBytes) { + RAD_ERR("gguf: %s declares %llu KVs and %llu tensors in %llu bytes", path_.c_str(), + (unsigned long long)n_kv, (unsigned long long)n_tensors, + (unsigned long long)file_bytes_); + close(); + return RAD_E_FORMAT; + } + + kv_.reserve(reserve_hint(n_kv)); + for (uint64_t k = 0; k < n_kv; ++k) { + GgufKV e; + uint32_t t = 0; + if (!c.str(&e.key) || !c.pod(&t)) { + RAD_ERR("gguf: %s: truncated in KV %llu", path_.c_str(), (unsigned long long)k); + close(); + return RAD_E_FORMAT; + } + uint64_t n = 1; + if (t == GGUF_ARR) { + e.is_array = true; + if (!c.pod(&t) || !c.pod(&n)) { + RAD_ERR("gguf: %s: truncated array header for '%s'", path_.c_str(), e.key.c_str()); + close(); + return RAD_E_FORMAT; + } + if (t == GGUF_ARR) { + RAD_ERR("gguf: %s: '%s' is an array of arrays, which GGUF does not define", + path_.c_str(), e.key.c_str()); + close(); + return RAD_E_FORMAT; + } + /* Every element has a smallest encoding -- its width, or a string's length prefix -- + * so a bogus count is caught here, against what is left of the file, rather than + * after a reserve sized by it has exhausted memory. A type with no encoding at all + * fails on its first element, so it is refused before anything is sized for it. */ + const size_t w = t == GGUF_STR ? sizeof(uint64_t) : gguf_scalar_bytes(t); + if (!w) { + RAD_ERR("gguf: %s: '%s' is an array of type %u, which GGUF does not define", + path_.c_str(), e.key.c_str(), t); + close(); + return RAD_E_FORMAT; + } + if (n > (c.end - c.off) / w) { + RAD_ERR("gguf: %s: '%s' claims %llu elements, past the end of the file", + path_.c_str(), e.key.c_str(), (unsigned long long)n); + close(); + return RAD_E_FORMAT; + } + } + e.type = t; + if (t == GGUF_STR) e.s.reserve(reserve_hint(n)); + else if (t == GGUF_F32 || t == GGUF_F64) e.f.reserve(reserve_hint(n)); + else e.i.reserve(reserve_hint(n)); + + for (uint64_t j = 0; j < n; ++j) { + if (!read_scalar(c, t, e)) { + RAD_ERR("gguf: %s: truncated value %llu of '%s' (type %u)", path_.c_str(), + (unsigned long long)j, e.key.c_str(), t); + close(); + return RAD_E_FORMAT; + } + } + /* Later duplicates lose. GGUF does not forbid them and a rewriter can leave one behind; + * the first is the one every other reader takes. */ + if (!kv_index_.count(e.key)) kv_index_[e.key] = kv_.size(); + kv_.push_back(std::move(e)); + } + + /* The alignment KV moves the data section, so it has to be read before the directory's + * offsets mean anything. 32 is the format's default. */ + int64_t al = 0; + if (get_i64("general.alignment", &al) && al > 0 && (al & (al - 1)) == 0) { + alignment_ = (uint64_t)al; + } + + tensors_.reserve(reserve_hint(n_tensors)); + for (uint64_t t = 0; t < n_tensors; ++t) { + GgufTensor ti; + if (!c.str(&ti.name) || !c.pod(&ti.n_dims)) { + RAD_ERR("gguf: %s: truncated in tensor %llu", path_.c_str(), (unsigned long long)t); + close(); + return RAD_E_FORMAT; + } + if (ti.n_dims > 4) { + RAD_ERR("gguf: %s: tensor '%s' has %u dimensions; GGUF allows 4", + path_.c_str(), ti.name.c_str(), ti.n_dims); + close(); + return RAD_E_FORMAT; + } + for (uint32_t d = 0; d < ti.n_dims; ++d) { + if (!c.pod(&ti.ne[d]) || ti.ne[d] < 0) { + RAD_ERR("gguf: %s: tensor '%s' has a bad dimension %u", path_.c_str(), + ti.name.c_str(), d); + close(); + return RAD_E_FORMAT; + } + } + if (!c.pod(&ti.ggml_type) || !c.pod(&ti.offset)) { + RAD_ERR("gguf: %s: truncated type/offset for '%s'", path_.c_str(), ti.name.c_str()); + close(); + return RAD_E_FORMAT; + } + const GgufDtype* dt = gguf_dtype(ti.ggml_type); + if (!dt) { + RAD_ERR("gguf: %s: tensor '%s' has dtype %u, which this build does not know. " + "Refusing rather than guessing its byte size.", + path_.c_str(), ti.name.c_str(), ti.ggml_type); + close(); + return RAD_E_FORMAT; + } + if (ti.ne[0] % dt->blck != 0) { + RAD_ERR("gguf: %s: tensor '%s' row is %lld elements, not a multiple of the %s block " + "of %d", path_.c_str(), ti.name.c_str(), (long long)ti.ne[0], dt->name, + dt->blck); + close(); + return RAD_E_FORMAT; + } + /* The product of four file-supplied dimensions, and its size in bytes, can each wrap -- + * to a small tensor that passes the bounds check below while its dimensions say it is + * vast. Both are checked, and the count also has to fit the signed type every consumer + * of `ne` computes it in. */ + uint64_t nelem = 1; + bool wraps = false; + for (int d = 0; d < 4; ++d) + wraps |= __builtin_mul_overflow(nelem, (uint64_t)ti.ne[d], &nelem); + wraps |= nelem > (uint64_t)INT64_MAX; + wraps |= __builtin_mul_overflow(nelem / (uint64_t)dt->blck, (uint64_t)dt->block_bytes, + &ti.bytes); + if (wraps) { + RAD_ERR("gguf: %s: tensor '%s' has dimensions %lld x %lld x %lld x %lld, whose size " + "does not fit in 64 bits", path_.c_str(), ti.name.c_str(), + (long long)ti.ne[0], (long long)ti.ne[1], (long long)ti.ne[2], + (long long)ti.ne[3]); + close(); + return RAD_E_FORMAT; + } + if (!tensor_index_.count(ti.name)) tensor_index_[ti.name] = tensors_.size(); + tensors_.push_back(std::move(ti)); + } + + data_off_ = align_up((int64_t)c.off, (int64_t)alignment_); + if (data_off_ > file_bytes_) { + RAD_ERR("gguf: %s: data section starts at %llu, past the end of a %llu-byte file", + path_.c_str(), (unsigned long long)data_off_, (unsigned long long)file_bytes_); + close(); + return RAD_E_FORMAT; + } + /* Every tensor must lie inside the file. Checking it once here is what lets tensor_data() + * hand out a raw pointer without every caller re-deriving the bound. */ + for (const GgufTensor& ti : tensors_) { + if (ti.offset > file_bytes_ - data_off_ || + ti.bytes > file_bytes_ - data_off_ - ti.offset) { + RAD_ERR("gguf: %s: tensor '%s' (%llu bytes at +%llu) leaves the file", + path_.c_str(), ti.name.c_str(), + (unsigned long long)ti.bytes, (unsigned long long)ti.offset); + close(); + return RAD_E_FORMAT; + } + } + + RAD_DEBUG("gguf: %s v%u, %zu KVs, %zu tensors, data at +%llu, align %llu", + path_.c_str(), version_, kv_.size(), tensors_.size(), + (unsigned long long)data_off_, (unsigned long long)alignment_); + return RAD_OK; +} + +/* ------------------------------------------------------------------ lookup */ +const GgufKV* GgufFile::find(std::string_view key) const { + auto it = kv_index_.find(std::string(key)); + return it == kv_index_.end() ? nullptr : &kv_[it->second]; +} + +const GgufTensor* GgufFile::tensor(std::string_view name) const { + auto it = tensor_index_.find(std::string(name)); + return it == tensor_index_.end() ? nullptr : &tensors_[it->second]; +} + +bool GgufFile::get_i64(std::string_view key, int64_t* out) const { + const GgufKV* e = find(key); + if (!e || e->i.empty()) return false; + *out = e->i[0]; + return true; +} + +bool GgufFile::get_f64(std::string_view key, double* out) const { + const GgufKV* e = find(key); + if (!e || e->f.empty()) return false; + *out = e->f[0]; + return true; +} + +bool GgufFile::get_str(std::string_view key, std::string* out) const { + const GgufKV* e = find(key); + if (!e || e->s.empty()) return false; + *out = e->s[0]; + return true; +} + +bool GgufFile::get_strs(std::string_view key, std::vector* out) const { + const GgufKV* e = find(key); + if (!e || e->type != GGUF_STR) return false; + *out = e->s; + return true; +} + +bool GgufFile::get_i64s(std::string_view key, std::vector* out) const { + const GgufKV* e = find(key); + if (!e || e->i.empty()) return false; + *out = e->i; + return true; +} + +bool GgufFile::get_f32s(std::string_view key, std::vector* out) const { + const GgufKV* e = find(key); + if (!e || e->f.empty()) return false; + out->assign(e->f.begin(), e->f.end()); + return true; +} + +const void* GgufFile::tensor_data(const GgufTensor& t) const { + if (!base_) return nullptr; + if (t.offset > file_bytes_ - data_off_ || t.bytes > file_bytes_ - data_off_ - t.offset) + return nullptr; + return base_ + data_off_ + t.offset; +} + +} /* namespace rad */ diff --git a/core/text/gguf.h b/core/text/gguf.h new file mode 100644 index 00000000..8e57a4ec --- /dev/null +++ b/core/text/gguf.h @@ -0,0 +1,133 @@ +/* gguf.h -- a reader for the GGUF container, and nothing else. + * + * spec §12 lists `ggml/src/gguf.cpp` as a lift, but that file is a reader, a writer and a + * ggml_context builder welded together: it fills `struct ggml_tensor`, calls `ggml_blck_size`, + * and pulls in `ggml.h` for both. Taking it whole would mean taking ggml, which §12 says + * explicitly we do not. So the reader is rewritten here under our own name -- the wire format is + * a header, a KV table, a tensor directory and a padded blob, and that is a page of code -- and + * `vendor/UPSTREAM` records the file it was read from rather than copied from. + * + * What we keep from upstream is the one thing that is genuinely data rather than code: the block + * geometry of every ggml dtype, without which a tensor's byte size cannot be computed. That table + * is transcribed from `ggml_blck_size`/`ggml_type_size` and is marked as such below. + * + * The file is mmapped whole and never copied. rad-convert walks the directory, reads what it + * wants through `tensor_data()`, and writes the .rad; nothing here interprets tensor CONTENT. + */ +#pragma once +#include "rad_internal.h" + +#include +#include +#include +#include + +namespace rad { + +/* GGUF's own value type numbering. These are wire values -- fixed by the format, not by us. */ +enum GgufType { + GGUF_U8 = 0, GGUF_I8 = 1, GGUF_U16 = 2, GGUF_I16 = 3, GGUF_U32 = 4, GGUF_I32 = 5, + GGUF_F32 = 6, GGUF_BOOL = 7, GGUF_STR = 8, GGUF_ARR = 9, GGUF_U64 = 10, + GGUF_I64 = 11, GGUF_F64 = 12 +}; + +/* One metadata entry. + * + * A scalar is stored as a one-element vector, so a caller reading `tokenizer.ggml.tokens` and a + * caller reading `general.name` write the same code and neither branches on `is_array`. The cost + * is one heap allocation per scalar KV at open, against a KV table that is a few hundred rows; + * the benefit is that the every-caller path has no special case in it, and a special case in a + * metadata reader is where a truncated vocab comes from. */ +struct GgufKV { + std::string key; + uint32_t type = GGUF_U8; /* for an array, the ELEMENT type; GGUF_ARR never appears here */ + bool is_array = false; + + /* Populated according to `type`: integers and bools widen into `i`, floats into `f`, + * strings into `s`. The other two stay empty. */ + std::vector i; + std::vector f; + std::vector s; +}; + +/* One tensor directory row. `offset` is from the start of the data section, which is where GGUF + * puts it; `data_off() + offset` is the file offset, and `tensor_data()` does that arithmetic. */ +struct GgufTensor { + std::string name; + uint32_t ggml_type = 0; + uint32_t n_dims = 0; + int64_t ne[4] = { 1, 1, 1, 1 }; /* GGUF is fixed at 4 dims, unused ones are 1 */ + uint64_t offset = 0; + uint64_t bytes = 0; /* computed from ne and the block geometry */ +}; + +/* Block geometry for a ggml dtype. Transcribed from ggml.c's `type_traits` at llama.cpp + * 06938ac12 -- see vendor/UPSTREAM. `blck` of 0 marks a removed or unknown type, and a tensor + * carrying one is refused at open rather than silently mis-sized. */ +struct GgufDtype { + int blck; /* logical elements per stored block */ + size_t block_bytes; /* bytes per stored block */ + const char* name; +}; +const GgufDtype* gguf_dtype(uint32_t ggml_type); /* null if out of range */ + +/* Map a ggml dtype onto RAD_* where the two agree exactly. Returns RAD_DT_INVALID for the + * k-quants and the iq-quants: those have no RAD_* equivalent, and rad-convert has to dequantise + * or refuse rather than reinterpret the bytes. */ +uint32_t gguf_to_rad_dtype(uint32_t ggml_type); + +class GgufFile { +public: + GgufFile() = default; + ~GgufFile(); + GgufFile(const GgufFile&) = delete; + GgufFile& operator=(const GgufFile&) = delete; + + /* RAD_OK, or a negative RAD_E_*: RAD_E_IO if the file will not open or map, + * RAD_E_FORMAT if the magic, version, or directory does not hold together. */ + int open(const char* path); + void close(); + bool is_open() const { return base_ != nullptr; } + + uint32_t version() const { return version_; } + uint64_t alignment() const { return alignment_; } + uint64_t data_off() const { return data_off_; } /* file offset of the tensor blob */ + uint64_t file_bytes() const { return file_bytes_; } + const void* base() const { return base_; } /* the mmap, or null */ + const std::string& path() const { return path_; } + + const std::vector& kv() const { return kv_; } + const std::vector& tensors() const { return tensors_; } + + const GgufKV* find(std::string_view key) const; + const GgufTensor* tensor(std::string_view name) const; + + /* Typed reads. Each returns false and leaves *out untouched when the key is absent or holds + * the wrong shape of value -- absence and a type mismatch are the same thing to a caller that + * has a default, and the ones that do not have a default check the return. */ + bool get_i64(std::string_view key, int64_t* out) const; + bool get_f64(std::string_view key, double* out) const; + bool get_str(std::string_view key, std::string* out) const; + bool get_strs(std::string_view key, std::vector* out) const; + bool get_i64s(std::string_view key, std::vector* out) const; + bool get_f32s(std::string_view key, std::vector* out) const; + + /* A pointer into the mmap. Null if the tensor's extent leaves the file, which is a corrupt + * container rather than a caller error -- open() already refused those, so this is belt. */ + const void* tensor_data(const GgufTensor& t) const; + +private: + std::string path_; + const uint8_t* base_ = nullptr; + uint64_t file_bytes_ = 0; + uint32_t version_ = 0; + uint64_t alignment_ = 32; + uint64_t data_off_ = 0; + + std::vector kv_; + std::vector tensors_; + std::unordered_map kv_index_; + std::unordered_map tensor_index_; +}; + +} /* namespace rad */ diff --git a/core/text/tokenizer.cpp b/core/text/tokenizer.cpp new file mode 100644 index 00000000..c6032adc --- /dev/null +++ b/core/text/tokenizer.cpp @@ -0,0 +1,1621 @@ +#include "text/tokenizer.h" +#include "text/tokenizer_bpe.h" +#include "text/tokenizer_nfc.h" +#include "text/tokenizer_regex.h" +#include "text/unicode_norm.h" +#include "llama/src/unicode.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rad { + +/* ================================================================== byte level + * + * GPT-2's byte alphabet, exactly. The printable ASCII range, Latin-1 punctuation and the + * accented Latin-1 letters map to themselves; the remaining 68 bytes map to U+0100 upward in + * ascending byte order. Getting this wrong is not a crash -- it is a vocab lookup that misses + * for one byte in four, which shows up as a 20% longer prompt and nothing else. It is + * reproduced from llama.cpp's unicode_byte_to_utf8_map(), which is itself HuggingFace's table. + * + * We do not call llama.cpp's version because its inverse throws std::out_of_range on an + * unmapped string, and in this engine errors are values (docs/IMPLEMENTATION.md). */ +namespace { + +struct ByteLevelAlphabet { + std::string to_utf8[256]; /* byte -> its 1-2 byte UTF-8 spelling */ + std::unordered_map from; /* and back */ + uint32_t cpt_of[256]; + int16_t byte_of_cpt[0x144]; /* codepoint -> byte, or -1 */ + + ByteLevelAlphabet() { + bool taken[256] = { false }; + for (int16_t& b : byte_of_cpt) b = -1; + auto give = [&](int b, uint32_t cpt) { + to_utf8[b] = unicode_cpt_to_utf8(cpt); + cpt_of[b] = cpt; + from[to_utf8[b]] = (uint8_t)b; + byte_of_cpt[cpt] = (int16_t)b; + taken[b] = true; + }; + for (int b = 0x21; b <= 0x7E; ++b) give(b, (uint32_t)b); /* '!' .. '~' */ + for (int b = 0xA1; b <= 0xAC; ++b) give(b, (uint32_t)b); /* U+00A1..AC */ + for (int b = 0xAE; b <= 0xFF; ++b) give(b, (uint32_t)b); /* U+00AE..FF */ + uint32_t n = 0; + for (int b = 0; b < 256; ++b) if (!taken[b]) give(b, 256 + n++); + } +}; + +const ByteLevelAlphabet& alphabet() { + static const ByteLevelAlphabet a; + return a; +} + +std::string byte_encode(std::string_view raw) { + const ByteLevelAlphabet& a = alphabet(); + std::string out; + out.reserve(raw.size() * 2); + for (unsigned char c : raw) out += a.to_utf8[c]; + return out; +} + +/* Inverse. An unmapped codepoint is passed through as its own UTF-8, which is what a + * user-defined token spelt in real text needs; it cannot be confused with a mapped one because + * the mapped set is closed. */ +std::string byte_decode(const std::string& enc) { + const ByteLevelAlphabet& a = alphabet(); + std::string out; + out.reserve(enc.size()); + for (size_t i = 0; i < enc.size(); ) { + const size_t n = std::min(unicode_len_utf8(enc[i]), enc.size() - i); + const std::string one = enc.substr(i, n); + auto it = a.from.find(one); + if (it != a.from.end()) out += (char)it->second; + else out += one; + i += n; + } + return out; +} + +/* The raw bytes a byte-level token stands for, when EVERY character of it is in the alphabet. + * Only such a token can equal a byte-level word -- mapping puts every byte of a word into the + * alphabet -- so a table of these by their raw bytes answers every lookup the mapped text would, + * and the encoder can merge raw bytes and never build the mapped text at all. */ +bool byte_decode_strict(const std::string& enc, std::string* out) { + const ByteLevelAlphabet& a = alphabet(); + out->clear(); + const uint8_t* p = (const uint8_t*)enc.data(); + for (size_t i = 0; i < enc.size(); ) { + uint32_t c; + if (p[i] < 0x80) { c = p[i]; i += 1; } + else if (p[i] >= 0xC2 && p[i] < 0xE0 && i + 1 < enc.size() && (p[i + 1] & 0xC0) == 0x80) { + c = ((p[i] & 0x1F) << 6) | (p[i + 1] & 0x3F); + i += 2; + } else { + return false; + } + if (c >= 0x144 || a.byte_of_cpt[c] < 0) return false; + *out += (char)a.byte_of_cpt[c]; + } + return true; +} + +constexpr const char* k_metaspace = "\xe2\x96\x81"; /* U+2581 LOWER ONE EIGHTH BLOCK */ + +void replace_all(std::string& s, std::string_view from, std::string_view to) { + if (from.empty()) return; + std::string out; + out.reserve(s.size()); + size_t i = 0; + for (;;) { + size_t j = s.find(from, i); + if (j == std::string::npos) { out.append(s, i, std::string::npos); break; } + out.append(s, i, j - i); + out.append(to); + i = j + from.size(); + } + s.swap(out); +} + +/* The GPT-2 pattern HuggingFace's ByteLevel pre-tokeniser carries inside itself when + * use_regex is set. */ +constexpr const char* k_gpt2_pattern = + "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+"; + +} /* namespace */ + +/* ================================================================== the compiled encoder + * + * Everything encode() needs that can be decided once per vocab: each Split pattern compiled to + * its DFA, the token and merge tables flattened into open-addressed arrays keyed the way the merge + * loop asks, the special-token matcher, and the segment cache. Built by Vocab::load and shared by + * every Tokenizer over the vocab. Two things in it change afterwards and both are safe to share: + * the segment cache, which locks, and the memo of which tokens merge back to themselves, whose + * entries are written once with relaxed atomics. */ + +namespace { + +/* --- special tokens ---------------------------------------------------------------------- */ + +struct SpecialFrag { int32_t id; uint32_t off, len; }; + +/* The text is cut at every special token before any other step sees it. WHICH occurrences are + * cut is decided by priority, not position: longest token first (then lowest id), and a token + * only claims occurrences that no higher-priority token has already claimed and that do not + * overlap one of its own claimed to their left. That is the result of splitting the text once + * per token, longest first, and it is why "<|im_start|>" is never cut in half by a shorter token + * that is a prefix of it. Finding the occurrences is one pass over the text with a + * trie of every special token, started only at a byte some token begins with. */ +class SpecialMatcher { +public: + void build(const std::vector& special, const std::vector& tokens, + const std::vector& types) { + nodes_.assign(1, Node{}); + for (size_t prio = 0; prio < special.size(); ++prio) { + const int32_t id = special[prio]; + const std::string& t = tokens[id]; + toks_.push_back({ id, (uint32_t)t.size(), + types[id] == RAD_TT_CONTROL || types[id] == RAD_TT_UNKNOWN }); + uint32_t n = 0; + for (unsigned char c : t) { + uint32_t next = UINT32_MAX; + for (const auto& k : nodes_[n].kids) if (k.first == c) { next = k.second; break; } + if (next == UINT32_MAX) { + next = (uint32_t)nodes_.size(); + nodes_[n].kids.push_back({ c, next }); + nodes_.push_back(Node{}); + } + n = next; + } + nodes_[n].ends.push_back((uint32_t)prio); + first_[(unsigned char)t[0]] = true; + } + int n_first = 0; + for (int c = 0; c < 256; ++c) if (first_[c]) { ++n_first; only_first_ = c; } + if (n_first != 1) only_first_ = -1; + } + + void split(std::string_view text, bool parse_special, std::vector& out) const { + out.clear(); + const uint8_t* s = (const uint8_t*)text.data(); + const size_t n = text.size(); + struct Occ { uint32_t prio, at; }; + std::vector occ; + auto walk = [&](size_t i) { + uint32_t node = 0; + for (size_t j = i; j < n; ++j) { + uint32_t next = UINT32_MAX; + for (const auto& k : nodes_[node].kids) if (k.first == s[j]) { next = k.second; break; } + if (next == UINT32_MAX) return; + node = next; + for (uint32_t prio : nodes_[node].ends) + if (parse_special || !toks_[prio].control) occ.push_back({ prio, (uint32_t)i }); + } + }; + if (only_first_ >= 0) { + for (const uint8_t* p = s; (p = (const uint8_t*)std::memchr(p, only_first_, (s + n) - p)); ++p) + walk((size_t)(p - s)); + } else if (!toks_.empty()) { + for (size_t i = 0; i < n; ++i) if (first_[s[i]]) walk(i); + } + if (occ.empty()) { + out.push_back({ -1, 0, (uint32_t)n }); + return; + } + std::sort(occ.begin(), occ.end(), [](const Occ& a, const Occ& b) { + return a.prio != b.prio ? a.prio < b.prio : a.at < b.at; + }); + std::map> taken; /* start -> (end, id) */ + for (const Occ& o : occ) { + const uint32_t b = o.at, e = o.at + toks_[o.prio].len; + auto it = taken.lower_bound(b); + if (it != taken.end() && it->first < e) continue; + if (it != taken.begin() && std::prev(it)->second.first > b) continue; + taken.emplace(b, std::make_pair(e, toks_[o.prio].id)); + } + uint32_t pos = 0; + for (const auto& t : taken) { + if (t.first > pos) out.push_back({ -1, pos, t.first - pos }); + out.push_back({ t.second.second, t.first, t.second.first - t.first }); + pos = t.second.first; + } + if (pos < n) out.push_back({ -1, pos, (uint32_t)n - pos }); + } + +private: + struct Tok { int32_t id; uint32_t len; bool control; }; + struct Node { + std::vector> kids; + std::vector ends; /* priorities of the tokens that end here */ + }; + std::vector toks_; /* in priority order */ + std::vector nodes_; + bool first_[256] = {}; + int only_first_ = -1; +}; + +/* --- the segment cache ------------------------------------------------------------------- */ + +/* Segment bytes -> ids. See Tokenizer's header for why a hit is exact. Entries are keyed by the + * whole segment: the hash picks the bucket and the bytes decide the match. The bound is on bytes + * held (key, ids and bookkeeping), and eviction is least recently used. + * + * The lock covers the index and nothing else. An entry is built before it is locked in, and a hit + * takes a reference to the entry's ids and copies them after the lock is released, so a + * 100,000-id segment copied into one admission never holds up another. */ +class SegmentCache { +public: + using Ids = std::shared_ptr>; + + bool lookup(std::string_view key, uint64_t h, std::vector& out) { + Ids ids; + { + std::lock_guard lk(mu_); + auto range = index_.equal_range(h); + for (auto it = range.first; it != range.second; ++it) { + const Entry& e = *it->second; + if (e.key.size() != key.size() || + std::memcmp(e.key.data(), key.data(), key.size()) != 0) + continue; + ids = e.ids; + lru_.splice(lru_.begin(), lru_, it->second); + break; + } + ++(ids ? hits_ : misses_); + } + if (!ids) return false; + out.insert(out.end(), ids->begin(), ids->end()); + return true; + } + + void insert(std::string_view key, uint64_t h, const int32_t* ids, size_t n) { + const size_t cost = key.size() + n * sizeof(int32_t) + kOverhead; + if (cost > limit_.load(std::memory_order_relaxed)) return; + std::list node; + node.push_back(Entry{ std::string(key), std::make_shared>(ids, ids + n), + h, cost }); + std::list evicted; + { + std::lock_guard lk(mu_); + auto range = index_.equal_range(h); + for (auto it = range.first; it != range.second; ++it) { + const Entry& e = *it->second; + if (e.key.size() == key.size() && std::memcmp(e.key.data(), key.data(), key.size()) == 0) + return; /* another encode got here first */ + } + lru_.splice(lru_.begin(), node); + index_.emplace(h, lru_.begin()); + bytes_ += cost; + evict(evicted); + } + } + + void set_limit(size_t bytes) { + std::list evicted; + std::lock_guard lk(mu_); + limit_.store(bytes, std::memory_order_relaxed); + evict(evicted); + } + + void clear() { + std::list gone; + std::lock_guard lk(mu_); + gone.swap(lru_); + index_.clear(); + bytes_ = 0; + hits_ = misses_ = 0; + } + + Tokenizer::CacheStats stats() { + std::lock_guard lk(mu_); + Tokenizer::CacheStats s; + s.hits = hits_; + s.misses = misses_; + s.entries = lru_.size(); + s.bytes = bytes_; + s.limit = limit_.load(std::memory_order_relaxed); + return s; + } + +private: + struct Entry { + std::string key; + Ids ids; + uint64_t hash; + size_t cost; + }; + /* A list node, a hash node, the shared vector's control block and the heap headers, rounded + * up. */ + static constexpr size_t kOverhead = 160; + + /* Moves the least recently used entries into `out` until the bound holds; the caller frees + * them after it unlocks. */ + void evict(std::list& out) { + while (bytes_ > limit_.load(std::memory_order_relaxed) && !lru_.empty()) { + auto last = std::prev(lru_.end()); + auto range = index_.equal_range(last->hash); + for (auto it = range.first; it != range.second; ++it) { + if (it->second == last) { index_.erase(it); break; } + } + bytes_ -= last->cost; + out.splice(out.begin(), lru_, last); + } + } + + std::mutex mu_; + std::list lru_; /* front is most recent */ + std::unordered_multimap::iterator> index_; + size_t bytes_ = 0; + std::atomic limit_{ Tokenizer::kSegmentCacheDefault }; + uint64_t hits_ = 0, misses_ = 0; +}; + +} /* namespace */ + +struct TokEncoder { + struct Step { + VocabStep step; + std::unique_ptr re; /* Split, a regex Replace, ByteLevel with use_regex */ + }; + std::vector norm, pre; + uint32_t kind = RAD_TOK_BPE; + bool bytelevel = false; /* the chain has a ByteLevel pre-tokeniser */ + bool byte_fallback = false; + /* The ByteLevel step at this index is the last step that rewrites text, so the mapping is + * never materialised: the BPE merges raw bytes against `raw` instead. -1 when that does not + * hold (no ByteLevel, or a step after it that reads the mapped text). */ + int defer_bytelevel = -1; + + TokTable text; /* token text -> lowest id */ + TokTable raw; /* raw bytes a byte-level token stands for -> id */ + int32_t byte_sym[256]; /* raw byte -> id of its byte-level character */ + int32_t byte_tok[256]; /* raw byte -> id of "<0xNN>" */ + MergeTable merges; + std::vector types; + int32_t unk = -1; + + /* Per token: whether its own text merges back to exactly itself -- 0 not yet known, 1 yes, + * 2 no. Most words of real text ARE a token, and the merge loop's answer for a token's text + * never changes, so once it has been worked out for one word it is looked up for every later + * one, by every thread, for the life of the vocab. Relaxed atomics: two threads that race + * store the same value. */ + std::unique_ptr[]> self_merges; + + SpecialMatcher specials; + mutable SegmentCache cache; + + int build(const VocabBuild& b, const std::vector& special); +}; + +int TokEncoder::build(const VocabBuild& b, const std::vector& special) { + kind = b.kind; + types = b.types; + unk = b.unk; + + auto compile = [&](const std::string& pat, const char* what, std::unique_ptr* re) { + std::string why; + if (TokRegex::compile(pat, re, &why) < 0) { + RAD_ERR("vocab: the %s pattern '%s' is outside the supported regex dialect: %s. " + "There is no fallback matcher; a pattern that does not compile does not load.", + what, pat.c_str(), why.c_str()); + return RAD_E_UNSUPPORTED; + } + return RAD_OK; + }; + + for (const VocabStep& s : b.steps) { + if (step_is_norm(s.kind)) { + Step st{ s, nullptr }; + if (s.kind == RAD_NORM_REPLACE && (s.flags & 1)) RAD_TRY(compile(s.arg0, "Replace", &st.re)); + norm.push_back(std::move(st)); + } else if (step_is_pre(s.kind)) { + Step st{ s, nullptr }; + if (s.kind == RAD_PRE_SPLIT) RAD_TRY(compile(s.arg0, "Split", &st.re)); + if (s.kind == RAD_PRE_BYTELEVEL) { + bytelevel = true; + if (s.flags & 2) RAD_TRY(compile(k_gpt2_pattern, "ByteLevel", &st.re)); + } + if (s.kind == RAD_PRE_BYTE_FALLBACK) byte_fallback = true; + pre.push_back(std::move(st)); + } + } + if (kind == RAD_TOK_BPE) { + for (size_t k = pre.size(); k-- > 0; ) { + const uint32_t sk = pre[k].step.kind; + if (sk == RAD_PRE_BYTE_FALLBACK) continue; + if (sk == RAD_PRE_BYTELEVEL) defer_bytelevel = (int)k; + break; + } + } + + const size_t n = b.tokens.size(); + text.reserve(n); + for (size_t i = 0; i < n; ++i) text.insert(b.tokens[i], (int32_t)i); + + const ByteLevelAlphabet& a = alphabet(); + for (int c = 0; c < 256; ++c) { + static const char* hex = "0123456789ABCDEF"; + const char buf[7] = { '<', '0', 'x', hex[c >> 4], hex[c & 15], '>', 0 }; + byte_tok[c] = text.find(buf); + byte_sym[c] = text.find(a.to_utf8[c]); + } + if (defer_bytelevel >= 0) { + raw.reserve(n); + std::string r; + for (size_t i = 0; i < n; ++i) + if (!b.tokens[i].empty() && byte_decode_strict(b.tokens[i], &r)) raw.insert(r, (int32_t)i); + } + + /* Keyed by the pair exactly as the vocab lists it, the lowest rank winning a duplicate. A + * symbol's id is always the LOWEST id spelling its text, so a merge listed against a higher + * id with the same text is never looked up. */ + merges.reserve(b.merges.size()); + std::string cat; + for (size_t r = 0; r < b.merges.size(); ++r) { + const uint32_t l = b.merges[r].first, rr = b.merges[r].second; + if (l >= n || rr >= n) continue; + cat.assign(b.tokens[l]); + cat += b.tokens[rr]; + merges.insert((int32_t)l, (int32_t)rr, (uint32_t)r, text.find(cat)); + } + + specials.build(special, b.tokens, b.types); + self_merges.reset(new std::atomic[n]()); + /* A byte-level BPE never looks text up by its mapped spelling once `raw` exists. */ + if (defer_bytelevel >= 0) text = TokTable(); + return RAD_OK; +} + +/* ================================================================== Vocab */ + +int Vocab::load(VocabBuild b) { + b_ = std::move(b); + ready_ = false; + text_to_id_.clear(); + merge_rank_.clear(); + special_.clear(); + byte_of_.clear(); + + if (b_.tokens.empty()) { + RAD_ERR("vocab: no tokens"); + return RAD_E_FORMAT; + } + if (b_.kind != RAD_TOK_BPE && b_.kind != RAD_TOK_UNIGRAM && b_.kind != RAD_TOK_WORDPIECE) { + RAD_ERR("vocab: tokenizer kind %u is not implemented (BPE, unigram and wordpiece are)", + b_.kind); + return RAD_E_UNSUPPORTED; + } + if (b_.types.empty()) b_.types.assign(b_.tokens.size(), (uint8_t)RAD_TT_NORMAL); + if (b_.types.size() != b_.tokens.size()) { + RAD_ERR("vocab: %zu tokens but %zu token types", b_.tokens.size(), b_.types.size()); + return RAD_E_FORMAT; + } + if (b_.kind == RAD_TOK_UNIGRAM && b_.scores.size() != b_.tokens.size()) { + RAD_ERR("vocab: unigram needs a score per token; have %zu for %zu tokens", + b_.scores.size(), b_.tokens.size()); + return RAD_E_FORMAT; + } + + /* A SPECIAL ID IS EMITTED AS IT STANDS -- bos and eos by encode, unk by every encoder on text + * no piece covers -- so one that names no token puts an id outside the vocabulary into a + * sequence. Every source of a vocabulary arrives here, and a GGUF or a container carries these + * ids as plain integers nothing else checks, so one out of range is treated as absent, which + * every reader of these fields already handles, and said so. */ + { + const struct { const char* name; int32_t* id; } specials[] = { + { "bos", &b_.bos }, { "eos", &b_.eos }, { "eot", &b_.eot }, + { "pad", &b_.pad }, { "unk", &b_.unk }, { "sep", &b_.sep }, + }; + for (const auto& s : specials) { + if (*s.id >= -1 && (int64_t)*s.id < (int64_t)b_.tokens.size()) continue; + RAD_WARN("vocab: the %s id %d names no token in a %zu-token vocabulary; treating " + "the vocabulary as having none", s.name, *s.id, b_.tokens.size()); + *s.id = -1; + } + } + + text_to_id_.reserve(b_.tokens.size() * 2); + for (size_t i = 0; i < b_.tokens.size(); ++i) { + /* First spelling wins. A duplicate is a producer bug, but it is not ours to fail on: + * llama.cpp's own vocabs contain them, and the lower id is the one the merge table and + * every published token count refer to. */ + text_to_id_.emplace(b_.tokens[i], (int32_t)i); + } + + /* Merge ranks are stored as an id pair rather than a string pair: the string pair would be + * a 248K-entry map of concatenated strings hashed on every bigram push, and the bigram push + * is the tokeniser's inner loop. */ + merge_rank_.reserve(b_.merges.size() * 2); + for (size_t r = 0; r < b_.merges.size(); ++r) { + const uint64_t key = ((uint64_t)b_.merges[r].first << 32) | (uint64_t)b_.merges[r].second; + merge_rank_.emplace(key, (int32_t)r); + } + + byte_of_.assign(b_.tokens.size(), -1); + const ByteLevelAlphabet& a = alphabet(); + for (size_t i = 0; i < b_.tokens.size(); ++i) { + const std::string& t = b_.tokens[i]; + if (b_.types[i] == RAD_TT_BYTE) { + /* Two spellings in the wild: SPM's "<0xF0>" and byte-level BPE's single mapped + * codepoint. Both are byte tokens and both have to decode to one byte. */ + if (t.size() == 6 && t.compare(0, 3, "<0x") == 0 && t.back() == '>') { + const int hi = t[3], lo = t[4]; + auto hex = [](int c) { return c >= '0' && c <= '9' ? c - '0' + : c >= 'a' && c <= 'f' ? c - 'a' + 10 + : c >= 'A' && c <= 'F' ? c - 'A' + 10 : -1; }; + if (hex(hi) >= 0 && hex(lo) >= 0) byte_of_[i] = hex(hi) * 16 + hex(lo); + } else { + auto it = a.from.find(t); + if (it != a.from.end()) byte_of_[i] = it->second; + } + } + if (b_.types[i] == RAD_TT_CONTROL || b_.types[i] == RAD_TT_UNKNOWN || + b_.types[i] == RAD_TT_USER_DEFINED) { + if (!t.empty()) special_.push_back((int32_t)i); + } + } + + /* Longest first. Special-token partitioning scans the text once per special token, and a + * shorter token that is a prefix of a longer one would otherwise cut the longer one in half + * -- "<|im_start|>" losing to "<|im" is the classic version of this bug. */ + std::sort(special_.begin(), special_.end(), [&](int32_t x, int32_t y) { + const size_t nx = b_.tokens[x].size(), ny = b_.tokens[y].size(); + return nx != ny ? nx > ny : x < y; + }); + + /* ------------------------------------------------------------------ end of generation + * + * A MODEL ENDS ITS TURN ON MORE THAN ONE TOKEN AND THE CONTAINER CARRIES ROOM FOR ONE. The + * header has `eos` and `eot` and nothing else, but a Qwen container declares + * eos_token_id: [<|im_end|>, <|endoftext|>] and will end a turn on either -- and its + * `<|endoftext|>` lands in `pad_id`, which nothing treats as terminal. The engine then + * generates straight past the end of the turn into a hallucinated next one, which does not + * read as a bug: it reads as a model that rambles. + * + * So the set is completed here, from the ONE piece of evidence in the container that is not a + * guess -- a CONTROL token whose spelling is a known end-of-generation marker. Both halves of + * that matter. Restricting it to control tokens means ordinary text can never become + * terminal, and matching an explicit list of spellings rather than a pattern means a token + * named `<|end_of_thinking|>` does not silently end generations. This is the same list, and + * the same reasoning, that llama.cpp's vocabulary loader applies. + * + * WHAT IS ADDED IS LOGGED. A token that silently gained the power to end every generation is + * exactly the kind of change that should be visible in a startup log, so it is. */ + eog_.clear(); + if (b_.eos >= 0) eog_.push_back(b_.eos); + if (b_.eot >= 0 && b_.eot != b_.eos) eog_.push_back(b_.eot); + { + static const char* const kEogNames[] = { + "<|endoftext|>", "<|im_end|>", "<|eot_id|>", "<|end_of_text|>", "", + "<|end|>", "<|EOT|>", "<|eom_id|>", "<|return|>", "", "", + }; + std::string added; + for (int32_t id : special_) { + if (b_.types[id] != RAD_TT_CONTROL) continue; + if (std::find(eog_.begin(), eog_.end(), id) != eog_.end()) continue; + bool known = false; + for (const char* n : kEogNames) if (b_.tokens[id] == n) { known = true; break; } + if (!known) continue; + eog_.push_back(id); + added += (added.empty() ? "" : " ") + b_.tokens[id] + "=" + std::to_string(id); + } + if (!added.empty()) + RAD_INFO("vocab: end-of-generation also on %s (a control token the container declares " + "neither as eos nor eot; without this a turn ending on it runs on)", + added.c_str()); + } + + /* The encoder: the chain compiled and the tables flattened. A pattern the regex compiler + * refuses refuses the vocab, with the construct named -- there is no slower matcher to hand + * it to instead. */ + enc_ = std::make_shared(); + RAD_TRY(enc_->build(b_, special_)); + + ready_ = true; + RAD_DEBUG("vocab: %zu tokens, %zu merges, %zu special, %zu eog, %zu chain steps, kind %u", + b_.tokens.size(), b_.merges.size(), special_.size(), eog_.size(), b_.steps.size(), + b_.kind); + return RAD_OK; +} + +const std::string& Vocab::text(int32_t id) const { + static const std::string empty; + if (id < 0 || id >= (int32_t)b_.tokens.size()) return empty; + return b_.tokens[id]; +} + +uint8_t Vocab::type(int32_t id) const { + if (id < 0 || id >= (int32_t)b_.types.size()) return RAD_TT_UNKNOWN; + return b_.types[id]; +} + +float Vocab::score(int32_t id) const { + if (id < 0 || id >= (int32_t)b_.scores.size()) return 0.0f; + return b_.scores[id]; +} + + +bool Vocab::is_eog(int32_t id) const { + return id >= 0 && std::find(eog_.begin(), eog_.end(), id) != eog_.end(); +} + +int32_t Vocab::find(std::string_view t) const { + auto it = text_to_id_.find(std::string(t)); + return it == text_to_id_.end() ? -1 : it->second; +} + +int32_t Vocab::merge_rank(std::string_view left, std::string_view right) const { + const int32_t l = find(left), r = find(right); + if (l < 0 || r < 0) return -1; + auto it = merge_rank_.find(((uint64_t)(uint32_t)l << 32) | (uint32_t)r); + return it == merge_rank_.end() ? -1 : it->second; +} + +int32_t Vocab::token_byte(int32_t id) const { + if (id < 0 || id >= (int32_t)byte_of_.size()) return -1; + return byte_of_[id]; +} + +/* ================================================================== the step chain */ + +std::string step_describe(const VocabStep& s) { + switch (s.kind) { + case RAD_NORM_NFC: return "NFC"; + case RAD_NORM_NFKC: return "NFKC"; + case RAD_NORM_NFD: return "NFD"; + case RAD_NORM_NFKD: return "NFKD"; + case RAD_NORM_LOWERCASE: return "Lowercase"; + case RAD_NORM_STRIP: + return fmt("Strip(left=%d right=%d)", (s.flags & 1) ? 1 : 0, (s.flags & 2) ? 1 : 0); + case RAD_NORM_REPLACE: + return fmt("Replace(%s '%s' -> '%s')", (s.flags & 1) ? "regex" : "literal", + s.arg0.c_str(), s.arg1.c_str()); + case RAD_NORM_PREPEND: return fmt("Prepend('%s')", s.arg0.c_str()); + case RAD_PRE_BYTELEVEL: + return fmt("ByteLevel(add_prefix_space=%d use_regex=%d)", + (s.flags & 1) ? 1 : 0, (s.flags & 2) ? 1 : 0); + case RAD_PRE_SPLIT: { + /* What the pattern compiled to is part of the description: the size of its DFA, or + * the construct that refused it. */ + std::unique_ptr re; + std::string why; + const std::string dfa = TokRegex::compile(s.arg0, &re, &why) < 0 + ? "[refused: " + why + "]" + : fmt("[dfa: %zu states, %zu classes]", re->n_states(), re->n_classes()); + return fmt("Split(%s behavior=%lld invert=%d) %s", + s.arg0.c_str(), (long long)s.iarg, (s.flags & 1) ? 1 : 0, dfa.c_str()); + } + case RAD_PRE_METASPACE: + return fmt("Metaspace('%s' prepend=%lld split=%d)", s.arg0.c_str(), + (long long)s.iarg, (s.flags & 1) ? 1 : 0); + case RAD_PRE_WHITESPACE: return "Whitespace"; + case RAD_PRE_PUNCTUATION: return fmt("Punctuation(behavior=%lld)", (long long)s.iarg); + case RAD_PRE_DIGITS: + return fmt("Digits(individual=%d)", (s.flags & 1) ? 1 : 0); + case RAD_PRE_BYTE_FALLBACK: return "ByteFallback"; + case RAD_DEC_BYTELEVEL: return "decode ByteLevel"; + case RAD_DEC_METASPACE: + return fmt("decode Metaspace('%s' prepend=%lld)", s.arg0.c_str(), (long long)s.iarg); + case RAD_DEC_REPLACE: + return fmt("decode Replace('%s' -> '%s')", s.arg0.c_str(), s.arg1.c_str()); + case RAD_DEC_STRIP: + return fmt("decode Strip('%s' start=%lld stop=%lld)", s.arg0.c_str(), + (long long)(s.iarg & 0xFFFFFFFF), (long long)(s.iarg >> 32)); + case RAD_DEC_FUSE: return "decode Fuse"; + case RAD_DEC_BYTE_FALLBACK: return "decode ByteFallback"; + default: return fmt("", s.kind); + } +} + +namespace { + +/* --- normalisers ------------------------------------------------------------------------- */ + +void apply_norm(std::string& text, const TokEncoder::Step& st) { + const VocabStep& s = st.step; + switch (s.kind) { + case RAD_NORM_NFC: tok_nfc(text); break; + case RAD_NORM_NFKC: text = unorm_utf8(text, true, true); break; + case RAD_NORM_NFD: text = unorm_utf8(text, false, false); break; + case RAD_NORM_NFKD: text = unorm_utf8(text, true, false); break; + case RAD_NORM_LOWERCASE: { + std::vector cpts = unicode_cpts_from_utf8(text); + std::string out; + out.reserve(text.size()); + for (uint32_t c : cpts) out += unicode_cpt_to_utf8(unicode_tolower(c)); + text.swap(out); + break; + } + case RAD_NORM_STRIP: { + /* Whitespace by the unicode definition, not isspace(): a non-breaking space in a + * pasted prompt is whitespace to HuggingFace and would not be to isspace(). */ + std::vector cpts = unicode_cpts_from_utf8(text); + size_t a = 0, b = cpts.size(); + if (s.flags & 1) while (a < b && unicode_cpt_flags_from_cpt(cpts[a]).is_whitespace) ++a; + if (s.flags & 2) while (b > a && unicode_cpt_flags_from_cpt(cpts[b-1]).is_whitespace) --b; + std::string out; + for (size_t i = a; i < b; ++i) out += unicode_cpt_to_utf8(cpts[i]); + text.swap(out); + break; + } + case RAD_NORM_REPLACE: + if (s.flags & 1) { + /* HuggingFace's Replace: every match of the compiled pattern becomes the content, + * verbatim -- the content is text, not a substitution template. */ + std::string canon, out; + std::string_view v = text; + if (!utf8_is_canonical(v)) { utf8_canonicalize(v, canon); v = canon; } + tok_replace(*st.re, v, s.arg1, out); + text.swap(out); + } else { + replace_all(text, s.arg0, s.arg1); + } + break; + case RAD_NORM_PREPEND: text = s.arg0 + text; break; + default: + RAD_WARN("tokenizer: normaliser step %u is not implemented; text passed through", + s.kind); + break; + } +} + +/* --- pre-tokenisers ---------------------------------------------------------------------- + * + * The pieces are spans of one buffer rather than a string each: a 500 KB prompt is 150,000 + * pieces, and a string each would be 150,000 allocations. A step that has to rewrite text + * appends the new text to the buffer (or builds a new buffer) and points its spans there. */ + +struct Pieces { + std::string buf; + std::vector spans; + bool canonical = false; /* every piece is known to be canonical UTF-8 */ + std::string_view at(const TokSpan& s) const { + return std::string_view(buf).substr(s.begin, s.end - s.begin); + } +}; + +struct EncodeScratch { + Pieces p; + std::string canon; + std::vector next, found, match; + std::vector syms; +}; + +/* One Split step over every piece. The pieces it produces are canonical UTF-8: a piece that is + * not is decoded and re-encoded first -- invalid bytes to U+FFFD, overlong forms shortest -- piece + * by piece, by the rules of the decoder the other steps use (utf8_canonicalize). */ +void apply_split(Pieces& p, const TokRegex& re, int behavior, bool invert, EncodeScratch& sc) { + if (!p.canonical) p.canonical = utf8_is_canonical(p.buf); + const bool whole = p.canonical; + sc.next.clear(); + for (size_t k = 0; k < p.spans.size(); ++k) { + const TokSpan s = p.spans[k]; + if (s.end == s.begin) continue; + uint32_t base = s.begin; + std::string_view v = p.at(s); + if (!whole && !utf8_is_canonical(v)) { + sc.canon.clear(); + utf8_canonicalize(v, sc.canon); + base = (uint32_t)p.buf.size(); + p.buf += sc.canon; + v = std::string_view(p.buf).substr(base, sc.canon.size()); + } + sc.found.clear(); + tok_split(re, v, behavior, invert, sc.found, sc.match); + for (const TokSpan& f : sc.found) sc.next.push_back({ base + f.begin, base + f.end }); + } + p.spans.swap(sc.next); + p.canonical = true; +} + +void rebuild(Pieces& p, const std::vector& words) { + std::string buf; + std::vector spans; + for (const std::string& w : words) { + spans.push_back({ (uint32_t)buf.size(), (uint32_t)(buf.size() + w.size()) }); + buf += w; + } + p.buf.swap(buf); + p.spans.swap(spans); +} + +std::vector words_of(const Pieces& p) { + std::vector w; + w.reserve(p.spans.size()); + for (const TokSpan& s : p.spans) w.emplace_back(p.at(s)); + return w; +} + +void apply_bytelevel(Pieces& p, const TokEncoder::Step& st, bool defer, EncodeScratch& sc) { + const bool add_prefix_space = (st.step.flags & 1) != 0; + if (add_prefix_space && !p.spans.empty() && p.spans[0].end > p.spans[0].begin && + p.buf[p.spans[0].begin] != ' ') { + const std::string first = " " + std::string(p.at(p.spans[0])); + p.spans[0] = { (uint32_t)p.buf.size(), (uint32_t)(p.buf.size() + first.size()) }; + p.buf += first; + } + /* HuggingFace's ByteLevel carries the GPT-2 pattern inside it. rad-convert normally splits + * that out into an explicit Split step so the chain reads as what it does, but a chain that + * declares it inline still has to work. */ + if (st.re) apply_split(p, *st.re, TOK_SPLIT_ISOLATED, false, sc); + if (defer) return; + std::vector w = words_of(p); + for (std::string& x : w) x = byte_encode(x); + rebuild(p, w); +} + +void apply_metaspace(std::vector& words, const VocabStep& s) { + const std::string rep = s.arg0.empty() ? std::string(k_metaspace) : s.arg0; + const int64_t prepend = s.iarg; /* 0 never, 1 first, 2 always */ + const bool split = (s.flags & 1) != 0; + + for (size_t i = 0; i < words.size(); ++i) { + std::string& w = words[i]; + if (prepend == 2 || (prepend == 1 && i == 0)) { + if (w.empty() || w.compare(0, 1, " ") != 0) w.insert(0, " "); + } + replace_all(w, " ", rep); + } + if (!split) return; + std::vector out; + for (const std::string& w : words) { + size_t i = 0; + while (i < w.size()) { + size_t j = w.find(rep, i + (w.compare(i, rep.size(), rep) == 0 ? rep.size() : 0)); + if (j == std::string::npos) { out.push_back(w.substr(i)); break; } + out.push_back(w.substr(i, j - i)); + i = j; + } + if (w.empty()) out.push_back(w); + } + words.swap(out); +} + +/* Whitespace pre-tokeniser: HuggingFace's is the regex \w+|[^\w\s]+ with Isolated behaviour, + * written here over the category flags. */ +void apply_whitespace(std::vector& words) { + std::vector out; + for (const std::string& w : words) { + const std::vector cpts = unicode_cpts_from_utf8(w); + size_t i = 0; + while (i < cpts.size()) { + const auto f = unicode_cpt_flags_from_cpt(cpts[i]); + if (f.is_whitespace) { ++i; continue; } + const bool word = f.is_letter || f.is_number || cpts[i] == '_'; + size_t j = i; + while (j < cpts.size()) { + const auto g = unicode_cpt_flags_from_cpt(cpts[j]); + if (g.is_whitespace) break; + const bool wj = g.is_letter || g.is_number || cpts[j] == '_'; + if (wj != word) break; + ++j; + } + std::string piece; + for (size_t k = i; k < j; ++k) piece += unicode_cpt_to_utf8(cpts[k]); + out.push_back(std::move(piece)); + i = j; + } + } + words.swap(out); +} + +void apply_punctuation(std::vector& words, const VocabStep& s) { + const int64_t behavior = s.iarg; + std::vector out; + for (const std::string& w : words) { + const std::vector cpts = unicode_cpts_from_utf8(w); + std::string acc; + for (uint32_t c : cpts) { + const auto f = unicode_cpt_flags_from_cpt(c); + const bool punct = f.is_punctuation || f.is_symbol; + if (punct) { + if (!acc.empty()) { out.push_back(acc); acc.clear(); } + if (behavior != TOK_SPLIT_REMOVED) out.push_back(unicode_cpt_to_utf8(c)); + } else { + acc += unicode_cpt_to_utf8(c); + } + } + if (!acc.empty()) out.push_back(acc); + } + words.swap(out); +} + +void apply_digits(std::vector& words, const VocabStep& s) { + const bool individual = (s.flags & 1) != 0; + std::vector out; + for (const std::string& w : words) { + const std::vector cpts = unicode_cpts_from_utf8(w); + std::string acc; + bool acc_digit = false; + for (uint32_t c : cpts) { + const bool d = unicode_cpt_flags_from_cpt(c).is_number; + if (acc.empty()) { acc_digit = d; acc += unicode_cpt_to_utf8(c); continue; } + if (d != acc_digit || (d && individual)) { + out.push_back(acc); + acc.clear(); + acc_digit = d; + } + acc += unicode_cpt_to_utf8(c); + } + if (!acc.empty()) out.push_back(acc); + } + words.swap(out); +} + +/* --- models ------------------------------------------------------------------------------ */ + +/* Word -> ids within one encode() call. Prose and code repeat their words heavily, so most words + * are merged once per call and then copied; the ids depend on nothing but the word, so the copy + * is exact. */ +class WordCache { +public: + static constexpr size_t kMaxKey = 128; + + bool find(std::string_view w, uint64_t h, std::vector& out) const { + if (slots_.empty()) return false; + for (size_t i = h & mask_;; i = (i + 1) & mask_) { + const Slot& s = slots_[i]; + if (s.klen == kEmpty) return false; + if (s.hash == h && s.klen == w.size() && + std::memcmp(keys_.data() + s.koff, w.data(), w.size()) == 0) { + out.insert(out.end(), ids_.begin() + s.ioff, ids_.begin() + s.ioff + s.ilen); + return true; + } + } + } + + void insert(std::string_view w, uint64_t h, const int32_t* ids, size_t n) { + if ((n_ + 1) * 2 > slots_.size()) grow(); + for (size_t i = h & mask_;; i = (i + 1) & mask_) { + Slot& s = slots_[i]; + if (s.klen != kEmpty) continue; + s = { h, (uint32_t)keys_.size(), (uint32_t)w.size(), (uint32_t)ids_.size(), (uint32_t)n }; + keys_.append(w.data(), w.size()); + ids_.insert(ids_.end(), ids, ids + n); + ++n_; + return; + } + } + +private: + static constexpr uint32_t kEmpty = UINT32_MAX; + struct Slot { uint64_t hash; uint32_t koff, klen, ioff, ilen; }; + std::vector slots_; + std::string keys_; + std::vector ids_; + size_t n_ = 0, mask_ = 0; + + void grow() { + std::vector old; + old.swap(slots_); + const size_t cap = old.empty() ? 1024 : old.size() * 2; + slots_.assign(cap, Slot{ 0, 0, kEmpty, 0, 0 }); + mask_ = cap - 1; + for (const Slot& s : old) { + if (s.klen == kEmpty) continue; + size_t i = s.hash & mask_; + while (slots_[i].klen != kEmpty) i = (i + 1) & mask_; + slots_[i] = s; + } + } +}; + +/* One word through the merge. The ids a symbol carries are the LOWEST id spelling its text, which + * is what the merge table is keyed on and what the word finally emits. */ +void bpe_word(const TokEncoder& e, std::string_view w, std::vector& out, + EncodeScratch& sc) { + const bool raw = e.defer_bytelevel >= 0; + const TokTable& table = raw ? e.raw : e.text; + + /* A user-defined token is taken whole rather than re-split. Added tokens are exact strings + * the vocabulary promises to round-trip; decomposing one into codepoints and merging back + * can land on a different sequence, because the merge table was never fitted over them. + * + * ORDINARY VOCABULARY ENTRIES STILL GO THROUGH THE MERGE LOOP, which is HuggingFace's + * behaviour at `ignore_merges: false` and is what every checkpoint in scope declares. A + * vocabulary setting it TRUE wants the same short-circuit for any word that is already a + * token, and this engine does not honour the flag: core/text/tokenizer_json.cpp only warns + * when it is set, and the vocabulary has nowhere to carry it. Such a model would tokenise + * differently here than it does in transformers, mostly on rare words. Supporting it is a + * vocabulary field, not a change to this loop. */ + const int32_t whole = table.find(w); + if (whole >= 0 && e.types[whole] == RAD_TT_USER_DEFINED) { + out.push_back(whole); + return; + } + const uint8_t known = whole >= 0 ? e.self_merges[whole].load(std::memory_order_relaxed) : 0; + if (known == 1) { + out.push_back(whole); + return; + } + + std::vector& syms = sc.syms; + syms.clear(); + const size_t n = w.size(); + if (raw) { + for (size_t i = 0; i < n; ++i) + syms.push_back({ (uint32_t)i, 1, e.byte_sym[(unsigned char)w[i]] }); + } else { + for (size_t i = 0; i < n; ) { + const size_t len = std::min(unicode_len_utf8(w[i]), n - i); + syms.push_back({ (uint32_t)i, (uint32_t)len, table.find(w.substr(i, len)) }); + i += len; + } + } + bpe_merge(syms, e.merges); + if (whole >= 0 && known == 0) { + const bool itself = syms.size() == 1 && syms[0].id == whole; + e.self_merges[whole].store(itself ? 1 : 2, std::memory_order_relaxed); + } + + for (const BpeSym& s : syms) { + if (s.id >= 0) { out.push_back(s.id); continue; } + const std::string_view str = w.substr(s.start, s.len); + + /* Miss. Decompose into single-byte tokens; how a byte is SPELT depends on the chain. + * Under ByteLevel every byte is already its own mapped codepoint, so the piece splits at + * codepoint boundaries; under byte fallback it is "<0xNN>". */ + if (raw) { + for (unsigned char c : str) { + const int32_t b = e.byte_sym[c]; + if (b >= 0) out.push_back(b); + else RAD_WARN("tokenizer: no token for byte-level piece '%s'", + alphabet().to_utf8[c].c_str()); + } + } else if (e.bytelevel) { + for (size_t k = 0; k < str.size(); ) { + const size_t m = std::min(unicode_len_utf8(str[k]), str.size() - k); + const int32_t b = e.text.find(str.substr(k, m)); + if (b >= 0) out.push_back(b); + else RAD_WARN("tokenizer: no token for byte-level piece '%s'", + std::string(str.substr(k, m)).c_str()); + k += m; + } + } else if (e.byte_fallback) { + for (unsigned char c : str) { + const int32_t b = e.byte_tok[c]; + if (b >= 0) out.push_back(b); + else if (e.unk >= 0) out.push_back(e.unk); + } + } else if (e.unk >= 0) { + out.push_back(e.unk); + } else { + RAD_WARN("tokenizer: piece '%s' is not in the vocab and the chain declares neither " + "ByteLevel nor ByteFallback; it is dropped", std::string(str).c_str()); + } + } +} + +void bpe(const TokEncoder& e, const Pieces& p, std::vector& out, EncodeScratch& sc, + WordCache& cache) { + const bool raw = e.defer_bytelevel >= 0; + for (const TokSpan& s : p.spans) { + const std::string_view w = p.at(s); + if (w.empty()) continue; + /* A one-byte word of a byte-level vocab is the token of that byte: the whole-word lookup + * and the merge both land on byte_sym, and a missing one is the fallback's warning. */ + if (raw && w.size() == 1 && e.byte_sym[(unsigned char)w[0]] >= 0) { + out.push_back(e.byte_sym[(unsigned char)w[0]]); + continue; + } + if (w.size() > WordCache::kMaxKey) { bpe_word(e, w, out, sc); continue; } + const uint64_t h = tok_hash(w); + if (cache.find(w, h, out)) continue; + const size_t start = out.size(); + bpe_word(e, w, out, sc); + cache.insert(w, h, out.data() + start, out.size() - start); + } +} + +/* Unigram, by Viterbi over a prefix trie -- SentencePiece's algorithm, in shape from + * llama.cpp's llm_tokenizer_ugm_session. Scores are summed in double precision because the + * reference implementation does and the argmax genuinely differs in float on long inputs. */ +void unigram(const Vocab& v, const TokEncoder& e, const std::string& text, + std::vector& out) { + if (text.empty()) return; + const size_t n = text.size(); + + struct Best { int32_t id; size_t from; double score; }; + std::vector best(n + 1, { v.unk(), 0, -DBL_MAX }); + best[0] = { v.unk(), 0, 0.0 }; + + /* The unknown-token penalty: SentencePiece uses (min score - 10). Recomputing it here rather + * than storing it keeps the .rad from carrying a derived number that could disagree. */ + double unk_penalty = 0.0; + if (!v.build().scores.empty()) { + unk_penalty = *std::min_element(v.build().scores.begin(), v.build().scores.end()) - 10.0; + } + + for (size_t i = 0; i < n; ) { + const size_t cp_len = std::min(unicode_len_utf8(text[i]), n - i); + bool matched_whole_cp = false; + /* Longest-prefix scan. A trie would beat this on a large vocab; the substring lookup is + * O(len) with a bounded len because no vocab entry is longer than the longest token, and + * that bound is what keeps it linear. */ + const size_t max_len = std::min(n - i, (size_t)256); + for (size_t l = 1; l <= max_len; ++l) { + const int32_t id = e.text.find(std::string_view(text.data() + i, l)); + if (id < 0) continue; + if (l == cp_len) matched_whole_cp = true; + const double sc = v.type(id) == RAD_TT_USER_DEFINED ? 0.0 : (double)v.score(id); + const double cand = best[i].score + sc; + if (cand > best[i + l].score) best[i + l] = { id, i, cand }; + } + if (!matched_whole_cp) { + const double cand = best[i].score + unk_penalty; + if (cand > best[i + cp_len].score) best[i + cp_len] = { v.unk(), i, cand }; + } + i += cp_len; + } + + /* A VOCABULARY WITH NO UNK TOKEN HAS NO ID FOR TEXT NO PIECE COVERS, and the Viterbi above + * still routes such text through the unk transition -- whose id is then -1, which is not a + * token and must never reach the output. The span is spelled as byte tokens when the chain + * declares byte fallback and dropped otherwise, as bpe() does with a piece it cannot match. + * Built back to front like the rest of the backtrack, so the bytes go in reversed. */ + const int32_t unk = v.unk(); + const bool byte_fallback = unk < 0 && e.byte_fallback; + + const size_t start = out.size(); + size_t dropped = 0; + bool prev_unk = false; + for (size_t pos = n; ; ) { + const Best& b = best[pos]; + const bool is_unk = (b.id == unk); + if (is_unk && unk < 0) { + for (size_t k = pos; k-- > b.from; ) { + const unsigned char c = (unsigned char)text[k]; + const int32_t id = byte_fallback ? e.byte_tok[c] : -1; + if (id >= 0) out.push_back(id); + else ++dropped; + } + } else if (!(prev_unk && is_unk)) { + out.push_back(b.id); + } + if (b.from == 0) break; + prev_unk = is_unk; + pos = b.from; + } + std::reverse(out.begin() + start, out.end()); + if (dropped) + RAD_WARN("tokenizer: %zu byte(s) of this text have no piece in the vocab, which has no unk " + "token and %s; they are dropped", dropped, + byte_fallback ? "lacks a byte token for them" : "declares no byte fallback"); +} + +/* WordPiece: greedy longest-match-first with a continuation prefix. Kept because BERT-family + * embedding models are a real deployment and they are all WordPiece; it is 30 lines. */ +void wordpiece(const Vocab& v, const TokEncoder& e, const Pieces& p, std::vector& out) { + for (const TokSpan& s : p.spans) { + const std::string w(p.at(s)); + if (w.empty()) continue; + size_t i = 0; + std::vector piece; + bool ok = true; + while (i < w.size()) { + size_t j = w.size(); + int32_t id = -1; + for (; j > i; --j) { + std::string sub = w.substr(i, j - i); + if (i > 0) sub = "##" + sub; + id = e.text.find(sub); + if (id >= 0) break; + } + if (id < 0) { ok = false; break; } + piece.push_back(id); + i = j; + } + if (ok) out.insert(out.end(), piece.begin(), piece.end()); + else if (v.unk() >= 0) out.push_back(v.unk()); + } +} + +/* One segment -- the text between two special tokens -- through the whole chain. */ +int encode_segment(const Vocab& v, const TokEncoder& e, std::string_view seg, + std::vector& out, EncodeScratch& sc, WordCache& words) { + Pieces& p = sc.p; + p.buf.assign(seg.data(), seg.size()); + for (const TokEncoder::Step& st : e.norm) apply_norm(p.buf, st); + if (p.buf.size() > (size_t)(UINT32_MAX / 8)) { + RAD_ERR("tokenizer: a %zu-byte segment is past what one encode can index", p.buf.size()); + return RAD_E_INVAL; + } + p.spans.assign(1, TokSpan{ 0, (uint32_t)p.buf.size() }); + p.canonical = false; + + for (size_t k = 0; k < e.pre.size(); ++k) { + const TokEncoder::Step& st = e.pre[k]; + switch (st.step.kind) { + case RAD_PRE_SPLIT: + apply_split(p, *st.re, (int)st.step.iarg, (st.step.flags & 1) != 0, sc); + break; + case RAD_PRE_BYTELEVEL: + apply_bytelevel(p, st, (int)k == e.defer_bytelevel, sc); + break; + case RAD_PRE_METASPACE: { + std::vector w = words_of(p); + apply_metaspace(w, st.step); + rebuild(p, w); + break; + } + case RAD_PRE_WHITESPACE: { + std::vector w = words_of(p); + apply_whitespace(w); + rebuild(p, w); + break; + } + case RAD_PRE_PUNCTUATION: { + std::vector w = words_of(p); + apply_punctuation(w, st.step); + rebuild(p, w); + break; + } + case RAD_PRE_DIGITS: { + std::vector w = words_of(p); + apply_digits(w, st.step); + rebuild(p, w); + break; + } + case RAD_PRE_BYTE_FALLBACK: + /* A declaration about what the MODEL does with an unknown piece, not a split. + * The fallback itself lives in bpe_word, where the miss happens. */ + break; + default: + RAD_ERR("tokenizer: pre-tokeniser step %u is not implemented", st.step.kind); + return RAD_E_UNSUPPORTED; + } + } + + switch (e.kind) { + case RAD_TOK_BPE: bpe(e, p, out, sc, words); break; + case RAD_TOK_WORDPIECE: wordpiece(v, e, p, out); break; + case RAD_TOK_UNIGRAM: { + /* Unigram runs Viterbi over the whole normalised segment; the pre-tokeniser's job + * there is only to insert the metaspace, so the pieces are rejoined. */ + std::string joined; + for (const TokSpan& s : p.spans) joined += p.at(s); + unigram(v, e, joined, out); + break; + } + default: + RAD_ERR("tokenizer: kind %u has no encoder", e.kind); + return RAD_E_UNSUPPORTED; + } + return RAD_OK; +} + +} /* namespace */ + +/* ================================================================== encode */ + +int Tokenizer::init(std::shared_ptr v) { + if (!v || !v->ready()) { + RAD_ERR("tokenizer: vocab is not loaded"); + return RAD_E_STATE; + } + v_ = std::move(v); + if (log_level() >= Log::Debug) { + for (const VocabStep& s : v_->steps()) + RAD_DEBUG("tokenizer: step %s", step_describe(s).c_str()); + } + return RAD_OK; +} + +int Tokenizer::encode(std::string_view text, std::vector& out, + bool add_special, bool parse_special) const { + if (!v_ || !v_->ready()) return RAD_E_STATE; + const TokEncoder& e = *v_->enc_; + + if (add_special && v_->add_bos() && v_->bos() >= 0) out.push_back(v_->bos()); + + /* Special-token partitioning. The text is cut into (raw, token, raw, token, ...) around any + * declared special token that appears literally, before any other step touches it, because a + * special token is not something the pre-tokeniser is allowed to split. + * + * `parse_special == false` means a control token typed by a user is ordinary text. That is + * not a nicety: without it, user content containing "<|im_start|>system" reaches the model + * as an actual role switch. */ + std::vector frags; + e.specials.split(text, parse_special, frags); + + EncodeScratch sc; + WordCache words; + for (const SpecialFrag& f : frags) { + if (f.id >= 0) { out.push_back(f.id); continue; } + if (f.len == 0) continue; + const std::string_view seg = text.substr(f.off, f.len); + if (!use_cache_ || seg.size() < kSegmentCacheMin) { + RAD_TRY(encode_segment(*v_, e, seg, out, sc, words)); + continue; + } + const uint64_t h = tok_hash(seg); + if (e.cache.lookup(seg, h, out)) continue; + const size_t start = out.size(); + RAD_TRY(encode_segment(*v_, e, seg, out, sc, words)); + e.cache.insert(seg, h, out.data() + start, out.size() - start); + } + + if (add_special && v_->add_eos() && v_->eos() >= 0) out.push_back(v_->eos()); + return RAD_OK; +} + +Tokenizer::CacheStats Tokenizer::cache_stats() const { + return v_ && v_->enc_ ? v_->enc_->cache.stats() : CacheStats{}; +} + +void Tokenizer::set_cache_limit(size_t bytes) const { + if (v_ && v_->enc_) v_->enc_->cache.set_limit(bytes); +} + +void Tokenizer::clear_cache() const { + if (v_ && v_->enc_) v_->enc_->cache.clear(); +} + +/* ================================================================== decode */ + +std::string Tokenizer::piece(int32_t id, bool render_special) const { + if (!v_ || !v_->ready()) return {}; + if (id < 0 || id >= v_->n_tokens()) return {}; + + const uint8_t t = v_->type(id); + if (!render_special && (t == RAD_TT_CONTROL || t == RAD_TT_UNKNOWN)) return {}; + + /* A byte token is one byte and no decoder step applies to it -- running ByteLevel over + * "<0x0A>" would produce the literal text. */ + const int32_t b = v_->token_byte(id); + if (b >= 0) return std::string(1, (char)b); + + std::string s = v_->text(id); + /* A user-defined or control token is stored as the literal text it stands for; only NORMAL + * tokens are in the vocab's own encoding and need the decoder chain. */ + if (t == RAD_TT_CONTROL || t == RAD_TT_UNKNOWN || t == RAD_TT_USER_DEFINED) return s; + + bool any = false; + for (const VocabStep& st : v_->steps()) { + if (!step_is_dec(st.kind)) continue; + any = true; + switch (st.kind) { + case RAD_DEC_BYTELEVEL: s = byte_decode(s); break; + case RAD_DEC_METASPACE: + replace_all(s, st.arg0.empty() ? std::string(k_metaspace) : st.arg0, " "); + break; + case RAD_DEC_REPLACE: replace_all(s, st.arg0, st.arg1); break; + case RAD_DEC_STRIP: { + const std::string c = st.arg0.empty() ? std::string(" ") : st.arg0; + int32_t start = (int32_t)(st.iarg & 0xFFFFFFFF); + int32_t stop = (int32_t)(st.iarg >> 32); + while (start-- > 0 && s.size() >= c.size() && s.compare(0, c.size(), c) == 0) + s.erase(0, c.size()); + while (stop-- > 0 && s.size() >= c.size() && + s.compare(s.size() - c.size(), c.size(), c) == 0) + s.erase(s.size() - c.size()); + break; + } + case RAD_DEC_FUSE: + case RAD_DEC_BYTE_FALLBACK: + /* Both are sequence-level: Fuse concatenates adjacent pieces and ByteFallback + * reassembles "<0xNN>" runs. Per-token there is nothing to do, and the + * sequence-level behaviour is what Detokenizer's buffering already is. */ + break; + default: + RAD_WARN("tokenizer: decoder step %u is not implemented", st.kind); + break; + } + } + /* A vocab with no declared decoder is a vocab whose tokens are already text -- which is + * true for unigram and wordpiece and false for byte-level BPE, so the absence is only safe + * when it was declared. It is; rad-convert emits the chain it read. */ + (void)any; + return s; +} + +std::string Tokenizer::decode(const std::vector& ids, bool render_special) const { + std::string out; + for (int32_t id : ids) out += piece(id, render_special); + return out; +} + +/* ================================================================== Detokenizer */ + +Detokenizer::Detokenizer(std::shared_ptr v, std::vector stops, + bool render_special, const std::vector& preserved) + : v_(std::move(v)), stops_(std::move(stops)), render_special_(render_special) { + /* RESOLVED BY TOKENISING THE MARKER, NOT BY LOOKING IT UP. What the chat format hands over + * are the MARKERS its parser scans for -- `" arrives as ""; emitting " 0 && back < 4) { + --i; ++back; + const unsigned char c = (unsigned char)pending_[i]; + if ((c & 0xC0) == 0x80) continue; /* continuation, keep walking back */ + const size_t need = unicode_len_utf8((char)c); + if (need > pending_.size() - i) cut = i; /* the sequence is not all here yet */ + break; + } + + /* (2) the longest suffix of pending_ that is a proper prefix of some stop string. */ + if (!stops_.empty()) { + const size_t limit = std::min(pending_.size(), max_stop_ - 1); + for (size_t n = limit; n > 0; --n) { + const char* tail = pending_.data() + pending_.size() - n; + bool is_prefix = false; + for (const std::string& s : stops_) { + if (s.size() > n && std::memcmp(s.data(), tail, n) == 0) { is_prefix = true; break; } + } + if (is_prefix) { cut = std::min(cut, pending_.size() - n); break; } + } + } + return cut; +} + +/* WHATWG's replacement policy: one U+FFFD per maximal subpart that cannot begin a well-formed + * sequence, which is what browsers and every other inference server do. The alternative -- one + * U+FFFD per bad byte -- turns a truncated three-byte character into three replacement + * characters, which reads as three lost characters rather than the one that was actually lost. */ +std::string utf8_sanitize(std::string_view s) { + /* The common case is a string that is already valid, and it must not be copied byte by byte. */ + std::string out; + size_t i = 0, good = 0; /* [good, i) is verified and not yet appended */ + const size_t n = s.size(); + auto flush_good = [&] { out.append(s.data() + good, i - good); good = i; }; + + while (i < n) { + const unsigned char c = (unsigned char)s[i]; + if (c < 0x80) { ++i; continue; } + + /* Length, and the range the SECOND byte is restricted to. The second-byte bounds are what + * reject overlong encodings, surrogates and anything past U+10FFFF without decoding. */ + size_t len; unsigned char lo, hi; + if (c >= 0xC2 && c <= 0xDF) { len = 2; lo = 0x80; hi = 0xBF; } + else if (c == 0xE0) { len = 3; lo = 0xA0; hi = 0xBF; } + else if (c >= 0xE1 && c <= 0xEC) { len = 3; lo = 0x80; hi = 0xBF; } + else if (c == 0xED) { len = 3; lo = 0x80; hi = 0x9F; } /* no surrogates */ + else if (c >= 0xEE && c <= 0xEF) { len = 3; lo = 0x80; hi = 0xBF; } + else if (c == 0xF0) { len = 4; lo = 0x90; hi = 0xBF; } + else if (c >= 0xF1 && c <= 0xF3) { len = 4; lo = 0x80; hi = 0xBF; } + else if (c == 0xF4) { len = 4; lo = 0x80; hi = 0x8F; } /* <= U+10FFFF */ + else { len = 0; lo = 0; hi = 0; } /* 0x80-0xC1, 0xF5+ */ + + size_t k = 1; + if (len) { + for (; k < len && i + k < n; ++k) { + const unsigned char d = (unsigned char)s[i + k]; + const unsigned char l = (k == 1) ? lo : 0x80, h = (k == 1) ? hi : 0xBF; + if (d < l || d > h) break; + } + } + if (len && k == len) { i += len; continue; } + + flush_good(); + out += "\xEF\xBF\xBD"; /* U+FFFD */ + i += k; /* the maximal subpart, never zero */ + good = i; + } + flush_good(); + return out; +} + +std::string Detokenizer::push(int32_t token) { + if (!v_ || !v_->ready() || stopped_) return {}; + + Tokenizer t; + /* Constructing a Tokenizer per push looks wasteful and is not: it holds a shared_ptr and + * nothing else, and piece() is a pure function of the vocab. Keeping one as a member would + * make Detokenizer non-copyable for no gain. */ + if (t.init(std::const_pointer_cast(std::const_pointer_cast(v_))) < 0) + return {}; + + std::string p = t.piece(token, render_special_ || preserved_.count(token) != 0); + + /* HuggingFace's decoders strip the leading space that Metaspace's prepend added. Only the + * first piece of a stream can carry it, which is why this is a member flag and not a + * property of the piece. */ + if (first_) { + first_ = false; + for (const VocabStep& s : v_->steps()) { + if (s.kind == RAD_DEC_METASPACE && s.iarg != 0 && !p.empty() && p[0] == ' ') { + p.erase(0, 1); + break; + } + } + } + + all_ += p; + pending_ += p; + + /* A complete stop string inside pending_ ends the stream. Everything before it is emitted; + * the stop string and anything after it never is. */ + if (!stops_.empty()) { + size_t best = std::string::npos; + const std::string* which = nullptr; + for (const std::string& s : stops_) { + const size_t m = pending_.find(s); + if (m != std::string::npos && m < best) { best = m; which = &s; } + } + if (which) { + std::string out = pending_.substr(0, best); + pending_.clear(); + stopped_ = true; + stop_hit_ = *which; + return utf8_sanitize(out); + } + } + + const size_t cut = safe_prefix(); + if (cut == 0) return {}; + std::string out = pending_.substr(0, cut); + pending_.erase(0, cut); + return utf8_sanitize(out); +} + +std::string Detokenizer::flush() { + /* End of stream: whatever is held back will never resolve, so it goes out. An incomplete + * UTF-8 tail here means the model stopped mid-codepoint, which is a real thing a length limit + * does; it leaves as one U+FFFD rather than as the raw bytes, because the raw bytes do not + * survive being put into a JSON string and the client would get an error in place of the + * whole answer. */ + std::string out; + out.swap(pending_); + return utf8_sanitize(out); +} + +} /* namespace rad */ diff --git a/core/text/tokenizer.h b/core/text/tokenizer.h new file mode 100644 index 00000000..532970f7 --- /dev/null +++ b/core/text/tokenizer.h @@ -0,0 +1,313 @@ +/* tokenizer.h -- the tokeniser, driven by the step chain baked into the .rad. + * + * spec §12: "The tokenizer is the one place llama.cpp's answer is Python." Their vocab is + * GGUF-shaped, the tokenizer.json -> vocab mapping lives in convert_hf_to_gguf.py, and at RUNTIME + * they identify the pre-tokeniser by HASHING tokenizer.json against a hardcoded enum. An + * unrecognised model therefore gets the default split, and the symptom of that is plausible text + * with wrong token boundaries -- the hardest kind of wrong to notice, because nothing crashes and + * the perplexity moves by a few percent. + * + * So the chain is DECLARED rather than recognised. rad-convert reads tokenizer.json's + * normalizer / pre_tokenizer / decoder sections and emits them as RadVocabStep rows; this file + * executes those rows in order. A model nobody has ever seen tokenises correctly if its + * tokenizer.json is honest, and a model whose chain we cannot express fails at CONVERT time with + * the step named, which is a diagnosis rather than a silent 2% regression. + * + * A `Split` step is a regex, and it is COMPILED at load (tokenizer_regex.h) into a DFA that + * reproduces what HuggingFace tokenizers' Oniguruma reports for it, over Oniguruma's own Unicode + * tables. A pattern outside the dialect that compiler implements does not load: the refusal names + * the construct, and there is no second matcher behind it. + * + * What is lifted from llama.cpp (06938ac12, MIT -- see vendor/UPSTREAM): + * - the byte-level alphabet and the unicode category tables the non-regex steps read + * (vendor/llama/src/unicode*) + * - the shape of the BPE bigram queue and the UGM Viterbi (src/llama-vocab.cpp) + * The last of those is re-expressed here rather than vendored: llama-vocab.cpp is welded to + * llama_model_loader, GGML_ASSERT and the llama_vocab class, so it is a file we would have had + * to modify heavily, and spec §12 says such a file belongs in core/ under our own name. + */ +#pragma once +#include "rad_internal.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace rad { + +class GgufFile; +struct TokEncoder; + +/* ================================================================== the mutable vocab */ + +/* One row of the declared chain, in the form rad-convert builds and the .rad bakes. + * + * `kind` is a RAD_NORM_* / RAD_PRE_* / RAD_DEC_* value from rad_format.h and its numeric range + * says which of the three chains the row belongs to, so the three are ONE list in declared order + * and no reader has to reassemble them. Per-kind meaning of flags/args is documented at + * `step_describe()` in tokenizer.cpp; it is the contract rad-convert writes against. */ +struct VocabStep { + uint32_t kind = 0; + uint32_t flags = 0; + std::string arg0, arg1; + int64_t iarg = 0; +}; + +/* Kind ranges, matching the enum blocks in rad_format.h. */ +inline bool step_is_norm(uint32_t k) { return k >= 1 && k < 32; } +inline bool step_is_pre (uint32_t k) { return k >= 32 && k < 64; } +inline bool step_is_dec (uint32_t k) { return k >= 64 && k < 96; } + +/* Everything the tokeniser needs, in a form that can be built, inspected, written and read. + * + * The engine could bind directly to the mmapped .rad and save copying 248K token strings, and + * deliberately does not: one construction path means the tokeniser that rad-convert tests with is + * byte-for-byte the tokeniser the server runs. The cost is a few megabytes and a few tens of + * milliseconds at load, against a model measured in gigabytes -- which is not a cost. */ +struct VocabBuild { + uint32_t kind = RAD_TOK_BPE; + + std::vector tokens; /* id -> text, in the vocab's own encoding */ + std::vector scores; /* unigram only; empty otherwise */ + std::vector types; /* RAD_TT_*; empty means all RAD_TT_NORMAL */ + std::vector> merges; /* BPE, in rank order */ + + std::vector steps; /* the whole declared chain, in order */ + + int32_t bos = -1, eos = -1, eot = -1, pad = -1, unk = -1, sep = -1; + bool add_bos = false, add_eos = false; + + std::string chat_template; + + /* Diagnostics only: what rad-convert thought it was reading. Not baked. */ + std::string source; +}; + +/* ================================================================== the loaded vocab */ + +class Vocab { +public: + int load(VocabBuild b); /* takes ownership; RAD_OK or negative */ + bool ready() const { return ready_; } + + uint32_t kind() const { return b_.kind; } + int32_t n_tokens() const { return (int32_t)b_.tokens.size(); } + + const std::string& text(int32_t id) const; + uint8_t type(int32_t id) const; + float score(int32_t id) const; + bool is_eog(int32_t id) const; /* eos, eot, or a declared extra */ + /* Every one of them, by id. The server needs the SPELLINGS: a chat format can fold the turn + * terminator into its last marker, so the decoder has to render it for the reply parser -- + * and then whatever the parser did not consume has to come back off the content, because a + * terminator is never something the user asked to read. */ + const std::vector& eog() const { return eog_; } + + /* -1 when the exact text is not a token. */ + int32_t find(std::string_view text) const; + /* BPE merge rank of the pair, or -1. */ + int32_t merge_rank(std::string_view left, std::string_view right) const; + + int32_t bos() const { return b_.bos; } + int32_t eos() const { return b_.eos; } + int32_t eot() const { return b_.eot; } + int32_t unk() const { return b_.unk; } + int32_t pad() const { return b_.pad; } + bool add_bos() const { return b_.add_bos; } + bool add_eos() const { return b_.add_eos; } + const std::string& chat_template() const { return b_.chat_template; } + + const std::vector& steps() const { return b_.steps; } + const std::vector& special_ids() const { return special_; } + const VocabBuild& build() const { return b_; } + + /* The byte a RAD_TT_BYTE token stands for, or -1. Both spellings are recognised: SPM's + * "<0xF0>" and byte-level BPE's single mapped codepoint. */ + int32_t token_byte(int32_t id) const; + +private: + VocabBuild b_; + bool ready_ = false; + std::unordered_map text_to_id_; + std::unordered_map merge_rank_; /* (lhs id << 32 | rhs id) -> rank */ + std::vector special_; /* ids the pre-splitter must isolate */ + std::vector byte_of_; /* id -> byte, or -1 */ + /* Every token that ends a generation, not just the one the header had room for. Built in + * load(); see the comment there for why a container's `eos` alone is not the whole set. */ + std::vector eog_; + /* The chain compiled for encoding: the Split DFAs, the flat token and merge tables, the + * special-token matcher and the segment cache. Built in load(), shared by every Tokenizer + * over this vocab and by every copy of it. */ + std::shared_ptr enc_; + friend class Tokenizer; + friend class Detokenizer; +}; + +/* ================================================================== encode */ + +class Tokenizer { +public: + int init(std::shared_ptr v); + + /* `add_special` prepends BOS / appends EOS as the vocab declares. `parse_special` lets + * control tokens in the raw text be recognised as themselves -- which the server wants for a + * rendered chat template and must NOT have for user content, because otherwise a user can + * type "<|im_start|>system" and reach the system role. */ + int encode(std::string_view text, std::vector& out, + bool add_special, bool parse_special) const; + + /* Non-streaming detokenise. The streaming one is Detokenizer below and it is the one the + * server uses; this exists for tests, logging and the /v1/completions echo path. */ + std::string decode(const std::vector& ids, bool render_special = false) const; + + /* One token's text after the decoder chain. Does not resolve partial UTF-8 -- that is + * exactly what Detokenizer is for. */ + std::string piece(int32_t id, bool render_special = false) const; + + const Vocab& vocab() const { return *v_; } + + /* THE SEGMENT CACHE. encode() cuts its text at special tokens before anything else touches + * it, and every piece between two of them is normalised, pre-tokenised and merged on its own: + * no step of the chain reads across a special token, and none reads anything but the piece + * (a Metaspace "first" prepend, a ByteLevel prefix space and every normaliser apply to each + * piece as if it were the whole text). A piece's ids are therefore a function of its bytes + * and the vocab alone, and a cache from the bytes to the ids returns exactly what encoding + * them again would. That is what makes a re-sent conversation cost only what is new in it: an + * agent's history arrives as the same pieces between the same `<|im_start|>` markers, turn + * after turn. + * + * The cache belongs to the vocab, so every Tokenizer over it shares it. It is keyed on the + * whole piece (the hash only picks the bucket), bounded in bytes with least-recently-used + * eviction, and locked for concurrent encodes. Pieces under kSegmentCacheMin bytes are not + * cached: re-encoding them costs less than the lookup. `set_segment_cache(false)` makes this + * Tokenizer bypass it, which is how the tests and rad-tokcheck compare the two. */ + static constexpr size_t kSegmentCacheMin = 64; + static constexpr size_t kSegmentCacheDefault = size_t(64) << 20; + void set_segment_cache(bool on) { use_cache_ = on; } + struct CacheStats { + uint64_t hits = 0, misses = 0; + size_t entries = 0, bytes = 0, limit = 0; + }; + CacheStats cache_stats() const; + void set_cache_limit(size_t bytes) const; + void clear_cache() const; + +private: + std::shared_ptr v_; + bool use_cache_ = true; +}; + +/* ================================================================== streaming decode */ + +/* Replace every byte that is not part of a well-formed UTF-8 sequence with U+FFFD, and leave + * everything else alone. A byte-fallback vocab can emit a byte that no continuation completes -- + * `<0xC1>` is a lead byte for an encoding that is overlong and therefore never legal -- and the + * generated text goes straight into a JSON string, where an invalid byte is not a mojibake + * character but a 500: nlohmann::json::dump throws type_error.316 on it and the client gets an + * engine error instead of the model's answer. Sanitising is the only option that keeps the + * response: the bytes cannot be held back (nothing will complete them) and dropping them silently + * would hide that the model produced something undecodable. Well-formed input is returned byte for + * byte, so this is a no-op on every normal completion. */ +std::string utf8_sanitize(std::string_view s); + + +/* Byte-level BPE emits partial UTF-8 sequences -- a single token can be one byte of a + * three-byte codepoint -- and a stop string can straddle a chunk boundary. Both are buffered + * until they resolve (spec §12). Emitting either one early is a visible bug: the first puts a + * replacement character in the user's stream, the second leaks "". + * + * The contract: push() returns text that is FINAL. It will never be retracted, it is always + * WELL-FORMED UTF-8, and it is never a prefix of a stop string. Whatever is still ambiguous stays + * inside until a later push resolves it or flush() gives up on it. A sequence that turns out to be + * malformed rather than merely unfinished -- a byte-fallback vocab can emit one -- leaves as + * U+FFFD (utf8_sanitize above) instead of as raw bytes, since the raw bytes cannot be put into a + * JSON string and would cost the client the whole response. */ +class Detokenizer { +public: + Detokenizer() = default; + /* `preserved` is the tokens that must reach the caller as TEXT even though they are CONTROL. + * A tool-calling format is MADE of them -- MiniCPM5 writes its calls with ``, ``, every one a control token -- so suppressing them the + * way a control token is normally suppressed hands the reply parser the arguments with the + * structure removed, and the call comes back to the client as prose. The chat template says + * which ones it needs (common_chat_params::preserved_tokens); nothing else is unsuppressed. */ + Detokenizer(std::shared_ptr v, std::vector stops = {}, + bool render_special = false, const std::vector& preserved = {}); + + std::string push(int32_t token); + std::string flush(); + + /* True once a stop string has been seen. The text before it has already been returned; the + * stop string itself and anything after it never is. */ + bool stopped() const { return stopped_; } + const std::string& stop_hit() const { return stop_hit_; } + + /* Everything pushed so far, stop string included. The scheduler wants this to decide whether + * a request finished on a stop or on a length limit. */ + const std::string& text() const { return all_; } + + void reset(); + +private: + std::shared_ptr v_; + std::vector stops_; + bool render_special_ = false; + std::unordered_set preserved_; /* control ids this stream renders anyway */ + std::string pending_; /* decoded but not yet safe to emit */ + std::string all_; /* everything, for the caller's record */ + bool stopped_ = false; + std::string stop_hit_; + size_t max_stop_ = 0; + bool first_ = true; + + size_t safe_prefix() const; /* how much of pending_ can be released */ +}; + +/* ================================================================== sources and sinks */ + +/* rad-convert owns the .rad's single string blob; the vocab section only needs to intern into + * it. Passing the interner rather than a blob keeps the two writers from disagreeing about who + * owns offset 0. */ +struct StringSink { + virtual ~StringSink() = default; + virtual rad_stroff intern(std::string_view s) = 0; +}; + +/* Build a VocabBuild from a HuggingFace tokenizer.json. + * + * This is the function spec §12 is about: it INTERPRETS the declared normalizer / pre_tokenizer / + * decoder chain instead of hashing the file. Returns RAD_OK, or a negative RAD_E_*; in + * particular RAD_E_UNSUPPORTED when the file declares a component we cannot express as a + * RadVocabStep, with the component named in the log. Failing there is the point -- a chain we + * cannot express must not become a chain we silently approximate. */ +int parse_tokenizer_json(const char* path, VocabBuild& out); +/* Same, from an in-memory buffer, for a tokenizer.json that arrived some other way. */ +int parse_tokenizer_json_buf(std::string_view json, const char* origin, VocabBuild& out); + +/* Build a VocabBuild from a GGUF's tokenizer.ggml.* metadata. + * + * GGUF has no declared chain -- it has `tokenizer.ggml.pre`, a name llama.cpp derived by hashing + * the original tokenizer.json. So this reconstructs the chain from that name against a table of + * the ones we know, and returns RAD_E_UNSUPPORTED for a name we do not, rather than falling back + * to a default split. That refusal is the whole difference from llama.cpp's behaviour, and it is + * why converting from the original tokenizer.json is the preferred path. */ +int vocab_from_gguf(const GgufFile& g, VocabBuild& out); + +/* Serialise into the .rad's vocab section. `section_file_off` is where rad-convert will place + * the section; every offset written into the RadVocabHeader is absolute from the start of the + * file, per rad_format.h's rule that "every offset is from the start of the file". */ +int vocab_serialize(const VocabBuild& in, StringSink& strings, uint64_t section_file_off, + std::vector& section_out); +/* Read it back. `file_base` is the mmapped .rad; `h` points inside it. */ +int vocab_deserialize(const void* file_base, uint64_t file_bytes, + const RadVocabHeader* h, VocabBuild& out); + +/* Human-readable one-liner for a step, for --debug-graph and for the convert log. */ +std::string step_describe(const VocabStep& s); + +} /* namespace rad */ diff --git a/core/text/tokenizer_bpe.cpp b/core/text/tokenizer_bpe.cpp new file mode 100644 index 00000000..d7ef902a --- /dev/null +++ b/core/text/tokenizer_bpe.cpp @@ -0,0 +1,185 @@ +#include "text/tokenizer_bpe.h" + +#include +#include + +namespace rad { + +/* ================================================================== TokTable */ + +void TokTable::reserve(size_t n) { + size_t cap = 16; + while (cap < n * 2) cap <<= 1; + if (cap <= slots_.size()) return; + std::vector old; + old.swap(slots_); + slots_.assign(cap, Slot{}); + mask_ = cap - 1; + for (const Slot& s : old) { + if (s.id < 0) continue; + const uint64_t h = tok_hash(keys_.data() + s.off, s.len); + size_t i = h & mask_; + while (slots_[i].id >= 0) i = (i + 1) & mask_; + slots_[i] = s; + } +} + +void TokTable::grow() { reserve(std::max(16, (n_ + 1) * 2)); } + +bool TokTable::insert(std::string_view key, int32_t id) { + if ((n_ + 1) * 2 > slots_.size()) grow(); + const uint64_t h = tok_hash(key); + const uint32_t tag = (uint32_t)(h >> 32); + for (size_t i = h & mask_;; i = (i + 1) & mask_) { + Slot& s = slots_[i]; + if (s.id < 0) { + s.off = (uint32_t)keys_.size(); + s.len = (uint32_t)key.size(); + s.id = id; + s.tag = tag; + keys_.append(key.data(), key.size()); + ++n_; + return true; + } + if (s.tag == tag && s.len == key.size() && + std::memcmp(keys_.data() + s.off, key.data(), key.size()) == 0) + return false; + } +} + +int32_t TokTable::find(std::string_view key) const { + if (slots_.empty()) return -1; + const uint64_t h = tok_hash(key); + const uint32_t tag = (uint32_t)(h >> 32); + for (size_t i = h & mask_;; i = (i + 1) & mask_) { + const Slot& s = slots_[i]; + if (s.id < 0) return -1; + if (s.tag == tag && s.len == key.size() && + std::memcmp(keys_.data() + s.off, key.data(), key.size()) == 0) + return s.id; + } +} + +/* ================================================================== MergeTable */ + +void MergeTable::reserve(size_t n) { + size_t cap = 16; + while (cap < n * 2) cap <<= 1; + if (cap <= slots_.size()) return; + std::vector old; + old.swap(slots_); + slots_.assign(cap, Slot{}); + mask_ = cap - 1; + for (const Slot& s : old) { + if (s.key == kEmpty) continue; + size_t i = mix(s.key) & mask_; + while (slots_[i].key != kEmpty) i = (i + 1) & mask_; + slots_[i] = s; + } +} + +void MergeTable::grow() { reserve(std::max(16, (n_ + 1) * 2)); } + +bool MergeTable::insert(int32_t l, int32_t r, uint32_t rank, int32_t merged) { + if (l < 0 || r < 0) return false; + if ((n_ + 1) * 2 > slots_.size()) grow(); + const uint64_t key = ((uint64_t)(uint32_t)l << 32) | (uint32_t)r; + for (size_t i = mix(key) & mask_;; i = (i + 1) & mask_) { + Slot& s = slots_[i]; + if (s.key == key) return false; + if (s.key == kEmpty) { + s.key = key; + s.rank = rank; + s.merged = merged; + ++n_; + return true; + } + } +} + +/* ================================================================== the merge */ + +namespace { + +void merge_linear(std::vector& syms, const MergeTable& merges) { + uint32_t rank[kBpeLinearMax]; + int32_t merged[kBpeLinearMax]; + size_t len = syms.size(); + for (size_t i = 0; i + 1 < len; ++i) rank[i] = merges.find(syms[i].id, syms[i + 1].id, &merged[i]); + rank[len - 1] = UINT32_MAX; + for (;;) { + uint32_t best = UINT32_MAX; + size_t bi = 0; + for (size_t i = 0; i + 1 < len; ++i) { + if (rank[i] < best) { best = rank[i]; bi = i; } + } + if (best == UINT32_MAX) break; + syms[bi].len += syms[bi + 1].len; + syms[bi].id = merged[bi]; + /* The right symbol and the pair it started are gone; the pairs either side of the new + * symbol are recomputed. */ + for (size_t k = bi + 1; k + 1 < len; ++k) { + syms[k] = syms[k + 1]; + rank[k] = rank[k + 1]; + merged[k] = merged[k + 1]; + } + --len; + if (bi > 0) rank[bi - 1] = merges.find(syms[bi - 1].id, syms[bi].id, &merged[bi - 1]); + rank[bi] = bi + 1 < len ? merges.find(syms[bi].id, syms[bi + 1].id, &merged[bi]) : UINT32_MAX; + } + syms.resize(len); +} + +void merge_heap(std::vector& syms, const MergeTable& merges) { + struct Node { int32_t prev, next; uint32_t ver; bool alive; }; + struct Cand { + uint32_t rank, left, right, vl, vr; + int32_t merged; + /* priority_queue is a max-heap: the pair that should come out first compares greatest. */ + bool operator<(const Cand& o) const { + return rank != o.rank ? rank > o.rank : left > o.left; + } + }; + const size_t n = syms.size(); + std::vector node(n); + for (size_t i = 0; i < n; ++i) + node[i] = { (int32_t)i - 1, i + 1 < n ? (int32_t)(i + 1) : -1, 0, true }; + std::priority_queue heap; + auto offer = [&](int32_t l, int32_t r) { + if (l < 0 || r < 0) return; + int32_t m = -1; + const uint32_t rank = merges.find(syms[l].id, syms[r].id, &m); + if (rank == UINT32_MAX) return; + heap.push({ rank, (uint32_t)l, (uint32_t)r, node[l].ver, node[r].ver, m }); + }; + for (size_t i = 0; i + 1 < n; ++i) offer((int32_t)i, (int32_t)(i + 1)); + while (!heap.empty()) { + const Cand c = heap.top(); + heap.pop(); + Node& l = node[c.left]; + Node& r = node[c.right]; + if (!l.alive || !r.alive || l.ver != c.vl || r.ver != c.vr) continue; + syms[c.left].len += syms[c.right].len; + syms[c.left].id = c.merged; + l.next = r.next; + if (r.next >= 0) node[r.next].prev = (int32_t)c.left; + r.alive = false; + ++r.ver; + ++l.ver; + offer(l.prev, (int32_t)c.left); + offer((int32_t)c.left, l.next); + } + size_t w = 0; + for (size_t i = 0; i < n; ++i) if (node[i].alive) syms[w++] = syms[i]; + syms.resize(w); +} + +} /* namespace */ + +void bpe_merge(std::vector& syms, const MergeTable& merges, bool force_heap) { + if (syms.size() < 2) return; + if (syms.size() <= kBpeLinearMax && !force_heap) merge_linear(syms, merges); + else merge_heap(syms, merges); +} + +} /* namespace rad */ diff --git a/core/text/tokenizer_bpe.h b/core/text/tokenizer_bpe.h new file mode 100644 index 00000000..ba4d6bcf --- /dev/null +++ b/core/text/tokenizer_bpe.h @@ -0,0 +1,110 @@ +/* tokenizer_bpe.h -- the tables and the merge loop under Tokenizer's BPE. + * + * The merge is the textbook one and the one every reference implements: repeatedly merge the + * adjacent pair with the lowest merge rank, the leftmost pair on a tie, until no adjacent pair + * has a rank. It is kept rather than replaced by a linear-time encoder (GitHub's `bpe` crate) + * because those are exact only for vocabularies whose every token re-encodes to itself, and a + * vocabulary is not checked for that; this loop is exact for all of them. What makes it fast is + * what it runs on: symbols are token ids, a rank lookup is one probe of an open-addressed table + * keyed by the id pair, and a word of up to kLinearMax symbols is merged by a scan over a small + * array instead of a heap, which for the four-to-eight-symbol words of real text is several times + * cheaper. Long words take the heap. Both pick the same pair at every step -- lowest rank, then + * lowest position -- so they produce the same merges. + */ +#pragma once +#include +#include +#include +#include +#include +#include + +namespace rad { + +/* 64-bit hash of a byte string: eight bytes a round, a multiply-xorshift finish. */ +inline uint64_t tok_hash(const void* data, size_t n) { + const uint8_t* p = static_cast(data); + uint64_t h = 0x9E3779B97F4A7C15ull ^ (n * 0xC2B2AE3D27D4EB4Full); + while (n >= 8) { + uint64_t w; + std::memcpy(&w, p, 8); + h = (h ^ w) * 0xFF51AFD7ED558CCDull; + h ^= h >> 32; + p += 8; + n -= 8; + } + if (n) { + uint64_t w = 0; + std::memcpy(&w, p, n); + h = (h ^ w) * 0xC4CEB9FE1A85EC53ull; + } + h ^= h >> 29; + h *= 0xBF58476D1CE4E5B9ull; + h ^= h >> 32; + return h; +} +inline uint64_t tok_hash(std::string_view s) { return tok_hash(s.data(), s.size()); } + +/* Byte string -> id, open-addressed, keys packed in one buffer. FIRST INSERT WINS, which is the + * rule every lookup in the tokeniser follows: when two ids spell the same text, the lower one is + * the one the merge table and every published count refer to. */ +class TokTable { +public: + void reserve(size_t n); + bool insert(std::string_view key, int32_t id); /* false when the key was present */ + int32_t find(std::string_view key) const; + size_t size() const { return n_; } + +private: + struct Slot { uint32_t off = 0, len = 0; int32_t id = -1; uint32_t tag = 0; }; + std::vector slots_; + std::string keys_; + size_t n_ = 0; + size_t mask_ = 0; + void grow(); +}; + +/* (left id, right id) -> (rank, id of the merged text or -1). FIRST INSERT WINS here too: a + * duplicated merge keeps its lowest rank. */ +class MergeTable { +public: + void reserve(size_t n); + bool insert(int32_t l, int32_t r, uint32_t rank, int32_t merged); + /* rank, or UINT32_MAX when the pair does not merge. */ + uint32_t find(int32_t l, int32_t r, int32_t* merged) const { + if (l < 0 || r < 0 || slots_.empty()) return UINT32_MAX; + const uint64_t key = ((uint64_t)(uint32_t)l << 32) | (uint32_t)r; + for (size_t i = mix(key) & mask_;; i = (i + 1) & mask_) { + const Slot& s = slots_[i]; + if (s.key == key) { *merged = s.merged; return s.rank; } + if (s.key == kEmpty) return UINT32_MAX; + } + } + size_t size() const { return n_; } + +private: + static constexpr uint64_t kEmpty = ~0ull; + struct Slot { uint64_t key = kEmpty; uint32_t rank = 0; int32_t merged = -1; }; + static uint64_t mix(uint64_t k) { + k ^= k >> 33; + k *= 0xFF51AFD7ED558CCDull; + k ^= k >> 33; + return k; + } + std::vector slots_; + size_t n_ = 0, mask_ = 0; + void grow(); +}; + +/* One symbol of a word being merged: a byte span of the word and the id its text spells, or -1 + * when it spells no token (it then merges with nothing). */ +struct BpeSym { uint32_t start, len; int32_t id; }; + +/* Words up to this many symbols are merged by linear scan; longer ones by heap. */ +constexpr size_t kBpeLinearMax = 64; + +/* Merge `syms` in place until no adjacent pair has a rank. `force_heap` exists for the test that + * holds the two strategies to the same answer. */ +void bpe_merge(std::vector& syms, const MergeTable& merges, bool force_heap = false); + +} /* namespace rad */ diff --git a/core/text/tokenizer_json.cpp b/core/text/tokenizer_json.cpp new file mode 100644 index 00000000..027518b0 --- /dev/null +++ b/core/text/tokenizer_json.cpp @@ -0,0 +1,1028 @@ +/* tokenizer_json.cpp -- reading a vocab in, and writing it into the .rad. + * + * Three sources and one sink: + * parse_tokenizer_json() the HuggingFace file, interpreted rather than hashed. This is the + * preferred path and the one spec §12 is about. + * vocab_from_gguf() GGUF metadata, where the chain has already been lost and has to be + * reconstructed from `tokenizer.ggml.pre`, a name llama.cpp derived by + * hashing the original tokenizer.json. + * vocab_serialize() into the .rad's vocab section, and back. + */ +#include "text/tokenizer.h" +#include "text/tokenizer_regex.h" +#include "text/gguf.h" + +#include + +#include +#include +#include +#include + +namespace rad { + +using json = nlohmann::json; + +namespace { + +/* HuggingFace's SplitDelimiterBehavior, in the order our iarg encodes. */ +int behavior_from_name(const std::string& s) { + if (s == "Removed") return 0; + if (s == "Isolated") return 1; + if (s == "MergedWithPrevious") return 2; + if (s == "MergedWithNext") return 3; + if (s == "Contiguous") return 4; + return 1; /* Isolated is the default in every tokenizer.json that omits it */ +} + +int prepend_scheme_from_name(const std::string& s) { + if (s == "never") return 0; + if (s == "first") return 1; + if (s == "always") return 2; + return 2; +} + +const json* get(const json& o, const char* k) { + if (!o.is_object()) return nullptr; + auto it = o.find(k); + return it == o.end() || it->is_null() ? nullptr : &*it; +} + +std::string str_or(const json& o, const char* k, const char* dflt) { + const json* v = get(o, k); + return v && v->is_string() ? v->get() : std::string(dflt); +} + +bool bool_or(const json& o, const char* k, bool dflt) { + const json* v = get(o, k); + return v && v->is_boolean() ? v->get() : dflt; +} + +/* A regex a step carries is compiled HERE as well as when the vocab loads, so that rad-convert + * refuses a pattern outside the compiler's dialect with the construct named, instead of writing a + * container no engine will load. */ +int check_regex(const std::string& pat, const char* what, const char* origin) { + std::unique_ptr re; + std::string why; + if (TokRegex::compile(pat, &re, &why) < 0) { + RAD_ERR("%s: the %s pattern '%s' is outside the supported regex dialect: %s", origin, what, + pat.c_str(), why.c_str()); + return RAD_E_UNSUPPORTED; + } + return RAD_OK; +} + +/* HuggingFace's pattern field is either {"String": "..."} (a literal) or {"Regex": "..."}. */ +bool read_pattern(const json& o, std::string* pat, bool* is_regex) { + const json* p = get(o, "pattern"); + if (!p) return false; + if (p->is_string()) { *pat = p->get(); *is_regex = false; return true; } + const json* s = get(*p, "String"); + if (s && s->is_string()) { *pat = s->get(); *is_regex = false; return true; } + const json* r = get(*p, "Regex"); + if (r && r->is_string()) { *pat = r->get(); *is_regex = true; return true; } + return false; +} + +/* A token id out of the file, which indexes the token table as soon as it is read: a negative + * one, or one that is not an integer, writes outside it, and a huge one sizes it. `limit` is + * one past the largest id accepted (see parse_tokenizer_json_buf). */ +bool read_id(const json& v, uint64_t limit, int32_t* out) { + if (!v.is_number_integer()) return false; + if (!v.is_number_unsigned() && v.get() < 0) return false; + const uint64_t id = v.is_number_unsigned() ? v.get() : (uint64_t)v.get(); + if (id >= limit || id > (uint64_t)INT32_MAX) return false; + *out = (int32_t)id; + return true; +} + +/* --- the three chains ---------------------------------------------------------------------- */ + +int read_normalizer(const json& n, std::vector& out, const char* origin); +int read_pretok(const json& n, std::vector& out, const char* origin); +int read_decoder(const json& n, std::vector& out, const char* origin); + +int read_normalizer(const json& n, std::vector& out, const char* origin) { + if (n.is_null()) return RAD_OK; + const std::string t = str_or(n, "type", ""); + VocabStep s; + if (t == "Sequence") { + const json* seq = get(n, "normalizers"); + if (!seq || !seq->is_array()) return RAD_OK; + for (const json& c : *seq) RAD_TRY(read_normalizer(c, out, origin)); + return RAD_OK; + } + if (t == "NFC") { s.kind = RAD_NORM_NFC; out.push_back(s); return RAD_OK; } + if (t == "NFKC") { s.kind = RAD_NORM_NFKC; out.push_back(s); return RAD_OK; } + if (t == "NFD") { s.kind = RAD_NORM_NFD; out.push_back(s); return RAD_OK; } + if (t == "NFKD") { s.kind = RAD_NORM_NFKD; out.push_back(s); return RAD_OK; } + if (t == "Lowercase") { s.kind = RAD_NORM_LOWERCASE; out.push_back(s); return RAD_OK; } + if (t == "Strip") { + s.kind = RAD_NORM_STRIP; + s.flags = (bool_or(n, "strip_left", true) ? 1u : 0u) | + (bool_or(n, "strip_right", true) ? 2u : 0u); + out.push_back(s); + return RAD_OK; + } + if (t == "Prepend") { + s.kind = RAD_NORM_PREPEND; + s.arg0 = str_or(n, "prepend", ""); + out.push_back(s); + return RAD_OK; + } + if (t == "Replace") { + bool is_regex = false; + if (!read_pattern(n, &s.arg0, &is_regex)) { + RAD_ERR("%s: Replace normalizer has no readable pattern", origin); + return RAD_E_FORMAT; + } + s.kind = RAD_NORM_REPLACE; + s.flags = is_regex ? 1u : 0u; + s.arg1 = str_or(n, "content", ""); + if (is_regex) RAD_TRY(check_regex(s.arg0, "Replace", origin)); + out.push_back(s); + return RAD_OK; + } + /* Everything else is refused BY NAME rather than ignored. An ignored normaliser is a + * tokeniser that runs, produces different boundaries, and says nothing -- exactly the + * failure this component exists to remove (spec §12). */ + RAD_ERR("%s: normalizer '%s' has no RadVocabStep. Refusing rather than approximating it; " + "add a RAD_NORM_* for it if a model needs it.", origin, t.c_str()); + return RAD_E_UNSUPPORTED; +} + +int read_pretok(const json& n, std::vector& out, const char* origin) { + if (n.is_null()) return RAD_OK; + const std::string t = str_or(n, "type", ""); + VocabStep s; + if (t == "Sequence") { + const json* seq = get(n, "pretokenizers"); + if (!seq) seq = get(n, "pre_tokenizers"); + if (!seq || !seq->is_array()) return RAD_OK; + for (const json& c : *seq) RAD_TRY(read_pretok(c, out, origin)); + return RAD_OK; + } + if (t == "ByteLevel") { + s.kind = RAD_PRE_BYTELEVEL; + s.flags = (bool_or(n, "add_prefix_space", false) ? 1u : 0u) | + (bool_or(n, "use_regex", true) ? 2u : 0u); + out.push_back(s); + return RAD_OK; + } + if (t == "Split") { + bool is_regex = false; + if (!read_pattern(n, &s.arg0, &is_regex)) { + RAD_ERR("%s: Split pre-tokenizer has no readable pattern", origin); + return RAD_E_FORMAT; + } + if (!is_regex) { + /* A literal delimiter is a regex with every metacharacter escaped. Doing the escape + * at convert time keeps the runtime with one kind of Split instead of two. */ + std::string q; + for (char c : s.arg0) { + if (std::strchr("\\^$.|?*+()[]{}", c)) q += '\\'; + q += c; + } + s.arg0.swap(q); + } + s.kind = RAD_PRE_SPLIT; + s.flags = bool_or(n, "invert", false) ? 1u : 0u; + s.iarg = behavior_from_name(str_or(n, "behavior", "Isolated")); + RAD_TRY(check_regex(s.arg0, "Split", origin)); + out.push_back(s); + return RAD_OK; + } + if (t == "Metaspace") { + s.kind = RAD_PRE_METASPACE; + s.arg0 = str_or(n, "replacement", "\xe2\x96\x81"); + s.iarg = prepend_scheme_from_name(str_or(n, "prepend_scheme", "always")); + s.flags = bool_or(n, "split", true) ? 1u : 0u; + /* The pre-0.14 spelling: add_prefix_space instead of prepend_scheme. */ + if (!get(n, "prepend_scheme")) s.iarg = bool_or(n, "add_prefix_space", true) ? 2 : 0; + out.push_back(s); + return RAD_OK; + } + if (t == "Whitespace" || t == "WhitespaceSplit" || t == "BertPreTokenizer") { + s.kind = RAD_PRE_WHITESPACE; + out.push_back(s); + return RAD_OK; + } + if (t == "Punctuation") { + s.kind = RAD_PRE_PUNCTUATION; + s.iarg = behavior_from_name(str_or(n, "behavior", "Isolated")); + out.push_back(s); + return RAD_OK; + } + if (t == "Digits") { + s.kind = RAD_PRE_DIGITS; + s.flags = bool_or(n, "individual_digits", false) ? 1u : 0u; + out.push_back(s); + return RAD_OK; + } + RAD_ERR("%s: pre_tokenizer '%s' has no RadVocabStep. Refusing rather than falling back to a " + "default split -- a default split is llama.cpp's failure mode, not ours.", + origin, t.c_str()); + return RAD_E_UNSUPPORTED; +} + +int read_decoder(const json& n, std::vector& out, const char* origin) { + if (n.is_null()) return RAD_OK; + const std::string t = str_or(n, "type", ""); + VocabStep s; + if (t == "Sequence") { + const json* seq = get(n, "decoders"); + if (!seq || !seq->is_array()) return RAD_OK; + for (const json& c : *seq) RAD_TRY(read_decoder(c, out, origin)); + return RAD_OK; + } + if (t == "ByteLevel") { s.kind = RAD_DEC_BYTELEVEL; out.push_back(s); return RAD_OK; } + if (t == "Fuse") { s.kind = RAD_DEC_FUSE; out.push_back(s); return RAD_OK; } + if (t == "ByteFallback") { s.kind = RAD_DEC_BYTE_FALLBACK; out.push_back(s); return RAD_OK; } + if (t == "Metaspace") { + s.kind = RAD_DEC_METASPACE; + s.arg0 = str_or(n, "replacement", "\xe2\x96\x81"); + s.iarg = prepend_scheme_from_name(str_or(n, "prepend_scheme", "always")); + if (!get(n, "prepend_scheme")) s.iarg = bool_or(n, "add_prefix_space", true) ? 2 : 0; + out.push_back(s); + return RAD_OK; + } + if (t == "Replace") { + bool is_regex = false; + if (!read_pattern(n, &s.arg0, &is_regex)) { + RAD_ERR("%s: Replace decoder has no readable pattern", origin); + return RAD_E_FORMAT; + } + if (is_regex) { + RAD_ERR("%s: a regex Replace decoder is not implemented; the decoder runs per token " + "on the streaming path and a regex there is a per-token allocation", origin); + return RAD_E_UNSUPPORTED; + } + s.kind = RAD_DEC_REPLACE; + s.arg1 = str_or(n, "content", ""); + out.push_back(s); + return RAD_OK; + } + if (t == "Strip") { + s.kind = RAD_DEC_STRIP; + s.arg0 = str_or(n, "content", " "); + const json* a = get(n, "start"); + const json* b = get(n, "stop"); + const int64_t st = a && a->is_number() ? a->get() : 0; + const int64_t sp = b && b->is_number() ? b->get() : 0; + s.iarg = (sp << 32) | (st & 0xFFFFFFFF); + out.push_back(s); + return RAD_OK; + } + if (t == "WordPiece") { + /* WordPiece's decoder is a Replace of the continuation prefix plus a leading strip. + * Expressing it as the two steps it is keeps the runtime free of a per-model branch. */ + VocabStep r; + r.kind = RAD_DEC_REPLACE; + r.arg0 = str_or(n, "prefix", "##"); + r.arg1 = ""; + out.push_back(r); + return RAD_OK; + } + if (t == "BPEDecoder") { + VocabStep r; + r.kind = RAD_DEC_REPLACE; + r.arg0 = str_or(n, "suffix", ""); + r.arg1 = " "; + out.push_back(r); + return RAD_OK; + } + RAD_ERR("%s: decoder '%s' has no RadVocabStep", origin, t.c_str()); + return RAD_E_UNSUPPORTED; +} + +/* --- the model section --------------------------------------------------------------------- */ + +int read_model(const json& m, VocabBuild& out, const char* origin, uint64_t id_limit) { + const std::string type = str_or(m, "type", ""); + const json* vocab = get(m, "vocab"); + if (!vocab) { + RAD_ERR("%s: model has no vocab", origin); + return RAD_E_FORMAT; + } + + /* {text: id}, the BPE and WordPiece shape. The ids are dense, but nothing guarantees the + * JSON order matches the id order, so each is placed by id -- which is why every one is + * checked before the table is sized from them. */ + auto read_text_to_id = [&](const char* kind) -> int { + if (!vocab->is_object()) { + RAD_ERR("%s: %s vocab is not an object of {text: id}", origin, kind); + return RAD_E_FORMAT; + } + int32_t max_id = -1; + for (auto it = vocab->begin(); it != vocab->end(); ++it) { + int32_t id = 0; + if (!read_id(it.value(), id_limit, &id)) { + RAD_ERR("%s: %s vocab entry '%s' has id %.64s, which is not a token id", + origin, kind, it.key().c_str(), it.value().dump().c_str()); + return RAD_E_FORMAT; + } + max_id = std::max(max_id, id); + } + out.tokens.assign((size_t)max_id + 1, std::string()); + for (auto it = vocab->begin(); it != vocab->end(); ++it) { + int32_t id = 0; + read_id(it.value(), id_limit, &id); + out.tokens[(size_t)id] = it.key(); + } + out.types.assign(out.tokens.size(), (uint8_t)RAD_TT_NORMAL); + return RAD_OK; + }; + + if (type == "BPE") { + out.kind = RAD_TOK_BPE; + /* `ignore_merges` SHORT-CIRCUITS THE MERGE LOOP for any word that is already a token, and + * this reader does not carry it: the vocabulary has no field for it and tokenizer.cpp + * applies the short-circuit only to added tokens. A vocabulary that sets it would tokenise + * differently here than in transformers, on rare words, with nothing in the output to say + * so -- so it is said here instead of being discovered from a quality regression. */ + if (const json* im = get(m, "ignore_merges")) + if (im->is_boolean() && im->get()) + RAD_WARN("%s: the vocabulary sets ignore_merges, which this tokeniser does not " + "implement. Words that are already tokens will be re-split through the " + "merge table and may tokenise differently than they do in transformers.", + origin); + RAD_TRY(read_text_to_id("BPE")); + } else if (type == "Unigram") { + out.kind = RAD_TOK_UNIGRAM; + if (!vocab->is_array()) { + RAD_ERR("%s: Unigram vocab is not an array", origin); + return RAD_E_FORMAT; + } + out.tokens.reserve(vocab->size()); + out.scores.reserve(vocab->size()); + for (const json& e : *vocab) { + if (!e.is_array() || e.size() != 2 || !e[0].is_string() || !e[1].is_number()) { + RAD_ERR("%s: Unigram vocab entry is not [text, score]", origin); + return RAD_E_FORMAT; + } + out.tokens.push_back(e[0].get()); + out.scores.push_back(e[1].get()); + } + out.types.assign(out.tokens.size(), (uint8_t)RAD_TT_NORMAL); + /* The encoder emits this id for text no piece covers, so one that names no token would + * put an id outside the vocabulary into the output. */ + const json* u = get(m, "unk_id"); + if (u && !read_id(*u, out.tokens.size(), &out.unk)) { + RAD_ERR("%s: Unigram unk_id %.64s is not an id in its %zu-token vocab", origin, + u->dump().c_str(), out.tokens.size()); + return RAD_E_FORMAT; + } + } else if (type == "WordPiece") { + out.kind = RAD_TOK_WORDPIECE; + RAD_TRY(read_text_to_id("WordPiece")); + } else { + RAD_ERR("%s: model type '%s' is not implemented (BPE, Unigram and WordPiece are)", + origin, type.c_str()); + return RAD_E_UNSUPPORTED; + } + + /* Byte fallback is a property of the MODEL in tokenizer.json and a step for us, because it + * changes what the encoder does on a miss and the encoder is where the miss happens. */ + if (bool_or(m, "byte_fallback", false)) { + VocabStep s; + s.kind = RAD_PRE_BYTE_FALLBACK; + out.steps.push_back(s); + } + + if (type != "BPE") return RAD_OK; + + /* Merges. Two spellings in the wild: ["a b", ...] and [["a","b"], ...]. The second exists + * because a token can contain a space. */ + const json* merges = get(m, "merges"); + if (!merges || !merges->is_array()) return RAD_OK; + + std::unordered_map id_of; + id_of.reserve(out.tokens.size() * 2); + for (size_t i = 0; i < out.tokens.size(); ++i) id_of.emplace(out.tokens[i], (uint32_t)i); + + size_t dropped = 0; + out.merges.reserve(merges->size()); + for (const json& e : *merges) { + std::string l, r; + if (e.is_array() && e.size() == 2 && e[0].is_string() && e[1].is_string()) { + l = e[0].get(); + r = e[1].get(); + } else if (e.is_string()) { + const std::string s = e.get(); + const size_t sp = s.find(' '); + if (sp == std::string::npos) { ++dropped; continue; } + l = s.substr(0, sp); + r = s.substr(sp + 1); + } else { + ++dropped; + continue; + } + auto li = id_of.find(l), ri = id_of.find(r); + if (li == id_of.end() || ri == id_of.end()) { ++dropped; continue; } + out.merges.emplace_back(li->second, ri->second); + } + if (dropped) { + /* Every dropped merge is a merge the tokeniser will not make, so the boundary moves. + * It is a warning rather than an error only because a handful of vocabs genuinely ship + * merges over strings they never added as tokens. */ + RAD_WARN("%s: %zu of %zu merges reference text that is not in the vocab and were " + "dropped; token boundaries may differ from the reference tokeniser", + origin, dropped, merges->size()); + } + return RAD_OK; +} + +/* Added tokens override the model vocab and may extend past it. `special` decides whether the + * pre-splitter treats them as control (isolated even when parse_special is off is NOT the rule -- + * see Tokenizer::encode) or as user-defined. */ +int read_added(const json& arr, VocabBuild& out, const char* origin, uint64_t id_limit) { + if (!arr.is_array()) return RAD_OK; + for (const json& e : arr) { + const json* idv = get(e, "id"); + const json* cv = get(e, "content"); + if (!idv || !cv) continue; + int32_t sid = 0; + if (!read_id(*idv, id_limit, &sid) || !cv->is_string()) { + RAD_ERR("%s: added token %.64s is not {id, content} with an id and a string", + origin, e.dump().c_str()); + return RAD_E_FORMAT; + } + const size_t id = (size_t)sid; + if (id >= out.tokens.size()) { + out.tokens.resize(id + 1); + out.types.resize(id + 1, (uint8_t)RAD_TT_NORMAL); + if (out.kind == RAD_TOK_UNIGRAM) out.scores.resize(id + 1, 0.0f); + } + out.tokens[id] = cv->get(); + out.types[id] = bool_or(e, "special", false) ? (uint8_t)RAD_TT_CONTROL + : (uint8_t)RAD_TT_USER_DEFINED; + } + return RAD_OK; +} + +/* tokenizer_config.json is where the ids live. tokenizer.json holds the vocab and the chain but + * not which token is BOS, so a convert that reads only tokenizer.json produces a vocab that + * cannot start a sequence. Reading the sibling is opportunistic: absent, the ids stay -1 and + * rad-convert can fill them from elsewhere. */ +void read_config_json(const std::string& dir, VocabBuild& out) { + const std::string path = dir + "tokenizer_config.json"; + std::ifstream f(path); + if (!f) { + RAD_INFO("tokenizer: no %s; bos/eos ids and the chat template are unset", path.c_str()); + return; + } + json c; + try { f >> c; } + catch (const std::exception& e) { + RAD_WARN("tokenizer: %s did not parse (%s); ids left unset", path.c_str(), e.what()); + return; + } + std::unordered_map id_of; + for (size_t i = 0; i < out.tokens.size(); ++i) id_of.emplace(out.tokens[i], (int32_t)i); + + auto token_id = [&](const char* key) -> int32_t { + const json* v = get(c, key); + if (!v) return -1; + std::string text; + const json* t = v->is_string() ? v : get(*v, "content"); + if (!t || !t->is_string()) return -1; + text = t->get(); + auto it = id_of.find(text); + return it == id_of.end() ? -1 : it->second; + }; + out.bos = token_id("bos_token"); + out.eos = token_id("eos_token"); + out.pad = token_id("pad_token"); + out.unk = out.unk >= 0 ? out.unk : token_id("unk_token"); + out.sep = token_id("sep_token"); + out.eot = out.eos; + out.add_bos = bool_or(c, "add_bos_token", false); + out.add_eos = bool_or(c, "add_eos_token", false); + + const json* ct = get(c, "chat_template"); + if (ct && ct->is_string()) out.chat_template = ct->get(); + else if (ct && ct->is_array() && !ct->empty()) { + /* The multi-template form: a list of {name, template}. The one named "default" wins, + * else the first, which is what every renderer does. */ + for (const json& e : *ct) { + if (str_or(e, "name", "") == "default") { out.chat_template = str_or(e, "template", ""); break; } + } + if (out.chat_template.empty()) out.chat_template = str_or((*ct)[0], "template", ""); + } +} + + +/* THE TEMPLATE MAY NOT BE IN tokenizer_config.json AT ALL. Recent transformers versions write it + * to a standalone chat_template.jinja and omit the key, so a checkpoint saved by one of those + * converts with NO template at all unless this sibling is read -- and the only symptom is the + * server answering /v1/chat/completions with 501, a long way from the cause. + * + * The file wins where it exists, which is what transformers itself does; in a checkpoint that + * carries both, the config key is the superseded copy. */ +void read_chat_template_file(const std::string& dir, VocabBuild& out) { + const std::string path = dir + "chat_template.jinja"; + std::ifstream f(path); + if (!f) return; + std::ostringstream ss; + ss << f.rdbuf(); + std::string t = ss.str(); + while (!t.empty() && (t.back() == '\n' || t.back() == '\r')) t.pop_back(); + if (t.empty()) return; + RAD_INFO("tokenizer: chat template from %s (%zu bytes)%s", path.c_str(), t.size(), + out.chat_template.empty() ? "" : ", overriding the tokenizer_config.json key"); + out.chat_template = std::move(t); +} + +void read_config(const std::string& dir, VocabBuild& out) { + read_config_json(dir, out); + read_chat_template_file(dir, out); +} + +} /* namespace */ + +/* ================================================================== parse_tokenizer_json */ + +namespace { + +int interpret_tokenizer_json(const json& j, uint64_t id_limit, const char* origin, + VocabBuild& out) { + const json* model = get(j, "model"); + if (!model) { + RAD_ERR("%s: no \"model\" section", origin); + return RAD_E_FORMAT; + } + RAD_TRY(read_model(*model, out, origin, id_limit)); + + /* Order matters and it is the file's order: normaliser, then pre-tokeniser, then decoder. + * They land in one list because that is what RadVocabHeader holds, and the kind ranges keep + * them separable. read_model may already have pushed a ByteFallback step, which belongs + * with the pre-tokenisers; it is re-sorted below. */ + std::vector pre_from_model; + pre_from_model.swap(out.steps); + + std::vector norm, pre, dec; + if (const json* n = get(j, "normalizer")) RAD_TRY(read_normalizer(*n, norm, origin)); + if (const json* p = get(j, "pre_tokenizer")) RAD_TRY(read_pretok(*p, pre, origin)); + if (const json* d = get(j, "decoder")) RAD_TRY(read_decoder(*d, dec, origin)); + for (VocabStep& s : pre_from_model) pre.push_back(std::move(s)); + + out.steps.clear(); + out.steps.insert(out.steps.end(), norm.begin(), norm.end()); + out.steps.insert(out.steps.end(), pre.begin(), pre.end()); + out.steps.insert(out.steps.end(), dec.begin(), dec.end()); + + if (const json* a = get(j, "added_tokens")) RAD_TRY(read_added(*a, out, origin, id_limit)); + + if (pre.empty() && out.kind == RAD_TOK_BPE) { + RAD_ERR("%s: a BPE model with no pre_tokenizer would tokenise the whole prompt as one " + "word. Refusing.", origin); + return RAD_E_FORMAT; + } + return RAD_OK; +} + +} /* namespace */ + +int parse_tokenizer_json_buf(std::string_view text, const char* origin, VocabBuild& out) { + json j; + try { + j = json::parse(text.begin(), text.end()); + } catch (const std::exception& e) { + RAD_ERR("%s: not valid JSON: %s", origin, e.what()); + return RAD_E_FORMAT; + } + out = VocabBuild{}; + out.source = origin; + + /* NO ID PAST THE SIZE OF THE FILE. Ids are dense, so a vocabulary that names one beyond the + * number of bytes listing it would leave more ids unused than the file has bytes; bounding + * them by it is what bounds the token table they size to a multiple of the input, whatever + * the ids claim. */ + const uint64_t id_limit = text.size(); + + /* A value of the wrong JSON type throws out of nlohmann on the first get<>() that meets it. + * The reader checks the shapes that decide what is written where; this turns any other one + * into the refusal it is rather than into std::terminate in the converter. */ + try { + return interpret_tokenizer_json(j, id_limit, origin, out); + } catch (const json::exception& e) { + RAD_ERR("%s: a value has the wrong type: %s", origin, e.what()); + return RAD_E_FORMAT; + } catch (const std::bad_alloc&) { + RAD_ERR("%s: out of memory reading the vocabulary", origin); + return RAD_E_NOMEM; + } +} + +int parse_tokenizer_json(const char* path, VocabBuild& out) { + if (!path) return RAD_E_INVAL; + std::ifstream f(path, std::ios::binary); + if (!f) { + RAD_ERR("tokenizer: cannot open %s", path); + return RAD_E_IO; + } + std::ostringstream ss; + ss << f.rdbuf(); + const std::string text = ss.str(); + + RAD_TRY(parse_tokenizer_json_buf(text, path, out)); + + /* The sibling config carries the ids and the chat template. */ + const std::string p(path); + const size_t slash = p.find_last_of('/'); + read_config(slash == std::string::npos ? std::string() : p.substr(0, slash + 1), out); + + RAD_INFO("tokenizer: %s -> %zu tokens, %zu merges, %zu chain steps", + path, out.tokens.size(), out.merges.size(), out.steps.size()); + for (const VocabStep& s : out.steps) RAD_INFO("tokenizer: %s", step_describe(s).c_str()); + return RAD_OK; +} + +/* ================================================================== vocab_from_gguf */ + +namespace { + +/* `tokenizer.ggml.pre` -> the pre-tokeniser regex list. + * + * These are llama.cpp's ADAPTED patterns, copied verbatim from llm_tokenizer_bpe's constructor + * (06938ac12). Copying rather than deriving is deliberate: the adaptation llama.cpp applied is + * part of the pattern's identity for a GGUF -- gpt-4o's `((?=[\p{L}])([^a-z]))*` is not o200k's + * `[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*`, and a GGUF tokenises the way llama.cpp runs it. They + * go through the same compiler as a tokenizer.json pattern. + * + * The one exception is kimi-k2. llama.cpp spells it `\p{Han}+` and uses that string only as the + * key of a hand-written splitter approximating Kimi-K2's real pattern; as a regex it would split + * Han runs and nothing else. The entry is the real pattern, from the model's tokenization_kimi.py, + * which is what that splitter was written to stand in for. + * + * The list is not exhaustive and does not try to be. A GGUF whose `pre` is not here is REFUSED, + * with the instruction to convert from tokenizer.json instead -- which is the path that does not + * depend on this table at all. */ +struct PreEntry { const char* name; const char* regex[4]; bool byte_encode; }; + +const PreEntry k_pre[] = { + { "default", { + "[\\p{P}\\$\\+<=>\\^~\\|]+", + "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)", + "\\p{N}+", + "[0-9][0-9][0-9]" }, true }, + { "llama3", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true }, + { "llama-bpe", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true }, + { "llama-v3", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true }, + { "falcon3", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true }, + { "pixtral", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true }, + { "lfm2", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true }, + { "dbrx", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true }, + { "smaug-bpe", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true }, + { "glm4", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true }, + { "chatglm-bpe", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true }, + + { "gpt-2", { "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true }, + { "phi-2", { "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true }, + { "mpt", { "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true }, + { "olmo", { "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true }, + { "jais", { "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true }, + { "trillion", { "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true }, + { "granite-docling", { "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true }, + + { "starcoder", { "\\p{N}", "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true }, + { "refact", { "\\p{N}", "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true }, + { "command-r", { "\\p{N}", "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true }, + { "smollm", { "\\p{N}", "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true }, + { "codeshell", { "\\p{N}", "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true }, + { "exaone", { "\\p{N}", "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true }, + { "minerva-7b",{ "\\p{N}", "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true }, + + { "qwen2", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true }, + { "stablelm2", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true }, + { "deepseek-r1-qwen", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true }, + { "hunyuan", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true }, + { "solar-open", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true }, + { "grok-2", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true }, + + { "qwen35", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?[\\p{L}\\p{M}]+|\\p{N}| ?[^\\s\\p{L}\\p{M}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true }, + + { "gpt-4o", { "[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))*((?=[\\p{L}])([^A-Z]))+(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))+((?=[\\p{L}])([^A-Z]))*(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true }, + { "llama4", { "[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))*((?=[\\p{L}])([^A-Z]))+(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))+((?=[\\p{L}])([^A-Z]))*(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true }, + { "tekken", { "[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))*((?=[\\p{L}])([^A-Z]))+|[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))+((?=[\\p{L}])([^A-Z]))*|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true }, + + { "seed-coder", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1}| ?[^\\s\\p{L}\\p{N}\\r\\n]+|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true }, + { "kimi-k2", { "[\\p{Han}]+|[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}&&[^\\p{Han}]]*[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}&&[^\\p{Han}]]+(?i:'s|'t|'re|'ve|'m|'ll|'d)?|[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}&&[^\\p{Han}]]+[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}&&[^\\p{Han}]]*(?i:'s|'t|'re|'ve|'m|'ll|'d)?|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true }, + { "whitespace", { "\\S+" }, false }, + { "gemma4", { "[^\\n]+|[\\n]+" }, false }, + { "sarvam-moe", { "[^\\n]+|[\\n]+" }, false }, +}; + +} /* namespace */ + +int vocab_from_gguf(const GgufFile& g, VocabBuild& out) { + out = VocabBuild{}; + out.source = g.path(); + + std::string model; + if (!g.get_str("tokenizer.ggml.model", &model)) { + RAD_ERR("gguf: %s has no tokenizer.ggml.model", g.path().c_str()); + return RAD_E_FORMAT; + } + if (!g.get_strs("tokenizer.ggml.tokens", &out.tokens) || out.tokens.empty()) { + RAD_ERR("gguf: %s has no tokenizer.ggml.tokens", g.path().c_str()); + return RAD_E_FORMAT; + } + + std::vector types; + if (g.get_i64s("tokenizer.ggml.token_type", &types) && types.size() == out.tokens.size()) { + out.types.resize(types.size()); + for (size_t i = 0; i < types.size(); ++i) out.types[i] = (uint8_t)types[i]; + } else { + out.types.assign(out.tokens.size(), (uint8_t)RAD_TT_NORMAL); + } + g.get_f32s("tokenizer.ggml.scores", &out.scores); + + auto id = [&](const char* k, int32_t* dst) { + int64_t v = 0; + if (g.get_i64(k, &v)) *dst = (int32_t)v; + }; + id("tokenizer.ggml.bos_token_id", &out.bos); + id("tokenizer.ggml.eos_token_id", &out.eos); + id("tokenizer.ggml.eot_token_id", &out.eot); + id("tokenizer.ggml.padding_token_id", &out.pad); + id("tokenizer.ggml.unknown_token_id", &out.unk); + id("tokenizer.ggml.seperator_token_id", &out.sep); + if (out.eot < 0) out.eot = out.eos; + int64_t b = 0; + if (g.get_i64("tokenizer.ggml.add_bos_token", &b)) out.add_bos = b != 0; + if (g.get_i64("tokenizer.ggml.add_eos_token", &b)) out.add_eos = b != 0; + g.get_str("tokenizer.chat_template", &out.chat_template); + + if (model == "gpt2") { + out.kind = RAD_TOK_BPE; + std::string pre; + if (!g.get_str("tokenizer.ggml.pre", &pre)) pre = "default"; + + const PreEntry* e = nullptr; + for (const PreEntry& p : k_pre) if (pre == p.name) { e = &p; break; } + if (!e) { + /* This is the refusal spec §12 asks for. llama.cpp would fall back to `default` here + * and produce plausible text with wrong boundaries; we would rather not run. */ + RAD_ERR("gguf: tokenizer.ggml.pre = '%s' is not in this build's table, and guessing " + "would give a silently different split. Convert from the model's " + "tokenizer.json instead, which needs no table.", pre.c_str()); + return RAD_E_UNSUPPORTED; + } + for (const char* r : e->regex) { + if (!r) break; + VocabStep s; + s.kind = RAD_PRE_SPLIT; + s.arg0 = r; + s.iarg = 1; /* Isolated */ + out.steps.push_back(s); + } + if (e->byte_encode) { + VocabStep s; + s.kind = RAD_PRE_BYTELEVEL; + s.flags = 0; /* the split above already carries the regex */ + out.steps.push_back(s); + VocabStep d; + d.kind = RAD_DEC_BYTELEVEL; + out.steps.push_back(d); + } else { + /* SPM-shaped BPE: the vocab is raw UTF-8 with U+2581 for space. */ + VocabStep s; + s.kind = RAD_PRE_METASPACE; + s.arg0 = "\xe2\x96\x81"; + s.iarg = 2; + out.steps.push_back(s); + VocabStep d; + d.kind = RAD_DEC_METASPACE; + d.arg0 = "\xe2\x96\x81"; + d.iarg = 2; + out.steps.push_back(d); + } + + std::vector merges; + g.get_strs("tokenizer.ggml.merges", &merges); + std::unordered_map id_of; + id_of.reserve(out.tokens.size() * 2); + for (size_t i = 0; i < out.tokens.size(); ++i) id_of.emplace(out.tokens[i], (uint32_t)i); + + size_t dropped = 0; + out.merges.reserve(merges.size()); + for (const std::string& m : merges) { + const size_t sp = m.find(' '); + if (sp == std::string::npos) { ++dropped; continue; } + auto l = id_of.find(m.substr(0, sp)); + auto r = id_of.find(m.substr(sp + 1)); + if (l == id_of.end() || r == id_of.end()) { ++dropped; continue; } + out.merges.emplace_back(l->second, r->second); + } + if (dropped) + RAD_WARN("gguf: %zu of %zu merges dropped (a half is not a token); token boundaries " + "may differ from the reference tokeniser", dropped, merges.size()); + } else if (model == "llama") { + out.kind = RAD_TOK_BPE; + /* SPM proper: whitespace escaped to U+2581, byte fallback for the rest. Expressed as + * steps so the runtime has no per-model branch. */ + VocabStep m; + m.kind = RAD_PRE_METASPACE; + m.arg0 = "\xe2\x96\x81"; + m.iarg = 2; + out.steps.push_back(m); + VocabStep bf; + bf.kind = RAD_PRE_BYTE_FALLBACK; + out.steps.push_back(bf); + VocabStep d; + d.kind = RAD_DEC_METASPACE; + d.arg0 = "\xe2\x96\x81"; + d.iarg = 2; + out.steps.push_back(d); + RAD_WARN("gguf: '%s' is a SentencePiece vocab and this build tokenises it as BPE over the " + "same pieces. That is right for the vocabs that ship as GGUF today and it is " + "not the SPM bigram algorithm; convert from tokenizer.json to be sure.", + model.c_str()); + } else if (model == "t5") { + out.kind = RAD_TOK_UNIGRAM; + VocabStep m; + m.kind = RAD_PRE_METASPACE; + m.arg0 = "\xe2\x96\x81"; + m.iarg = 2; + out.steps.push_back(m); + VocabStep d; + d.kind = RAD_DEC_METASPACE; + d.arg0 = "\xe2\x96\x81"; + d.iarg = 2; + out.steps.push_back(d); + } else if (model == "bert") { + out.kind = RAD_TOK_WORDPIECE; + VocabStep n; + n.kind = RAD_NORM_LOWERCASE; + out.steps.push_back(n); + VocabStep w; + w.kind = RAD_PRE_WHITESPACE; + out.steps.push_back(w); + VocabStep p; + p.kind = RAD_PRE_PUNCTUATION; + p.iarg = 1; + out.steps.push_back(p); + VocabStep d; + d.kind = RAD_DEC_REPLACE; + d.arg0 = "##"; + out.steps.push_back(d); + } else { + RAD_ERR("gguf: tokenizer.ggml.model = '%s' is not implemented", model.c_str()); + return RAD_E_UNSUPPORTED; + } + + RAD_INFO("gguf: vocab %zu tokens, %zu merges, %zu chain steps", + out.tokens.size(), out.merges.size(), out.steps.size()); + for (const VocabStep& s : out.steps) RAD_INFO("gguf: %s", step_describe(s).c_str()); + return RAD_OK; +} + +/* ================================================================== serialise */ + +namespace { +template void put(std::vector& b, const T& v) { + const uint8_t* p = reinterpret_cast(&v); + b.insert(b.end(), p, p + sizeof(T)); +} +void pad_to(std::vector& b, size_t base, size_t align) { + while ((base + b.size()) % align) b.push_back(0); +} +} /* namespace */ + +int vocab_serialize(const VocabBuild& in, StringSink& strings, uint64_t off, + std::vector& out) { + if (in.tokens.empty()) return RAD_E_INVAL; + if (in.tokens.size() > UINT32_MAX || in.merges.size() > UINT32_MAX || + in.steps.size() > UINT32_MAX) return RAD_E_INVAL; + + /* Every string goes into the file's one blob and only its offset is stored here, per + * rad_format.h. That is what makes the section fixed-stride and mmap-walkable. */ + std::vector tok_off(in.tokens.size()); + for (size_t i = 0; i < in.tokens.size(); ++i) tok_off[i] = strings.intern(in.tokens[i]); + + std::vector steps(in.steps.size()); + for (size_t i = 0; i < in.steps.size(); ++i) { + steps[i].kind = in.steps[i].kind; + steps[i].flags = in.steps[i].flags; + steps[i].arg0 = strings.intern(in.steps[i].arg0); + steps[i].arg1 = strings.intern(in.steps[i].arg1); + steps[i].iarg = in.steps[i].iarg; + } + const rad_stroff tmpl = strings.intern(in.chat_template); + + out.clear(); + RadVocabHeader h{}; + h.kind = in.kind; + h.n_tokens = (uint32_t)in.tokens.size(); + h.n_merges = (uint32_t)in.merges.size(); + h.n_steps = (uint32_t)in.steps.size(); + h.bos = in.bos; h.eos = in.eos; h.eot = in.eot; + h.pad_id = in.pad; h.unk = in.unk; h.sep = in.sep; + h.add_bos = in.add_bos ? 1u : 0u; + h.add_eos = in.add_eos ? 1u : 0u; + h.chat_template = tmpl; + out.resize(sizeof(RadVocabHeader), 0); + + /* Each array is aligned to its own element so a mapped reader can point a typed pointer at + * it. RAD_ALIGN_SUB would be enough for the container's rules; 8 is what the types need. */ + auto place = [&](size_t align, const void* p, size_t bytes) -> uint64_t { + pad_to(out, (size_t)off, align); + const uint64_t at = off + out.size(); + const uint8_t* s = static_cast(p); + out.insert(out.end(), s, s + bytes); + return at; + }; + + h.tok_text_off = place(8, tok_off.data(), tok_off.size() * sizeof(rad_stroff)); + if (!in.scores.empty()) + h.tok_score_off = place(4, in.scores.data(), in.scores.size() * sizeof(float)); + if (!in.types.empty()) + h.tok_type_off = place(1, in.types.data(), in.types.size()); + if (!in.merges.empty()) { + std::vector flat(in.merges.size() * 2); + for (size_t i = 0; i < in.merges.size(); ++i) { + flat[i * 2 + 0] = in.merges[i].first; + flat[i * 2 + 1] = in.merges[i].second; + } + h.merge_off = place(4, flat.data(), flat.size() * sizeof(uint32_t)); + } + if (!steps.empty()) + h.step_off = place(8, steps.data(), steps.size() * sizeof(RadVocabStep)); + + std::memcpy(out.data(), &h, sizeof h); + return RAD_OK; +} + +int vocab_deserialize(const void* file_base, uint64_t file_bytes, const RadVocabHeader* h, + VocabBuild& out) { + if (!file_base || !h) return RAD_E_INVAL; + const uint8_t* base = static_cast(file_base); + const char* strs = nullptr; + uint64_t str_bytes = 0; + { + /* The string blob's extent comes from the file header, which sits at offset 0. Reading + * it here rather than taking it as an argument keeps the caller from having to keep the + * two in sync. */ + if (file_bytes < sizeof(RadFileHeader)) return RAD_E_FORMAT; + const RadFileHeader* fh = reinterpret_cast(base); + if (fh->str_off + fh->str_bytes > file_bytes) return RAD_E_FORMAT; + strs = reinterpret_cast(base + fh->str_off); + str_bytes = fh->str_bytes; + } + auto S = [&](rad_stroff o) -> std::string { + if (o >= str_bytes) return {}; + const char* p = strs + o; + const size_t max = (size_t)(str_bytes - o); + return std::string(p, strnlen(p, max)); + }; + auto in_file = [&](uint64_t o, uint64_t n) { return o <= file_bytes && n <= file_bytes - o; }; + + out = VocabBuild{}; + out.kind = h->kind; + out.bos = h->bos; out.eos = h->eos; out.eot = h->eot; + out.pad = h->pad_id; out.unk = h->unk; out.sep = h->sep; + out.add_bos = h->add_bos != 0; + out.add_eos = h->add_eos != 0; + out.chat_template = S(h->chat_template); + + if (!in_file(h->tok_text_off, (uint64_t)h->n_tokens * sizeof(rad_stroff))) + return RAD_E_FORMAT; + const rad_stroff* toff = reinterpret_cast(base + h->tok_text_off); + out.tokens.resize(h->n_tokens); + for (uint32_t i = 0; i < h->n_tokens; ++i) out.tokens[i] = S(toff[i]); + + if (h->tok_score_off) { + if (!in_file(h->tok_score_off, (uint64_t)h->n_tokens * sizeof(float))) return RAD_E_FORMAT; + const float* p = reinterpret_cast(base + h->tok_score_off); + out.scores.assign(p, p + h->n_tokens); + } + if (h->tok_type_off) { + if (!in_file(h->tok_type_off, h->n_tokens)) return RAD_E_FORMAT; + const uint8_t* p = base + h->tok_type_off; + out.types.assign(p, p + h->n_tokens); + } + if (h->merge_off) { + if (!in_file(h->merge_off, (uint64_t)h->n_merges * 2 * sizeof(uint32_t))) + return RAD_E_FORMAT; + const uint32_t* p = reinterpret_cast(base + h->merge_off); + out.merges.resize(h->n_merges); + for (uint32_t i = 0; i < h->n_merges; ++i) out.merges[i] = { p[i * 2], p[i * 2 + 1] }; + } + if (h->step_off) { + if (!in_file(h->step_off, (uint64_t)h->n_steps * sizeof(RadVocabStep))) + return RAD_E_FORMAT; + const RadVocabStep* p = reinterpret_cast(base + h->step_off); + out.steps.resize(h->n_steps); + for (uint32_t i = 0; i < h->n_steps; ++i) { + out.steps[i].kind = p[i].kind; + out.steps[i].flags = p[i].flags; + out.steps[i].arg0 = S(p[i].arg0); + out.steps[i].arg1 = S(p[i].arg1); + out.steps[i].iarg = p[i].iarg; + } + } + return RAD_OK; +} + +} /* namespace rad */ diff --git a/core/text/tokenizer_nfc.cpp b/core/text/tokenizer_nfc.cpp new file mode 100644 index 00000000..8572e925 --- /dev/null +++ b/core/text/tokenizer_nfc.cpp @@ -0,0 +1,129 @@ +#include "text/tokenizer_nfc.h" +#include "text/unicode_norm.h" + +#include +#include +#include + +namespace rad { + +namespace { + +/* NFC, applied only where it can change something. + * + * UAX #15's quick check: a codepoint whose NFC_QC is Yes and whose combining class is 0 is a + * BOUNDARY -- nothing before it can compose with it or reorder across it, and nothing it becomes + * can reach back past it -- so normalising the text between two boundaries on its own gives exactly + * the bytes normalising the whole text gives there. The text is scanned for the codepoints that + * are not boundaries (NFC_QC No or Maybe, a mark out of canonical order, anything not strictly + * well-formed), and only the stretch from the boundary before each one to the boundary after it + * goes through unorm_utf8; everything else is already NFC and is copied. The properties are + * derived from the same tables unorm_utf8 runs on -- "No" is a codepoint NFC does not leave alone + * by itself, "Maybe" is one that can compose with what precedes it -- so the scan agrees with that + * implementation rather than with some other one. Invalid bytes are never at a boundary, so the + * decoder's replacement of them happens inside a normalised stretch, byte for byte as it does when + * the whole text is normalised. */ +class NfcQuick { +public: + NfcQuick() : not_yes_(kWords, 0), marked_(kWords, 0) { + for (size_t i = 0; i < k_decomp_rows_n; ++i) { + const DecompRow& r = k_decomp_rows[i]; + if (r.len_c == 0) continue; + if (unorm_nfc({ r.cpt }) != std::vector{ r.cpt }) set(not_yes_, r.cpt); + } + for (size_t i = 0; i < k_compose_n; ++i) set(not_yes_, k_compose[i].b); + for (uint32_t c = 0x1161; c <= 0x1175; ++c) set(not_yes_, c); /* Hangul V, composes after L */ + for (uint32_t c = 0x11A8; c <= 0x11C2; ++c) set(not_yes_, c); /* Hangul T, composes after LV */ + for (size_t i = 0; i < k_ccc_n; ++i) + for (uint32_t c = k_ccc[i].first; c <= k_ccc[i].last; ++c) set(marked_, c); + } + + /* Normalise `text` in place; false when it was already NFC and is untouched. */ + bool apply(std::string& text) const { + const uint8_t* p = (const uint8_t*)text.data(); + const size_t n = text.size(); + std::string out; + size_t copied = 0; /* text[0, copied) is in `out` */ + size_t boundary = 0; /* start of the last boundary codepoint seen */ + uint32_t last = 0; /* combining class of the previous codepoint */ + for (size_t i = 0; i < n; ) { + if (i + 8 <= n) { + uint64_t w; + std::memcpy(&w, p + i, 8); + if (!(w & 0x8080808080808080ull)) { last = 0; boundary = i + 7; i += 8; continue; } + } + uint32_t len, ccc; + const int k = classify(p + i, n - i, &len, &ccc); + if (k == kBoundary) { last = 0; boundary = i; i += len; continue; } + if (k == kKeep && !(ccc != 0 && last > ccc)) { last = ccc; i += len; continue; } + /* Something NFC may change: normalise from the boundary before it to the next one. */ + size_t end = i + len; + while (end < n) { + uint32_t l2, c2; + if (classify(p + end, n - end, &l2, &c2) == kBoundary) break; + end += l2; + } + const size_t start = std::max(boundary, copied); + out.append(text, copied, start - copied); + out += unorm_utf8(text.substr(start, end - start), false, true); + copied = end; + boundary = end; + last = 0; + i = end; + } + if (copied == 0) return false; + out.append(text, copied, std::string::npos); + text.swap(out); + return true; + } + +private: + enum { kBoundary, kKeep, kChange }; + static constexpr uint32_t kInvalidLen = UINT32_MAX; + static constexpr size_t kWords = (0x110000 + 63) / 64; + static void set(std::vector& b, uint32_t c) { b[c >> 6] |= 1ull << (c & 63); } + static bool get(const std::vector& b, uint32_t c) { return (b[c >> 6] >> (c & 63)) & 1; } + + /* kBoundary: a well-formed codepoint with class 0 and NFC_QC Yes. kKeep: well-formed, NFC_QC + * Yes, a nonzero class (in `ccc`) the caller checks for order. kChange: anything else; an + * invalid byte reports a length of 1 and kInvalidLen in `ccc`. */ + int classify(const uint8_t* p, size_t n, uint32_t* len, uint32_t* ccc) const { + const uint32_t b = p[0]; + *ccc = 0; + if (b < 0x80) { *len = 1; return kBoundary; } + uint32_t c; + auto cont = [&](size_t k) { return k < n && (p[k] & 0xC0) == 0x80; }; + if (b >= 0xC2 && b < 0xE0 && cont(1)) { + c = ((b & 0x1F) << 6) | (p[1] & 0x3F); + *len = 2; + } else if (b >= 0xE0 && b < 0xF0 && cont(1) && cont(2)) { + c = ((b & 0x0F) << 12) | ((p[1] & 0x3F) << 6) | (p[2] & 0x3F); + *len = 3; + if (c < 0x800 || (c >= 0xD800 && c <= 0xDFFF)) { *len = 1; *ccc = kInvalidLen; return kChange; } + } else if (b >= 0xF0 && b < 0xF5 && cont(1) && cont(2) && cont(3)) { + c = ((b & 0x07) << 18) | ((p[1] & 0x3F) << 12) | ((p[2] & 0x3F) << 6) | (p[3] & 0x3F); + *len = 4; + if (c < 0x10000 || c > 0x10FFFF) { *len = 1; *ccc = kInvalidLen; return kChange; } + } else { + *len = 1; + *ccc = kInvalidLen; + return kChange; + } + if (get(not_yes_, c)) { *ccc = get(marked_, c) ? unorm_ccc(c) : 0; return kChange; } + if (!get(marked_, c)) return kBoundary; + *ccc = unorm_ccc(c); + return *ccc ? kKeep : kBoundary; + } + + std::vector not_yes_; /* NFC_QC is No or Maybe */ + std::vector marked_; /* canonical combining class is not 0 */ +}; + +} /* namespace */ + +bool tok_nfc(std::string& text) { + static const NfcQuick q; + return q.apply(text); +} + +} /* namespace rad */ diff --git a/core/text/tokenizer_nfc.h b/core/text/tokenizer_nfc.h new file mode 100644 index 00000000..7d18e571 --- /dev/null +++ b/core/text/tokenizer_nfc.h @@ -0,0 +1,13 @@ +/* tokenizer_nfc.h -- NFC for the tokeniser's normaliser chain, applied only where it can change + * something. Byte for byte what unorm_utf8(text, false, true) returns; see tokenizer_nfc.cpp for + * why normalising the stretches around the codepoints that are not NFC boundaries is the same as + * normalising the whole text. */ +#pragma once +#include + +namespace rad { + +/* Normalise `text` in place. False when it was already NFC and has not been touched. */ +bool tok_nfc(std::string& text); + +} /* namespace rad */ diff --git a/core/text/tokenizer_regex.cpp b/core/text/tokenizer_regex.cpp new file mode 100644 index 00000000..fef43a8f --- /dev/null +++ b/core/text/tokenizer_regex.cpp @@ -0,0 +1,1436 @@ +#include "text/tokenizer_regex.h" +#include "text/tokenizer_ucd.h" +#include "rad_internal.h" + +#include +#include +#include + +namespace rad { + +namespace { + +constexpr uint32_t kMaxCp = 0x10FFFF; + +/* ================================================================== codepoint sets + * + * Sorted, disjoint, merged [first, last] ranges. Every set a pattern names is one of these until + * the alphabet is partitioned, after which the DFA only ever sees class numbers. */ +using CpSet = std::vector>; + +void set_normalize(CpSet& s) { + std::sort(s.begin(), s.end()); + CpSet out; + for (const auto& r : s) { + if (!out.empty() && r.first <= out.back().second + 1) { + out.back().second = std::max(out.back().second, r.second); + } else { + out.push_back(r); + } + } + s.swap(out); +} + +CpSet set_union(const CpSet& a, const CpSet& b) { + CpSet r = a; + r.insert(r.end(), b.begin(), b.end()); + set_normalize(r); + return r; +} + +CpSet set_complement(const CpSet& a) { + CpSet r; + uint32_t next = 0; + for (const auto& x : a) { + if (x.first > next) r.push_back({ next, x.first - 1 }); + next = x.second + 1; + } + if (next <= kMaxCp) r.push_back({ next, kMaxCp }); + return r; +} + +CpSet set_intersect(const CpSet& a, const CpSet& b) { + CpSet r; + size_t i = 0, j = 0; + while (i < a.size() && j < b.size()) { + const uint32_t lo = std::max(a[i].first, b[j].first); + const uint32_t hi = std::min(a[i].second, b[j].second); + if (lo <= hi) r.push_back({ lo, hi }); + if (a[i].second < b[j].second) ++i; else ++j; + } + return r; +} + +bool set_has(const CpSet& s, uint32_t c) { + auto it = std::upper_bound(s.begin(), s.end(), c, + [](uint32_t v, const std::pair& r) { + return v < r.first; + }); + return it != s.begin() && c <= (it - 1)->second; +} + +CpSet set_from(const ucd::CpRange* r, size_t n) { + CpSet s; + s.reserve(n); + for (size_t i = 0; i < n; ++i) s.push_back({ r[i].first, r[i].last }); + set_normalize(s); + return s; +} + +/* One set per general category, built once from the run table. */ +const std::vector& gc_sets() { + static const std::vector sets = [] { + std::vector v(ucd::kGcCount); + for (size_t i = 0; i < ucd::k_gc_runs_n; ++i) { + const uint32_t first = ucd::k_gc_runs[i].first; + const uint32_t last = i + 1 < ucd::k_gc_runs_n ? ucd::k_gc_runs[i + 1].first - 1 : kMaxCp; + v[ucd::k_gc_runs[i].gc].push_back({ first, last }); + } + for (CpSet& s : v) set_normalize(s); + return v; + }(); + return sets; +} + +CpSet gc_mask_set(uint32_t mask) { + CpSet s; + for (uint32_t g = 0; g < ucd::kGcCount; ++g) + if (mask & (1u << g)) s.insert(s.end(), gc_sets()[g].begin(), gc_sets()[g].end()); + set_normalize(s); + return s; +} + +const CpSet& white_space_set() { static const CpSet s = set_from(ucd::k_white_space, ucd::k_white_space_n); return s; } +const CpSet& digit_set() { static const CpSet s = set_from(ucd::k_digit, ucd::k_digit_n); return s; } +const CpSet& word_set() { static const CpSet s = set_from(ucd::k_word, ucd::k_word_n); return s; } +const CpSet& word_class_set() { static const CpSet s = set_from(ucd::k_word_class, ucd::k_word_class_n); return s; } +const CpSet& hex_set() { + static const CpSet s = { { '0', '9' }, { 'A', 'F' }, { 'a', 'f' } }; + return s; +} + +/* Case-folding orbits. `(?i)` makes a character match its whole orbit. */ +struct CaseData { + std::vector> orbits; + std::unordered_map orbit_of; + CpSet multi; +}; + +const CaseData& case_data() { + static const CaseData d = [] { + CaseData c; + for (size_t i = 0; i < ucd::k_case_orbits_n; ) { + const uint32_t n = ucd::k_case_orbits[i++]; + std::vector o(ucd::k_case_orbits + i, ucd::k_case_orbits + i + n); + for (uint32_t m : o) c.orbit_of[m] = (uint32_t)c.orbits.size(); + c.orbits.push_back(std::move(o)); + i += n; + } + for (size_t i = 0; i < ucd::k_case_multi_n; ++i) + c.multi.push_back({ ucd::k_case_multi[i], ucd::k_case_multi[i] }); + set_normalize(c.multi); + return c; + }(); + return d; +} + +CpSet case_close(const CpSet& s) { + CpSet add; + for (const auto& o : case_data().orbits) { + bool any = false; + for (uint32_t m : o) if (set_has(s, m)) { any = true; break; } + if (any) for (uint32_t m : o) add.push_back({ m, m }); + } + return add.empty() ? s : set_union(s, add); +} + +/* The general-category names Oniguruma accepts, short and long, after the same normalisation + * it applies (case, spaces, underscores and hyphens ignored). */ +struct GcName { const char* name; uint32_t mask; }; + +constexpr uint32_t bit(ucd::Gc g) { return 1u << g; } +constexpr uint32_t kL = bit(ucd::Lu) | bit(ucd::Ll) | bit(ucd::Lt) | bit(ucd::Lm) | bit(ucd::Lo); +constexpr uint32_t kM = bit(ucd::Mn) | bit(ucd::Mc) | bit(ucd::Me); +constexpr uint32_t kN = bit(ucd::Nd) | bit(ucd::Nl) | bit(ucd::No); +constexpr uint32_t kP = bit(ucd::Pc) | bit(ucd::Pd) | bit(ucd::Ps) | bit(ucd::Pe) | + bit(ucd::Pi) | bit(ucd::Pf) | bit(ucd::Po); +constexpr uint32_t kS = bit(ucd::Sm) | bit(ucd::Sc) | bit(ucd::Sk) | bit(ucd::So); +constexpr uint32_t kZ = bit(ucd::Zs) | bit(ucd::Zl) | bit(ucd::Zp); +constexpr uint32_t kC = bit(ucd::Cc) | bit(ucd::Cf) | bit(ucd::Cs) | bit(ucd::Co) | bit(ucd::Cn); + +const GcName k_gc_names[] = { + { "l", kL }, { "letter", kL }, + { "lu", bit(ucd::Lu) }, { "uppercaseletter", bit(ucd::Lu) }, + { "ll", bit(ucd::Ll) }, { "lowercaseletter", bit(ucd::Ll) }, + { "lt", bit(ucd::Lt) }, { "titlecaseletter", bit(ucd::Lt) }, + { "lm", bit(ucd::Lm) }, { "modifierletter", bit(ucd::Lm) }, + { "lo", bit(ucd::Lo) }, { "otherletter", bit(ucd::Lo) }, + { "m", kM }, { "mark", kM }, { "combiningmark", kM }, + { "mn", bit(ucd::Mn) }, { "nonspacingmark", bit(ucd::Mn) }, + { "mc", bit(ucd::Mc) }, { "spacingmark", bit(ucd::Mc) }, + { "me", bit(ucd::Me) }, { "enclosingmark", bit(ucd::Me) }, + { "n", kN }, { "number", kN }, + { "nd", bit(ucd::Nd) }, { "decimalnumber", bit(ucd::Nd) }, { "digit", bit(ucd::Nd) }, + { "nl", bit(ucd::Nl) }, { "letternumber", bit(ucd::Nl) }, + { "no", bit(ucd::No) }, { "othernumber", bit(ucd::No) }, + { "p", kP }, { "punctuation", kP }, { "punct", kP }, + { "pc", bit(ucd::Pc) }, { "connectorpunctuation", bit(ucd::Pc) }, + { "pd", bit(ucd::Pd) }, { "dashpunctuation", bit(ucd::Pd) }, + { "ps", bit(ucd::Ps) }, { "openpunctuation", bit(ucd::Ps) }, + { "pe", bit(ucd::Pe) }, { "closepunctuation", bit(ucd::Pe) }, + { "pi", bit(ucd::Pi) }, { "initialpunctuation", bit(ucd::Pi) }, + { "pf", bit(ucd::Pf) }, { "finalpunctuation", bit(ucd::Pf) }, + { "po", bit(ucd::Po) }, { "otherpunctuation", bit(ucd::Po) }, + { "s", kS }, { "symbol", kS }, + { "sm", bit(ucd::Sm) }, { "mathsymbol", bit(ucd::Sm) }, + { "sc", bit(ucd::Sc) }, { "currencysymbol", bit(ucd::Sc) }, + { "sk", bit(ucd::Sk) }, { "modifiersymbol", bit(ucd::Sk) }, + { "so", bit(ucd::So) }, { "othersymbol", bit(ucd::So) }, + { "z", kZ }, { "separator", kZ }, + { "zs", bit(ucd::Zs) }, { "spaceseparator", bit(ucd::Zs) }, + { "zl", bit(ucd::Zl) }, { "lineseparator", bit(ucd::Zl) }, + { "zp", bit(ucd::Zp) }, { "paragraphseparator", bit(ucd::Zp) }, + { "c", kC }, { "other", kC }, + { "cc", bit(ucd::Cc) }, { "control", bit(ucd::Cc) }, { "cntrl", bit(ucd::Cc) }, + { "cf", bit(ucd::Cf) }, { "format", bit(ucd::Cf) }, + { "cs", bit(ucd::Cs) }, { "surrogate", bit(ucd::Cs) }, + { "co", bit(ucd::Co) }, { "privateuse", bit(ucd::Co) }, + { "cn", bit(ucd::Cn) }, { "unassigned", bit(ucd::Cn) }, +}; + +std::string prop_key(const std::string& raw) { + std::string k; + for (char c : raw) { + if (c == ' ' || c == '_' || c == '-') continue; + k += (char)((c >= 'A' && c <= 'Z') ? c - 'A' + 'a' : c); + } + return k; +} + +bool property_set(const std::string& name, CpSet* out) { + const std::string k = prop_key(name); + for (const GcName& g : k_gc_names) { + if (k == g.name) { *out = gc_mask_set(g.mask); return true; } + } + for (size_t i = 0; i < ucd::k_scripts_n; ++i) { + if (k == prop_key(ucd::k_scripts[i].name)) { + *out = set_from(ucd::k_scripts[i].ranges, ucd::k_scripts[i].n); + return true; + } + } + return false; +} + +/* ================================================================== the pattern, parsed */ + +enum AssertKind : uint8_t { + A_LINE_START, A_LINE_END, A_TEXT_START, A_TEXT_END, A_WORD_B, A_NOT_WORD_B, + A_AHEAD, A_AHEAD_NOT, A_BEHIND, A_BEHIND_NOT, +}; + +struct Node { + enum Kind : uint8_t { EMPTY, SET, CAT, ALT, REP, ASSERT } kind = EMPTY; + uint8_t assert_kind = 0; + bool greedy = true; + int min = 0, max = 0; /* REP; max < 0 is unbounded */ + int set = -1; /* SET, and the lookaround ASSERTs */ + std::vector kids; +}; + +struct Flags { bool i = false, m = false, x = false; }; + +/* Recursive descent over the pattern's codepoints. Every refusal goes through fail(), which + * records the first reason and makes every caller unwind; the message names the construct and + * the byte where it starts, because "unsupported pattern" alone sends the reader to a + * 200-character regex with no idea where to look. */ +class Parser { +public: + explicit Parser(std::string_view pat) : pat_(pat) {} + + bool parse(int* root) { + if (!decode_pattern()) return false; + Flags f; + const int r = parse_alt(f); + if (r < 0) return false; + if (i_ < cp_.size()) return fail("an unmatched ')'"); + *root = r; + return true; + } + + std::string err; + std::vector nodes; + std::vector sets; + +private: + std::string_view pat_; + std::vector cp_; + std::vector off_; /* byte offset of each codepoint */ + size_t i_ = 0; + size_t start_ = 0; /* where the construct being parsed began */ + + bool decode_pattern() { + const uint8_t* p = (const uint8_t*)pat_.data(); + const size_t n = pat_.size(); + for (size_t i = 0; i < n; ) { + uint32_t c = p[i], len = 1; + if (c >= 0x80) { + if (c >= 0xC2 && c < 0xE0) { len = 2; c &= 0x1F; } + else if (c >= 0xE0 && c < 0xF0) { len = 3; c &= 0x0F; } + else if (c >= 0xF0 && c < 0xF5) { len = 4; c &= 0x07; } + else { err = fmt("the pattern is not UTF-8 (byte %zu)", i); return false; } + if (i + len > n) { err = fmt("the pattern is not UTF-8 (byte %zu)", i); return false; } + for (uint32_t k = 1; k < len; ++k) { + if ((p[i + k] & 0xC0) != 0x80) { + err = fmt("the pattern is not UTF-8 (byte %zu)", i); + return false; + } + c = (c << 6) | (p[i + k] & 0x3F); + } + } + cp_.push_back(c); + off_.push_back(i); + i += len; + } + off_.push_back(n); + return true; + } + + bool fail(const char* what) { + if (err.empty()) { + const size_t at = off_.empty() ? 0 : off_[std::min(start_, off_.size() - 1)]; + const size_t end = off_.empty() ? 0 : off_[std::min(i_, off_.size() - 1)]; + /* The construct, cut at a codepoint boundary so the message stays UTF-8. */ + size_t stop = std::max(end, at + 1); + const size_t cap = std::min(start_ + 40, off_.size() - 1); + if (stop > off_[cap]) stop = off_[cap]; + std::string frag(pat_.substr(at, stop - at)); + if (stop < end) frag += "..."; + err = fmt("%s at byte %zu ('%s')", what, at, frag.c_str()); + } + return false; + } + int failn(const char* what) { fail(what); return -1; } + + bool at_end() const { return i_ >= cp_.size(); } + uint32_t peek(size_t k = 0) const { return i_ + k < cp_.size() ? cp_[i_ + k] : 0xFFFFFFFFu; } + + int add(Node n) { nodes.push_back(std::move(n)); return (int)nodes.size() - 1; } + int add_set(CpSet s) { sets.push_back(std::move(s)); return (int)sets.size() - 1; } + int mk_set(CpSet s) { Node n; n.kind = Node::SET; n.set = add_set(std::move(s)); return add(n); } + int mk_assert(uint8_t k, int set = -1) { + Node n; n.kind = Node::ASSERT; n.assert_kind = k; n.set = set; return add(n); + } + + void skip_extended(const Flags& f) { + if (!f.x) return; + while (!at_end()) { + const uint32_t c = peek(); + if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\v') { ++i_; continue; } + if (c == '#') { while (!at_end() && peek() != '\n') ++i_; continue; } + break; + } + } + + int parse_alt(const Flags& f) { + std::vector alts; + for (;;) { + const int c = parse_concat(f); + if (c < 0) return -1; + alts.push_back(c); + if (!at_end() && peek() == '|') { ++i_; continue; } + break; + } + if (alts.size() == 1) return alts[0]; + Node n; n.kind = Node::ALT; n.kids = std::move(alts); + return add(n); + } + + /* `(?imx-imx)` with no colon. Oniguruma reads the REST of the enclosing group -- every `|` + * after it included -- as one group with the new flags, so `a(?i)b|c` is `a(?i:b|c)` and not + * `a(?i:b)|(?i:c)`. The caller parses that rest as a nested alternation. */ + bool try_inline_flags(const Flags& f, Flags* g) { + if (peek() != '(' || peek(1) != '?') return false; + size_t k = 2; + bool on = true, any = false; + *g = f; + for (;; ++k) { + const uint32_t c = peek(k); + if (c == '-') { on = false; continue; } + if (c == 'i') { g->i = on; any = true; continue; } + if (c == 'm') { g->m = on; any = true; continue; } + if (c == 'x') { g->x = on; any = true; continue; } + if (c == ')' && any) { i_ += k + 1; return true; } + return false; + } + } + + int parse_concat(const Flags& f) { + std::vector items; + for (;;) { + skip_extended(f); + if (at_end() || peek() == '|' || peek() == ')') break; + Flags g; + if (try_inline_flags(f, &g)) { + const int rest = parse_alt(g); + if (rest < 0) return -1; + items.push_back(rest); + break; + } + start_ = i_; + int a = parse_atom(f); + if (a < 0) return -1; + a = parse_quant(a, f); + if (a < 0) return -1; + items.push_back(a); + } + if (items.empty()) return add(Node{}); + if (items.size() == 1) return items[0]; + Node n; n.kind = Node::CAT; n.kids = std::move(items); + return add(n); + } + + static bool is_digit(uint32_t c) { return c >= '0' && c <= '9'; } + + /* `{n}`, `{n,}`, `{,m}`, `{n,m}`, digits only. Anything else is a literal brace, as in Ruby. */ + bool interval_at(size_t at, int* mn, int* mx, size_t* len) const { + if (at >= cp_.size() || cp_[at] != '{') return false; + size_t k = at + 1; + long a = -1, b = -1; + auto num = [&](long* v) { + if (k >= cp_.size() || !is_digit(cp_[k])) return; + long x = 0; + while (k < cp_.size() && is_digit(cp_[k])) { x = std::min(x * 10 + (long)(cp_[k] - '0'), 100000L); ++k; } + *v = x; + }; + num(&a); + bool comma = false; + if (k < cp_.size() && cp_[k] == ',') { comma = true; ++k; num(&b); } + if (k >= cp_.size() || cp_[k] != '}') return false; + if (a < 0 && (!comma || b < 0)) return false; + *mn = a < 0 ? 0 : (int)a; + *mx = comma ? (b < 0 ? -1 : (int)b) : *mn; + *len = k + 1 - at; + return true; + } + + bool is_quantifier_at(size_t at) const { + if (at >= cp_.size()) return false; + const uint32_t c = cp_[at]; + if (c == '?' || c == '*' || c == '+') return true; + int a, b; size_t l; + return interval_at(at, &a, &b, &l); + } + + static bool nullable(const std::vector& nodes, int id) { + const Node& n = nodes[id]; + switch (n.kind) { + case Node::EMPTY: case Node::ASSERT: return true; + case Node::SET: return false; + case Node::CAT: + for (int k : n.kids) if (!nullable(nodes, k)) return false; + return true; + case Node::ALT: + for (int k : n.kids) if (nullable(nodes, k)) return true; + return false; + case Node::REP: return n.min == 0 || nullable(nodes, n.kids[0]); + } + return true; + } + + int parse_quant(int atom, const Flags& f) { + skip_extended(f); + if (at_end()) return atom; + int mn = 0, mx = 0; + size_t len = 1; + const uint32_t c = peek(); + if (c == '?') { mn = 0; mx = 1; } + else if (c == '*') { mn = 0; mx = -1; } + else if (c == '+') { mn = 1; mx = -1; } + else if (!interval_at(i_, &mn, &mx, &len)) return atom; + const bool brace = c == '{'; + i_ += len; + bool greedy = true; + if (!at_end() && peek() == '?') { greedy = false; ++i_; } + else if (!at_end() && peek() == '+') { + return failn(brace ? "a quantifier applied to a quantifier (Ruby reads '{n,m}+' as nested repetition)" + : "a possessive quantifier"); + } + if (is_quantifier_at(i_)) return failn("a quantifier applied to a quantifier"); + if (nodes[atom].kind == Node::ASSERT) return failn("a quantifier on an assertion"); + if (mx >= 0 && mn > mx) return failn("a repetition whose minimum exceeds its maximum"); + if (mn > 1000 || mx > 1000) return failn("a counted repetition above 1000"); + if (mx < 0 && nullable(nodes, atom)) + return failn("unbounded repetition of an expression that can match empty"); + Node n; n.kind = Node::REP; n.min = mn; n.max = mx; n.greedy = greedy; n.kids = { atom }; + return add(n); + } + + int literal(uint32_t c, const Flags& f) { + if (f.i) { + if (set_has(case_data().multi, c)) + return failn("a case-insensitive character that also matches a multi-codepoint sequence"); + return mk_set(case_close({ { c, c } })); + } + return mk_set({ { c, c } }); + } + + /* A lookaround body must be one codepoint wide: a class, a character, or an alternation of + * those. Its set is what the assertion tests the neighbouring codepoint against. */ + bool single_cp_set(int id, CpSet* out) { + const Node& n = nodes[id]; + if (n.kind == Node::SET) { *out = sets[n.set]; return true; } + if (n.kind == Node::CAT && n.kids.size() == 1) return single_cp_set(n.kids[0], out); + if (n.kind == Node::ALT) { + CpSet u; + for (int k : n.kids) { + CpSet s; + if (!single_cp_set(k, &s)) return false; + u = set_union(u, s); + } + *out = u; + return true; + } + return false; + } + + int parse_group(const Flags& outer) { + /* `(` already consumed. */ + Flags f = outer; + if (peek() != '?') { + const int r = parse_alt(f); + if (r < 0) return -1; + if (peek() != ')') return failn("an unterminated group"); + ++i_; + return r; + } + ++i_; + const uint32_t c = peek(); + ++i_; + auto body = [&](Flags& g) -> int { + const int r = parse_alt(g); + if (r < 0) return -1; + if (peek() != ')') return failn("an unterminated group"); + ++i_; + return r; + }; + auto lookaround = [&](uint8_t kind) -> int { + const size_t at = start_; + const int r = body(f); + if (r < 0) return -1; + CpSet s; + if (!single_cp_set(r, &s)) { + start_ = at; + return failn("a lookaround wider than one codepoint"); + } + return mk_assert(kind, add_set(std::move(s))); + }; + switch (c) { + case ':': return body(f); + case '=': return lookaround(A_AHEAD); + case '!': return lookaround(A_AHEAD_NOT); + case '>': return failn("an atomic group"); + case '~': return failn("an absent operator"); + case '#': { + while (!at_end() && peek() != ')') ++i_; + if (at_end()) return failn("an unterminated comment"); + ++i_; + return add(Node{}); + } + case '<': { + if (peek() == '=') { ++i_; return lookaround(A_BEHIND); } + if (peek() == '!') { ++i_; return lookaround(A_BEHIND_NOT); } + while (!at_end() && peek() != '>') ++i_; /* a named group */ + if (at_end()) return failn("an unterminated group name"); + ++i_; + return body(f); + } + case '\'': { + while (!at_end() && peek() != '\'') ++i_; + if (at_end()) return failn("an unterminated group name"); + ++i_; + return body(f); + } + default: break; + } + /* `(?imx-imx:...)`. The no-colon form was consumed by try_inline_flags. */ + --i_; + bool on = true, any = false; + for (;;) { + const uint32_t k = peek(); + if (k == '-') { on = false; ++i_; continue; } + if (k == 'i') { f.i = on; any = true; ++i_; continue; } + if (k == 'm') { f.m = on; any = true; ++i_; continue; } + if (k == 'x') { f.x = on; any = true; ++i_; continue; } + if (k == ':' && any) { ++i_; return body(f); } + return failn("an unknown group option"); + } + } + + int parse_atom(const Flags& f) { + const uint32_t c = peek(); + ++i_; + switch (c) { + case '(': return parse_group(f); + case '[': { + CpSet s; + if (!parse_class(f, &s)) return -1; + return mk_set(std::move(s)); + } + case '.': { + CpSet s = { { 0, kMaxCp } }; + if (!f.m) s = { { 0, '\n' - 1 }, { '\n' + 1, kMaxCp } }; + return mk_set(std::move(s)); + } + case '^': return mk_assert(A_LINE_START); + case '$': return mk_assert(A_LINE_END); + case '\\': return parse_escape_atom(f); + case '?': case '*': case '+': return failn("a quantifier with nothing to repeat"); + case '{': { + int a, b; size_t l; + if (interval_at(i_ - 1, &a, &b, &l)) return failn("a quantifier with nothing to repeat"); + return literal(c, f); + } + default: return literal(c, f); + } + } + + /* Escapes shared by atoms and classes. `kind` says what came back. */ + enum EscKind { E_CHAR, E_SET, E_ASSERT }; + struct Esc { + EscKind kind = E_CHAR; + uint32_t ch = 0; + CpSet set; + uint8_t assert_kind = 0; + bool prop = false; /* the set came from \p{...} */ + }; + + static int hexval(uint32_t c) { + return c >= '0' && c <= '9' ? (int)(c - '0') : c >= 'a' && c <= 'f' ? (int)(c - 'a' + 10) + : c >= 'A' && c <= 'F' ? (int)(c - 'A' + 10) : -1; + } + + bool parse_escape(bool in_class, Esc* e) { + if (at_end()) return fail("a trailing backslash"); + const uint32_t c = peek(); + ++i_; + e->kind = E_CHAR; + switch (c) { + case 't': e->ch = 9; return true; + case 'n': e->ch = 10; return true; + case 'r': e->ch = 13; return true; + case 'f': e->ch = 12; return true; + case 'v': e->ch = 11; return true; + case 'a': e->ch = 7; return true; + case 'e': e->ch = 27; return true; + case '0': { + uint32_t v = 0; + for (int k = 0; k < 2 && peek() >= '0' && peek() <= '7'; ++k) { v = v * 8 + (peek() - '0'); ++i_; } + e->ch = v; + return true; + } + case 'x': { + uint32_t v = 0; + if (peek() == '{') { + ++i_; + int nd = 0; + while (hexval(peek()) >= 0 && nd < 8) { v = v * 16 + hexval(peek()); ++i_; ++nd; } + if (nd == 0 || peek() != '}') return fail("a malformed \\x{...} escape"); + ++i_; + } else { + int nd = 0; + while (hexval(peek()) >= 0 && nd < 2) { v = v * 16 + hexval(peek()); ++i_; ++nd; } + if (nd == 0) return fail("a malformed \\x escape"); + } + if (v > kMaxCp) return fail("a codepoint above U+10FFFF"); + e->ch = v; + return true; + } + case 'u': { + uint32_t v = 0; + for (int k = 0; k < 4; ++k) { + if (hexval(peek()) < 0) return fail("a malformed \\u escape"); + v = v * 16 + hexval(peek()); + ++i_; + } + e->ch = v; + return true; + } + case 'c': { + if (at_end()) return fail("a malformed \\c escape"); + e->ch = peek() & 0x1F; + ++i_; + return true; + } + case 'd': e->kind = E_SET; e->set = digit_set(); return true; + case 'D': e->kind = E_SET; e->set = set_complement(digit_set()); return true; + case 's': e->kind = E_SET; e->set = white_space_set(); return true; + case 'S': e->kind = E_SET; e->set = set_complement(white_space_set()); return true; + case 'w': case 'W': { + /* Oniguruma's two definitions; see tokenizer_ucd.h. */ + const CpSet& w = in_class ? word_class_set() : word_set(); + e->kind = E_SET; + e->set = c == 'w' ? w : set_complement(w); + return true; + } + case 'h': e->kind = E_SET; e->set = hex_set(); return true; + case 'H': e->kind = E_SET; e->set = set_complement(hex_set()); return true; + case 'p': case 'P': { + if (peek() != '{') return fail("a property escape without braces"); + ++i_; + bool neg = c == 'P'; + if (peek() == '^') { neg = !neg; ++i_; } + std::string name; + while (!at_end() && peek() != '}') { + if (peek() >= 0x80) return fail("an unknown property"); + name += (char)peek(); + ++i_; + } + if (at_end()) return fail("an unterminated property escape"); + ++i_; + CpSet s; + if (!property_set(name, &s)) return fail("a property the tables do not carry"); + e->kind = E_SET; + e->prop = true; + e->set = neg ? set_complement(s) : s; + return true; + } + case 'b': + if (in_class) { e->ch = 8; return true; } + e->kind = E_ASSERT; e->assert_kind = A_WORD_B; return true; + case 'B': case 'A': case 'z': + if (in_class) return fail("an assertion inside a character class"); + e->kind = E_ASSERT; + e->assert_kind = c == 'B' ? A_NOT_WORD_B : c == 'A' ? A_TEXT_START : A_TEXT_END; + return true; + case 'Z': return fail("\\Z (end of text or before a final newline)"); + case 'G': return fail("\\G"); + case 'R': return fail("\\R (an atomic linebreak)"); + case 'X': return fail("\\X (a grapheme cluster)"); + case 'K': return fail("\\K"); + case 'Q': return fail("\\Q...\\E quoting"); + case 'k': case 'g': return fail("a backreference or subexpression call"); + default: break; + } + if (c >= '1' && c <= '9') return fail("a backreference"); + if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) return fail("an unknown escape"); + e->ch = c; /* an escaped metacharacter, or any other symbol, is itself */ + return true; + } + + int parse_escape_atom(const Flags& f) { + Esc e; + if (!parse_escape(false, &e)) return -1; + if (e.kind == E_ASSERT) return mk_assert(e.assert_kind); + if (e.kind == E_SET) return mk_set(std::move(e.set)); + return literal(e.ch, f); + } + + /* `[` already consumed. Oniguruma's classes: a leading `^`, nested classes as union, `&&` as + * intersection, `-` literal at either end. Under `(?i)` the class is closed over the case + * orbits BEFORE it is negated, which is what makes `(?i:[^a-z])` exclude 'A'. */ + bool parse_class(const Flags& f, CpSet* out) { + const size_t at = start_; + const bool neg = peek() == '^'; + if (neg) ++i_; + CpSet acc, cur; + bool have_acc = false, first = true, used_prop = false, nested = false; + for (;;) { + if (at_end()) { start_ = at; return fail("an unterminated character class"); } + const uint32_t c = peek(); + if (c == ']' && !first) { ++i_; break; } + if (c == '&' && peek(1) == '&') { + i_ += 2; + acc = have_acc ? set_intersect(acc, cur) : cur; + have_acc = true; + cur.clear(); + first = false; + continue; + } + if (c == '[') { + if (peek(1) == ':') return fail("a POSIX bracket expression"); + ++i_; + CpSet inner; + if (!parse_class(f, &inner)) return false; + cur = set_union(cur, inner); + nested = true; + first = false; + continue; + } + uint32_t lo; + if (c == '\\') { + ++i_; + Esc e; + if (!parse_escape(true, &e)) return false; + if (e.kind == E_SET) { + used_prop = used_prop || e.prop; + cur = set_union(cur, e.set); + first = false; + continue; + } + lo = e.ch; + } else { + lo = c; + ++i_; + } + first = false; + if (peek() == '-' && peek(1) != ']' && peek(1) != 0xFFFFFFFFu) { + ++i_; + uint32_t hi; + if (peek() == '\\') { + ++i_; + Esc e; + if (!parse_escape(true, &e)) return false; + if (e.kind != E_CHAR) return fail("a class range whose end is not a character"); + hi = e.ch; + } else if (peek() == '[') { + return fail("a class range whose end is not a character"); + } else { + hi = peek(); + ++i_; + } + if (hi < lo) return fail("a class range out of order"); + cur = set_union(cur, { { lo, hi } }); + } else { + cur = set_union(cur, { { lo, lo } }); + } + } + CpSet s = have_acc ? set_intersect(acc, cur) : cur; + if (f.i) { + start_ = at; + if (have_acc) return fail("a class intersection under (?i)"); + if (used_prop) return fail("a property inside a class under (?i)"); + if (nested) return fail("a nested class under (?i)"); + if (!set_intersect(s, case_data().multi).empty()) + return fail("a case-insensitive class holding a character that also matches a " + "multi-codepoint sequence"); + s = case_close(s); + } + *out = neg ? set_complement(s) : s; + return true; + } +}; + +/* ================================================================== NFA */ + +enum NOp : uint8_t { N_CHAR, N_SPLIT, N_EPS, N_ASSERT, N_MATCH }; + +struct NState { + uint8_t op; + int out = -1, out1 = -1; + int arg = -1; /* N_CHAR: set; N_ASSERT: node index of the assertion */ +}; + +constexpr size_t kMaxNfaStates = 200000; +constexpr size_t kMaxDfaStates = 20000; + +class NfaBuilder { +public: + NfaBuilder(const std::vector& nodes) : nodes_(nodes) {} + std::vector st; + bool too_big = false; + + int build(int root) { + Frag f = frag(root); + const int m = add(N_MATCH); + patch(f.outs, m); + return f.start; + } + +private: + struct Frag { int start; std::vector> outs; }; + const std::vector& nodes_; + + int add(uint8_t op, int arg = -1) { + if (st.size() >= kMaxNfaStates) too_big = true; + NState s; s.op = op; s.arg = arg; + st.push_back(s); + return (int)st.size() - 1; + } + void patch(const std::vector>& outs, int to) { + for (const auto& o : outs) (o.second ? st[o.first].out1 : st[o.first].out) = to; + } + + Frag frag(int id) { + const Node& n = nodes_[id]; + if (too_big) { const int s = add(N_EPS); return { s, { { s, 0 } } }; } + switch (n.kind) { + case Node::EMPTY: { const int s = add(N_EPS); return { s, { { s, 0 } } }; } + case Node::SET: { const int s = add(N_CHAR, n.set); return { s, { { s, 0 } } }; } + case Node::ASSERT:{ const int s = add(N_ASSERT, id); return { s, { { s, 0 } } }; } + case Node::CAT: { + Frag a = frag(n.kids[0]); + for (size_t k = 1; k < n.kids.size(); ++k) { + Frag b = frag(n.kids[k]); + patch(a.outs, b.start); + a.outs = std::move(b.outs); + } + return a; + } + case Node::ALT: { + /* A chain of splits, each preferring the earlier alternative. */ + Frag last = frag(n.kids.back()); + int start = last.start; + std::vector> outs = last.outs; + for (size_t k = n.kids.size() - 1; k-- > 0; ) { + Frag a = frag(n.kids[k]); + const int s = add(N_SPLIT); + st[s].out = a.start; + st[s].out1 = start; + outs.insert(outs.end(), a.outs.begin(), a.outs.end()); + start = s; + } + return { start, outs }; + } + case Node::REP: { + const int kid = n.kids[0]; + Frag acc{ -1, {} }; + auto append = [&](Frag f) { + if (acc.start < 0) acc = std::move(f); + else { patch(acc.outs, f.start); acc.outs = std::move(f.outs); } + }; + for (int k = 0; k < n.min; ++k) append(frag(kid)); + if (n.max < 0) { + /* The loop: the split prefers another iteration when greedy, the exit when lazy. */ + const int s = add(N_SPLIT); + Frag body = frag(kid); + patch(body.outs, s); + Frag loop{ s, {} }; + if (n.greedy) { st[s].out = body.start; loop.outs = { { s, 1 } }; } + else { st[s].out1 = body.start; loop.outs = { { s, 0 } }; } + append(std::move(loop)); + } else if (n.max > n.min) { + /* Nested optionals: x{0,2} is (x(x)?)?. */ + std::vector> exits; + int first = -1; + std::vector> pending; + for (int k = n.min; k < n.max; ++k) { + const int s = add(N_SPLIT); + Frag body = frag(kid); + if (n.greedy) { st[s].out = body.start; exits.push_back({ s, 1 }); } + else { st[s].out1 = body.start; exits.push_back({ s, 0 }); } + if (first < 0) first = s; else patch(pending, s); + pending = std::move(body.outs); + } + exits.insert(exits.end(), pending.begin(), pending.end()); + append(Frag{ first, exits }); + } + if (acc.start < 0) { const int s = add(N_EPS); acc = { s, { { s, 0 } } }; } + return acc; + } + } + const int s = add(N_EPS); + return { s, { { s, 0 } } }; + } +}; + +} /* namespace */ + +/* ================================================================== DFA */ + +namespace { + +/* Decode one codepoint of canonical UTF-8. */ +inline uint32_t decode_canon(const uint8_t* p, uint32_t* len) { + const uint32_t b = p[0]; + if (b < 0x80) { *len = 1; return b; } + if (b < 0xE0) { *len = 2; return ((b & 0x1F) << 6) | (p[1] & 0x3F); } + if (b < 0xF0) { *len = 3; return ((b & 0x0F) << 12) | ((p[1] & 0x3F) << 6) | (p[2] & 0x3F); } + *len = 4; + return ((b & 0x07) << 18) | ((p[1] & 0x3F) << 12) | ((p[2] & 0x3F) << 6) | (p[3] & 0x3F); +} + +} /* namespace */ + +struct TokRegex::Dfa { + static constexpr uint32_t kMatch = 0x80000000u; + + /* States are named by their ROW OFFSET, state * ncls, so the inner loop indexes the table + * with one add. The dead state is row 0. */ + uint32_t ncls = 0; + std::vector trans; /* row + class -> next row | kMatch */ + std::vector eoi_match; /* per state: a match ends at the end of the text */ + uint32_t start_text = 0; /* start row at the beginning of the text */ + std::vector start_after; /* start row after a codepoint of each class */ + bool uses_behind = false; + + uint8_t ascii[128]; + std::vector stage1; /* cp >> 8 -> block */ + std::vector stage2; /* block * 256 + (cp & 255) -> class */ + + uint32_t cls_of(uint32_t cp) const { + return cp < 128 ? ascii[cp] : stage2[((uint32_t)stage1[cp >> 8] << 8) | (cp & 0xFF)]; + } + + /* The class of the codepoint that ends just before byte `pos`. */ + uint32_t prev_class(const uint8_t* s, size_t pos) const { + size_t b = pos - 1; + while (b > 0 && (s[b] & 0xC0) == 0x80 && pos - b < 4) --b; + uint32_t len; + return cls_of(decode_canon(s + b, &len)); + } +}; + + +TokRegex::~TokRegex() = default; +size_t TokRegex::n_states() const { return dfa_ ? dfa_->eoi_match.size() : 0; } +size_t TokRegex::n_classes() const { return dfa_ ? dfa_->ncls : 0; } + +int TokRegex::compile(std::string_view pattern, std::unique_ptr* out, std::string* why) { + auto refuse = [&](const std::string& m) { + if (why) *why = m; + return RAD_E_UNSUPPORTED; + }; + + Parser p(pattern); + int root = -1; + if (!p.parse(&root)) return refuse(p.err); + + NfaBuilder nb(p.nodes); + const int start = nb.build(root); + if (nb.too_big) return refuse(fmt("the pattern expands to more than %zu NFA states", kMaxNfaStates)); + const std::vector& nfa = nb.st; + + /* ---- the sets the DFA has to tell apart, and the assertions that read them. */ + std::vector& sets = p.sets; + const int nl_set = (int)sets.size(); + sets.push_back({ { '\n', '\n' } }); + const int word = (int)sets.size(); + sets.push_back(word_set()); + + std::vector behind; /* sets whose membership the state remembers */ + auto behind_bit = [&](int set) -> uint32_t { + for (size_t k = 0; k < behind.size(); ++k) + if (behind[k] == set) return 1u << (k + 1); + behind.push_back(set); + return 1u << behind.size(); + }; + struct Look { uint8_t kind; int set; uint32_t bbit; }; + std::unordered_map looks; /* NFA assert state -> what it tests */ + bool uses_behind = false; + std::vector set_used(sets.size(), 0); + for (size_t s = 0; s < nfa.size(); ++s) { + if (nfa[s].op == N_CHAR) set_used[nfa[s].arg] = 1; + if (nfa[s].op != N_ASSERT) continue; + const Node& a = p.nodes[nfa[s].arg]; + Look l{ a.assert_kind, a.set, 0 }; + switch (a.assert_kind) { + case A_LINE_START: l.set = nl_set; l.bbit = behind_bit(nl_set); uses_behind = true; break; + case A_LINE_END: l.set = nl_set; break; + case A_TEXT_START: uses_behind = true; break; + case A_TEXT_END: break; + case A_WORD_B: case A_NOT_WORD_B: + l.set = word; l.bbit = behind_bit(word); uses_behind = true; break; + case A_BEHIND: case A_BEHIND_NOT: + l.bbit = behind_bit(a.set); uses_behind = true; break; + default: break; + } + if (l.set >= 0) set_used[l.set] = 1; + looks[(int)s] = l; + } + if (behind.size() > 30) return refuse("more than 30 distinct lookbehind sets"); + + /* ---- the alphabet partition: codepoints no set tells apart share a class. */ + std::vector used; + for (size_t k = 0; k < sets.size(); ++k) if (set_used[k]) used.push_back((int)k); + std::vector bounds = { 0, kMaxCp + 1 }; + for (int k : used) + for (const auto& r : sets[k]) { bounds.push_back(r.first); bounds.push_back(r.second + 1); } + std::sort(bounds.begin(), bounds.end()); + bounds.erase(std::unique(bounds.begin(), bounds.end()), bounds.end()); + + auto d = std::make_unique(); + std::vector cls_full(kMaxCp + 1); + std::unordered_map sig_to_cls; + std::vector> in_set; /* class -> membership per set index */ + for (size_t b = 0; b + 1 < bounds.size(); ++b) { + const uint32_t lo = bounds[b], hi = bounds[b + 1]; + std::string sig(used.size(), '\0'); + for (size_t k = 0; k < used.size(); ++k) sig[k] = set_has(sets[used[k]], lo) ? 1 : 0; + auto it = sig_to_cls.find(sig); + uint32_t c; + if (it == sig_to_cls.end()) { + c = (uint32_t)in_set.size(); + if (c >= 256) return refuse("the pattern needs more than 256 codepoint classes"); + sig_to_cls.emplace(sig, c); + std::vector m(sets.size(), 0); + for (size_t k = 0; k < used.size(); ++k) m[used[k]] = (uint8_t)sig[k]; + in_set.push_back(std::move(m)); + } else { + c = it->second; + } + std::fill(cls_full.begin() + lo, cls_full.begin() + hi, (uint8_t)c); + } + d->ncls = (uint32_t)in_set.size(); + for (int c = 0; c < 128; ++c) d->ascii[c] = cls_full[c]; + { + std::unordered_map blocks; + d->stage1.resize((kMaxCp + 1) >> 8); + for (uint32_t blk = 0; blk < d->stage1.size(); ++blk) { + std::string key((const char*)cls_full.data() + blk * 256, 256); + auto it = blocks.find(key); + if (it == blocks.end()) { + const uint16_t id = (uint16_t)blocks.size(); + blocks.emplace(key, id); + d->stage2.insert(d->stage2.end(), key.begin(), key.end()); + d->stage1[blk] = id; + } else { + d->stage1[blk] = it->second; + } + } + } + + /* What the state remembers about the codepoint just consumed. Bit 0 is "at the start". */ + std::vector lb_after(d->ncls, 0); + for (uint32_t c = 0; c < d->ncls; ++c) + for (size_t k = 0; k < behind.size(); ++k) + if (in_set[c][behind[k]]) lb_after[c] |= 1u << (k + 1); + /* next < 0 is the end of the text. */ + auto holds = [&](const Look& l, uint32_t lb, int next) -> bool { + const bool at_start = (lb & 1) != 0; + auto in = [&](int set) { return next >= 0 && in_set[next][set] != 0; }; + switch (l.kind) { + case A_LINE_START: return at_start || (lb & l.bbit); + case A_LINE_END: return next < 0 || in(l.set); + case A_TEXT_START: return at_start; + case A_TEXT_END: return next < 0; + case A_WORD_B: return (!at_start && (lb & l.bbit)) != in(l.set); + case A_NOT_WORD_B: return (!at_start && (lb & l.bbit)) == in(l.set); + case A_AHEAD: return in(l.set); + case A_AHEAD_NOT: return !in(l.set); + case A_BEHIND: return !at_start && (lb & l.bbit); + case A_BEHIND_NOT: return at_start || !(lb & l.bbit); + } + return false; + }; + + /* ---- subset construction, leftmost-first. + * + * A DFA state is the ordered list of NFA states reached by consuming the last codepoint + * (before their epsilon closure), plus what is remembered of that codepoint. The closure is + * taken on the TRANSITION, when the next codepoint's class is known, so a lookahead is + * decided exactly. Walking the closure in priority order, reaching MATCH means a match ends + * here and every thread after it is dropped: a lower-priority thread can never produce the + * match a backtracking engine would report once a higher one has matched. The threads before + * it survive, and a later match from one of them replaces this one. */ + std::vector mark(nfa.size(), 0), mark2(nfa.size(), 0); + uint32_t stamp = 0, stamp2 = 0; + std::vector stack, chars, next_kernel; + + auto closure = [&](const std::vector& kernel, uint32_t lb, int next, + std::vector* next_out) -> bool { + ++stamp; + chars.clear(); + bool matched = false; + for (int k0 : kernel) { + stack.clear(); + stack.push_back(k0); + while (!stack.empty() && !matched) { + const int s = stack.back(); + stack.pop_back(); + if (s < 0 || mark[s] == stamp) continue; + mark[s] = stamp; + const NState& ns = nfa[s]; + switch (ns.op) { + case N_CHAR: chars.push_back(s); break; + case N_EPS: stack.push_back(ns.out); break; + case N_SPLIT: stack.push_back(ns.out1); stack.push_back(ns.out); break; + case N_ASSERT: if (holds(looks[s], lb, next)) stack.push_back(ns.out); break; + case N_MATCH: matched = true; break; + } + } + if (matched) break; + } + if (next_out) { + next_out->clear(); + if (next >= 0) { + ++stamp2; + for (int s : chars) { + if (!in_set[next][nfa[s].arg]) continue; + const int t = nfa[s].out; + if (mark2[t] == stamp2) continue; + mark2[t] = stamp2; + next_out->push_back(t); + } + } + } + return matched; + }; + + std::unordered_map ids; + std::vector> kernels; + std::vector lbs; + auto intern = [&](const std::vector& k, uint32_t lb) -> uint32_t { + if (k.empty()) return 0; + std::string key((const char*)k.data(), k.size() * sizeof(int)); + key.append((const char*)&lb, sizeof lb); + auto it = ids.find(key); + if (it != ids.end()) return it->second; + const uint32_t id = (uint32_t)kernels.size(); + ids.emplace(std::move(key), id); + kernels.push_back(k); + lbs.push_back(lb); + return id; + }; + kernels.push_back({}); /* 0: dead */ + lbs.push_back(0); + + d->uses_behind = uses_behind; + d->start_text = intern({ start }, uses_behind ? 1u : 0u); + d->start_after.assign(d->ncls, d->start_text); + if (uses_behind) + for (uint32_t c = 0; c < d->ncls; ++c) d->start_after[c] = intern({ start }, lb_after[c]); + + for (uint32_t s = 0; s < kernels.size(); ++s) { + if (kernels.size() > kMaxDfaStates) + return refuse(fmt("the pattern determinises to more than %zu states", kMaxDfaStates)); + d->trans.resize((size_t)kernels.size() * d->ncls, 0); + d->eoi_match.resize(kernels.size(), 0); + if (s == 0) continue; + const std::vector kernel = kernels[s]; + const uint32_t lb = lbs[s]; + for (uint32_t c = 0; c < d->ncls; ++c) { + const bool m = closure(kernel, lb, (int)c, &next_kernel); + const uint32_t t = intern(next_kernel, uses_behind ? lb_after[c] : 0); + d->trans.resize((size_t)kernels.size() * d->ncls, 0); + d->trans[(size_t)s * d->ncls + c] = t | (m ? Dfa::kMatch : 0); + } + d->eoi_match[s] = closure(kernel, lb, -1, nullptr) ? 1 : 0; + } + d->trans.resize((size_t)kernels.size() * d->ncls, 0); + d->eoi_match.resize(kernels.size(), 0); + for (uint32_t& t : d->trans) t = ((t & ~Dfa::kMatch) * d->ncls) | (t & Dfa::kMatch); + d->start_text *= d->ncls; + for (uint32_t& t : d->start_after) t *= d->ncls; + + std::unique_ptr re(new TokRegex()); + re->pattern_ = std::string(pattern); + re->dfa_ = std::move(d); + *out = std::move(re); + return RAD_OK; +} + +int64_t TokRegex::match_at(std::string_view text, size_t pos) const { + const Dfa& d = *dfa_; + const uint8_t* s = (const uint8_t*)text.data(); + const size_t n = text.size(); + uint32_t state = pos == 0 || !d.uses_behind ? d.start_text : d.start_after[d.prev_class(s, pos)]; + const uint32_t* trans = d.trans.data(); + int64_t best = -1; + size_t q = pos; + while (q < n) { + uint32_t len, cls; + const uint32_t b = s[q]; + if (b < 0x80) { cls = d.ascii[b]; len = 1; } + else { cls = d.cls_of(decode_canon(s + q, &len)); } + const uint32_t t = trans[state + cls]; + if (t & Dfa::kMatch) best = (int64_t)q; + state = t & ~Dfa::kMatch; + if (state == 0) return best; + q += len; + } + if (d.eoi_match[state / d.ncls]) best = (int64_t)n; + return best; +} + +void TokRegex::find_iter(std::string_view text, std::vector& out) const { + /* Oniguruma's iteration as the `onig` crate drives it: search from the end of the previous + * match for the leftmost position with a match; an EMPTY match exactly at the end of the + * previous one is skipped by advancing one codepoint and searching again. */ + const uint8_t* s = (const uint8_t*)text.data(); + const size_t n = text.size(); + size_t pos = 0; + bool have_prev = false; + size_t prev_end = 0; + while (pos <= n) { + const int64_t e = match_at(text, pos); + if (e >= 0 && !((size_t)e == pos && have_prev && prev_end == pos)) { + out.push_back({ (uint32_t)pos, (uint32_t)e }); + have_prev = true; + prev_end = (size_t)e; + if ((size_t)e > pos) { pos = (size_t)e; continue; } + } + if (pos == n) break; + uint32_t len; + decode_canon(s + pos, &len); + pos += len; + } +} + +void tok_split(const TokRegex& re, std::string_view text, int behavior, bool invert, + std::vector& out, std::vector& m) { + m.clear(); + re.find_iter(text, m); + const uint32_t n = (uint32_t)text.size(); + + /* Isolated keeps every match and every gap as its own piece, so `invert` cannot change it. */ + if (behavior == TOK_SPLIT_ISOLATED) { + uint32_t prev = 0; + for (const TokSpan& x : m) { + if (x.begin > prev) out.push_back({ prev, x.begin }); + if (x.end > x.begin) out.push_back(x); + prev = x.end; + } + if (prev < n) out.push_back({ prev, n }); + return; + } + + /* The general case follows NormalizedString::split step by step: matches and gaps in order + * (empty matches included), flipped by `invert`, folded by the behaviour, then the removed + * and the empty pieces dropped. */ + struct Part { uint32_t b, e; bool match; }; + std::vector parts; + { + uint32_t prev = 0; + for (const TokSpan& x : m) { + if (x.begin != prev) parts.push_back({ prev, x.begin, false }); + parts.push_back({ x.begin, x.end, true }); + prev = x.end; + } + if (prev != n) parts.push_back({ prev, n, false }); + if (invert) for (Part& p : parts) p.match = !p.match; + } + struct Keep { uint32_t b, e; bool remove; }; + std::vector keep; + switch (behavior) { + case TOK_SPLIT_REMOVED: + for (const Part& p : parts) keep.push_back({ p.b, p.e, p.match }); + break; + case TOK_SPLIT_CONTIGUOUS: { + bool prev_match = false; + for (const Part& p : parts) { + if (p.match == prev_match && !keep.empty()) keep.back().e = p.e; + else keep.push_back({ p.b, p.e, false }); + prev_match = p.match; + } + break; + } + case TOK_SPLIT_MERGED_PREV: { + bool prev_match = false; + for (const Part& p : parts) { + if (p.match && !prev_match && !keep.empty()) keep.back().e = p.e; + else keep.push_back({ p.b, p.e, false }); + prev_match = p.match; + } + break; + } + case TOK_SPLIT_MERGED_NEXT: { + bool prev_match = false; + for (size_t k = parts.size(); k-- > 0; ) { + const Part& p = parts[k]; + if (p.match && !prev_match && !keep.empty()) keep.back().b = p.b; + else keep.push_back({ p.b, p.e, false }); + prev_match = p.match; + } + std::reverse(keep.begin(), keep.end()); + break; + } + default: + for (const Part& p : parts) keep.push_back({ p.b, p.e, false }); + break; + } + for (const Keep& k : keep) + if (!k.remove && k.e > k.b) out.push_back({ k.b, k.e }); +} + +void tok_replace(const TokRegex& re, std::string_view text, std::string_view content, + std::string& out) { + std::vector m; + re.find_iter(text, m); + uint32_t prev = 0; + for (const TokSpan& x : m) { + out.append(text.data() + prev, x.begin - prev); + out.append(content); + prev = x.end; + } + out.append(text.data() + prev, text.size() - prev); +} + +bool utf8_is_canonical(std::string_view str) { + const uint8_t* p = (const uint8_t*)str.data(); + const size_t n = str.size(); + size_t i = 0; + while (i < n) { + if (i + 8 <= n) { + uint64_t w; + std::memcpy(&w, p + i, 8); + if (!(w & 0x8080808080808080ull)) { i += 8; continue; } + } + const uint8_t b = p[i]; + if (b < 0x80) { ++i; continue; } + if (b < 0xC2) return false; /* continuation, or overlong C0/C1 */ + if (b < 0xE0) { + if (i + 1 >= n || (p[i + 1] & 0xC0) != 0x80) return false; + i += 2; + continue; + } + if (b < 0xF0) { + if (i + 2 >= n || (p[i + 1] & 0xC0) != 0x80 || (p[i + 2] & 0xC0) != 0x80) return false; + if (b == 0xE0 && p[i + 1] < 0xA0) return false; /* overlong */ + i += 3; + continue; + } + if (b < 0xF5) { + if (i + 3 >= n || (p[i + 1] & 0xC0) != 0x80 || (p[i + 2] & 0xC0) != 0x80 || + (p[i + 3] & 0xC0) != 0x80) return false; + if (b == 0xF0 && p[i + 1] < 0x90) return false; /* overlong */ + if (b == 0xF4 && p[i + 1] > 0x8F) return false; /* above U+10FFFF */ + i += 4; + continue; + } + return false; + } + return true; +} + +void utf8_canonicalize(std::string_view str, std::string& out) { + const uint8_t* p = (const uint8_t*)str.data(); + const size_t n = str.size(); + auto cont = [&](size_t k) { return k < n && (p[k] & 0xC0) == 0x80; }; + auto put = [&](uint32_t c) { + if (c < 0x80) { out += (char)c; return; } + if (c < 0x800) { out += (char)(0xC0 | (c >> 6)); out += (char)(0x80 | (c & 0x3F)); return; } + if (c < 0x10000) { + out += (char)(0xE0 | (c >> 12)); + out += (char)(0x80 | ((c >> 6) & 0x3F)); + out += (char)(0x80 | (c & 0x3F)); + return; + } + out += (char)(0xF0 | (c >> 18)); + out += (char)(0x80 | ((c >> 12) & 0x3F)); + out += (char)(0x80 | ((c >> 6) & 0x3F)); + out += (char)(0x80 | (c & 0x3F)); + }; + /* unicode_cpts_from_utf8's rules, the decoder the rest of the chain uses: a lead byte with + * the continuations it announces decodes (overlong forms and surrogates included), anything + * else is one U+FFFD per byte. */ + for (size_t i = 0; i < n; ) { + const uint8_t b = p[i]; + if (b < 0x80) { out += (char)b; ++i; continue; } + if (!(b & 0x40)) { put(0xFFFD); ++i; continue; } + if (!(b & 0x20)) { + if (!cont(i + 1)) { put(0xFFFD); ++i; continue; } + put(((b & 0x1F) << 6) | (p[i + 1] & 0x3F)); + i += 2; + continue; + } + if (!(b & 0x10)) { + if (!cont(i + 1) || !cont(i + 2)) { put(0xFFFD); ++i; continue; } + put(((b & 0x0F) << 12) | ((p[i + 1] & 0x3F) << 6) | (p[i + 2] & 0x3F)); + i += 3; + continue; + } + if (!(b & 0x08)) { + if (!cont(i + 1) || !cont(i + 2) || !cont(i + 3)) { put(0xFFFD); ++i; continue; } + const uint32_t c = ((b & 0x07) << 18) | ((p[i + 1] & 0x3F) << 12) | + ((p[i + 2] & 0x3F) << 6) | (p[i + 3] & 0x3F); + if (c > kMaxCp) { put(0xFFFD); ++i; continue; } + put(c); + i += 4; + continue; + } + put(0xFFFD); + ++i; + } +} + +} /* namespace rad */ diff --git a/core/text/tokenizer_regex.h b/core/text/tokenizer_regex.h new file mode 100644 index 00000000..cd653e51 --- /dev/null +++ b/core/text/tokenizer_regex.h @@ -0,0 +1,91 @@ +/* tokenizer_regex.h -- the pre-tokeniser pattern compiler. + * + * A tokenizer.json `Split` carries a regex in Oniguruma's Ruby syntax, and HuggingFace tokenizers + * runs it through Oniguruma's backtracking matcher. This compiles the same pattern into a DFA over + * codepoint classes and reproduces what that matcher reports, match for match: + * + * - Unicode properties are Oniguruma's own (tokenizer_ucd.h), so `\p{L}`, `\s`, `\w` and the + * `(?i)` orbits mean exactly what they mean there. + * - Alternation is leftmost-FIRST, not leftmost-longest: the DFA carries its NFA threads in + * priority order and a match cuts every thread below it, which is the backtracking order + * without the backtracking (the construction RE2 and regex-automata use). Greedy and lazy + * quantifiers are the same priority order read the other way. + * - Lookaround of ONE codepoint (`\s+(?!\S)`, `(?=[\p{L}])`, `(?<=x)`), `^`, `$`, `\A`, `\z`, + * `\b` and `\B` are assertions on the neighbouring codepoints. The DFA carries what it needs + * of the previous codepoint in its state and decides a lookahead on the transition that reads + * the next one, so a match is reported one transition late, when that codepoint is known. + * - find_iter reproduces Oniguruma's iteration exactly, empty matches included: a match is + * reported at the leftmost position where one exists, and an empty match at the end of the + * previous match is skipped by one codepoint, as the `onig` crate does. + * + * Anything else is REFUSED at compile time with the construct named: backreferences, atomic + * groups and possessive quantifiers, lookaround wider than one codepoint, unbounded repetition of + * something that can match empty, `(?i)` over a character that folds to several (U+00DF against + * "ss"), and properties the tables do not carry. There is no second matcher to fall back to; a + * pattern either compiles to this or the vocabulary does not load. + */ +#pragma once +#include +#include +#include +#include +#include +#include + +namespace rad { + +/* [begin, end) in bytes. */ +struct TokSpan { uint32_t begin, end; }; + +class TokRegex { +public: + ~TokRegex(); + + /* RAD_OK, or RAD_E_UNSUPPORTED with `why` saying which construct at which byte. */ + static int compile(std::string_view pattern, std::unique_ptr* out, std::string* why); + + /* Every match Oniguruma's find_iter reports over `text`, appended in order. `text` must be + * canonical UTF-8 (utf8_is_canonical); the tokeniser canonicalises before it splits. */ + void find_iter(std::string_view text, std::vector& out) const; + + /* The end of the leftmost-first match anchored at byte `pos`, or -1 when there is none. */ + int64_t match_at(std::string_view text, size_t pos) const; + + const std::string& pattern() const { return pattern_; } + size_t n_states() const; + size_t n_classes() const; + +private: + TokRegex() = default; + struct Dfa; + std::string pattern_; + std::unique_ptr dfa_; +}; + +/* HuggingFace's SplitDelimiterBehavior, in the order VocabStep::iarg carries it. */ +enum TokSplitBehavior { + TOK_SPLIT_REMOVED = 0, TOK_SPLIT_ISOLATED = 1, TOK_SPLIT_MERGED_PREV = 2, + TOK_SPLIT_MERGED_NEXT = 3, TOK_SPLIT_CONTIGUOUS = 4, +}; + +/* NormalizedString::split: the non-empty pieces of `text` that `behavior` keeps, appended to + * `out` as spans of `text`. `scratch` is reused between calls to keep the hot path free of + * allocation. */ +void tok_split(const TokRegex& re, std::string_view text, int behavior, bool invert, + std::vector& out, std::vector& scratch); + +/* NormalizedString::replace with a regex: every match replaced by `content`, verbatim. */ +void tok_replace(const TokRegex& re, std::string_view text, std::string_view content, + std::string& out); + +/* True when `s` decodes to codepoints and re-encodes to the same bytes under the tokeniser's + * decoder: no invalid or truncated sequence, no overlong form, nothing above U+10FFFF. */ +bool utf8_is_canonical(std::string_view s); + +/* Append that round trip of `s` to `out`: each byte that does not start a decodable sequence + * becomes U+FFFD, an overlong form becomes its shortest one. These are the rules of + * unicode_cpts_from_utf8, the decoder the normalisers and the other pre-tokenisers use, so a + * Split sees the same text they do. */ +void utf8_canonicalize(std::string_view s, std::string& out); + +} /* namespace rad */ diff --git a/core/text/tokenizer_ucd.cpp b/core/text/tokenizer_ucd.cpp new file mode 100644 index 00000000..df75a47e --- /dev/null +++ b/core/text/tokenizer_ucd.cpp @@ -0,0 +1,2745 @@ +/* tokenizer_ucd.cpp -- GENERATED by tools/gen_tokenizer_ucd.cpp; do not edit. + * + * Oniguruma 6.9.10, which is what HuggingFace tokenizers matches pre-tokeniser patterns + * with. See the generator for why the tables are read out of it. */ +#include "text/tokenizer_ucd.h" + +namespace rad { +namespace ucd { + +const GcRun k_gc_runs[] = { + {0x0,25}, {0x20,22}, {0x21,17}, {0x24,19}, {0x25,17}, {0x28,13}, + {0x29,14}, {0x2A,17}, {0x2B,18}, {0x2C,17}, {0x2D,12}, {0x2E,17}, + {0x30,8}, {0x3A,17}, {0x3C,18}, {0x3F,17}, {0x41,0}, {0x5B,13}, + {0x5C,17}, {0x5D,14}, {0x5E,20}, {0x5F,11}, {0x60,20}, {0x61,1}, + {0x7B,13}, {0x7C,18}, {0x7D,14}, {0x7E,18}, {0x7F,25}, {0xA0,22}, + {0xA1,17}, {0xA2,19}, {0xA6,21}, {0xA7,17}, {0xA8,20}, {0xA9,21}, + {0xAA,4}, {0xAB,15}, {0xAC,18}, {0xAD,26}, {0xAE,21}, {0xAF,20}, + {0xB0,21}, {0xB1,18}, {0xB2,10}, {0xB4,20}, {0xB5,1}, {0xB6,17}, + {0xB8,20}, {0xB9,10}, {0xBA,4}, {0xBB,16}, {0xBC,10}, {0xBF,17}, + {0xC0,0}, {0xD7,18}, {0xD8,0}, {0xDF,1}, {0xF7,18}, {0xF8,1}, + {0x100,0}, {0x101,1}, {0x102,0}, {0x103,1}, {0x104,0}, {0x105,1}, + {0x106,0}, {0x107,1}, {0x108,0}, {0x109,1}, {0x10A,0}, {0x10B,1}, + {0x10C,0}, {0x10D,1}, {0x10E,0}, {0x10F,1}, {0x110,0}, {0x111,1}, + {0x112,0}, {0x113,1}, {0x114,0}, {0x115,1}, {0x116,0}, {0x117,1}, + {0x118,0}, {0x119,1}, {0x11A,0}, {0x11B,1}, {0x11C,0}, {0x11D,1}, + {0x11E,0}, {0x11F,1}, {0x120,0}, {0x121,1}, {0x122,0}, {0x123,1}, + {0x124,0}, {0x125,1}, {0x126,0}, {0x127,1}, {0x128,0}, {0x129,1}, + {0x12A,0}, {0x12B,1}, {0x12C,0}, {0x12D,1}, {0x12E,0}, {0x12F,1}, + {0x130,0}, {0x131,1}, {0x132,0}, {0x133,1}, {0x134,0}, {0x135,1}, + {0x136,0}, {0x137,1}, {0x139,0}, {0x13A,1}, {0x13B,0}, {0x13C,1}, + {0x13D,0}, {0x13E,1}, {0x13F,0}, {0x140,1}, {0x141,0}, {0x142,1}, + {0x143,0}, {0x144,1}, {0x145,0}, {0x146,1}, {0x147,0}, {0x148,1}, + {0x14A,0}, {0x14B,1}, {0x14C,0}, {0x14D,1}, {0x14E,0}, {0x14F,1}, + {0x150,0}, {0x151,1}, {0x152,0}, {0x153,1}, {0x154,0}, {0x155,1}, + {0x156,0}, {0x157,1}, {0x158,0}, {0x159,1}, {0x15A,0}, {0x15B,1}, + {0x15C,0}, {0x15D,1}, {0x15E,0}, {0x15F,1}, {0x160,0}, {0x161,1}, + {0x162,0}, {0x163,1}, {0x164,0}, {0x165,1}, {0x166,0}, {0x167,1}, + {0x168,0}, {0x169,1}, {0x16A,0}, {0x16B,1}, {0x16C,0}, {0x16D,1}, + {0x16E,0}, {0x16F,1}, {0x170,0}, {0x171,1}, {0x172,0}, {0x173,1}, + {0x174,0}, {0x175,1}, {0x176,0}, {0x177,1}, {0x178,0}, {0x17A,1}, + {0x17B,0}, {0x17C,1}, {0x17D,0}, {0x17E,1}, {0x181,0}, {0x183,1}, + {0x184,0}, {0x185,1}, {0x186,0}, {0x188,1}, {0x189,0}, {0x18C,1}, + {0x18E,0}, {0x192,1}, {0x193,0}, {0x195,1}, {0x196,0}, {0x199,1}, + {0x19C,0}, {0x19E,1}, {0x19F,0}, {0x1A1,1}, {0x1A2,0}, {0x1A3,1}, + {0x1A4,0}, {0x1A5,1}, {0x1A6,0}, {0x1A8,1}, {0x1A9,0}, {0x1AA,1}, + {0x1AC,0}, {0x1AD,1}, {0x1AE,0}, {0x1B0,1}, {0x1B1,0}, {0x1B4,1}, + {0x1B5,0}, {0x1B6,1}, {0x1B7,0}, {0x1B9,1}, {0x1BB,4}, {0x1BC,0}, + {0x1BD,1}, {0x1C0,4}, {0x1C4,0}, {0x1C5,2}, {0x1C6,1}, {0x1C7,0}, + {0x1C8,2}, {0x1C9,1}, {0x1CA,0}, {0x1CB,2}, {0x1CC,1}, {0x1CD,0}, + {0x1CE,1}, {0x1CF,0}, {0x1D0,1}, {0x1D1,0}, {0x1D2,1}, {0x1D3,0}, + {0x1D4,1}, {0x1D5,0}, {0x1D6,1}, {0x1D7,0}, {0x1D8,1}, {0x1D9,0}, + {0x1DA,1}, {0x1DB,0}, {0x1DC,1}, {0x1DE,0}, {0x1DF,1}, {0x1E0,0}, + {0x1E1,1}, {0x1E2,0}, {0x1E3,1}, {0x1E4,0}, {0x1E5,1}, {0x1E6,0}, + {0x1E7,1}, {0x1E8,0}, {0x1E9,1}, {0x1EA,0}, {0x1EB,1}, {0x1EC,0}, + {0x1ED,1}, {0x1EE,0}, {0x1EF,1}, {0x1F1,0}, {0x1F2,2}, {0x1F3,1}, + {0x1F4,0}, {0x1F5,1}, {0x1F6,0}, {0x1F9,1}, {0x1FA,0}, {0x1FB,1}, + {0x1FC,0}, {0x1FD,1}, {0x1FE,0}, {0x1FF,1}, {0x200,0}, {0x201,1}, + {0x202,0}, {0x203,1}, {0x204,0}, {0x205,1}, {0x206,0}, {0x207,1}, + {0x208,0}, {0x209,1}, {0x20A,0}, {0x20B,1}, {0x20C,0}, {0x20D,1}, + {0x20E,0}, {0x20F,1}, {0x210,0}, {0x211,1}, {0x212,0}, {0x213,1}, + {0x214,0}, {0x215,1}, {0x216,0}, {0x217,1}, {0x218,0}, {0x219,1}, + {0x21A,0}, {0x21B,1}, {0x21C,0}, {0x21D,1}, {0x21E,0}, {0x21F,1}, + {0x220,0}, {0x221,1}, {0x222,0}, {0x223,1}, {0x224,0}, {0x225,1}, + {0x226,0}, {0x227,1}, {0x228,0}, {0x229,1}, {0x22A,0}, {0x22B,1}, + {0x22C,0}, {0x22D,1}, {0x22E,0}, {0x22F,1}, {0x230,0}, {0x231,1}, + {0x232,0}, {0x233,1}, {0x23A,0}, {0x23C,1}, {0x23D,0}, {0x23F,1}, + {0x241,0}, {0x242,1}, {0x243,0}, {0x247,1}, {0x248,0}, {0x249,1}, + {0x24A,0}, {0x24B,1}, {0x24C,0}, {0x24D,1}, {0x24E,0}, {0x24F,1}, + {0x294,4}, {0x295,1}, {0x2B0,3}, {0x2C2,20}, {0x2C6,3}, {0x2D2,20}, + {0x2E0,3}, {0x2E5,20}, {0x2EC,3}, {0x2ED,20}, {0x2EE,3}, {0x2EF,20}, + {0x300,5}, {0x370,0}, {0x371,1}, {0x372,0}, {0x373,1}, {0x374,3}, + {0x375,20}, {0x376,0}, {0x377,1}, {0x378,29}, {0x37A,3}, {0x37B,1}, + {0x37E,17}, {0x37F,0}, {0x380,29}, {0x384,20}, {0x386,0}, {0x387,17}, + {0x388,0}, {0x38B,29}, {0x38C,0}, {0x38D,29}, {0x38E,0}, {0x390,1}, + {0x391,0}, {0x3A2,29}, {0x3A3,0}, {0x3AC,1}, {0x3CF,0}, {0x3D0,1}, + {0x3D2,0}, {0x3D5,1}, {0x3D8,0}, {0x3D9,1}, {0x3DA,0}, {0x3DB,1}, + {0x3DC,0}, {0x3DD,1}, {0x3DE,0}, {0x3DF,1}, {0x3E0,0}, {0x3E1,1}, + {0x3E2,0}, {0x3E3,1}, {0x3E4,0}, {0x3E5,1}, {0x3E6,0}, {0x3E7,1}, + {0x3E8,0}, {0x3E9,1}, {0x3EA,0}, {0x3EB,1}, {0x3EC,0}, {0x3ED,1}, + {0x3EE,0}, {0x3EF,1}, {0x3F4,0}, {0x3F5,1}, {0x3F6,18}, {0x3F7,0}, + {0x3F8,1}, {0x3F9,0}, {0x3FB,1}, {0x3FD,0}, {0x430,1}, {0x460,0}, + {0x461,1}, {0x462,0}, {0x463,1}, {0x464,0}, {0x465,1}, {0x466,0}, + {0x467,1}, {0x468,0}, {0x469,1}, {0x46A,0}, {0x46B,1}, {0x46C,0}, + {0x46D,1}, {0x46E,0}, {0x46F,1}, {0x470,0}, {0x471,1}, {0x472,0}, + {0x473,1}, {0x474,0}, {0x475,1}, {0x476,0}, {0x477,1}, {0x478,0}, + {0x479,1}, {0x47A,0}, {0x47B,1}, {0x47C,0}, {0x47D,1}, {0x47E,0}, + {0x47F,1}, {0x480,0}, {0x481,1}, {0x482,21}, {0x483,5}, {0x488,7}, + {0x48A,0}, {0x48B,1}, {0x48C,0}, {0x48D,1}, {0x48E,0}, {0x48F,1}, + {0x490,0}, {0x491,1}, {0x492,0}, {0x493,1}, {0x494,0}, {0x495,1}, + {0x496,0}, {0x497,1}, {0x498,0}, {0x499,1}, {0x49A,0}, {0x49B,1}, + {0x49C,0}, {0x49D,1}, {0x49E,0}, {0x49F,1}, {0x4A0,0}, {0x4A1,1}, + {0x4A2,0}, {0x4A3,1}, {0x4A4,0}, {0x4A5,1}, {0x4A6,0}, {0x4A7,1}, + {0x4A8,0}, {0x4A9,1}, {0x4AA,0}, {0x4AB,1}, {0x4AC,0}, {0x4AD,1}, + {0x4AE,0}, {0x4AF,1}, {0x4B0,0}, {0x4B1,1}, {0x4B2,0}, {0x4B3,1}, + {0x4B4,0}, {0x4B5,1}, {0x4B6,0}, {0x4B7,1}, {0x4B8,0}, {0x4B9,1}, + {0x4BA,0}, {0x4BB,1}, {0x4BC,0}, {0x4BD,1}, {0x4BE,0}, {0x4BF,1}, + {0x4C0,0}, {0x4C2,1}, {0x4C3,0}, {0x4C4,1}, {0x4C5,0}, {0x4C6,1}, + {0x4C7,0}, {0x4C8,1}, {0x4C9,0}, {0x4CA,1}, {0x4CB,0}, {0x4CC,1}, + {0x4CD,0}, {0x4CE,1}, {0x4D0,0}, {0x4D1,1}, {0x4D2,0}, {0x4D3,1}, + {0x4D4,0}, {0x4D5,1}, {0x4D6,0}, {0x4D7,1}, {0x4D8,0}, {0x4D9,1}, + {0x4DA,0}, {0x4DB,1}, {0x4DC,0}, {0x4DD,1}, {0x4DE,0}, {0x4DF,1}, + {0x4E0,0}, {0x4E1,1}, {0x4E2,0}, {0x4E3,1}, {0x4E4,0}, {0x4E5,1}, + {0x4E6,0}, {0x4E7,1}, {0x4E8,0}, {0x4E9,1}, {0x4EA,0}, {0x4EB,1}, + {0x4EC,0}, {0x4ED,1}, {0x4EE,0}, {0x4EF,1}, {0x4F0,0}, {0x4F1,1}, + {0x4F2,0}, {0x4F3,1}, {0x4F4,0}, {0x4F5,1}, {0x4F6,0}, {0x4F7,1}, + {0x4F8,0}, {0x4F9,1}, {0x4FA,0}, {0x4FB,1}, {0x4FC,0}, {0x4FD,1}, + {0x4FE,0}, {0x4FF,1}, {0x500,0}, {0x501,1}, {0x502,0}, {0x503,1}, + {0x504,0}, {0x505,1}, {0x506,0}, {0x507,1}, {0x508,0}, {0x509,1}, + {0x50A,0}, {0x50B,1}, {0x50C,0}, {0x50D,1}, {0x50E,0}, {0x50F,1}, + {0x510,0}, {0x511,1}, {0x512,0}, {0x513,1}, {0x514,0}, {0x515,1}, + {0x516,0}, {0x517,1}, {0x518,0}, {0x519,1}, {0x51A,0}, {0x51B,1}, + {0x51C,0}, {0x51D,1}, {0x51E,0}, {0x51F,1}, {0x520,0}, {0x521,1}, + {0x522,0}, {0x523,1}, {0x524,0}, {0x525,1}, {0x526,0}, {0x527,1}, + {0x528,0}, {0x529,1}, {0x52A,0}, {0x52B,1}, {0x52C,0}, {0x52D,1}, + {0x52E,0}, {0x52F,1}, {0x530,29}, {0x531,0}, {0x557,29}, {0x559,3}, + {0x55A,17}, {0x560,1}, {0x589,17}, {0x58A,12}, {0x58B,29}, {0x58D,21}, + {0x58F,19}, {0x590,29}, {0x591,5}, {0x5BE,12}, {0x5BF,5}, {0x5C0,17}, + {0x5C1,5}, {0x5C3,17}, {0x5C4,5}, {0x5C6,17}, {0x5C7,5}, {0x5C8,29}, + {0x5D0,4}, {0x5EB,29}, {0x5EF,4}, {0x5F3,17}, {0x5F5,29}, {0x600,26}, + {0x606,18}, {0x609,17}, {0x60B,19}, {0x60C,17}, {0x60E,21}, {0x610,5}, + {0x61B,17}, {0x61C,26}, {0x61D,17}, {0x620,4}, {0x640,3}, {0x641,4}, + {0x64B,5}, {0x660,8}, {0x66A,17}, {0x66E,4}, {0x670,5}, {0x671,4}, + {0x6D4,17}, {0x6D5,4}, {0x6D6,5}, {0x6DD,26}, {0x6DE,21}, {0x6DF,5}, + {0x6E5,3}, {0x6E7,5}, {0x6E9,21}, {0x6EA,5}, {0x6EE,4}, {0x6F0,8}, + {0x6FA,4}, {0x6FD,21}, {0x6FF,4}, {0x700,17}, {0x70E,29}, {0x70F,26}, + {0x710,4}, {0x711,5}, {0x712,4}, {0x730,5}, {0x74B,29}, {0x74D,4}, + {0x7A6,5}, {0x7B1,4}, {0x7B2,29}, {0x7C0,8}, {0x7CA,4}, {0x7EB,5}, + {0x7F4,3}, {0x7F6,21}, {0x7F7,17}, {0x7FA,3}, {0x7FB,29}, {0x7FD,5}, + {0x7FE,19}, {0x800,4}, {0x816,5}, {0x81A,3}, {0x81B,5}, {0x824,3}, + {0x825,5}, {0x828,3}, {0x829,5}, {0x82E,29}, {0x830,17}, {0x83F,29}, + {0x840,4}, {0x859,5}, {0x85C,29}, {0x85E,17}, {0x85F,29}, {0x860,4}, + {0x86B,29}, {0x870,4}, {0x888,20}, {0x889,4}, {0x88F,29}, {0x890,26}, + {0x892,29}, {0x897,5}, {0x8A0,4}, {0x8C9,3}, {0x8CA,5}, {0x8E2,26}, + {0x8E3,5}, {0x903,6}, {0x904,4}, {0x93A,5}, {0x93B,6}, {0x93C,5}, + {0x93D,4}, {0x93E,6}, {0x941,5}, {0x949,6}, {0x94D,5}, {0x94E,6}, + {0x950,4}, {0x951,5}, {0x958,4}, {0x962,5}, {0x964,17}, {0x966,8}, + {0x970,17}, {0x971,3}, {0x972,4}, {0x981,5}, {0x982,6}, {0x984,29}, + {0x985,4}, {0x98D,29}, {0x98F,4}, {0x991,29}, {0x993,4}, {0x9A9,29}, + {0x9AA,4}, {0x9B1,29}, {0x9B2,4}, {0x9B3,29}, {0x9B6,4}, {0x9BA,29}, + {0x9BC,5}, {0x9BD,4}, {0x9BE,6}, {0x9C1,5}, {0x9C5,29}, {0x9C7,6}, + {0x9C9,29}, {0x9CB,6}, {0x9CD,5}, {0x9CE,4}, {0x9CF,29}, {0x9D7,6}, + {0x9D8,29}, {0x9DC,4}, {0x9DE,29}, {0x9DF,4}, {0x9E2,5}, {0x9E4,29}, + {0x9E6,8}, {0x9F0,4}, {0x9F2,19}, {0x9F4,10}, {0x9FA,21}, {0x9FB,19}, + {0x9FC,4}, {0x9FD,17}, {0x9FE,5}, {0x9FF,29}, {0xA01,5}, {0xA03,6}, + {0xA04,29}, {0xA05,4}, {0xA0B,29}, {0xA0F,4}, {0xA11,29}, {0xA13,4}, + {0xA29,29}, {0xA2A,4}, {0xA31,29}, {0xA32,4}, {0xA34,29}, {0xA35,4}, + {0xA37,29}, {0xA38,4}, {0xA3A,29}, {0xA3C,5}, {0xA3D,29}, {0xA3E,6}, + {0xA41,5}, {0xA43,29}, {0xA47,5}, {0xA49,29}, {0xA4B,5}, {0xA4E,29}, + {0xA51,5}, {0xA52,29}, {0xA59,4}, {0xA5D,29}, {0xA5E,4}, {0xA5F,29}, + {0xA66,8}, {0xA70,5}, {0xA72,4}, {0xA75,5}, {0xA76,17}, {0xA77,29}, + {0xA81,5}, {0xA83,6}, {0xA84,29}, {0xA85,4}, {0xA8E,29}, {0xA8F,4}, + {0xA92,29}, {0xA93,4}, {0xAA9,29}, {0xAAA,4}, {0xAB1,29}, {0xAB2,4}, + {0xAB4,29}, {0xAB5,4}, {0xABA,29}, {0xABC,5}, {0xABD,4}, {0xABE,6}, + {0xAC1,5}, {0xAC6,29}, {0xAC7,5}, {0xAC9,6}, {0xACA,29}, {0xACB,6}, + {0xACD,5}, {0xACE,29}, {0xAD0,4}, {0xAD1,29}, {0xAE0,4}, {0xAE2,5}, + {0xAE4,29}, {0xAE6,8}, {0xAF0,17}, {0xAF1,19}, {0xAF2,29}, {0xAF9,4}, + {0xAFA,5}, {0xB00,29}, {0xB01,5}, {0xB02,6}, {0xB04,29}, {0xB05,4}, + {0xB0D,29}, {0xB0F,4}, {0xB11,29}, {0xB13,4}, {0xB29,29}, {0xB2A,4}, + {0xB31,29}, {0xB32,4}, {0xB34,29}, {0xB35,4}, {0xB3A,29}, {0xB3C,5}, + {0xB3D,4}, {0xB3E,6}, {0xB3F,5}, {0xB40,6}, {0xB41,5}, {0xB45,29}, + {0xB47,6}, {0xB49,29}, {0xB4B,6}, {0xB4D,5}, {0xB4E,29}, {0xB55,5}, + {0xB57,6}, {0xB58,29}, {0xB5C,4}, {0xB5E,29}, {0xB5F,4}, {0xB62,5}, + {0xB64,29}, {0xB66,8}, {0xB70,21}, {0xB71,4}, {0xB72,10}, {0xB78,29}, + {0xB82,5}, {0xB83,4}, {0xB84,29}, {0xB85,4}, {0xB8B,29}, {0xB8E,4}, + {0xB91,29}, {0xB92,4}, {0xB96,29}, {0xB99,4}, {0xB9B,29}, {0xB9C,4}, + {0xB9D,29}, {0xB9E,4}, {0xBA0,29}, {0xBA3,4}, {0xBA5,29}, {0xBA8,4}, + {0xBAB,29}, {0xBAE,4}, {0xBBA,29}, {0xBBE,6}, {0xBC0,5}, {0xBC1,6}, + {0xBC3,29}, {0xBC6,6}, {0xBC9,29}, {0xBCA,6}, {0xBCD,5}, {0xBCE,29}, + {0xBD0,4}, {0xBD1,29}, {0xBD7,6}, {0xBD8,29}, {0xBE6,8}, {0xBF0,10}, + {0xBF3,21}, {0xBF9,19}, {0xBFA,21}, {0xBFB,29}, {0xC00,5}, {0xC01,6}, + {0xC04,5}, {0xC05,4}, {0xC0D,29}, {0xC0E,4}, {0xC11,29}, {0xC12,4}, + {0xC29,29}, {0xC2A,4}, {0xC3A,29}, {0xC3C,5}, {0xC3D,4}, {0xC3E,5}, + {0xC41,6}, {0xC45,29}, {0xC46,5}, {0xC49,29}, {0xC4A,5}, {0xC4E,29}, + {0xC55,5}, {0xC57,29}, {0xC58,4}, {0xC5B,29}, {0xC5D,4}, {0xC5E,29}, + {0xC60,4}, {0xC62,5}, {0xC64,29}, {0xC66,8}, {0xC70,29}, {0xC77,17}, + {0xC78,10}, {0xC7F,21}, {0xC80,4}, {0xC81,5}, {0xC82,6}, {0xC84,17}, + {0xC85,4}, {0xC8D,29}, {0xC8E,4}, {0xC91,29}, {0xC92,4}, {0xCA9,29}, + {0xCAA,4}, {0xCB4,29}, {0xCB5,4}, {0xCBA,29}, {0xCBC,5}, {0xCBD,4}, + {0xCBE,6}, {0xCBF,5}, {0xCC0,6}, {0xCC5,29}, {0xCC6,5}, {0xCC7,6}, + {0xCC9,29}, {0xCCA,6}, {0xCCC,5}, {0xCCE,29}, {0xCD5,6}, {0xCD7,29}, + {0xCDD,4}, {0xCDF,29}, {0xCE0,4}, {0xCE2,5}, {0xCE4,29}, {0xCE6,8}, + {0xCF0,29}, {0xCF1,4}, {0xCF3,6}, {0xCF4,29}, {0xD00,5}, {0xD02,6}, + {0xD04,4}, {0xD0D,29}, {0xD0E,4}, {0xD11,29}, {0xD12,4}, {0xD3B,5}, + {0xD3D,4}, {0xD3E,6}, {0xD41,5}, {0xD45,29}, {0xD46,6}, {0xD49,29}, + {0xD4A,6}, {0xD4D,5}, {0xD4E,4}, {0xD4F,21}, {0xD50,29}, {0xD54,4}, + {0xD57,6}, {0xD58,10}, {0xD5F,4}, {0xD62,5}, {0xD64,29}, {0xD66,8}, + {0xD70,10}, {0xD79,21}, {0xD7A,4}, {0xD80,29}, {0xD81,5}, {0xD82,6}, + {0xD84,29}, {0xD85,4}, {0xD97,29}, {0xD9A,4}, {0xDB2,29}, {0xDB3,4}, + {0xDBC,29}, {0xDBD,4}, {0xDBE,29}, {0xDC0,4}, {0xDC7,29}, {0xDCA,5}, + {0xDCB,29}, {0xDCF,6}, {0xDD2,5}, {0xDD5,29}, {0xDD6,5}, {0xDD7,29}, + {0xDD8,6}, {0xDE0,29}, {0xDE6,8}, {0xDF0,29}, {0xDF2,6}, {0xDF4,17}, + {0xDF5,29}, {0xE01,4}, {0xE31,5}, {0xE32,4}, {0xE34,5}, {0xE3B,29}, + {0xE3F,19}, {0xE40,4}, {0xE46,3}, {0xE47,5}, {0xE4F,17}, {0xE50,8}, + {0xE5A,17}, {0xE5C,29}, {0xE81,4}, {0xE83,29}, {0xE84,4}, {0xE85,29}, + {0xE86,4}, {0xE8B,29}, {0xE8C,4}, {0xEA4,29}, {0xEA5,4}, {0xEA6,29}, + {0xEA7,4}, {0xEB1,5}, {0xEB2,4}, {0xEB4,5}, {0xEBD,4}, {0xEBE,29}, + {0xEC0,4}, {0xEC5,29}, {0xEC6,3}, {0xEC7,29}, {0xEC8,5}, {0xECF,29}, + {0xED0,8}, {0xEDA,29}, {0xEDC,4}, {0xEE0,29}, {0xF00,4}, {0xF01,21}, + {0xF04,17}, {0xF13,21}, {0xF14,17}, {0xF15,21}, {0xF18,5}, {0xF1A,21}, + {0xF20,8}, {0xF2A,10}, {0xF34,21}, {0xF35,5}, {0xF36,21}, {0xF37,5}, + {0xF38,21}, {0xF39,5}, {0xF3A,13}, {0xF3B,14}, {0xF3C,13}, {0xF3D,14}, + {0xF3E,6}, {0xF40,4}, {0xF48,29}, {0xF49,4}, {0xF6D,29}, {0xF71,5}, + {0xF7F,6}, {0xF80,5}, {0xF85,17}, {0xF86,5}, {0xF88,4}, {0xF8D,5}, + {0xF98,29}, {0xF99,5}, {0xFBD,29}, {0xFBE,21}, {0xFC6,5}, {0xFC7,21}, + {0xFCD,29}, {0xFCE,21}, {0xFD0,17}, {0xFD5,21}, {0xFD9,17}, {0xFDB,29}, + {0x1000,4}, {0x102B,6}, {0x102D,5}, {0x1031,6}, {0x1032,5}, {0x1038,6}, + {0x1039,5}, {0x103B,6}, {0x103D,5}, {0x103F,4}, {0x1040,8}, {0x104A,17}, + {0x1050,4}, {0x1056,6}, {0x1058,5}, {0x105A,4}, {0x105E,5}, {0x1061,4}, + {0x1062,6}, {0x1065,4}, {0x1067,6}, {0x106E,4}, {0x1071,5}, {0x1075,4}, + {0x1082,5}, {0x1083,6}, {0x1085,5}, {0x1087,6}, {0x108D,5}, {0x108E,4}, + {0x108F,6}, {0x1090,8}, {0x109A,6}, {0x109D,5}, {0x109E,21}, {0x10A0,0}, + {0x10C6,29}, {0x10C7,0}, {0x10C8,29}, {0x10CD,0}, {0x10CE,29}, {0x10D0,1}, + {0x10FB,17}, {0x10FC,3}, {0x10FD,1}, {0x1100,4}, {0x1249,29}, {0x124A,4}, + {0x124E,29}, {0x1250,4}, {0x1257,29}, {0x1258,4}, {0x1259,29}, {0x125A,4}, + {0x125E,29}, {0x1260,4}, {0x1289,29}, {0x128A,4}, {0x128E,29}, {0x1290,4}, + {0x12B1,29}, {0x12B2,4}, {0x12B6,29}, {0x12B8,4}, {0x12BF,29}, {0x12C0,4}, + {0x12C1,29}, {0x12C2,4}, {0x12C6,29}, {0x12C8,4}, {0x12D7,29}, {0x12D8,4}, + {0x1311,29}, {0x1312,4}, {0x1316,29}, {0x1318,4}, {0x135B,29}, {0x135D,5}, + {0x1360,17}, {0x1369,10}, {0x137D,29}, {0x1380,4}, {0x1390,21}, {0x139A,29}, + {0x13A0,0}, {0x13F6,29}, {0x13F8,1}, {0x13FE,29}, {0x1400,12}, {0x1401,4}, + {0x166D,21}, {0x166E,17}, {0x166F,4}, {0x1680,22}, {0x1681,4}, {0x169B,13}, + {0x169C,14}, {0x169D,29}, {0x16A0,4}, {0x16EB,17}, {0x16EE,9}, {0x16F1,4}, + {0x16F9,29}, {0x1700,4}, {0x1712,5}, {0x1715,6}, {0x1716,29}, {0x171F,4}, + {0x1732,5}, {0x1734,6}, {0x1735,17}, {0x1737,29}, {0x1740,4}, {0x1752,5}, + {0x1754,29}, {0x1760,4}, {0x176D,29}, {0x176E,4}, {0x1771,29}, {0x1772,5}, + {0x1774,29}, {0x1780,4}, {0x17B4,5}, {0x17B6,6}, {0x17B7,5}, {0x17BE,6}, + {0x17C6,5}, {0x17C7,6}, {0x17C9,5}, {0x17D4,17}, {0x17D7,3}, {0x17D8,17}, + {0x17DB,19}, {0x17DC,4}, {0x17DD,5}, {0x17DE,29}, {0x17E0,8}, {0x17EA,29}, + {0x17F0,10}, {0x17FA,29}, {0x1800,17}, {0x1806,12}, {0x1807,17}, {0x180B,5}, + {0x180E,26}, {0x180F,5}, {0x1810,8}, {0x181A,29}, {0x1820,4}, {0x1843,3}, + {0x1844,4}, {0x1879,29}, {0x1880,4}, {0x1885,5}, {0x1887,4}, {0x18A9,5}, + {0x18AA,4}, {0x18AB,29}, {0x18B0,4}, {0x18F6,29}, {0x1900,4}, {0x191F,29}, + {0x1920,5}, {0x1923,6}, {0x1927,5}, {0x1929,6}, {0x192C,29}, {0x1930,6}, + {0x1932,5}, {0x1933,6}, {0x1939,5}, {0x193C,29}, {0x1940,21}, {0x1941,29}, + {0x1944,17}, {0x1946,8}, {0x1950,4}, {0x196E,29}, {0x1970,4}, {0x1975,29}, + {0x1980,4}, {0x19AC,29}, {0x19B0,4}, {0x19CA,29}, {0x19D0,8}, {0x19DA,10}, + {0x19DB,29}, {0x19DE,21}, {0x1A00,4}, {0x1A17,5}, {0x1A19,6}, {0x1A1B,5}, + {0x1A1C,29}, {0x1A1E,17}, {0x1A20,4}, {0x1A55,6}, {0x1A56,5}, {0x1A57,6}, + {0x1A58,5}, {0x1A5F,29}, {0x1A60,5}, {0x1A61,6}, {0x1A62,5}, {0x1A63,6}, + {0x1A65,5}, {0x1A6D,6}, {0x1A73,5}, {0x1A7D,29}, {0x1A7F,5}, {0x1A80,8}, + {0x1A8A,29}, {0x1A90,8}, {0x1A9A,29}, {0x1AA0,17}, {0x1AA7,3}, {0x1AA8,17}, + {0x1AAE,29}, {0x1AB0,5}, {0x1ABE,7}, {0x1ABF,5}, {0x1ACF,29}, {0x1B00,5}, + {0x1B04,6}, {0x1B05,4}, {0x1B34,5}, {0x1B35,6}, {0x1B36,5}, {0x1B3B,6}, + {0x1B3C,5}, {0x1B3D,6}, {0x1B42,5}, {0x1B43,6}, {0x1B45,4}, {0x1B4D,29}, + {0x1B4E,17}, {0x1B50,8}, {0x1B5A,17}, {0x1B61,21}, {0x1B6B,5}, {0x1B74,21}, + {0x1B7D,17}, {0x1B80,5}, {0x1B82,6}, {0x1B83,4}, {0x1BA1,6}, {0x1BA2,5}, + {0x1BA6,6}, {0x1BA8,5}, {0x1BAA,6}, {0x1BAB,5}, {0x1BAE,4}, {0x1BB0,8}, + {0x1BBA,4}, {0x1BE6,5}, {0x1BE7,6}, {0x1BE8,5}, {0x1BEA,6}, {0x1BED,5}, + {0x1BEE,6}, {0x1BEF,5}, {0x1BF2,6}, {0x1BF4,29}, {0x1BFC,17}, {0x1C00,4}, + {0x1C24,6}, {0x1C2C,5}, {0x1C34,6}, {0x1C36,5}, {0x1C38,29}, {0x1C3B,17}, + {0x1C40,8}, {0x1C4A,29}, {0x1C4D,4}, {0x1C50,8}, {0x1C5A,4}, {0x1C78,3}, + {0x1C7E,17}, {0x1C80,1}, {0x1C89,0}, {0x1C8A,1}, {0x1C8B,29}, {0x1C90,0}, + {0x1CBB,29}, {0x1CBD,0}, {0x1CC0,17}, {0x1CC8,29}, {0x1CD0,5}, {0x1CD3,17}, + {0x1CD4,5}, {0x1CE1,6}, {0x1CE2,5}, {0x1CE9,4}, {0x1CED,5}, {0x1CEE,4}, + {0x1CF4,5}, {0x1CF5,4}, {0x1CF7,6}, {0x1CF8,5}, {0x1CFA,4}, {0x1CFB,29}, + {0x1D00,1}, {0x1D2C,3}, {0x1D6B,1}, {0x1D78,3}, {0x1D79,1}, {0x1D9B,3}, + {0x1DC0,5}, {0x1E00,0}, {0x1E01,1}, {0x1E02,0}, {0x1E03,1}, {0x1E04,0}, + {0x1E05,1}, {0x1E06,0}, {0x1E07,1}, {0x1E08,0}, {0x1E09,1}, {0x1E0A,0}, + {0x1E0B,1}, {0x1E0C,0}, {0x1E0D,1}, {0x1E0E,0}, {0x1E0F,1}, {0x1E10,0}, + {0x1E11,1}, {0x1E12,0}, {0x1E13,1}, {0x1E14,0}, {0x1E15,1}, {0x1E16,0}, + {0x1E17,1}, {0x1E18,0}, {0x1E19,1}, {0x1E1A,0}, {0x1E1B,1}, {0x1E1C,0}, + {0x1E1D,1}, {0x1E1E,0}, {0x1E1F,1}, {0x1E20,0}, {0x1E21,1}, {0x1E22,0}, + {0x1E23,1}, {0x1E24,0}, {0x1E25,1}, {0x1E26,0}, {0x1E27,1}, {0x1E28,0}, + {0x1E29,1}, {0x1E2A,0}, {0x1E2B,1}, {0x1E2C,0}, {0x1E2D,1}, {0x1E2E,0}, + {0x1E2F,1}, {0x1E30,0}, {0x1E31,1}, {0x1E32,0}, {0x1E33,1}, {0x1E34,0}, + {0x1E35,1}, {0x1E36,0}, {0x1E37,1}, {0x1E38,0}, {0x1E39,1}, {0x1E3A,0}, + {0x1E3B,1}, {0x1E3C,0}, {0x1E3D,1}, {0x1E3E,0}, {0x1E3F,1}, {0x1E40,0}, + {0x1E41,1}, {0x1E42,0}, {0x1E43,1}, {0x1E44,0}, {0x1E45,1}, {0x1E46,0}, + {0x1E47,1}, {0x1E48,0}, {0x1E49,1}, {0x1E4A,0}, {0x1E4B,1}, {0x1E4C,0}, + {0x1E4D,1}, {0x1E4E,0}, {0x1E4F,1}, {0x1E50,0}, {0x1E51,1}, {0x1E52,0}, + {0x1E53,1}, {0x1E54,0}, {0x1E55,1}, {0x1E56,0}, {0x1E57,1}, {0x1E58,0}, + {0x1E59,1}, {0x1E5A,0}, {0x1E5B,1}, {0x1E5C,0}, {0x1E5D,1}, {0x1E5E,0}, + {0x1E5F,1}, {0x1E60,0}, {0x1E61,1}, {0x1E62,0}, {0x1E63,1}, {0x1E64,0}, + {0x1E65,1}, {0x1E66,0}, {0x1E67,1}, {0x1E68,0}, {0x1E69,1}, {0x1E6A,0}, + {0x1E6B,1}, {0x1E6C,0}, {0x1E6D,1}, {0x1E6E,0}, {0x1E6F,1}, {0x1E70,0}, + {0x1E71,1}, {0x1E72,0}, {0x1E73,1}, {0x1E74,0}, {0x1E75,1}, {0x1E76,0}, + {0x1E77,1}, {0x1E78,0}, {0x1E79,1}, {0x1E7A,0}, {0x1E7B,1}, {0x1E7C,0}, + {0x1E7D,1}, {0x1E7E,0}, {0x1E7F,1}, {0x1E80,0}, {0x1E81,1}, {0x1E82,0}, + {0x1E83,1}, {0x1E84,0}, {0x1E85,1}, {0x1E86,0}, {0x1E87,1}, {0x1E88,0}, + {0x1E89,1}, {0x1E8A,0}, {0x1E8B,1}, {0x1E8C,0}, {0x1E8D,1}, {0x1E8E,0}, + {0x1E8F,1}, {0x1E90,0}, {0x1E91,1}, {0x1E92,0}, {0x1E93,1}, {0x1E94,0}, + {0x1E95,1}, {0x1E9E,0}, {0x1E9F,1}, {0x1EA0,0}, {0x1EA1,1}, {0x1EA2,0}, + {0x1EA3,1}, {0x1EA4,0}, {0x1EA5,1}, {0x1EA6,0}, {0x1EA7,1}, {0x1EA8,0}, + {0x1EA9,1}, {0x1EAA,0}, {0x1EAB,1}, {0x1EAC,0}, {0x1EAD,1}, {0x1EAE,0}, + {0x1EAF,1}, {0x1EB0,0}, {0x1EB1,1}, {0x1EB2,0}, {0x1EB3,1}, {0x1EB4,0}, + {0x1EB5,1}, {0x1EB6,0}, {0x1EB7,1}, {0x1EB8,0}, {0x1EB9,1}, {0x1EBA,0}, + {0x1EBB,1}, {0x1EBC,0}, {0x1EBD,1}, {0x1EBE,0}, {0x1EBF,1}, {0x1EC0,0}, + {0x1EC1,1}, {0x1EC2,0}, {0x1EC3,1}, {0x1EC4,0}, {0x1EC5,1}, {0x1EC6,0}, + {0x1EC7,1}, {0x1EC8,0}, {0x1EC9,1}, {0x1ECA,0}, {0x1ECB,1}, {0x1ECC,0}, + {0x1ECD,1}, {0x1ECE,0}, {0x1ECF,1}, {0x1ED0,0}, {0x1ED1,1}, {0x1ED2,0}, + {0x1ED3,1}, {0x1ED4,0}, {0x1ED5,1}, {0x1ED6,0}, {0x1ED7,1}, {0x1ED8,0}, + {0x1ED9,1}, {0x1EDA,0}, {0x1EDB,1}, {0x1EDC,0}, {0x1EDD,1}, {0x1EDE,0}, + {0x1EDF,1}, {0x1EE0,0}, {0x1EE1,1}, {0x1EE2,0}, {0x1EE3,1}, {0x1EE4,0}, + {0x1EE5,1}, {0x1EE6,0}, {0x1EE7,1}, {0x1EE8,0}, {0x1EE9,1}, {0x1EEA,0}, + {0x1EEB,1}, {0x1EEC,0}, {0x1EED,1}, {0x1EEE,0}, {0x1EEF,1}, {0x1EF0,0}, + {0x1EF1,1}, {0x1EF2,0}, {0x1EF3,1}, {0x1EF4,0}, {0x1EF5,1}, {0x1EF6,0}, + {0x1EF7,1}, {0x1EF8,0}, {0x1EF9,1}, {0x1EFA,0}, {0x1EFB,1}, {0x1EFC,0}, + {0x1EFD,1}, {0x1EFE,0}, {0x1EFF,1}, {0x1F08,0}, {0x1F10,1}, {0x1F16,29}, + {0x1F18,0}, {0x1F1E,29}, {0x1F20,1}, {0x1F28,0}, {0x1F30,1}, {0x1F38,0}, + {0x1F40,1}, {0x1F46,29}, {0x1F48,0}, {0x1F4E,29}, {0x1F50,1}, {0x1F58,29}, + {0x1F59,0}, {0x1F5A,29}, {0x1F5B,0}, {0x1F5C,29}, {0x1F5D,0}, {0x1F5E,29}, + {0x1F5F,0}, {0x1F60,1}, {0x1F68,0}, {0x1F70,1}, {0x1F7E,29}, {0x1F80,1}, + {0x1F88,2}, {0x1F90,1}, {0x1F98,2}, {0x1FA0,1}, {0x1FA8,2}, {0x1FB0,1}, + {0x1FB5,29}, {0x1FB6,1}, {0x1FB8,0}, {0x1FBC,2}, {0x1FBD,20}, {0x1FBE,1}, + {0x1FBF,20}, {0x1FC2,1}, {0x1FC5,29}, {0x1FC6,1}, {0x1FC8,0}, {0x1FCC,2}, + {0x1FCD,20}, {0x1FD0,1}, {0x1FD4,29}, {0x1FD6,1}, {0x1FD8,0}, {0x1FDC,29}, + {0x1FDD,20}, {0x1FE0,1}, {0x1FE8,0}, {0x1FED,20}, {0x1FF0,29}, {0x1FF2,1}, + {0x1FF5,29}, {0x1FF6,1}, {0x1FF8,0}, {0x1FFC,2}, {0x1FFD,20}, {0x1FFF,29}, + {0x2000,22}, {0x200B,26}, {0x2010,12}, {0x2016,17}, {0x2018,15}, {0x2019,16}, + {0x201A,13}, {0x201B,15}, {0x201D,16}, {0x201E,13}, {0x201F,15}, {0x2020,17}, + {0x2028,23}, {0x2029,24}, {0x202A,26}, {0x202F,22}, {0x2030,17}, {0x2039,15}, + {0x203A,16}, {0x203B,17}, {0x203F,11}, {0x2041,17}, {0x2044,18}, {0x2045,13}, + {0x2046,14}, {0x2047,17}, {0x2052,18}, {0x2053,17}, {0x2054,11}, {0x2055,17}, + {0x205F,22}, {0x2060,26}, {0x2065,29}, {0x2066,26}, {0x2070,10}, {0x2071,3}, + {0x2072,29}, {0x2074,10}, {0x207A,18}, {0x207D,13}, {0x207E,14}, {0x207F,3}, + {0x2080,10}, {0x208A,18}, {0x208D,13}, {0x208E,14}, {0x208F,29}, {0x2090,3}, + {0x209D,29}, {0x20A0,19}, {0x20C1,29}, {0x20D0,5}, {0x20DD,7}, {0x20E1,5}, + {0x20E2,7}, {0x20E5,5}, {0x20F1,29}, {0x2100,21}, {0x2102,0}, {0x2103,21}, + {0x2107,0}, {0x2108,21}, {0x210A,1}, {0x210B,0}, {0x210E,1}, {0x2110,0}, + {0x2113,1}, {0x2114,21}, {0x2115,0}, {0x2116,21}, {0x2118,18}, {0x2119,0}, + {0x211E,21}, {0x2124,0}, {0x2125,21}, {0x2126,0}, {0x2127,21}, {0x2128,0}, + {0x2129,21}, {0x212A,0}, {0x212E,21}, {0x212F,1}, {0x2130,0}, {0x2134,1}, + {0x2135,4}, {0x2139,1}, {0x213A,21}, {0x213C,1}, {0x213E,0}, {0x2140,18}, + {0x2145,0}, {0x2146,1}, {0x214A,21}, {0x214B,18}, {0x214C,21}, {0x214E,1}, + {0x214F,21}, {0x2150,10}, {0x2160,9}, {0x2183,0}, {0x2184,1}, {0x2185,9}, + {0x2189,10}, {0x218A,21}, {0x218C,29}, {0x2190,18}, {0x2195,21}, {0x219A,18}, + {0x219C,21}, {0x21A0,18}, {0x21A1,21}, {0x21A3,18}, {0x21A4,21}, {0x21A6,18}, + {0x21A7,21}, {0x21AE,18}, {0x21AF,21}, {0x21CE,18}, {0x21D0,21}, {0x21D2,18}, + {0x21D3,21}, {0x21D4,18}, {0x21D5,21}, {0x21F4,18}, {0x2300,21}, {0x2308,13}, + {0x2309,14}, {0x230A,13}, {0x230B,14}, {0x230C,21}, {0x2320,18}, {0x2322,21}, + {0x2329,13}, {0x232A,14}, {0x232B,21}, {0x237C,18}, {0x237D,21}, {0x239B,18}, + {0x23B4,21}, {0x23DC,18}, {0x23E2,21}, {0x242A,29}, {0x2440,21}, {0x244B,29}, + {0x2460,10}, {0x249C,21}, {0x24EA,10}, {0x2500,21}, {0x25B7,18}, {0x25B8,21}, + {0x25C1,18}, {0x25C2,21}, {0x25F8,18}, {0x2600,21}, {0x266F,18}, {0x2670,21}, + {0x2768,13}, {0x2769,14}, {0x276A,13}, {0x276B,14}, {0x276C,13}, {0x276D,14}, + {0x276E,13}, {0x276F,14}, {0x2770,13}, {0x2771,14}, {0x2772,13}, {0x2773,14}, + {0x2774,13}, {0x2775,14}, {0x2776,10}, {0x2794,21}, {0x27C0,18}, {0x27C5,13}, + {0x27C6,14}, {0x27C7,18}, {0x27E6,13}, {0x27E7,14}, {0x27E8,13}, {0x27E9,14}, + {0x27EA,13}, {0x27EB,14}, {0x27EC,13}, {0x27ED,14}, {0x27EE,13}, {0x27EF,14}, + {0x27F0,18}, {0x2800,21}, {0x2900,18}, {0x2983,13}, {0x2984,14}, {0x2985,13}, + {0x2986,14}, {0x2987,13}, {0x2988,14}, {0x2989,13}, {0x298A,14}, {0x298B,13}, + {0x298C,14}, {0x298D,13}, {0x298E,14}, {0x298F,13}, {0x2990,14}, {0x2991,13}, + {0x2992,14}, {0x2993,13}, {0x2994,14}, {0x2995,13}, {0x2996,14}, {0x2997,13}, + {0x2998,14}, {0x2999,18}, {0x29D8,13}, {0x29D9,14}, {0x29DA,13}, {0x29DB,14}, + {0x29DC,18}, {0x29FC,13}, {0x29FD,14}, {0x29FE,18}, {0x2B00,21}, {0x2B30,18}, + {0x2B45,21}, {0x2B47,18}, {0x2B4D,21}, {0x2B74,29}, {0x2B76,21}, {0x2B96,29}, + {0x2B97,21}, {0x2C00,0}, {0x2C30,1}, {0x2C60,0}, {0x2C61,1}, {0x2C62,0}, + {0x2C65,1}, {0x2C67,0}, {0x2C68,1}, {0x2C69,0}, {0x2C6A,1}, {0x2C6B,0}, + {0x2C6C,1}, {0x2C6D,0}, {0x2C71,1}, {0x2C72,0}, {0x2C73,1}, {0x2C75,0}, + {0x2C76,1}, {0x2C7C,3}, {0x2C7E,0}, {0x2C81,1}, {0x2C82,0}, {0x2C83,1}, + {0x2C84,0}, {0x2C85,1}, {0x2C86,0}, {0x2C87,1}, {0x2C88,0}, {0x2C89,1}, + {0x2C8A,0}, {0x2C8B,1}, {0x2C8C,0}, {0x2C8D,1}, {0x2C8E,0}, {0x2C8F,1}, + {0x2C90,0}, {0x2C91,1}, {0x2C92,0}, {0x2C93,1}, {0x2C94,0}, {0x2C95,1}, + {0x2C96,0}, {0x2C97,1}, {0x2C98,0}, {0x2C99,1}, {0x2C9A,0}, {0x2C9B,1}, + {0x2C9C,0}, {0x2C9D,1}, {0x2C9E,0}, {0x2C9F,1}, {0x2CA0,0}, {0x2CA1,1}, + {0x2CA2,0}, {0x2CA3,1}, {0x2CA4,0}, {0x2CA5,1}, {0x2CA6,0}, {0x2CA7,1}, + {0x2CA8,0}, {0x2CA9,1}, {0x2CAA,0}, {0x2CAB,1}, {0x2CAC,0}, {0x2CAD,1}, + {0x2CAE,0}, {0x2CAF,1}, {0x2CB0,0}, {0x2CB1,1}, {0x2CB2,0}, {0x2CB3,1}, + {0x2CB4,0}, {0x2CB5,1}, {0x2CB6,0}, {0x2CB7,1}, {0x2CB8,0}, {0x2CB9,1}, + {0x2CBA,0}, {0x2CBB,1}, {0x2CBC,0}, {0x2CBD,1}, {0x2CBE,0}, {0x2CBF,1}, + {0x2CC0,0}, {0x2CC1,1}, {0x2CC2,0}, {0x2CC3,1}, {0x2CC4,0}, {0x2CC5,1}, + {0x2CC6,0}, {0x2CC7,1}, {0x2CC8,0}, {0x2CC9,1}, {0x2CCA,0}, {0x2CCB,1}, + {0x2CCC,0}, {0x2CCD,1}, {0x2CCE,0}, {0x2CCF,1}, {0x2CD0,0}, {0x2CD1,1}, + {0x2CD2,0}, {0x2CD3,1}, {0x2CD4,0}, {0x2CD5,1}, {0x2CD6,0}, {0x2CD7,1}, + {0x2CD8,0}, {0x2CD9,1}, {0x2CDA,0}, {0x2CDB,1}, {0x2CDC,0}, {0x2CDD,1}, + {0x2CDE,0}, {0x2CDF,1}, {0x2CE0,0}, {0x2CE1,1}, {0x2CE2,0}, {0x2CE3,1}, + {0x2CE5,21}, {0x2CEB,0}, {0x2CEC,1}, {0x2CED,0}, {0x2CEE,1}, {0x2CEF,5}, + {0x2CF2,0}, {0x2CF3,1}, {0x2CF4,29}, {0x2CF9,17}, {0x2CFD,10}, {0x2CFE,17}, + {0x2D00,1}, {0x2D26,29}, {0x2D27,1}, {0x2D28,29}, {0x2D2D,1}, {0x2D2E,29}, + {0x2D30,4}, {0x2D68,29}, {0x2D6F,3}, {0x2D70,17}, {0x2D71,29}, {0x2D7F,5}, + {0x2D80,4}, {0x2D97,29}, {0x2DA0,4}, {0x2DA7,29}, {0x2DA8,4}, {0x2DAF,29}, + {0x2DB0,4}, {0x2DB7,29}, {0x2DB8,4}, {0x2DBF,29}, {0x2DC0,4}, {0x2DC7,29}, + {0x2DC8,4}, {0x2DCF,29}, {0x2DD0,4}, {0x2DD7,29}, {0x2DD8,4}, {0x2DDF,29}, + {0x2DE0,5}, {0x2E00,17}, {0x2E02,15}, {0x2E03,16}, {0x2E04,15}, {0x2E05,16}, + {0x2E06,17}, {0x2E09,15}, {0x2E0A,16}, {0x2E0B,17}, {0x2E0C,15}, {0x2E0D,16}, + {0x2E0E,17}, {0x2E17,12}, {0x2E18,17}, {0x2E1A,12}, {0x2E1B,17}, {0x2E1C,15}, + {0x2E1D,16}, {0x2E1E,17}, {0x2E20,15}, {0x2E21,16}, {0x2E22,13}, {0x2E23,14}, + {0x2E24,13}, {0x2E25,14}, {0x2E26,13}, {0x2E27,14}, {0x2E28,13}, {0x2E29,14}, + {0x2E2A,17}, {0x2E2F,3}, {0x2E30,17}, {0x2E3A,12}, {0x2E3C,17}, {0x2E40,12}, + {0x2E41,17}, {0x2E42,13}, {0x2E43,17}, {0x2E50,21}, {0x2E52,17}, {0x2E55,13}, + {0x2E56,14}, {0x2E57,13}, {0x2E58,14}, {0x2E59,13}, {0x2E5A,14}, {0x2E5B,13}, + {0x2E5C,14}, {0x2E5D,12}, {0x2E5E,29}, {0x2E80,21}, {0x2E9A,29}, {0x2E9B,21}, + {0x2EF4,29}, {0x2F00,21}, {0x2FD6,29}, {0x2FF0,21}, {0x3000,22}, {0x3001,17}, + {0x3004,21}, {0x3005,3}, {0x3006,4}, {0x3007,9}, {0x3008,13}, {0x3009,14}, + {0x300A,13}, {0x300B,14}, {0x300C,13}, {0x300D,14}, {0x300E,13}, {0x300F,14}, + {0x3010,13}, {0x3011,14}, {0x3012,21}, {0x3014,13}, {0x3015,14}, {0x3016,13}, + {0x3017,14}, {0x3018,13}, {0x3019,14}, {0x301A,13}, {0x301B,14}, {0x301C,12}, + {0x301D,13}, {0x301E,14}, {0x3020,21}, {0x3021,9}, {0x302A,5}, {0x302E,6}, + {0x3030,12}, {0x3031,3}, {0x3036,21}, {0x3038,9}, {0x303B,3}, {0x303C,4}, + {0x303D,17}, {0x303E,21}, {0x3040,29}, {0x3041,4}, {0x3097,29}, {0x3099,5}, + {0x309B,20}, {0x309D,3}, {0x309F,4}, {0x30A0,12}, {0x30A1,4}, {0x30FB,17}, + {0x30FC,3}, {0x30FF,4}, {0x3100,29}, {0x3105,4}, {0x3130,29}, {0x3131,4}, + {0x318F,29}, {0x3190,21}, {0x3192,10}, {0x3196,21}, {0x31A0,4}, {0x31C0,21}, + {0x31E6,29}, {0x31EF,21}, {0x31F0,4}, {0x3200,21}, {0x321F,29}, {0x3220,10}, + {0x322A,21}, {0x3248,10}, {0x3250,21}, {0x3251,10}, {0x3260,21}, {0x3280,10}, + {0x328A,21}, {0x32B1,10}, {0x32C0,21}, {0x3400,4}, {0x4DC0,21}, {0x4E00,4}, + {0xA015,3}, {0xA016,4}, {0xA48D,29}, {0xA490,21}, {0xA4C7,29}, {0xA4D0,4}, + {0xA4F8,3}, {0xA4FE,17}, {0xA500,4}, {0xA60C,3}, {0xA60D,17}, {0xA610,4}, + {0xA620,8}, {0xA62A,4}, {0xA62C,29}, {0xA640,0}, {0xA641,1}, {0xA642,0}, + {0xA643,1}, {0xA644,0}, {0xA645,1}, {0xA646,0}, {0xA647,1}, {0xA648,0}, + {0xA649,1}, {0xA64A,0}, {0xA64B,1}, {0xA64C,0}, {0xA64D,1}, {0xA64E,0}, + {0xA64F,1}, {0xA650,0}, {0xA651,1}, {0xA652,0}, {0xA653,1}, {0xA654,0}, + {0xA655,1}, {0xA656,0}, {0xA657,1}, {0xA658,0}, {0xA659,1}, {0xA65A,0}, + {0xA65B,1}, {0xA65C,0}, {0xA65D,1}, {0xA65E,0}, {0xA65F,1}, {0xA660,0}, + {0xA661,1}, {0xA662,0}, {0xA663,1}, {0xA664,0}, {0xA665,1}, {0xA666,0}, + {0xA667,1}, {0xA668,0}, {0xA669,1}, {0xA66A,0}, {0xA66B,1}, {0xA66C,0}, + {0xA66D,1}, {0xA66E,4}, {0xA66F,5}, {0xA670,7}, {0xA673,17}, {0xA674,5}, + {0xA67E,17}, {0xA67F,3}, {0xA680,0}, {0xA681,1}, {0xA682,0}, {0xA683,1}, + {0xA684,0}, {0xA685,1}, {0xA686,0}, {0xA687,1}, {0xA688,0}, {0xA689,1}, + {0xA68A,0}, {0xA68B,1}, {0xA68C,0}, {0xA68D,1}, {0xA68E,0}, {0xA68F,1}, + {0xA690,0}, {0xA691,1}, {0xA692,0}, {0xA693,1}, {0xA694,0}, {0xA695,1}, + {0xA696,0}, {0xA697,1}, {0xA698,0}, {0xA699,1}, {0xA69A,0}, {0xA69B,1}, + {0xA69C,3}, {0xA69E,5}, {0xA6A0,4}, {0xA6E6,9}, {0xA6F0,5}, {0xA6F2,17}, + {0xA6F8,29}, {0xA700,20}, {0xA717,3}, {0xA720,20}, {0xA722,0}, {0xA723,1}, + {0xA724,0}, {0xA725,1}, {0xA726,0}, {0xA727,1}, {0xA728,0}, {0xA729,1}, + {0xA72A,0}, {0xA72B,1}, {0xA72C,0}, {0xA72D,1}, {0xA72E,0}, {0xA72F,1}, + {0xA732,0}, {0xA733,1}, {0xA734,0}, {0xA735,1}, {0xA736,0}, {0xA737,1}, + {0xA738,0}, {0xA739,1}, {0xA73A,0}, {0xA73B,1}, {0xA73C,0}, {0xA73D,1}, + {0xA73E,0}, {0xA73F,1}, {0xA740,0}, {0xA741,1}, {0xA742,0}, {0xA743,1}, + {0xA744,0}, {0xA745,1}, {0xA746,0}, {0xA747,1}, {0xA748,0}, {0xA749,1}, + {0xA74A,0}, {0xA74B,1}, {0xA74C,0}, {0xA74D,1}, {0xA74E,0}, {0xA74F,1}, + {0xA750,0}, {0xA751,1}, {0xA752,0}, {0xA753,1}, {0xA754,0}, {0xA755,1}, + {0xA756,0}, {0xA757,1}, {0xA758,0}, {0xA759,1}, {0xA75A,0}, {0xA75B,1}, + {0xA75C,0}, {0xA75D,1}, {0xA75E,0}, {0xA75F,1}, {0xA760,0}, {0xA761,1}, + {0xA762,0}, {0xA763,1}, {0xA764,0}, {0xA765,1}, {0xA766,0}, {0xA767,1}, + {0xA768,0}, {0xA769,1}, {0xA76A,0}, {0xA76B,1}, {0xA76C,0}, {0xA76D,1}, + {0xA76E,0}, {0xA76F,1}, {0xA770,3}, {0xA771,1}, {0xA779,0}, {0xA77A,1}, + {0xA77B,0}, {0xA77C,1}, {0xA77D,0}, {0xA77F,1}, {0xA780,0}, {0xA781,1}, + {0xA782,0}, {0xA783,1}, {0xA784,0}, {0xA785,1}, {0xA786,0}, {0xA787,1}, + {0xA788,3}, {0xA789,20}, {0xA78B,0}, {0xA78C,1}, {0xA78D,0}, {0xA78E,1}, + {0xA78F,4}, {0xA790,0}, {0xA791,1}, {0xA792,0}, {0xA793,1}, {0xA796,0}, + {0xA797,1}, {0xA798,0}, {0xA799,1}, {0xA79A,0}, {0xA79B,1}, {0xA79C,0}, + {0xA79D,1}, {0xA79E,0}, {0xA79F,1}, {0xA7A0,0}, {0xA7A1,1}, {0xA7A2,0}, + {0xA7A3,1}, {0xA7A4,0}, {0xA7A5,1}, {0xA7A6,0}, {0xA7A7,1}, {0xA7A8,0}, + {0xA7A9,1}, {0xA7AA,0}, {0xA7AF,1}, {0xA7B0,0}, {0xA7B5,1}, {0xA7B6,0}, + {0xA7B7,1}, {0xA7B8,0}, {0xA7B9,1}, {0xA7BA,0}, {0xA7BB,1}, {0xA7BC,0}, + {0xA7BD,1}, {0xA7BE,0}, {0xA7BF,1}, {0xA7C0,0}, {0xA7C1,1}, {0xA7C2,0}, + {0xA7C3,1}, {0xA7C4,0}, {0xA7C8,1}, {0xA7C9,0}, {0xA7CA,1}, {0xA7CB,0}, + {0xA7CD,1}, {0xA7CE,29}, {0xA7D0,0}, {0xA7D1,1}, {0xA7D2,29}, {0xA7D3,1}, + {0xA7D4,29}, {0xA7D5,1}, {0xA7D6,0}, {0xA7D7,1}, {0xA7D8,0}, {0xA7D9,1}, + {0xA7DA,0}, {0xA7DB,1}, {0xA7DC,0}, {0xA7DD,29}, {0xA7F2,3}, {0xA7F5,0}, + {0xA7F6,1}, {0xA7F7,4}, {0xA7F8,3}, {0xA7FA,1}, {0xA7FB,4}, {0xA802,5}, + {0xA803,4}, {0xA806,5}, {0xA807,4}, {0xA80B,5}, {0xA80C,4}, {0xA823,6}, + {0xA825,5}, {0xA827,6}, {0xA828,21}, {0xA82C,5}, {0xA82D,29}, {0xA830,10}, + {0xA836,21}, {0xA838,19}, {0xA839,21}, {0xA83A,29}, {0xA840,4}, {0xA874,17}, + {0xA878,29}, {0xA880,6}, {0xA882,4}, {0xA8B4,6}, {0xA8C4,5}, {0xA8C6,29}, + {0xA8CE,17}, {0xA8D0,8}, {0xA8DA,29}, {0xA8E0,5}, {0xA8F2,4}, {0xA8F8,17}, + {0xA8FB,4}, {0xA8FC,17}, {0xA8FD,4}, {0xA8FF,5}, {0xA900,8}, {0xA90A,4}, + {0xA926,5}, {0xA92E,17}, {0xA930,4}, {0xA947,5}, {0xA952,6}, {0xA954,29}, + {0xA95F,17}, {0xA960,4}, {0xA97D,29}, {0xA980,5}, {0xA983,6}, {0xA984,4}, + {0xA9B3,5}, {0xA9B4,6}, {0xA9B6,5}, {0xA9BA,6}, {0xA9BC,5}, {0xA9BE,6}, + {0xA9C1,17}, {0xA9CE,29}, {0xA9CF,3}, {0xA9D0,8}, {0xA9DA,29}, {0xA9DE,17}, + {0xA9E0,4}, {0xA9E5,5}, {0xA9E6,3}, {0xA9E7,4}, {0xA9F0,8}, {0xA9FA,4}, + {0xA9FF,29}, {0xAA00,4}, {0xAA29,5}, {0xAA2F,6}, {0xAA31,5}, {0xAA33,6}, + {0xAA35,5}, {0xAA37,29}, {0xAA40,4}, {0xAA43,5}, {0xAA44,4}, {0xAA4C,5}, + {0xAA4D,6}, {0xAA4E,29}, {0xAA50,8}, {0xAA5A,29}, {0xAA5C,17}, {0xAA60,4}, + {0xAA70,3}, {0xAA71,4}, {0xAA77,21}, {0xAA7A,4}, {0xAA7B,6}, {0xAA7C,5}, + {0xAA7D,6}, {0xAA7E,4}, {0xAAB0,5}, {0xAAB1,4}, {0xAAB2,5}, {0xAAB5,4}, + {0xAAB7,5}, {0xAAB9,4}, {0xAABE,5}, {0xAAC0,4}, {0xAAC1,5}, {0xAAC2,4}, + {0xAAC3,29}, {0xAADB,4}, {0xAADD,3}, {0xAADE,17}, {0xAAE0,4}, {0xAAEB,6}, + {0xAAEC,5}, {0xAAEE,6}, {0xAAF0,17}, {0xAAF2,4}, {0xAAF3,3}, {0xAAF5,6}, + {0xAAF6,5}, {0xAAF7,29}, {0xAB01,4}, {0xAB07,29}, {0xAB09,4}, {0xAB0F,29}, + {0xAB11,4}, {0xAB17,29}, {0xAB20,4}, {0xAB27,29}, {0xAB28,4}, {0xAB2F,29}, + {0xAB30,1}, {0xAB5B,20}, {0xAB5C,3}, {0xAB60,1}, {0xAB69,3}, {0xAB6A,20}, + {0xAB6C,29}, {0xAB70,1}, {0xABC0,4}, {0xABE3,6}, {0xABE5,5}, {0xABE6,6}, + {0xABE8,5}, {0xABE9,6}, {0xABEB,17}, {0xABEC,6}, {0xABED,5}, {0xABEE,29}, + {0xABF0,8}, {0xABFA,29}, {0xAC00,4}, {0xD7A4,29}, {0xD7B0,4}, {0xD7C7,29}, + {0xD7CB,4}, {0xD7FC,29}, {0xD800,27}, {0xE000,28}, {0xF900,4}, {0xFA6E,29}, + {0xFA70,4}, {0xFADA,29}, {0xFB00,1}, {0xFB07,29}, {0xFB13,1}, {0xFB18,29}, + {0xFB1D,4}, {0xFB1E,5}, {0xFB1F,4}, {0xFB29,18}, {0xFB2A,4}, {0xFB37,29}, + {0xFB38,4}, {0xFB3D,29}, {0xFB3E,4}, {0xFB3F,29}, {0xFB40,4}, {0xFB42,29}, + {0xFB43,4}, {0xFB45,29}, {0xFB46,4}, {0xFBB2,20}, {0xFBC3,29}, {0xFBD3,4}, + {0xFD3E,14}, {0xFD3F,13}, {0xFD40,21}, {0xFD50,4}, {0xFD90,29}, {0xFD92,4}, + {0xFDC8,29}, {0xFDCF,21}, {0xFDD0,29}, {0xFDF0,4}, {0xFDFC,19}, {0xFDFD,21}, + {0xFE00,5}, {0xFE10,17}, {0xFE17,13}, {0xFE18,14}, {0xFE19,17}, {0xFE1A,29}, + {0xFE20,5}, {0xFE30,17}, {0xFE31,12}, {0xFE33,11}, {0xFE35,13}, {0xFE36,14}, + {0xFE37,13}, {0xFE38,14}, {0xFE39,13}, {0xFE3A,14}, {0xFE3B,13}, {0xFE3C,14}, + {0xFE3D,13}, {0xFE3E,14}, {0xFE3F,13}, {0xFE40,14}, {0xFE41,13}, {0xFE42,14}, + {0xFE43,13}, {0xFE44,14}, {0xFE45,17}, {0xFE47,13}, {0xFE48,14}, {0xFE49,17}, + {0xFE4D,11}, {0xFE50,17}, {0xFE53,29}, {0xFE54,17}, {0xFE58,12}, {0xFE59,13}, + {0xFE5A,14}, {0xFE5B,13}, {0xFE5C,14}, {0xFE5D,13}, {0xFE5E,14}, {0xFE5F,17}, + {0xFE62,18}, {0xFE63,12}, {0xFE64,18}, {0xFE67,29}, {0xFE68,17}, {0xFE69,19}, + {0xFE6A,17}, {0xFE6C,29}, {0xFE70,4}, {0xFE75,29}, {0xFE76,4}, {0xFEFD,29}, + {0xFEFF,26}, {0xFF00,29}, {0xFF01,17}, {0xFF04,19}, {0xFF05,17}, {0xFF08,13}, + {0xFF09,14}, {0xFF0A,17}, {0xFF0B,18}, {0xFF0C,17}, {0xFF0D,12}, {0xFF0E,17}, + {0xFF10,8}, {0xFF1A,17}, {0xFF1C,18}, {0xFF1F,17}, {0xFF21,0}, {0xFF3B,13}, + {0xFF3C,17}, {0xFF3D,14}, {0xFF3E,20}, {0xFF3F,11}, {0xFF40,20}, {0xFF41,1}, + {0xFF5B,13}, {0xFF5C,18}, {0xFF5D,14}, {0xFF5E,18}, {0xFF5F,13}, {0xFF60,14}, + {0xFF61,17}, {0xFF62,13}, {0xFF63,14}, {0xFF64,17}, {0xFF66,4}, {0xFF70,3}, + {0xFF71,4}, {0xFF9E,3}, {0xFFA0,4}, {0xFFBF,29}, {0xFFC2,4}, {0xFFC8,29}, + {0xFFCA,4}, {0xFFD0,29}, {0xFFD2,4}, {0xFFD8,29}, {0xFFDA,4}, {0xFFDD,29}, + {0xFFE0,19}, {0xFFE2,18}, {0xFFE3,20}, {0xFFE4,21}, {0xFFE5,19}, {0xFFE7,29}, + {0xFFE8,21}, {0xFFE9,18}, {0xFFED,21}, {0xFFEF,29}, {0xFFF9,26}, {0xFFFC,21}, + {0xFFFE,29}, {0x10000,4}, {0x1000C,29}, {0x1000D,4}, {0x10027,29}, {0x10028,4}, + {0x1003B,29}, {0x1003C,4}, {0x1003E,29}, {0x1003F,4}, {0x1004E,29}, {0x10050,4}, + {0x1005E,29}, {0x10080,4}, {0x100FB,29}, {0x10100,17}, {0x10103,29}, {0x10107,10}, + {0x10134,29}, {0x10137,21}, {0x10140,9}, {0x10175,10}, {0x10179,21}, {0x1018A,10}, + {0x1018C,21}, {0x1018F,29}, {0x10190,21}, {0x1019D,29}, {0x101A0,21}, {0x101A1,29}, + {0x101D0,21}, {0x101FD,5}, {0x101FE,29}, {0x10280,4}, {0x1029D,29}, {0x102A0,4}, + {0x102D1,29}, {0x102E0,5}, {0x102E1,10}, {0x102FC,29}, {0x10300,4}, {0x10320,10}, + {0x10324,29}, {0x1032D,4}, {0x10341,9}, {0x10342,4}, {0x1034A,9}, {0x1034B,29}, + {0x10350,4}, {0x10376,5}, {0x1037B,29}, {0x10380,4}, {0x1039E,29}, {0x1039F,17}, + {0x103A0,4}, {0x103C4,29}, {0x103C8,4}, {0x103D0,17}, {0x103D1,9}, {0x103D6,29}, + {0x10400,0}, {0x10428,1}, {0x10450,4}, {0x1049E,29}, {0x104A0,8}, {0x104AA,29}, + {0x104B0,0}, {0x104D4,29}, {0x104D8,1}, {0x104FC,29}, {0x10500,4}, {0x10528,29}, + {0x10530,4}, {0x10564,29}, {0x1056F,17}, {0x10570,0}, {0x1057B,29}, {0x1057C,0}, + {0x1058B,29}, {0x1058C,0}, {0x10593,29}, {0x10594,0}, {0x10596,29}, {0x10597,1}, + {0x105A2,29}, {0x105A3,1}, {0x105B2,29}, {0x105B3,1}, {0x105BA,29}, {0x105BB,1}, + {0x105BD,29}, {0x105C0,4}, {0x105F4,29}, {0x10600,4}, {0x10737,29}, {0x10740,4}, + {0x10756,29}, {0x10760,4}, {0x10768,29}, {0x10780,3}, {0x10786,29}, {0x10787,3}, + {0x107B1,29}, {0x107B2,3}, {0x107BB,29}, {0x10800,4}, {0x10806,29}, {0x10808,4}, + {0x10809,29}, {0x1080A,4}, {0x10836,29}, {0x10837,4}, {0x10839,29}, {0x1083C,4}, + {0x1083D,29}, {0x1083F,4}, {0x10856,29}, {0x10857,17}, {0x10858,10}, {0x10860,4}, + {0x10877,21}, {0x10879,10}, {0x10880,4}, {0x1089F,29}, {0x108A7,10}, {0x108B0,29}, + {0x108E0,4}, {0x108F3,29}, {0x108F4,4}, {0x108F6,29}, {0x108FB,10}, {0x10900,4}, + {0x10916,10}, {0x1091C,29}, {0x1091F,17}, {0x10920,4}, {0x1093A,29}, {0x1093F,17}, + {0x10940,29}, {0x10980,4}, {0x109B8,29}, {0x109BC,10}, {0x109BE,4}, {0x109C0,10}, + {0x109D0,29}, {0x109D2,10}, {0x10A00,4}, {0x10A01,5}, {0x10A04,29}, {0x10A05,5}, + {0x10A07,29}, {0x10A0C,5}, {0x10A10,4}, {0x10A14,29}, {0x10A15,4}, {0x10A18,29}, + {0x10A19,4}, {0x10A36,29}, {0x10A38,5}, {0x10A3B,29}, {0x10A3F,5}, {0x10A40,10}, + {0x10A49,29}, {0x10A50,17}, {0x10A59,29}, {0x10A60,4}, {0x10A7D,10}, {0x10A7F,17}, + {0x10A80,4}, {0x10A9D,10}, {0x10AA0,29}, {0x10AC0,4}, {0x10AC8,21}, {0x10AC9,4}, + {0x10AE5,5}, {0x10AE7,29}, {0x10AEB,10}, {0x10AF0,17}, {0x10AF7,29}, {0x10B00,4}, + {0x10B36,29}, {0x10B39,17}, {0x10B40,4}, {0x10B56,29}, {0x10B58,10}, {0x10B60,4}, + {0x10B73,29}, {0x10B78,10}, {0x10B80,4}, {0x10B92,29}, {0x10B99,17}, {0x10B9D,29}, + {0x10BA9,10}, {0x10BB0,29}, {0x10C00,4}, {0x10C49,29}, {0x10C80,0}, {0x10CB3,29}, + {0x10CC0,1}, {0x10CF3,29}, {0x10CFA,10}, {0x10D00,4}, {0x10D24,5}, {0x10D28,29}, + {0x10D30,8}, {0x10D3A,29}, {0x10D40,8}, {0x10D4A,4}, {0x10D4E,3}, {0x10D4F,4}, + {0x10D50,0}, {0x10D66,29}, {0x10D69,5}, {0x10D6E,12}, {0x10D6F,3}, {0x10D70,1}, + {0x10D86,29}, {0x10D8E,18}, {0x10D90,29}, {0x10E60,10}, {0x10E7F,29}, {0x10E80,4}, + {0x10EAA,29}, {0x10EAB,5}, {0x10EAD,12}, {0x10EAE,29}, {0x10EB0,4}, {0x10EB2,29}, + {0x10EC2,4}, {0x10EC5,29}, {0x10EFC,5}, {0x10F00,4}, {0x10F1D,10}, {0x10F27,4}, + {0x10F28,29}, {0x10F30,4}, {0x10F46,5}, {0x10F51,10}, {0x10F55,17}, {0x10F5A,29}, + {0x10F70,4}, {0x10F82,5}, {0x10F86,17}, {0x10F8A,29}, {0x10FB0,4}, {0x10FC5,10}, + {0x10FCC,29}, {0x10FE0,4}, {0x10FF7,29}, {0x11000,6}, {0x11001,5}, {0x11002,6}, + {0x11003,4}, {0x11038,5}, {0x11047,17}, {0x1104E,29}, {0x11052,10}, {0x11066,8}, + {0x11070,5}, {0x11071,4}, {0x11073,5}, {0x11075,4}, {0x11076,29}, {0x1107F,5}, + {0x11082,6}, {0x11083,4}, {0x110B0,6}, {0x110B3,5}, {0x110B7,6}, {0x110B9,5}, + {0x110BB,17}, {0x110BD,26}, {0x110BE,17}, {0x110C2,5}, {0x110C3,29}, {0x110CD,26}, + {0x110CE,29}, {0x110D0,4}, {0x110E9,29}, {0x110F0,8}, {0x110FA,29}, {0x11100,5}, + {0x11103,4}, {0x11127,5}, {0x1112C,6}, {0x1112D,5}, {0x11135,29}, {0x11136,8}, + {0x11140,17}, {0x11144,4}, {0x11145,6}, {0x11147,4}, {0x11148,29}, {0x11150,4}, + {0x11173,5}, {0x11174,17}, {0x11176,4}, {0x11177,29}, {0x11180,5}, {0x11182,6}, + {0x11183,4}, {0x111B3,6}, {0x111B6,5}, {0x111BF,6}, {0x111C1,4}, {0x111C5,17}, + {0x111C9,5}, {0x111CD,17}, {0x111CE,6}, {0x111CF,5}, {0x111D0,8}, {0x111DA,4}, + {0x111DB,17}, {0x111DC,4}, {0x111DD,17}, {0x111E0,29}, {0x111E1,10}, {0x111F5,29}, + {0x11200,4}, {0x11212,29}, {0x11213,4}, {0x1122C,6}, {0x1122F,5}, {0x11232,6}, + {0x11234,5}, {0x11235,6}, {0x11236,5}, {0x11238,17}, {0x1123E,5}, {0x1123F,4}, + {0x11241,5}, {0x11242,29}, {0x11280,4}, {0x11287,29}, {0x11288,4}, {0x11289,29}, + {0x1128A,4}, {0x1128E,29}, {0x1128F,4}, {0x1129E,29}, {0x1129F,4}, {0x112A9,17}, + {0x112AA,29}, {0x112B0,4}, {0x112DF,5}, {0x112E0,6}, {0x112E3,5}, {0x112EB,29}, + {0x112F0,8}, {0x112FA,29}, {0x11300,5}, {0x11302,6}, {0x11304,29}, {0x11305,4}, + {0x1130D,29}, {0x1130F,4}, {0x11311,29}, {0x11313,4}, {0x11329,29}, {0x1132A,4}, + {0x11331,29}, {0x11332,4}, {0x11334,29}, {0x11335,4}, {0x1133A,29}, {0x1133B,5}, + {0x1133D,4}, {0x1133E,6}, {0x11340,5}, {0x11341,6}, {0x11345,29}, {0x11347,6}, + {0x11349,29}, {0x1134B,6}, {0x1134E,29}, {0x11350,4}, {0x11351,29}, {0x11357,6}, + {0x11358,29}, {0x1135D,4}, {0x11362,6}, {0x11364,29}, {0x11366,5}, {0x1136D,29}, + {0x11370,5}, {0x11375,29}, {0x11380,4}, {0x1138A,29}, {0x1138B,4}, {0x1138C,29}, + {0x1138E,4}, {0x1138F,29}, {0x11390,4}, {0x113B6,29}, {0x113B7,4}, {0x113B8,6}, + {0x113BB,5}, {0x113C1,29}, {0x113C2,6}, {0x113C3,29}, {0x113C5,6}, {0x113C6,29}, + {0x113C7,6}, {0x113CB,29}, {0x113CC,6}, {0x113CE,5}, {0x113CF,6}, {0x113D0,5}, + {0x113D1,4}, {0x113D2,5}, {0x113D3,4}, {0x113D4,17}, {0x113D6,29}, {0x113D7,17}, + {0x113D9,29}, {0x113E1,5}, {0x113E3,29}, {0x11400,4}, {0x11435,6}, {0x11438,5}, + {0x11440,6}, {0x11442,5}, {0x11445,6}, {0x11446,5}, {0x11447,4}, {0x1144B,17}, + {0x11450,8}, {0x1145A,17}, {0x1145C,29}, {0x1145D,17}, {0x1145E,5}, {0x1145F,4}, + {0x11462,29}, {0x11480,4}, {0x114B0,6}, {0x114B3,5}, {0x114B9,6}, {0x114BA,5}, + {0x114BB,6}, {0x114BF,5}, {0x114C1,6}, {0x114C2,5}, {0x114C4,4}, {0x114C6,17}, + {0x114C7,4}, {0x114C8,29}, {0x114D0,8}, {0x114DA,29}, {0x11580,4}, {0x115AF,6}, + {0x115B2,5}, {0x115B6,29}, {0x115B8,6}, {0x115BC,5}, {0x115BE,6}, {0x115BF,5}, + {0x115C1,17}, {0x115D8,4}, {0x115DC,5}, {0x115DE,29}, {0x11600,4}, {0x11630,6}, + {0x11633,5}, {0x1163B,6}, {0x1163D,5}, {0x1163E,6}, {0x1163F,5}, {0x11641,17}, + {0x11644,4}, {0x11645,29}, {0x11650,8}, {0x1165A,29}, {0x11660,17}, {0x1166D,29}, + {0x11680,4}, {0x116AB,5}, {0x116AC,6}, {0x116AD,5}, {0x116AE,6}, {0x116B0,5}, + {0x116B6,6}, {0x116B7,5}, {0x116B8,4}, {0x116B9,17}, {0x116BA,29}, {0x116C0,8}, + {0x116CA,29}, {0x116D0,8}, {0x116E4,29}, {0x11700,4}, {0x1171B,29}, {0x1171D,5}, + {0x1171E,6}, {0x1171F,5}, {0x11720,6}, {0x11722,5}, {0x11726,6}, {0x11727,5}, + {0x1172C,29}, {0x11730,8}, {0x1173A,10}, {0x1173C,17}, {0x1173F,21}, {0x11740,4}, + {0x11747,29}, {0x11800,4}, {0x1182C,6}, {0x1182F,5}, {0x11838,6}, {0x11839,5}, + {0x1183B,17}, {0x1183C,29}, {0x118A0,0}, {0x118C0,1}, {0x118E0,8}, {0x118EA,10}, + {0x118F3,29}, {0x118FF,4}, {0x11907,29}, {0x11909,4}, {0x1190A,29}, {0x1190C,4}, + {0x11914,29}, {0x11915,4}, {0x11917,29}, {0x11918,4}, {0x11930,6}, {0x11936,29}, + {0x11937,6}, {0x11939,29}, {0x1193B,5}, {0x1193D,6}, {0x1193E,5}, {0x1193F,4}, + {0x11940,6}, {0x11941,4}, {0x11942,6}, {0x11943,5}, {0x11944,17}, {0x11947,29}, + {0x11950,8}, {0x1195A,29}, {0x119A0,4}, {0x119A8,29}, {0x119AA,4}, {0x119D1,6}, + {0x119D4,5}, {0x119D8,29}, {0x119DA,5}, {0x119DC,6}, {0x119E0,5}, {0x119E1,4}, + {0x119E2,17}, {0x119E3,4}, {0x119E4,6}, {0x119E5,29}, {0x11A00,4}, {0x11A01,5}, + {0x11A0B,4}, {0x11A33,5}, {0x11A39,6}, {0x11A3A,4}, {0x11A3B,5}, {0x11A3F,17}, + {0x11A47,5}, {0x11A48,29}, {0x11A50,4}, {0x11A51,5}, {0x11A57,6}, {0x11A59,5}, + {0x11A5C,4}, {0x11A8A,5}, {0x11A97,6}, {0x11A98,5}, {0x11A9A,17}, {0x11A9D,4}, + {0x11A9E,17}, {0x11AA3,29}, {0x11AB0,4}, {0x11AF9,29}, {0x11B00,17}, {0x11B0A,29}, + {0x11BC0,4}, {0x11BE1,17}, {0x11BE2,29}, {0x11BF0,8}, {0x11BFA,29}, {0x11C00,4}, + {0x11C09,29}, {0x11C0A,4}, {0x11C2F,6}, {0x11C30,5}, {0x11C37,29}, {0x11C38,5}, + {0x11C3E,6}, {0x11C3F,5}, {0x11C40,4}, {0x11C41,17}, {0x11C46,29}, {0x11C50,8}, + {0x11C5A,10}, {0x11C6D,29}, {0x11C70,17}, {0x11C72,4}, {0x11C90,29}, {0x11C92,5}, + {0x11CA8,29}, {0x11CA9,6}, {0x11CAA,5}, {0x11CB1,6}, {0x11CB2,5}, {0x11CB4,6}, + {0x11CB5,5}, {0x11CB7,29}, {0x11D00,4}, {0x11D07,29}, {0x11D08,4}, {0x11D0A,29}, + {0x11D0B,4}, {0x11D31,5}, {0x11D37,29}, {0x11D3A,5}, {0x11D3B,29}, {0x11D3C,5}, + {0x11D3E,29}, {0x11D3F,5}, {0x11D46,4}, {0x11D47,5}, {0x11D48,29}, {0x11D50,8}, + {0x11D5A,29}, {0x11D60,4}, {0x11D66,29}, {0x11D67,4}, {0x11D69,29}, {0x11D6A,4}, + {0x11D8A,6}, {0x11D8F,29}, {0x11D90,5}, {0x11D92,29}, {0x11D93,6}, {0x11D95,5}, + {0x11D96,6}, {0x11D97,5}, {0x11D98,4}, {0x11D99,29}, {0x11DA0,8}, {0x11DAA,29}, + {0x11EE0,4}, {0x11EF3,5}, {0x11EF5,6}, {0x11EF7,17}, {0x11EF9,29}, {0x11F00,5}, + {0x11F02,4}, {0x11F03,6}, {0x11F04,4}, {0x11F11,29}, {0x11F12,4}, {0x11F34,6}, + {0x11F36,5}, {0x11F3B,29}, {0x11F3E,6}, {0x11F40,5}, {0x11F41,6}, {0x11F42,5}, + {0x11F43,17}, {0x11F50,8}, {0x11F5A,5}, {0x11F5B,29}, {0x11FB0,4}, {0x11FB1,29}, + {0x11FC0,10}, {0x11FD5,21}, {0x11FDD,19}, {0x11FE1,21}, {0x11FF2,29}, {0x11FFF,17}, + {0x12000,4}, {0x1239A,29}, {0x12400,9}, {0x1246F,29}, {0x12470,17}, {0x12475,29}, + {0x12480,4}, {0x12544,29}, {0x12F90,4}, {0x12FF1,17}, {0x12FF3,29}, {0x13000,4}, + {0x13430,26}, {0x13440,5}, {0x13441,4}, {0x13447,5}, {0x13456,29}, {0x13460,4}, + {0x143FB,29}, {0x14400,4}, {0x14647,29}, {0x16100,4}, {0x1611E,5}, {0x1612A,6}, + {0x1612D,5}, {0x16130,8}, {0x1613A,29}, {0x16800,4}, {0x16A39,29}, {0x16A40,4}, + {0x16A5F,29}, {0x16A60,8}, {0x16A6A,29}, {0x16A6E,17}, {0x16A70,4}, {0x16ABF,29}, + {0x16AC0,8}, {0x16ACA,29}, {0x16AD0,4}, {0x16AEE,29}, {0x16AF0,5}, {0x16AF5,17}, + {0x16AF6,29}, {0x16B00,4}, {0x16B30,5}, {0x16B37,17}, {0x16B3C,21}, {0x16B40,3}, + {0x16B44,17}, {0x16B45,21}, {0x16B46,29}, {0x16B50,8}, {0x16B5A,29}, {0x16B5B,10}, + {0x16B62,29}, {0x16B63,4}, {0x16B78,29}, {0x16B7D,4}, {0x16B90,29}, {0x16D40,3}, + {0x16D43,4}, {0x16D6B,3}, {0x16D6D,17}, {0x16D70,8}, {0x16D7A,29}, {0x16E40,0}, + {0x16E60,1}, {0x16E80,10}, {0x16E97,17}, {0x16E9B,29}, {0x16F00,4}, {0x16F4B,29}, + {0x16F4F,5}, {0x16F50,4}, {0x16F51,6}, {0x16F88,29}, {0x16F8F,5}, {0x16F93,3}, + {0x16FA0,29}, {0x16FE0,3}, {0x16FE2,17}, {0x16FE3,3}, {0x16FE4,5}, {0x16FE5,29}, + {0x16FF0,6}, {0x16FF2,29}, {0x17000,4}, {0x187F8,29}, {0x18800,4}, {0x18CD6,29}, + {0x18CFF,4}, {0x18D09,29}, {0x1AFF0,3}, {0x1AFF4,29}, {0x1AFF5,3}, {0x1AFFC,29}, + {0x1AFFD,3}, {0x1AFFF,29}, {0x1B000,4}, {0x1B123,29}, {0x1B132,4}, {0x1B133,29}, + {0x1B150,4}, {0x1B153,29}, {0x1B155,4}, {0x1B156,29}, {0x1B164,4}, {0x1B168,29}, + {0x1B170,4}, {0x1B2FC,29}, {0x1BC00,4}, {0x1BC6B,29}, {0x1BC70,4}, {0x1BC7D,29}, + {0x1BC80,4}, {0x1BC89,29}, {0x1BC90,4}, {0x1BC9A,29}, {0x1BC9C,21}, {0x1BC9D,5}, + {0x1BC9F,17}, {0x1BCA0,26}, {0x1BCA4,29}, {0x1CC00,21}, {0x1CCF0,8}, {0x1CCFA,29}, + {0x1CD00,21}, {0x1CEB4,29}, {0x1CF00,5}, {0x1CF2E,29}, {0x1CF30,5}, {0x1CF47,29}, + {0x1CF50,21}, {0x1CFC4,29}, {0x1D000,21}, {0x1D0F6,29}, {0x1D100,21}, {0x1D127,29}, + {0x1D129,21}, {0x1D165,6}, {0x1D167,5}, {0x1D16A,21}, {0x1D16D,6}, {0x1D173,26}, + {0x1D17B,5}, {0x1D183,21}, {0x1D185,5}, {0x1D18C,21}, {0x1D1AA,5}, {0x1D1AE,21}, + {0x1D1EB,29}, {0x1D200,21}, {0x1D242,5}, {0x1D245,21}, {0x1D246,29}, {0x1D2C0,10}, + {0x1D2D4,29}, {0x1D2E0,10}, {0x1D2F4,29}, {0x1D300,21}, {0x1D357,29}, {0x1D360,10}, + {0x1D379,29}, {0x1D400,0}, {0x1D41A,1}, {0x1D434,0}, {0x1D44E,1}, {0x1D455,29}, + {0x1D456,1}, {0x1D468,0}, {0x1D482,1}, {0x1D49C,0}, {0x1D49D,29}, {0x1D49E,0}, + {0x1D4A0,29}, {0x1D4A2,0}, {0x1D4A3,29}, {0x1D4A5,0}, {0x1D4A7,29}, {0x1D4A9,0}, + {0x1D4AD,29}, {0x1D4AE,0}, {0x1D4B6,1}, {0x1D4BA,29}, {0x1D4BB,1}, {0x1D4BC,29}, + {0x1D4BD,1}, {0x1D4C4,29}, {0x1D4C5,1}, {0x1D4D0,0}, {0x1D4EA,1}, {0x1D504,0}, + {0x1D506,29}, {0x1D507,0}, {0x1D50B,29}, {0x1D50D,0}, {0x1D515,29}, {0x1D516,0}, + {0x1D51D,29}, {0x1D51E,1}, {0x1D538,0}, {0x1D53A,29}, {0x1D53B,0}, {0x1D53F,29}, + {0x1D540,0}, {0x1D545,29}, {0x1D546,0}, {0x1D547,29}, {0x1D54A,0}, {0x1D551,29}, + {0x1D552,1}, {0x1D56C,0}, {0x1D586,1}, {0x1D5A0,0}, {0x1D5BA,1}, {0x1D5D4,0}, + {0x1D5EE,1}, {0x1D608,0}, {0x1D622,1}, {0x1D63C,0}, {0x1D656,1}, {0x1D670,0}, + {0x1D68A,1}, {0x1D6A6,29}, {0x1D6A8,0}, {0x1D6C1,18}, {0x1D6C2,1}, {0x1D6DB,18}, + {0x1D6DC,1}, {0x1D6E2,0}, {0x1D6FB,18}, {0x1D6FC,1}, {0x1D715,18}, {0x1D716,1}, + {0x1D71C,0}, {0x1D735,18}, {0x1D736,1}, {0x1D74F,18}, {0x1D750,1}, {0x1D756,0}, + {0x1D76F,18}, {0x1D770,1}, {0x1D789,18}, {0x1D78A,1}, {0x1D790,0}, {0x1D7A9,18}, + {0x1D7AA,1}, {0x1D7C3,18}, {0x1D7C4,1}, {0x1D7CA,0}, {0x1D7CB,1}, {0x1D7CC,29}, + {0x1D7CE,8}, {0x1D800,21}, {0x1DA00,5}, {0x1DA37,21}, {0x1DA3B,5}, {0x1DA6D,21}, + {0x1DA75,5}, {0x1DA76,21}, {0x1DA84,5}, {0x1DA85,21}, {0x1DA87,17}, {0x1DA8C,29}, + {0x1DA9B,5}, {0x1DAA0,29}, {0x1DAA1,5}, {0x1DAB0,29}, {0x1DF00,1}, {0x1DF0A,4}, + {0x1DF0B,1}, {0x1DF1F,29}, {0x1DF25,1}, {0x1DF2B,29}, {0x1E000,5}, {0x1E007,29}, + {0x1E008,5}, {0x1E019,29}, {0x1E01B,5}, {0x1E022,29}, {0x1E023,5}, {0x1E025,29}, + {0x1E026,5}, {0x1E02B,29}, {0x1E030,3}, {0x1E06E,29}, {0x1E08F,5}, {0x1E090,29}, + {0x1E100,4}, {0x1E12D,29}, {0x1E130,5}, {0x1E137,3}, {0x1E13E,29}, {0x1E140,8}, + {0x1E14A,29}, {0x1E14E,4}, {0x1E14F,21}, {0x1E150,29}, {0x1E290,4}, {0x1E2AE,5}, + {0x1E2AF,29}, {0x1E2C0,4}, {0x1E2EC,5}, {0x1E2F0,8}, {0x1E2FA,29}, {0x1E2FF,19}, + {0x1E300,29}, {0x1E4D0,4}, {0x1E4EB,3}, {0x1E4EC,5}, {0x1E4F0,8}, {0x1E4FA,29}, + {0x1E5D0,4}, {0x1E5EE,5}, {0x1E5F0,4}, {0x1E5F1,8}, {0x1E5FB,29}, {0x1E5FF,17}, + {0x1E600,29}, {0x1E7E0,4}, {0x1E7E7,29}, {0x1E7E8,4}, {0x1E7EC,29}, {0x1E7ED,4}, + {0x1E7EF,29}, {0x1E7F0,4}, {0x1E7FF,29}, {0x1E800,4}, {0x1E8C5,29}, {0x1E8C7,10}, + {0x1E8D0,5}, {0x1E8D7,29}, {0x1E900,0}, {0x1E922,1}, {0x1E944,5}, {0x1E94B,3}, + {0x1E94C,29}, {0x1E950,8}, {0x1E95A,29}, {0x1E95E,17}, {0x1E960,29}, {0x1EC71,10}, + {0x1ECAC,21}, {0x1ECAD,10}, {0x1ECB0,19}, {0x1ECB1,10}, {0x1ECB5,29}, {0x1ED01,10}, + {0x1ED2E,21}, {0x1ED2F,10}, {0x1ED3E,29}, {0x1EE00,4}, {0x1EE04,29}, {0x1EE05,4}, + {0x1EE20,29}, {0x1EE21,4}, {0x1EE23,29}, {0x1EE24,4}, {0x1EE25,29}, {0x1EE27,4}, + {0x1EE28,29}, {0x1EE29,4}, {0x1EE33,29}, {0x1EE34,4}, {0x1EE38,29}, {0x1EE39,4}, + {0x1EE3A,29}, {0x1EE3B,4}, {0x1EE3C,29}, {0x1EE42,4}, {0x1EE43,29}, {0x1EE47,4}, + {0x1EE48,29}, {0x1EE49,4}, {0x1EE4A,29}, {0x1EE4B,4}, {0x1EE4C,29}, {0x1EE4D,4}, + {0x1EE50,29}, {0x1EE51,4}, {0x1EE53,29}, {0x1EE54,4}, {0x1EE55,29}, {0x1EE57,4}, + {0x1EE58,29}, {0x1EE59,4}, {0x1EE5A,29}, {0x1EE5B,4}, {0x1EE5C,29}, {0x1EE5D,4}, + {0x1EE5E,29}, {0x1EE5F,4}, {0x1EE60,29}, {0x1EE61,4}, {0x1EE63,29}, {0x1EE64,4}, + {0x1EE65,29}, {0x1EE67,4}, {0x1EE6B,29}, {0x1EE6C,4}, {0x1EE73,29}, {0x1EE74,4}, + {0x1EE78,29}, {0x1EE79,4}, {0x1EE7D,29}, {0x1EE7E,4}, {0x1EE7F,29}, {0x1EE80,4}, + {0x1EE8A,29}, {0x1EE8B,4}, {0x1EE9C,29}, {0x1EEA1,4}, {0x1EEA4,29}, {0x1EEA5,4}, + {0x1EEAA,29}, {0x1EEAB,4}, {0x1EEBC,29}, {0x1EEF0,18}, {0x1EEF2,29}, {0x1F000,21}, + {0x1F02C,29}, {0x1F030,21}, {0x1F094,29}, {0x1F0A0,21}, {0x1F0AF,29}, {0x1F0B1,21}, + {0x1F0C0,29}, {0x1F0C1,21}, {0x1F0D0,29}, {0x1F0D1,21}, {0x1F0F6,29}, {0x1F100,10}, + {0x1F10D,21}, {0x1F1AE,29}, {0x1F1E6,21}, {0x1F203,29}, {0x1F210,21}, {0x1F23C,29}, + {0x1F240,21}, {0x1F249,29}, {0x1F250,21}, {0x1F252,29}, {0x1F260,21}, {0x1F266,29}, + {0x1F300,21}, {0x1F3FB,20}, {0x1F400,21}, {0x1F6D8,29}, {0x1F6DC,21}, {0x1F6ED,29}, + {0x1F6F0,21}, {0x1F6FD,29}, {0x1F700,21}, {0x1F777,29}, {0x1F77B,21}, {0x1F7DA,29}, + {0x1F7E0,21}, {0x1F7EC,29}, {0x1F7F0,21}, {0x1F7F1,29}, {0x1F800,21}, {0x1F80C,29}, + {0x1F810,21}, {0x1F848,29}, {0x1F850,21}, {0x1F85A,29}, {0x1F860,21}, {0x1F888,29}, + {0x1F890,21}, {0x1F8AE,29}, {0x1F8B0,21}, {0x1F8BC,29}, {0x1F8C0,21}, {0x1F8C2,29}, + {0x1F900,21}, {0x1FA54,29}, {0x1FA60,21}, {0x1FA6E,29}, {0x1FA70,21}, {0x1FA7D,29}, + {0x1FA80,21}, {0x1FA8A,29}, {0x1FA8F,21}, {0x1FAC7,29}, {0x1FACE,21}, {0x1FADD,29}, + {0x1FADF,21}, {0x1FAEA,29}, {0x1FAF0,21}, {0x1FAF9,29}, {0x1FB00,21}, {0x1FB93,29}, + {0x1FB94,21}, {0x1FBF0,8}, {0x1FBFA,29}, {0x20000,4}, {0x2A6E0,29}, {0x2A700,4}, + {0x2B73A,29}, {0x2B740,4}, {0x2B81E,29}, {0x2B820,4}, {0x2CEA2,29}, {0x2CEB0,4}, + {0x2EBE1,29}, {0x2EBF0,4}, {0x2EE5E,29}, {0x2F800,4}, {0x2FA1E,29}, {0x30000,4}, + {0x3134B,29}, {0x31350,4}, {0x323B0,29}, {0xE0001,26}, {0xE0002,29}, {0xE0020,26}, + {0xE0080,29}, {0xE0100,5}, {0xE01F0,29}, {0xF0000,28}, {0xFFFFE,29}, {0x100000,28}, + {0x10FFFE,29}, +}; +const size_t k_gc_runs_n = sizeof(k_gc_runs) / sizeof(k_gc_runs[0]); + +const CpRange k_white_space[] = { + {0x9,0xD}, {0x20,0x20}, {0x85,0x85}, {0xA0,0xA0}, {0x1680,0x1680}, {0x2000,0x200A}, + {0x2028,0x2029}, {0x202F,0x202F}, {0x205F,0x205F}, {0x3000,0x3000}, +}; +const size_t k_white_space_n = sizeof(k_white_space) / sizeof(k_white_space[0]); + +const CpRange k_digit[] = { + {0x30,0x39}, {0x660,0x669}, {0x6F0,0x6F9}, {0x7C0,0x7C9}, {0x966,0x96F}, {0x9E6,0x9EF}, + {0xA66,0xA6F}, {0xAE6,0xAEF}, {0xB66,0xB6F}, {0xBE6,0xBEF}, {0xC66,0xC6F}, {0xCE6,0xCEF}, + {0xD66,0xD6F}, {0xDE6,0xDEF}, {0xE50,0xE59}, {0xED0,0xED9}, {0xF20,0xF29}, {0x1040,0x1049}, + {0x1090,0x1099}, {0x17E0,0x17E9}, {0x1810,0x1819}, {0x1946,0x194F}, {0x19D0,0x19D9}, {0x1A80,0x1A89}, + {0x1A90,0x1A99}, {0x1B50,0x1B59}, {0x1BB0,0x1BB9}, {0x1C40,0x1C49}, {0x1C50,0x1C59}, {0xA620,0xA629}, + {0xA8D0,0xA8D9}, {0xA900,0xA909}, {0xA9D0,0xA9D9}, {0xA9F0,0xA9F9}, {0xAA50,0xAA59}, {0xABF0,0xABF9}, + {0xFF10,0xFF19}, {0x104A0,0x104A9}, {0x10D30,0x10D39}, {0x10D40,0x10D49}, {0x11066,0x1106F}, {0x110F0,0x110F9}, + {0x11136,0x1113F}, {0x111D0,0x111D9}, {0x112F0,0x112F9}, {0x11450,0x11459}, {0x114D0,0x114D9}, {0x11650,0x11659}, + {0x116C0,0x116C9}, {0x116D0,0x116E3}, {0x11730,0x11739}, {0x118E0,0x118E9}, {0x11950,0x11959}, {0x11BF0,0x11BF9}, + {0x11C50,0x11C59}, {0x11D50,0x11D59}, {0x11DA0,0x11DA9}, {0x11F50,0x11F59}, {0x16130,0x16139}, {0x16A60,0x16A69}, + {0x16AC0,0x16AC9}, {0x16B50,0x16B59}, {0x16D70,0x16D79}, {0x1CCF0,0x1CCF9}, {0x1D7CE,0x1D7FF}, {0x1E140,0x1E149}, + {0x1E2F0,0x1E2F9}, {0x1E4F0,0x1E4F9}, {0x1E5F1,0x1E5FA}, {0x1E950,0x1E959}, {0x1FBF0,0x1FBF9}, +}; +const size_t k_digit_n = sizeof(k_digit) / sizeof(k_digit[0]); + +const CpRange k_word[] = { + {0x30,0x39}, {0x41,0x5A}, {0x5F,0x5F}, {0x61,0x7A}, {0xAA,0xAA}, {0xB2,0xB3}, + {0xB5,0xB5}, {0xB9,0xBA}, {0xBC,0xBE}, {0xC0,0xD6}, {0xD8,0xF6}, {0xF8,0x2C1}, + {0x2C6,0x2D1}, {0x2E0,0x2E4}, {0x2EC,0x2EC}, {0x2EE,0x2EE}, {0x300,0x374}, {0x376,0x377}, + {0x37A,0x37D}, {0x37F,0x37F}, {0x386,0x386}, {0x388,0x38A}, {0x38C,0x38C}, {0x38E,0x3A1}, + {0x3A3,0x3F5}, {0x3F7,0x481}, {0x483,0x52F}, {0x531,0x556}, {0x559,0x559}, {0x560,0x588}, + {0x591,0x5BD}, {0x5BF,0x5BF}, {0x5C1,0x5C2}, {0x5C4,0x5C5}, {0x5C7,0x5C7}, {0x5D0,0x5EA}, + {0x5EF,0x5F2}, {0x610,0x61A}, {0x620,0x669}, {0x66E,0x6D3}, {0x6D5,0x6DC}, {0x6DF,0x6E8}, + {0x6EA,0x6FC}, {0x6FF,0x6FF}, {0x710,0x74A}, {0x74D,0x7B1}, {0x7C0,0x7F5}, {0x7FA,0x7FA}, + {0x7FD,0x7FD}, {0x800,0x82D}, {0x840,0x85B}, {0x860,0x86A}, {0x870,0x887}, {0x889,0x88E}, + {0x897,0x8E1}, {0x8E3,0x963}, {0x966,0x96F}, {0x971,0x983}, {0x985,0x98C}, {0x98F,0x990}, + {0x993,0x9A8}, {0x9AA,0x9B0}, {0x9B2,0x9B2}, {0x9B6,0x9B9}, {0x9BC,0x9C4}, {0x9C7,0x9C8}, + {0x9CB,0x9CE}, {0x9D7,0x9D7}, {0x9DC,0x9DD}, {0x9DF,0x9E3}, {0x9E6,0x9F1}, {0x9FC,0x9FC}, + {0x9FE,0x9FE}, {0xA01,0xA03}, {0xA05,0xA0A}, {0xA0F,0xA10}, {0xA13,0xA28}, {0xA2A,0xA30}, + {0xA32,0xA33}, {0xA35,0xA36}, {0xA38,0xA39}, {0xA3C,0xA3C}, {0xA3E,0xA42}, {0xA47,0xA48}, + {0xA4B,0xA4D}, {0xA51,0xA51}, {0xA59,0xA5C}, {0xA5E,0xA5E}, {0xA66,0xA75}, {0xA81,0xA83}, + {0xA85,0xA8D}, {0xA8F,0xA91}, {0xA93,0xAA8}, {0xAAA,0xAB0}, {0xAB2,0xAB3}, {0xAB5,0xAB9}, + {0xABC,0xAC5}, {0xAC7,0xAC9}, {0xACB,0xACD}, {0xAD0,0xAD0}, {0xAE0,0xAE3}, {0xAE6,0xAEF}, + {0xAF9,0xAFF}, {0xB01,0xB03}, {0xB05,0xB0C}, {0xB0F,0xB10}, {0xB13,0xB28}, {0xB2A,0xB30}, + {0xB32,0xB33}, {0xB35,0xB39}, {0xB3C,0xB44}, {0xB47,0xB48}, {0xB4B,0xB4D}, {0xB55,0xB57}, + {0xB5C,0xB5D}, {0xB5F,0xB63}, {0xB66,0xB6F}, {0xB71,0xB71}, {0xB82,0xB83}, {0xB85,0xB8A}, + {0xB8E,0xB90}, {0xB92,0xB95}, {0xB99,0xB9A}, {0xB9C,0xB9C}, {0xB9E,0xB9F}, {0xBA3,0xBA4}, + {0xBA8,0xBAA}, {0xBAE,0xBB9}, {0xBBE,0xBC2}, {0xBC6,0xBC8}, {0xBCA,0xBCD}, {0xBD0,0xBD0}, + {0xBD7,0xBD7}, {0xBE6,0xBEF}, {0xC00,0xC0C}, {0xC0E,0xC10}, {0xC12,0xC28}, {0xC2A,0xC39}, + {0xC3C,0xC44}, {0xC46,0xC48}, {0xC4A,0xC4D}, {0xC55,0xC56}, {0xC58,0xC5A}, {0xC5D,0xC5D}, + {0xC60,0xC63}, {0xC66,0xC6F}, {0xC80,0xC83}, {0xC85,0xC8C}, {0xC8E,0xC90}, {0xC92,0xCA8}, + {0xCAA,0xCB3}, {0xCB5,0xCB9}, {0xCBC,0xCC4}, {0xCC6,0xCC8}, {0xCCA,0xCCD}, {0xCD5,0xCD6}, + {0xCDD,0xCDE}, {0xCE0,0xCE3}, {0xCE6,0xCEF}, {0xCF1,0xCF3}, {0xD00,0xD0C}, {0xD0E,0xD10}, + {0xD12,0xD44}, {0xD46,0xD48}, {0xD4A,0xD4E}, {0xD54,0xD57}, {0xD5F,0xD63}, {0xD66,0xD6F}, + {0xD7A,0xD7F}, {0xD81,0xD83}, {0xD85,0xD96}, {0xD9A,0xDB1}, {0xDB3,0xDBB}, {0xDBD,0xDBD}, + {0xDC0,0xDC6}, {0xDCA,0xDCA}, {0xDCF,0xDD4}, {0xDD6,0xDD6}, {0xDD8,0xDDF}, {0xDE6,0xDEF}, + {0xDF2,0xDF3}, {0xE01,0xE3A}, {0xE40,0xE4E}, {0xE50,0xE59}, {0xE81,0xE82}, {0xE84,0xE84}, + {0xE86,0xE8A}, {0xE8C,0xEA3}, {0xEA5,0xEA5}, {0xEA7,0xEBD}, {0xEC0,0xEC4}, {0xEC6,0xEC6}, + {0xEC8,0xECE}, {0xED0,0xED9}, {0xEDC,0xEDF}, {0xF00,0xF00}, {0xF18,0xF19}, {0xF20,0xF29}, + {0xF35,0xF35}, {0xF37,0xF37}, {0xF39,0xF39}, {0xF3E,0xF47}, {0xF49,0xF6C}, {0xF71,0xF84}, + {0xF86,0xF97}, {0xF99,0xFBC}, {0xFC6,0xFC6}, {0x1000,0x1049}, {0x1050,0x109D}, {0x10A0,0x10C5}, + {0x10C7,0x10C7}, {0x10CD,0x10CD}, {0x10D0,0x10FA}, {0x10FC,0x1248}, {0x124A,0x124D}, {0x1250,0x1256}, + {0x1258,0x1258}, {0x125A,0x125D}, {0x1260,0x1288}, {0x128A,0x128D}, {0x1290,0x12B0}, {0x12B2,0x12B5}, + {0x12B8,0x12BE}, {0x12C0,0x12C0}, {0x12C2,0x12C5}, {0x12C8,0x12D6}, {0x12D8,0x1310}, {0x1312,0x1315}, + {0x1318,0x135A}, {0x135D,0x135F}, {0x1380,0x138F}, {0x13A0,0x13F5}, {0x13F8,0x13FD}, {0x1401,0x166C}, + {0x166F,0x167F}, {0x1681,0x169A}, {0x16A0,0x16EA}, {0x16EE,0x16F8}, {0x1700,0x1715}, {0x171F,0x1734}, + {0x1740,0x1753}, {0x1760,0x176C}, {0x176E,0x1770}, {0x1772,0x1773}, {0x1780,0x17D3}, {0x17D7,0x17D7}, + {0x17DC,0x17DD}, {0x17E0,0x17E9}, {0x180B,0x180D}, {0x180F,0x1819}, {0x1820,0x1878}, {0x1880,0x18AA}, + {0x18B0,0x18F5}, {0x1900,0x191E}, {0x1920,0x192B}, {0x1930,0x193B}, {0x1946,0x196D}, {0x1970,0x1974}, + {0x1980,0x19AB}, {0x19B0,0x19C9}, {0x19D0,0x19D9}, {0x1A00,0x1A1B}, {0x1A20,0x1A5E}, {0x1A60,0x1A7C}, + {0x1A7F,0x1A89}, {0x1A90,0x1A99}, {0x1AA7,0x1AA7}, {0x1AB0,0x1ACE}, {0x1B00,0x1B4C}, {0x1B50,0x1B59}, + {0x1B6B,0x1B73}, {0x1B80,0x1BF3}, {0x1C00,0x1C37}, {0x1C40,0x1C49}, {0x1C4D,0x1C7D}, {0x1C80,0x1C8A}, + {0x1C90,0x1CBA}, {0x1CBD,0x1CBF}, {0x1CD0,0x1CD2}, {0x1CD4,0x1CFA}, {0x1D00,0x1F15}, {0x1F18,0x1F1D}, + {0x1F20,0x1F45}, {0x1F48,0x1F4D}, {0x1F50,0x1F57}, {0x1F59,0x1F59}, {0x1F5B,0x1F5B}, {0x1F5D,0x1F5D}, + {0x1F5F,0x1F7D}, {0x1F80,0x1FB4}, {0x1FB6,0x1FBC}, {0x1FBE,0x1FBE}, {0x1FC2,0x1FC4}, {0x1FC6,0x1FCC}, + {0x1FD0,0x1FD3}, {0x1FD6,0x1FDB}, {0x1FE0,0x1FEC}, {0x1FF2,0x1FF4}, {0x1FF6,0x1FFC}, {0x203F,0x2040}, + {0x2054,0x2054}, {0x2071,0x2071}, {0x207F,0x207F}, {0x2090,0x209C}, {0x20D0,0x20F0}, {0x2102,0x2102}, + {0x2107,0x2107}, {0x210A,0x2113}, {0x2115,0x2115}, {0x2119,0x211D}, {0x2124,0x2124}, {0x2126,0x2126}, + {0x2128,0x2128}, {0x212A,0x212D}, {0x212F,0x2139}, {0x213C,0x213F}, {0x2145,0x2149}, {0x214E,0x214E}, + {0x2160,0x2188}, {0x24B6,0x24E9}, {0x2C00,0x2CE4}, {0x2CEB,0x2CF3}, {0x2D00,0x2D25}, {0x2D27,0x2D27}, + {0x2D2D,0x2D2D}, {0x2D30,0x2D67}, {0x2D6F,0x2D6F}, {0x2D7F,0x2D96}, {0x2DA0,0x2DA6}, {0x2DA8,0x2DAE}, + {0x2DB0,0x2DB6}, {0x2DB8,0x2DBE}, {0x2DC0,0x2DC6}, {0x2DC8,0x2DCE}, {0x2DD0,0x2DD6}, {0x2DD8,0x2DDE}, + {0x2DE0,0x2DFF}, {0x2E2F,0x2E2F}, {0x3005,0x3007}, {0x3021,0x302F}, {0x3031,0x3035}, {0x3038,0x303C}, + {0x3041,0x3096}, {0x3099,0x309A}, {0x309D,0x309F}, {0x30A1,0x30FA}, {0x30FC,0x30FF}, {0x3105,0x312F}, + {0x3131,0x318E}, {0x31A0,0x31BF}, {0x31F0,0x31FF}, {0x3400,0x4DBF}, {0x4E00,0xA48C}, {0xA4D0,0xA4FD}, + {0xA500,0xA60C}, {0xA610,0xA62B}, {0xA640,0xA672}, {0xA674,0xA67D}, {0xA67F,0xA6F1}, {0xA717,0xA71F}, + {0xA722,0xA788}, {0xA78B,0xA7CD}, {0xA7D0,0xA7D1}, {0xA7D3,0xA7D3}, {0xA7D5,0xA7DC}, {0xA7F2,0xA827}, + {0xA82C,0xA82C}, {0xA840,0xA873}, {0xA880,0xA8C5}, {0xA8D0,0xA8D9}, {0xA8E0,0xA8F7}, {0xA8FB,0xA8FB}, + {0xA8FD,0xA92D}, {0xA930,0xA953}, {0xA960,0xA97C}, {0xA980,0xA9C0}, {0xA9CF,0xA9D9}, {0xA9E0,0xA9FE}, + {0xAA00,0xAA36}, {0xAA40,0xAA4D}, {0xAA50,0xAA59}, {0xAA60,0xAA76}, {0xAA7A,0xAAC2}, {0xAADB,0xAADD}, + {0xAAE0,0xAAEF}, {0xAAF2,0xAAF6}, {0xAB01,0xAB06}, {0xAB09,0xAB0E}, {0xAB11,0xAB16}, {0xAB20,0xAB26}, + {0xAB28,0xAB2E}, {0xAB30,0xAB5A}, {0xAB5C,0xAB69}, {0xAB70,0xABEA}, {0xABEC,0xABED}, {0xABF0,0xABF9}, + {0xAC00,0xD7A3}, {0xD7B0,0xD7C6}, {0xD7CB,0xD7FB}, {0xF900,0xFA6D}, {0xFA70,0xFAD9}, {0xFB00,0xFB06}, + {0xFB13,0xFB17}, {0xFB1D,0xFB28}, {0xFB2A,0xFB36}, {0xFB38,0xFB3C}, {0xFB3E,0xFB3E}, {0xFB40,0xFB41}, + {0xFB43,0xFB44}, {0xFB46,0xFBB1}, {0xFBD3,0xFD3D}, {0xFD50,0xFD8F}, {0xFD92,0xFDC7}, {0xFDF0,0xFDFB}, + {0xFE00,0xFE0F}, {0xFE20,0xFE2F}, {0xFE33,0xFE34}, {0xFE4D,0xFE4F}, {0xFE70,0xFE74}, {0xFE76,0xFEFC}, + {0xFF10,0xFF19}, {0xFF21,0xFF3A}, {0xFF3F,0xFF3F}, {0xFF41,0xFF5A}, {0xFF66,0xFFBE}, {0xFFC2,0xFFC7}, + {0xFFCA,0xFFCF}, {0xFFD2,0xFFD7}, {0xFFDA,0xFFDC}, {0x10000,0x1000B}, {0x1000D,0x10026}, {0x10028,0x1003A}, + {0x1003C,0x1003D}, {0x1003F,0x1004D}, {0x10050,0x1005D}, {0x10080,0x100FA}, {0x10140,0x10174}, {0x101FD,0x101FD}, + {0x10280,0x1029C}, {0x102A0,0x102D0}, {0x102E0,0x102E0}, {0x10300,0x1031F}, {0x1032D,0x1034A}, {0x10350,0x1037A}, + {0x10380,0x1039D}, {0x103A0,0x103C3}, {0x103C8,0x103CF}, {0x103D1,0x103D5}, {0x10400,0x1049D}, {0x104A0,0x104A9}, + {0x104B0,0x104D3}, {0x104D8,0x104FB}, {0x10500,0x10527}, {0x10530,0x10563}, {0x10570,0x1057A}, {0x1057C,0x1058A}, + {0x1058C,0x10592}, {0x10594,0x10595}, {0x10597,0x105A1}, {0x105A3,0x105B1}, {0x105B3,0x105B9}, {0x105BB,0x105BC}, + {0x105C0,0x105F3}, {0x10600,0x10736}, {0x10740,0x10755}, {0x10760,0x10767}, {0x10780,0x10785}, {0x10787,0x107B0}, + {0x107B2,0x107BA}, {0x10800,0x10805}, {0x10808,0x10808}, {0x1080A,0x10835}, {0x10837,0x10838}, {0x1083C,0x1083C}, + {0x1083F,0x10855}, {0x10860,0x10876}, {0x10880,0x1089E}, {0x108E0,0x108F2}, {0x108F4,0x108F5}, {0x10900,0x10915}, + {0x10920,0x10939}, {0x10980,0x109B7}, {0x109BE,0x109BF}, {0x10A00,0x10A03}, {0x10A05,0x10A06}, {0x10A0C,0x10A13}, + {0x10A15,0x10A17}, {0x10A19,0x10A35}, {0x10A38,0x10A3A}, {0x10A3F,0x10A3F}, {0x10A60,0x10A7C}, {0x10A80,0x10A9C}, + {0x10AC0,0x10AC7}, {0x10AC9,0x10AE6}, {0x10B00,0x10B35}, {0x10B40,0x10B55}, {0x10B60,0x10B72}, {0x10B80,0x10B91}, + {0x10C00,0x10C48}, {0x10C80,0x10CB2}, {0x10CC0,0x10CF2}, {0x10D00,0x10D27}, {0x10D30,0x10D39}, {0x10D40,0x10D65}, + {0x10D69,0x10D6D}, {0x10D6F,0x10D85}, {0x10E80,0x10EA9}, {0x10EAB,0x10EAC}, {0x10EB0,0x10EB1}, {0x10EC2,0x10EC4}, + {0x10EFC,0x10F1C}, {0x10F27,0x10F27}, {0x10F30,0x10F50}, {0x10F70,0x10F85}, {0x10FB0,0x10FC4}, {0x10FE0,0x10FF6}, + {0x11000,0x11046}, {0x11066,0x11075}, {0x1107F,0x110BA}, {0x110C2,0x110C2}, {0x110D0,0x110E8}, {0x110F0,0x110F9}, + {0x11100,0x11134}, {0x11136,0x1113F}, {0x11144,0x11147}, {0x11150,0x11173}, {0x11176,0x11176}, {0x11180,0x111C4}, + {0x111C9,0x111CC}, {0x111CE,0x111DA}, {0x111DC,0x111DC}, {0x11200,0x11211}, {0x11213,0x11237}, {0x1123E,0x11241}, + {0x11280,0x11286}, {0x11288,0x11288}, {0x1128A,0x1128D}, {0x1128F,0x1129D}, {0x1129F,0x112A8}, {0x112B0,0x112EA}, + {0x112F0,0x112F9}, {0x11300,0x11303}, {0x11305,0x1130C}, {0x1130F,0x11310}, {0x11313,0x11328}, {0x1132A,0x11330}, + {0x11332,0x11333}, {0x11335,0x11339}, {0x1133B,0x11344}, {0x11347,0x11348}, {0x1134B,0x1134D}, {0x11350,0x11350}, + {0x11357,0x11357}, {0x1135D,0x11363}, {0x11366,0x1136C}, {0x11370,0x11374}, {0x11380,0x11389}, {0x1138B,0x1138B}, + {0x1138E,0x1138E}, {0x11390,0x113B5}, {0x113B7,0x113C0}, {0x113C2,0x113C2}, {0x113C5,0x113C5}, {0x113C7,0x113CA}, + {0x113CC,0x113D3}, {0x113E1,0x113E2}, {0x11400,0x1144A}, {0x11450,0x11459}, {0x1145E,0x11461}, {0x11480,0x114C5}, + {0x114C7,0x114C7}, {0x114D0,0x114D9}, {0x11580,0x115B5}, {0x115B8,0x115C0}, {0x115D8,0x115DD}, {0x11600,0x11640}, + {0x11644,0x11644}, {0x11650,0x11659}, {0x11680,0x116B8}, {0x116C0,0x116C9}, {0x116D0,0x116E3}, {0x11700,0x1171A}, + {0x1171D,0x1172B}, {0x11730,0x11739}, {0x11740,0x11746}, {0x11800,0x1183A}, {0x118A0,0x118E9}, {0x118FF,0x11906}, + {0x11909,0x11909}, {0x1190C,0x11913}, {0x11915,0x11916}, {0x11918,0x11935}, {0x11937,0x11938}, {0x1193B,0x11943}, + {0x11950,0x11959}, {0x119A0,0x119A7}, {0x119AA,0x119D7}, {0x119DA,0x119E1}, {0x119E3,0x119E4}, {0x11A00,0x11A3E}, + {0x11A47,0x11A47}, {0x11A50,0x11A99}, {0x11A9D,0x11A9D}, {0x11AB0,0x11AF8}, {0x11BC0,0x11BE0}, {0x11BF0,0x11BF9}, + {0x11C00,0x11C08}, {0x11C0A,0x11C36}, {0x11C38,0x11C40}, {0x11C50,0x11C59}, {0x11C72,0x11C8F}, {0x11C92,0x11CA7}, + {0x11CA9,0x11CB6}, {0x11D00,0x11D06}, {0x11D08,0x11D09}, {0x11D0B,0x11D36}, {0x11D3A,0x11D3A}, {0x11D3C,0x11D3D}, + {0x11D3F,0x11D47}, {0x11D50,0x11D59}, {0x11D60,0x11D65}, {0x11D67,0x11D68}, {0x11D6A,0x11D8E}, {0x11D90,0x11D91}, + {0x11D93,0x11D98}, {0x11DA0,0x11DA9}, {0x11EE0,0x11EF6}, {0x11F00,0x11F10}, {0x11F12,0x11F3A}, {0x11F3E,0x11F42}, + {0x11F50,0x11F5A}, {0x11FB0,0x11FB0}, {0x12000,0x12399}, {0x12400,0x1246E}, {0x12480,0x12543}, {0x12F90,0x12FF0}, + {0x13000,0x1342F}, {0x13440,0x13455}, {0x13460,0x143FA}, {0x14400,0x14646}, {0x16100,0x16139}, {0x16800,0x16A38}, + {0x16A40,0x16A5E}, {0x16A60,0x16A69}, {0x16A70,0x16ABE}, {0x16AC0,0x16AC9}, {0x16AD0,0x16AED}, {0x16AF0,0x16AF4}, + {0x16B00,0x16B36}, {0x16B40,0x16B43}, {0x16B50,0x16B59}, {0x16B63,0x16B77}, {0x16B7D,0x16B8F}, {0x16D40,0x16D6C}, + {0x16D70,0x16D79}, {0x16E40,0x16E7F}, {0x16F00,0x16F4A}, {0x16F4F,0x16F87}, {0x16F8F,0x16F9F}, {0x16FE0,0x16FE1}, + {0x16FE3,0x16FE4}, {0x16FF0,0x16FF1}, {0x17000,0x187F7}, {0x18800,0x18CD5}, {0x18CFF,0x18D08}, {0x1AFF0,0x1AFF3}, + {0x1AFF5,0x1AFFB}, {0x1AFFD,0x1AFFE}, {0x1B000,0x1B122}, {0x1B132,0x1B132}, {0x1B150,0x1B152}, {0x1B155,0x1B155}, + {0x1B164,0x1B167}, {0x1B170,0x1B2FB}, {0x1BC00,0x1BC6A}, {0x1BC70,0x1BC7C}, {0x1BC80,0x1BC88}, {0x1BC90,0x1BC99}, + {0x1BC9D,0x1BC9E}, {0x1CCF0,0x1CCF9}, {0x1CF00,0x1CF2D}, {0x1CF30,0x1CF46}, {0x1D165,0x1D169}, {0x1D16D,0x1D172}, + {0x1D17B,0x1D182}, {0x1D185,0x1D18B}, {0x1D1AA,0x1D1AD}, {0x1D242,0x1D244}, {0x1D400,0x1D454}, {0x1D456,0x1D49C}, + {0x1D49E,0x1D49F}, {0x1D4A2,0x1D4A2}, {0x1D4A5,0x1D4A6}, {0x1D4A9,0x1D4AC}, {0x1D4AE,0x1D4B9}, {0x1D4BB,0x1D4BB}, + {0x1D4BD,0x1D4C3}, {0x1D4C5,0x1D505}, {0x1D507,0x1D50A}, {0x1D50D,0x1D514}, {0x1D516,0x1D51C}, {0x1D51E,0x1D539}, + {0x1D53B,0x1D53E}, {0x1D540,0x1D544}, {0x1D546,0x1D546}, {0x1D54A,0x1D550}, {0x1D552,0x1D6A5}, {0x1D6A8,0x1D6C0}, + {0x1D6C2,0x1D6DA}, {0x1D6DC,0x1D6FA}, {0x1D6FC,0x1D714}, {0x1D716,0x1D734}, {0x1D736,0x1D74E}, {0x1D750,0x1D76E}, + {0x1D770,0x1D788}, {0x1D78A,0x1D7A8}, {0x1D7AA,0x1D7C2}, {0x1D7C4,0x1D7CB}, {0x1D7CE,0x1D7FF}, {0x1DA00,0x1DA36}, + {0x1DA3B,0x1DA6C}, {0x1DA75,0x1DA75}, {0x1DA84,0x1DA84}, {0x1DA9B,0x1DA9F}, {0x1DAA1,0x1DAAF}, {0x1DF00,0x1DF1E}, + {0x1DF25,0x1DF2A}, {0x1E000,0x1E006}, {0x1E008,0x1E018}, {0x1E01B,0x1E021}, {0x1E023,0x1E024}, {0x1E026,0x1E02A}, + {0x1E030,0x1E06D}, {0x1E08F,0x1E08F}, {0x1E100,0x1E12C}, {0x1E130,0x1E13D}, {0x1E140,0x1E149}, {0x1E14E,0x1E14E}, + {0x1E290,0x1E2AE}, {0x1E2C0,0x1E2F9}, {0x1E4D0,0x1E4F9}, {0x1E5D0,0x1E5FA}, {0x1E7E0,0x1E7E6}, {0x1E7E8,0x1E7EB}, + {0x1E7ED,0x1E7EE}, {0x1E7F0,0x1E7FE}, {0x1E800,0x1E8C4}, {0x1E8D0,0x1E8D6}, {0x1E900,0x1E94B}, {0x1E950,0x1E959}, + {0x1EE00,0x1EE03}, {0x1EE05,0x1EE1F}, {0x1EE21,0x1EE22}, {0x1EE24,0x1EE24}, {0x1EE27,0x1EE27}, {0x1EE29,0x1EE32}, + {0x1EE34,0x1EE37}, {0x1EE39,0x1EE39}, {0x1EE3B,0x1EE3B}, {0x1EE42,0x1EE42}, {0x1EE47,0x1EE47}, {0x1EE49,0x1EE49}, + {0x1EE4B,0x1EE4B}, {0x1EE4D,0x1EE4F}, {0x1EE51,0x1EE52}, {0x1EE54,0x1EE54}, {0x1EE57,0x1EE57}, {0x1EE59,0x1EE59}, + {0x1EE5B,0x1EE5B}, {0x1EE5D,0x1EE5D}, {0x1EE5F,0x1EE5F}, {0x1EE61,0x1EE62}, {0x1EE64,0x1EE64}, {0x1EE67,0x1EE6A}, + {0x1EE6C,0x1EE72}, {0x1EE74,0x1EE77}, {0x1EE79,0x1EE7C}, {0x1EE7E,0x1EE7E}, {0x1EE80,0x1EE89}, {0x1EE8B,0x1EE9B}, + {0x1EEA1,0x1EEA3}, {0x1EEA5,0x1EEA9}, {0x1EEAB,0x1EEBB}, {0x1F130,0x1F149}, {0x1F150,0x1F169}, {0x1F170,0x1F189}, + {0x1FBF0,0x1FBF9}, {0x20000,0x2A6DF}, {0x2A700,0x2B739}, {0x2B740,0x2B81D}, {0x2B820,0x2CEA1}, {0x2CEB0,0x2EBE0}, + {0x2EBF0,0x2EE5D}, {0x2F800,0x2FA1D}, {0x30000,0x3134A}, {0x31350,0x323AF}, {0xE0100,0xE01EF}, +}; +const size_t k_word_n = sizeof(k_word) / sizeof(k_word[0]); + +const CpRange k_word_class[] = { + {0x30,0x39}, {0x41,0x5A}, {0x5F,0x5F}, {0x61,0x7A}, {0xAA,0xAA}, {0xB5,0xB5}, + {0xBA,0xBA}, {0xC0,0xD6}, {0xD8,0xF6}, {0xF8,0x2C1}, {0x2C6,0x2D1}, {0x2E0,0x2E4}, + {0x2EC,0x2EC}, {0x2EE,0x2EE}, {0x300,0x374}, {0x376,0x377}, {0x37A,0x37D}, {0x37F,0x37F}, + {0x386,0x386}, {0x388,0x38A}, {0x38C,0x38C}, {0x38E,0x3A1}, {0x3A3,0x3F5}, {0x3F7,0x481}, + {0x483,0x52F}, {0x531,0x556}, {0x559,0x559}, {0x560,0x588}, {0x591,0x5BD}, {0x5BF,0x5BF}, + {0x5C1,0x5C2}, {0x5C4,0x5C5}, {0x5C7,0x5C7}, {0x5D0,0x5EA}, {0x5EF,0x5F2}, {0x610,0x61A}, + {0x620,0x669}, {0x66E,0x6D3}, {0x6D5,0x6DC}, {0x6DF,0x6E8}, {0x6EA,0x6FC}, {0x6FF,0x6FF}, + {0x710,0x74A}, {0x74D,0x7B1}, {0x7C0,0x7F5}, {0x7FA,0x7FA}, {0x7FD,0x7FD}, {0x800,0x82D}, + {0x840,0x85B}, {0x860,0x86A}, {0x870,0x887}, {0x889,0x88E}, {0x897,0x8E1}, {0x8E3,0x963}, + {0x966,0x96F}, {0x971,0x983}, {0x985,0x98C}, {0x98F,0x990}, {0x993,0x9A8}, {0x9AA,0x9B0}, + {0x9B2,0x9B2}, {0x9B6,0x9B9}, {0x9BC,0x9C4}, {0x9C7,0x9C8}, {0x9CB,0x9CE}, {0x9D7,0x9D7}, + {0x9DC,0x9DD}, {0x9DF,0x9E3}, {0x9E6,0x9F1}, {0x9FC,0x9FC}, {0x9FE,0x9FE}, {0xA01,0xA03}, + {0xA05,0xA0A}, {0xA0F,0xA10}, {0xA13,0xA28}, {0xA2A,0xA30}, {0xA32,0xA33}, {0xA35,0xA36}, + {0xA38,0xA39}, {0xA3C,0xA3C}, {0xA3E,0xA42}, {0xA47,0xA48}, {0xA4B,0xA4D}, {0xA51,0xA51}, + {0xA59,0xA5C}, {0xA5E,0xA5E}, {0xA66,0xA75}, {0xA81,0xA83}, {0xA85,0xA8D}, {0xA8F,0xA91}, + {0xA93,0xAA8}, {0xAAA,0xAB0}, {0xAB2,0xAB3}, {0xAB5,0xAB9}, {0xABC,0xAC5}, {0xAC7,0xAC9}, + {0xACB,0xACD}, {0xAD0,0xAD0}, {0xAE0,0xAE3}, {0xAE6,0xAEF}, {0xAF9,0xAFF}, {0xB01,0xB03}, + {0xB05,0xB0C}, {0xB0F,0xB10}, {0xB13,0xB28}, {0xB2A,0xB30}, {0xB32,0xB33}, {0xB35,0xB39}, + {0xB3C,0xB44}, {0xB47,0xB48}, {0xB4B,0xB4D}, {0xB55,0xB57}, {0xB5C,0xB5D}, {0xB5F,0xB63}, + {0xB66,0xB6F}, {0xB71,0xB71}, {0xB82,0xB83}, {0xB85,0xB8A}, {0xB8E,0xB90}, {0xB92,0xB95}, + {0xB99,0xB9A}, {0xB9C,0xB9C}, {0xB9E,0xB9F}, {0xBA3,0xBA4}, {0xBA8,0xBAA}, {0xBAE,0xBB9}, + {0xBBE,0xBC2}, {0xBC6,0xBC8}, {0xBCA,0xBCD}, {0xBD0,0xBD0}, {0xBD7,0xBD7}, {0xBE6,0xBEF}, + {0xC00,0xC0C}, {0xC0E,0xC10}, {0xC12,0xC28}, {0xC2A,0xC39}, {0xC3C,0xC44}, {0xC46,0xC48}, + {0xC4A,0xC4D}, {0xC55,0xC56}, {0xC58,0xC5A}, {0xC5D,0xC5D}, {0xC60,0xC63}, {0xC66,0xC6F}, + {0xC80,0xC83}, {0xC85,0xC8C}, {0xC8E,0xC90}, {0xC92,0xCA8}, {0xCAA,0xCB3}, {0xCB5,0xCB9}, + {0xCBC,0xCC4}, {0xCC6,0xCC8}, {0xCCA,0xCCD}, {0xCD5,0xCD6}, {0xCDD,0xCDE}, {0xCE0,0xCE3}, + {0xCE6,0xCEF}, {0xCF1,0xCF3}, {0xD00,0xD0C}, {0xD0E,0xD10}, {0xD12,0xD44}, {0xD46,0xD48}, + {0xD4A,0xD4E}, {0xD54,0xD57}, {0xD5F,0xD63}, {0xD66,0xD6F}, {0xD7A,0xD7F}, {0xD81,0xD83}, + {0xD85,0xD96}, {0xD9A,0xDB1}, {0xDB3,0xDBB}, {0xDBD,0xDBD}, {0xDC0,0xDC6}, {0xDCA,0xDCA}, + {0xDCF,0xDD4}, {0xDD6,0xDD6}, {0xDD8,0xDDF}, {0xDE6,0xDEF}, {0xDF2,0xDF3}, {0xE01,0xE3A}, + {0xE40,0xE4E}, {0xE50,0xE59}, {0xE81,0xE82}, {0xE84,0xE84}, {0xE86,0xE8A}, {0xE8C,0xEA3}, + {0xEA5,0xEA5}, {0xEA7,0xEBD}, {0xEC0,0xEC4}, {0xEC6,0xEC6}, {0xEC8,0xECE}, {0xED0,0xED9}, + {0xEDC,0xEDF}, {0xF00,0xF00}, {0xF18,0xF19}, {0xF20,0xF29}, {0xF35,0xF35}, {0xF37,0xF37}, + {0xF39,0xF39}, {0xF3E,0xF47}, {0xF49,0xF6C}, {0xF71,0xF84}, {0xF86,0xF97}, {0xF99,0xFBC}, + {0xFC6,0xFC6}, {0x1000,0x1049}, {0x1050,0x109D}, {0x10A0,0x10C5}, {0x10C7,0x10C7}, {0x10CD,0x10CD}, + {0x10D0,0x10FA}, {0x10FC,0x1248}, {0x124A,0x124D}, {0x1250,0x1256}, {0x1258,0x1258}, {0x125A,0x125D}, + {0x1260,0x1288}, {0x128A,0x128D}, {0x1290,0x12B0}, {0x12B2,0x12B5}, {0x12B8,0x12BE}, {0x12C0,0x12C0}, + {0x12C2,0x12C5}, {0x12C8,0x12D6}, {0x12D8,0x1310}, {0x1312,0x1315}, {0x1318,0x135A}, {0x135D,0x135F}, + {0x1380,0x138F}, {0x13A0,0x13F5}, {0x13F8,0x13FD}, {0x1401,0x166C}, {0x166F,0x167F}, {0x1681,0x169A}, + {0x16A0,0x16EA}, {0x16EE,0x16F8}, {0x1700,0x1715}, {0x171F,0x1734}, {0x1740,0x1753}, {0x1760,0x176C}, + {0x176E,0x1770}, {0x1772,0x1773}, {0x1780,0x17D3}, {0x17D7,0x17D7}, {0x17DC,0x17DD}, {0x17E0,0x17E9}, + {0x180B,0x180D}, {0x180F,0x1819}, {0x1820,0x1878}, {0x1880,0x18AA}, {0x18B0,0x18F5}, {0x1900,0x191E}, + {0x1920,0x192B}, {0x1930,0x193B}, {0x1946,0x196D}, {0x1970,0x1974}, {0x1980,0x19AB}, {0x19B0,0x19C9}, + {0x19D0,0x19D9}, {0x1A00,0x1A1B}, {0x1A20,0x1A5E}, {0x1A60,0x1A7C}, {0x1A7F,0x1A89}, {0x1A90,0x1A99}, + {0x1AA7,0x1AA7}, {0x1AB0,0x1ACE}, {0x1B00,0x1B4C}, {0x1B50,0x1B59}, {0x1B6B,0x1B73}, {0x1B80,0x1BF3}, + {0x1C00,0x1C37}, {0x1C40,0x1C49}, {0x1C4D,0x1C7D}, {0x1C80,0x1C8A}, {0x1C90,0x1CBA}, {0x1CBD,0x1CBF}, + {0x1CD0,0x1CD2}, {0x1CD4,0x1CFA}, {0x1D00,0x1F15}, {0x1F18,0x1F1D}, {0x1F20,0x1F45}, {0x1F48,0x1F4D}, + {0x1F50,0x1F57}, {0x1F59,0x1F59}, {0x1F5B,0x1F5B}, {0x1F5D,0x1F5D}, {0x1F5F,0x1F7D}, {0x1F80,0x1FB4}, + {0x1FB6,0x1FBC}, {0x1FBE,0x1FBE}, {0x1FC2,0x1FC4}, {0x1FC6,0x1FCC}, {0x1FD0,0x1FD3}, {0x1FD6,0x1FDB}, + {0x1FE0,0x1FEC}, {0x1FF2,0x1FF4}, {0x1FF6,0x1FFC}, {0x203F,0x2040}, {0x2054,0x2054}, {0x2071,0x2071}, + {0x207F,0x207F}, {0x2090,0x209C}, {0x20D0,0x20F0}, {0x2102,0x2102}, {0x2107,0x2107}, {0x210A,0x2113}, + {0x2115,0x2115}, {0x2119,0x211D}, {0x2124,0x2124}, {0x2126,0x2126}, {0x2128,0x2128}, {0x212A,0x212D}, + {0x212F,0x2139}, {0x213C,0x213F}, {0x2145,0x2149}, {0x214E,0x214E}, {0x2160,0x2188}, {0x24B6,0x24E9}, + {0x2C00,0x2CE4}, {0x2CEB,0x2CF3}, {0x2D00,0x2D25}, {0x2D27,0x2D27}, {0x2D2D,0x2D2D}, {0x2D30,0x2D67}, + {0x2D6F,0x2D6F}, {0x2D7F,0x2D96}, {0x2DA0,0x2DA6}, {0x2DA8,0x2DAE}, {0x2DB0,0x2DB6}, {0x2DB8,0x2DBE}, + {0x2DC0,0x2DC6}, {0x2DC8,0x2DCE}, {0x2DD0,0x2DD6}, {0x2DD8,0x2DDE}, {0x2DE0,0x2DFF}, {0x2E2F,0x2E2F}, + {0x3005,0x3007}, {0x3021,0x302F}, {0x3031,0x3035}, {0x3038,0x303C}, {0x3041,0x3096}, {0x3099,0x309A}, + {0x309D,0x309F}, {0x30A1,0x30FA}, {0x30FC,0x30FF}, {0x3105,0x312F}, {0x3131,0x318E}, {0x31A0,0x31BF}, + {0x31F0,0x31FF}, {0x3400,0x4DBF}, {0x4E00,0xA48C}, {0xA4D0,0xA4FD}, {0xA500,0xA60C}, {0xA610,0xA62B}, + {0xA640,0xA672}, {0xA674,0xA67D}, {0xA67F,0xA6F1}, {0xA717,0xA71F}, {0xA722,0xA788}, {0xA78B,0xA7CD}, + {0xA7D0,0xA7D1}, {0xA7D3,0xA7D3}, {0xA7D5,0xA7DC}, {0xA7F2,0xA827}, {0xA82C,0xA82C}, {0xA840,0xA873}, + {0xA880,0xA8C5}, {0xA8D0,0xA8D9}, {0xA8E0,0xA8F7}, {0xA8FB,0xA8FB}, {0xA8FD,0xA92D}, {0xA930,0xA953}, + {0xA960,0xA97C}, {0xA980,0xA9C0}, {0xA9CF,0xA9D9}, {0xA9E0,0xA9FE}, {0xAA00,0xAA36}, {0xAA40,0xAA4D}, + {0xAA50,0xAA59}, {0xAA60,0xAA76}, {0xAA7A,0xAAC2}, {0xAADB,0xAADD}, {0xAAE0,0xAAEF}, {0xAAF2,0xAAF6}, + {0xAB01,0xAB06}, {0xAB09,0xAB0E}, {0xAB11,0xAB16}, {0xAB20,0xAB26}, {0xAB28,0xAB2E}, {0xAB30,0xAB5A}, + {0xAB5C,0xAB69}, {0xAB70,0xABEA}, {0xABEC,0xABED}, {0xABF0,0xABF9}, {0xAC00,0xD7A3}, {0xD7B0,0xD7C6}, + {0xD7CB,0xD7FB}, {0xF900,0xFA6D}, {0xFA70,0xFAD9}, {0xFB00,0xFB06}, {0xFB13,0xFB17}, {0xFB1D,0xFB28}, + {0xFB2A,0xFB36}, {0xFB38,0xFB3C}, {0xFB3E,0xFB3E}, {0xFB40,0xFB41}, {0xFB43,0xFB44}, {0xFB46,0xFBB1}, + {0xFBD3,0xFD3D}, {0xFD50,0xFD8F}, {0xFD92,0xFDC7}, {0xFDF0,0xFDFB}, {0xFE00,0xFE0F}, {0xFE20,0xFE2F}, + {0xFE33,0xFE34}, {0xFE4D,0xFE4F}, {0xFE70,0xFE74}, {0xFE76,0xFEFC}, {0xFF10,0xFF19}, {0xFF21,0xFF3A}, + {0xFF3F,0xFF3F}, {0xFF41,0xFF5A}, {0xFF66,0xFFBE}, {0xFFC2,0xFFC7}, {0xFFCA,0xFFCF}, {0xFFD2,0xFFD7}, + {0xFFDA,0xFFDC}, {0x10000,0x1000B}, {0x1000D,0x10026}, {0x10028,0x1003A}, {0x1003C,0x1003D}, {0x1003F,0x1004D}, + {0x10050,0x1005D}, {0x10080,0x100FA}, {0x10140,0x10174}, {0x101FD,0x101FD}, {0x10280,0x1029C}, {0x102A0,0x102D0}, + {0x102E0,0x102E0}, {0x10300,0x1031F}, {0x1032D,0x1034A}, {0x10350,0x1037A}, {0x10380,0x1039D}, {0x103A0,0x103C3}, + {0x103C8,0x103CF}, {0x103D1,0x103D5}, {0x10400,0x1049D}, {0x104A0,0x104A9}, {0x104B0,0x104D3}, {0x104D8,0x104FB}, + {0x10500,0x10527}, {0x10530,0x10563}, {0x10570,0x1057A}, {0x1057C,0x1058A}, {0x1058C,0x10592}, {0x10594,0x10595}, + {0x10597,0x105A1}, {0x105A3,0x105B1}, {0x105B3,0x105B9}, {0x105BB,0x105BC}, {0x105C0,0x105F3}, {0x10600,0x10736}, + {0x10740,0x10755}, {0x10760,0x10767}, {0x10780,0x10785}, {0x10787,0x107B0}, {0x107B2,0x107BA}, {0x10800,0x10805}, + {0x10808,0x10808}, {0x1080A,0x10835}, {0x10837,0x10838}, {0x1083C,0x1083C}, {0x1083F,0x10855}, {0x10860,0x10876}, + {0x10880,0x1089E}, {0x108E0,0x108F2}, {0x108F4,0x108F5}, {0x10900,0x10915}, {0x10920,0x10939}, {0x10980,0x109B7}, + {0x109BE,0x109BF}, {0x10A00,0x10A03}, {0x10A05,0x10A06}, {0x10A0C,0x10A13}, {0x10A15,0x10A17}, {0x10A19,0x10A35}, + {0x10A38,0x10A3A}, {0x10A3F,0x10A3F}, {0x10A60,0x10A7C}, {0x10A80,0x10A9C}, {0x10AC0,0x10AC7}, {0x10AC9,0x10AE6}, + {0x10B00,0x10B35}, {0x10B40,0x10B55}, {0x10B60,0x10B72}, {0x10B80,0x10B91}, {0x10C00,0x10C48}, {0x10C80,0x10CB2}, + {0x10CC0,0x10CF2}, {0x10D00,0x10D27}, {0x10D30,0x10D39}, {0x10D40,0x10D65}, {0x10D69,0x10D6D}, {0x10D6F,0x10D85}, + {0x10E80,0x10EA9}, {0x10EAB,0x10EAC}, {0x10EB0,0x10EB1}, {0x10EC2,0x10EC4}, {0x10EFC,0x10F1C}, {0x10F27,0x10F27}, + {0x10F30,0x10F50}, {0x10F70,0x10F85}, {0x10FB0,0x10FC4}, {0x10FE0,0x10FF6}, {0x11000,0x11046}, {0x11066,0x11075}, + {0x1107F,0x110BA}, {0x110C2,0x110C2}, {0x110D0,0x110E8}, {0x110F0,0x110F9}, {0x11100,0x11134}, {0x11136,0x1113F}, + {0x11144,0x11147}, {0x11150,0x11173}, {0x11176,0x11176}, {0x11180,0x111C4}, {0x111C9,0x111CC}, {0x111CE,0x111DA}, + {0x111DC,0x111DC}, {0x11200,0x11211}, {0x11213,0x11237}, {0x1123E,0x11241}, {0x11280,0x11286}, {0x11288,0x11288}, + {0x1128A,0x1128D}, {0x1128F,0x1129D}, {0x1129F,0x112A8}, {0x112B0,0x112EA}, {0x112F0,0x112F9}, {0x11300,0x11303}, + {0x11305,0x1130C}, {0x1130F,0x11310}, {0x11313,0x11328}, {0x1132A,0x11330}, {0x11332,0x11333}, {0x11335,0x11339}, + {0x1133B,0x11344}, {0x11347,0x11348}, {0x1134B,0x1134D}, {0x11350,0x11350}, {0x11357,0x11357}, {0x1135D,0x11363}, + {0x11366,0x1136C}, {0x11370,0x11374}, {0x11380,0x11389}, {0x1138B,0x1138B}, {0x1138E,0x1138E}, {0x11390,0x113B5}, + {0x113B7,0x113C0}, {0x113C2,0x113C2}, {0x113C5,0x113C5}, {0x113C7,0x113CA}, {0x113CC,0x113D3}, {0x113E1,0x113E2}, + {0x11400,0x1144A}, {0x11450,0x11459}, {0x1145E,0x11461}, {0x11480,0x114C5}, {0x114C7,0x114C7}, {0x114D0,0x114D9}, + {0x11580,0x115B5}, {0x115B8,0x115C0}, {0x115D8,0x115DD}, {0x11600,0x11640}, {0x11644,0x11644}, {0x11650,0x11659}, + {0x11680,0x116B8}, {0x116C0,0x116C9}, {0x116D0,0x116E3}, {0x11700,0x1171A}, {0x1171D,0x1172B}, {0x11730,0x11739}, + {0x11740,0x11746}, {0x11800,0x1183A}, {0x118A0,0x118E9}, {0x118FF,0x11906}, {0x11909,0x11909}, {0x1190C,0x11913}, + {0x11915,0x11916}, {0x11918,0x11935}, {0x11937,0x11938}, {0x1193B,0x11943}, {0x11950,0x11959}, {0x119A0,0x119A7}, + {0x119AA,0x119D7}, {0x119DA,0x119E1}, {0x119E3,0x119E4}, {0x11A00,0x11A3E}, {0x11A47,0x11A47}, {0x11A50,0x11A99}, + {0x11A9D,0x11A9D}, {0x11AB0,0x11AF8}, {0x11BC0,0x11BE0}, {0x11BF0,0x11BF9}, {0x11C00,0x11C08}, {0x11C0A,0x11C36}, + {0x11C38,0x11C40}, {0x11C50,0x11C59}, {0x11C72,0x11C8F}, {0x11C92,0x11CA7}, {0x11CA9,0x11CB6}, {0x11D00,0x11D06}, + {0x11D08,0x11D09}, {0x11D0B,0x11D36}, {0x11D3A,0x11D3A}, {0x11D3C,0x11D3D}, {0x11D3F,0x11D47}, {0x11D50,0x11D59}, + {0x11D60,0x11D65}, {0x11D67,0x11D68}, {0x11D6A,0x11D8E}, {0x11D90,0x11D91}, {0x11D93,0x11D98}, {0x11DA0,0x11DA9}, + {0x11EE0,0x11EF6}, {0x11F00,0x11F10}, {0x11F12,0x11F3A}, {0x11F3E,0x11F42}, {0x11F50,0x11F5A}, {0x11FB0,0x11FB0}, + {0x12000,0x12399}, {0x12400,0x1246E}, {0x12480,0x12543}, {0x12F90,0x12FF0}, {0x13000,0x1342F}, {0x13440,0x13455}, + {0x13460,0x143FA}, {0x14400,0x14646}, {0x16100,0x16139}, {0x16800,0x16A38}, {0x16A40,0x16A5E}, {0x16A60,0x16A69}, + {0x16A70,0x16ABE}, {0x16AC0,0x16AC9}, {0x16AD0,0x16AED}, {0x16AF0,0x16AF4}, {0x16B00,0x16B36}, {0x16B40,0x16B43}, + {0x16B50,0x16B59}, {0x16B63,0x16B77}, {0x16B7D,0x16B8F}, {0x16D40,0x16D6C}, {0x16D70,0x16D79}, {0x16E40,0x16E7F}, + {0x16F00,0x16F4A}, {0x16F4F,0x16F87}, {0x16F8F,0x16F9F}, {0x16FE0,0x16FE1}, {0x16FE3,0x16FE4}, {0x16FF0,0x16FF1}, + {0x17000,0x187F7}, {0x18800,0x18CD5}, {0x18CFF,0x18D08}, {0x1AFF0,0x1AFF3}, {0x1AFF5,0x1AFFB}, {0x1AFFD,0x1AFFE}, + {0x1B000,0x1B122}, {0x1B132,0x1B132}, {0x1B150,0x1B152}, {0x1B155,0x1B155}, {0x1B164,0x1B167}, {0x1B170,0x1B2FB}, + {0x1BC00,0x1BC6A}, {0x1BC70,0x1BC7C}, {0x1BC80,0x1BC88}, {0x1BC90,0x1BC99}, {0x1BC9D,0x1BC9E}, {0x1CCF0,0x1CCF9}, + {0x1CF00,0x1CF2D}, {0x1CF30,0x1CF46}, {0x1D165,0x1D169}, {0x1D16D,0x1D172}, {0x1D17B,0x1D182}, {0x1D185,0x1D18B}, + {0x1D1AA,0x1D1AD}, {0x1D242,0x1D244}, {0x1D400,0x1D454}, {0x1D456,0x1D49C}, {0x1D49E,0x1D49F}, {0x1D4A2,0x1D4A2}, + {0x1D4A5,0x1D4A6}, {0x1D4A9,0x1D4AC}, {0x1D4AE,0x1D4B9}, {0x1D4BB,0x1D4BB}, {0x1D4BD,0x1D4C3}, {0x1D4C5,0x1D505}, + {0x1D507,0x1D50A}, {0x1D50D,0x1D514}, {0x1D516,0x1D51C}, {0x1D51E,0x1D539}, {0x1D53B,0x1D53E}, {0x1D540,0x1D544}, + {0x1D546,0x1D546}, {0x1D54A,0x1D550}, {0x1D552,0x1D6A5}, {0x1D6A8,0x1D6C0}, {0x1D6C2,0x1D6DA}, {0x1D6DC,0x1D6FA}, + {0x1D6FC,0x1D714}, {0x1D716,0x1D734}, {0x1D736,0x1D74E}, {0x1D750,0x1D76E}, {0x1D770,0x1D788}, {0x1D78A,0x1D7A8}, + {0x1D7AA,0x1D7C2}, {0x1D7C4,0x1D7CB}, {0x1D7CE,0x1D7FF}, {0x1DA00,0x1DA36}, {0x1DA3B,0x1DA6C}, {0x1DA75,0x1DA75}, + {0x1DA84,0x1DA84}, {0x1DA9B,0x1DA9F}, {0x1DAA1,0x1DAAF}, {0x1DF00,0x1DF1E}, {0x1DF25,0x1DF2A}, {0x1E000,0x1E006}, + {0x1E008,0x1E018}, {0x1E01B,0x1E021}, {0x1E023,0x1E024}, {0x1E026,0x1E02A}, {0x1E030,0x1E06D}, {0x1E08F,0x1E08F}, + {0x1E100,0x1E12C}, {0x1E130,0x1E13D}, {0x1E140,0x1E149}, {0x1E14E,0x1E14E}, {0x1E290,0x1E2AE}, {0x1E2C0,0x1E2F9}, + {0x1E4D0,0x1E4F9}, {0x1E5D0,0x1E5FA}, {0x1E7E0,0x1E7E6}, {0x1E7E8,0x1E7EB}, {0x1E7ED,0x1E7EE}, {0x1E7F0,0x1E7FE}, + {0x1E800,0x1E8C4}, {0x1E8D0,0x1E8D6}, {0x1E900,0x1E94B}, {0x1E950,0x1E959}, {0x1EE00,0x1EE03}, {0x1EE05,0x1EE1F}, + {0x1EE21,0x1EE22}, {0x1EE24,0x1EE24}, {0x1EE27,0x1EE27}, {0x1EE29,0x1EE32}, {0x1EE34,0x1EE37}, {0x1EE39,0x1EE39}, + {0x1EE3B,0x1EE3B}, {0x1EE42,0x1EE42}, {0x1EE47,0x1EE47}, {0x1EE49,0x1EE49}, {0x1EE4B,0x1EE4B}, {0x1EE4D,0x1EE4F}, + {0x1EE51,0x1EE52}, {0x1EE54,0x1EE54}, {0x1EE57,0x1EE57}, {0x1EE59,0x1EE59}, {0x1EE5B,0x1EE5B}, {0x1EE5D,0x1EE5D}, + {0x1EE5F,0x1EE5F}, {0x1EE61,0x1EE62}, {0x1EE64,0x1EE64}, {0x1EE67,0x1EE6A}, {0x1EE6C,0x1EE72}, {0x1EE74,0x1EE77}, + {0x1EE79,0x1EE7C}, {0x1EE7E,0x1EE7E}, {0x1EE80,0x1EE89}, {0x1EE8B,0x1EE9B}, {0x1EEA1,0x1EEA3}, {0x1EEA5,0x1EEA9}, + {0x1EEAB,0x1EEBB}, {0x1F130,0x1F149}, {0x1F150,0x1F169}, {0x1F170,0x1F189}, {0x1FBF0,0x1FBF9}, {0x20000,0x2A6DF}, + {0x2A700,0x2B739}, {0x2B740,0x2B81D}, {0x2B820,0x2CEA1}, {0x2CEB0,0x2EBE0}, {0x2EBF0,0x2EE5D}, {0x2F800,0x2FA1D}, + {0x30000,0x3134A}, {0x31350,0x323AF}, {0xE0100,0xE01EF}, +}; +const size_t k_word_class_n = sizeof(k_word_class) / sizeof(k_word_class[0]); + +const CpRange k_script_Han[] = { + {0x2E80,0x2E99}, {0x2E9B,0x2EF3}, {0x2F00,0x2FD5}, {0x3005,0x3005}, {0x3007,0x3007}, {0x3021,0x3029}, + {0x3038,0x303B}, {0x3400,0x4DBF}, {0x4E00,0x9FFF}, {0xF900,0xFA6D}, {0xFA70,0xFAD9}, {0x16FE2,0x16FE3}, + {0x16FF0,0x16FF1}, {0x20000,0x2A6DF}, {0x2A700,0x2B739}, {0x2B740,0x2B81D}, {0x2B820,0x2CEA1}, {0x2CEB0,0x2EBE0}, + {0x2EBF0,0x2EE5D}, {0x2F800,0x2FA1D}, {0x30000,0x3134A}, {0x31350,0x323AF}, +}; +const size_t k_script_Han_n = sizeof(k_script_Han) / sizeof(k_script_Han[0]); + +const CpRange k_script_Hiragana[] = { + {0x3041,0x3096}, {0x309D,0x309F}, {0x1B001,0x1B11F}, {0x1B132,0x1B132}, {0x1B150,0x1B152}, {0x1F200,0x1F200}, +}; +const size_t k_script_Hiragana_n = sizeof(k_script_Hiragana) / sizeof(k_script_Hiragana[0]); + +const CpRange k_script_Katakana[] = { + {0x30A1,0x30FA}, {0x30FD,0x30FF}, {0x31F0,0x31FF}, {0x32D0,0x32FE}, {0x3300,0x3357}, {0xFF66,0xFF6F}, + {0xFF71,0xFF9D}, {0x1AFF0,0x1AFF3}, {0x1AFF5,0x1AFFB}, {0x1AFFD,0x1AFFE}, {0x1B000,0x1B000}, {0x1B120,0x1B122}, + {0x1B155,0x1B155}, {0x1B164,0x1B167}, +}; +const size_t k_script_Katakana_n = sizeof(k_script_Katakana) / sizeof(k_script_Katakana[0]); + +const CpRange k_script_Hangul[] = { + {0x1100,0x11FF}, {0x302E,0x302F}, {0x3131,0x318E}, {0x3200,0x321E}, {0x3260,0x327E}, {0xA960,0xA97C}, + {0xAC00,0xD7A3}, {0xD7B0,0xD7C6}, {0xD7CB,0xD7FB}, {0xFFA0,0xFFBE}, {0xFFC2,0xFFC7}, {0xFFCA,0xFFCF}, + {0xFFD2,0xFFD7}, {0xFFDA,0xFFDC}, +}; +const size_t k_script_Hangul_n = sizeof(k_script_Hangul) / sizeof(k_script_Hangul[0]); + +const CpRange k_script_Bopomofo[] = { + {0x2EA,0x2EB}, {0x3105,0x312F}, {0x31A0,0x31BF}, +}; +const size_t k_script_Bopomofo_n = sizeof(k_script_Bopomofo) / sizeof(k_script_Bopomofo[0]); + +const CpRange k_script_Latin[] = { + {0x41,0x5A}, {0x61,0x7A}, {0xAA,0xAA}, {0xBA,0xBA}, {0xC0,0xD6}, {0xD8,0xF6}, + {0xF8,0x2B8}, {0x2E0,0x2E4}, {0x1D00,0x1D25}, {0x1D2C,0x1D5C}, {0x1D62,0x1D65}, {0x1D6B,0x1D77}, + {0x1D79,0x1DBE}, {0x1E00,0x1EFF}, {0x2071,0x2071}, {0x207F,0x207F}, {0x2090,0x209C}, {0x212A,0x212B}, + {0x2132,0x2132}, {0x214E,0x214E}, {0x2160,0x2188}, {0x2C60,0x2C7F}, {0xA722,0xA787}, {0xA78B,0xA7CD}, + {0xA7D0,0xA7D1}, {0xA7D3,0xA7D3}, {0xA7D5,0xA7DC}, {0xA7F2,0xA7FF}, {0xAB30,0xAB5A}, {0xAB5C,0xAB64}, + {0xAB66,0xAB69}, {0xFB00,0xFB06}, {0xFF21,0xFF3A}, {0xFF41,0xFF5A}, {0x10780,0x10785}, {0x10787,0x107B0}, + {0x107B2,0x107BA}, {0x1DF00,0x1DF1E}, {0x1DF25,0x1DF2A}, +}; +const size_t k_script_Latin_n = sizeof(k_script_Latin) / sizeof(k_script_Latin[0]); + +const CpRange k_script_Greek[] = { + {0x370,0x373}, {0x375,0x377}, {0x37A,0x37D}, {0x37F,0x37F}, {0x384,0x384}, {0x386,0x386}, + {0x388,0x38A}, {0x38C,0x38C}, {0x38E,0x3A1}, {0x3A3,0x3E1}, {0x3F0,0x3FF}, {0x1D26,0x1D2A}, + {0x1D5D,0x1D61}, {0x1D66,0x1D6A}, {0x1DBF,0x1DBF}, {0x1F00,0x1F15}, {0x1F18,0x1F1D}, {0x1F20,0x1F45}, + {0x1F48,0x1F4D}, {0x1F50,0x1F57}, {0x1F59,0x1F59}, {0x1F5B,0x1F5B}, {0x1F5D,0x1F5D}, {0x1F5F,0x1F7D}, + {0x1F80,0x1FB4}, {0x1FB6,0x1FC4}, {0x1FC6,0x1FD3}, {0x1FD6,0x1FDB}, {0x1FDD,0x1FEF}, {0x1FF2,0x1FF4}, + {0x1FF6,0x1FFE}, {0x2126,0x2126}, {0xAB65,0xAB65}, {0x10140,0x1018E}, {0x101A0,0x101A0}, {0x1D200,0x1D245}, +}; +const size_t k_script_Greek_n = sizeof(k_script_Greek) / sizeof(k_script_Greek[0]); + +const CpRange k_script_Cyrillic[] = { + {0x400,0x484}, {0x487,0x52F}, {0x1C80,0x1C8A}, {0x1D2B,0x1D2B}, {0x1D78,0x1D78}, {0x2DE0,0x2DFF}, + {0xA640,0xA69F}, {0xFE2E,0xFE2F}, {0x1E030,0x1E06D}, {0x1E08F,0x1E08F}, +}; +const size_t k_script_Cyrillic_n = sizeof(k_script_Cyrillic) / sizeof(k_script_Cyrillic[0]); + +const CpRange k_script_Armenian[] = { + {0x531,0x556}, {0x559,0x58A}, {0x58D,0x58F}, {0xFB13,0xFB17}, +}; +const size_t k_script_Armenian_n = sizeof(k_script_Armenian) / sizeof(k_script_Armenian[0]); + +const CpRange k_script_Hebrew[] = { + {0x591,0x5C7}, {0x5D0,0x5EA}, {0x5EF,0x5F4}, {0xFB1D,0xFB36}, {0xFB38,0xFB3C}, {0xFB3E,0xFB3E}, + {0xFB40,0xFB41}, {0xFB43,0xFB44}, {0xFB46,0xFB4F}, +}; +const size_t k_script_Hebrew_n = sizeof(k_script_Hebrew) / sizeof(k_script_Hebrew[0]); + +const CpRange k_script_Arabic[] = { + {0x600,0x604}, {0x606,0x60B}, {0x60D,0x61A}, {0x61C,0x61E}, {0x620,0x63F}, {0x641,0x64A}, + {0x656,0x66F}, {0x671,0x6DC}, {0x6DE,0x6FF}, {0x750,0x77F}, {0x870,0x88E}, {0x890,0x891}, + {0x897,0x8E1}, {0x8E3,0x8FF}, {0xFB50,0xFBC2}, {0xFBD3,0xFD3D}, {0xFD40,0xFD8F}, {0xFD92,0xFDC7}, + {0xFDCF,0xFDCF}, {0xFDF0,0xFDFF}, {0xFE70,0xFE74}, {0xFE76,0xFEFC}, {0x10E60,0x10E7E}, {0x10EC2,0x10EC4}, + {0x10EFC,0x10EFF}, {0x1EE00,0x1EE03}, {0x1EE05,0x1EE1F}, {0x1EE21,0x1EE22}, {0x1EE24,0x1EE24}, {0x1EE27,0x1EE27}, + {0x1EE29,0x1EE32}, {0x1EE34,0x1EE37}, {0x1EE39,0x1EE39}, {0x1EE3B,0x1EE3B}, {0x1EE42,0x1EE42}, {0x1EE47,0x1EE47}, + {0x1EE49,0x1EE49}, {0x1EE4B,0x1EE4B}, {0x1EE4D,0x1EE4F}, {0x1EE51,0x1EE52}, {0x1EE54,0x1EE54}, {0x1EE57,0x1EE57}, + {0x1EE59,0x1EE59}, {0x1EE5B,0x1EE5B}, {0x1EE5D,0x1EE5D}, {0x1EE5F,0x1EE5F}, {0x1EE61,0x1EE62}, {0x1EE64,0x1EE64}, + {0x1EE67,0x1EE6A}, {0x1EE6C,0x1EE72}, {0x1EE74,0x1EE77}, {0x1EE79,0x1EE7C}, {0x1EE7E,0x1EE7E}, {0x1EE80,0x1EE89}, + {0x1EE8B,0x1EE9B}, {0x1EEA1,0x1EEA3}, {0x1EEA5,0x1EEA9}, {0x1EEAB,0x1EEBB}, {0x1EEF0,0x1EEF1}, +}; +const size_t k_script_Arabic_n = sizeof(k_script_Arabic) / sizeof(k_script_Arabic[0]); + +const CpRange k_script_Thai[] = { + {0xE01,0xE3A}, {0xE40,0xE5B}, +}; +const size_t k_script_Thai_n = sizeof(k_script_Thai) / sizeof(k_script_Thai[0]); + +const CpRange k_script_Lao[] = { + {0xE81,0xE82}, {0xE84,0xE84}, {0xE86,0xE8A}, {0xE8C,0xEA3}, {0xEA5,0xEA5}, {0xEA7,0xEBD}, + {0xEC0,0xEC4}, {0xEC6,0xEC6}, {0xEC8,0xECE}, {0xED0,0xED9}, {0xEDC,0xEDF}, +}; +const size_t k_script_Lao_n = sizeof(k_script_Lao) / sizeof(k_script_Lao[0]); + +const CpRange k_script_Khmer[] = { + {0x1780,0x17DD}, {0x17E0,0x17E9}, {0x17F0,0x17F9}, {0x19E0,0x19FF}, +}; +const size_t k_script_Khmer_n = sizeof(k_script_Khmer) / sizeof(k_script_Khmer[0]); + +const CpRange k_script_Myanmar[] = { + {0x1000,0x109F}, {0xA9E0,0xA9FE}, {0xAA60,0xAA7F}, {0x116D0,0x116E3}, +}; +const size_t k_script_Myanmar_n = sizeof(k_script_Myanmar) / sizeof(k_script_Myanmar[0]); + +const CpRange k_script_Tibetan[] = { + {0xF00,0xF47}, {0xF49,0xF6C}, {0xF71,0xF97}, {0xF99,0xFBC}, {0xFBE,0xFCC}, {0xFCE,0xFD4}, + {0xFD9,0xFDA}, +}; +const size_t k_script_Tibetan_n = sizeof(k_script_Tibetan) / sizeof(k_script_Tibetan[0]); + +const CpRange k_script_Devanagari[] = { + {0x900,0x950}, {0x955,0x963}, {0x966,0x97F}, {0xA8E0,0xA8FF}, {0x11B00,0x11B09}, +}; +const size_t k_script_Devanagari_n = sizeof(k_script_Devanagari) / sizeof(k_script_Devanagari[0]); + +const CpRange k_script_Bengali[] = { + {0x980,0x983}, {0x985,0x98C}, {0x98F,0x990}, {0x993,0x9A8}, {0x9AA,0x9B0}, {0x9B2,0x9B2}, + {0x9B6,0x9B9}, {0x9BC,0x9C4}, {0x9C7,0x9C8}, {0x9CB,0x9CE}, {0x9D7,0x9D7}, {0x9DC,0x9DD}, + {0x9DF,0x9E3}, {0x9E6,0x9FE}, +}; +const size_t k_script_Bengali_n = sizeof(k_script_Bengali) / sizeof(k_script_Bengali[0]); + +const CpRange k_script_Gurmukhi[] = { + {0xA01,0xA03}, {0xA05,0xA0A}, {0xA0F,0xA10}, {0xA13,0xA28}, {0xA2A,0xA30}, {0xA32,0xA33}, + {0xA35,0xA36}, {0xA38,0xA39}, {0xA3C,0xA3C}, {0xA3E,0xA42}, {0xA47,0xA48}, {0xA4B,0xA4D}, + {0xA51,0xA51}, {0xA59,0xA5C}, {0xA5E,0xA5E}, {0xA66,0xA76}, +}; +const size_t k_script_Gurmukhi_n = sizeof(k_script_Gurmukhi) / sizeof(k_script_Gurmukhi[0]); + +const CpRange k_script_Gujarati[] = { + {0xA81,0xA83}, {0xA85,0xA8D}, {0xA8F,0xA91}, {0xA93,0xAA8}, {0xAAA,0xAB0}, {0xAB2,0xAB3}, + {0xAB5,0xAB9}, {0xABC,0xAC5}, {0xAC7,0xAC9}, {0xACB,0xACD}, {0xAD0,0xAD0}, {0xAE0,0xAE3}, + {0xAE6,0xAF1}, {0xAF9,0xAFF}, +}; +const size_t k_script_Gujarati_n = sizeof(k_script_Gujarati) / sizeof(k_script_Gujarati[0]); + +const CpRange k_script_Oriya[] = { + {0xB01,0xB03}, {0xB05,0xB0C}, {0xB0F,0xB10}, {0xB13,0xB28}, {0xB2A,0xB30}, {0xB32,0xB33}, + {0xB35,0xB39}, {0xB3C,0xB44}, {0xB47,0xB48}, {0xB4B,0xB4D}, {0xB55,0xB57}, {0xB5C,0xB5D}, + {0xB5F,0xB63}, {0xB66,0xB77}, +}; +const size_t k_script_Oriya_n = sizeof(k_script_Oriya) / sizeof(k_script_Oriya[0]); + +const CpRange k_script_Tamil[] = { + {0xB82,0xB83}, {0xB85,0xB8A}, {0xB8E,0xB90}, {0xB92,0xB95}, {0xB99,0xB9A}, {0xB9C,0xB9C}, + {0xB9E,0xB9F}, {0xBA3,0xBA4}, {0xBA8,0xBAA}, {0xBAE,0xBB9}, {0xBBE,0xBC2}, {0xBC6,0xBC8}, + {0xBCA,0xBCD}, {0xBD0,0xBD0}, {0xBD7,0xBD7}, {0xBE6,0xBFA}, {0x11FC0,0x11FF1}, {0x11FFF,0x11FFF}, +}; +const size_t k_script_Tamil_n = sizeof(k_script_Tamil) / sizeof(k_script_Tamil[0]); + +const CpRange k_script_Telugu[] = { + {0xC00,0xC0C}, {0xC0E,0xC10}, {0xC12,0xC28}, {0xC2A,0xC39}, {0xC3C,0xC44}, {0xC46,0xC48}, + {0xC4A,0xC4D}, {0xC55,0xC56}, {0xC58,0xC5A}, {0xC5D,0xC5D}, {0xC60,0xC63}, {0xC66,0xC6F}, + {0xC77,0xC7F}, +}; +const size_t k_script_Telugu_n = sizeof(k_script_Telugu) / sizeof(k_script_Telugu[0]); + +const CpRange k_script_Kannada[] = { + {0xC80,0xC8C}, {0xC8E,0xC90}, {0xC92,0xCA8}, {0xCAA,0xCB3}, {0xCB5,0xCB9}, {0xCBC,0xCC4}, + {0xCC6,0xCC8}, {0xCCA,0xCCD}, {0xCD5,0xCD6}, {0xCDD,0xCDE}, {0xCE0,0xCE3}, {0xCE6,0xCEF}, + {0xCF1,0xCF3}, +}; +const size_t k_script_Kannada_n = sizeof(k_script_Kannada) / sizeof(k_script_Kannada[0]); + +const CpRange k_script_Malayalam[] = { + {0xD00,0xD0C}, {0xD0E,0xD10}, {0xD12,0xD44}, {0xD46,0xD48}, {0xD4A,0xD4F}, {0xD54,0xD63}, + {0xD66,0xD7F}, +}; +const size_t k_script_Malayalam_n = sizeof(k_script_Malayalam) / sizeof(k_script_Malayalam[0]); + +const CpRange k_script_Sinhala[] = { + {0xD81,0xD83}, {0xD85,0xD96}, {0xD9A,0xDB1}, {0xDB3,0xDBB}, {0xDBD,0xDBD}, {0xDC0,0xDC6}, + {0xDCA,0xDCA}, {0xDCF,0xDD4}, {0xDD6,0xDD6}, {0xDD8,0xDDF}, {0xDE6,0xDEF}, {0xDF2,0xDF4}, + {0x111E1,0x111F4}, +}; +const size_t k_script_Sinhala_n = sizeof(k_script_Sinhala) / sizeof(k_script_Sinhala[0]); + +const CpRange k_script_Georgian[] = { + {0x10A0,0x10C5}, {0x10C7,0x10C7}, {0x10CD,0x10CD}, {0x10D0,0x10FA}, {0x10FC,0x10FF}, {0x1C90,0x1CBA}, + {0x1CBD,0x1CBF}, {0x2D00,0x2D25}, {0x2D27,0x2D27}, {0x2D2D,0x2D2D}, +}; +const size_t k_script_Georgian_n = sizeof(k_script_Georgian) / sizeof(k_script_Georgian[0]); + +const CpRange k_script_Ethiopic[] = { + {0x1200,0x1248}, {0x124A,0x124D}, {0x1250,0x1256}, {0x1258,0x1258}, {0x125A,0x125D}, {0x1260,0x1288}, + {0x128A,0x128D}, {0x1290,0x12B0}, {0x12B2,0x12B5}, {0x12B8,0x12BE}, {0x12C0,0x12C0}, {0x12C2,0x12C5}, + {0x12C8,0x12D6}, {0x12D8,0x1310}, {0x1312,0x1315}, {0x1318,0x135A}, {0x135D,0x137C}, {0x1380,0x1399}, + {0x2D80,0x2D96}, {0x2DA0,0x2DA6}, {0x2DA8,0x2DAE}, {0x2DB0,0x2DB6}, {0x2DB8,0x2DBE}, {0x2DC0,0x2DC6}, + {0x2DC8,0x2DCE}, {0x2DD0,0x2DD6}, {0x2DD8,0x2DDE}, {0xAB01,0xAB06}, {0xAB09,0xAB0E}, {0xAB11,0xAB16}, + {0xAB20,0xAB26}, {0xAB28,0xAB2E}, {0x1E7E0,0x1E7E6}, {0x1E7E8,0x1E7EB}, {0x1E7ED,0x1E7EE}, {0x1E7F0,0x1E7FE}, +}; +const size_t k_script_Ethiopic_n = sizeof(k_script_Ethiopic) / sizeof(k_script_Ethiopic[0]); + +const CpRange k_script_Mongolian[] = { + {0x1800,0x1801}, {0x1804,0x1804}, {0x1806,0x1819}, {0x1820,0x1878}, {0x1880,0x18AA}, {0x11660,0x1166C}, +}; +const size_t k_script_Mongolian_n = sizeof(k_script_Mongolian) / sizeof(k_script_Mongolian[0]); + +const CpRange k_script_Common[] = { + {0x0,0x40}, {0x5B,0x60}, {0x7B,0xA9}, {0xAB,0xB9}, {0xBB,0xBF}, {0xD7,0xD7}, + {0xF7,0xF7}, {0x2B9,0x2DF}, {0x2E5,0x2E9}, {0x2EC,0x2FF}, {0x374,0x374}, {0x37E,0x37E}, + {0x385,0x385}, {0x387,0x387}, {0x605,0x605}, {0x60C,0x60C}, {0x61B,0x61B}, {0x61F,0x61F}, + {0x640,0x640}, {0x6DD,0x6DD}, {0x8E2,0x8E2}, {0x964,0x965}, {0xE3F,0xE3F}, {0xFD5,0xFD8}, + {0x10FB,0x10FB}, {0x16EB,0x16ED}, {0x1735,0x1736}, {0x1802,0x1803}, {0x1805,0x1805}, {0x1CD3,0x1CD3}, + {0x1CE1,0x1CE1}, {0x1CE9,0x1CEC}, {0x1CEE,0x1CF3}, {0x1CF5,0x1CF7}, {0x1CFA,0x1CFA}, {0x2000,0x200B}, + {0x200E,0x2064}, {0x2066,0x2070}, {0x2074,0x207E}, {0x2080,0x208E}, {0x20A0,0x20C0}, {0x2100,0x2125}, + {0x2127,0x2129}, {0x212C,0x2131}, {0x2133,0x214D}, {0x214F,0x215F}, {0x2189,0x218B}, {0x2190,0x2429}, + {0x2440,0x244A}, {0x2460,0x27FF}, {0x2900,0x2B73}, {0x2B76,0x2B95}, {0x2B97,0x2BFF}, {0x2E00,0x2E5D}, + {0x2FF0,0x3004}, {0x3006,0x3006}, {0x3008,0x3020}, {0x3030,0x3037}, {0x303C,0x303F}, {0x309B,0x309C}, + {0x30A0,0x30A0}, {0x30FB,0x30FC}, {0x3190,0x319F}, {0x31C0,0x31E5}, {0x31EF,0x31EF}, {0x3220,0x325F}, + {0x327F,0x32CF}, {0x32FF,0x32FF}, {0x3358,0x33FF}, {0x4DC0,0x4DFF}, {0xA700,0xA721}, {0xA788,0xA78A}, + {0xA830,0xA839}, {0xA92E,0xA92E}, {0xA9CF,0xA9CF}, {0xAB5B,0xAB5B}, {0xAB6A,0xAB6B}, {0xFD3E,0xFD3F}, + {0xFE10,0xFE19}, {0xFE30,0xFE52}, {0xFE54,0xFE66}, {0xFE68,0xFE6B}, {0xFEFF,0xFEFF}, {0xFF01,0xFF20}, + {0xFF3B,0xFF40}, {0xFF5B,0xFF65}, {0xFF70,0xFF70}, {0xFF9E,0xFF9F}, {0xFFE0,0xFFE6}, {0xFFE8,0xFFEE}, + {0xFFF9,0xFFFD}, {0x10100,0x10102}, {0x10107,0x10133}, {0x10137,0x1013F}, {0x10190,0x1019C}, {0x101D0,0x101FC}, + {0x102E1,0x102FB}, {0x1BCA0,0x1BCA3}, {0x1CC00,0x1CCF9}, {0x1CD00,0x1CEB3}, {0x1CF50,0x1CFC3}, {0x1D000,0x1D0F5}, + {0x1D100,0x1D126}, {0x1D129,0x1D166}, {0x1D16A,0x1D17A}, {0x1D183,0x1D184}, {0x1D18C,0x1D1A9}, {0x1D1AE,0x1D1EA}, + {0x1D2C0,0x1D2D3}, {0x1D2E0,0x1D2F3}, {0x1D300,0x1D356}, {0x1D360,0x1D378}, {0x1D400,0x1D454}, {0x1D456,0x1D49C}, + {0x1D49E,0x1D49F}, {0x1D4A2,0x1D4A2}, {0x1D4A5,0x1D4A6}, {0x1D4A9,0x1D4AC}, {0x1D4AE,0x1D4B9}, {0x1D4BB,0x1D4BB}, + {0x1D4BD,0x1D4C3}, {0x1D4C5,0x1D505}, {0x1D507,0x1D50A}, {0x1D50D,0x1D514}, {0x1D516,0x1D51C}, {0x1D51E,0x1D539}, + {0x1D53B,0x1D53E}, {0x1D540,0x1D544}, {0x1D546,0x1D546}, {0x1D54A,0x1D550}, {0x1D552,0x1D6A5}, {0x1D6A8,0x1D7CB}, + {0x1D7CE,0x1D7FF}, {0x1EC71,0x1ECB4}, {0x1ED01,0x1ED3D}, {0x1F000,0x1F02B}, {0x1F030,0x1F093}, {0x1F0A0,0x1F0AE}, + {0x1F0B1,0x1F0BF}, {0x1F0C1,0x1F0CF}, {0x1F0D1,0x1F0F5}, {0x1F100,0x1F1AD}, {0x1F1E6,0x1F1FF}, {0x1F201,0x1F202}, + {0x1F210,0x1F23B}, {0x1F240,0x1F248}, {0x1F250,0x1F251}, {0x1F260,0x1F265}, {0x1F300,0x1F6D7}, {0x1F6DC,0x1F6EC}, + {0x1F6F0,0x1F6FC}, {0x1F700,0x1F776}, {0x1F77B,0x1F7D9}, {0x1F7E0,0x1F7EB}, {0x1F7F0,0x1F7F0}, {0x1F800,0x1F80B}, + {0x1F810,0x1F847}, {0x1F850,0x1F859}, {0x1F860,0x1F887}, {0x1F890,0x1F8AD}, {0x1F8B0,0x1F8BB}, {0x1F8C0,0x1F8C1}, + {0x1F900,0x1FA53}, {0x1FA60,0x1FA6D}, {0x1FA70,0x1FA7C}, {0x1FA80,0x1FA89}, {0x1FA8F,0x1FAC6}, {0x1FACE,0x1FADC}, + {0x1FADF,0x1FAE9}, {0x1FAF0,0x1FAF8}, {0x1FB00,0x1FB92}, {0x1FB94,0x1FBF9}, {0xE0001,0xE0001}, {0xE0020,0xE007F}, +}; +const size_t k_script_Common_n = sizeof(k_script_Common) / sizeof(k_script_Common[0]); + +const CpRange k_script_Inherited[] = { + {0x300,0x36F}, {0x485,0x486}, {0x64B,0x655}, {0x670,0x670}, {0x951,0x954}, {0x1AB0,0x1ACE}, + {0x1CD0,0x1CD2}, {0x1CD4,0x1CE0}, {0x1CE2,0x1CE8}, {0x1CED,0x1CED}, {0x1CF4,0x1CF4}, {0x1CF8,0x1CF9}, + {0x1DC0,0x1DFF}, {0x200C,0x200D}, {0x20D0,0x20F0}, {0x302A,0x302D}, {0x3099,0x309A}, {0xFE00,0xFE0F}, + {0xFE20,0xFE2D}, {0x101FD,0x101FD}, {0x102E0,0x102E0}, {0x1133B,0x1133B}, {0x1CF00,0x1CF2D}, {0x1CF30,0x1CF46}, + {0x1D167,0x1D169}, {0x1D17B,0x1D182}, {0x1D185,0x1D18B}, {0x1D1AA,0x1D1AD}, {0xE0100,0xE01EF}, +}; +const size_t k_script_Inherited_n = sizeof(k_script_Inherited) / sizeof(k_script_Inherited[0]); + +const ScriptTable k_scripts[] = { + { "Han", k_script_Han, k_script_Han_n }, + { "Hiragana", k_script_Hiragana, k_script_Hiragana_n }, + { "Katakana", k_script_Katakana, k_script_Katakana_n }, + { "Hangul", k_script_Hangul, k_script_Hangul_n }, + { "Bopomofo", k_script_Bopomofo, k_script_Bopomofo_n }, + { "Latin", k_script_Latin, k_script_Latin_n }, + { "Greek", k_script_Greek, k_script_Greek_n }, + { "Cyrillic", k_script_Cyrillic, k_script_Cyrillic_n }, + { "Armenian", k_script_Armenian, k_script_Armenian_n }, + { "Hebrew", k_script_Hebrew, k_script_Hebrew_n }, + { "Arabic", k_script_Arabic, k_script_Arabic_n }, + { "Thai", k_script_Thai, k_script_Thai_n }, + { "Lao", k_script_Lao, k_script_Lao_n }, + { "Khmer", k_script_Khmer, k_script_Khmer_n }, + { "Myanmar", k_script_Myanmar, k_script_Myanmar_n }, + { "Tibetan", k_script_Tibetan, k_script_Tibetan_n }, + { "Devanagari", k_script_Devanagari, k_script_Devanagari_n }, + { "Bengali", k_script_Bengali, k_script_Bengali_n }, + { "Gurmukhi", k_script_Gurmukhi, k_script_Gurmukhi_n }, + { "Gujarati", k_script_Gujarati, k_script_Gujarati_n }, + { "Oriya", k_script_Oriya, k_script_Oriya_n }, + { "Tamil", k_script_Tamil, k_script_Tamil_n }, + { "Telugu", k_script_Telugu, k_script_Telugu_n }, + { "Kannada", k_script_Kannada, k_script_Kannada_n }, + { "Malayalam", k_script_Malayalam, k_script_Malayalam_n }, + { "Sinhala", k_script_Sinhala, k_script_Sinhala_n }, + { "Georgian", k_script_Georgian, k_script_Georgian_n }, + { "Ethiopic", k_script_Ethiopic, k_script_Ethiopic_n }, + { "Mongolian", k_script_Mongolian, k_script_Mongolian_n }, + { "Common", k_script_Common, k_script_Common_n }, + { "Inherited", k_script_Inherited, k_script_Inherited_n }, +}; +const size_t k_scripts_n = sizeof(k_scripts) / sizeof(k_scripts[0]); + +/* Each orbit is its length followed by its members, ascending. */ +const uint32_t k_case_orbits[] = { + 2, 0x41, 0x61, + 2, 0x42, 0x62, + 2, 0x43, 0x63, + 2, 0x44, 0x64, + 2, 0x45, 0x65, + 2, 0x46, 0x66, + 2, 0x47, 0x67, + 2, 0x48, 0x68, + 2, 0x49, 0x69, + 2, 0x4A, 0x6A, + 3, 0x4B, 0x6B, 0x212A, + 2, 0x4C, 0x6C, + 2, 0x4D, 0x6D, + 2, 0x4E, 0x6E, + 2, 0x4F, 0x6F, + 2, 0x50, 0x70, + 2, 0x51, 0x71, + 2, 0x52, 0x72, + 3, 0x53, 0x73, 0x17F, + 2, 0x54, 0x74, + 2, 0x55, 0x75, + 2, 0x56, 0x76, + 2, 0x57, 0x77, + 2, 0x58, 0x78, + 2, 0x59, 0x79, + 2, 0x5A, 0x7A, + 3, 0xB5, 0x39C, 0x3BC, + 2, 0xC0, 0xE0, + 2, 0xC1, 0xE1, + 2, 0xC2, 0xE2, + 2, 0xC3, 0xE3, + 2, 0xC4, 0xE4, + 3, 0xC5, 0xE5, 0x212B, + 2, 0xC6, 0xE6, + 2, 0xC7, 0xE7, + 2, 0xC8, 0xE8, + 2, 0xC9, 0xE9, + 2, 0xCA, 0xEA, + 2, 0xCB, 0xEB, + 2, 0xCC, 0xEC, + 2, 0xCD, 0xED, + 2, 0xCE, 0xEE, + 2, 0xCF, 0xEF, + 2, 0xD0, 0xF0, + 2, 0xD1, 0xF1, + 2, 0xD2, 0xF2, + 2, 0xD3, 0xF3, + 2, 0xD4, 0xF4, + 2, 0xD5, 0xF5, + 2, 0xD6, 0xF6, + 2, 0xD8, 0xF8, + 2, 0xD9, 0xF9, + 2, 0xDA, 0xFA, + 2, 0xDB, 0xFB, + 2, 0xDC, 0xFC, + 2, 0xDD, 0xFD, + 2, 0xDE, 0xFE, + 2, 0xDF, 0x1E9E, + 2, 0xFF, 0x178, + 2, 0x100, 0x101, + 2, 0x102, 0x103, + 2, 0x104, 0x105, + 2, 0x106, 0x107, + 2, 0x108, 0x109, + 2, 0x10A, 0x10B, + 2, 0x10C, 0x10D, + 2, 0x10E, 0x10F, + 2, 0x110, 0x111, + 2, 0x112, 0x113, + 2, 0x114, 0x115, + 2, 0x116, 0x117, + 2, 0x118, 0x119, + 2, 0x11A, 0x11B, + 2, 0x11C, 0x11D, + 2, 0x11E, 0x11F, + 2, 0x120, 0x121, + 2, 0x122, 0x123, + 2, 0x124, 0x125, + 2, 0x126, 0x127, + 2, 0x128, 0x129, + 2, 0x12A, 0x12B, + 2, 0x12C, 0x12D, + 2, 0x12E, 0x12F, + 2, 0x132, 0x133, + 2, 0x134, 0x135, + 2, 0x136, 0x137, + 2, 0x139, 0x13A, + 2, 0x13B, 0x13C, + 2, 0x13D, 0x13E, + 2, 0x13F, 0x140, + 2, 0x141, 0x142, + 2, 0x143, 0x144, + 2, 0x145, 0x146, + 2, 0x147, 0x148, + 2, 0x14A, 0x14B, + 2, 0x14C, 0x14D, + 2, 0x14E, 0x14F, + 2, 0x150, 0x151, + 2, 0x152, 0x153, + 2, 0x154, 0x155, + 2, 0x156, 0x157, + 2, 0x158, 0x159, + 2, 0x15A, 0x15B, + 2, 0x15C, 0x15D, + 2, 0x15E, 0x15F, + 2, 0x160, 0x161, + 2, 0x162, 0x163, + 2, 0x164, 0x165, + 2, 0x166, 0x167, + 2, 0x168, 0x169, + 2, 0x16A, 0x16B, + 2, 0x16C, 0x16D, + 2, 0x16E, 0x16F, + 2, 0x170, 0x171, + 2, 0x172, 0x173, + 2, 0x174, 0x175, + 2, 0x176, 0x177, + 2, 0x179, 0x17A, + 2, 0x17B, 0x17C, + 2, 0x17D, 0x17E, + 2, 0x180, 0x243, + 2, 0x181, 0x253, + 2, 0x182, 0x183, + 2, 0x184, 0x185, + 2, 0x186, 0x254, + 2, 0x187, 0x188, + 2, 0x189, 0x256, + 2, 0x18A, 0x257, + 2, 0x18B, 0x18C, + 2, 0x18E, 0x1DD, + 2, 0x18F, 0x259, + 2, 0x190, 0x25B, + 2, 0x191, 0x192, + 2, 0x193, 0x260, + 2, 0x194, 0x263, + 2, 0x195, 0x1F6, + 2, 0x196, 0x269, + 2, 0x197, 0x268, + 2, 0x198, 0x199, + 2, 0x19A, 0x23D, + 2, 0x19B, 0xA7DC, + 2, 0x19C, 0x26F, + 2, 0x19D, 0x272, + 2, 0x19E, 0x220, + 2, 0x19F, 0x275, + 2, 0x1A0, 0x1A1, + 2, 0x1A2, 0x1A3, + 2, 0x1A4, 0x1A5, + 2, 0x1A6, 0x280, + 2, 0x1A7, 0x1A8, + 2, 0x1A9, 0x283, + 2, 0x1AC, 0x1AD, + 2, 0x1AE, 0x288, + 2, 0x1AF, 0x1B0, + 2, 0x1B1, 0x28A, + 2, 0x1B2, 0x28B, + 2, 0x1B3, 0x1B4, + 2, 0x1B5, 0x1B6, + 2, 0x1B7, 0x292, + 2, 0x1B8, 0x1B9, + 2, 0x1BC, 0x1BD, + 2, 0x1BF, 0x1F7, + 3, 0x1C4, 0x1C5, 0x1C6, + 3, 0x1C7, 0x1C8, 0x1C9, + 3, 0x1CA, 0x1CB, 0x1CC, + 2, 0x1CD, 0x1CE, + 2, 0x1CF, 0x1D0, + 2, 0x1D1, 0x1D2, + 2, 0x1D3, 0x1D4, + 2, 0x1D5, 0x1D6, + 2, 0x1D7, 0x1D8, + 2, 0x1D9, 0x1DA, + 2, 0x1DB, 0x1DC, + 2, 0x1DE, 0x1DF, + 2, 0x1E0, 0x1E1, + 2, 0x1E2, 0x1E3, + 2, 0x1E4, 0x1E5, + 2, 0x1E6, 0x1E7, + 2, 0x1E8, 0x1E9, + 2, 0x1EA, 0x1EB, + 2, 0x1EC, 0x1ED, + 2, 0x1EE, 0x1EF, + 3, 0x1F1, 0x1F2, 0x1F3, + 2, 0x1F4, 0x1F5, + 2, 0x1F8, 0x1F9, + 2, 0x1FA, 0x1FB, + 2, 0x1FC, 0x1FD, + 2, 0x1FE, 0x1FF, + 2, 0x200, 0x201, + 2, 0x202, 0x203, + 2, 0x204, 0x205, + 2, 0x206, 0x207, + 2, 0x208, 0x209, + 2, 0x20A, 0x20B, + 2, 0x20C, 0x20D, + 2, 0x20E, 0x20F, + 2, 0x210, 0x211, + 2, 0x212, 0x213, + 2, 0x214, 0x215, + 2, 0x216, 0x217, + 2, 0x218, 0x219, + 2, 0x21A, 0x21B, + 2, 0x21C, 0x21D, + 2, 0x21E, 0x21F, + 2, 0x222, 0x223, + 2, 0x224, 0x225, + 2, 0x226, 0x227, + 2, 0x228, 0x229, + 2, 0x22A, 0x22B, + 2, 0x22C, 0x22D, + 2, 0x22E, 0x22F, + 2, 0x230, 0x231, + 2, 0x232, 0x233, + 2, 0x23A, 0x2C65, + 2, 0x23B, 0x23C, + 2, 0x23E, 0x2C66, + 2, 0x23F, 0x2C7E, + 2, 0x240, 0x2C7F, + 2, 0x241, 0x242, + 2, 0x244, 0x289, + 2, 0x245, 0x28C, + 2, 0x246, 0x247, + 2, 0x248, 0x249, + 2, 0x24A, 0x24B, + 2, 0x24C, 0x24D, + 2, 0x24E, 0x24F, + 2, 0x250, 0x2C6F, + 2, 0x251, 0x2C6D, + 2, 0x252, 0x2C70, + 2, 0x25C, 0xA7AB, + 2, 0x261, 0xA7AC, + 2, 0x264, 0xA7CB, + 2, 0x265, 0xA78D, + 2, 0x266, 0xA7AA, + 2, 0x26A, 0xA7AE, + 2, 0x26B, 0x2C62, + 2, 0x26C, 0xA7AD, + 2, 0x271, 0x2C6E, + 2, 0x27D, 0x2C64, + 2, 0x282, 0xA7C5, + 2, 0x287, 0xA7B1, + 2, 0x29D, 0xA7B2, + 2, 0x29E, 0xA7B0, + 4, 0x345, 0x399, 0x3B9, 0x1FBE, + 2, 0x370, 0x371, + 2, 0x372, 0x373, + 2, 0x376, 0x377, + 2, 0x37B, 0x3FD, + 2, 0x37C, 0x3FE, + 2, 0x37D, 0x3FF, + 2, 0x37F, 0x3F3, + 2, 0x386, 0x3AC, + 2, 0x388, 0x3AD, + 2, 0x389, 0x3AE, + 2, 0x38A, 0x3AF, + 2, 0x38C, 0x3CC, + 2, 0x38E, 0x3CD, + 2, 0x38F, 0x3CE, + 2, 0x390, 0x1FD3, + 2, 0x391, 0x3B1, + 3, 0x392, 0x3B2, 0x3D0, + 2, 0x393, 0x3B3, + 2, 0x394, 0x3B4, + 3, 0x395, 0x3B5, 0x3F5, + 2, 0x396, 0x3B6, + 2, 0x397, 0x3B7, + 4, 0x398, 0x3B8, 0x3D1, 0x3F4, + 3, 0x39A, 0x3BA, 0x3F0, + 2, 0x39B, 0x3BB, + 2, 0x39D, 0x3BD, + 2, 0x39E, 0x3BE, + 2, 0x39F, 0x3BF, + 3, 0x3A0, 0x3C0, 0x3D6, + 3, 0x3A1, 0x3C1, 0x3F1, + 3, 0x3A3, 0x3C2, 0x3C3, + 2, 0x3A4, 0x3C4, + 2, 0x3A5, 0x3C5, + 3, 0x3A6, 0x3C6, 0x3D5, + 2, 0x3A7, 0x3C7, + 2, 0x3A8, 0x3C8, + 3, 0x3A9, 0x3C9, 0x2126, + 2, 0x3AA, 0x3CA, + 2, 0x3AB, 0x3CB, + 2, 0x3B0, 0x1FE3, + 2, 0x3CF, 0x3D7, + 2, 0x3D8, 0x3D9, + 2, 0x3DA, 0x3DB, + 2, 0x3DC, 0x3DD, + 2, 0x3DE, 0x3DF, + 2, 0x3E0, 0x3E1, + 2, 0x3E2, 0x3E3, + 2, 0x3E4, 0x3E5, + 2, 0x3E6, 0x3E7, + 2, 0x3E8, 0x3E9, + 2, 0x3EA, 0x3EB, + 2, 0x3EC, 0x3ED, + 2, 0x3EE, 0x3EF, + 2, 0x3F2, 0x3F9, + 2, 0x3F7, 0x3F8, + 2, 0x3FA, 0x3FB, + 2, 0x400, 0x450, + 2, 0x401, 0x451, + 2, 0x402, 0x452, + 2, 0x403, 0x453, + 2, 0x404, 0x454, + 2, 0x405, 0x455, + 2, 0x406, 0x456, + 2, 0x407, 0x457, + 2, 0x408, 0x458, + 2, 0x409, 0x459, + 2, 0x40A, 0x45A, + 2, 0x40B, 0x45B, + 2, 0x40C, 0x45C, + 2, 0x40D, 0x45D, + 2, 0x40E, 0x45E, + 2, 0x40F, 0x45F, + 2, 0x410, 0x430, + 2, 0x411, 0x431, + 3, 0x412, 0x432, 0x1C80, + 2, 0x413, 0x433, + 3, 0x414, 0x434, 0x1C81, + 2, 0x415, 0x435, + 2, 0x416, 0x436, + 2, 0x417, 0x437, + 2, 0x418, 0x438, + 2, 0x419, 0x439, + 2, 0x41A, 0x43A, + 2, 0x41B, 0x43B, + 2, 0x41C, 0x43C, + 2, 0x41D, 0x43D, + 3, 0x41E, 0x43E, 0x1C82, + 2, 0x41F, 0x43F, + 2, 0x420, 0x440, + 3, 0x421, 0x441, 0x1C83, + 4, 0x422, 0x442, 0x1C84, 0x1C85, + 2, 0x423, 0x443, + 2, 0x424, 0x444, + 2, 0x425, 0x445, + 2, 0x426, 0x446, + 2, 0x427, 0x447, + 2, 0x428, 0x448, + 2, 0x429, 0x449, + 3, 0x42A, 0x44A, 0x1C86, + 2, 0x42B, 0x44B, + 2, 0x42C, 0x44C, + 2, 0x42D, 0x44D, + 2, 0x42E, 0x44E, + 2, 0x42F, 0x44F, + 2, 0x460, 0x461, + 3, 0x462, 0x463, 0x1C87, + 2, 0x464, 0x465, + 2, 0x466, 0x467, + 2, 0x468, 0x469, + 2, 0x46A, 0x46B, + 2, 0x46C, 0x46D, + 2, 0x46E, 0x46F, + 2, 0x470, 0x471, + 2, 0x472, 0x473, + 2, 0x474, 0x475, + 2, 0x476, 0x477, + 2, 0x478, 0x479, + 2, 0x47A, 0x47B, + 2, 0x47C, 0x47D, + 2, 0x47E, 0x47F, + 2, 0x480, 0x481, + 2, 0x48A, 0x48B, + 2, 0x48C, 0x48D, + 2, 0x48E, 0x48F, + 2, 0x490, 0x491, + 2, 0x492, 0x493, + 2, 0x494, 0x495, + 2, 0x496, 0x497, + 2, 0x498, 0x499, + 2, 0x49A, 0x49B, + 2, 0x49C, 0x49D, + 2, 0x49E, 0x49F, + 2, 0x4A0, 0x4A1, + 2, 0x4A2, 0x4A3, + 2, 0x4A4, 0x4A5, + 2, 0x4A6, 0x4A7, + 2, 0x4A8, 0x4A9, + 2, 0x4AA, 0x4AB, + 2, 0x4AC, 0x4AD, + 2, 0x4AE, 0x4AF, + 2, 0x4B0, 0x4B1, + 2, 0x4B2, 0x4B3, + 2, 0x4B4, 0x4B5, + 2, 0x4B6, 0x4B7, + 2, 0x4B8, 0x4B9, + 2, 0x4BA, 0x4BB, + 2, 0x4BC, 0x4BD, + 2, 0x4BE, 0x4BF, + 2, 0x4C0, 0x4CF, + 2, 0x4C1, 0x4C2, + 2, 0x4C3, 0x4C4, + 2, 0x4C5, 0x4C6, + 2, 0x4C7, 0x4C8, + 2, 0x4C9, 0x4CA, + 2, 0x4CB, 0x4CC, + 2, 0x4CD, 0x4CE, + 2, 0x4D0, 0x4D1, + 2, 0x4D2, 0x4D3, + 2, 0x4D4, 0x4D5, + 2, 0x4D6, 0x4D7, + 2, 0x4D8, 0x4D9, + 2, 0x4DA, 0x4DB, + 2, 0x4DC, 0x4DD, + 2, 0x4DE, 0x4DF, + 2, 0x4E0, 0x4E1, + 2, 0x4E2, 0x4E3, + 2, 0x4E4, 0x4E5, + 2, 0x4E6, 0x4E7, + 2, 0x4E8, 0x4E9, + 2, 0x4EA, 0x4EB, + 2, 0x4EC, 0x4ED, + 2, 0x4EE, 0x4EF, + 2, 0x4F0, 0x4F1, + 2, 0x4F2, 0x4F3, + 2, 0x4F4, 0x4F5, + 2, 0x4F6, 0x4F7, + 2, 0x4F8, 0x4F9, + 2, 0x4FA, 0x4FB, + 2, 0x4FC, 0x4FD, + 2, 0x4FE, 0x4FF, + 2, 0x500, 0x501, + 2, 0x502, 0x503, + 2, 0x504, 0x505, + 2, 0x506, 0x507, + 2, 0x508, 0x509, + 2, 0x50A, 0x50B, + 2, 0x50C, 0x50D, + 2, 0x50E, 0x50F, + 2, 0x510, 0x511, + 2, 0x512, 0x513, + 2, 0x514, 0x515, + 2, 0x516, 0x517, + 2, 0x518, 0x519, + 2, 0x51A, 0x51B, + 2, 0x51C, 0x51D, + 2, 0x51E, 0x51F, + 2, 0x520, 0x521, + 2, 0x522, 0x523, + 2, 0x524, 0x525, + 2, 0x526, 0x527, + 2, 0x528, 0x529, + 2, 0x52A, 0x52B, + 2, 0x52C, 0x52D, + 2, 0x52E, 0x52F, + 2, 0x531, 0x561, + 2, 0x532, 0x562, + 2, 0x533, 0x563, + 2, 0x534, 0x564, + 2, 0x535, 0x565, + 2, 0x536, 0x566, + 2, 0x537, 0x567, + 2, 0x538, 0x568, + 2, 0x539, 0x569, + 2, 0x53A, 0x56A, + 2, 0x53B, 0x56B, + 2, 0x53C, 0x56C, + 2, 0x53D, 0x56D, + 2, 0x53E, 0x56E, + 2, 0x53F, 0x56F, + 2, 0x540, 0x570, + 2, 0x541, 0x571, + 2, 0x542, 0x572, + 2, 0x543, 0x573, + 2, 0x544, 0x574, + 2, 0x545, 0x575, + 2, 0x546, 0x576, + 2, 0x547, 0x577, + 2, 0x548, 0x578, + 2, 0x549, 0x579, + 2, 0x54A, 0x57A, + 2, 0x54B, 0x57B, + 2, 0x54C, 0x57C, + 2, 0x54D, 0x57D, + 2, 0x54E, 0x57E, + 2, 0x54F, 0x57F, + 2, 0x550, 0x580, + 2, 0x551, 0x581, + 2, 0x552, 0x582, + 2, 0x553, 0x583, + 2, 0x554, 0x584, + 2, 0x555, 0x585, + 2, 0x556, 0x586, + 2, 0x10A0, 0x2D00, + 2, 0x10A1, 0x2D01, + 2, 0x10A2, 0x2D02, + 2, 0x10A3, 0x2D03, + 2, 0x10A4, 0x2D04, + 2, 0x10A5, 0x2D05, + 2, 0x10A6, 0x2D06, + 2, 0x10A7, 0x2D07, + 2, 0x10A8, 0x2D08, + 2, 0x10A9, 0x2D09, + 2, 0x10AA, 0x2D0A, + 2, 0x10AB, 0x2D0B, + 2, 0x10AC, 0x2D0C, + 2, 0x10AD, 0x2D0D, + 2, 0x10AE, 0x2D0E, + 2, 0x10AF, 0x2D0F, + 2, 0x10B0, 0x2D10, + 2, 0x10B1, 0x2D11, + 2, 0x10B2, 0x2D12, + 2, 0x10B3, 0x2D13, + 2, 0x10B4, 0x2D14, + 2, 0x10B5, 0x2D15, + 2, 0x10B6, 0x2D16, + 2, 0x10B7, 0x2D17, + 2, 0x10B8, 0x2D18, + 2, 0x10B9, 0x2D19, + 2, 0x10BA, 0x2D1A, + 2, 0x10BB, 0x2D1B, + 2, 0x10BC, 0x2D1C, + 2, 0x10BD, 0x2D1D, + 2, 0x10BE, 0x2D1E, + 2, 0x10BF, 0x2D1F, + 2, 0x10C0, 0x2D20, + 2, 0x10C1, 0x2D21, + 2, 0x10C2, 0x2D22, + 2, 0x10C3, 0x2D23, + 2, 0x10C4, 0x2D24, + 2, 0x10C5, 0x2D25, + 2, 0x10C7, 0x2D27, + 2, 0x10CD, 0x2D2D, + 2, 0x10D0, 0x1C90, + 2, 0x10D1, 0x1C91, + 2, 0x10D2, 0x1C92, + 2, 0x10D3, 0x1C93, + 2, 0x10D4, 0x1C94, + 2, 0x10D5, 0x1C95, + 2, 0x10D6, 0x1C96, + 2, 0x10D7, 0x1C97, + 2, 0x10D8, 0x1C98, + 2, 0x10D9, 0x1C99, + 2, 0x10DA, 0x1C9A, + 2, 0x10DB, 0x1C9B, + 2, 0x10DC, 0x1C9C, + 2, 0x10DD, 0x1C9D, + 2, 0x10DE, 0x1C9E, + 2, 0x10DF, 0x1C9F, + 2, 0x10E0, 0x1CA0, + 2, 0x10E1, 0x1CA1, + 2, 0x10E2, 0x1CA2, + 2, 0x10E3, 0x1CA3, + 2, 0x10E4, 0x1CA4, + 2, 0x10E5, 0x1CA5, + 2, 0x10E6, 0x1CA6, + 2, 0x10E7, 0x1CA7, + 2, 0x10E8, 0x1CA8, + 2, 0x10E9, 0x1CA9, + 2, 0x10EA, 0x1CAA, + 2, 0x10EB, 0x1CAB, + 2, 0x10EC, 0x1CAC, + 2, 0x10ED, 0x1CAD, + 2, 0x10EE, 0x1CAE, + 2, 0x10EF, 0x1CAF, + 2, 0x10F0, 0x1CB0, + 2, 0x10F1, 0x1CB1, + 2, 0x10F2, 0x1CB2, + 2, 0x10F3, 0x1CB3, + 2, 0x10F4, 0x1CB4, + 2, 0x10F5, 0x1CB5, + 2, 0x10F6, 0x1CB6, + 2, 0x10F7, 0x1CB7, + 2, 0x10F8, 0x1CB8, + 2, 0x10F9, 0x1CB9, + 2, 0x10FA, 0x1CBA, + 2, 0x10FD, 0x1CBD, + 2, 0x10FE, 0x1CBE, + 2, 0x10FF, 0x1CBF, + 2, 0x13A0, 0xAB70, + 2, 0x13A1, 0xAB71, + 2, 0x13A2, 0xAB72, + 2, 0x13A3, 0xAB73, + 2, 0x13A4, 0xAB74, + 2, 0x13A5, 0xAB75, + 2, 0x13A6, 0xAB76, + 2, 0x13A7, 0xAB77, + 2, 0x13A8, 0xAB78, + 2, 0x13A9, 0xAB79, + 2, 0x13AA, 0xAB7A, + 2, 0x13AB, 0xAB7B, + 2, 0x13AC, 0xAB7C, + 2, 0x13AD, 0xAB7D, + 2, 0x13AE, 0xAB7E, + 2, 0x13AF, 0xAB7F, + 2, 0x13B0, 0xAB80, + 2, 0x13B1, 0xAB81, + 2, 0x13B2, 0xAB82, + 2, 0x13B3, 0xAB83, + 2, 0x13B4, 0xAB84, + 2, 0x13B5, 0xAB85, + 2, 0x13B6, 0xAB86, + 2, 0x13B7, 0xAB87, + 2, 0x13B8, 0xAB88, + 2, 0x13B9, 0xAB89, + 2, 0x13BA, 0xAB8A, + 2, 0x13BB, 0xAB8B, + 2, 0x13BC, 0xAB8C, + 2, 0x13BD, 0xAB8D, + 2, 0x13BE, 0xAB8E, + 2, 0x13BF, 0xAB8F, + 2, 0x13C0, 0xAB90, + 2, 0x13C1, 0xAB91, + 2, 0x13C2, 0xAB92, + 2, 0x13C3, 0xAB93, + 2, 0x13C4, 0xAB94, + 2, 0x13C5, 0xAB95, + 2, 0x13C6, 0xAB96, + 2, 0x13C7, 0xAB97, + 2, 0x13C8, 0xAB98, + 2, 0x13C9, 0xAB99, + 2, 0x13CA, 0xAB9A, + 2, 0x13CB, 0xAB9B, + 2, 0x13CC, 0xAB9C, + 2, 0x13CD, 0xAB9D, + 2, 0x13CE, 0xAB9E, + 2, 0x13CF, 0xAB9F, + 2, 0x13D0, 0xABA0, + 2, 0x13D1, 0xABA1, + 2, 0x13D2, 0xABA2, + 2, 0x13D3, 0xABA3, + 2, 0x13D4, 0xABA4, + 2, 0x13D5, 0xABA5, + 2, 0x13D6, 0xABA6, + 2, 0x13D7, 0xABA7, + 2, 0x13D8, 0xABA8, + 2, 0x13D9, 0xABA9, + 2, 0x13DA, 0xABAA, + 2, 0x13DB, 0xABAB, + 2, 0x13DC, 0xABAC, + 2, 0x13DD, 0xABAD, + 2, 0x13DE, 0xABAE, + 2, 0x13DF, 0xABAF, + 2, 0x13E0, 0xABB0, + 2, 0x13E1, 0xABB1, + 2, 0x13E2, 0xABB2, + 2, 0x13E3, 0xABB3, + 2, 0x13E4, 0xABB4, + 2, 0x13E5, 0xABB5, + 2, 0x13E6, 0xABB6, + 2, 0x13E7, 0xABB7, + 2, 0x13E8, 0xABB8, + 2, 0x13E9, 0xABB9, + 2, 0x13EA, 0xABBA, + 2, 0x13EB, 0xABBB, + 2, 0x13EC, 0xABBC, + 2, 0x13ED, 0xABBD, + 2, 0x13EE, 0xABBE, + 2, 0x13EF, 0xABBF, + 2, 0x13F0, 0x13F8, + 2, 0x13F1, 0x13F9, + 2, 0x13F2, 0x13FA, + 2, 0x13F3, 0x13FB, + 2, 0x13F4, 0x13FC, + 2, 0x13F5, 0x13FD, + 3, 0x1C88, 0xA64A, 0xA64B, + 2, 0x1C89, 0x1C8A, + 2, 0x1D79, 0xA77D, + 2, 0x1D7D, 0x2C63, + 2, 0x1D8E, 0xA7C6, + 2, 0x1E00, 0x1E01, + 2, 0x1E02, 0x1E03, + 2, 0x1E04, 0x1E05, + 2, 0x1E06, 0x1E07, + 2, 0x1E08, 0x1E09, + 2, 0x1E0A, 0x1E0B, + 2, 0x1E0C, 0x1E0D, + 2, 0x1E0E, 0x1E0F, + 2, 0x1E10, 0x1E11, + 2, 0x1E12, 0x1E13, + 2, 0x1E14, 0x1E15, + 2, 0x1E16, 0x1E17, + 2, 0x1E18, 0x1E19, + 2, 0x1E1A, 0x1E1B, + 2, 0x1E1C, 0x1E1D, + 2, 0x1E1E, 0x1E1F, + 2, 0x1E20, 0x1E21, + 2, 0x1E22, 0x1E23, + 2, 0x1E24, 0x1E25, + 2, 0x1E26, 0x1E27, + 2, 0x1E28, 0x1E29, + 2, 0x1E2A, 0x1E2B, + 2, 0x1E2C, 0x1E2D, + 2, 0x1E2E, 0x1E2F, + 2, 0x1E30, 0x1E31, + 2, 0x1E32, 0x1E33, + 2, 0x1E34, 0x1E35, + 2, 0x1E36, 0x1E37, + 2, 0x1E38, 0x1E39, + 2, 0x1E3A, 0x1E3B, + 2, 0x1E3C, 0x1E3D, + 2, 0x1E3E, 0x1E3F, + 2, 0x1E40, 0x1E41, + 2, 0x1E42, 0x1E43, + 2, 0x1E44, 0x1E45, + 2, 0x1E46, 0x1E47, + 2, 0x1E48, 0x1E49, + 2, 0x1E4A, 0x1E4B, + 2, 0x1E4C, 0x1E4D, + 2, 0x1E4E, 0x1E4F, + 2, 0x1E50, 0x1E51, + 2, 0x1E52, 0x1E53, + 2, 0x1E54, 0x1E55, + 2, 0x1E56, 0x1E57, + 2, 0x1E58, 0x1E59, + 2, 0x1E5A, 0x1E5B, + 2, 0x1E5C, 0x1E5D, + 2, 0x1E5E, 0x1E5F, + 3, 0x1E60, 0x1E61, 0x1E9B, + 2, 0x1E62, 0x1E63, + 2, 0x1E64, 0x1E65, + 2, 0x1E66, 0x1E67, + 2, 0x1E68, 0x1E69, + 2, 0x1E6A, 0x1E6B, + 2, 0x1E6C, 0x1E6D, + 2, 0x1E6E, 0x1E6F, + 2, 0x1E70, 0x1E71, + 2, 0x1E72, 0x1E73, + 2, 0x1E74, 0x1E75, + 2, 0x1E76, 0x1E77, + 2, 0x1E78, 0x1E79, + 2, 0x1E7A, 0x1E7B, + 2, 0x1E7C, 0x1E7D, + 2, 0x1E7E, 0x1E7F, + 2, 0x1E80, 0x1E81, + 2, 0x1E82, 0x1E83, + 2, 0x1E84, 0x1E85, + 2, 0x1E86, 0x1E87, + 2, 0x1E88, 0x1E89, + 2, 0x1E8A, 0x1E8B, + 2, 0x1E8C, 0x1E8D, + 2, 0x1E8E, 0x1E8F, + 2, 0x1E90, 0x1E91, + 2, 0x1E92, 0x1E93, + 2, 0x1E94, 0x1E95, + 2, 0x1EA0, 0x1EA1, + 2, 0x1EA2, 0x1EA3, + 2, 0x1EA4, 0x1EA5, + 2, 0x1EA6, 0x1EA7, + 2, 0x1EA8, 0x1EA9, + 2, 0x1EAA, 0x1EAB, + 2, 0x1EAC, 0x1EAD, + 2, 0x1EAE, 0x1EAF, + 2, 0x1EB0, 0x1EB1, + 2, 0x1EB2, 0x1EB3, + 2, 0x1EB4, 0x1EB5, + 2, 0x1EB6, 0x1EB7, + 2, 0x1EB8, 0x1EB9, + 2, 0x1EBA, 0x1EBB, + 2, 0x1EBC, 0x1EBD, + 2, 0x1EBE, 0x1EBF, + 2, 0x1EC0, 0x1EC1, + 2, 0x1EC2, 0x1EC3, + 2, 0x1EC4, 0x1EC5, + 2, 0x1EC6, 0x1EC7, + 2, 0x1EC8, 0x1EC9, + 2, 0x1ECA, 0x1ECB, + 2, 0x1ECC, 0x1ECD, + 2, 0x1ECE, 0x1ECF, + 2, 0x1ED0, 0x1ED1, + 2, 0x1ED2, 0x1ED3, + 2, 0x1ED4, 0x1ED5, + 2, 0x1ED6, 0x1ED7, + 2, 0x1ED8, 0x1ED9, + 2, 0x1EDA, 0x1EDB, + 2, 0x1EDC, 0x1EDD, + 2, 0x1EDE, 0x1EDF, + 2, 0x1EE0, 0x1EE1, + 2, 0x1EE2, 0x1EE3, + 2, 0x1EE4, 0x1EE5, + 2, 0x1EE6, 0x1EE7, + 2, 0x1EE8, 0x1EE9, + 2, 0x1EEA, 0x1EEB, + 2, 0x1EEC, 0x1EED, + 2, 0x1EEE, 0x1EEF, + 2, 0x1EF0, 0x1EF1, + 2, 0x1EF2, 0x1EF3, + 2, 0x1EF4, 0x1EF5, + 2, 0x1EF6, 0x1EF7, + 2, 0x1EF8, 0x1EF9, + 2, 0x1EFA, 0x1EFB, + 2, 0x1EFC, 0x1EFD, + 2, 0x1EFE, 0x1EFF, + 2, 0x1F00, 0x1F08, + 2, 0x1F01, 0x1F09, + 2, 0x1F02, 0x1F0A, + 2, 0x1F03, 0x1F0B, + 2, 0x1F04, 0x1F0C, + 2, 0x1F05, 0x1F0D, + 2, 0x1F06, 0x1F0E, + 2, 0x1F07, 0x1F0F, + 2, 0x1F10, 0x1F18, + 2, 0x1F11, 0x1F19, + 2, 0x1F12, 0x1F1A, + 2, 0x1F13, 0x1F1B, + 2, 0x1F14, 0x1F1C, + 2, 0x1F15, 0x1F1D, + 2, 0x1F20, 0x1F28, + 2, 0x1F21, 0x1F29, + 2, 0x1F22, 0x1F2A, + 2, 0x1F23, 0x1F2B, + 2, 0x1F24, 0x1F2C, + 2, 0x1F25, 0x1F2D, + 2, 0x1F26, 0x1F2E, + 2, 0x1F27, 0x1F2F, + 2, 0x1F30, 0x1F38, + 2, 0x1F31, 0x1F39, + 2, 0x1F32, 0x1F3A, + 2, 0x1F33, 0x1F3B, + 2, 0x1F34, 0x1F3C, + 2, 0x1F35, 0x1F3D, + 2, 0x1F36, 0x1F3E, + 2, 0x1F37, 0x1F3F, + 2, 0x1F40, 0x1F48, + 2, 0x1F41, 0x1F49, + 2, 0x1F42, 0x1F4A, + 2, 0x1F43, 0x1F4B, + 2, 0x1F44, 0x1F4C, + 2, 0x1F45, 0x1F4D, + 2, 0x1F51, 0x1F59, + 2, 0x1F53, 0x1F5B, + 2, 0x1F55, 0x1F5D, + 2, 0x1F57, 0x1F5F, + 2, 0x1F60, 0x1F68, + 2, 0x1F61, 0x1F69, + 2, 0x1F62, 0x1F6A, + 2, 0x1F63, 0x1F6B, + 2, 0x1F64, 0x1F6C, + 2, 0x1F65, 0x1F6D, + 2, 0x1F66, 0x1F6E, + 2, 0x1F67, 0x1F6F, + 2, 0x1F70, 0x1FBA, + 2, 0x1F71, 0x1FBB, + 2, 0x1F72, 0x1FC8, + 2, 0x1F73, 0x1FC9, + 2, 0x1F74, 0x1FCA, + 2, 0x1F75, 0x1FCB, + 2, 0x1F76, 0x1FDA, + 2, 0x1F77, 0x1FDB, + 2, 0x1F78, 0x1FF8, + 2, 0x1F79, 0x1FF9, + 2, 0x1F7A, 0x1FEA, + 2, 0x1F7B, 0x1FEB, + 2, 0x1F7C, 0x1FFA, + 2, 0x1F7D, 0x1FFB, + 2, 0x1F80, 0x1F88, + 2, 0x1F81, 0x1F89, + 2, 0x1F82, 0x1F8A, + 2, 0x1F83, 0x1F8B, + 2, 0x1F84, 0x1F8C, + 2, 0x1F85, 0x1F8D, + 2, 0x1F86, 0x1F8E, + 2, 0x1F87, 0x1F8F, + 2, 0x1F90, 0x1F98, + 2, 0x1F91, 0x1F99, + 2, 0x1F92, 0x1F9A, + 2, 0x1F93, 0x1F9B, + 2, 0x1F94, 0x1F9C, + 2, 0x1F95, 0x1F9D, + 2, 0x1F96, 0x1F9E, + 2, 0x1F97, 0x1F9F, + 2, 0x1FA0, 0x1FA8, + 2, 0x1FA1, 0x1FA9, + 2, 0x1FA2, 0x1FAA, + 2, 0x1FA3, 0x1FAB, + 2, 0x1FA4, 0x1FAC, + 2, 0x1FA5, 0x1FAD, + 2, 0x1FA6, 0x1FAE, + 2, 0x1FA7, 0x1FAF, + 2, 0x1FB0, 0x1FB8, + 2, 0x1FB1, 0x1FB9, + 2, 0x1FB3, 0x1FBC, + 2, 0x1FC3, 0x1FCC, + 2, 0x1FD0, 0x1FD8, + 2, 0x1FD1, 0x1FD9, + 2, 0x1FE0, 0x1FE8, + 2, 0x1FE1, 0x1FE9, + 2, 0x1FE5, 0x1FEC, + 2, 0x1FF3, 0x1FFC, + 2, 0x2132, 0x214E, + 2, 0x2160, 0x2170, + 2, 0x2161, 0x2171, + 2, 0x2162, 0x2172, + 2, 0x2163, 0x2173, + 2, 0x2164, 0x2174, + 2, 0x2165, 0x2175, + 2, 0x2166, 0x2176, + 2, 0x2167, 0x2177, + 2, 0x2168, 0x2178, + 2, 0x2169, 0x2179, + 2, 0x216A, 0x217A, + 2, 0x216B, 0x217B, + 2, 0x216C, 0x217C, + 2, 0x216D, 0x217D, + 2, 0x216E, 0x217E, + 2, 0x216F, 0x217F, + 2, 0x2183, 0x2184, + 2, 0x24B6, 0x24D0, + 2, 0x24B7, 0x24D1, + 2, 0x24B8, 0x24D2, + 2, 0x24B9, 0x24D3, + 2, 0x24BA, 0x24D4, + 2, 0x24BB, 0x24D5, + 2, 0x24BC, 0x24D6, + 2, 0x24BD, 0x24D7, + 2, 0x24BE, 0x24D8, + 2, 0x24BF, 0x24D9, + 2, 0x24C0, 0x24DA, + 2, 0x24C1, 0x24DB, + 2, 0x24C2, 0x24DC, + 2, 0x24C3, 0x24DD, + 2, 0x24C4, 0x24DE, + 2, 0x24C5, 0x24DF, + 2, 0x24C6, 0x24E0, + 2, 0x24C7, 0x24E1, + 2, 0x24C8, 0x24E2, + 2, 0x24C9, 0x24E3, + 2, 0x24CA, 0x24E4, + 2, 0x24CB, 0x24E5, + 2, 0x24CC, 0x24E6, + 2, 0x24CD, 0x24E7, + 2, 0x24CE, 0x24E8, + 2, 0x24CF, 0x24E9, + 2, 0x2C00, 0x2C30, + 2, 0x2C01, 0x2C31, + 2, 0x2C02, 0x2C32, + 2, 0x2C03, 0x2C33, + 2, 0x2C04, 0x2C34, + 2, 0x2C05, 0x2C35, + 2, 0x2C06, 0x2C36, + 2, 0x2C07, 0x2C37, + 2, 0x2C08, 0x2C38, + 2, 0x2C09, 0x2C39, + 2, 0x2C0A, 0x2C3A, + 2, 0x2C0B, 0x2C3B, + 2, 0x2C0C, 0x2C3C, + 2, 0x2C0D, 0x2C3D, + 2, 0x2C0E, 0x2C3E, + 2, 0x2C0F, 0x2C3F, + 2, 0x2C10, 0x2C40, + 2, 0x2C11, 0x2C41, + 2, 0x2C12, 0x2C42, + 2, 0x2C13, 0x2C43, + 2, 0x2C14, 0x2C44, + 2, 0x2C15, 0x2C45, + 2, 0x2C16, 0x2C46, + 2, 0x2C17, 0x2C47, + 2, 0x2C18, 0x2C48, + 2, 0x2C19, 0x2C49, + 2, 0x2C1A, 0x2C4A, + 2, 0x2C1B, 0x2C4B, + 2, 0x2C1C, 0x2C4C, + 2, 0x2C1D, 0x2C4D, + 2, 0x2C1E, 0x2C4E, + 2, 0x2C1F, 0x2C4F, + 2, 0x2C20, 0x2C50, + 2, 0x2C21, 0x2C51, + 2, 0x2C22, 0x2C52, + 2, 0x2C23, 0x2C53, + 2, 0x2C24, 0x2C54, + 2, 0x2C25, 0x2C55, + 2, 0x2C26, 0x2C56, + 2, 0x2C27, 0x2C57, + 2, 0x2C28, 0x2C58, + 2, 0x2C29, 0x2C59, + 2, 0x2C2A, 0x2C5A, + 2, 0x2C2B, 0x2C5B, + 2, 0x2C2C, 0x2C5C, + 2, 0x2C2D, 0x2C5D, + 2, 0x2C2E, 0x2C5E, + 2, 0x2C2F, 0x2C5F, + 2, 0x2C60, 0x2C61, + 2, 0x2C67, 0x2C68, + 2, 0x2C69, 0x2C6A, + 2, 0x2C6B, 0x2C6C, + 2, 0x2C72, 0x2C73, + 2, 0x2C75, 0x2C76, + 2, 0x2C80, 0x2C81, + 2, 0x2C82, 0x2C83, + 2, 0x2C84, 0x2C85, + 2, 0x2C86, 0x2C87, + 2, 0x2C88, 0x2C89, + 2, 0x2C8A, 0x2C8B, + 2, 0x2C8C, 0x2C8D, + 2, 0x2C8E, 0x2C8F, + 2, 0x2C90, 0x2C91, + 2, 0x2C92, 0x2C93, + 2, 0x2C94, 0x2C95, + 2, 0x2C96, 0x2C97, + 2, 0x2C98, 0x2C99, + 2, 0x2C9A, 0x2C9B, + 2, 0x2C9C, 0x2C9D, + 2, 0x2C9E, 0x2C9F, + 2, 0x2CA0, 0x2CA1, + 2, 0x2CA2, 0x2CA3, + 2, 0x2CA4, 0x2CA5, + 2, 0x2CA6, 0x2CA7, + 2, 0x2CA8, 0x2CA9, + 2, 0x2CAA, 0x2CAB, + 2, 0x2CAC, 0x2CAD, + 2, 0x2CAE, 0x2CAF, + 2, 0x2CB0, 0x2CB1, + 2, 0x2CB2, 0x2CB3, + 2, 0x2CB4, 0x2CB5, + 2, 0x2CB6, 0x2CB7, + 2, 0x2CB8, 0x2CB9, + 2, 0x2CBA, 0x2CBB, + 2, 0x2CBC, 0x2CBD, + 2, 0x2CBE, 0x2CBF, + 2, 0x2CC0, 0x2CC1, + 2, 0x2CC2, 0x2CC3, + 2, 0x2CC4, 0x2CC5, + 2, 0x2CC6, 0x2CC7, + 2, 0x2CC8, 0x2CC9, + 2, 0x2CCA, 0x2CCB, + 2, 0x2CCC, 0x2CCD, + 2, 0x2CCE, 0x2CCF, + 2, 0x2CD0, 0x2CD1, + 2, 0x2CD2, 0x2CD3, + 2, 0x2CD4, 0x2CD5, + 2, 0x2CD6, 0x2CD7, + 2, 0x2CD8, 0x2CD9, + 2, 0x2CDA, 0x2CDB, + 2, 0x2CDC, 0x2CDD, + 2, 0x2CDE, 0x2CDF, + 2, 0x2CE0, 0x2CE1, + 2, 0x2CE2, 0x2CE3, + 2, 0x2CEB, 0x2CEC, + 2, 0x2CED, 0x2CEE, + 2, 0x2CF2, 0x2CF3, + 2, 0xA640, 0xA641, + 2, 0xA642, 0xA643, + 2, 0xA644, 0xA645, + 2, 0xA646, 0xA647, + 2, 0xA648, 0xA649, + 2, 0xA64C, 0xA64D, + 2, 0xA64E, 0xA64F, + 2, 0xA650, 0xA651, + 2, 0xA652, 0xA653, + 2, 0xA654, 0xA655, + 2, 0xA656, 0xA657, + 2, 0xA658, 0xA659, + 2, 0xA65A, 0xA65B, + 2, 0xA65C, 0xA65D, + 2, 0xA65E, 0xA65F, + 2, 0xA660, 0xA661, + 2, 0xA662, 0xA663, + 2, 0xA664, 0xA665, + 2, 0xA666, 0xA667, + 2, 0xA668, 0xA669, + 2, 0xA66A, 0xA66B, + 2, 0xA66C, 0xA66D, + 2, 0xA680, 0xA681, + 2, 0xA682, 0xA683, + 2, 0xA684, 0xA685, + 2, 0xA686, 0xA687, + 2, 0xA688, 0xA689, + 2, 0xA68A, 0xA68B, + 2, 0xA68C, 0xA68D, + 2, 0xA68E, 0xA68F, + 2, 0xA690, 0xA691, + 2, 0xA692, 0xA693, + 2, 0xA694, 0xA695, + 2, 0xA696, 0xA697, + 2, 0xA698, 0xA699, + 2, 0xA69A, 0xA69B, + 2, 0xA722, 0xA723, + 2, 0xA724, 0xA725, + 2, 0xA726, 0xA727, + 2, 0xA728, 0xA729, + 2, 0xA72A, 0xA72B, + 2, 0xA72C, 0xA72D, + 2, 0xA72E, 0xA72F, + 2, 0xA732, 0xA733, + 2, 0xA734, 0xA735, + 2, 0xA736, 0xA737, + 2, 0xA738, 0xA739, + 2, 0xA73A, 0xA73B, + 2, 0xA73C, 0xA73D, + 2, 0xA73E, 0xA73F, + 2, 0xA740, 0xA741, + 2, 0xA742, 0xA743, + 2, 0xA744, 0xA745, + 2, 0xA746, 0xA747, + 2, 0xA748, 0xA749, + 2, 0xA74A, 0xA74B, + 2, 0xA74C, 0xA74D, + 2, 0xA74E, 0xA74F, + 2, 0xA750, 0xA751, + 2, 0xA752, 0xA753, + 2, 0xA754, 0xA755, + 2, 0xA756, 0xA757, + 2, 0xA758, 0xA759, + 2, 0xA75A, 0xA75B, + 2, 0xA75C, 0xA75D, + 2, 0xA75E, 0xA75F, + 2, 0xA760, 0xA761, + 2, 0xA762, 0xA763, + 2, 0xA764, 0xA765, + 2, 0xA766, 0xA767, + 2, 0xA768, 0xA769, + 2, 0xA76A, 0xA76B, + 2, 0xA76C, 0xA76D, + 2, 0xA76E, 0xA76F, + 2, 0xA779, 0xA77A, + 2, 0xA77B, 0xA77C, + 2, 0xA77E, 0xA77F, + 2, 0xA780, 0xA781, + 2, 0xA782, 0xA783, + 2, 0xA784, 0xA785, + 2, 0xA786, 0xA787, + 2, 0xA78B, 0xA78C, + 2, 0xA790, 0xA791, + 2, 0xA792, 0xA793, + 2, 0xA794, 0xA7C4, + 2, 0xA796, 0xA797, + 2, 0xA798, 0xA799, + 2, 0xA79A, 0xA79B, + 2, 0xA79C, 0xA79D, + 2, 0xA79E, 0xA79F, + 2, 0xA7A0, 0xA7A1, + 2, 0xA7A2, 0xA7A3, + 2, 0xA7A4, 0xA7A5, + 2, 0xA7A6, 0xA7A7, + 2, 0xA7A8, 0xA7A9, + 2, 0xA7B3, 0xAB53, + 2, 0xA7B4, 0xA7B5, + 2, 0xA7B6, 0xA7B7, + 2, 0xA7B8, 0xA7B9, + 2, 0xA7BA, 0xA7BB, + 2, 0xA7BC, 0xA7BD, + 2, 0xA7BE, 0xA7BF, + 2, 0xA7C0, 0xA7C1, + 2, 0xA7C2, 0xA7C3, + 2, 0xA7C7, 0xA7C8, + 2, 0xA7C9, 0xA7CA, + 2, 0xA7CC, 0xA7CD, + 2, 0xA7D0, 0xA7D1, + 2, 0xA7D6, 0xA7D7, + 2, 0xA7D8, 0xA7D9, + 2, 0xA7DA, 0xA7DB, + 2, 0xA7F5, 0xA7F6, + 2, 0xFB05, 0xFB06, + 2, 0xFF21, 0xFF41, + 2, 0xFF22, 0xFF42, + 2, 0xFF23, 0xFF43, + 2, 0xFF24, 0xFF44, + 2, 0xFF25, 0xFF45, + 2, 0xFF26, 0xFF46, + 2, 0xFF27, 0xFF47, + 2, 0xFF28, 0xFF48, + 2, 0xFF29, 0xFF49, + 2, 0xFF2A, 0xFF4A, + 2, 0xFF2B, 0xFF4B, + 2, 0xFF2C, 0xFF4C, + 2, 0xFF2D, 0xFF4D, + 2, 0xFF2E, 0xFF4E, + 2, 0xFF2F, 0xFF4F, + 2, 0xFF30, 0xFF50, + 2, 0xFF31, 0xFF51, + 2, 0xFF32, 0xFF52, + 2, 0xFF33, 0xFF53, + 2, 0xFF34, 0xFF54, + 2, 0xFF35, 0xFF55, + 2, 0xFF36, 0xFF56, + 2, 0xFF37, 0xFF57, + 2, 0xFF38, 0xFF58, + 2, 0xFF39, 0xFF59, + 2, 0xFF3A, 0xFF5A, + 2, 0x10400, 0x10428, + 2, 0x10401, 0x10429, + 2, 0x10402, 0x1042A, + 2, 0x10403, 0x1042B, + 2, 0x10404, 0x1042C, + 2, 0x10405, 0x1042D, + 2, 0x10406, 0x1042E, + 2, 0x10407, 0x1042F, + 2, 0x10408, 0x10430, + 2, 0x10409, 0x10431, + 2, 0x1040A, 0x10432, + 2, 0x1040B, 0x10433, + 2, 0x1040C, 0x10434, + 2, 0x1040D, 0x10435, + 2, 0x1040E, 0x10436, + 2, 0x1040F, 0x10437, + 2, 0x10410, 0x10438, + 2, 0x10411, 0x10439, + 2, 0x10412, 0x1043A, + 2, 0x10413, 0x1043B, + 2, 0x10414, 0x1043C, + 2, 0x10415, 0x1043D, + 2, 0x10416, 0x1043E, + 2, 0x10417, 0x1043F, + 2, 0x10418, 0x10440, + 2, 0x10419, 0x10441, + 2, 0x1041A, 0x10442, + 2, 0x1041B, 0x10443, + 2, 0x1041C, 0x10444, + 2, 0x1041D, 0x10445, + 2, 0x1041E, 0x10446, + 2, 0x1041F, 0x10447, + 2, 0x10420, 0x10448, + 2, 0x10421, 0x10449, + 2, 0x10422, 0x1044A, + 2, 0x10423, 0x1044B, + 2, 0x10424, 0x1044C, + 2, 0x10425, 0x1044D, + 2, 0x10426, 0x1044E, + 2, 0x10427, 0x1044F, + 2, 0x104B0, 0x104D8, + 2, 0x104B1, 0x104D9, + 2, 0x104B2, 0x104DA, + 2, 0x104B3, 0x104DB, + 2, 0x104B4, 0x104DC, + 2, 0x104B5, 0x104DD, + 2, 0x104B6, 0x104DE, + 2, 0x104B7, 0x104DF, + 2, 0x104B8, 0x104E0, + 2, 0x104B9, 0x104E1, + 2, 0x104BA, 0x104E2, + 2, 0x104BB, 0x104E3, + 2, 0x104BC, 0x104E4, + 2, 0x104BD, 0x104E5, + 2, 0x104BE, 0x104E6, + 2, 0x104BF, 0x104E7, + 2, 0x104C0, 0x104E8, + 2, 0x104C1, 0x104E9, + 2, 0x104C2, 0x104EA, + 2, 0x104C3, 0x104EB, + 2, 0x104C4, 0x104EC, + 2, 0x104C5, 0x104ED, + 2, 0x104C6, 0x104EE, + 2, 0x104C7, 0x104EF, + 2, 0x104C8, 0x104F0, + 2, 0x104C9, 0x104F1, + 2, 0x104CA, 0x104F2, + 2, 0x104CB, 0x104F3, + 2, 0x104CC, 0x104F4, + 2, 0x104CD, 0x104F5, + 2, 0x104CE, 0x104F6, + 2, 0x104CF, 0x104F7, + 2, 0x104D0, 0x104F8, + 2, 0x104D1, 0x104F9, + 2, 0x104D2, 0x104FA, + 2, 0x104D3, 0x104FB, + 2, 0x10570, 0x10597, + 2, 0x10571, 0x10598, + 2, 0x10572, 0x10599, + 2, 0x10573, 0x1059A, + 2, 0x10574, 0x1059B, + 2, 0x10575, 0x1059C, + 2, 0x10576, 0x1059D, + 2, 0x10577, 0x1059E, + 2, 0x10578, 0x1059F, + 2, 0x10579, 0x105A0, + 2, 0x1057A, 0x105A1, + 2, 0x1057C, 0x105A3, + 2, 0x1057D, 0x105A4, + 2, 0x1057E, 0x105A5, + 2, 0x1057F, 0x105A6, + 2, 0x10580, 0x105A7, + 2, 0x10581, 0x105A8, + 2, 0x10582, 0x105A9, + 2, 0x10583, 0x105AA, + 2, 0x10584, 0x105AB, + 2, 0x10585, 0x105AC, + 2, 0x10586, 0x105AD, + 2, 0x10587, 0x105AE, + 2, 0x10588, 0x105AF, + 2, 0x10589, 0x105B0, + 2, 0x1058A, 0x105B1, + 2, 0x1058C, 0x105B3, + 2, 0x1058D, 0x105B4, + 2, 0x1058E, 0x105B5, + 2, 0x1058F, 0x105B6, + 2, 0x10590, 0x105B7, + 2, 0x10591, 0x105B8, + 2, 0x10592, 0x105B9, + 2, 0x10594, 0x105BB, + 2, 0x10595, 0x105BC, + 2, 0x10C80, 0x10CC0, + 2, 0x10C81, 0x10CC1, + 2, 0x10C82, 0x10CC2, + 2, 0x10C83, 0x10CC3, + 2, 0x10C84, 0x10CC4, + 2, 0x10C85, 0x10CC5, + 2, 0x10C86, 0x10CC6, + 2, 0x10C87, 0x10CC7, + 2, 0x10C88, 0x10CC8, + 2, 0x10C89, 0x10CC9, + 2, 0x10C8A, 0x10CCA, + 2, 0x10C8B, 0x10CCB, + 2, 0x10C8C, 0x10CCC, + 2, 0x10C8D, 0x10CCD, + 2, 0x10C8E, 0x10CCE, + 2, 0x10C8F, 0x10CCF, + 2, 0x10C90, 0x10CD0, + 2, 0x10C91, 0x10CD1, + 2, 0x10C92, 0x10CD2, + 2, 0x10C93, 0x10CD3, + 2, 0x10C94, 0x10CD4, + 2, 0x10C95, 0x10CD5, + 2, 0x10C96, 0x10CD6, + 2, 0x10C97, 0x10CD7, + 2, 0x10C98, 0x10CD8, + 2, 0x10C99, 0x10CD9, + 2, 0x10C9A, 0x10CDA, + 2, 0x10C9B, 0x10CDB, + 2, 0x10C9C, 0x10CDC, + 2, 0x10C9D, 0x10CDD, + 2, 0x10C9E, 0x10CDE, + 2, 0x10C9F, 0x10CDF, + 2, 0x10CA0, 0x10CE0, + 2, 0x10CA1, 0x10CE1, + 2, 0x10CA2, 0x10CE2, + 2, 0x10CA3, 0x10CE3, + 2, 0x10CA4, 0x10CE4, + 2, 0x10CA5, 0x10CE5, + 2, 0x10CA6, 0x10CE6, + 2, 0x10CA7, 0x10CE7, + 2, 0x10CA8, 0x10CE8, + 2, 0x10CA9, 0x10CE9, + 2, 0x10CAA, 0x10CEA, + 2, 0x10CAB, 0x10CEB, + 2, 0x10CAC, 0x10CEC, + 2, 0x10CAD, 0x10CED, + 2, 0x10CAE, 0x10CEE, + 2, 0x10CAF, 0x10CEF, + 2, 0x10CB0, 0x10CF0, + 2, 0x10CB1, 0x10CF1, + 2, 0x10CB2, 0x10CF2, + 2, 0x10D50, 0x10D70, + 2, 0x10D51, 0x10D71, + 2, 0x10D52, 0x10D72, + 2, 0x10D53, 0x10D73, + 2, 0x10D54, 0x10D74, + 2, 0x10D55, 0x10D75, + 2, 0x10D56, 0x10D76, + 2, 0x10D57, 0x10D77, + 2, 0x10D58, 0x10D78, + 2, 0x10D59, 0x10D79, + 2, 0x10D5A, 0x10D7A, + 2, 0x10D5B, 0x10D7B, + 2, 0x10D5C, 0x10D7C, + 2, 0x10D5D, 0x10D7D, + 2, 0x10D5E, 0x10D7E, + 2, 0x10D5F, 0x10D7F, + 2, 0x10D60, 0x10D80, + 2, 0x10D61, 0x10D81, + 2, 0x10D62, 0x10D82, + 2, 0x10D63, 0x10D83, + 2, 0x10D64, 0x10D84, + 2, 0x10D65, 0x10D85, + 2, 0x118A0, 0x118C0, + 2, 0x118A1, 0x118C1, + 2, 0x118A2, 0x118C2, + 2, 0x118A3, 0x118C3, + 2, 0x118A4, 0x118C4, + 2, 0x118A5, 0x118C5, + 2, 0x118A6, 0x118C6, + 2, 0x118A7, 0x118C7, + 2, 0x118A8, 0x118C8, + 2, 0x118A9, 0x118C9, + 2, 0x118AA, 0x118CA, + 2, 0x118AB, 0x118CB, + 2, 0x118AC, 0x118CC, + 2, 0x118AD, 0x118CD, + 2, 0x118AE, 0x118CE, + 2, 0x118AF, 0x118CF, + 2, 0x118B0, 0x118D0, + 2, 0x118B1, 0x118D1, + 2, 0x118B2, 0x118D2, + 2, 0x118B3, 0x118D3, + 2, 0x118B4, 0x118D4, + 2, 0x118B5, 0x118D5, + 2, 0x118B6, 0x118D6, + 2, 0x118B7, 0x118D7, + 2, 0x118B8, 0x118D8, + 2, 0x118B9, 0x118D9, + 2, 0x118BA, 0x118DA, + 2, 0x118BB, 0x118DB, + 2, 0x118BC, 0x118DC, + 2, 0x118BD, 0x118DD, + 2, 0x118BE, 0x118DE, + 2, 0x118BF, 0x118DF, + 2, 0x16E40, 0x16E60, + 2, 0x16E41, 0x16E61, + 2, 0x16E42, 0x16E62, + 2, 0x16E43, 0x16E63, + 2, 0x16E44, 0x16E64, + 2, 0x16E45, 0x16E65, + 2, 0x16E46, 0x16E66, + 2, 0x16E47, 0x16E67, + 2, 0x16E48, 0x16E68, + 2, 0x16E49, 0x16E69, + 2, 0x16E4A, 0x16E6A, + 2, 0x16E4B, 0x16E6B, + 2, 0x16E4C, 0x16E6C, + 2, 0x16E4D, 0x16E6D, + 2, 0x16E4E, 0x16E6E, + 2, 0x16E4F, 0x16E6F, + 2, 0x16E50, 0x16E70, + 2, 0x16E51, 0x16E71, + 2, 0x16E52, 0x16E72, + 2, 0x16E53, 0x16E73, + 2, 0x16E54, 0x16E74, + 2, 0x16E55, 0x16E75, + 2, 0x16E56, 0x16E76, + 2, 0x16E57, 0x16E77, + 2, 0x16E58, 0x16E78, + 2, 0x16E59, 0x16E79, + 2, 0x16E5A, 0x16E7A, + 2, 0x16E5B, 0x16E7B, + 2, 0x16E5C, 0x16E7C, + 2, 0x16E5D, 0x16E7D, + 2, 0x16E5E, 0x16E7E, + 2, 0x16E5F, 0x16E7F, + 2, 0x1E900, 0x1E922, + 2, 0x1E901, 0x1E923, + 2, 0x1E902, 0x1E924, + 2, 0x1E903, 0x1E925, + 2, 0x1E904, 0x1E926, + 2, 0x1E905, 0x1E927, + 2, 0x1E906, 0x1E928, + 2, 0x1E907, 0x1E929, + 2, 0x1E908, 0x1E92A, + 2, 0x1E909, 0x1E92B, + 2, 0x1E90A, 0x1E92C, + 2, 0x1E90B, 0x1E92D, + 2, 0x1E90C, 0x1E92E, + 2, 0x1E90D, 0x1E92F, + 2, 0x1E90E, 0x1E930, + 2, 0x1E90F, 0x1E931, + 2, 0x1E910, 0x1E932, + 2, 0x1E911, 0x1E933, + 2, 0x1E912, 0x1E934, + 2, 0x1E913, 0x1E935, + 2, 0x1E914, 0x1E936, + 2, 0x1E915, 0x1E937, + 2, 0x1E916, 0x1E938, + 2, 0x1E917, 0x1E939, + 2, 0x1E918, 0x1E93A, + 2, 0x1E919, 0x1E93B, + 2, 0x1E91A, 0x1E93C, + 2, 0x1E91B, 0x1E93D, + 2, 0x1E91C, 0x1E93E, + 2, 0x1E91D, 0x1E93F, + 2, 0x1E91E, 0x1E940, + 2, 0x1E91F, 0x1E941, + 2, 0x1E920, 0x1E942, + 2, 0x1E921, 0x1E943, +}; +const size_t k_case_orbits_n = sizeof(k_case_orbits) / sizeof(k_case_orbits[0]); + +const uint32_t k_case_multi[] = { + 0xDF, 0x130, 0x149, 0x1F0, 0x390, 0x3B0, 0x587, 0x1E96, 0x1E97, 0x1E98, + 0x1E99, 0x1E9A, 0x1E9E, 0x1F50, 0x1F52, 0x1F54, 0x1F56, 0x1F80, 0x1F81, 0x1F82, + 0x1F83, 0x1F84, 0x1F85, 0x1F86, 0x1F87, 0x1F88, 0x1F89, 0x1F8A, 0x1F8B, 0x1F8C, + 0x1F8D, 0x1F8E, 0x1F8F, 0x1F90, 0x1F91, 0x1F92, 0x1F93, 0x1F94, 0x1F95, 0x1F96, + 0x1F97, 0x1F98, 0x1F99, 0x1F9A, 0x1F9B, 0x1F9C, 0x1F9D, 0x1F9E, 0x1F9F, 0x1FA0, + 0x1FA1, 0x1FA2, 0x1FA3, 0x1FA4, 0x1FA5, 0x1FA6, 0x1FA7, 0x1FA8, 0x1FA9, 0x1FAA, + 0x1FAB, 0x1FAC, 0x1FAD, 0x1FAE, 0x1FAF, 0x1FB2, 0x1FB3, 0x1FB4, 0x1FB6, 0x1FB7, + 0x1FBC, 0x1FC2, 0x1FC3, 0x1FC4, 0x1FC6, 0x1FC7, 0x1FCC, 0x1FD2, 0x1FD3, 0x1FD6, + 0x1FD7, 0x1FE2, 0x1FE3, 0x1FE4, 0x1FE6, 0x1FE7, 0x1FF2, 0x1FF3, 0x1FF4, 0x1FF6, + 0x1FF7, 0x1FFC, 0xFB00, 0xFB01, 0xFB02, 0xFB03, 0xFB04, 0xFB05, 0xFB06, 0xFB13, + 0xFB14, 0xFB15, 0xFB16, 0xFB17, +}; +const size_t k_case_multi_n = sizeof(k_case_multi) / sizeof(k_case_multi[0]); + +} /* namespace ucd */ +} /* namespace rad */ diff --git a/core/text/tokenizer_ucd.h b/core/text/tokenizer_ucd.h new file mode 100644 index 00000000..ca3a726d --- /dev/null +++ b/core/text/tokenizer_ucd.h @@ -0,0 +1,49 @@ +/* tokenizer_ucd.h -- the Unicode properties a pre-tokeniser pattern can name. + * + * The tables are generated (tools/gen_tokenizer_ucd.cpp) by asking Oniguruma, the engine + * HuggingFace tokenizers matches Split patterns with, what each property contains. A pattern in a + * tokenizer.json means whatever it means THERE, so that is the one definition this compiler has: + * the general categories at Oniguruma's Unicode version, its `\s`, `\d` and `\w`, its scripts, and + * its case-folding orbits for `(?i)`. + */ +#pragma once +#include +#include + +namespace rad { +namespace ucd { + +/* General category, in the generator's order. */ +enum Gc : uint8_t { + Lu, Ll, Lt, Lm, Lo, Mn, Mc, Me, Nd, Nl, No, + Pc, Pd, Ps, Pe, Pi, Pf, Po, Sm, Sc, Sk, So, + Zs, Zl, Zp, Cc, Cf, Cs, Co, Cn, + kGcCount +}; + +/* A run of one category, from `first` to the next run's `first`. */ +struct GcRun { uint32_t first; uint32_t gc; }; +struct CpRange { uint32_t first, last; }; +struct ScriptTable { const char* name; const CpRange* ranges; size_t n; }; + +extern const GcRun k_gc_runs[]; +extern const size_t k_gc_runs_n; +extern const CpRange k_white_space[]; /* \s */ +extern const size_t k_white_space_n; +extern const CpRange k_digit[]; /* \d */ +extern const size_t k_digit_n; +extern const CpRange k_word[]; /* \w as an atom, and the word test of \b */ +extern const size_t k_word_n; +extern const CpRange k_word_class[]; /* \w inside a bracket class */ +extern const size_t k_word_class_n; +extern const ScriptTable k_scripts[]; +extern const size_t k_scripts_n; +/* Case-folding orbits: each is its length followed by its members. */ +extern const uint32_t k_case_orbits[]; +extern const size_t k_case_orbits_n; +/* Codepoints that (?i) also matches against a multi-codepoint sequence. */ +extern const uint32_t k_case_multi[]; +extern const size_t k_case_multi_n; + +} /* namespace ucd */ +} /* namespace rad */ diff --git a/core/text/unicode_norm.cpp b/core/text/unicode_norm.cpp new file mode 100644 index 00000000..11881090 --- /dev/null +++ b/core/text/unicode_norm.cpp @@ -0,0 +1,161 @@ +#include "text/unicode_norm.h" +#include "llama/src/unicode.h" + +#include + +namespace rad { + +/* Hangul, per UAX #15. 11172 syllables that would otherwise be 11172 table rows. */ +static constexpr uint32_t k_s_base = 0xAC00, k_l_base = 0x1100, k_v_base = 0x1161, + k_t_base = 0x11A7, k_l_count = 19, k_v_count = 21, k_t_count = 28, + k_n_count = k_v_count * k_t_count, /* 588 */ + k_s_count = k_l_count * k_n_count; /* 11172 */ + +uint32_t unorm_ccc(uint32_t cpt) { + /* Binary search over runs. Class 0 is the common case and is not in the table, so the + * miss path is the fast path -- which is what a run of ASCII wants. */ + size_t lo = 0, hi = k_ccc_n; + while (lo < hi) { + size_t mid = (lo + hi) / 2; + if (cpt < k_ccc[mid].first) hi = mid; + else if (cpt > k_ccc[mid].last) lo = mid + 1; + else return k_ccc[mid].ccc; + } + return 0; +} + +static const DecompRow* decomp_row(uint32_t cpt) { + size_t lo = 0, hi = k_decomp_rows_n; + while (lo < hi) { + size_t mid = (lo + hi) / 2; + if (cpt < k_decomp_rows[mid].cpt) hi = mid; + else if (cpt > k_decomp_rows[mid].cpt) lo = mid + 1; + else return &k_decomp_rows[mid]; + } + return nullptr; +} + +/* Canonical ordering: a stable sort of each run of non-starters by combining class. Written as + * an insertion sort over the run rather than std::stable_sort because the runs are almost always + * length 0 or 1 and the comparison is the whole cost. */ +static void canonical_order(std::vector& v) { + for (size_t i = 1; i < v.size(); ++i) { + const uint32_t ccc_i = unorm_ccc(v[i]); + if (ccc_i == 0) continue; + size_t j = i; + while (j > 0) { + const uint32_t ccc_p = unorm_ccc(v[j - 1]); + if (ccc_p == 0 || ccc_p <= ccc_i) break; + std::swap(v[j], v[j - 1]); + --j; + } + } +} + +void unorm_decompose(std::vector& cpts, bool compat) { + std::vector out; + out.reserve(cpts.size() + cpts.size() / 4); + for (uint32_t c : cpts) { + if (c - k_s_base < k_s_count) { /* Hangul syllable */ + const uint32_t s = c - k_s_base; + out.push_back(k_l_base + s / k_n_count); + out.push_back(k_v_base + (s % k_n_count) / k_t_count); + const uint32_t t = s % k_t_count; + if (t) out.push_back(k_t_base + t); + continue; + } + const DecompRow* r = decomp_row(c); + /* The pool holds fully-expanded sequences, so this is one lookup and not a fixed point. + * A row with only a canonical decomposition serves the K forms too. */ + const uint32_t off = (compat && r && r->len_k) ? r->off_k : (r ? r->off_c : 0); + const uint32_t len = (compat && r && r->len_k) ? r->len_k : (r ? r->len_c : 0); + if (!r || len == 0) { out.push_back(c); continue; } + for (uint32_t i = 0; i < len; ++i) out.push_back(k_decomp_pool[off + i]); + } + canonical_order(out); + cpts.swap(out); +} + +static bool compose_pair(uint32_t a, uint32_t b, uint32_t* out) { + /* Hangul first: arithmetic beats a lookup and it is the only algorithmic composition. */ + if (a - k_l_base < k_l_count && b - k_v_base < k_v_count) { + *out = k_s_base + ((a - k_l_base) * k_v_count + (b - k_v_base)) * k_t_count; + return true; + } + if (a - k_s_base < k_s_count && (a - k_s_base) % k_t_count == 0 && + b - k_t_base < k_t_count && b != k_t_base) { + *out = a + (b - k_t_base); + return true; + } + size_t lo = 0, hi = k_compose_n; + while (lo < hi) { + size_t mid = (lo + hi) / 2; + const ComposeRow& r = k_compose[mid]; + if (a < r.a || (a == r.a && b < r.b)) hi = mid; + else if (a > r.a || (a == r.a && b > r.b)) lo = mid + 1; + else { *out = r.c; return true; } + } + return false; +} + +/* Canonical composition, UAX #15 D117. Input must already be in NFD/NFKD order. */ +void unorm_compose(std::vector& cpts) { + if (cpts.empty()) return; + std::vector out; + out.reserve(cpts.size()); + out.push_back(cpts[0]); + size_t starter = 0; /* index in `out` of the last starter */ + uint32_t last_ccc = unorm_ccc(cpts[0]); + /* A leading non-starter is not a starter and can never be a composition target; marking it + * with a ccc that blocks everything is how the standard says to say that. */ + bool have_starter = (last_ccc == 0); + + for (size_t i = 1; i < cpts.size(); ++i) { + const uint32_t c = cpts[i]; + const uint32_t ccc = unorm_ccc(c); + uint32_t composed = 0; + /* Blocked when a character of equal or greater combining class already sits between the + * starter and this one -- that is the whole of the blocking rule. */ + const bool blocked = (last_ccc != 0 && last_ccc >= ccc) || (ccc == 0 && last_ccc != 0); + if (have_starter && !blocked && compose_pair(out[starter], c, &composed)) { + out[starter] = composed; + continue; /* last_ccc unchanged: the pair collapsed */ + } + out.push_back(c); + if (ccc == 0) { starter = out.size() - 1; have_starter = true; } + last_ccc = ccc; + } + cpts.swap(out); +} + +std::vector unorm_nfd(const std::vector& in) { + std::vector v = in; unorm_decompose(v, false); return v; +} +std::vector unorm_nfkd(const std::vector& in) { + std::vector v = in; unorm_decompose(v, true); return v; +} +std::vector unorm_nfc(const std::vector& in) { + std::vector v = in; unorm_decompose(v, false); unorm_compose(v); return v; +} +std::vector unorm_nfkc(const std::vector& in) { + std::vector v = in; unorm_decompose(v, true); unorm_compose(v); return v; +} + +std::string unorm_utf8(const std::string& in, bool compat, bool compose) { + /* ASCII is in every normalisation form already, and it is most of every prompt. Skipping the + * decode/normalise/encode round trip for it is the difference between normalisation costing + * nothing and costing a pass over the prompt. */ + bool ascii = true; + for (unsigned char ch : in) { if (ch >= 0x80) { ascii = false; break; } } + if (ascii) return in; + + std::vector cpts = unicode_cpts_from_utf8(in); + unorm_decompose(cpts, compat); + if (compose) unorm_compose(cpts); + std::string out; + out.reserve(in.size()); + for (uint32_t c : cpts) out += unicode_cpt_to_utf8(c); + return out; +} + +} /* namespace rad */ diff --git a/core/text/unicode_norm.h b/core/text/unicode_norm.h new file mode 100644 index 00000000..d8012ffe --- /dev/null +++ b/core/text/unicode_norm.h @@ -0,0 +1,47 @@ +/* unicode_norm.h -- NFC / NFD / NFKC / NFKD over codepoint vectors. + * + * The four forms are declared steps in a HuggingFace normaliser chain, so the tokeniser has to + * be able to run them or a model that declares one gets silently different token boundaries -- + * the exact failure class spec §12 exists to remove. llama.cpp has no equivalent, so this is + * ours; the tables it reads live in unicode_norm_data.cpp and say there how they were made. + */ +#pragma once +#include +#include +#include +#include + +namespace rad { + +/* One codepoint's decomposition. `off_*`/`len_*` index k_decomp_pool; a zero `len` means the + * codepoint has no decomposition of that kind and stands for itself. */ +struct DecompRow { uint32_t cpt, off_c, len_c, off_k, len_k; }; +struct ComposeRow { uint32_t a, b, c; }; +struct CccRow { uint32_t first, last; uint32_t ccc; }; + +extern const uint32_t k_decomp_pool[]; +extern const size_t k_decomp_pool_n; +extern const DecompRow k_decomp_rows[]; +extern const size_t k_decomp_rows_n; +extern const ComposeRow k_compose[]; +extern const size_t k_compose_n; +extern const CccRow k_ccc[]; +extern const size_t k_ccc_n; + +uint32_t unorm_ccc(uint32_t cpt); + +/* In place, on codepoints. `compat` selects the K forms, `compose` selects the C forms, so the + * four public names below are the four corners of that square. */ +void unorm_decompose(std::vector& cpts, bool compat); +void unorm_compose(std::vector& cpts); + +std::vector unorm_nfd (const std::vector& in); +std::vector unorm_nfkd(const std::vector& in); +std::vector unorm_nfc (const std::vector& in); +std::vector unorm_nfkc(const std::vector& in); + +/* UTF-8 in, UTF-8 out. The tokeniser's step chain works on strings, so this is the form it + * calls; the codepoint forms above are what the tests pin. */ +std::string unorm_utf8(const std::string& in, bool compat, bool compose); + +} /* namespace rad */ diff --git a/core/text/unicode_norm_data.cpp b/core/text/unicode_norm_data.cpp new file mode 100644 index 00000000..a7f350be --- /dev/null +++ b/core/text/unicode_norm_data.cpp @@ -0,0 +1,8099 @@ +/* unicode_norm_data.cpp -- the Unicode normalisation tables, generated data. + * + * llama.cpp does not have these. Its `unicode_ranges_nfd` is a strip-accents table (A-grave to + * A, dropping the mark) used by the WordPiece path, not a canonical decomposition, so NFC/NFD/ + * NFKC/NFKD had to come from somewhere else. They come from here. + * + * HOW THIS FILE IS MADE, so it can be remade. A ~100-line C++ generator runs against a system + * libicu-uc -- these tables came from ICU 78.3; radiance itself links no ICU and never will: + * + * - k_decomp_rows: for every codepoint that is not a Hangul syllable, ICU's NFD and NFKD of + * that single codepoint, kept when it differs from the codepoint. The stored sequences are + * FULLY expanded, so the runtime does one lookup rather than iterating to a fixed point. + * A row whose NFKD equals its NFD points both spans at the same pool offset. + * - k_compose: for every codepoint whose RAW (single-step) canonical decomposition is a pair, + * the pair, kept when ICU's NFC puts the pair back together. That last test is exactly the + * Composition_Exclusion + Full_Composition_Exclusion rule and needs no separate table. + * Deriving from the raw decomposition rather than the full one matters: U+1E14 composes from + * (U+0112, U+0300), neither of which appears in its full NFD. + * - k_ccc: canonical combining class, run-length coded. Class 0 is the default and absent. + * - Hangul is not in any table. UAX #15 gives it as arithmetic and the arithmetic is in + * unicode_norm.cpp, which is smaller and faster than 11172 rows. + * + * The cost of this choice, stated: the tables are pinned to the Unicode version ICU 78.3 carried + * (Unicode 17). A tokenizer.json normalised against a later Unicode differs on codepoints + * assigned after it. That is the same exposure every other engine has and it is bounded; the + * alternative is linking ICU into an inference engine. + */ +#include "text/unicode_norm.h" + +namespace rad { + +/* Fully-expanded decomposition sequences, indexed by k_decomp_rows. */ +const uint32_t k_decomp_pool[] = { +0x20,0x20,0x308,0x61,0x20,0x304,0x32,0x33,0x20,0x301,0x3BC,0x20, +0x327,0x31,0x6F,0x31,0x2044,0x34,0x31,0x2044,0x32,0x33,0x2044,0x34, +0x41,0x300,0x41,0x301,0x41,0x302,0x41,0x303,0x41,0x308,0x41,0x30A, +0x43,0x327,0x45,0x300,0x45,0x301,0x45,0x302,0x45,0x308,0x49,0x300, +0x49,0x301,0x49,0x302,0x49,0x308,0x4E,0x303,0x4F,0x300,0x4F,0x301, +0x4F,0x302,0x4F,0x303,0x4F,0x308,0x55,0x300,0x55,0x301,0x55,0x302, +0x55,0x308,0x59,0x301,0x61,0x300,0x61,0x301,0x61,0x302,0x61,0x303, +0x61,0x308,0x61,0x30A,0x63,0x327,0x65,0x300,0x65,0x301,0x65,0x302, +0x65,0x308,0x69,0x300,0x69,0x301,0x69,0x302,0x69,0x308,0x6E,0x303, +0x6F,0x300,0x6F,0x301,0x6F,0x302,0x6F,0x303,0x6F,0x308,0x75,0x300, +0x75,0x301,0x75,0x302,0x75,0x308,0x79,0x301,0x79,0x308,0x41,0x304, +0x61,0x304,0x41,0x306,0x61,0x306,0x41,0x328,0x61,0x328,0x43,0x301, +0x63,0x301,0x43,0x302,0x63,0x302,0x43,0x307,0x63,0x307,0x43,0x30C, +0x63,0x30C,0x44,0x30C,0x64,0x30C,0x45,0x304,0x65,0x304,0x45,0x306, +0x65,0x306,0x45,0x307,0x65,0x307,0x45,0x328,0x65,0x328,0x45,0x30C, +0x65,0x30C,0x47,0x302,0x67,0x302,0x47,0x306,0x67,0x306,0x47,0x307, +0x67,0x307,0x47,0x327,0x67,0x327,0x48,0x302,0x68,0x302,0x49,0x303, +0x69,0x303,0x49,0x304,0x69,0x304,0x49,0x306,0x69,0x306,0x49,0x328, +0x69,0x328,0x49,0x307,0x49,0x4A,0x69,0x6A,0x4A,0x302,0x6A,0x302, +0x4B,0x327,0x6B,0x327,0x4C,0x301,0x6C,0x301,0x4C,0x327,0x6C,0x327, +0x4C,0x30C,0x6C,0x30C,0x4C,0xB7,0x6C,0xB7,0x4E,0x301,0x6E,0x301, +0x4E,0x327,0x6E,0x327,0x4E,0x30C,0x6E,0x30C,0x2BC,0x6E,0x4F,0x304, +0x6F,0x304,0x4F,0x306,0x6F,0x306,0x4F,0x30B,0x6F,0x30B,0x52,0x301, +0x72,0x301,0x52,0x327,0x72,0x327,0x52,0x30C,0x72,0x30C,0x53,0x301, +0x73,0x301,0x53,0x302,0x73,0x302,0x53,0x327,0x73,0x327,0x53,0x30C, +0x73,0x30C,0x54,0x327,0x74,0x327,0x54,0x30C,0x74,0x30C,0x55,0x303, +0x75,0x303,0x55,0x304,0x75,0x304,0x55,0x306,0x75,0x306,0x55,0x30A, +0x75,0x30A,0x55,0x30B,0x75,0x30B,0x55,0x328,0x75,0x328,0x57,0x302, +0x77,0x302,0x59,0x302,0x79,0x302,0x59,0x308,0x5A,0x301,0x7A,0x301, +0x5A,0x307,0x7A,0x307,0x5A,0x30C,0x7A,0x30C,0x73,0x4F,0x31B,0x6F, +0x31B,0x55,0x31B,0x75,0x31B,0x44,0x5A,0x30C,0x44,0x7A,0x30C,0x64, +0x7A,0x30C,0x4C,0x4A,0x4C,0x6A,0x6C,0x6A,0x4E,0x4A,0x4E,0x6A, +0x6E,0x6A,0x41,0x30C,0x61,0x30C,0x49,0x30C,0x69,0x30C,0x4F,0x30C, +0x6F,0x30C,0x55,0x30C,0x75,0x30C,0x55,0x308,0x304,0x75,0x308,0x304, +0x55,0x308,0x301,0x75,0x308,0x301,0x55,0x308,0x30C,0x75,0x308,0x30C, +0x55,0x308,0x300,0x75,0x308,0x300,0x41,0x308,0x304,0x61,0x308,0x304, +0x41,0x307,0x304,0x61,0x307,0x304,0xC6,0x304,0xE6,0x304,0x47,0x30C, +0x67,0x30C,0x4B,0x30C,0x6B,0x30C,0x4F,0x328,0x6F,0x328,0x4F,0x328, +0x304,0x6F,0x328,0x304,0x1B7,0x30C,0x292,0x30C,0x6A,0x30C,0x44,0x5A, +0x44,0x7A,0x64,0x7A,0x47,0x301,0x67,0x301,0x4E,0x300,0x6E,0x300, +0x41,0x30A,0x301,0x61,0x30A,0x301,0xC6,0x301,0xE6,0x301,0xD8,0x301, +0xF8,0x301,0x41,0x30F,0x61,0x30F,0x41,0x311,0x61,0x311,0x45,0x30F, +0x65,0x30F,0x45,0x311,0x65,0x311,0x49,0x30F,0x69,0x30F,0x49,0x311, +0x69,0x311,0x4F,0x30F,0x6F,0x30F,0x4F,0x311,0x6F,0x311,0x52,0x30F, +0x72,0x30F,0x52,0x311,0x72,0x311,0x55,0x30F,0x75,0x30F,0x55,0x311, +0x75,0x311,0x53,0x326,0x73,0x326,0x54,0x326,0x74,0x326,0x48,0x30C, +0x68,0x30C,0x41,0x307,0x61,0x307,0x45,0x327,0x65,0x327,0x4F,0x308, +0x304,0x6F,0x308,0x304,0x4F,0x303,0x304,0x6F,0x303,0x304,0x4F,0x307, +0x6F,0x307,0x4F,0x307,0x304,0x6F,0x307,0x304,0x59,0x304,0x79,0x304, +0x68,0x266,0x6A,0x72,0x279,0x27B,0x281,0x77,0x79,0x20,0x306,0x20, +0x307,0x20,0x30A,0x20,0x328,0x20,0x303,0x20,0x30B,0x263,0x6C,0x73, +0x78,0x295,0x300,0x301,0x313,0x308,0x301,0x2B9,0x20,0x345,0x3B,0x20, +0x301,0xA8,0x301,0x20,0x308,0x301,0x391,0x301,0xB7,0x395,0x301,0x397, +0x301,0x399,0x301,0x39F,0x301,0x3A5,0x301,0x3A9,0x301,0x3B9,0x308,0x301, +0x399,0x308,0x3A5,0x308,0x3B1,0x301,0x3B5,0x301,0x3B7,0x301,0x3B9,0x301, +0x3C5,0x308,0x301,0x3B9,0x308,0x3C5,0x308,0x3BF,0x301,0x3C5,0x301,0x3C9, +0x301,0x3B2,0x3B8,0x3A5,0x3D2,0x301,0x3A5,0x301,0x3D2,0x308,0x3A5,0x308, +0x3C6,0x3C0,0x3BA,0x3C1,0x3C2,0x398,0x3B5,0x3A3,0x415,0x300,0x415,0x308, +0x413,0x301,0x406,0x308,0x41A,0x301,0x418,0x300,0x423,0x306,0x418,0x306, +0x438,0x306,0x435,0x300,0x435,0x308,0x433,0x301,0x456,0x308,0x43A,0x301, +0x438,0x300,0x443,0x306,0x474,0x30F,0x475,0x30F,0x416,0x306,0x436,0x306, +0x410,0x306,0x430,0x306,0x410,0x308,0x430,0x308,0x415,0x306,0x435,0x306, +0x4D8,0x308,0x4D9,0x308,0x416,0x308,0x436,0x308,0x417,0x308,0x437,0x308, +0x418,0x304,0x438,0x304,0x418,0x308,0x438,0x308,0x41E,0x308,0x43E,0x308, +0x4E8,0x308,0x4E9,0x308,0x42D,0x308,0x44D,0x308,0x423,0x304,0x443,0x304, +0x423,0x308,0x443,0x308,0x423,0x30B,0x443,0x30B,0x427,0x308,0x447,0x308, +0x42B,0x308,0x44B,0x308,0x565,0x582,0x627,0x653,0x627,0x654,0x648,0x654, +0x627,0x655,0x64A,0x654,0x627,0x674,0x648,0x674,0x6C7,0x674,0x64A,0x674, +0x6D5,0x654,0x6C1,0x654,0x6D2,0x654,0x928,0x93C,0x930,0x93C,0x933,0x93C, +0x915,0x93C,0x916,0x93C,0x917,0x93C,0x91C,0x93C,0x921,0x93C,0x922,0x93C, +0x92B,0x93C,0x92F,0x93C,0x9C7,0x9BE,0x9C7,0x9D7,0x9A1,0x9BC,0x9A2,0x9BC, +0x9AF,0x9BC,0xA32,0xA3C,0xA38,0xA3C,0xA16,0xA3C,0xA17,0xA3C,0xA1C,0xA3C, +0xA2B,0xA3C,0xB47,0xB56,0xB47,0xB3E,0xB47,0xB57,0xB21,0xB3C,0xB22,0xB3C, +0xB92,0xBD7,0xBC6,0xBBE,0xBC7,0xBBE,0xBC6,0xBD7,0xC46,0xC56,0xCBF,0xCD5, +0xCC6,0xCD5,0xCC6,0xCD6,0xCC6,0xCC2,0xCC6,0xCC2,0xCD5,0xD46,0xD3E,0xD47, +0xD3E,0xD46,0xD57,0xDD9,0xDCA,0xDD9,0xDCF,0xDD9,0xDCF,0xDCA,0xDD9,0xDDF, +0xE4D,0xE32,0xECD,0xEB2,0xEAB,0xE99,0xEAB,0xEA1,0xF0B,0xF42,0xFB7,0xF4C, +0xFB7,0xF51,0xFB7,0xF56,0xFB7,0xF5B,0xFB7,0xF40,0xFB5,0xF71,0xF72,0xF71, +0xF74,0xFB2,0xF80,0xFB2,0xF71,0xF80,0xFB3,0xF80,0xFB3,0xF71,0xF80,0xF71, +0xF80,0xF92,0xFB7,0xF9C,0xFB7,0xFA1,0xFB7,0xFA6,0xFB7,0xFAB,0xFB7,0xF90, +0xFB5,0x1025,0x102E,0x10DC,0x1B05,0x1B35,0x1B07,0x1B35,0x1B09,0x1B35,0x1B0B,0x1B35, +0x1B0D,0x1B35,0x1B11,0x1B35,0x1B3A,0x1B35,0x1B3C,0x1B35,0x1B3E,0x1B35,0x1B3F,0x1B35, +0x1B42,0x1B35,0x41,0xC6,0x42,0x44,0x45,0x18E,0x47,0x48,0x49,0x4A, +0x4B,0x4C,0x4D,0x4E,0x4F,0x222,0x50,0x52,0x54,0x55,0x57,0x61, +0x250,0x251,0x1D02,0x62,0x64,0x65,0x259,0x25B,0x25C,0x67,0x6B,0x6D, +0x14B,0x6F,0x254,0x1D16,0x1D17,0x70,0x74,0x75,0x1D1D,0x26F,0x76,0x1D25, +0x3B2,0x3B3,0x3B4,0x3C6,0x3C7,0x69,0x72,0x75,0x76,0x3B2,0x3B3,0x3C1, +0x3C6,0x3C7,0x43D,0x252,0x63,0x255,0xF0,0x25C,0x66,0x25F,0x261,0x265, +0x268,0x269,0x26A,0x1D7B,0x29D,0x26D,0x1D85,0x29F,0x271,0x270,0x272,0x273, +0x274,0x275,0x278,0x282,0x283,0x1AB,0x289,0x28A,0x1D1C,0x28B,0x28C,0x7A, +0x290,0x291,0x292,0x3B8,0x41,0x325,0x61,0x325,0x42,0x307,0x62,0x307, +0x42,0x323,0x62,0x323,0x42,0x331,0x62,0x331,0x43,0x327,0x301,0x63, +0x327,0x301,0x44,0x307,0x64,0x307,0x44,0x323,0x64,0x323,0x44,0x331, +0x64,0x331,0x44,0x327,0x64,0x327,0x44,0x32D,0x64,0x32D,0x45,0x304, +0x300,0x65,0x304,0x300,0x45,0x304,0x301,0x65,0x304,0x301,0x45,0x32D, +0x65,0x32D,0x45,0x330,0x65,0x330,0x45,0x327,0x306,0x65,0x327,0x306, +0x46,0x307,0x66,0x307,0x47,0x304,0x67,0x304,0x48,0x307,0x68,0x307, +0x48,0x323,0x68,0x323,0x48,0x308,0x68,0x308,0x48,0x327,0x68,0x327, +0x48,0x32E,0x68,0x32E,0x49,0x330,0x69,0x330,0x49,0x308,0x301,0x69, +0x308,0x301,0x4B,0x301,0x6B,0x301,0x4B,0x323,0x6B,0x323,0x4B,0x331, +0x6B,0x331,0x4C,0x323,0x6C,0x323,0x4C,0x323,0x304,0x6C,0x323,0x304, +0x4C,0x331,0x6C,0x331,0x4C,0x32D,0x6C,0x32D,0x4D,0x301,0x6D,0x301, +0x4D,0x307,0x6D,0x307,0x4D,0x323,0x6D,0x323,0x4E,0x307,0x6E,0x307, +0x4E,0x323,0x6E,0x323,0x4E,0x331,0x6E,0x331,0x4E,0x32D,0x6E,0x32D, +0x4F,0x303,0x301,0x6F,0x303,0x301,0x4F,0x303,0x308,0x6F,0x303,0x308, +0x4F,0x304,0x300,0x6F,0x304,0x300,0x4F,0x304,0x301,0x6F,0x304,0x301, +0x50,0x301,0x70,0x301,0x50,0x307,0x70,0x307,0x52,0x307,0x72,0x307, +0x52,0x323,0x72,0x323,0x52,0x323,0x304,0x72,0x323,0x304,0x52,0x331, +0x72,0x331,0x53,0x307,0x73,0x307,0x53,0x323,0x73,0x323,0x53,0x301, +0x307,0x73,0x301,0x307,0x53,0x30C,0x307,0x73,0x30C,0x307,0x53,0x323, +0x307,0x73,0x323,0x307,0x54,0x307,0x74,0x307,0x54,0x323,0x74,0x323, +0x54,0x331,0x74,0x331,0x54,0x32D,0x74,0x32D,0x55,0x324,0x75,0x324, +0x55,0x330,0x75,0x330,0x55,0x32D,0x75,0x32D,0x55,0x303,0x301,0x75, +0x303,0x301,0x55,0x304,0x308,0x75,0x304,0x308,0x56,0x303,0x76,0x303, +0x56,0x323,0x76,0x323,0x57,0x300,0x77,0x300,0x57,0x301,0x77,0x301, +0x57,0x308,0x77,0x308,0x57,0x307,0x77,0x307,0x57,0x323,0x77,0x323, +0x58,0x307,0x78,0x307,0x58,0x308,0x78,0x308,0x59,0x307,0x79,0x307, +0x5A,0x302,0x7A,0x302,0x5A,0x323,0x7A,0x323,0x5A,0x331,0x7A,0x331, +0x68,0x331,0x74,0x308,0x77,0x30A,0x79,0x30A,0x61,0x2BE,0x17F,0x307, +0x73,0x307,0x41,0x323,0x61,0x323,0x41,0x309,0x61,0x309,0x41,0x302, +0x301,0x61,0x302,0x301,0x41,0x302,0x300,0x61,0x302,0x300,0x41,0x302, +0x309,0x61,0x302,0x309,0x41,0x302,0x303,0x61,0x302,0x303,0x41,0x323, +0x302,0x61,0x323,0x302,0x41,0x306,0x301,0x61,0x306,0x301,0x41,0x306, +0x300,0x61,0x306,0x300,0x41,0x306,0x309,0x61,0x306,0x309,0x41,0x306, +0x303,0x61,0x306,0x303,0x41,0x323,0x306,0x61,0x323,0x306,0x45,0x323, +0x65,0x323,0x45,0x309,0x65,0x309,0x45,0x303,0x65,0x303,0x45,0x302, +0x301,0x65,0x302,0x301,0x45,0x302,0x300,0x65,0x302,0x300,0x45,0x302, +0x309,0x65,0x302,0x309,0x45,0x302,0x303,0x65,0x302,0x303,0x45,0x323, +0x302,0x65,0x323,0x302,0x49,0x309,0x69,0x309,0x49,0x323,0x69,0x323, +0x4F,0x323,0x6F,0x323,0x4F,0x309,0x6F,0x309,0x4F,0x302,0x301,0x6F, +0x302,0x301,0x4F,0x302,0x300,0x6F,0x302,0x300,0x4F,0x302,0x309,0x6F, +0x302,0x309,0x4F,0x302,0x303,0x6F,0x302,0x303,0x4F,0x323,0x302,0x6F, +0x323,0x302,0x4F,0x31B,0x301,0x6F,0x31B,0x301,0x4F,0x31B,0x300,0x6F, +0x31B,0x300,0x4F,0x31B,0x309,0x6F,0x31B,0x309,0x4F,0x31B,0x303,0x6F, +0x31B,0x303,0x4F,0x31B,0x323,0x6F,0x31B,0x323,0x55,0x323,0x75,0x323, +0x55,0x309,0x75,0x309,0x55,0x31B,0x301,0x75,0x31B,0x301,0x55,0x31B, +0x300,0x75,0x31B,0x300,0x55,0x31B,0x309,0x75,0x31B,0x309,0x55,0x31B, +0x303,0x75,0x31B,0x303,0x55,0x31B,0x323,0x75,0x31B,0x323,0x59,0x300, +0x79,0x300,0x59,0x323,0x79,0x323,0x59,0x309,0x79,0x309,0x59,0x303, +0x79,0x303,0x3B1,0x313,0x3B1,0x314,0x3B1,0x313,0x300,0x3B1,0x314,0x300, +0x3B1,0x313,0x301,0x3B1,0x314,0x301,0x3B1,0x313,0x342,0x3B1,0x314,0x342, +0x391,0x313,0x391,0x314,0x391,0x313,0x300,0x391,0x314,0x300,0x391,0x313, +0x301,0x391,0x314,0x301,0x391,0x313,0x342,0x391,0x314,0x342,0x3B5,0x313, +0x3B5,0x314,0x3B5,0x313,0x300,0x3B5,0x314,0x300,0x3B5,0x313,0x301,0x3B5, +0x314,0x301,0x395,0x313,0x395,0x314,0x395,0x313,0x300,0x395,0x314,0x300, +0x395,0x313,0x301,0x395,0x314,0x301,0x3B7,0x313,0x3B7,0x314,0x3B7,0x313, +0x300,0x3B7,0x314,0x300,0x3B7,0x313,0x301,0x3B7,0x314,0x301,0x3B7,0x313, +0x342,0x3B7,0x314,0x342,0x397,0x313,0x397,0x314,0x397,0x313,0x300,0x397, +0x314,0x300,0x397,0x313,0x301,0x397,0x314,0x301,0x397,0x313,0x342,0x397, +0x314,0x342,0x3B9,0x313,0x3B9,0x314,0x3B9,0x313,0x300,0x3B9,0x314,0x300, +0x3B9,0x313,0x301,0x3B9,0x314,0x301,0x3B9,0x313,0x342,0x3B9,0x314,0x342, +0x399,0x313,0x399,0x314,0x399,0x313,0x300,0x399,0x314,0x300,0x399,0x313, +0x301,0x399,0x314,0x301,0x399,0x313,0x342,0x399,0x314,0x342,0x3BF,0x313, +0x3BF,0x314,0x3BF,0x313,0x300,0x3BF,0x314,0x300,0x3BF,0x313,0x301,0x3BF, +0x314,0x301,0x39F,0x313,0x39F,0x314,0x39F,0x313,0x300,0x39F,0x314,0x300, +0x39F,0x313,0x301,0x39F,0x314,0x301,0x3C5,0x313,0x3C5,0x314,0x3C5,0x313, +0x300,0x3C5,0x314,0x300,0x3C5,0x313,0x301,0x3C5,0x314,0x301,0x3C5,0x313, +0x342,0x3C5,0x314,0x342,0x3A5,0x314,0x3A5,0x314,0x300,0x3A5,0x314,0x301, +0x3A5,0x314,0x342,0x3C9,0x313,0x3C9,0x314,0x3C9,0x313,0x300,0x3C9,0x314, +0x300,0x3C9,0x313,0x301,0x3C9,0x314,0x301,0x3C9,0x313,0x342,0x3C9,0x314, +0x342,0x3A9,0x313,0x3A9,0x314,0x3A9,0x313,0x300,0x3A9,0x314,0x300,0x3A9, +0x313,0x301,0x3A9,0x314,0x301,0x3A9,0x313,0x342,0x3A9,0x314,0x342,0x3B1, +0x300,0x3B1,0x301,0x3B5,0x300,0x3B5,0x301,0x3B7,0x300,0x3B7,0x301,0x3B9, +0x300,0x3B9,0x301,0x3BF,0x300,0x3BF,0x301,0x3C5,0x300,0x3C5,0x301,0x3C9, +0x300,0x3C9,0x301,0x3B1,0x313,0x345,0x3B1,0x314,0x345,0x3B1,0x313,0x300, +0x345,0x3B1,0x314,0x300,0x345,0x3B1,0x313,0x301,0x345,0x3B1,0x314,0x301, +0x345,0x3B1,0x313,0x342,0x345,0x3B1,0x314,0x342,0x345,0x391,0x313,0x345, +0x391,0x314,0x345,0x391,0x313,0x300,0x345,0x391,0x314,0x300,0x345,0x391, +0x313,0x301,0x345,0x391,0x314,0x301,0x345,0x391,0x313,0x342,0x345,0x391, +0x314,0x342,0x345,0x3B7,0x313,0x345,0x3B7,0x314,0x345,0x3B7,0x313,0x300, +0x345,0x3B7,0x314,0x300,0x345,0x3B7,0x313,0x301,0x345,0x3B7,0x314,0x301, +0x345,0x3B7,0x313,0x342,0x345,0x3B7,0x314,0x342,0x345,0x397,0x313,0x345, +0x397,0x314,0x345,0x397,0x313,0x300,0x345,0x397,0x314,0x300,0x345,0x397, +0x313,0x301,0x345,0x397,0x314,0x301,0x345,0x397,0x313,0x342,0x345,0x397, +0x314,0x342,0x345,0x3C9,0x313,0x345,0x3C9,0x314,0x345,0x3C9,0x313,0x300, +0x345,0x3C9,0x314,0x300,0x345,0x3C9,0x313,0x301,0x345,0x3C9,0x314,0x301, +0x345,0x3C9,0x313,0x342,0x345,0x3C9,0x314,0x342,0x345,0x3A9,0x313,0x345, +0x3A9,0x314,0x345,0x3A9,0x313,0x300,0x345,0x3A9,0x314,0x300,0x345,0x3A9, +0x313,0x301,0x345,0x3A9,0x314,0x301,0x345,0x3A9,0x313,0x342,0x345,0x3A9, +0x314,0x342,0x345,0x3B1,0x306,0x3B1,0x304,0x3B1,0x300,0x345,0x3B1,0x345, +0x3B1,0x301,0x345,0x3B1,0x342,0x3B1,0x342,0x345,0x391,0x306,0x391,0x304, +0x391,0x300,0x391,0x301,0x391,0x345,0x20,0x313,0x3B9,0x20,0x313,0x20, +0x342,0xA8,0x342,0x20,0x308,0x342,0x3B7,0x300,0x345,0x3B7,0x345,0x3B7, +0x301,0x345,0x3B7,0x342,0x3B7,0x342,0x345,0x395,0x300,0x395,0x301,0x397, +0x300,0x397,0x301,0x397,0x345,0x1FBF,0x300,0x20,0x313,0x300,0x1FBF,0x301, +0x20,0x313,0x301,0x1FBF,0x342,0x20,0x313,0x342,0x3B9,0x306,0x3B9,0x304, +0x3B9,0x308,0x300,0x3B9,0x308,0x301,0x3B9,0x342,0x3B9,0x308,0x342,0x399, +0x306,0x399,0x304,0x399,0x300,0x399,0x301,0x1FFE,0x300,0x20,0x314,0x300, +0x1FFE,0x301,0x20,0x314,0x301,0x1FFE,0x342,0x20,0x314,0x342,0x3C5,0x306, +0x3C5,0x304,0x3C5,0x308,0x300,0x3C5,0x308,0x301,0x3C1,0x313,0x3C1,0x314, +0x3C5,0x342,0x3C5,0x308,0x342,0x3A5,0x306,0x3A5,0x304,0x3A5,0x300,0x3A5, +0x301,0x3A1,0x314,0xA8,0x300,0x20,0x308,0x300,0xA8,0x301,0x20,0x308, +0x301,0x60,0x3C9,0x300,0x345,0x3C9,0x345,0x3C9,0x301,0x345,0x3C9,0x342, +0x3C9,0x342,0x345,0x39F,0x300,0x39F,0x301,0x3A9,0x300,0x3A9,0x301,0x3A9, +0x345,0xB4,0x20,0x301,0x20,0x314,0x2002,0x20,0x2003,0x20,0x20,0x20, +0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x2010,0x20,0x333,0x2E,0x2E, +0x2E,0x2E,0x2E,0x2E,0x20,0x2032,0x2032,0x2032,0x2032,0x2032,0x2035,0x2035, +0x2035,0x2035,0x2035,0x21,0x21,0x20,0x305,0x3F,0x3F,0x3F,0x21,0x21, +0x3F,0x2032,0x2032,0x2032,0x2032,0x20,0x30,0x69,0x34,0x35,0x36,0x37, +0x38,0x39,0x2B,0x2212,0x3D,0x28,0x29,0x6E,0x30,0x31,0x32,0x33, +0x34,0x35,0x36,0x37,0x38,0x39,0x2B,0x2212,0x3D,0x28,0x29,0x61, +0x65,0x6F,0x78,0x259,0x68,0x6B,0x6C,0x6D,0x6E,0x70,0x73,0x74, +0x52,0x73,0x61,0x2F,0x63,0x61,0x2F,0x73,0x43,0xB0,0x43,0x63, +0x2F,0x6F,0x63,0x2F,0x75,0x190,0xB0,0x46,0x67,0x48,0x48,0x48, +0x68,0x127,0x49,0x49,0x4C,0x6C,0x4E,0x4E,0x6F,0x50,0x51,0x52, +0x52,0x52,0x53,0x4D,0x54,0x45,0x4C,0x54,0x4D,0x5A,0x3A9,0x5A, +0x4B,0x41,0x30A,0x42,0x43,0x65,0x45,0x46,0x4D,0x6F,0x5D0,0x5D1, +0x5D2,0x5D3,0x69,0x46,0x41,0x58,0x3C0,0x3B3,0x393,0x3A0,0x2211,0x44, +0x64,0x65,0x69,0x6A,0x31,0x2044,0x37,0x31,0x2044,0x39,0x31,0x2044, +0x31,0x30,0x31,0x2044,0x33,0x32,0x2044,0x33,0x31,0x2044,0x35,0x32, +0x2044,0x35,0x33,0x2044,0x35,0x34,0x2044,0x35,0x31,0x2044,0x36,0x35, +0x2044,0x36,0x31,0x2044,0x38,0x33,0x2044,0x38,0x35,0x2044,0x38,0x37, +0x2044,0x38,0x31,0x2044,0x49,0x49,0x49,0x49,0x49,0x49,0x49,0x56, +0x56,0x56,0x49,0x56,0x49,0x49,0x56,0x49,0x49,0x49,0x49,0x58, +0x58,0x58,0x49,0x58,0x49,0x49,0x4C,0x43,0x44,0x4D,0x69,0x69, +0x69,0x69,0x69,0x69,0x69,0x76,0x76,0x76,0x69,0x76,0x69,0x69, +0x76,0x69,0x69,0x69,0x69,0x78,0x78,0x78,0x69,0x78,0x69,0x69, +0x6C,0x63,0x64,0x6D,0x30,0x2044,0x33,0x2190,0x338,0x2192,0x338,0x2194, +0x338,0x21D0,0x338,0x21D4,0x338,0x21D2,0x338,0x2203,0x338,0x2208,0x338,0x220B, +0x338,0x2223,0x338,0x2225,0x338,0x222B,0x222B,0x222B,0x222B,0x222B,0x222E,0x222E, +0x222E,0x222E,0x222E,0x223C,0x338,0x2243,0x338,0x2245,0x338,0x2248,0x338,0x3D, +0x338,0x2261,0x338,0x224D,0x338,0x3C,0x338,0x3E,0x338,0x2264,0x338,0x2265, +0x338,0x2272,0x338,0x2273,0x338,0x2276,0x338,0x2277,0x338,0x227A,0x338,0x227B, +0x338,0x2282,0x338,0x2283,0x338,0x2286,0x338,0x2287,0x338,0x22A2,0x338,0x22A8, +0x338,0x22A9,0x338,0x22AB,0x338,0x227C,0x338,0x227D,0x338,0x2291,0x338,0x2292, +0x338,0x22B2,0x338,0x22B3,0x338,0x22B4,0x338,0x22B5,0x338,0x3008,0x3009,0x31, +0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x31,0x30,0x31,0x31, +0x31,0x32,0x31,0x33,0x31,0x34,0x31,0x35,0x31,0x36,0x31,0x37, +0x31,0x38,0x31,0x39,0x32,0x30,0x28,0x31,0x29,0x28,0x32,0x29, +0x28,0x33,0x29,0x28,0x34,0x29,0x28,0x35,0x29,0x28,0x36,0x29, +0x28,0x37,0x29,0x28,0x38,0x29,0x28,0x39,0x29,0x28,0x31,0x30, +0x29,0x28,0x31,0x31,0x29,0x28,0x31,0x32,0x29,0x28,0x31,0x33, +0x29,0x28,0x31,0x34,0x29,0x28,0x31,0x35,0x29,0x28,0x31,0x36, +0x29,0x28,0x31,0x37,0x29,0x28,0x31,0x38,0x29,0x28,0x31,0x39, +0x29,0x28,0x32,0x30,0x29,0x31,0x2E,0x32,0x2E,0x33,0x2E,0x34, +0x2E,0x35,0x2E,0x36,0x2E,0x37,0x2E,0x38,0x2E,0x39,0x2E,0x31, +0x30,0x2E,0x31,0x31,0x2E,0x31,0x32,0x2E,0x31,0x33,0x2E,0x31, +0x34,0x2E,0x31,0x35,0x2E,0x31,0x36,0x2E,0x31,0x37,0x2E,0x31, +0x38,0x2E,0x31,0x39,0x2E,0x32,0x30,0x2E,0x28,0x61,0x29,0x28, +0x62,0x29,0x28,0x63,0x29,0x28,0x64,0x29,0x28,0x65,0x29,0x28, +0x66,0x29,0x28,0x67,0x29,0x28,0x68,0x29,0x28,0x69,0x29,0x28, +0x6A,0x29,0x28,0x6B,0x29,0x28,0x6C,0x29,0x28,0x6D,0x29,0x28, +0x6E,0x29,0x28,0x6F,0x29,0x28,0x70,0x29,0x28,0x71,0x29,0x28, +0x72,0x29,0x28,0x73,0x29,0x28,0x74,0x29,0x28,0x75,0x29,0x28, +0x76,0x29,0x28,0x77,0x29,0x28,0x78,0x29,0x28,0x79,0x29,0x28, +0x7A,0x29,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A, +0x4B,0x4C,0x4D,0x4E,0x4F,0x50,0x51,0x52,0x53,0x54,0x55,0x56, +0x57,0x58,0x59,0x5A,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68, +0x69,0x6A,0x6B,0x6C,0x6D,0x6E,0x6F,0x70,0x71,0x72,0x73,0x74, +0x75,0x76,0x77,0x78,0x79,0x7A,0x30,0x222B,0x222B,0x222B,0x222B,0x3A, +0x3A,0x3D,0x3D,0x3D,0x3D,0x3D,0x3D,0x2ADD,0x338,0x6A,0x56,0x2D61, +0x6BCD,0x9F9F,0x4E00,0x4E28,0x4E36,0x4E3F,0x4E59,0x4E85,0x4E8C,0x4EA0,0x4EBA,0x513F, +0x5165,0x516B,0x5182,0x5196,0x51AB,0x51E0,0x51F5,0x5200,0x529B,0x52F9,0x5315,0x531A, +0x5338,0x5341,0x535C,0x5369,0x5382,0x53B6,0x53C8,0x53E3,0x56D7,0x571F,0x58EB,0x5902, +0x590A,0x5915,0x5927,0x5973,0x5B50,0x5B80,0x5BF8,0x5C0F,0x5C22,0x5C38,0x5C6E,0x5C71, +0x5DDB,0x5DE5,0x5DF1,0x5DFE,0x5E72,0x5E7A,0x5E7F,0x5EF4,0x5EFE,0x5F0B,0x5F13,0x5F50, +0x5F61,0x5F73,0x5FC3,0x6208,0x6236,0x624B,0x652F,0x6534,0x6587,0x6597,0x65A4,0x65B9, +0x65E0,0x65E5,0x66F0,0x6708,0x6728,0x6B20,0x6B62,0x6B79,0x6BB3,0x6BCB,0x6BD4,0x6BDB, +0x6C0F,0x6C14,0x6C34,0x706B,0x722A,0x7236,0x723B,0x723F,0x7247,0x7259,0x725B,0x72AC, +0x7384,0x7389,0x74DC,0x74E6,0x7518,0x751F,0x7528,0x7530,0x758B,0x7592,0x7676,0x767D, +0x76AE,0x76BF,0x76EE,0x77DB,0x77E2,0x77F3,0x793A,0x79B8,0x79BE,0x7A74,0x7ACB,0x7AF9, +0x7C73,0x7CF8,0x7F36,0x7F51,0x7F8A,0x7FBD,0x8001,0x800C,0x8012,0x8033,0x807F,0x8089, +0x81E3,0x81EA,0x81F3,0x81FC,0x820C,0x821B,0x821F,0x826E,0x8272,0x8278,0x864D,0x866B, +0x8840,0x884C,0x8863,0x897E,0x898B,0x89D2,0x8A00,0x8C37,0x8C46,0x8C55,0x8C78,0x8C9D, +0x8D64,0x8D70,0x8DB3,0x8EAB,0x8ECA,0x8F9B,0x8FB0,0x8FB5,0x9091,0x9149,0x91C6,0x91CC, +0x91D1,0x9577,0x9580,0x961C,0x96B6,0x96B9,0x96E8,0x9751,0x975E,0x9762,0x9769,0x97CB, +0x97ED,0x97F3,0x9801,0x98A8,0x98DB,0x98DF,0x9996,0x9999,0x99AC,0x9AA8,0x9AD8,0x9ADF, +0x9B25,0x9B2F,0x9B32,0x9B3C,0x9B5A,0x9CE5,0x9E75,0x9E7F,0x9EA5,0x9EBB,0x9EC3,0x9ECD, +0x9ED1,0x9EF9,0x9EFD,0x9F0E,0x9F13,0x9F20,0x9F3B,0x9F4A,0x9F52,0x9F8D,0x9F9C,0x9FA0, +0x20,0x3012,0x5341,0x5344,0x5345,0x304B,0x3099,0x304D,0x3099,0x304F,0x3099,0x3051, +0x3099,0x3053,0x3099,0x3055,0x3099,0x3057,0x3099,0x3059,0x3099,0x305B,0x3099,0x305D, +0x3099,0x305F,0x3099,0x3061,0x3099,0x3064,0x3099,0x3066,0x3099,0x3068,0x3099,0x306F, +0x3099,0x306F,0x309A,0x3072,0x3099,0x3072,0x309A,0x3075,0x3099,0x3075,0x309A,0x3078, +0x3099,0x3078,0x309A,0x307B,0x3099,0x307B,0x309A,0x3046,0x3099,0x20,0x3099,0x20, +0x309A,0x309D,0x3099,0x3088,0x308A,0x30AB,0x3099,0x30AD,0x3099,0x30AF,0x3099,0x30B1, +0x3099,0x30B3,0x3099,0x30B5,0x3099,0x30B7,0x3099,0x30B9,0x3099,0x30BB,0x3099,0x30BD, +0x3099,0x30BF,0x3099,0x30C1,0x3099,0x30C4,0x3099,0x30C6,0x3099,0x30C8,0x3099,0x30CF, +0x3099,0x30CF,0x309A,0x30D2,0x3099,0x30D2,0x309A,0x30D5,0x3099,0x30D5,0x309A,0x30D8, +0x3099,0x30D8,0x309A,0x30DB,0x3099,0x30DB,0x309A,0x30A6,0x3099,0x30EF,0x3099,0x30F0, +0x3099,0x30F1,0x3099,0x30F2,0x3099,0x30FD,0x3099,0x30B3,0x30C8,0x1100,0x1101,0x11AA, +0x1102,0x11AC,0x11AD,0x1103,0x1104,0x1105,0x11B0,0x11B1,0x11B2,0x11B3,0x11B4,0x11B5, +0x111A,0x1106,0x1107,0x1108,0x1121,0x1109,0x110A,0x110B,0x110C,0x110D,0x110E,0x110F, +0x1110,0x1111,0x1112,0x1161,0x1162,0x1163,0x1164,0x1165,0x1166,0x1167,0x1168,0x1169, +0x116A,0x116B,0x116C,0x116D,0x116E,0x116F,0x1170,0x1171,0x1172,0x1173,0x1174,0x1175, +0x1160,0x1114,0x1115,0x11C7,0x11C8,0x11CC,0x11CE,0x11D3,0x11D7,0x11D9,0x111C,0x11DD, +0x11DF,0x111D,0x111E,0x1120,0x1122,0x1123,0x1127,0x1129,0x112B,0x112C,0x112D,0x112E, +0x112F,0x1132,0x1136,0x1140,0x1147,0x114C,0x11F1,0x11F2,0x1157,0x1158,0x1159,0x1184, +0x1185,0x1188,0x1191,0x1192,0x1194,0x119E,0x11A1,0x4E00,0x4E8C,0x4E09,0x56DB,0x4E0A, +0x4E2D,0x4E0B,0x7532,0x4E59,0x4E19,0x4E01,0x5929,0x5730,0x4EBA,0x28,0x1100,0x29, +0x28,0x1102,0x29,0x28,0x1103,0x29,0x28,0x1105,0x29,0x28,0x1106,0x29, +0x28,0x1107,0x29,0x28,0x1109,0x29,0x28,0x110B,0x29,0x28,0x110C,0x29, +0x28,0x110E,0x29,0x28,0x110F,0x29,0x28,0x1110,0x29,0x28,0x1111,0x29, +0x28,0x1112,0x29,0x28,0x1100,0x1161,0x29,0x28,0x1102,0x1161,0x29,0x28, +0x1103,0x1161,0x29,0x28,0x1105,0x1161,0x29,0x28,0x1106,0x1161,0x29,0x28, +0x1107,0x1161,0x29,0x28,0x1109,0x1161,0x29,0x28,0x110B,0x1161,0x29,0x28, +0x110C,0x1161,0x29,0x28,0x110E,0x1161,0x29,0x28,0x110F,0x1161,0x29,0x28, +0x1110,0x1161,0x29,0x28,0x1111,0x1161,0x29,0x28,0x1112,0x1161,0x29,0x28, +0x110C,0x116E,0x29,0x28,0x110B,0x1169,0x110C,0x1165,0x11AB,0x29,0x28,0x110B, +0x1169,0x1112,0x116E,0x29,0x28,0x4E00,0x29,0x28,0x4E8C,0x29,0x28,0x4E09, +0x29,0x28,0x56DB,0x29,0x28,0x4E94,0x29,0x28,0x516D,0x29,0x28,0x4E03, +0x29,0x28,0x516B,0x29,0x28,0x4E5D,0x29,0x28,0x5341,0x29,0x28,0x6708, +0x29,0x28,0x706B,0x29,0x28,0x6C34,0x29,0x28,0x6728,0x29,0x28,0x91D1, +0x29,0x28,0x571F,0x29,0x28,0x65E5,0x29,0x28,0x682A,0x29,0x28,0x6709, +0x29,0x28,0x793E,0x29,0x28,0x540D,0x29,0x28,0x7279,0x29,0x28,0x8CA1, +0x29,0x28,0x795D,0x29,0x28,0x52B4,0x29,0x28,0x4EE3,0x29,0x28,0x547C, +0x29,0x28,0x5B66,0x29,0x28,0x76E3,0x29,0x28,0x4F01,0x29,0x28,0x8CC7, +0x29,0x28,0x5354,0x29,0x28,0x796D,0x29,0x28,0x4F11,0x29,0x28,0x81EA, +0x29,0x28,0x81F3,0x29,0x554F,0x5E7C,0x6587,0x7B8F,0x50,0x54,0x45,0x32, +0x31,0x32,0x32,0x32,0x33,0x32,0x34,0x32,0x35,0x32,0x36,0x32, +0x37,0x32,0x38,0x32,0x39,0x33,0x30,0x33,0x31,0x33,0x32,0x33, +0x33,0x33,0x34,0x33,0x35,0x1100,0x1102,0x1103,0x1105,0x1106,0x1107,0x1109, +0x110B,0x110C,0x110E,0x110F,0x1110,0x1111,0x1112,0x1100,0x1161,0x1102,0x1161,0x1103, +0x1161,0x1105,0x1161,0x1106,0x1161,0x1107,0x1161,0x1109,0x1161,0x110B,0x1161,0x110C, +0x1161,0x110E,0x1161,0x110F,0x1161,0x1110,0x1161,0x1111,0x1161,0x1112,0x1161,0x110E, +0x1161,0x11B7,0x1100,0x1169,0x110C,0x116E,0x110B,0x1174,0x110B,0x116E,0x4E00,0x4E8C, +0x4E09,0x56DB,0x4E94,0x516D,0x4E03,0x516B,0x4E5D,0x5341,0x6708,0x706B,0x6C34,0x6728, +0x91D1,0x571F,0x65E5,0x682A,0x6709,0x793E,0x540D,0x7279,0x8CA1,0x795D,0x52B4,0x79D8, +0x7537,0x5973,0x9069,0x512A,0x5370,0x6CE8,0x9805,0x4F11,0x5199,0x6B63,0x4E0A,0x4E2D, +0x4E0B,0x5DE6,0x53F3,0x533B,0x5B97,0x5B66,0x76E3,0x4F01,0x8CC7,0x5354,0x591C,0x33, +0x36,0x33,0x37,0x33,0x38,0x33,0x39,0x34,0x30,0x34,0x31,0x34, +0x32,0x34,0x33,0x34,0x34,0x34,0x35,0x34,0x36,0x34,0x37,0x34, +0x38,0x34,0x39,0x35,0x30,0x31,0x6708,0x32,0x6708,0x33,0x6708,0x34, +0x6708,0x35,0x6708,0x36,0x6708,0x37,0x6708,0x38,0x6708,0x39,0x6708,0x31, +0x30,0x6708,0x31,0x31,0x6708,0x31,0x32,0x6708,0x48,0x67,0x65,0x72, +0x67,0x65,0x56,0x4C,0x54,0x44,0x30A2,0x30A4,0x30A6,0x30A8,0x30AA,0x30AB, +0x30AD,0x30AF,0x30B1,0x30B3,0x30B5,0x30B7,0x30B9,0x30BB,0x30BD,0x30BF,0x30C1,0x30C4, +0x30C6,0x30C8,0x30CA,0x30CB,0x30CC,0x30CD,0x30CE,0x30CF,0x30D2,0x30D5,0x30D8,0x30DB, +0x30DE,0x30DF,0x30E0,0x30E1,0x30E2,0x30E4,0x30E6,0x30E8,0x30E9,0x30EA,0x30EB,0x30EC, +0x30ED,0x30EF,0x30F0,0x30F1,0x30F2,0x4EE4,0x548C,0x30A2,0x30CF,0x309A,0x30FC,0x30C8, +0x30A2,0x30EB,0x30D5,0x30A1,0x30A2,0x30F3,0x30D8,0x309A,0x30A2,0x30A2,0x30FC,0x30EB, +0x30A4,0x30CB,0x30F3,0x30AF,0x3099,0x30A4,0x30F3,0x30C1,0x30A6,0x30A9,0x30F3,0x30A8, +0x30B9,0x30AF,0x30FC,0x30C8,0x3099,0x30A8,0x30FC,0x30AB,0x30FC,0x30AA,0x30F3,0x30B9, +0x30AA,0x30FC,0x30E0,0x30AB,0x30A4,0x30EA,0x30AB,0x30E9,0x30C3,0x30C8,0x30AB,0x30ED, +0x30EA,0x30FC,0x30AB,0x3099,0x30ED,0x30F3,0x30AB,0x3099,0x30F3,0x30DE,0x30AD,0x3099, +0x30AB,0x3099,0x30AD,0x3099,0x30CB,0x30FC,0x30AD,0x30E5,0x30EA,0x30FC,0x30AD,0x3099, +0x30EB,0x30BF,0x3099,0x30FC,0x30AD,0x30ED,0x30AD,0x30ED,0x30AF,0x3099,0x30E9,0x30E0, +0x30AD,0x30ED,0x30E1,0x30FC,0x30C8,0x30EB,0x30AD,0x30ED,0x30EF,0x30C3,0x30C8,0x30AF, +0x3099,0x30E9,0x30E0,0x30AF,0x3099,0x30E9,0x30E0,0x30C8,0x30F3,0x30AF,0x30EB,0x30BB, +0x3099,0x30A4,0x30ED,0x30AF,0x30ED,0x30FC,0x30CD,0x30B1,0x30FC,0x30B9,0x30B3,0x30EB, +0x30CA,0x30B3,0x30FC,0x30DB,0x309A,0x30B5,0x30A4,0x30AF,0x30EB,0x30B5,0x30F3,0x30C1, +0x30FC,0x30E0,0x30B7,0x30EA,0x30F3,0x30AF,0x3099,0x30BB,0x30F3,0x30C1,0x30BB,0x30F3, +0x30C8,0x30BF,0x3099,0x30FC,0x30B9,0x30C6,0x3099,0x30B7,0x30C8,0x3099,0x30EB,0x30C8, +0x30F3,0x30CA,0x30CE,0x30CE,0x30C3,0x30C8,0x30CF,0x30A4,0x30C4,0x30CF,0x309A,0x30FC, +0x30BB,0x30F3,0x30C8,0x30CF,0x309A,0x30FC,0x30C4,0x30CF,0x3099,0x30FC,0x30EC,0x30EB, +0x30D2,0x309A,0x30A2,0x30B9,0x30C8,0x30EB,0x30D2,0x309A,0x30AF,0x30EB,0x30D2,0x309A, +0x30B3,0x30D2,0x3099,0x30EB,0x30D5,0x30A1,0x30E9,0x30C3,0x30C8,0x3099,0x30D5,0x30A3, +0x30FC,0x30C8,0x30D5,0x3099,0x30C3,0x30B7,0x30A7,0x30EB,0x30D5,0x30E9,0x30F3,0x30D8, +0x30AF,0x30BF,0x30FC,0x30EB,0x30D8,0x309A,0x30BD,0x30D8,0x309A,0x30CB,0x30D2,0x30D8, +0x30EB,0x30C4,0x30D8,0x309A,0x30F3,0x30B9,0x30D8,0x309A,0x30FC,0x30B7,0x3099,0x30D8, +0x3099,0x30FC,0x30BF,0x30DB,0x309A,0x30A4,0x30F3,0x30C8,0x30DB,0x3099,0x30EB,0x30C8, +0x30DB,0x30F3,0x30DB,0x309A,0x30F3,0x30C8,0x3099,0x30DB,0x30FC,0x30EB,0x30DB,0x30FC, +0x30F3,0x30DE,0x30A4,0x30AF,0x30ED,0x30DE,0x30A4,0x30EB,0x30DE,0x30C3,0x30CF,0x30DE, +0x30EB,0x30AF,0x30DE,0x30F3,0x30B7,0x30E7,0x30F3,0x30DF,0x30AF,0x30ED,0x30F3,0x30DF, +0x30EA,0x30DF,0x30EA,0x30CF,0x3099,0x30FC,0x30EB,0x30E1,0x30AB,0x3099,0x30E1,0x30AB, +0x3099,0x30C8,0x30F3,0x30E1,0x30FC,0x30C8,0x30EB,0x30E4,0x30FC,0x30C8,0x3099,0x30E4, +0x30FC,0x30EB,0x30E6,0x30A2,0x30F3,0x30EA,0x30C3,0x30C8,0x30EB,0x30EA,0x30E9,0x30EB, +0x30D2,0x309A,0x30FC,0x30EB,0x30FC,0x30D5,0x3099,0x30EB,0x30EC,0x30E0,0x30EC,0x30F3, +0x30C8,0x30B1,0x3099,0x30F3,0x30EF,0x30C3,0x30C8,0x30,0x70B9,0x31,0x70B9,0x32, +0x70B9,0x33,0x70B9,0x34,0x70B9,0x35,0x70B9,0x36,0x70B9,0x37,0x70B9,0x38, +0x70B9,0x39,0x70B9,0x31,0x30,0x70B9,0x31,0x31,0x70B9,0x31,0x32,0x70B9, +0x31,0x33,0x70B9,0x31,0x34,0x70B9,0x31,0x35,0x70B9,0x31,0x36,0x70B9, +0x31,0x37,0x70B9,0x31,0x38,0x70B9,0x31,0x39,0x70B9,0x32,0x30,0x70B9, +0x32,0x31,0x70B9,0x32,0x32,0x70B9,0x32,0x33,0x70B9,0x32,0x34,0x70B9, +0x68,0x50,0x61,0x64,0x61,0x41,0x55,0x62,0x61,0x72,0x6F,0x56, +0x70,0x63,0x64,0x6D,0x64,0x6D,0x32,0x64,0x6D,0x33,0x49,0x55, +0x5E73,0x6210,0x662D,0x548C,0x5927,0x6B63,0x660E,0x6CBB,0x682A,0x5F0F,0x4F1A,0x793E, +0x70,0x41,0x6E,0x41,0x3BC,0x41,0x6D,0x41,0x6B,0x41,0x4B,0x42, +0x4D,0x42,0x47,0x42,0x63,0x61,0x6C,0x6B,0x63,0x61,0x6C,0x70, +0x46,0x6E,0x46,0x3BC,0x46,0x3BC,0x67,0x6D,0x67,0x6B,0x67,0x48, +0x7A,0x6B,0x48,0x7A,0x4D,0x48,0x7A,0x47,0x48,0x7A,0x54,0x48, +0x7A,0x3BC,0x6C,0x6D,0x6C,0x64,0x6C,0x6B,0x6C,0x66,0x6D,0x6E, +0x6D,0x3BC,0x6D,0x6D,0x6D,0x63,0x6D,0x6B,0x6D,0x6D,0x6D,0x32, +0x63,0x6D,0x32,0x6D,0x32,0x6B,0x6D,0x32,0x6D,0x6D,0x33,0x63, +0x6D,0x33,0x6D,0x33,0x6B,0x6D,0x33,0x6D,0x2215,0x73,0x6D,0x2215, +0x73,0x32,0x50,0x61,0x6B,0x50,0x61,0x4D,0x50,0x61,0x47,0x50, +0x61,0x72,0x61,0x64,0x72,0x61,0x64,0x2215,0x73,0x72,0x61,0x64, +0x2215,0x73,0x32,0x70,0x73,0x6E,0x73,0x3BC,0x73,0x6D,0x73,0x70, +0x56,0x6E,0x56,0x3BC,0x56,0x6D,0x56,0x6B,0x56,0x4D,0x56,0x70, +0x57,0x6E,0x57,0x3BC,0x57,0x6D,0x57,0x6B,0x57,0x4D,0x57,0x6B, +0x3A9,0x4D,0x3A9,0x61,0x2E,0x6D,0x2E,0x42,0x71,0x63,0x63,0x63, +0x64,0x43,0x2215,0x6B,0x67,0x43,0x6F,0x2E,0x64,0x42,0x47,0x79, +0x68,0x61,0x48,0x50,0x69,0x6E,0x4B,0x4B,0x4B,0x4D,0x6B,0x74, +0x6C,0x6D,0x6C,0x6E,0x6C,0x6F,0x67,0x6C,0x78,0x6D,0x62,0x6D, +0x69,0x6C,0x6D,0x6F,0x6C,0x50,0x48,0x70,0x2E,0x6D,0x2E,0x50, +0x50,0x4D,0x50,0x52,0x73,0x72,0x53,0x76,0x57,0x62,0x56,0x2215, +0x6D,0x41,0x2215,0x6D,0x31,0x65E5,0x32,0x65E5,0x33,0x65E5,0x34,0x65E5, +0x35,0x65E5,0x36,0x65E5,0x37,0x65E5,0x38,0x65E5,0x39,0x65E5,0x31,0x30, +0x65E5,0x31,0x31,0x65E5,0x31,0x32,0x65E5,0x31,0x33,0x65E5,0x31,0x34, +0x65E5,0x31,0x35,0x65E5,0x31,0x36,0x65E5,0x31,0x37,0x65E5,0x31,0x38, +0x65E5,0x31,0x39,0x65E5,0x32,0x30,0x65E5,0x32,0x31,0x65E5,0x32,0x32, +0x65E5,0x32,0x33,0x65E5,0x32,0x34,0x65E5,0x32,0x35,0x65E5,0x32,0x36, +0x65E5,0x32,0x37,0x65E5,0x32,0x38,0x65E5,0x32,0x39,0x65E5,0x33,0x30, +0x65E5,0x33,0x31,0x65E5,0x67,0x61,0x6C,0x44A,0x44C,0xA76F,0x53,0x43, +0x46,0x51,0x126,0x153,0xA727,0xAB37,0x26B,0xAB52,0x28D,0x8C48,0x66F4,0x8ECA, +0x8CC8,0x6ED1,0x4E32,0x53E5,0x9F9C,0x9F9C,0x5951,0x91D1,0x5587,0x5948,0x61F6,0x7669, +0x7F85,0x863F,0x87BA,0x88F8,0x908F,0x6A02,0x6D1B,0x70D9,0x73DE,0x843D,0x916A,0x99F1, +0x4E82,0x5375,0x6B04,0x721B,0x862D,0x9E1E,0x5D50,0x6FEB,0x85CD,0x8964,0x62C9,0x81D8, +0x881F,0x5ECA,0x6717,0x6D6A,0x72FC,0x90CE,0x4F86,0x51B7,0x52DE,0x64C4,0x6AD3,0x7210, +0x76E7,0x8001,0x8606,0x865C,0x8DEF,0x9732,0x9B6F,0x9DFA,0x788C,0x797F,0x7DA0,0x83C9, +0x9304,0x9E7F,0x8AD6,0x58DF,0x5F04,0x7C60,0x807E,0x7262,0x78CA,0x8CC2,0x96F7,0x58D8, +0x5C62,0x6A13,0x6DDA,0x6F0F,0x7D2F,0x7E37,0x964B,0x52D2,0x808B,0x51DC,0x51CC,0x7A1C, +0x7DBE,0x83F1,0x9675,0x8B80,0x62CF,0x6A02,0x8AFE,0x4E39,0x5BE7,0x6012,0x7387,0x7570, +0x5317,0x78FB,0x4FBF,0x5FA9,0x4E0D,0x6CCC,0x6578,0x7D22,0x53C3,0x585E,0x7701,0x8449, +0x8AAA,0x6BBA,0x8FB0,0x6C88,0x62FE,0x82E5,0x63A0,0x7565,0x4EAE,0x5169,0x51C9,0x6881, +0x7CE7,0x826F,0x8AD2,0x91CF,0x52F5,0x5442,0x5973,0x5EEC,0x65C5,0x6FFE,0x792A,0x95AD, +0x9A6A,0x9E97,0x9ECE,0x529B,0x66C6,0x6B77,0x8F62,0x5E74,0x6190,0x6200,0x649A,0x6F23, +0x7149,0x7489,0x79CA,0x7DF4,0x806F,0x8F26,0x84EE,0x9023,0x934A,0x5217,0x52A3,0x54BD, +0x70C8,0x88C2,0x8AAA,0x5EC9,0x5FF5,0x637B,0x6BAE,0x7C3E,0x7375,0x4EE4,0x56F9,0x5BE7, +0x5DBA,0x601C,0x73B2,0x7469,0x7F9A,0x8046,0x9234,0x96F6,0x9748,0x9818,0x4F8B,0x79AE, +0x91B4,0x96B8,0x60E1,0x4E86,0x50DA,0x5BEE,0x5C3F,0x6599,0x6A02,0x71CE,0x7642,0x84FC, +0x907C,0x9F8D,0x6688,0x962E,0x5289,0x677B,0x67F3,0x6D41,0x6E9C,0x7409,0x7559,0x786B, +0x7D10,0x985E,0x516D,0x622E,0x9678,0x502B,0x5D19,0x6DEA,0x8F2A,0x5F8B,0x6144,0x6817, +0x7387,0x9686,0x5229,0x540F,0x5C65,0x6613,0x674E,0x68A8,0x6CE5,0x7406,0x75E2,0x7F79, +0x88CF,0x88E1,0x91CC,0x96E2,0x533F,0x6EBA,0x541D,0x71D0,0x7498,0x85FA,0x96A3,0x9C57, +0x9E9F,0x6797,0x6DCB,0x81E8,0x7ACB,0x7B20,0x7C92,0x72C0,0x7099,0x8B58,0x4EC0,0x8336, +0x523A,0x5207,0x5EA6,0x62D3,0x7CD6,0x5B85,0x6D1E,0x66B4,0x8F3B,0x884C,0x964D,0x898B, +0x5ED3,0x5140,0x55C0,0x585A,0x6674,0x51DE,0x732A,0x76CA,0x793C,0x795E,0x7965,0x798F, +0x9756,0x7CBE,0x7FBD,0x8612,0x8AF8,0x9038,0x90FD,0x98EF,0x98FC,0x9928,0x9DB4,0x90DE, +0x96B7,0x4FAE,0x50E7,0x514D,0x52C9,0x52E4,0x5351,0x559D,0x5606,0x5668,0x5840,0x58A8, +0x5C64,0x5C6E,0x6094,0x6168,0x618E,0x61F2,0x654F,0x65E2,0x6691,0x6885,0x6D77,0x6E1A, +0x6F22,0x716E,0x722B,0x7422,0x7891,0x793E,0x7949,0x7948,0x7950,0x7956,0x795D,0x798D, +0x798E,0x7A40,0x7A81,0x7BC0,0x7DF4,0x7E09,0x7E41,0x7F72,0x8005,0x81ED,0x8279,0x8279, +0x8457,0x8910,0x8996,0x8B01,0x8B39,0x8CD3,0x8D08,0x8FB6,0x9038,0x96E3,0x97FF,0x983B, +0x6075,0x242EE,0x8218,0x4E26,0x51B5,0x5168,0x4F80,0x5145,0x5180,0x52C7,0x52FA,0x559D, +0x5555,0x5599,0x55E2,0x585A,0x58B3,0x5944,0x5954,0x5A62,0x5B28,0x5ED2,0x5ED9,0x5F69, +0x5FAD,0x60D8,0x614E,0x6108,0x618E,0x6160,0x61F2,0x6234,0x63C4,0x641C,0x6452,0x6556, +0x6674,0x6717,0x671B,0x6756,0x6B79,0x6BBA,0x6D41,0x6EDB,0x6ECB,0x6F22,0x701E,0x716E, +0x77A7,0x7235,0x72AF,0x732A,0x7471,0x7506,0x753B,0x761D,0x761F,0x76CA,0x76DB,0x76F4, +0x774A,0x7740,0x78CC,0x7AB1,0x7BC0,0x7C7B,0x7D5B,0x7DF4,0x7F3E,0x8005,0x8352,0x83EF, +0x8779,0x8941,0x8986,0x8996,0x8ABF,0x8AF8,0x8ACB,0x8B01,0x8AFE,0x8AED,0x8B39,0x8B8A, +0x8D08,0x8F38,0x9072,0x9199,0x9276,0x967C,0x96E3,0x9756,0x97DB,0x97FF,0x980B,0x983B, +0x9B12,0x9F9C,0x2284A,0x22844,0x233D5,0x3B9D,0x4018,0x4039,0x25249,0x25CD0,0x27ED3,0x9F43, +0x9F8E,0x66,0x66,0x66,0x69,0x66,0x6C,0x66,0x66,0x69,0x66,0x66, +0x6C,0x73,0x74,0x73,0x74,0x574,0x576,0x574,0x565,0x574,0x56B,0x57E, +0x576,0x574,0x56D,0x5D9,0x5B4,0x5F2,0x5B7,0x5E2,0x5D0,0x5D3,0x5D4,0x5DB, +0x5DC,0x5DD,0x5E8,0x5EA,0x2B,0x5E9,0x5C1,0x5E9,0x5C2,0x5E9,0x5BC,0x5C1, +0x5E9,0x5BC,0x5C2,0x5D0,0x5B7,0x5D0,0x5B8,0x5D0,0x5BC,0x5D1,0x5BC,0x5D2, +0x5BC,0x5D3,0x5BC,0x5D4,0x5BC,0x5D5,0x5BC,0x5D6,0x5BC,0x5D8,0x5BC,0x5D9, +0x5BC,0x5DA,0x5BC,0x5DB,0x5BC,0x5DC,0x5BC,0x5DE,0x5BC,0x5E0,0x5BC,0x5E1, +0x5BC,0x5E3,0x5BC,0x5E4,0x5BC,0x5E6,0x5BC,0x5E7,0x5BC,0x5E8,0x5BC,0x5E9, +0x5BC,0x5EA,0x5BC,0x5D5,0x5B9,0x5D1,0x5BF,0x5DB,0x5BF,0x5E4,0x5BF,0x5D0, +0x5DC,0x671,0x671,0x67B,0x67B,0x67B,0x67B,0x67E,0x67E,0x67E,0x67E,0x680, +0x680,0x680,0x680,0x67A,0x67A,0x67A,0x67A,0x67F,0x67F,0x67F,0x67F,0x679, +0x679,0x679,0x679,0x6A4,0x6A4,0x6A4,0x6A4,0x6A6,0x6A6,0x6A6,0x6A6,0x684, +0x684,0x684,0x684,0x683,0x683,0x683,0x683,0x686,0x686,0x686,0x686,0x687, +0x687,0x687,0x687,0x68D,0x68D,0x68C,0x68C,0x68E,0x68E,0x688,0x688,0x698, +0x698,0x691,0x691,0x6A9,0x6A9,0x6A9,0x6A9,0x6AF,0x6AF,0x6AF,0x6AF,0x6B3, +0x6B3,0x6B3,0x6B3,0x6B1,0x6B1,0x6B1,0x6B1,0x6BA,0x6BA,0x6BB,0x6BB,0x6BB, +0x6BB,0x6D5,0x654,0x6D5,0x654,0x6C1,0x6C1,0x6C1,0x6C1,0x6BE,0x6BE,0x6BE, +0x6BE,0x6D2,0x6D2,0x6D2,0x654,0x6D2,0x654,0x6AD,0x6AD,0x6AD,0x6AD,0x6C7, +0x6C7,0x6C6,0x6C6,0x6C8,0x6C8,0x6C7,0x674,0x6CB,0x6CB,0x6C5,0x6C5,0x6C9, +0x6C9,0x6D0,0x6D0,0x6D0,0x6D0,0x649,0x649,0x64A,0x654,0x627,0x64A,0x654, +0x627,0x64A,0x654,0x6D5,0x64A,0x654,0x6D5,0x64A,0x654,0x648,0x64A,0x654, +0x648,0x64A,0x654,0x6C7,0x64A,0x654,0x6C7,0x64A,0x654,0x6C6,0x64A,0x654, +0x6C6,0x64A,0x654,0x6C8,0x64A,0x654,0x6C8,0x64A,0x654,0x6D0,0x64A,0x654, +0x6D0,0x64A,0x654,0x6D0,0x64A,0x654,0x649,0x64A,0x654,0x649,0x64A,0x654, +0x649,0x6CC,0x6CC,0x6CC,0x6CC,0x64A,0x654,0x62C,0x64A,0x654,0x62D,0x64A, +0x654,0x645,0x64A,0x654,0x649,0x64A,0x654,0x64A,0x628,0x62C,0x628,0x62D, +0x628,0x62E,0x628,0x645,0x628,0x649,0x628,0x64A,0x62A,0x62C,0x62A,0x62D, +0x62A,0x62E,0x62A,0x645,0x62A,0x649,0x62A,0x64A,0x62B,0x62C,0x62B,0x645, +0x62B,0x649,0x62B,0x64A,0x62C,0x62D,0x62C,0x645,0x62D,0x62C,0x62D,0x645, +0x62E,0x62C,0x62E,0x62D,0x62E,0x645,0x633,0x62C,0x633,0x62D,0x633,0x62E, +0x633,0x645,0x635,0x62D,0x635,0x645,0x636,0x62C,0x636,0x62D,0x636,0x62E, +0x636,0x645,0x637,0x62D,0x637,0x645,0x638,0x645,0x639,0x62C,0x639,0x645, +0x63A,0x62C,0x63A,0x645,0x641,0x62C,0x641,0x62D,0x641,0x62E,0x641,0x645, +0x641,0x649,0x641,0x64A,0x642,0x62D,0x642,0x645,0x642,0x649,0x642,0x64A, +0x643,0x627,0x643,0x62C,0x643,0x62D,0x643,0x62E,0x643,0x644,0x643,0x645, +0x643,0x649,0x643,0x64A,0x644,0x62C,0x644,0x62D,0x644,0x62E,0x644,0x645, +0x644,0x649,0x644,0x64A,0x645,0x62C,0x645,0x62D,0x645,0x62E,0x645,0x645, +0x645,0x649,0x645,0x64A,0x646,0x62C,0x646,0x62D,0x646,0x62E,0x646,0x645, +0x646,0x649,0x646,0x64A,0x647,0x62C,0x647,0x645,0x647,0x649,0x647,0x64A, +0x64A,0x62C,0x64A,0x62D,0x64A,0x62E,0x64A,0x645,0x64A,0x649,0x64A,0x64A, +0x630,0x670,0x631,0x670,0x649,0x670,0x20,0x64C,0x651,0x20,0x64D,0x651, +0x20,0x64E,0x651,0x20,0x64F,0x651,0x20,0x650,0x651,0x20,0x651,0x670, +0x64A,0x654,0x631,0x64A,0x654,0x632,0x64A,0x654,0x645,0x64A,0x654,0x646, +0x64A,0x654,0x649,0x64A,0x654,0x64A,0x628,0x631,0x628,0x632,0x628,0x645, +0x628,0x646,0x628,0x649,0x628,0x64A,0x62A,0x631,0x62A,0x632,0x62A,0x645, +0x62A,0x646,0x62A,0x649,0x62A,0x64A,0x62B,0x631,0x62B,0x632,0x62B,0x645, +0x62B,0x646,0x62B,0x649,0x62B,0x64A,0x641,0x649,0x641,0x64A,0x642,0x649, +0x642,0x64A,0x643,0x627,0x643,0x644,0x643,0x645,0x643,0x649,0x643,0x64A, +0x644,0x645,0x644,0x649,0x644,0x64A,0x645,0x627,0x645,0x645,0x646,0x631, +0x646,0x632,0x646,0x645,0x646,0x646,0x646,0x649,0x646,0x64A,0x649,0x670, +0x64A,0x631,0x64A,0x632,0x64A,0x645,0x64A,0x646,0x64A,0x649,0x64A,0x64A, +0x64A,0x654,0x62C,0x64A,0x654,0x62D,0x64A,0x654,0x62E,0x64A,0x654,0x645, +0x64A,0x654,0x647,0x628,0x62C,0x628,0x62D,0x628,0x62E,0x628,0x645,0x628, +0x647,0x62A,0x62C,0x62A,0x62D,0x62A,0x62E,0x62A,0x645,0x62A,0x647,0x62B, +0x645,0x62C,0x62D,0x62C,0x645,0x62D,0x62C,0x62D,0x645,0x62E,0x62C,0x62E, +0x645,0x633,0x62C,0x633,0x62D,0x633,0x62E,0x633,0x645,0x635,0x62D,0x635, +0x62E,0x635,0x645,0x636,0x62C,0x636,0x62D,0x636,0x62E,0x636,0x645,0x637, +0x62D,0x638,0x645,0x639,0x62C,0x639,0x645,0x63A,0x62C,0x63A,0x645,0x641, +0x62C,0x641,0x62D,0x641,0x62E,0x641,0x645,0x642,0x62D,0x642,0x645,0x643, +0x62C,0x643,0x62D,0x643,0x62E,0x643,0x644,0x643,0x645,0x644,0x62C,0x644, +0x62D,0x644,0x62E,0x644,0x645,0x644,0x647,0x645,0x62C,0x645,0x62D,0x645, +0x62E,0x645,0x645,0x646,0x62C,0x646,0x62D,0x646,0x62E,0x646,0x645,0x646, +0x647,0x647,0x62C,0x647,0x645,0x647,0x670,0x64A,0x62C,0x64A,0x62D,0x64A, +0x62E,0x64A,0x645,0x64A,0x647,0x64A,0x654,0x645,0x64A,0x654,0x647,0x628, +0x645,0x628,0x647,0x62A,0x645,0x62A,0x647,0x62B,0x645,0x62B,0x647,0x633, +0x645,0x633,0x647,0x634,0x645,0x634,0x647,0x643,0x644,0x643,0x645,0x644, +0x645,0x646,0x645,0x646,0x647,0x64A,0x645,0x64A,0x647,0x640,0x64E,0x651, +0x640,0x64F,0x651,0x640,0x650,0x651,0x637,0x649,0x637,0x64A,0x639,0x649, +0x639,0x64A,0x63A,0x649,0x63A,0x64A,0x633,0x649,0x633,0x64A,0x634,0x649, +0x634,0x64A,0x62D,0x649,0x62D,0x64A,0x62C,0x649,0x62C,0x64A,0x62E,0x649, +0x62E,0x64A,0x635,0x649,0x635,0x64A,0x636,0x649,0x636,0x64A,0x634,0x62C, +0x634,0x62D,0x634,0x62E,0x634,0x645,0x634,0x631,0x633,0x631,0x635,0x631, +0x636,0x631,0x637,0x649,0x637,0x64A,0x639,0x649,0x639,0x64A,0x63A,0x649, +0x63A,0x64A,0x633,0x649,0x633,0x64A,0x634,0x649,0x634,0x64A,0x62D,0x649, +0x62D,0x64A,0x62C,0x649,0x62C,0x64A,0x62E,0x649,0x62E,0x64A,0x635,0x649, +0x635,0x64A,0x636,0x649,0x636,0x64A,0x634,0x62C,0x634,0x62D,0x634,0x62E, +0x634,0x645,0x634,0x631,0x633,0x631,0x635,0x631,0x636,0x631,0x634,0x62C, +0x634,0x62D,0x634,0x62E,0x634,0x645,0x633,0x647,0x634,0x647,0x637,0x645, +0x633,0x62C,0x633,0x62D,0x633,0x62E,0x634,0x62C,0x634,0x62D,0x634,0x62E, +0x637,0x645,0x638,0x645,0x627,0x64B,0x627,0x64B,0x62A,0x62C,0x645,0x62A, +0x62D,0x62C,0x62A,0x62D,0x62C,0x62A,0x62D,0x645,0x62A,0x62E,0x645,0x62A, +0x645,0x62C,0x62A,0x645,0x62D,0x62A,0x645,0x62E,0x62C,0x645,0x62D,0x62C, +0x645,0x62D,0x62D,0x645,0x64A,0x62D,0x645,0x649,0x633,0x62D,0x62C,0x633, +0x62C,0x62D,0x633,0x62C,0x649,0x633,0x645,0x62D,0x633,0x645,0x62D,0x633, +0x645,0x62C,0x633,0x645,0x645,0x633,0x645,0x645,0x635,0x62D,0x62D,0x635, +0x62D,0x62D,0x635,0x645,0x645,0x634,0x62D,0x645,0x634,0x62D,0x645,0x634, +0x62C,0x64A,0x634,0x645,0x62E,0x634,0x645,0x62E,0x634,0x645,0x645,0x634, +0x645,0x645,0x636,0x62D,0x649,0x636,0x62E,0x645,0x636,0x62E,0x645,0x637, +0x645,0x62D,0x637,0x645,0x62D,0x637,0x645,0x645,0x637,0x645,0x64A,0x639, +0x62C,0x645,0x639,0x645,0x645,0x639,0x645,0x645,0x639,0x645,0x649,0x63A, +0x645,0x645,0x63A,0x645,0x64A,0x63A,0x645,0x649,0x641,0x62E,0x645,0x641, +0x62E,0x645,0x642,0x645,0x62D,0x642,0x645,0x645,0x644,0x62D,0x645,0x644, +0x62D,0x64A,0x644,0x62D,0x649,0x644,0x62C,0x62C,0x644,0x62C,0x62C,0x644, +0x62E,0x645,0x644,0x62E,0x645,0x644,0x645,0x62D,0x644,0x645,0x62D,0x645, +0x62D,0x62C,0x645,0x62D,0x645,0x645,0x62D,0x64A,0x645,0x62C,0x62D,0x645, +0x62C,0x645,0x645,0x62E,0x62C,0x645,0x62E,0x645,0x645,0x62C,0x62E,0x647, +0x645,0x62C,0x647,0x645,0x645,0x646,0x62D,0x645,0x646,0x62D,0x649,0x646, +0x62C,0x645,0x646,0x62C,0x645,0x646,0x62C,0x649,0x646,0x645,0x64A,0x646, +0x645,0x649,0x64A,0x645,0x645,0x64A,0x645,0x645,0x628,0x62E,0x64A,0x62A, +0x62C,0x64A,0x62A,0x62C,0x649,0x62A,0x62E,0x64A,0x62A,0x62E,0x649,0x62A, +0x645,0x64A,0x62A,0x645,0x649,0x62C,0x645,0x64A,0x62C,0x62D,0x649,0x62C, +0x645,0x649,0x633,0x62E,0x649,0x635,0x62D,0x64A,0x634,0x62D,0x64A,0x636, +0x62D,0x64A,0x644,0x62C,0x64A,0x644,0x645,0x64A,0x64A,0x62D,0x64A,0x64A, +0x62C,0x64A,0x64A,0x645,0x64A,0x645,0x645,0x64A,0x642,0x645,0x64A,0x646, +0x62D,0x64A,0x642,0x645,0x62D,0x644,0x62D,0x645,0x639,0x645,0x64A,0x643, +0x645,0x64A,0x646,0x62C,0x62D,0x645,0x62E,0x64A,0x644,0x62C,0x645,0x643, +0x645,0x645,0x644,0x62C,0x645,0x646,0x62C,0x62D,0x62C,0x62D,0x64A,0x62D, +0x62C,0x64A,0x645,0x62C,0x64A,0x641,0x645,0x64A,0x628,0x62D,0x64A,0x643, +0x645,0x645,0x639,0x62C,0x645,0x635,0x645,0x645,0x633,0x62E,0x64A,0x646, +0x62C,0x64A,0x635,0x644,0x6D2,0x642,0x644,0x6D2,0x627,0x644,0x644,0x647, +0x627,0x643,0x628,0x631,0x645,0x62D,0x645,0x62F,0x635,0x644,0x639,0x645, +0x631,0x633,0x648,0x644,0x639,0x644,0x64A,0x647,0x648,0x633,0x644,0x645, +0x635,0x644,0x649,0x635,0x644,0x649,0x20,0x627,0x644,0x644,0x647,0x20, +0x639,0x644,0x64A,0x647,0x20,0x648,0x633,0x644,0x645,0x62C,0x644,0x20, +0x62C,0x644,0x627,0x644,0x647,0x631,0x6CC,0x627,0x644,0x2C,0x3001,0x3002, +0x3A,0x3B,0x21,0x3F,0x3016,0x3017,0x2E,0x2E,0x2E,0x2E,0x2E,0x2014, +0x2013,0x5F,0x5F,0x28,0x29,0x7B,0x7D,0x3014,0x3015,0x3010,0x3011,0x300A, +0x300B,0x3008,0x3009,0x300C,0x300D,0x300E,0x300F,0x5B,0x5D,0x20,0x305,0x20, +0x305,0x20,0x305,0x20,0x305,0x5F,0x5F,0x5F,0x2C,0x3001,0x2E,0x3B, +0x3A,0x3F,0x21,0x2014,0x28,0x29,0x7B,0x7D,0x3014,0x3015,0x23,0x26, +0x2A,0x2B,0x2D,0x3C,0x3E,0x3D,0x5C,0x24,0x25,0x40,0x20,0x64B, +0x640,0x64B,0x20,0x64C,0x20,0x64D,0x20,0x64E,0x640,0x64E,0x20,0x64F, +0x640,0x64F,0x20,0x650,0x640,0x650,0x20,0x651,0x640,0x651,0x20,0x652, +0x640,0x652,0x621,0x627,0x653,0x627,0x653,0x627,0x654,0x627,0x654,0x648, +0x654,0x648,0x654,0x627,0x655,0x627,0x655,0x64A,0x654,0x64A,0x654,0x64A, +0x654,0x64A,0x654,0x627,0x627,0x628,0x628,0x628,0x628,0x629,0x629,0x62A, +0x62A,0x62A,0x62A,0x62B,0x62B,0x62B,0x62B,0x62C,0x62C,0x62C,0x62C,0x62D, +0x62D,0x62D,0x62D,0x62E,0x62E,0x62E,0x62E,0x62F,0x62F,0x630,0x630,0x631, +0x631,0x632,0x632,0x633,0x633,0x633,0x633,0x634,0x634,0x634,0x634,0x635, +0x635,0x635,0x635,0x636,0x636,0x636,0x636,0x637,0x637,0x637,0x637,0x638, +0x638,0x638,0x638,0x639,0x639,0x639,0x639,0x63A,0x63A,0x63A,0x63A,0x641, +0x641,0x641,0x641,0x642,0x642,0x642,0x642,0x643,0x643,0x643,0x643,0x644, +0x644,0x644,0x644,0x645,0x645,0x645,0x645,0x646,0x646,0x646,0x646,0x647, +0x647,0x647,0x647,0x648,0x648,0x649,0x649,0x64A,0x64A,0x64A,0x64A,0x644, +0x627,0x653,0x644,0x627,0x653,0x644,0x627,0x654,0x644,0x627,0x654,0x644, +0x627,0x655,0x644,0x627,0x655,0x644,0x627,0x644,0x627,0x21,0x22,0x23, +0x24,0x25,0x26,0x27,0x28,0x29,0x2A,0x2B,0x2C,0x2D,0x2E,0x2F, +0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3A,0x3B, +0x3C,0x3D,0x3E,0x3F,0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47, +0x48,0x49,0x4A,0x4B,0x4C,0x4D,0x4E,0x4F,0x50,0x51,0x52,0x53, +0x54,0x55,0x56,0x57,0x58,0x59,0x5A,0x5B,0x5C,0x5D,0x5E,0x5F, +0x60,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x6B, +0x6C,0x6D,0x6E,0x6F,0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77, +0x78,0x79,0x7A,0x7B,0x7C,0x7D,0x7E,0x2985,0x2986,0x3002,0x300C,0x300D, +0x3001,0x30FB,0x30F2,0x30A1,0x30A3,0x30A5,0x30A7,0x30A9,0x30E3,0x30E5,0x30E7,0x30C3, +0x30FC,0x30A2,0x30A4,0x30A6,0x30A8,0x30AA,0x30AB,0x30AD,0x30AF,0x30B1,0x30B3,0x30B5, +0x30B7,0x30B9,0x30BB,0x30BD,0x30BF,0x30C1,0x30C4,0x30C6,0x30C8,0x30CA,0x30CB,0x30CC, +0x30CD,0x30CE,0x30CF,0x30D2,0x30D5,0x30D8,0x30DB,0x30DE,0x30DF,0x30E0,0x30E1,0x30E2, +0x30E4,0x30E6,0x30E8,0x30E9,0x30EA,0x30EB,0x30EC,0x30ED,0x30EF,0x30F3,0x3099,0x309A, +0x1160,0x1100,0x1101,0x11AA,0x1102,0x11AC,0x11AD,0x1103,0x1104,0x1105,0x11B0,0x11B1, +0x11B2,0x11B3,0x11B4,0x11B5,0x111A,0x1106,0x1107,0x1108,0x1121,0x1109,0x110A,0x110B, +0x110C,0x110D,0x110E,0x110F,0x1110,0x1111,0x1112,0x1161,0x1162,0x1163,0x1164,0x1165, +0x1166,0x1167,0x1168,0x1169,0x116A,0x116B,0x116C,0x116D,0x116E,0x116F,0x1170,0x1171, +0x1172,0x1173,0x1174,0x1175,0xA2,0xA3,0xAC,0x20,0x304,0xA6,0xA5,0x20A9, +0x2502,0x2190,0x2191,0x2192,0x2193,0x25A0,0x25CB,0x105D2,0x307,0x105DA,0x307,0x2D0, +0x2D1,0xE6,0x299,0x253,0x2A3,0xAB66,0x2A5,0x2A4,0x256,0x257,0x1D91,0x258, +0x25E,0x2A9,0x264,0x262,0x260,0x29B,0x127,0x29C,0x267,0x284,0x2AA,0x2AB, +0x26C,0x1DF04,0xA78E,0x26E,0x1DF05,0x28E,0x1DF06,0xF8,0x276,0x277,0x71,0x27A, +0x1DF08,0x27D,0x27E,0x280,0x2A8,0x2A6,0xAB67,0x2A7,0x288,0x2C71,0x28F,0x2A1, +0x2A2,0x298,0x1C0,0x1C1,0x1C2,0x1DF0A,0x1DF1E,0x11099,0x110BA,0x1109B,0x110BA,0x110A5, +0x110BA,0x11131,0x11127,0x11132,0x11127,0x11347,0x1133E,0x11347,0x11357,0x11382,0x113C9,0x11384, +0x113BB,0x1138B,0x113C2,0x11390,0x113C9,0x113C2,0x113C2,0x113C2,0x113B8,0x113C2,0x113C9,0x114B9, +0x114BA,0x114B9,0x114B0,0x114B9,0x114BD,0x115B8,0x115AF,0x115B9,0x115AF,0x11935,0x11930,0x1611E, +0x1611E,0x1611E,0x16129,0x1611E,0x1611F,0x16129,0x1611F,0x1611E,0x16120,0x1611E,0x1611E,0x1611F, +0x1611E,0x16129,0x1611F,0x1611E,0x1611E,0x16120,0x16D67,0x16D67,0x16D63,0x16D67,0x16D63,0x16D67, +0x16D67,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A,0x4B, +0x4C,0x4D,0x4E,0x4F,0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57, +0x58,0x59,0x5A,0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38, +0x39,0x1D157,0x1D165,0x1D158,0x1D165,0x1D158,0x1D165,0x1D16E,0x1D158,0x1D165,0x1D16F,0x1D158, +0x1D165,0x1D170,0x1D158,0x1D165,0x1D171,0x1D158,0x1D165,0x1D172,0x1D1B9,0x1D165,0x1D1BA,0x1D165, +0x1D1B9,0x1D165,0x1D16E,0x1D1BA,0x1D165,0x1D16E,0x1D1B9,0x1D165,0x1D16F,0x1D1BA,0x1D165,0x1D16F, +0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A,0x4B,0x4C, +0x4D,0x4E,0x4F,0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58, +0x59,0x5A,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A, +0x6B,0x6C,0x6D,0x6E,0x6F,0x70,0x71,0x72,0x73,0x74,0x75,0x76, +0x77,0x78,0x79,0x7A,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48, +0x49,0x4A,0x4B,0x4C,0x4D,0x4E,0x4F,0x50,0x51,0x52,0x53,0x54, +0x55,0x56,0x57,0x58,0x59,0x5A,0x61,0x62,0x63,0x64,0x65,0x66, +0x67,0x69,0x6A,0x6B,0x6C,0x6D,0x6E,0x6F,0x70,0x71,0x72,0x73, +0x74,0x75,0x76,0x77,0x78,0x79,0x7A,0x41,0x42,0x43,0x44,0x45, +0x46,0x47,0x48,0x49,0x4A,0x4B,0x4C,0x4D,0x4E,0x4F,0x50,0x51, +0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5A,0x61,0x62,0x63, +0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x6B,0x6C,0x6D,0x6E,0x6F, +0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7A,0x41, +0x43,0x44,0x47,0x4A,0x4B,0x4E,0x4F,0x50,0x51,0x53,0x54,0x55, +0x56,0x57,0x58,0x59,0x5A,0x61,0x62,0x63,0x64,0x66,0x68,0x69, +0x6A,0x6B,0x6C,0x6D,0x6E,0x70,0x71,0x72,0x73,0x74,0x75,0x76, +0x77,0x78,0x79,0x7A,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48, +0x49,0x4A,0x4B,0x4C,0x4D,0x4E,0x4F,0x50,0x51,0x52,0x53,0x54, +0x55,0x56,0x57,0x58,0x59,0x5A,0x61,0x62,0x63,0x64,0x65,0x66, +0x67,0x68,0x69,0x6A,0x6B,0x6C,0x6D,0x6E,0x6F,0x70,0x71,0x72, +0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7A,0x41,0x42,0x44,0x45, +0x46,0x47,0x4A,0x4B,0x4C,0x4D,0x4E,0x4F,0x50,0x51,0x53,0x54, +0x55,0x56,0x57,0x58,0x59,0x61,0x62,0x63,0x64,0x65,0x66,0x67, +0x68,0x69,0x6A,0x6B,0x6C,0x6D,0x6E,0x6F,0x70,0x71,0x72,0x73, +0x74,0x75,0x76,0x77,0x78,0x79,0x7A,0x41,0x42,0x44,0x45,0x46, +0x47,0x49,0x4A,0x4B,0x4C,0x4D,0x4F,0x53,0x54,0x55,0x56,0x57, +0x58,0x59,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A, +0x6B,0x6C,0x6D,0x6E,0x6F,0x70,0x71,0x72,0x73,0x74,0x75,0x76, +0x77,0x78,0x79,0x7A,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48, +0x49,0x4A,0x4B,0x4C,0x4D,0x4E,0x4F,0x50,0x51,0x52,0x53,0x54, +0x55,0x56,0x57,0x58,0x59,0x5A,0x61,0x62,0x63,0x64,0x65,0x66, +0x67,0x68,0x69,0x6A,0x6B,0x6C,0x6D,0x6E,0x6F,0x70,0x71,0x72, +0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7A,0x41,0x42,0x43,0x44, +0x45,0x46,0x47,0x48,0x49,0x4A,0x4B,0x4C,0x4D,0x4E,0x4F,0x50, +0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5A,0x61,0x62, +0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x6B,0x6C,0x6D,0x6E, +0x6F,0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7A, +0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A,0x4B,0x4C, +0x4D,0x4E,0x4F,0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58, +0x59,0x5A,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A, +0x6B,0x6C,0x6D,0x6E,0x6F,0x70,0x71,0x72,0x73,0x74,0x75,0x76, +0x77,0x78,0x79,0x7A,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48, +0x49,0x4A,0x4B,0x4C,0x4D,0x4E,0x4F,0x50,0x51,0x52,0x53,0x54, +0x55,0x56,0x57,0x58,0x59,0x5A,0x61,0x62,0x63,0x64,0x65,0x66, +0x67,0x68,0x69,0x6A,0x6B,0x6C,0x6D,0x6E,0x6F,0x70,0x71,0x72, +0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7A,0x41,0x42,0x43,0x44, +0x45,0x46,0x47,0x48,0x49,0x4A,0x4B,0x4C,0x4D,0x4E,0x4F,0x50, +0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5A,0x61,0x62, +0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x6B,0x6C,0x6D,0x6E, +0x6F,0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7A, +0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A,0x4B,0x4C, +0x4D,0x4E,0x4F,0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58, +0x59,0x5A,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A, +0x6B,0x6C,0x6D,0x6E,0x6F,0x70,0x71,0x72,0x73,0x74,0x75,0x76, +0x77,0x78,0x79,0x7A,0x131,0x237,0x391,0x392,0x393,0x394,0x395,0x396, +0x397,0x398,0x399,0x39A,0x39B,0x39C,0x39D,0x39E,0x39F,0x3A0,0x3A1,0x398, +0x3A3,0x3A4,0x3A5,0x3A6,0x3A7,0x3A8,0x3A9,0x2207,0x3B1,0x3B2,0x3B3,0x3B4, +0x3B5,0x3B6,0x3B7,0x3B8,0x3B9,0x3BA,0x3BB,0x3BC,0x3BD,0x3BE,0x3BF,0x3C0, +0x3C1,0x3C2,0x3C3,0x3C4,0x3C5,0x3C6,0x3C7,0x3C8,0x3C9,0x2202,0x3B5,0x3B8, +0x3BA,0x3C6,0x3C1,0x3C0,0x391,0x392,0x393,0x394,0x395,0x396,0x397,0x398, +0x399,0x39A,0x39B,0x39C,0x39D,0x39E,0x39F,0x3A0,0x3A1,0x398,0x3A3,0x3A4, +0x3A5,0x3A6,0x3A7,0x3A8,0x3A9,0x2207,0x3B1,0x3B2,0x3B3,0x3B4,0x3B5,0x3B6, +0x3B7,0x3B8,0x3B9,0x3BA,0x3BB,0x3BC,0x3BD,0x3BE,0x3BF,0x3C0,0x3C1,0x3C2, +0x3C3,0x3C4,0x3C5,0x3C6,0x3C7,0x3C8,0x3C9,0x2202,0x3B5,0x3B8,0x3BA,0x3C6, +0x3C1,0x3C0,0x391,0x392,0x393,0x394,0x395,0x396,0x397,0x398,0x399,0x39A, +0x39B,0x39C,0x39D,0x39E,0x39F,0x3A0,0x3A1,0x398,0x3A3,0x3A4,0x3A5,0x3A6, +0x3A7,0x3A8,0x3A9,0x2207,0x3B1,0x3B2,0x3B3,0x3B4,0x3B5,0x3B6,0x3B7,0x3B8, +0x3B9,0x3BA,0x3BB,0x3BC,0x3BD,0x3BE,0x3BF,0x3C0,0x3C1,0x3C2,0x3C3,0x3C4, +0x3C5,0x3C6,0x3C7,0x3C8,0x3C9,0x2202,0x3B5,0x3B8,0x3BA,0x3C6,0x3C1,0x3C0, +0x391,0x392,0x393,0x394,0x395,0x396,0x397,0x398,0x399,0x39A,0x39B,0x39C, +0x39D,0x39E,0x39F,0x3A0,0x3A1,0x398,0x3A3,0x3A4,0x3A5,0x3A6,0x3A7,0x3A8, +0x3A9,0x2207,0x3B1,0x3B2,0x3B3,0x3B4,0x3B5,0x3B6,0x3B7,0x3B8,0x3B9,0x3BA, +0x3BB,0x3BC,0x3BD,0x3BE,0x3BF,0x3C0,0x3C1,0x3C2,0x3C3,0x3C4,0x3C5,0x3C6, +0x3C7,0x3C8,0x3C9,0x2202,0x3B5,0x3B8,0x3BA,0x3C6,0x3C1,0x3C0,0x391,0x392, +0x393,0x394,0x395,0x396,0x397,0x398,0x399,0x39A,0x39B,0x39C,0x39D,0x39E, +0x39F,0x3A0,0x3A1,0x398,0x3A3,0x3A4,0x3A5,0x3A6,0x3A7,0x3A8,0x3A9,0x2207, +0x3B1,0x3B2,0x3B3,0x3B4,0x3B5,0x3B6,0x3B7,0x3B8,0x3B9,0x3BA,0x3BB,0x3BC, +0x3BD,0x3BE,0x3BF,0x3C0,0x3C1,0x3C2,0x3C3,0x3C4,0x3C5,0x3C6,0x3C7,0x3C8, +0x3C9,0x2202,0x3B5,0x3B8,0x3BA,0x3C6,0x3C1,0x3C0,0x3DC,0x3DD,0x30,0x31, +0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x30,0x31,0x32,0x33, +0x34,0x35,0x36,0x37,0x38,0x39,0x30,0x31,0x32,0x33,0x34,0x35, +0x36,0x37,0x38,0x39,0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37, +0x38,0x39,0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39, +0x430,0x431,0x432,0x433,0x434,0x435,0x436,0x437,0x438,0x43A,0x43B,0x43C, +0x43E,0x43F,0x440,0x441,0x442,0x443,0x444,0x445,0x446,0x447,0x448,0x44B, +0x44D,0x44E,0xA689,0x4D9,0x456,0x458,0x4E9,0x4AF,0x4CF,0x430,0x431,0x432, +0x433,0x434,0x435,0x436,0x437,0x438,0x43A,0x43B,0x43E,0x43F,0x441,0x443, +0x444,0x445,0x446,0x447,0x448,0x44A,0x44B,0x491,0x456,0x455,0x45F,0x4AB, +0xA651,0x4B1,0x627,0x628,0x62C,0x62F,0x648,0x632,0x62D,0x637,0x64A,0x643, +0x644,0x645,0x646,0x633,0x639,0x641,0x635,0x642,0x631,0x634,0x62A,0x62B, +0x62E,0x630,0x636,0x638,0x63A,0x66E,0x6BA,0x6A1,0x66F,0x628,0x62C,0x647, +0x62D,0x64A,0x643,0x644,0x645,0x646,0x633,0x639,0x641,0x635,0x642,0x634, +0x62A,0x62B,0x62E,0x636,0x63A,0x62C,0x62D,0x64A,0x644,0x646,0x633,0x639, +0x635,0x642,0x634,0x62E,0x636,0x63A,0x6BA,0x66F,0x628,0x62C,0x647,0x62D, +0x637,0x64A,0x643,0x645,0x646,0x633,0x639,0x641,0x635,0x642,0x634,0x62A, +0x62B,0x62E,0x636,0x638,0x63A,0x66E,0x6A1,0x627,0x628,0x62C,0x62F,0x647, +0x648,0x632,0x62D,0x637,0x64A,0x644,0x645,0x646,0x633,0x639,0x641,0x635, +0x642,0x631,0x634,0x62A,0x62B,0x62E,0x630,0x636,0x638,0x63A,0x628,0x62C, +0x62F,0x648,0x632,0x62D,0x637,0x64A,0x644,0x645,0x646,0x633,0x639,0x641, +0x635,0x642,0x631,0x634,0x62A,0x62B,0x62E,0x630,0x636,0x638,0x63A,0x30, +0x2E,0x30,0x2C,0x31,0x2C,0x32,0x2C,0x33,0x2C,0x34,0x2C,0x35, +0x2C,0x36,0x2C,0x37,0x2C,0x38,0x2C,0x39,0x2C,0x28,0x41,0x29, +0x28,0x42,0x29,0x28,0x43,0x29,0x28,0x44,0x29,0x28,0x45,0x29, +0x28,0x46,0x29,0x28,0x47,0x29,0x28,0x48,0x29,0x28,0x49,0x29, +0x28,0x4A,0x29,0x28,0x4B,0x29,0x28,0x4C,0x29,0x28,0x4D,0x29, +0x28,0x4E,0x29,0x28,0x4F,0x29,0x28,0x50,0x29,0x28,0x51,0x29, +0x28,0x52,0x29,0x28,0x53,0x29,0x28,0x54,0x29,0x28,0x55,0x29, +0x28,0x56,0x29,0x28,0x57,0x29,0x28,0x58,0x29,0x28,0x59,0x29, +0x28,0x5A,0x29,0x3014,0x53,0x3015,0x43,0x52,0x43,0x44,0x57,0x5A, +0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A,0x4B,0x4C, +0x4D,0x4E,0x4F,0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58, +0x59,0x5A,0x48,0x56,0x4D,0x56,0x53,0x44,0x53,0x53,0x50,0x50, +0x56,0x57,0x43,0x4D,0x43,0x4D,0x44,0x4D,0x52,0x44,0x4A,0x307B, +0x304B,0x30B3,0x30B3,0x30B5,0x624B,0x5B57,0x53CC,0x30C6,0x3099,0x4E8C,0x591A,0x89E3, +0x5929,0x4EA4,0x6620,0x7121,0x6599,0x524D,0x5F8C,0x518D,0x65B0,0x521D,0x7D42,0x751F, +0x8CA9,0x58F0,0x5439,0x6F14,0x6295,0x6355,0x4E00,0x4E09,0x904A,0x5DE6,0x4E2D,0x53F3, +0x6307,0x8D70,0x6253,0x7981,0x7A7A,0x5408,0x6E80,0x6709,0x6708,0x7533,0x5272,0x55B6, +0x914D,0x3014,0x672C,0x3015,0x3014,0x4E09,0x3015,0x3014,0x4E8C,0x3015,0x3014,0x5B89, +0x3015,0x3014,0x70B9,0x3015,0x3014,0x6253,0x3015,0x3014,0x76D7,0x3015,0x3014,0x52DD, +0x3015,0x3014,0x6557,0x3015,0x5F97,0x53EF,0x30,0x31,0x32,0x33,0x34,0x35, +0x36,0x37,0x38,0x39,0x4E3D,0x4E38,0x4E41,0x20122,0x4F60,0x4FAE,0x4FBB,0x5002, +0x507A,0x5099,0x50E7,0x50CF,0x349E,0x2063A,0x514D,0x5154,0x5164,0x5177,0x2051C,0x34B9, +0x5167,0x518D,0x2054B,0x5197,0x51A4,0x4ECC,0x51AC,0x51B5,0x291DF,0x51F5,0x5203,0x34DF, +0x523B,0x5246,0x5272,0x5277,0x3515,0x52C7,0x52C9,0x52E4,0x52FA,0x5305,0x5306,0x5317, +0x5349,0x5351,0x535A,0x5373,0x537D,0x537F,0x537F,0x537F,0x20A2C,0x7070,0x53CA,0x53DF, +0x20B63,0x53EB,0x53F1,0x5406,0x549E,0x5438,0x5448,0x5468,0x54A2,0x54F6,0x5510,0x5553, +0x5563,0x5584,0x5584,0x5599,0x55AB,0x55B3,0x55C2,0x5716,0x5606,0x5717,0x5651,0x5674, +0x5207,0x58EE,0x57CE,0x57F4,0x580D,0x578B,0x5832,0x5831,0x58AC,0x214E4,0x58F2,0x58F7, +0x5906,0x591A,0x5922,0x5962,0x216A8,0x216EA,0x59EC,0x5A1B,0x5A27,0x59D8,0x5A66,0x36EE, +0x36FC,0x5B08,0x5B3E,0x5B3E,0x219C8,0x5BC3,0x5BD8,0x5BE7,0x5BF3,0x21B18,0x5BFF,0x5C06, +0x5F53,0x5C22,0x3781,0x5C60,0x5C6E,0x5CC0,0x5C8D,0x21DE4,0x5D43,0x21DE6,0x5D6E,0x5D6B, +0x5D7C,0x5DE1,0x5DE2,0x382F,0x5DFD,0x5E28,0x5E3D,0x5E69,0x3862,0x22183,0x387C,0x5EB0, +0x5EB3,0x5EB6,0x5ECA,0x2A392,0x5EFE,0x22331,0x22331,0x8201,0x5F22,0x5F22,0x38C7,0x232B8, +0x261DA,0x5F62,0x5F6B,0x38E3,0x5F9A,0x5FCD,0x5FD7,0x5FF9,0x6081,0x393A,0x391C,0x6094, +0x226D4,0x60C7,0x6148,0x614C,0x614E,0x614C,0x617A,0x618E,0x61B2,0x61A4,0x61AF,0x61DE, +0x61F2,0x61F6,0x6210,0x621B,0x625D,0x62B1,0x62D4,0x6350,0x22B0C,0x633D,0x62FC,0x6368, +0x6383,0x63E4,0x22BF1,0x6422,0x63C5,0x63A9,0x3A2E,0x6469,0x647E,0x649D,0x6477,0x3A6C, +0x654F,0x656C,0x2300A,0x65E3,0x66F8,0x6649,0x3B19,0x6691,0x3B08,0x3AE4,0x5192,0x5195, +0x6700,0x669C,0x80AD,0x43D9,0x6717,0x671B,0x6721,0x675E,0x6753,0x233C3,0x3B49,0x67FA, +0x6785,0x6852,0x6885,0x2346D,0x688E,0x681F,0x6914,0x3B9D,0x6942,0x69A3,0x69EA,0x6AA8, +0x236A3,0x6ADB,0x3C18,0x6B21,0x238A7,0x6B54,0x3C4E,0x6B72,0x6B9F,0x6BBA,0x6BBB,0x23A8D, +0x21D0B,0x23AFA,0x6C4E,0x23CBC,0x6CBF,0x6CCD,0x6C67,0x6D16,0x6D3E,0x6D77,0x6D41,0x6D69, +0x6D78,0x6D85,0x23D1E,0x6D34,0x6E2F,0x6E6E,0x3D33,0x6ECB,0x6EC7,0x23ED1,0x6DF9,0x6F6E, +0x23F5E,0x23F8E,0x6FC6,0x7039,0x701E,0x701B,0x3D96,0x704A,0x707D,0x7077,0x70AD,0x20525, +0x7145,0x24263,0x719C,0x243AB,0x7228,0x7235,0x7250,0x24608,0x7280,0x7295,0x24735,0x24814, +0x737A,0x738B,0x3EAC,0x73A5,0x3EB8,0x3EB8,0x7447,0x745C,0x7471,0x7485,0x74CA,0x3F1B, +0x7524,0x24C36,0x753E,0x24C92,0x7570,0x2219F,0x7610,0x24FA1,0x24FB8,0x25044,0x3FFC,0x4008, +0x76F4,0x250F3,0x250F2,0x25119,0x25133,0x771E,0x771F,0x771F,0x774A,0x4039,0x778B,0x4046, +0x4096,0x2541D,0x784E,0x788C,0x78CC,0x40E3,0x25626,0x7956,0x2569A,0x256C5,0x798F,0x79EB, +0x412F,0x7A40,0x7A4A,0x7A4F,0x2597C,0x25AA7,0x25AA7,0x7AEE,0x4202,0x25BAB,0x7BC6,0x7BC9, +0x4227,0x25C80,0x7CD2,0x42A0,0x7CE8,0x7CE3,0x7D00,0x25F86,0x7D63,0x4301,0x7DC7,0x7E02, +0x7E45,0x4334,0x26228,0x26247,0x4359,0x262D9,0x7F7A,0x2633E,0x7F95,0x7FFA,0x8005,0x264DA, +0x26523,0x8060,0x265A8,0x8070,0x2335F,0x43D5,0x80B2,0x8103,0x440B,0x813E,0x5AB5,0x267A7, +0x267B5,0x23393,0x2339C,0x8201,0x8204,0x8F9E,0x446B,0x8291,0x828B,0x829D,0x52B3,0x82B1, +0x82B3,0x82BD,0x82E6,0x26B3C,0x82E5,0x831D,0x8363,0x83AD,0x8323,0x83BD,0x83E7,0x8457, +0x8353,0x83CA,0x83CC,0x83DC,0x26C36,0x26D6B,0x26CD5,0x452B,0x84F1,0x84F3,0x8516,0x273CA, +0x8564,0x26F2C,0x455D,0x4561,0x26FB1,0x270D2,0x456B,0x8650,0x865C,0x8667,0x8669,0x86A9, +0x8688,0x870E,0x86E2,0x8779,0x8728,0x876B,0x8786,0x45D7,0x87E1,0x8801,0x45F9,0x8860, +0x8863,0x27667,0x88D7,0x88DE,0x4635,0x88FA,0x34BB,0x278AE,0x27966,0x46BE,0x46C7,0x8AA0, +0x8AED,0x8B8A,0x8C55,0x27CA8,0x8CAB,0x8CC1,0x8D1B,0x8D77,0x27F2F,0x20804,0x8DCB,0x8DBC, +0x8DF0,0x208DE,0x8ED4,0x8F38,0x285D2,0x285ED,0x9094,0x90F1,0x9111,0x2872E,0x911B,0x9238, +0x92D7,0x92D8,0x927C,0x93F9,0x9415,0x28BFA,0x958B,0x4995,0x95B7,0x28D77,0x49E6,0x96C3, +0x5DB2,0x9723,0x29145,0x2921A,0x4A6E,0x4A76,0x97E0,0x2940A,0x4AB2,0x29496,0x980B,0x980B, +0x9829,0x295B6,0x98E2,0x4B33,0x9929,0x99A7,0x99C2,0x99FE,0x4BCE,0x29B30,0x9B12,0x9C40, +0x9CFD,0x4CCE,0x4CED,0x9D67,0x2A0CE,0x4CF8,0x2A105,0x2A20E,0x2A291,0x9EBB,0x4D56,0x9EF9, +0x9EFE,0x9F05,0x9F0F,0x9F16,0x9F3B,0x2A600, +}; +const size_t k_decomp_pool_n = sizeof(k_decomp_pool)/sizeof(k_decomp_pool[0]); + +/* Sorted by codepoint, so a lookup is a binary search. */ +const DecompRow k_decomp_rows[] = { +{0xA0,0,0,0,1}, +{0xA8,0,0,1,2}, +{0xAA,0,0,3,1}, +{0xAF,0,0,4,2}, +{0xB2,0,0,6,1}, +{0xB3,0,0,7,1}, +{0xB4,0,0,8,2}, +{0xB5,0,0,10,1}, +{0xB8,0,0,11,2}, +{0xB9,0,0,13,1}, +{0xBA,0,0,14,1}, +{0xBC,0,0,15,3}, +{0xBD,0,0,18,3}, +{0xBE,0,0,21,3}, +{0xC0,24,2,24,2}, +{0xC1,26,2,26,2}, +{0xC2,28,2,28,2}, +{0xC3,30,2,30,2}, +{0xC4,32,2,32,2}, +{0xC5,34,2,34,2}, +{0xC7,36,2,36,2}, +{0xC8,38,2,38,2}, +{0xC9,40,2,40,2}, +{0xCA,42,2,42,2}, +{0xCB,44,2,44,2}, +{0xCC,46,2,46,2}, +{0xCD,48,2,48,2}, +{0xCE,50,2,50,2}, +{0xCF,52,2,52,2}, +{0xD1,54,2,54,2}, +{0xD2,56,2,56,2}, +{0xD3,58,2,58,2}, +{0xD4,60,2,60,2}, +{0xD5,62,2,62,2}, +{0xD6,64,2,64,2}, +{0xD9,66,2,66,2}, +{0xDA,68,2,68,2}, +{0xDB,70,2,70,2}, +{0xDC,72,2,72,2}, +{0xDD,74,2,74,2}, +{0xE0,76,2,76,2}, +{0xE1,78,2,78,2}, +{0xE2,80,2,80,2}, +{0xE3,82,2,82,2}, +{0xE4,84,2,84,2}, +{0xE5,86,2,86,2}, +{0xE7,88,2,88,2}, +{0xE8,90,2,90,2}, +{0xE9,92,2,92,2}, +{0xEA,94,2,94,2}, +{0xEB,96,2,96,2}, +{0xEC,98,2,98,2}, +{0xED,100,2,100,2}, +{0xEE,102,2,102,2}, +{0xEF,104,2,104,2}, +{0xF1,106,2,106,2}, +{0xF2,108,2,108,2}, +{0xF3,110,2,110,2}, +{0xF4,112,2,112,2}, +{0xF5,114,2,114,2}, +{0xF6,116,2,116,2}, +{0xF9,118,2,118,2}, +{0xFA,120,2,120,2}, +{0xFB,122,2,122,2}, +{0xFC,124,2,124,2}, +{0xFD,126,2,126,2}, +{0xFF,128,2,128,2}, +{0x100,130,2,130,2}, +{0x101,132,2,132,2}, +{0x102,134,2,134,2}, +{0x103,136,2,136,2}, +{0x104,138,2,138,2}, +{0x105,140,2,140,2}, +{0x106,142,2,142,2}, +{0x107,144,2,144,2}, +{0x108,146,2,146,2}, +{0x109,148,2,148,2}, +{0x10A,150,2,150,2}, +{0x10B,152,2,152,2}, +{0x10C,154,2,154,2}, +{0x10D,156,2,156,2}, +{0x10E,158,2,158,2}, +{0x10F,160,2,160,2}, +{0x112,162,2,162,2}, +{0x113,164,2,164,2}, +{0x114,166,2,166,2}, +{0x115,168,2,168,2}, +{0x116,170,2,170,2}, +{0x117,172,2,172,2}, +{0x118,174,2,174,2}, +{0x119,176,2,176,2}, +{0x11A,178,2,178,2}, +{0x11B,180,2,180,2}, +{0x11C,182,2,182,2}, +{0x11D,184,2,184,2}, +{0x11E,186,2,186,2}, +{0x11F,188,2,188,2}, +{0x120,190,2,190,2}, +{0x121,192,2,192,2}, +{0x122,194,2,194,2}, +{0x123,196,2,196,2}, +{0x124,198,2,198,2}, +{0x125,200,2,200,2}, +{0x128,202,2,202,2}, +{0x129,204,2,204,2}, +{0x12A,206,2,206,2}, +{0x12B,208,2,208,2}, +{0x12C,210,2,210,2}, +{0x12D,212,2,212,2}, +{0x12E,214,2,214,2}, +{0x12F,216,2,216,2}, +{0x130,218,2,218,2}, +{0x132,0,0,220,2}, +{0x133,0,0,222,2}, +{0x134,224,2,224,2}, +{0x135,226,2,226,2}, +{0x136,228,2,228,2}, +{0x137,230,2,230,2}, +{0x139,232,2,232,2}, +{0x13A,234,2,234,2}, +{0x13B,236,2,236,2}, +{0x13C,238,2,238,2}, +{0x13D,240,2,240,2}, +{0x13E,242,2,242,2}, +{0x13F,0,0,244,2}, +{0x140,0,0,246,2}, +{0x143,248,2,248,2}, +{0x144,250,2,250,2}, +{0x145,252,2,252,2}, +{0x146,254,2,254,2}, +{0x147,256,2,256,2}, +{0x148,258,2,258,2}, +{0x149,0,0,260,2}, +{0x14C,262,2,262,2}, +{0x14D,264,2,264,2}, +{0x14E,266,2,266,2}, +{0x14F,268,2,268,2}, +{0x150,270,2,270,2}, +{0x151,272,2,272,2}, +{0x154,274,2,274,2}, +{0x155,276,2,276,2}, +{0x156,278,2,278,2}, +{0x157,280,2,280,2}, +{0x158,282,2,282,2}, +{0x159,284,2,284,2}, +{0x15A,286,2,286,2}, +{0x15B,288,2,288,2}, +{0x15C,290,2,290,2}, +{0x15D,292,2,292,2}, +{0x15E,294,2,294,2}, +{0x15F,296,2,296,2}, +{0x160,298,2,298,2}, +{0x161,300,2,300,2}, +{0x162,302,2,302,2}, +{0x163,304,2,304,2}, +{0x164,306,2,306,2}, +{0x165,308,2,308,2}, +{0x168,310,2,310,2}, +{0x169,312,2,312,2}, +{0x16A,314,2,314,2}, +{0x16B,316,2,316,2}, +{0x16C,318,2,318,2}, +{0x16D,320,2,320,2}, +{0x16E,322,2,322,2}, +{0x16F,324,2,324,2}, +{0x170,326,2,326,2}, +{0x171,328,2,328,2}, +{0x172,330,2,330,2}, +{0x173,332,2,332,2}, +{0x174,334,2,334,2}, +{0x175,336,2,336,2}, +{0x176,338,2,338,2}, +{0x177,340,2,340,2}, +{0x178,342,2,342,2}, +{0x179,344,2,344,2}, +{0x17A,346,2,346,2}, +{0x17B,348,2,348,2}, +{0x17C,350,2,350,2}, +{0x17D,352,2,352,2}, +{0x17E,354,2,354,2}, +{0x17F,0,0,356,1}, +{0x1A0,357,2,357,2}, +{0x1A1,359,2,359,2}, +{0x1AF,361,2,361,2}, +{0x1B0,363,2,363,2}, +{0x1C4,0,0,365,3}, +{0x1C5,0,0,368,3}, +{0x1C6,0,0,371,3}, +{0x1C7,0,0,374,2}, +{0x1C8,0,0,376,2}, +{0x1C9,0,0,378,2}, +{0x1CA,0,0,380,2}, +{0x1CB,0,0,382,2}, +{0x1CC,0,0,384,2}, +{0x1CD,386,2,386,2}, +{0x1CE,388,2,388,2}, +{0x1CF,390,2,390,2}, +{0x1D0,392,2,392,2}, +{0x1D1,394,2,394,2}, +{0x1D2,396,2,396,2}, +{0x1D3,398,2,398,2}, +{0x1D4,400,2,400,2}, +{0x1D5,402,3,402,3}, +{0x1D6,405,3,405,3}, +{0x1D7,408,3,408,3}, +{0x1D8,411,3,411,3}, +{0x1D9,414,3,414,3}, +{0x1DA,417,3,417,3}, +{0x1DB,420,3,420,3}, +{0x1DC,423,3,423,3}, +{0x1DE,426,3,426,3}, +{0x1DF,429,3,429,3}, +{0x1E0,432,3,432,3}, +{0x1E1,435,3,435,3}, +{0x1E2,438,2,438,2}, +{0x1E3,440,2,440,2}, +{0x1E6,442,2,442,2}, +{0x1E7,444,2,444,2}, +{0x1E8,446,2,446,2}, +{0x1E9,448,2,448,2}, +{0x1EA,450,2,450,2}, +{0x1EB,452,2,452,2}, +{0x1EC,454,3,454,3}, +{0x1ED,457,3,457,3}, +{0x1EE,460,2,460,2}, +{0x1EF,462,2,462,2}, +{0x1F0,464,2,464,2}, +{0x1F1,0,0,466,2}, +{0x1F2,0,0,468,2}, +{0x1F3,0,0,470,2}, +{0x1F4,472,2,472,2}, +{0x1F5,474,2,474,2}, +{0x1F8,476,2,476,2}, +{0x1F9,478,2,478,2}, +{0x1FA,480,3,480,3}, +{0x1FB,483,3,483,3}, +{0x1FC,486,2,486,2}, +{0x1FD,488,2,488,2}, +{0x1FE,490,2,490,2}, +{0x1FF,492,2,492,2}, +{0x200,494,2,494,2}, +{0x201,496,2,496,2}, +{0x202,498,2,498,2}, +{0x203,500,2,500,2}, +{0x204,502,2,502,2}, +{0x205,504,2,504,2}, +{0x206,506,2,506,2}, +{0x207,508,2,508,2}, +{0x208,510,2,510,2}, +{0x209,512,2,512,2}, +{0x20A,514,2,514,2}, +{0x20B,516,2,516,2}, +{0x20C,518,2,518,2}, +{0x20D,520,2,520,2}, +{0x20E,522,2,522,2}, +{0x20F,524,2,524,2}, +{0x210,526,2,526,2}, +{0x211,528,2,528,2}, +{0x212,530,2,530,2}, +{0x213,532,2,532,2}, +{0x214,534,2,534,2}, +{0x215,536,2,536,2}, +{0x216,538,2,538,2}, +{0x217,540,2,540,2}, +{0x218,542,2,542,2}, +{0x219,544,2,544,2}, +{0x21A,546,2,546,2}, +{0x21B,548,2,548,2}, +{0x21E,550,2,550,2}, +{0x21F,552,2,552,2}, +{0x226,554,2,554,2}, +{0x227,556,2,556,2}, +{0x228,558,2,558,2}, +{0x229,560,2,560,2}, +{0x22A,562,3,562,3}, +{0x22B,565,3,565,3}, +{0x22C,568,3,568,3}, +{0x22D,571,3,571,3}, +{0x22E,574,2,574,2}, +{0x22F,576,2,576,2}, +{0x230,578,3,578,3}, +{0x231,581,3,581,3}, +{0x232,584,2,584,2}, +{0x233,586,2,586,2}, +{0x2B0,0,0,588,1}, +{0x2B1,0,0,589,1}, +{0x2B2,0,0,590,1}, +{0x2B3,0,0,591,1}, +{0x2B4,0,0,592,1}, +{0x2B5,0,0,593,1}, +{0x2B6,0,0,594,1}, +{0x2B7,0,0,595,1}, +{0x2B8,0,0,596,1}, +{0x2D8,0,0,597,2}, +{0x2D9,0,0,599,2}, +{0x2DA,0,0,601,2}, +{0x2DB,0,0,603,2}, +{0x2DC,0,0,605,2}, +{0x2DD,0,0,607,2}, +{0x2E0,0,0,609,1}, +{0x2E1,0,0,610,1}, +{0x2E2,0,0,611,1}, +{0x2E3,0,0,612,1}, +{0x2E4,0,0,613,1}, +{0x340,614,1,614,1}, +{0x341,615,1,615,1}, +{0x343,616,1,616,1}, +{0x344,617,2,617,2}, +{0x374,619,1,619,1}, +{0x37A,0,0,620,2}, +{0x37E,622,1,622,1}, +{0x384,0,0,623,2}, +{0x385,625,2,627,3}, +{0x386,630,2,630,2}, +{0x387,632,1,632,1}, +{0x388,633,2,633,2}, +{0x389,635,2,635,2}, +{0x38A,637,2,637,2}, +{0x38C,639,2,639,2}, +{0x38E,641,2,641,2}, +{0x38F,643,2,643,2}, +{0x390,645,3,645,3}, +{0x3AA,648,2,648,2}, +{0x3AB,650,2,650,2}, +{0x3AC,652,2,652,2}, +{0x3AD,654,2,654,2}, +{0x3AE,656,2,656,2}, +{0x3AF,658,2,658,2}, +{0x3B0,660,3,660,3}, +{0x3CA,663,2,663,2}, +{0x3CB,665,2,665,2}, +{0x3CC,667,2,667,2}, +{0x3CD,669,2,669,2}, +{0x3CE,671,2,671,2}, +{0x3D0,0,0,673,1}, +{0x3D1,0,0,674,1}, +{0x3D2,0,0,675,1}, +{0x3D3,676,2,678,2}, +{0x3D4,680,2,682,2}, +{0x3D5,0,0,684,1}, +{0x3D6,0,0,685,1}, +{0x3F0,0,0,686,1}, +{0x3F1,0,0,687,1}, +{0x3F2,0,0,688,1}, +{0x3F4,0,0,689,1}, +{0x3F5,0,0,690,1}, +{0x3F9,0,0,691,1}, +{0x400,692,2,692,2}, +{0x401,694,2,694,2}, +{0x403,696,2,696,2}, +{0x407,698,2,698,2}, +{0x40C,700,2,700,2}, +{0x40D,702,2,702,2}, +{0x40E,704,2,704,2}, +{0x419,706,2,706,2}, +{0x439,708,2,708,2}, +{0x450,710,2,710,2}, +{0x451,712,2,712,2}, +{0x453,714,2,714,2}, +{0x457,716,2,716,2}, +{0x45C,718,2,718,2}, +{0x45D,720,2,720,2}, +{0x45E,722,2,722,2}, +{0x476,724,2,724,2}, +{0x477,726,2,726,2}, +{0x4C1,728,2,728,2}, +{0x4C2,730,2,730,2}, +{0x4D0,732,2,732,2}, +{0x4D1,734,2,734,2}, +{0x4D2,736,2,736,2}, +{0x4D3,738,2,738,2}, +{0x4D6,740,2,740,2}, +{0x4D7,742,2,742,2}, +{0x4DA,744,2,744,2}, +{0x4DB,746,2,746,2}, +{0x4DC,748,2,748,2}, +{0x4DD,750,2,750,2}, +{0x4DE,752,2,752,2}, +{0x4DF,754,2,754,2}, +{0x4E2,756,2,756,2}, +{0x4E3,758,2,758,2}, +{0x4E4,760,2,760,2}, +{0x4E5,762,2,762,2}, +{0x4E6,764,2,764,2}, +{0x4E7,766,2,766,2}, +{0x4EA,768,2,768,2}, +{0x4EB,770,2,770,2}, +{0x4EC,772,2,772,2}, +{0x4ED,774,2,774,2}, +{0x4EE,776,2,776,2}, +{0x4EF,778,2,778,2}, +{0x4F0,780,2,780,2}, +{0x4F1,782,2,782,2}, +{0x4F2,784,2,784,2}, +{0x4F3,786,2,786,2}, +{0x4F4,788,2,788,2}, +{0x4F5,790,2,790,2}, +{0x4F8,792,2,792,2}, +{0x4F9,794,2,794,2}, +{0x587,0,0,796,2}, +{0x622,798,2,798,2}, +{0x623,800,2,800,2}, +{0x624,802,2,802,2}, +{0x625,804,2,804,2}, +{0x626,806,2,806,2}, +{0x675,0,0,808,2}, +{0x676,0,0,810,2}, +{0x677,0,0,812,2}, +{0x678,0,0,814,2}, +{0x6C0,816,2,816,2}, +{0x6C2,818,2,818,2}, +{0x6D3,820,2,820,2}, +{0x929,822,2,822,2}, +{0x931,824,2,824,2}, +{0x934,826,2,826,2}, +{0x958,828,2,828,2}, +{0x959,830,2,830,2}, +{0x95A,832,2,832,2}, +{0x95B,834,2,834,2}, +{0x95C,836,2,836,2}, +{0x95D,838,2,838,2}, +{0x95E,840,2,840,2}, +{0x95F,842,2,842,2}, +{0x9CB,844,2,844,2}, +{0x9CC,846,2,846,2}, +{0x9DC,848,2,848,2}, +{0x9DD,850,2,850,2}, +{0x9DF,852,2,852,2}, +{0xA33,854,2,854,2}, +{0xA36,856,2,856,2}, +{0xA59,858,2,858,2}, +{0xA5A,860,2,860,2}, +{0xA5B,862,2,862,2}, +{0xA5E,864,2,864,2}, +{0xB48,866,2,866,2}, +{0xB4B,868,2,868,2}, +{0xB4C,870,2,870,2}, +{0xB5C,872,2,872,2}, +{0xB5D,874,2,874,2}, +{0xB94,876,2,876,2}, +{0xBCA,878,2,878,2}, +{0xBCB,880,2,880,2}, +{0xBCC,882,2,882,2}, +{0xC48,884,2,884,2}, +{0xCC0,886,2,886,2}, +{0xCC7,888,2,888,2}, +{0xCC8,890,2,890,2}, +{0xCCA,892,2,892,2}, +{0xCCB,894,3,894,3}, +{0xD4A,897,2,897,2}, +{0xD4B,899,2,899,2}, +{0xD4C,901,2,901,2}, +{0xDDA,903,2,903,2}, +{0xDDC,905,2,905,2}, +{0xDDD,907,3,907,3}, +{0xDDE,910,2,910,2}, +{0xE33,0,0,912,2}, +{0xEB3,0,0,914,2}, +{0xEDC,0,0,916,2}, +{0xEDD,0,0,918,2}, +{0xF0C,0,0,920,1}, +{0xF43,921,2,921,2}, +{0xF4D,923,2,923,2}, +{0xF52,925,2,925,2}, +{0xF57,927,2,927,2}, +{0xF5C,929,2,929,2}, +{0xF69,931,2,931,2}, +{0xF73,933,2,933,2}, +{0xF75,935,2,935,2}, +{0xF76,937,2,937,2}, +{0xF77,0,0,939,3}, +{0xF78,942,2,942,2}, +{0xF79,0,0,944,3}, +{0xF81,947,2,947,2}, +{0xF93,949,2,949,2}, +{0xF9D,951,2,951,2}, +{0xFA2,953,2,953,2}, +{0xFA7,955,2,955,2}, +{0xFAC,957,2,957,2}, +{0xFB9,959,2,959,2}, +{0x1026,961,2,961,2}, +{0x10FC,0,0,963,1}, +{0x1B06,964,2,964,2}, +{0x1B08,966,2,966,2}, +{0x1B0A,968,2,968,2}, +{0x1B0C,970,2,970,2}, +{0x1B0E,972,2,972,2}, +{0x1B12,974,2,974,2}, +{0x1B3B,976,2,976,2}, +{0x1B3D,978,2,978,2}, +{0x1B40,980,2,980,2}, +{0x1B41,982,2,982,2}, +{0x1B43,984,2,984,2}, +{0x1D2C,0,0,986,1}, +{0x1D2D,0,0,987,1}, +{0x1D2E,0,0,988,1}, +{0x1D30,0,0,989,1}, +{0x1D31,0,0,990,1}, +{0x1D32,0,0,991,1}, +{0x1D33,0,0,992,1}, +{0x1D34,0,0,993,1}, +{0x1D35,0,0,994,1}, +{0x1D36,0,0,995,1}, +{0x1D37,0,0,996,1}, +{0x1D38,0,0,997,1}, +{0x1D39,0,0,998,1}, +{0x1D3A,0,0,999,1}, +{0x1D3C,0,0,1000,1}, +{0x1D3D,0,0,1001,1}, +{0x1D3E,0,0,1002,1}, +{0x1D3F,0,0,1003,1}, +{0x1D40,0,0,1004,1}, +{0x1D41,0,0,1005,1}, +{0x1D42,0,0,1006,1}, +{0x1D43,0,0,1007,1}, +{0x1D44,0,0,1008,1}, +{0x1D45,0,0,1009,1}, +{0x1D46,0,0,1010,1}, +{0x1D47,0,0,1011,1}, +{0x1D48,0,0,1012,1}, +{0x1D49,0,0,1013,1}, +{0x1D4A,0,0,1014,1}, +{0x1D4B,0,0,1015,1}, +{0x1D4C,0,0,1016,1}, +{0x1D4D,0,0,1017,1}, +{0x1D4F,0,0,1018,1}, +{0x1D50,0,0,1019,1}, +{0x1D51,0,0,1020,1}, +{0x1D52,0,0,1021,1}, +{0x1D53,0,0,1022,1}, +{0x1D54,0,0,1023,1}, +{0x1D55,0,0,1024,1}, +{0x1D56,0,0,1025,1}, +{0x1D57,0,0,1026,1}, +{0x1D58,0,0,1027,1}, +{0x1D59,0,0,1028,1}, +{0x1D5A,0,0,1029,1}, +{0x1D5B,0,0,1030,1}, +{0x1D5C,0,0,1031,1}, +{0x1D5D,0,0,1032,1}, +{0x1D5E,0,0,1033,1}, +{0x1D5F,0,0,1034,1}, +{0x1D60,0,0,1035,1}, +{0x1D61,0,0,1036,1}, +{0x1D62,0,0,1037,1}, +{0x1D63,0,0,1038,1}, +{0x1D64,0,0,1039,1}, +{0x1D65,0,0,1040,1}, +{0x1D66,0,0,1041,1}, +{0x1D67,0,0,1042,1}, +{0x1D68,0,0,1043,1}, +{0x1D69,0,0,1044,1}, +{0x1D6A,0,0,1045,1}, +{0x1D78,0,0,1046,1}, +{0x1D9B,0,0,1047,1}, +{0x1D9C,0,0,1048,1}, +{0x1D9D,0,0,1049,1}, +{0x1D9E,0,0,1050,1}, +{0x1D9F,0,0,1051,1}, +{0x1DA0,0,0,1052,1}, +{0x1DA1,0,0,1053,1}, +{0x1DA2,0,0,1054,1}, +{0x1DA3,0,0,1055,1}, +{0x1DA4,0,0,1056,1}, +{0x1DA5,0,0,1057,1}, +{0x1DA6,0,0,1058,1}, +{0x1DA7,0,0,1059,1}, +{0x1DA8,0,0,1060,1}, +{0x1DA9,0,0,1061,1}, +{0x1DAA,0,0,1062,1}, +{0x1DAB,0,0,1063,1}, +{0x1DAC,0,0,1064,1}, +{0x1DAD,0,0,1065,1}, +{0x1DAE,0,0,1066,1}, +{0x1DAF,0,0,1067,1}, +{0x1DB0,0,0,1068,1}, +{0x1DB1,0,0,1069,1}, +{0x1DB2,0,0,1070,1}, +{0x1DB3,0,0,1071,1}, +{0x1DB4,0,0,1072,1}, +{0x1DB5,0,0,1073,1}, +{0x1DB6,0,0,1074,1}, +{0x1DB7,0,0,1075,1}, +{0x1DB8,0,0,1076,1}, +{0x1DB9,0,0,1077,1}, +{0x1DBA,0,0,1078,1}, +{0x1DBB,0,0,1079,1}, +{0x1DBC,0,0,1080,1}, +{0x1DBD,0,0,1081,1}, +{0x1DBE,0,0,1082,1}, +{0x1DBF,0,0,1083,1}, +{0x1E00,1084,2,1084,2}, +{0x1E01,1086,2,1086,2}, +{0x1E02,1088,2,1088,2}, +{0x1E03,1090,2,1090,2}, +{0x1E04,1092,2,1092,2}, +{0x1E05,1094,2,1094,2}, +{0x1E06,1096,2,1096,2}, +{0x1E07,1098,2,1098,2}, +{0x1E08,1100,3,1100,3}, +{0x1E09,1103,3,1103,3}, +{0x1E0A,1106,2,1106,2}, +{0x1E0B,1108,2,1108,2}, +{0x1E0C,1110,2,1110,2}, +{0x1E0D,1112,2,1112,2}, +{0x1E0E,1114,2,1114,2}, +{0x1E0F,1116,2,1116,2}, +{0x1E10,1118,2,1118,2}, +{0x1E11,1120,2,1120,2}, +{0x1E12,1122,2,1122,2}, +{0x1E13,1124,2,1124,2}, +{0x1E14,1126,3,1126,3}, +{0x1E15,1129,3,1129,3}, +{0x1E16,1132,3,1132,3}, +{0x1E17,1135,3,1135,3}, +{0x1E18,1138,2,1138,2}, +{0x1E19,1140,2,1140,2}, +{0x1E1A,1142,2,1142,2}, +{0x1E1B,1144,2,1144,2}, +{0x1E1C,1146,3,1146,3}, +{0x1E1D,1149,3,1149,3}, +{0x1E1E,1152,2,1152,2}, +{0x1E1F,1154,2,1154,2}, +{0x1E20,1156,2,1156,2}, +{0x1E21,1158,2,1158,2}, +{0x1E22,1160,2,1160,2}, +{0x1E23,1162,2,1162,2}, +{0x1E24,1164,2,1164,2}, +{0x1E25,1166,2,1166,2}, +{0x1E26,1168,2,1168,2}, +{0x1E27,1170,2,1170,2}, +{0x1E28,1172,2,1172,2}, +{0x1E29,1174,2,1174,2}, +{0x1E2A,1176,2,1176,2}, +{0x1E2B,1178,2,1178,2}, +{0x1E2C,1180,2,1180,2}, +{0x1E2D,1182,2,1182,2}, +{0x1E2E,1184,3,1184,3}, +{0x1E2F,1187,3,1187,3}, +{0x1E30,1190,2,1190,2}, +{0x1E31,1192,2,1192,2}, +{0x1E32,1194,2,1194,2}, +{0x1E33,1196,2,1196,2}, +{0x1E34,1198,2,1198,2}, +{0x1E35,1200,2,1200,2}, +{0x1E36,1202,2,1202,2}, +{0x1E37,1204,2,1204,2}, +{0x1E38,1206,3,1206,3}, +{0x1E39,1209,3,1209,3}, +{0x1E3A,1212,2,1212,2}, +{0x1E3B,1214,2,1214,2}, +{0x1E3C,1216,2,1216,2}, +{0x1E3D,1218,2,1218,2}, +{0x1E3E,1220,2,1220,2}, +{0x1E3F,1222,2,1222,2}, +{0x1E40,1224,2,1224,2}, +{0x1E41,1226,2,1226,2}, +{0x1E42,1228,2,1228,2}, +{0x1E43,1230,2,1230,2}, +{0x1E44,1232,2,1232,2}, +{0x1E45,1234,2,1234,2}, +{0x1E46,1236,2,1236,2}, +{0x1E47,1238,2,1238,2}, +{0x1E48,1240,2,1240,2}, +{0x1E49,1242,2,1242,2}, +{0x1E4A,1244,2,1244,2}, +{0x1E4B,1246,2,1246,2}, +{0x1E4C,1248,3,1248,3}, +{0x1E4D,1251,3,1251,3}, +{0x1E4E,1254,3,1254,3}, +{0x1E4F,1257,3,1257,3}, +{0x1E50,1260,3,1260,3}, +{0x1E51,1263,3,1263,3}, +{0x1E52,1266,3,1266,3}, +{0x1E53,1269,3,1269,3}, +{0x1E54,1272,2,1272,2}, +{0x1E55,1274,2,1274,2}, +{0x1E56,1276,2,1276,2}, +{0x1E57,1278,2,1278,2}, +{0x1E58,1280,2,1280,2}, +{0x1E59,1282,2,1282,2}, +{0x1E5A,1284,2,1284,2}, +{0x1E5B,1286,2,1286,2}, +{0x1E5C,1288,3,1288,3}, +{0x1E5D,1291,3,1291,3}, +{0x1E5E,1294,2,1294,2}, +{0x1E5F,1296,2,1296,2}, +{0x1E60,1298,2,1298,2}, +{0x1E61,1300,2,1300,2}, +{0x1E62,1302,2,1302,2}, +{0x1E63,1304,2,1304,2}, +{0x1E64,1306,3,1306,3}, +{0x1E65,1309,3,1309,3}, +{0x1E66,1312,3,1312,3}, +{0x1E67,1315,3,1315,3}, +{0x1E68,1318,3,1318,3}, +{0x1E69,1321,3,1321,3}, +{0x1E6A,1324,2,1324,2}, +{0x1E6B,1326,2,1326,2}, +{0x1E6C,1328,2,1328,2}, +{0x1E6D,1330,2,1330,2}, +{0x1E6E,1332,2,1332,2}, +{0x1E6F,1334,2,1334,2}, +{0x1E70,1336,2,1336,2}, +{0x1E71,1338,2,1338,2}, +{0x1E72,1340,2,1340,2}, +{0x1E73,1342,2,1342,2}, +{0x1E74,1344,2,1344,2}, +{0x1E75,1346,2,1346,2}, +{0x1E76,1348,2,1348,2}, +{0x1E77,1350,2,1350,2}, +{0x1E78,1352,3,1352,3}, +{0x1E79,1355,3,1355,3}, +{0x1E7A,1358,3,1358,3}, +{0x1E7B,1361,3,1361,3}, +{0x1E7C,1364,2,1364,2}, +{0x1E7D,1366,2,1366,2}, +{0x1E7E,1368,2,1368,2}, +{0x1E7F,1370,2,1370,2}, +{0x1E80,1372,2,1372,2}, +{0x1E81,1374,2,1374,2}, +{0x1E82,1376,2,1376,2}, +{0x1E83,1378,2,1378,2}, +{0x1E84,1380,2,1380,2}, +{0x1E85,1382,2,1382,2}, +{0x1E86,1384,2,1384,2}, +{0x1E87,1386,2,1386,2}, +{0x1E88,1388,2,1388,2}, +{0x1E89,1390,2,1390,2}, +{0x1E8A,1392,2,1392,2}, +{0x1E8B,1394,2,1394,2}, +{0x1E8C,1396,2,1396,2}, +{0x1E8D,1398,2,1398,2}, +{0x1E8E,1400,2,1400,2}, +{0x1E8F,1402,2,1402,2}, +{0x1E90,1404,2,1404,2}, +{0x1E91,1406,2,1406,2}, +{0x1E92,1408,2,1408,2}, +{0x1E93,1410,2,1410,2}, +{0x1E94,1412,2,1412,2}, +{0x1E95,1414,2,1414,2}, +{0x1E96,1416,2,1416,2}, +{0x1E97,1418,2,1418,2}, +{0x1E98,1420,2,1420,2}, +{0x1E99,1422,2,1422,2}, +{0x1E9A,0,0,1424,2}, +{0x1E9B,1426,2,1428,2}, +{0x1EA0,1430,2,1430,2}, +{0x1EA1,1432,2,1432,2}, +{0x1EA2,1434,2,1434,2}, +{0x1EA3,1436,2,1436,2}, +{0x1EA4,1438,3,1438,3}, +{0x1EA5,1441,3,1441,3}, +{0x1EA6,1444,3,1444,3}, +{0x1EA7,1447,3,1447,3}, +{0x1EA8,1450,3,1450,3}, +{0x1EA9,1453,3,1453,3}, +{0x1EAA,1456,3,1456,3}, +{0x1EAB,1459,3,1459,3}, +{0x1EAC,1462,3,1462,3}, +{0x1EAD,1465,3,1465,3}, +{0x1EAE,1468,3,1468,3}, +{0x1EAF,1471,3,1471,3}, +{0x1EB0,1474,3,1474,3}, +{0x1EB1,1477,3,1477,3}, +{0x1EB2,1480,3,1480,3}, +{0x1EB3,1483,3,1483,3}, +{0x1EB4,1486,3,1486,3}, +{0x1EB5,1489,3,1489,3}, +{0x1EB6,1492,3,1492,3}, +{0x1EB7,1495,3,1495,3}, +{0x1EB8,1498,2,1498,2}, +{0x1EB9,1500,2,1500,2}, +{0x1EBA,1502,2,1502,2}, +{0x1EBB,1504,2,1504,2}, +{0x1EBC,1506,2,1506,2}, +{0x1EBD,1508,2,1508,2}, +{0x1EBE,1510,3,1510,3}, +{0x1EBF,1513,3,1513,3}, +{0x1EC0,1516,3,1516,3}, +{0x1EC1,1519,3,1519,3}, +{0x1EC2,1522,3,1522,3}, +{0x1EC3,1525,3,1525,3}, +{0x1EC4,1528,3,1528,3}, +{0x1EC5,1531,3,1531,3}, +{0x1EC6,1534,3,1534,3}, +{0x1EC7,1537,3,1537,3}, +{0x1EC8,1540,2,1540,2}, +{0x1EC9,1542,2,1542,2}, +{0x1ECA,1544,2,1544,2}, +{0x1ECB,1546,2,1546,2}, +{0x1ECC,1548,2,1548,2}, +{0x1ECD,1550,2,1550,2}, +{0x1ECE,1552,2,1552,2}, +{0x1ECF,1554,2,1554,2}, +{0x1ED0,1556,3,1556,3}, +{0x1ED1,1559,3,1559,3}, +{0x1ED2,1562,3,1562,3}, +{0x1ED3,1565,3,1565,3}, +{0x1ED4,1568,3,1568,3}, +{0x1ED5,1571,3,1571,3}, +{0x1ED6,1574,3,1574,3}, +{0x1ED7,1577,3,1577,3}, +{0x1ED8,1580,3,1580,3}, +{0x1ED9,1583,3,1583,3}, +{0x1EDA,1586,3,1586,3}, +{0x1EDB,1589,3,1589,3}, +{0x1EDC,1592,3,1592,3}, +{0x1EDD,1595,3,1595,3}, +{0x1EDE,1598,3,1598,3}, +{0x1EDF,1601,3,1601,3}, +{0x1EE0,1604,3,1604,3}, +{0x1EE1,1607,3,1607,3}, +{0x1EE2,1610,3,1610,3}, +{0x1EE3,1613,3,1613,3}, +{0x1EE4,1616,2,1616,2}, +{0x1EE5,1618,2,1618,2}, +{0x1EE6,1620,2,1620,2}, +{0x1EE7,1622,2,1622,2}, +{0x1EE8,1624,3,1624,3}, +{0x1EE9,1627,3,1627,3}, +{0x1EEA,1630,3,1630,3}, +{0x1EEB,1633,3,1633,3}, +{0x1EEC,1636,3,1636,3}, +{0x1EED,1639,3,1639,3}, +{0x1EEE,1642,3,1642,3}, +{0x1EEF,1645,3,1645,3}, +{0x1EF0,1648,3,1648,3}, +{0x1EF1,1651,3,1651,3}, +{0x1EF2,1654,2,1654,2}, +{0x1EF3,1656,2,1656,2}, +{0x1EF4,1658,2,1658,2}, +{0x1EF5,1660,2,1660,2}, +{0x1EF6,1662,2,1662,2}, +{0x1EF7,1664,2,1664,2}, +{0x1EF8,1666,2,1666,2}, +{0x1EF9,1668,2,1668,2}, +{0x1F00,1670,2,1670,2}, +{0x1F01,1672,2,1672,2}, +{0x1F02,1674,3,1674,3}, +{0x1F03,1677,3,1677,3}, +{0x1F04,1680,3,1680,3}, +{0x1F05,1683,3,1683,3}, +{0x1F06,1686,3,1686,3}, +{0x1F07,1689,3,1689,3}, +{0x1F08,1692,2,1692,2}, +{0x1F09,1694,2,1694,2}, +{0x1F0A,1696,3,1696,3}, +{0x1F0B,1699,3,1699,3}, +{0x1F0C,1702,3,1702,3}, +{0x1F0D,1705,3,1705,3}, +{0x1F0E,1708,3,1708,3}, +{0x1F0F,1711,3,1711,3}, +{0x1F10,1714,2,1714,2}, +{0x1F11,1716,2,1716,2}, +{0x1F12,1718,3,1718,3}, +{0x1F13,1721,3,1721,3}, +{0x1F14,1724,3,1724,3}, +{0x1F15,1727,3,1727,3}, +{0x1F18,1730,2,1730,2}, +{0x1F19,1732,2,1732,2}, +{0x1F1A,1734,3,1734,3}, +{0x1F1B,1737,3,1737,3}, +{0x1F1C,1740,3,1740,3}, +{0x1F1D,1743,3,1743,3}, +{0x1F20,1746,2,1746,2}, +{0x1F21,1748,2,1748,2}, +{0x1F22,1750,3,1750,3}, +{0x1F23,1753,3,1753,3}, +{0x1F24,1756,3,1756,3}, +{0x1F25,1759,3,1759,3}, +{0x1F26,1762,3,1762,3}, +{0x1F27,1765,3,1765,3}, +{0x1F28,1768,2,1768,2}, +{0x1F29,1770,2,1770,2}, +{0x1F2A,1772,3,1772,3}, +{0x1F2B,1775,3,1775,3}, +{0x1F2C,1778,3,1778,3}, +{0x1F2D,1781,3,1781,3}, +{0x1F2E,1784,3,1784,3}, +{0x1F2F,1787,3,1787,3}, +{0x1F30,1790,2,1790,2}, +{0x1F31,1792,2,1792,2}, +{0x1F32,1794,3,1794,3}, +{0x1F33,1797,3,1797,3}, +{0x1F34,1800,3,1800,3}, +{0x1F35,1803,3,1803,3}, +{0x1F36,1806,3,1806,3}, +{0x1F37,1809,3,1809,3}, +{0x1F38,1812,2,1812,2}, +{0x1F39,1814,2,1814,2}, +{0x1F3A,1816,3,1816,3}, +{0x1F3B,1819,3,1819,3}, +{0x1F3C,1822,3,1822,3}, +{0x1F3D,1825,3,1825,3}, +{0x1F3E,1828,3,1828,3}, +{0x1F3F,1831,3,1831,3}, +{0x1F40,1834,2,1834,2}, +{0x1F41,1836,2,1836,2}, +{0x1F42,1838,3,1838,3}, +{0x1F43,1841,3,1841,3}, +{0x1F44,1844,3,1844,3}, +{0x1F45,1847,3,1847,3}, +{0x1F48,1850,2,1850,2}, +{0x1F49,1852,2,1852,2}, +{0x1F4A,1854,3,1854,3}, +{0x1F4B,1857,3,1857,3}, +{0x1F4C,1860,3,1860,3}, +{0x1F4D,1863,3,1863,3}, +{0x1F50,1866,2,1866,2}, +{0x1F51,1868,2,1868,2}, +{0x1F52,1870,3,1870,3}, +{0x1F53,1873,3,1873,3}, +{0x1F54,1876,3,1876,3}, +{0x1F55,1879,3,1879,3}, +{0x1F56,1882,3,1882,3}, +{0x1F57,1885,3,1885,3}, +{0x1F59,1888,2,1888,2}, +{0x1F5B,1890,3,1890,3}, +{0x1F5D,1893,3,1893,3}, +{0x1F5F,1896,3,1896,3}, +{0x1F60,1899,2,1899,2}, +{0x1F61,1901,2,1901,2}, +{0x1F62,1903,3,1903,3}, +{0x1F63,1906,3,1906,3}, +{0x1F64,1909,3,1909,3}, +{0x1F65,1912,3,1912,3}, +{0x1F66,1915,3,1915,3}, +{0x1F67,1918,3,1918,3}, +{0x1F68,1921,2,1921,2}, +{0x1F69,1923,2,1923,2}, +{0x1F6A,1925,3,1925,3}, +{0x1F6B,1928,3,1928,3}, +{0x1F6C,1931,3,1931,3}, +{0x1F6D,1934,3,1934,3}, +{0x1F6E,1937,3,1937,3}, +{0x1F6F,1940,3,1940,3}, +{0x1F70,1943,2,1943,2}, +{0x1F71,1945,2,1945,2}, +{0x1F72,1947,2,1947,2}, +{0x1F73,1949,2,1949,2}, +{0x1F74,1951,2,1951,2}, +{0x1F75,1953,2,1953,2}, +{0x1F76,1955,2,1955,2}, +{0x1F77,1957,2,1957,2}, +{0x1F78,1959,2,1959,2}, +{0x1F79,1961,2,1961,2}, +{0x1F7A,1963,2,1963,2}, +{0x1F7B,1965,2,1965,2}, +{0x1F7C,1967,2,1967,2}, +{0x1F7D,1969,2,1969,2}, +{0x1F80,1971,3,1971,3}, +{0x1F81,1974,3,1974,3}, +{0x1F82,1977,4,1977,4}, +{0x1F83,1981,4,1981,4}, +{0x1F84,1985,4,1985,4}, +{0x1F85,1989,4,1989,4}, +{0x1F86,1993,4,1993,4}, +{0x1F87,1997,4,1997,4}, +{0x1F88,2001,3,2001,3}, +{0x1F89,2004,3,2004,3}, +{0x1F8A,2007,4,2007,4}, +{0x1F8B,2011,4,2011,4}, +{0x1F8C,2015,4,2015,4}, +{0x1F8D,2019,4,2019,4}, +{0x1F8E,2023,4,2023,4}, +{0x1F8F,2027,4,2027,4}, +{0x1F90,2031,3,2031,3}, +{0x1F91,2034,3,2034,3}, +{0x1F92,2037,4,2037,4}, +{0x1F93,2041,4,2041,4}, +{0x1F94,2045,4,2045,4}, +{0x1F95,2049,4,2049,4}, +{0x1F96,2053,4,2053,4}, +{0x1F97,2057,4,2057,4}, +{0x1F98,2061,3,2061,3}, +{0x1F99,2064,3,2064,3}, +{0x1F9A,2067,4,2067,4}, +{0x1F9B,2071,4,2071,4}, +{0x1F9C,2075,4,2075,4}, +{0x1F9D,2079,4,2079,4}, +{0x1F9E,2083,4,2083,4}, +{0x1F9F,2087,4,2087,4}, +{0x1FA0,2091,3,2091,3}, +{0x1FA1,2094,3,2094,3}, +{0x1FA2,2097,4,2097,4}, +{0x1FA3,2101,4,2101,4}, +{0x1FA4,2105,4,2105,4}, +{0x1FA5,2109,4,2109,4}, +{0x1FA6,2113,4,2113,4}, +{0x1FA7,2117,4,2117,4}, +{0x1FA8,2121,3,2121,3}, +{0x1FA9,2124,3,2124,3}, +{0x1FAA,2127,4,2127,4}, +{0x1FAB,2131,4,2131,4}, +{0x1FAC,2135,4,2135,4}, +{0x1FAD,2139,4,2139,4}, +{0x1FAE,2143,4,2143,4}, +{0x1FAF,2147,4,2147,4}, +{0x1FB0,2151,2,2151,2}, +{0x1FB1,2153,2,2153,2}, +{0x1FB2,2155,3,2155,3}, +{0x1FB3,2158,2,2158,2}, +{0x1FB4,2160,3,2160,3}, +{0x1FB6,2163,2,2163,2}, +{0x1FB7,2165,3,2165,3}, +{0x1FB8,2168,2,2168,2}, +{0x1FB9,2170,2,2170,2}, +{0x1FBA,2172,2,2172,2}, +{0x1FBB,2174,2,2174,2}, +{0x1FBC,2176,2,2176,2}, +{0x1FBD,0,0,2178,2}, +{0x1FBE,2180,1,2180,1}, +{0x1FBF,0,0,2181,2}, +{0x1FC0,0,0,2183,2}, +{0x1FC1,2185,2,2187,3}, +{0x1FC2,2190,3,2190,3}, +{0x1FC3,2193,2,2193,2}, +{0x1FC4,2195,3,2195,3}, +{0x1FC6,2198,2,2198,2}, +{0x1FC7,2200,3,2200,3}, +{0x1FC8,2203,2,2203,2}, +{0x1FC9,2205,2,2205,2}, +{0x1FCA,2207,2,2207,2}, +{0x1FCB,2209,2,2209,2}, +{0x1FCC,2211,2,2211,2}, +{0x1FCD,2213,2,2215,3}, +{0x1FCE,2218,2,2220,3}, +{0x1FCF,2223,2,2225,3}, +{0x1FD0,2228,2,2228,2}, +{0x1FD1,2230,2,2230,2}, +{0x1FD2,2232,3,2232,3}, +{0x1FD3,2235,3,2235,3}, +{0x1FD6,2238,2,2238,2}, +{0x1FD7,2240,3,2240,3}, +{0x1FD8,2243,2,2243,2}, +{0x1FD9,2245,2,2245,2}, +{0x1FDA,2247,2,2247,2}, +{0x1FDB,2249,2,2249,2}, +{0x1FDD,2251,2,2253,3}, +{0x1FDE,2256,2,2258,3}, +{0x1FDF,2261,2,2263,3}, +{0x1FE0,2266,2,2266,2}, +{0x1FE1,2268,2,2268,2}, +{0x1FE2,2270,3,2270,3}, +{0x1FE3,2273,3,2273,3}, +{0x1FE4,2276,2,2276,2}, +{0x1FE5,2278,2,2278,2}, +{0x1FE6,2280,2,2280,2}, +{0x1FE7,2282,3,2282,3}, +{0x1FE8,2285,2,2285,2}, +{0x1FE9,2287,2,2287,2}, +{0x1FEA,2289,2,2289,2}, +{0x1FEB,2291,2,2291,2}, +{0x1FEC,2293,2,2293,2}, +{0x1FED,2295,2,2297,3}, +{0x1FEE,2300,2,2302,3}, +{0x1FEF,2305,1,2305,1}, +{0x1FF2,2306,3,2306,3}, +{0x1FF3,2309,2,2309,2}, +{0x1FF4,2311,3,2311,3}, +{0x1FF6,2314,2,2314,2}, +{0x1FF7,2316,3,2316,3}, +{0x1FF8,2319,2,2319,2}, +{0x1FF9,2321,2,2321,2}, +{0x1FFA,2323,2,2323,2}, +{0x1FFB,2325,2,2325,2}, +{0x1FFC,2327,2,2327,2}, +{0x1FFD,2329,1,2330,2}, +{0x1FFE,0,0,2332,2}, +{0x2000,2334,1,2335,1}, +{0x2001,2336,1,2337,1}, +{0x2002,0,0,2338,1}, +{0x2003,0,0,2339,1}, +{0x2004,0,0,2340,1}, +{0x2005,0,0,2341,1}, +{0x2006,0,0,2342,1}, +{0x2007,0,0,2343,1}, +{0x2008,0,0,2344,1}, +{0x2009,0,0,2345,1}, +{0x200A,0,0,2346,1}, +{0x2011,0,0,2347,1}, +{0x2017,0,0,2348,2}, +{0x2024,0,0,2350,1}, +{0x2025,0,0,2351,2}, +{0x2026,0,0,2353,3}, +{0x202F,0,0,2356,1}, +{0x2033,0,0,2357,2}, +{0x2034,0,0,2359,3}, +{0x2036,0,0,2362,2}, +{0x2037,0,0,2364,3}, +{0x203C,0,0,2367,2}, +{0x203E,0,0,2369,2}, +{0x2047,0,0,2371,2}, +{0x2048,0,0,2373,2}, +{0x2049,0,0,2375,2}, +{0x2057,0,0,2377,4}, +{0x205F,0,0,2381,1}, +{0x2070,0,0,2382,1}, +{0x2071,0,0,2383,1}, +{0x2074,0,0,2384,1}, +{0x2075,0,0,2385,1}, +{0x2076,0,0,2386,1}, +{0x2077,0,0,2387,1}, +{0x2078,0,0,2388,1}, +{0x2079,0,0,2389,1}, +{0x207A,0,0,2390,1}, +{0x207B,0,0,2391,1}, +{0x207C,0,0,2392,1}, +{0x207D,0,0,2393,1}, +{0x207E,0,0,2394,1}, +{0x207F,0,0,2395,1}, +{0x2080,0,0,2396,1}, +{0x2081,0,0,2397,1}, +{0x2082,0,0,2398,1}, +{0x2083,0,0,2399,1}, +{0x2084,0,0,2400,1}, +{0x2085,0,0,2401,1}, +{0x2086,0,0,2402,1}, +{0x2087,0,0,2403,1}, +{0x2088,0,0,2404,1}, +{0x2089,0,0,2405,1}, +{0x208A,0,0,2406,1}, +{0x208B,0,0,2407,1}, +{0x208C,0,0,2408,1}, +{0x208D,0,0,2409,1}, +{0x208E,0,0,2410,1}, +{0x2090,0,0,2411,1}, +{0x2091,0,0,2412,1}, +{0x2092,0,0,2413,1}, +{0x2093,0,0,2414,1}, +{0x2094,0,0,2415,1}, +{0x2095,0,0,2416,1}, +{0x2096,0,0,2417,1}, +{0x2097,0,0,2418,1}, +{0x2098,0,0,2419,1}, +{0x2099,0,0,2420,1}, +{0x209A,0,0,2421,1}, +{0x209B,0,0,2422,1}, +{0x209C,0,0,2423,1}, +{0x20A8,0,0,2424,2}, +{0x2100,0,0,2426,3}, +{0x2101,0,0,2429,3}, +{0x2102,0,0,2432,1}, +{0x2103,0,0,2433,2}, +{0x2105,0,0,2435,3}, +{0x2106,0,0,2438,3}, +{0x2107,0,0,2441,1}, +{0x2109,0,0,2442,2}, +{0x210A,0,0,2444,1}, +{0x210B,0,0,2445,1}, +{0x210C,0,0,2446,1}, +{0x210D,0,0,2447,1}, +{0x210E,0,0,2448,1}, +{0x210F,0,0,2449,1}, +{0x2110,0,0,2450,1}, +{0x2111,0,0,2451,1}, +{0x2112,0,0,2452,1}, +{0x2113,0,0,2453,1}, +{0x2115,0,0,2454,1}, +{0x2116,0,0,2455,2}, +{0x2119,0,0,2457,1}, +{0x211A,0,0,2458,1}, +{0x211B,0,0,2459,1}, +{0x211C,0,0,2460,1}, +{0x211D,0,0,2461,1}, +{0x2120,0,0,2462,2}, +{0x2121,0,0,2464,3}, +{0x2122,0,0,2467,2}, +{0x2124,0,0,2469,1}, +{0x2126,2470,1,2470,1}, +{0x2128,0,0,2471,1}, +{0x212A,2472,1,2472,1}, +{0x212B,2473,2,2473,2}, +{0x212C,0,0,2475,1}, +{0x212D,0,0,2476,1}, +{0x212F,0,0,2477,1}, +{0x2130,0,0,2478,1}, +{0x2131,0,0,2479,1}, +{0x2133,0,0,2480,1}, +{0x2134,0,0,2481,1}, +{0x2135,0,0,2482,1}, +{0x2136,0,0,2483,1}, +{0x2137,0,0,2484,1}, +{0x2138,0,0,2485,1}, +{0x2139,0,0,2486,1}, +{0x213B,0,0,2487,3}, +{0x213C,0,0,2490,1}, +{0x213D,0,0,2491,1}, +{0x213E,0,0,2492,1}, +{0x213F,0,0,2493,1}, +{0x2140,0,0,2494,1}, +{0x2145,0,0,2495,1}, +{0x2146,0,0,2496,1}, +{0x2147,0,0,2497,1}, +{0x2148,0,0,2498,1}, +{0x2149,0,0,2499,1}, +{0x2150,0,0,2500,3}, +{0x2151,0,0,2503,3}, +{0x2152,0,0,2506,4}, +{0x2153,0,0,2510,3}, +{0x2154,0,0,2513,3}, +{0x2155,0,0,2516,3}, +{0x2156,0,0,2519,3}, +{0x2157,0,0,2522,3}, +{0x2158,0,0,2525,3}, +{0x2159,0,0,2528,3}, +{0x215A,0,0,2531,3}, +{0x215B,0,0,2534,3}, +{0x215C,0,0,2537,3}, +{0x215D,0,0,2540,3}, +{0x215E,0,0,2543,3}, +{0x215F,0,0,2546,2}, +{0x2160,0,0,2548,1}, +{0x2161,0,0,2549,2}, +{0x2162,0,0,2551,3}, +{0x2163,0,0,2554,2}, +{0x2164,0,0,2556,1}, +{0x2165,0,0,2557,2}, +{0x2166,0,0,2559,3}, +{0x2167,0,0,2562,4}, +{0x2168,0,0,2566,2}, +{0x2169,0,0,2568,1}, +{0x216A,0,0,2569,2}, +{0x216B,0,0,2571,3}, +{0x216C,0,0,2574,1}, +{0x216D,0,0,2575,1}, +{0x216E,0,0,2576,1}, +{0x216F,0,0,2577,1}, +{0x2170,0,0,2578,1}, +{0x2171,0,0,2579,2}, +{0x2172,0,0,2581,3}, +{0x2173,0,0,2584,2}, +{0x2174,0,0,2586,1}, +{0x2175,0,0,2587,2}, +{0x2176,0,0,2589,3}, +{0x2177,0,0,2592,4}, +{0x2178,0,0,2596,2}, +{0x2179,0,0,2598,1}, +{0x217A,0,0,2599,2}, +{0x217B,0,0,2601,3}, +{0x217C,0,0,2604,1}, +{0x217D,0,0,2605,1}, +{0x217E,0,0,2606,1}, +{0x217F,0,0,2607,1}, +{0x2189,0,0,2608,3}, +{0x219A,2611,2,2611,2}, +{0x219B,2613,2,2613,2}, +{0x21AE,2615,2,2615,2}, +{0x21CD,2617,2,2617,2}, +{0x21CE,2619,2,2619,2}, +{0x21CF,2621,2,2621,2}, +{0x2204,2623,2,2623,2}, +{0x2209,2625,2,2625,2}, +{0x220C,2627,2,2627,2}, +{0x2224,2629,2,2629,2}, +{0x2226,2631,2,2631,2}, +{0x222C,0,0,2633,2}, +{0x222D,0,0,2635,3}, +{0x222F,0,0,2638,2}, +{0x2230,0,0,2640,3}, +{0x2241,2643,2,2643,2}, +{0x2244,2645,2,2645,2}, +{0x2247,2647,2,2647,2}, +{0x2249,2649,2,2649,2}, +{0x2260,2651,2,2651,2}, +{0x2262,2653,2,2653,2}, +{0x226D,2655,2,2655,2}, +{0x226E,2657,2,2657,2}, +{0x226F,2659,2,2659,2}, +{0x2270,2661,2,2661,2}, +{0x2271,2663,2,2663,2}, +{0x2274,2665,2,2665,2}, +{0x2275,2667,2,2667,2}, +{0x2278,2669,2,2669,2}, +{0x2279,2671,2,2671,2}, +{0x2280,2673,2,2673,2}, +{0x2281,2675,2,2675,2}, +{0x2284,2677,2,2677,2}, +{0x2285,2679,2,2679,2}, +{0x2288,2681,2,2681,2}, +{0x2289,2683,2,2683,2}, +{0x22AC,2685,2,2685,2}, +{0x22AD,2687,2,2687,2}, +{0x22AE,2689,2,2689,2}, +{0x22AF,2691,2,2691,2}, +{0x22E0,2693,2,2693,2}, +{0x22E1,2695,2,2695,2}, +{0x22E2,2697,2,2697,2}, +{0x22E3,2699,2,2699,2}, +{0x22EA,2701,2,2701,2}, +{0x22EB,2703,2,2703,2}, +{0x22EC,2705,2,2705,2}, +{0x22ED,2707,2,2707,2}, +{0x2329,2709,1,2709,1}, +{0x232A,2710,1,2710,1}, +{0x2460,0,0,2711,1}, +{0x2461,0,0,2712,1}, +{0x2462,0,0,2713,1}, +{0x2463,0,0,2714,1}, +{0x2464,0,0,2715,1}, +{0x2465,0,0,2716,1}, +{0x2466,0,0,2717,1}, +{0x2467,0,0,2718,1}, +{0x2468,0,0,2719,1}, +{0x2469,0,0,2720,2}, +{0x246A,0,0,2722,2}, +{0x246B,0,0,2724,2}, +{0x246C,0,0,2726,2}, +{0x246D,0,0,2728,2}, +{0x246E,0,0,2730,2}, +{0x246F,0,0,2732,2}, +{0x2470,0,0,2734,2}, +{0x2471,0,0,2736,2}, +{0x2472,0,0,2738,2}, +{0x2473,0,0,2740,2}, +{0x2474,0,0,2742,3}, +{0x2475,0,0,2745,3}, +{0x2476,0,0,2748,3}, +{0x2477,0,0,2751,3}, +{0x2478,0,0,2754,3}, +{0x2479,0,0,2757,3}, +{0x247A,0,0,2760,3}, +{0x247B,0,0,2763,3}, +{0x247C,0,0,2766,3}, +{0x247D,0,0,2769,4}, +{0x247E,0,0,2773,4}, +{0x247F,0,0,2777,4}, +{0x2480,0,0,2781,4}, +{0x2481,0,0,2785,4}, +{0x2482,0,0,2789,4}, +{0x2483,0,0,2793,4}, +{0x2484,0,0,2797,4}, +{0x2485,0,0,2801,4}, +{0x2486,0,0,2805,4}, +{0x2487,0,0,2809,4}, +{0x2488,0,0,2813,2}, +{0x2489,0,0,2815,2}, +{0x248A,0,0,2817,2}, +{0x248B,0,0,2819,2}, +{0x248C,0,0,2821,2}, +{0x248D,0,0,2823,2}, +{0x248E,0,0,2825,2}, +{0x248F,0,0,2827,2}, +{0x2490,0,0,2829,2}, +{0x2491,0,0,2831,3}, +{0x2492,0,0,2834,3}, +{0x2493,0,0,2837,3}, +{0x2494,0,0,2840,3}, +{0x2495,0,0,2843,3}, +{0x2496,0,0,2846,3}, +{0x2497,0,0,2849,3}, +{0x2498,0,0,2852,3}, +{0x2499,0,0,2855,3}, +{0x249A,0,0,2858,3}, +{0x249B,0,0,2861,3}, +{0x249C,0,0,2864,3}, +{0x249D,0,0,2867,3}, +{0x249E,0,0,2870,3}, +{0x249F,0,0,2873,3}, +{0x24A0,0,0,2876,3}, +{0x24A1,0,0,2879,3}, +{0x24A2,0,0,2882,3}, +{0x24A3,0,0,2885,3}, +{0x24A4,0,0,2888,3}, +{0x24A5,0,0,2891,3}, +{0x24A6,0,0,2894,3}, +{0x24A7,0,0,2897,3}, +{0x24A8,0,0,2900,3}, +{0x24A9,0,0,2903,3}, +{0x24AA,0,0,2906,3}, +{0x24AB,0,0,2909,3}, +{0x24AC,0,0,2912,3}, +{0x24AD,0,0,2915,3}, +{0x24AE,0,0,2918,3}, +{0x24AF,0,0,2921,3}, +{0x24B0,0,0,2924,3}, +{0x24B1,0,0,2927,3}, +{0x24B2,0,0,2930,3}, +{0x24B3,0,0,2933,3}, +{0x24B4,0,0,2936,3}, +{0x24B5,0,0,2939,3}, +{0x24B6,0,0,2942,1}, +{0x24B7,0,0,2943,1}, +{0x24B8,0,0,2944,1}, +{0x24B9,0,0,2945,1}, +{0x24BA,0,0,2946,1}, +{0x24BB,0,0,2947,1}, +{0x24BC,0,0,2948,1}, +{0x24BD,0,0,2949,1}, +{0x24BE,0,0,2950,1}, +{0x24BF,0,0,2951,1}, +{0x24C0,0,0,2952,1}, +{0x24C1,0,0,2953,1}, +{0x24C2,0,0,2954,1}, +{0x24C3,0,0,2955,1}, +{0x24C4,0,0,2956,1}, +{0x24C5,0,0,2957,1}, +{0x24C6,0,0,2958,1}, +{0x24C7,0,0,2959,1}, +{0x24C8,0,0,2960,1}, +{0x24C9,0,0,2961,1}, +{0x24CA,0,0,2962,1}, +{0x24CB,0,0,2963,1}, +{0x24CC,0,0,2964,1}, +{0x24CD,0,0,2965,1}, +{0x24CE,0,0,2966,1}, +{0x24CF,0,0,2967,1}, +{0x24D0,0,0,2968,1}, +{0x24D1,0,0,2969,1}, +{0x24D2,0,0,2970,1}, +{0x24D3,0,0,2971,1}, +{0x24D4,0,0,2972,1}, +{0x24D5,0,0,2973,1}, +{0x24D6,0,0,2974,1}, +{0x24D7,0,0,2975,1}, +{0x24D8,0,0,2976,1}, +{0x24D9,0,0,2977,1}, +{0x24DA,0,0,2978,1}, +{0x24DB,0,0,2979,1}, +{0x24DC,0,0,2980,1}, +{0x24DD,0,0,2981,1}, +{0x24DE,0,0,2982,1}, +{0x24DF,0,0,2983,1}, +{0x24E0,0,0,2984,1}, +{0x24E1,0,0,2985,1}, +{0x24E2,0,0,2986,1}, +{0x24E3,0,0,2987,1}, +{0x24E4,0,0,2988,1}, +{0x24E5,0,0,2989,1}, +{0x24E6,0,0,2990,1}, +{0x24E7,0,0,2991,1}, +{0x24E8,0,0,2992,1}, +{0x24E9,0,0,2993,1}, +{0x24EA,0,0,2994,1}, +{0x2A0C,0,0,2995,4}, +{0x2A74,0,0,2999,3}, +{0x2A75,0,0,3002,2}, +{0x2A76,0,0,3004,3}, +{0x2ADC,3007,2,3007,2}, +{0x2C7C,0,0,3009,1}, +{0x2C7D,0,0,3010,1}, +{0x2D6F,0,0,3011,1}, +{0x2E9F,0,0,3012,1}, +{0x2EF3,0,0,3013,1}, +{0x2F00,0,0,3014,1}, +{0x2F01,0,0,3015,1}, +{0x2F02,0,0,3016,1}, +{0x2F03,0,0,3017,1}, +{0x2F04,0,0,3018,1}, +{0x2F05,0,0,3019,1}, +{0x2F06,0,0,3020,1}, +{0x2F07,0,0,3021,1}, +{0x2F08,0,0,3022,1}, +{0x2F09,0,0,3023,1}, +{0x2F0A,0,0,3024,1}, +{0x2F0B,0,0,3025,1}, +{0x2F0C,0,0,3026,1}, +{0x2F0D,0,0,3027,1}, +{0x2F0E,0,0,3028,1}, +{0x2F0F,0,0,3029,1}, +{0x2F10,0,0,3030,1}, +{0x2F11,0,0,3031,1}, +{0x2F12,0,0,3032,1}, +{0x2F13,0,0,3033,1}, +{0x2F14,0,0,3034,1}, +{0x2F15,0,0,3035,1}, +{0x2F16,0,0,3036,1}, +{0x2F17,0,0,3037,1}, +{0x2F18,0,0,3038,1}, +{0x2F19,0,0,3039,1}, +{0x2F1A,0,0,3040,1}, +{0x2F1B,0,0,3041,1}, +{0x2F1C,0,0,3042,1}, +{0x2F1D,0,0,3043,1}, +{0x2F1E,0,0,3044,1}, +{0x2F1F,0,0,3045,1}, +{0x2F20,0,0,3046,1}, +{0x2F21,0,0,3047,1}, +{0x2F22,0,0,3048,1}, +{0x2F23,0,0,3049,1}, +{0x2F24,0,0,3050,1}, +{0x2F25,0,0,3051,1}, +{0x2F26,0,0,3052,1}, +{0x2F27,0,0,3053,1}, +{0x2F28,0,0,3054,1}, +{0x2F29,0,0,3055,1}, +{0x2F2A,0,0,3056,1}, +{0x2F2B,0,0,3057,1}, +{0x2F2C,0,0,3058,1}, +{0x2F2D,0,0,3059,1}, +{0x2F2E,0,0,3060,1}, +{0x2F2F,0,0,3061,1}, +{0x2F30,0,0,3062,1}, +{0x2F31,0,0,3063,1}, +{0x2F32,0,0,3064,1}, +{0x2F33,0,0,3065,1}, +{0x2F34,0,0,3066,1}, +{0x2F35,0,0,3067,1}, +{0x2F36,0,0,3068,1}, +{0x2F37,0,0,3069,1}, +{0x2F38,0,0,3070,1}, +{0x2F39,0,0,3071,1}, +{0x2F3A,0,0,3072,1}, +{0x2F3B,0,0,3073,1}, +{0x2F3C,0,0,3074,1}, +{0x2F3D,0,0,3075,1}, +{0x2F3E,0,0,3076,1}, +{0x2F3F,0,0,3077,1}, +{0x2F40,0,0,3078,1}, +{0x2F41,0,0,3079,1}, +{0x2F42,0,0,3080,1}, +{0x2F43,0,0,3081,1}, +{0x2F44,0,0,3082,1}, +{0x2F45,0,0,3083,1}, +{0x2F46,0,0,3084,1}, +{0x2F47,0,0,3085,1}, +{0x2F48,0,0,3086,1}, +{0x2F49,0,0,3087,1}, +{0x2F4A,0,0,3088,1}, +{0x2F4B,0,0,3089,1}, +{0x2F4C,0,0,3090,1}, +{0x2F4D,0,0,3091,1}, +{0x2F4E,0,0,3092,1}, +{0x2F4F,0,0,3093,1}, +{0x2F50,0,0,3094,1}, +{0x2F51,0,0,3095,1}, +{0x2F52,0,0,3096,1}, +{0x2F53,0,0,3097,1}, +{0x2F54,0,0,3098,1}, +{0x2F55,0,0,3099,1}, +{0x2F56,0,0,3100,1}, +{0x2F57,0,0,3101,1}, +{0x2F58,0,0,3102,1}, +{0x2F59,0,0,3103,1}, +{0x2F5A,0,0,3104,1}, +{0x2F5B,0,0,3105,1}, +{0x2F5C,0,0,3106,1}, +{0x2F5D,0,0,3107,1}, +{0x2F5E,0,0,3108,1}, +{0x2F5F,0,0,3109,1}, +{0x2F60,0,0,3110,1}, +{0x2F61,0,0,3111,1}, +{0x2F62,0,0,3112,1}, +{0x2F63,0,0,3113,1}, +{0x2F64,0,0,3114,1}, +{0x2F65,0,0,3115,1}, +{0x2F66,0,0,3116,1}, +{0x2F67,0,0,3117,1}, +{0x2F68,0,0,3118,1}, +{0x2F69,0,0,3119,1}, +{0x2F6A,0,0,3120,1}, +{0x2F6B,0,0,3121,1}, +{0x2F6C,0,0,3122,1}, +{0x2F6D,0,0,3123,1}, +{0x2F6E,0,0,3124,1}, +{0x2F6F,0,0,3125,1}, +{0x2F70,0,0,3126,1}, +{0x2F71,0,0,3127,1}, +{0x2F72,0,0,3128,1}, +{0x2F73,0,0,3129,1}, +{0x2F74,0,0,3130,1}, +{0x2F75,0,0,3131,1}, +{0x2F76,0,0,3132,1}, +{0x2F77,0,0,3133,1}, +{0x2F78,0,0,3134,1}, +{0x2F79,0,0,3135,1}, +{0x2F7A,0,0,3136,1}, +{0x2F7B,0,0,3137,1}, +{0x2F7C,0,0,3138,1}, +{0x2F7D,0,0,3139,1}, +{0x2F7E,0,0,3140,1}, +{0x2F7F,0,0,3141,1}, +{0x2F80,0,0,3142,1}, +{0x2F81,0,0,3143,1}, +{0x2F82,0,0,3144,1}, +{0x2F83,0,0,3145,1}, +{0x2F84,0,0,3146,1}, +{0x2F85,0,0,3147,1}, +{0x2F86,0,0,3148,1}, +{0x2F87,0,0,3149,1}, +{0x2F88,0,0,3150,1}, +{0x2F89,0,0,3151,1}, +{0x2F8A,0,0,3152,1}, +{0x2F8B,0,0,3153,1}, +{0x2F8C,0,0,3154,1}, +{0x2F8D,0,0,3155,1}, +{0x2F8E,0,0,3156,1}, +{0x2F8F,0,0,3157,1}, +{0x2F90,0,0,3158,1}, +{0x2F91,0,0,3159,1}, +{0x2F92,0,0,3160,1}, +{0x2F93,0,0,3161,1}, +{0x2F94,0,0,3162,1}, +{0x2F95,0,0,3163,1}, +{0x2F96,0,0,3164,1}, +{0x2F97,0,0,3165,1}, +{0x2F98,0,0,3166,1}, +{0x2F99,0,0,3167,1}, +{0x2F9A,0,0,3168,1}, +{0x2F9B,0,0,3169,1}, +{0x2F9C,0,0,3170,1}, +{0x2F9D,0,0,3171,1}, +{0x2F9E,0,0,3172,1}, +{0x2F9F,0,0,3173,1}, +{0x2FA0,0,0,3174,1}, +{0x2FA1,0,0,3175,1}, +{0x2FA2,0,0,3176,1}, +{0x2FA3,0,0,3177,1}, +{0x2FA4,0,0,3178,1}, +{0x2FA5,0,0,3179,1}, +{0x2FA6,0,0,3180,1}, +{0x2FA7,0,0,3181,1}, +{0x2FA8,0,0,3182,1}, +{0x2FA9,0,0,3183,1}, +{0x2FAA,0,0,3184,1}, +{0x2FAB,0,0,3185,1}, +{0x2FAC,0,0,3186,1}, +{0x2FAD,0,0,3187,1}, +{0x2FAE,0,0,3188,1}, +{0x2FAF,0,0,3189,1}, +{0x2FB0,0,0,3190,1}, +{0x2FB1,0,0,3191,1}, +{0x2FB2,0,0,3192,1}, +{0x2FB3,0,0,3193,1}, +{0x2FB4,0,0,3194,1}, +{0x2FB5,0,0,3195,1}, +{0x2FB6,0,0,3196,1}, +{0x2FB7,0,0,3197,1}, +{0x2FB8,0,0,3198,1}, +{0x2FB9,0,0,3199,1}, +{0x2FBA,0,0,3200,1}, +{0x2FBB,0,0,3201,1}, +{0x2FBC,0,0,3202,1}, +{0x2FBD,0,0,3203,1}, +{0x2FBE,0,0,3204,1}, +{0x2FBF,0,0,3205,1}, +{0x2FC0,0,0,3206,1}, +{0x2FC1,0,0,3207,1}, +{0x2FC2,0,0,3208,1}, +{0x2FC3,0,0,3209,1}, +{0x2FC4,0,0,3210,1}, +{0x2FC5,0,0,3211,1}, +{0x2FC6,0,0,3212,1}, +{0x2FC7,0,0,3213,1}, +{0x2FC8,0,0,3214,1}, +{0x2FC9,0,0,3215,1}, +{0x2FCA,0,0,3216,1}, +{0x2FCB,0,0,3217,1}, +{0x2FCC,0,0,3218,1}, +{0x2FCD,0,0,3219,1}, +{0x2FCE,0,0,3220,1}, +{0x2FCF,0,0,3221,1}, +{0x2FD0,0,0,3222,1}, +{0x2FD1,0,0,3223,1}, +{0x2FD2,0,0,3224,1}, +{0x2FD3,0,0,3225,1}, +{0x2FD4,0,0,3226,1}, +{0x2FD5,0,0,3227,1}, +{0x3000,0,0,3228,1}, +{0x3036,0,0,3229,1}, +{0x3038,0,0,3230,1}, +{0x3039,0,0,3231,1}, +{0x303A,0,0,3232,1}, +{0x304C,3233,2,3233,2}, +{0x304E,3235,2,3235,2}, +{0x3050,3237,2,3237,2}, +{0x3052,3239,2,3239,2}, +{0x3054,3241,2,3241,2}, +{0x3056,3243,2,3243,2}, +{0x3058,3245,2,3245,2}, +{0x305A,3247,2,3247,2}, +{0x305C,3249,2,3249,2}, +{0x305E,3251,2,3251,2}, +{0x3060,3253,2,3253,2}, +{0x3062,3255,2,3255,2}, +{0x3065,3257,2,3257,2}, +{0x3067,3259,2,3259,2}, +{0x3069,3261,2,3261,2}, +{0x3070,3263,2,3263,2}, +{0x3071,3265,2,3265,2}, +{0x3073,3267,2,3267,2}, +{0x3074,3269,2,3269,2}, +{0x3076,3271,2,3271,2}, +{0x3077,3273,2,3273,2}, +{0x3079,3275,2,3275,2}, +{0x307A,3277,2,3277,2}, +{0x307C,3279,2,3279,2}, +{0x307D,3281,2,3281,2}, +{0x3094,3283,2,3283,2}, +{0x309B,0,0,3285,2}, +{0x309C,0,0,3287,2}, +{0x309E,3289,2,3289,2}, +{0x309F,0,0,3291,2}, +{0x30AC,3293,2,3293,2}, +{0x30AE,3295,2,3295,2}, +{0x30B0,3297,2,3297,2}, +{0x30B2,3299,2,3299,2}, +{0x30B4,3301,2,3301,2}, +{0x30B6,3303,2,3303,2}, +{0x30B8,3305,2,3305,2}, +{0x30BA,3307,2,3307,2}, +{0x30BC,3309,2,3309,2}, +{0x30BE,3311,2,3311,2}, +{0x30C0,3313,2,3313,2}, +{0x30C2,3315,2,3315,2}, +{0x30C5,3317,2,3317,2}, +{0x30C7,3319,2,3319,2}, +{0x30C9,3321,2,3321,2}, +{0x30D0,3323,2,3323,2}, +{0x30D1,3325,2,3325,2}, +{0x30D3,3327,2,3327,2}, +{0x30D4,3329,2,3329,2}, +{0x30D6,3331,2,3331,2}, +{0x30D7,3333,2,3333,2}, +{0x30D9,3335,2,3335,2}, +{0x30DA,3337,2,3337,2}, +{0x30DC,3339,2,3339,2}, +{0x30DD,3341,2,3341,2}, +{0x30F4,3343,2,3343,2}, +{0x30F7,3345,2,3345,2}, +{0x30F8,3347,2,3347,2}, +{0x30F9,3349,2,3349,2}, +{0x30FA,3351,2,3351,2}, +{0x30FE,3353,2,3353,2}, +{0x30FF,0,0,3355,2}, +{0x3131,0,0,3357,1}, +{0x3132,0,0,3358,1}, +{0x3133,0,0,3359,1}, +{0x3134,0,0,3360,1}, +{0x3135,0,0,3361,1}, +{0x3136,0,0,3362,1}, +{0x3137,0,0,3363,1}, +{0x3138,0,0,3364,1}, +{0x3139,0,0,3365,1}, +{0x313A,0,0,3366,1}, +{0x313B,0,0,3367,1}, +{0x313C,0,0,3368,1}, +{0x313D,0,0,3369,1}, +{0x313E,0,0,3370,1}, +{0x313F,0,0,3371,1}, +{0x3140,0,0,3372,1}, +{0x3141,0,0,3373,1}, +{0x3142,0,0,3374,1}, +{0x3143,0,0,3375,1}, +{0x3144,0,0,3376,1}, +{0x3145,0,0,3377,1}, +{0x3146,0,0,3378,1}, +{0x3147,0,0,3379,1}, +{0x3148,0,0,3380,1}, +{0x3149,0,0,3381,1}, +{0x314A,0,0,3382,1}, +{0x314B,0,0,3383,1}, +{0x314C,0,0,3384,1}, +{0x314D,0,0,3385,1}, +{0x314E,0,0,3386,1}, +{0x314F,0,0,3387,1}, +{0x3150,0,0,3388,1}, +{0x3151,0,0,3389,1}, +{0x3152,0,0,3390,1}, +{0x3153,0,0,3391,1}, +{0x3154,0,0,3392,1}, +{0x3155,0,0,3393,1}, +{0x3156,0,0,3394,1}, +{0x3157,0,0,3395,1}, +{0x3158,0,0,3396,1}, +{0x3159,0,0,3397,1}, +{0x315A,0,0,3398,1}, +{0x315B,0,0,3399,1}, +{0x315C,0,0,3400,1}, +{0x315D,0,0,3401,1}, +{0x315E,0,0,3402,1}, +{0x315F,0,0,3403,1}, +{0x3160,0,0,3404,1}, +{0x3161,0,0,3405,1}, +{0x3162,0,0,3406,1}, +{0x3163,0,0,3407,1}, +{0x3164,0,0,3408,1}, +{0x3165,0,0,3409,1}, +{0x3166,0,0,3410,1}, +{0x3167,0,0,3411,1}, +{0x3168,0,0,3412,1}, +{0x3169,0,0,3413,1}, +{0x316A,0,0,3414,1}, +{0x316B,0,0,3415,1}, +{0x316C,0,0,3416,1}, +{0x316D,0,0,3417,1}, +{0x316E,0,0,3418,1}, +{0x316F,0,0,3419,1}, +{0x3170,0,0,3420,1}, +{0x3171,0,0,3421,1}, +{0x3172,0,0,3422,1}, +{0x3173,0,0,3423,1}, +{0x3174,0,0,3424,1}, +{0x3175,0,0,3425,1}, +{0x3176,0,0,3426,1}, +{0x3177,0,0,3427,1}, +{0x3178,0,0,3428,1}, +{0x3179,0,0,3429,1}, +{0x317A,0,0,3430,1}, +{0x317B,0,0,3431,1}, +{0x317C,0,0,3432,1}, +{0x317D,0,0,3433,1}, +{0x317E,0,0,3434,1}, +{0x317F,0,0,3435,1}, +{0x3180,0,0,3436,1}, +{0x3181,0,0,3437,1}, +{0x3182,0,0,3438,1}, +{0x3183,0,0,3439,1}, +{0x3184,0,0,3440,1}, +{0x3185,0,0,3441,1}, +{0x3186,0,0,3442,1}, +{0x3187,0,0,3443,1}, +{0x3188,0,0,3444,1}, +{0x3189,0,0,3445,1}, +{0x318A,0,0,3446,1}, +{0x318B,0,0,3447,1}, +{0x318C,0,0,3448,1}, +{0x318D,0,0,3449,1}, +{0x318E,0,0,3450,1}, +{0x3192,0,0,3451,1}, +{0x3193,0,0,3452,1}, +{0x3194,0,0,3453,1}, +{0x3195,0,0,3454,1}, +{0x3196,0,0,3455,1}, +{0x3197,0,0,3456,1}, +{0x3198,0,0,3457,1}, +{0x3199,0,0,3458,1}, +{0x319A,0,0,3459,1}, +{0x319B,0,0,3460,1}, +{0x319C,0,0,3461,1}, +{0x319D,0,0,3462,1}, +{0x319E,0,0,3463,1}, +{0x319F,0,0,3464,1}, +{0x3200,0,0,3465,3}, +{0x3201,0,0,3468,3}, +{0x3202,0,0,3471,3}, +{0x3203,0,0,3474,3}, +{0x3204,0,0,3477,3}, +{0x3205,0,0,3480,3}, +{0x3206,0,0,3483,3}, +{0x3207,0,0,3486,3}, +{0x3208,0,0,3489,3}, +{0x3209,0,0,3492,3}, +{0x320A,0,0,3495,3}, +{0x320B,0,0,3498,3}, +{0x320C,0,0,3501,3}, +{0x320D,0,0,3504,3}, +{0x320E,0,0,3507,4}, +{0x320F,0,0,3511,4}, +{0x3210,0,0,3515,4}, +{0x3211,0,0,3519,4}, +{0x3212,0,0,3523,4}, +{0x3213,0,0,3527,4}, +{0x3214,0,0,3531,4}, +{0x3215,0,0,3535,4}, +{0x3216,0,0,3539,4}, +{0x3217,0,0,3543,4}, +{0x3218,0,0,3547,4}, +{0x3219,0,0,3551,4}, +{0x321A,0,0,3555,4}, +{0x321B,0,0,3559,4}, +{0x321C,0,0,3563,4}, +{0x321D,0,0,3567,7}, +{0x321E,0,0,3574,6}, +{0x3220,0,0,3580,3}, +{0x3221,0,0,3583,3}, +{0x3222,0,0,3586,3}, +{0x3223,0,0,3589,3}, +{0x3224,0,0,3592,3}, +{0x3225,0,0,3595,3}, +{0x3226,0,0,3598,3}, +{0x3227,0,0,3601,3}, +{0x3228,0,0,3604,3}, +{0x3229,0,0,3607,3}, +{0x322A,0,0,3610,3}, +{0x322B,0,0,3613,3}, +{0x322C,0,0,3616,3}, +{0x322D,0,0,3619,3}, +{0x322E,0,0,3622,3}, +{0x322F,0,0,3625,3}, +{0x3230,0,0,3628,3}, +{0x3231,0,0,3631,3}, +{0x3232,0,0,3634,3}, +{0x3233,0,0,3637,3}, +{0x3234,0,0,3640,3}, +{0x3235,0,0,3643,3}, +{0x3236,0,0,3646,3}, +{0x3237,0,0,3649,3}, +{0x3238,0,0,3652,3}, +{0x3239,0,0,3655,3}, +{0x323A,0,0,3658,3}, +{0x323B,0,0,3661,3}, +{0x323C,0,0,3664,3}, +{0x323D,0,0,3667,3}, +{0x323E,0,0,3670,3}, +{0x323F,0,0,3673,3}, +{0x3240,0,0,3676,3}, +{0x3241,0,0,3679,3}, +{0x3242,0,0,3682,3}, +{0x3243,0,0,3685,3}, +{0x3244,0,0,3688,1}, +{0x3245,0,0,3689,1}, +{0x3246,0,0,3690,1}, +{0x3247,0,0,3691,1}, +{0x3250,0,0,3692,3}, +{0x3251,0,0,3695,2}, +{0x3252,0,0,3697,2}, +{0x3253,0,0,3699,2}, +{0x3254,0,0,3701,2}, +{0x3255,0,0,3703,2}, +{0x3256,0,0,3705,2}, +{0x3257,0,0,3707,2}, +{0x3258,0,0,3709,2}, +{0x3259,0,0,3711,2}, +{0x325A,0,0,3713,2}, +{0x325B,0,0,3715,2}, +{0x325C,0,0,3717,2}, +{0x325D,0,0,3719,2}, +{0x325E,0,0,3721,2}, +{0x325F,0,0,3723,2}, +{0x3260,0,0,3725,1}, +{0x3261,0,0,3726,1}, +{0x3262,0,0,3727,1}, +{0x3263,0,0,3728,1}, +{0x3264,0,0,3729,1}, +{0x3265,0,0,3730,1}, +{0x3266,0,0,3731,1}, +{0x3267,0,0,3732,1}, +{0x3268,0,0,3733,1}, +{0x3269,0,0,3734,1}, +{0x326A,0,0,3735,1}, +{0x326B,0,0,3736,1}, +{0x326C,0,0,3737,1}, +{0x326D,0,0,3738,1}, +{0x326E,0,0,3739,2}, +{0x326F,0,0,3741,2}, +{0x3270,0,0,3743,2}, +{0x3271,0,0,3745,2}, +{0x3272,0,0,3747,2}, +{0x3273,0,0,3749,2}, +{0x3274,0,0,3751,2}, +{0x3275,0,0,3753,2}, +{0x3276,0,0,3755,2}, +{0x3277,0,0,3757,2}, +{0x3278,0,0,3759,2}, +{0x3279,0,0,3761,2}, +{0x327A,0,0,3763,2}, +{0x327B,0,0,3765,2}, +{0x327C,0,0,3767,5}, +{0x327D,0,0,3772,4}, +{0x327E,0,0,3776,2}, +{0x3280,0,0,3778,1}, +{0x3281,0,0,3779,1}, +{0x3282,0,0,3780,1}, +{0x3283,0,0,3781,1}, +{0x3284,0,0,3782,1}, +{0x3285,0,0,3783,1}, +{0x3286,0,0,3784,1}, +{0x3287,0,0,3785,1}, +{0x3288,0,0,3786,1}, +{0x3289,0,0,3787,1}, +{0x328A,0,0,3788,1}, +{0x328B,0,0,3789,1}, +{0x328C,0,0,3790,1}, +{0x328D,0,0,3791,1}, +{0x328E,0,0,3792,1}, +{0x328F,0,0,3793,1}, +{0x3290,0,0,3794,1}, +{0x3291,0,0,3795,1}, +{0x3292,0,0,3796,1}, +{0x3293,0,0,3797,1}, +{0x3294,0,0,3798,1}, +{0x3295,0,0,3799,1}, +{0x3296,0,0,3800,1}, +{0x3297,0,0,3801,1}, +{0x3298,0,0,3802,1}, +{0x3299,0,0,3803,1}, +{0x329A,0,0,3804,1}, +{0x329B,0,0,3805,1}, +{0x329C,0,0,3806,1}, +{0x329D,0,0,3807,1}, +{0x329E,0,0,3808,1}, +{0x329F,0,0,3809,1}, +{0x32A0,0,0,3810,1}, +{0x32A1,0,0,3811,1}, +{0x32A2,0,0,3812,1}, +{0x32A3,0,0,3813,1}, +{0x32A4,0,0,3814,1}, +{0x32A5,0,0,3815,1}, +{0x32A6,0,0,3816,1}, +{0x32A7,0,0,3817,1}, +{0x32A8,0,0,3818,1}, +{0x32A9,0,0,3819,1}, +{0x32AA,0,0,3820,1}, +{0x32AB,0,0,3821,1}, +{0x32AC,0,0,3822,1}, +{0x32AD,0,0,3823,1}, +{0x32AE,0,0,3824,1}, +{0x32AF,0,0,3825,1}, +{0x32B0,0,0,3826,1}, +{0x32B1,0,0,3827,2}, +{0x32B2,0,0,3829,2}, +{0x32B3,0,0,3831,2}, +{0x32B4,0,0,3833,2}, +{0x32B5,0,0,3835,2}, +{0x32B6,0,0,3837,2}, +{0x32B7,0,0,3839,2}, +{0x32B8,0,0,3841,2}, +{0x32B9,0,0,3843,2}, +{0x32BA,0,0,3845,2}, +{0x32BB,0,0,3847,2}, +{0x32BC,0,0,3849,2}, +{0x32BD,0,0,3851,2}, +{0x32BE,0,0,3853,2}, +{0x32BF,0,0,3855,2}, +{0x32C0,0,0,3857,2}, +{0x32C1,0,0,3859,2}, +{0x32C2,0,0,3861,2}, +{0x32C3,0,0,3863,2}, +{0x32C4,0,0,3865,2}, +{0x32C5,0,0,3867,2}, +{0x32C6,0,0,3869,2}, +{0x32C7,0,0,3871,2}, +{0x32C8,0,0,3873,2}, +{0x32C9,0,0,3875,3}, +{0x32CA,0,0,3878,3}, +{0x32CB,0,0,3881,3}, +{0x32CC,0,0,3884,2}, +{0x32CD,0,0,3886,3}, +{0x32CE,0,0,3889,2}, +{0x32CF,0,0,3891,3}, +{0x32D0,0,0,3894,1}, +{0x32D1,0,0,3895,1}, +{0x32D2,0,0,3896,1}, +{0x32D3,0,0,3897,1}, +{0x32D4,0,0,3898,1}, +{0x32D5,0,0,3899,1}, +{0x32D6,0,0,3900,1}, +{0x32D7,0,0,3901,1}, +{0x32D8,0,0,3902,1}, +{0x32D9,0,0,3903,1}, +{0x32DA,0,0,3904,1}, +{0x32DB,0,0,3905,1}, +{0x32DC,0,0,3906,1}, +{0x32DD,0,0,3907,1}, +{0x32DE,0,0,3908,1}, +{0x32DF,0,0,3909,1}, +{0x32E0,0,0,3910,1}, +{0x32E1,0,0,3911,1}, +{0x32E2,0,0,3912,1}, +{0x32E3,0,0,3913,1}, +{0x32E4,0,0,3914,1}, +{0x32E5,0,0,3915,1}, +{0x32E6,0,0,3916,1}, +{0x32E7,0,0,3917,1}, +{0x32E8,0,0,3918,1}, +{0x32E9,0,0,3919,1}, +{0x32EA,0,0,3920,1}, +{0x32EB,0,0,3921,1}, +{0x32EC,0,0,3922,1}, +{0x32ED,0,0,3923,1}, +{0x32EE,0,0,3924,1}, +{0x32EF,0,0,3925,1}, +{0x32F0,0,0,3926,1}, +{0x32F1,0,0,3927,1}, +{0x32F2,0,0,3928,1}, +{0x32F3,0,0,3929,1}, +{0x32F4,0,0,3930,1}, +{0x32F5,0,0,3931,1}, +{0x32F6,0,0,3932,1}, +{0x32F7,0,0,3933,1}, +{0x32F8,0,0,3934,1}, +{0x32F9,0,0,3935,1}, +{0x32FA,0,0,3936,1}, +{0x32FB,0,0,3937,1}, +{0x32FC,0,0,3938,1}, +{0x32FD,0,0,3939,1}, +{0x32FE,0,0,3940,1}, +{0x32FF,0,0,3941,2}, +{0x3300,0,0,3943,5}, +{0x3301,0,0,3948,4}, +{0x3302,0,0,3952,5}, +{0x3303,0,0,3957,3}, +{0x3304,0,0,3960,5}, +{0x3305,0,0,3965,3}, +{0x3306,0,0,3968,3}, +{0x3307,0,0,3971,6}, +{0x3308,0,0,3977,4}, +{0x3309,0,0,3981,3}, +{0x330A,0,0,3984,3}, +{0x330B,0,0,3987,3}, +{0x330C,0,0,3990,4}, +{0x330D,0,0,3994,4}, +{0x330E,0,0,3998,4}, +{0x330F,0,0,4002,4}, +{0x3310,0,0,4006,4}, +{0x3311,0,0,4010,4}, +{0x3312,0,0,4014,4}, +{0x3313,0,0,4018,6}, +{0x3314,0,0,4024,2}, +{0x3315,0,0,4026,6}, +{0x3316,0,0,4032,6}, +{0x3317,0,0,4038,5}, +{0x3318,0,0,4043,4}, +{0x3319,0,0,4047,6}, +{0x331A,0,0,4053,6}, +{0x331B,0,0,4059,4}, +{0x331C,0,0,4063,3}, +{0x331D,0,0,4066,3}, +{0x331E,0,0,4069,4}, +{0x331F,0,0,4073,4}, +{0x3320,0,0,4077,5}, +{0x3321,0,0,4082,5}, +{0x3322,0,0,4087,3}, +{0x3323,0,0,4090,3}, +{0x3324,0,0,4093,4}, +{0x3325,0,0,4097,3}, +{0x3326,0,0,4100,3}, +{0x3327,0,0,4103,2}, +{0x3328,0,0,4105,2}, +{0x3329,0,0,4107,3}, +{0x332A,0,0,4110,3}, +{0x332B,0,0,4113,6}, +{0x332C,0,0,4119,4}, +{0x332D,0,0,4123,5}, +{0x332E,0,0,4128,6}, +{0x332F,0,0,4134,4}, +{0x3330,0,0,4138,3}, +{0x3331,0,0,4141,3}, +{0x3332,0,0,4144,6}, +{0x3333,0,0,4150,4}, +{0x3334,0,0,4154,6}, +{0x3335,0,0,4160,3}, +{0x3336,0,0,4163,5}, +{0x3337,0,0,4168,3}, +{0x3338,0,0,4171,4}, +{0x3339,0,0,4175,3}, +{0x333A,0,0,4178,4}, +{0x333B,0,0,4182,5}, +{0x333C,0,0,4187,4}, +{0x333D,0,0,4191,5}, +{0x333E,0,0,4196,4}, +{0x333F,0,0,4200,2}, +{0x3340,0,0,4202,5}, +{0x3341,0,0,4207,3}, +{0x3342,0,0,4210,3}, +{0x3343,0,0,4213,4}, +{0x3344,0,0,4217,3}, +{0x3345,0,0,4220,3}, +{0x3346,0,0,4223,3}, +{0x3347,0,0,4226,5}, +{0x3348,0,0,4231,4}, +{0x3349,0,0,4235,2}, +{0x334A,0,0,4237,6}, +{0x334B,0,0,4243,3}, +{0x334C,0,0,4246,5}, +{0x334D,0,0,4251,4}, +{0x334E,0,0,4255,4}, +{0x334F,0,0,4259,3}, +{0x3350,0,0,4262,3}, +{0x3351,0,0,4265,4}, +{0x3352,0,0,4269,2}, +{0x3353,0,0,4271,4}, +{0x3354,0,0,4275,5}, +{0x3355,0,0,4280,2}, +{0x3356,0,0,4282,6}, +{0x3357,0,0,4288,3}, +{0x3358,0,0,4291,2}, +{0x3359,0,0,4293,2}, +{0x335A,0,0,4295,2}, +{0x335B,0,0,4297,2}, +{0x335C,0,0,4299,2}, +{0x335D,0,0,4301,2}, +{0x335E,0,0,4303,2}, +{0x335F,0,0,4305,2}, +{0x3360,0,0,4307,2}, +{0x3361,0,0,4309,2}, +{0x3362,0,0,4311,3}, +{0x3363,0,0,4314,3}, +{0x3364,0,0,4317,3}, +{0x3365,0,0,4320,3}, +{0x3366,0,0,4323,3}, +{0x3367,0,0,4326,3}, +{0x3368,0,0,4329,3}, +{0x3369,0,0,4332,3}, +{0x336A,0,0,4335,3}, +{0x336B,0,0,4338,3}, +{0x336C,0,0,4341,3}, +{0x336D,0,0,4344,3}, +{0x336E,0,0,4347,3}, +{0x336F,0,0,4350,3}, +{0x3370,0,0,4353,3}, +{0x3371,0,0,4356,3}, +{0x3372,0,0,4359,2}, +{0x3373,0,0,4361,2}, +{0x3374,0,0,4363,3}, +{0x3375,0,0,4366,2}, +{0x3376,0,0,4368,2}, +{0x3377,0,0,4370,2}, +{0x3378,0,0,4372,3}, +{0x3379,0,0,4375,3}, +{0x337A,0,0,4378,2}, +{0x337B,0,0,4380,2}, +{0x337C,0,0,4382,2}, +{0x337D,0,0,4384,2}, +{0x337E,0,0,4386,2}, +{0x337F,0,0,4388,4}, +{0x3380,0,0,4392,2}, +{0x3381,0,0,4394,2}, +{0x3382,0,0,4396,2}, +{0x3383,0,0,4398,2}, +{0x3384,0,0,4400,2}, +{0x3385,0,0,4402,2}, +{0x3386,0,0,4404,2}, +{0x3387,0,0,4406,2}, +{0x3388,0,0,4408,3}, +{0x3389,0,0,4411,4}, +{0x338A,0,0,4415,2}, +{0x338B,0,0,4417,2}, +{0x338C,0,0,4419,2}, +{0x338D,0,0,4421,2}, +{0x338E,0,0,4423,2}, +{0x338F,0,0,4425,2}, +{0x3390,0,0,4427,2}, +{0x3391,0,0,4429,3}, +{0x3392,0,0,4432,3}, +{0x3393,0,0,4435,3}, +{0x3394,0,0,4438,3}, +{0x3395,0,0,4441,2}, +{0x3396,0,0,4443,2}, +{0x3397,0,0,4445,2}, +{0x3398,0,0,4447,2}, +{0x3399,0,0,4449,2}, +{0x339A,0,0,4451,2}, +{0x339B,0,0,4453,2}, +{0x339C,0,0,4455,2}, +{0x339D,0,0,4457,2}, +{0x339E,0,0,4459,2}, +{0x339F,0,0,4461,3}, +{0x33A0,0,0,4464,3}, +{0x33A1,0,0,4467,2}, +{0x33A2,0,0,4469,3}, +{0x33A3,0,0,4472,3}, +{0x33A4,0,0,4475,3}, +{0x33A5,0,0,4478,2}, +{0x33A6,0,0,4480,3}, +{0x33A7,0,0,4483,3}, +{0x33A8,0,0,4486,4}, +{0x33A9,0,0,4490,2}, +{0x33AA,0,0,4492,3}, +{0x33AB,0,0,4495,3}, +{0x33AC,0,0,4498,3}, +{0x33AD,0,0,4501,3}, +{0x33AE,0,0,4504,5}, +{0x33AF,0,0,4509,6}, +{0x33B0,0,0,4515,2}, +{0x33B1,0,0,4517,2}, +{0x33B2,0,0,4519,2}, +{0x33B3,0,0,4521,2}, +{0x33B4,0,0,4523,2}, +{0x33B5,0,0,4525,2}, +{0x33B6,0,0,4527,2}, +{0x33B7,0,0,4529,2}, +{0x33B8,0,0,4531,2}, +{0x33B9,0,0,4533,2}, +{0x33BA,0,0,4535,2}, +{0x33BB,0,0,4537,2}, +{0x33BC,0,0,4539,2}, +{0x33BD,0,0,4541,2}, +{0x33BE,0,0,4543,2}, +{0x33BF,0,0,4545,2}, +{0x33C0,0,0,4547,2}, +{0x33C1,0,0,4549,2}, +{0x33C2,0,0,4551,4}, +{0x33C3,0,0,4555,2}, +{0x33C4,0,0,4557,2}, +{0x33C5,0,0,4559,2}, +{0x33C6,0,0,4561,4}, +{0x33C7,0,0,4565,3}, +{0x33C8,0,0,4568,2}, +{0x33C9,0,0,4570,2}, +{0x33CA,0,0,4572,2}, +{0x33CB,0,0,4574,2}, +{0x33CC,0,0,4576,2}, +{0x33CD,0,0,4578,2}, +{0x33CE,0,0,4580,2}, +{0x33CF,0,0,4582,2}, +{0x33D0,0,0,4584,2}, +{0x33D1,0,0,4586,2}, +{0x33D2,0,0,4588,3}, +{0x33D3,0,0,4591,2}, +{0x33D4,0,0,4593,2}, +{0x33D5,0,0,4595,3}, +{0x33D6,0,0,4598,3}, +{0x33D7,0,0,4601,2}, +{0x33D8,0,0,4603,4}, +{0x33D9,0,0,4607,3}, +{0x33DA,0,0,4610,2}, +{0x33DB,0,0,4612,2}, +{0x33DC,0,0,4614,2}, +{0x33DD,0,0,4616,2}, +{0x33DE,0,0,4618,3}, +{0x33DF,0,0,4621,3}, +{0x33E0,0,0,4624,2}, +{0x33E1,0,0,4626,2}, +{0x33E2,0,0,4628,2}, +{0x33E3,0,0,4630,2}, +{0x33E4,0,0,4632,2}, +{0x33E5,0,0,4634,2}, +{0x33E6,0,0,4636,2}, +{0x33E7,0,0,4638,2}, +{0x33E8,0,0,4640,2}, +{0x33E9,0,0,4642,3}, +{0x33EA,0,0,4645,3}, +{0x33EB,0,0,4648,3}, +{0x33EC,0,0,4651,3}, +{0x33ED,0,0,4654,3}, +{0x33EE,0,0,4657,3}, +{0x33EF,0,0,4660,3}, +{0x33F0,0,0,4663,3}, +{0x33F1,0,0,4666,3}, +{0x33F2,0,0,4669,3}, +{0x33F3,0,0,4672,3}, +{0x33F4,0,0,4675,3}, +{0x33F5,0,0,4678,3}, +{0x33F6,0,0,4681,3}, +{0x33F7,0,0,4684,3}, +{0x33F8,0,0,4687,3}, +{0x33F9,0,0,4690,3}, +{0x33FA,0,0,4693,3}, +{0x33FB,0,0,4696,3}, +{0x33FC,0,0,4699,3}, +{0x33FD,0,0,4702,3}, +{0x33FE,0,0,4705,3}, +{0x33FF,0,0,4708,3}, +{0xA69C,0,0,4711,1}, +{0xA69D,0,0,4712,1}, +{0xA770,0,0,4713,1}, +{0xA7F1,0,0,4714,1}, +{0xA7F2,0,0,4715,1}, +{0xA7F3,0,0,4716,1}, +{0xA7F4,0,0,4717,1}, +{0xA7F8,0,0,4718,1}, +{0xA7F9,0,0,4719,1}, +{0xAB5C,0,0,4720,1}, +{0xAB5D,0,0,4721,1}, +{0xAB5E,0,0,4722,1}, +{0xAB5F,0,0,4723,1}, +{0xAB69,0,0,4724,1}, +{0xF900,4725,1,4725,1}, +{0xF901,4726,1,4726,1}, +{0xF902,4727,1,4727,1}, +{0xF903,4728,1,4728,1}, +{0xF904,4729,1,4729,1}, +{0xF905,4730,1,4730,1}, +{0xF906,4731,1,4731,1}, +{0xF907,4732,1,4732,1}, +{0xF908,4733,1,4733,1}, +{0xF909,4734,1,4734,1}, +{0xF90A,4735,1,4735,1}, +{0xF90B,4736,1,4736,1}, +{0xF90C,4737,1,4737,1}, +{0xF90D,4738,1,4738,1}, +{0xF90E,4739,1,4739,1}, +{0xF90F,4740,1,4740,1}, +{0xF910,4741,1,4741,1}, +{0xF911,4742,1,4742,1}, +{0xF912,4743,1,4743,1}, +{0xF913,4744,1,4744,1}, +{0xF914,4745,1,4745,1}, +{0xF915,4746,1,4746,1}, +{0xF916,4747,1,4747,1}, +{0xF917,4748,1,4748,1}, +{0xF918,4749,1,4749,1}, +{0xF919,4750,1,4750,1}, +{0xF91A,4751,1,4751,1}, +{0xF91B,4752,1,4752,1}, +{0xF91C,4753,1,4753,1}, +{0xF91D,4754,1,4754,1}, +{0xF91E,4755,1,4755,1}, +{0xF91F,4756,1,4756,1}, +{0xF920,4757,1,4757,1}, +{0xF921,4758,1,4758,1}, +{0xF922,4759,1,4759,1}, +{0xF923,4760,1,4760,1}, +{0xF924,4761,1,4761,1}, +{0xF925,4762,1,4762,1}, +{0xF926,4763,1,4763,1}, +{0xF927,4764,1,4764,1}, +{0xF928,4765,1,4765,1}, +{0xF929,4766,1,4766,1}, +{0xF92A,4767,1,4767,1}, +{0xF92B,4768,1,4768,1}, +{0xF92C,4769,1,4769,1}, +{0xF92D,4770,1,4770,1}, +{0xF92E,4771,1,4771,1}, +{0xF92F,4772,1,4772,1}, +{0xF930,4773,1,4773,1}, +{0xF931,4774,1,4774,1}, +{0xF932,4775,1,4775,1}, +{0xF933,4776,1,4776,1}, +{0xF934,4777,1,4777,1}, +{0xF935,4778,1,4778,1}, +{0xF936,4779,1,4779,1}, +{0xF937,4780,1,4780,1}, +{0xF938,4781,1,4781,1}, +{0xF939,4782,1,4782,1}, +{0xF93A,4783,1,4783,1}, +{0xF93B,4784,1,4784,1}, +{0xF93C,4785,1,4785,1}, +{0xF93D,4786,1,4786,1}, +{0xF93E,4787,1,4787,1}, +{0xF93F,4788,1,4788,1}, +{0xF940,4789,1,4789,1}, +{0xF941,4790,1,4790,1}, +{0xF942,4791,1,4791,1}, +{0xF943,4792,1,4792,1}, +{0xF944,4793,1,4793,1}, +{0xF945,4794,1,4794,1}, +{0xF946,4795,1,4795,1}, +{0xF947,4796,1,4796,1}, +{0xF948,4797,1,4797,1}, +{0xF949,4798,1,4798,1}, +{0xF94A,4799,1,4799,1}, +{0xF94B,4800,1,4800,1}, +{0xF94C,4801,1,4801,1}, +{0xF94D,4802,1,4802,1}, +{0xF94E,4803,1,4803,1}, +{0xF94F,4804,1,4804,1}, +{0xF950,4805,1,4805,1}, +{0xF951,4806,1,4806,1}, +{0xF952,4807,1,4807,1}, +{0xF953,4808,1,4808,1}, +{0xF954,4809,1,4809,1}, +{0xF955,4810,1,4810,1}, +{0xF956,4811,1,4811,1}, +{0xF957,4812,1,4812,1}, +{0xF958,4813,1,4813,1}, +{0xF959,4814,1,4814,1}, +{0xF95A,4815,1,4815,1}, +{0xF95B,4816,1,4816,1}, +{0xF95C,4817,1,4817,1}, +{0xF95D,4818,1,4818,1}, +{0xF95E,4819,1,4819,1}, +{0xF95F,4820,1,4820,1}, +{0xF960,4821,1,4821,1}, +{0xF961,4822,1,4822,1}, +{0xF962,4823,1,4823,1}, +{0xF963,4824,1,4824,1}, +{0xF964,4825,1,4825,1}, +{0xF965,4826,1,4826,1}, +{0xF966,4827,1,4827,1}, +{0xF967,4828,1,4828,1}, +{0xF968,4829,1,4829,1}, +{0xF969,4830,1,4830,1}, +{0xF96A,4831,1,4831,1}, +{0xF96B,4832,1,4832,1}, +{0xF96C,4833,1,4833,1}, +{0xF96D,4834,1,4834,1}, +{0xF96E,4835,1,4835,1}, +{0xF96F,4836,1,4836,1}, +{0xF970,4837,1,4837,1}, +{0xF971,4838,1,4838,1}, +{0xF972,4839,1,4839,1}, +{0xF973,4840,1,4840,1}, +{0xF974,4841,1,4841,1}, +{0xF975,4842,1,4842,1}, +{0xF976,4843,1,4843,1}, +{0xF977,4844,1,4844,1}, +{0xF978,4845,1,4845,1}, +{0xF979,4846,1,4846,1}, +{0xF97A,4847,1,4847,1}, +{0xF97B,4848,1,4848,1}, +{0xF97C,4849,1,4849,1}, +{0xF97D,4850,1,4850,1}, +{0xF97E,4851,1,4851,1}, +{0xF97F,4852,1,4852,1}, +{0xF980,4853,1,4853,1}, +{0xF981,4854,1,4854,1}, +{0xF982,4855,1,4855,1}, +{0xF983,4856,1,4856,1}, +{0xF984,4857,1,4857,1}, +{0xF985,4858,1,4858,1}, +{0xF986,4859,1,4859,1}, +{0xF987,4860,1,4860,1}, +{0xF988,4861,1,4861,1}, +{0xF989,4862,1,4862,1}, +{0xF98A,4863,1,4863,1}, +{0xF98B,4864,1,4864,1}, +{0xF98C,4865,1,4865,1}, +{0xF98D,4866,1,4866,1}, +{0xF98E,4867,1,4867,1}, +{0xF98F,4868,1,4868,1}, +{0xF990,4869,1,4869,1}, +{0xF991,4870,1,4870,1}, +{0xF992,4871,1,4871,1}, +{0xF993,4872,1,4872,1}, +{0xF994,4873,1,4873,1}, +{0xF995,4874,1,4874,1}, +{0xF996,4875,1,4875,1}, +{0xF997,4876,1,4876,1}, +{0xF998,4877,1,4877,1}, +{0xF999,4878,1,4878,1}, +{0xF99A,4879,1,4879,1}, +{0xF99B,4880,1,4880,1}, +{0xF99C,4881,1,4881,1}, +{0xF99D,4882,1,4882,1}, +{0xF99E,4883,1,4883,1}, +{0xF99F,4884,1,4884,1}, +{0xF9A0,4885,1,4885,1}, +{0xF9A1,4886,1,4886,1}, +{0xF9A2,4887,1,4887,1}, +{0xF9A3,4888,1,4888,1}, +{0xF9A4,4889,1,4889,1}, +{0xF9A5,4890,1,4890,1}, +{0xF9A6,4891,1,4891,1}, +{0xF9A7,4892,1,4892,1}, +{0xF9A8,4893,1,4893,1}, +{0xF9A9,4894,1,4894,1}, +{0xF9AA,4895,1,4895,1}, +{0xF9AB,4896,1,4896,1}, +{0xF9AC,4897,1,4897,1}, +{0xF9AD,4898,1,4898,1}, +{0xF9AE,4899,1,4899,1}, +{0xF9AF,4900,1,4900,1}, +{0xF9B0,4901,1,4901,1}, +{0xF9B1,4902,1,4902,1}, +{0xF9B2,4903,1,4903,1}, +{0xF9B3,4904,1,4904,1}, +{0xF9B4,4905,1,4905,1}, +{0xF9B5,4906,1,4906,1}, +{0xF9B6,4907,1,4907,1}, +{0xF9B7,4908,1,4908,1}, +{0xF9B8,4909,1,4909,1}, +{0xF9B9,4910,1,4910,1}, +{0xF9BA,4911,1,4911,1}, +{0xF9BB,4912,1,4912,1}, +{0xF9BC,4913,1,4913,1}, +{0xF9BD,4914,1,4914,1}, +{0xF9BE,4915,1,4915,1}, +{0xF9BF,4916,1,4916,1}, +{0xF9C0,4917,1,4917,1}, +{0xF9C1,4918,1,4918,1}, +{0xF9C2,4919,1,4919,1}, +{0xF9C3,4920,1,4920,1}, +{0xF9C4,4921,1,4921,1}, +{0xF9C5,4922,1,4922,1}, +{0xF9C6,4923,1,4923,1}, +{0xF9C7,4924,1,4924,1}, +{0xF9C8,4925,1,4925,1}, +{0xF9C9,4926,1,4926,1}, +{0xF9CA,4927,1,4927,1}, +{0xF9CB,4928,1,4928,1}, +{0xF9CC,4929,1,4929,1}, +{0xF9CD,4930,1,4930,1}, +{0xF9CE,4931,1,4931,1}, +{0xF9CF,4932,1,4932,1}, +{0xF9D0,4933,1,4933,1}, +{0xF9D1,4934,1,4934,1}, +{0xF9D2,4935,1,4935,1}, +{0xF9D3,4936,1,4936,1}, +{0xF9D4,4937,1,4937,1}, +{0xF9D5,4938,1,4938,1}, +{0xF9D6,4939,1,4939,1}, +{0xF9D7,4940,1,4940,1}, +{0xF9D8,4941,1,4941,1}, +{0xF9D9,4942,1,4942,1}, +{0xF9DA,4943,1,4943,1}, +{0xF9DB,4944,1,4944,1}, +{0xF9DC,4945,1,4945,1}, +{0xF9DD,4946,1,4946,1}, +{0xF9DE,4947,1,4947,1}, +{0xF9DF,4948,1,4948,1}, +{0xF9E0,4949,1,4949,1}, +{0xF9E1,4950,1,4950,1}, +{0xF9E2,4951,1,4951,1}, +{0xF9E3,4952,1,4952,1}, +{0xF9E4,4953,1,4953,1}, +{0xF9E5,4954,1,4954,1}, +{0xF9E6,4955,1,4955,1}, +{0xF9E7,4956,1,4956,1}, +{0xF9E8,4957,1,4957,1}, +{0xF9E9,4958,1,4958,1}, +{0xF9EA,4959,1,4959,1}, +{0xF9EB,4960,1,4960,1}, +{0xF9EC,4961,1,4961,1}, +{0xF9ED,4962,1,4962,1}, +{0xF9EE,4963,1,4963,1}, +{0xF9EF,4964,1,4964,1}, +{0xF9F0,4965,1,4965,1}, +{0xF9F1,4966,1,4966,1}, +{0xF9F2,4967,1,4967,1}, +{0xF9F3,4968,1,4968,1}, +{0xF9F4,4969,1,4969,1}, +{0xF9F5,4970,1,4970,1}, +{0xF9F6,4971,1,4971,1}, +{0xF9F7,4972,1,4972,1}, +{0xF9F8,4973,1,4973,1}, +{0xF9F9,4974,1,4974,1}, +{0xF9FA,4975,1,4975,1}, +{0xF9FB,4976,1,4976,1}, +{0xF9FC,4977,1,4977,1}, +{0xF9FD,4978,1,4978,1}, +{0xF9FE,4979,1,4979,1}, +{0xF9FF,4980,1,4980,1}, +{0xFA00,4981,1,4981,1}, +{0xFA01,4982,1,4982,1}, +{0xFA02,4983,1,4983,1}, +{0xFA03,4984,1,4984,1}, +{0xFA04,4985,1,4985,1}, +{0xFA05,4986,1,4986,1}, +{0xFA06,4987,1,4987,1}, +{0xFA07,4988,1,4988,1}, +{0xFA08,4989,1,4989,1}, +{0xFA09,4990,1,4990,1}, +{0xFA0A,4991,1,4991,1}, +{0xFA0B,4992,1,4992,1}, +{0xFA0C,4993,1,4993,1}, +{0xFA0D,4994,1,4994,1}, +{0xFA10,4995,1,4995,1}, +{0xFA12,4996,1,4996,1}, +{0xFA15,4997,1,4997,1}, +{0xFA16,4998,1,4998,1}, +{0xFA17,4999,1,4999,1}, +{0xFA18,5000,1,5000,1}, +{0xFA19,5001,1,5001,1}, +{0xFA1A,5002,1,5002,1}, +{0xFA1B,5003,1,5003,1}, +{0xFA1C,5004,1,5004,1}, +{0xFA1D,5005,1,5005,1}, +{0xFA1E,5006,1,5006,1}, +{0xFA20,5007,1,5007,1}, +{0xFA22,5008,1,5008,1}, +{0xFA25,5009,1,5009,1}, +{0xFA26,5010,1,5010,1}, +{0xFA2A,5011,1,5011,1}, +{0xFA2B,5012,1,5012,1}, +{0xFA2C,5013,1,5013,1}, +{0xFA2D,5014,1,5014,1}, +{0xFA2E,5015,1,5015,1}, +{0xFA2F,5016,1,5016,1}, +{0xFA30,5017,1,5017,1}, +{0xFA31,5018,1,5018,1}, +{0xFA32,5019,1,5019,1}, +{0xFA33,5020,1,5020,1}, +{0xFA34,5021,1,5021,1}, +{0xFA35,5022,1,5022,1}, +{0xFA36,5023,1,5023,1}, +{0xFA37,5024,1,5024,1}, +{0xFA38,5025,1,5025,1}, +{0xFA39,5026,1,5026,1}, +{0xFA3A,5027,1,5027,1}, +{0xFA3B,5028,1,5028,1}, +{0xFA3C,5029,1,5029,1}, +{0xFA3D,5030,1,5030,1}, +{0xFA3E,5031,1,5031,1}, +{0xFA3F,5032,1,5032,1}, +{0xFA40,5033,1,5033,1}, +{0xFA41,5034,1,5034,1}, +{0xFA42,5035,1,5035,1}, +{0xFA43,5036,1,5036,1}, +{0xFA44,5037,1,5037,1}, +{0xFA45,5038,1,5038,1}, +{0xFA46,5039,1,5039,1}, +{0xFA47,5040,1,5040,1}, +{0xFA48,5041,1,5041,1}, +{0xFA49,5042,1,5042,1}, +{0xFA4A,5043,1,5043,1}, +{0xFA4B,5044,1,5044,1}, +{0xFA4C,5045,1,5045,1}, +{0xFA4D,5046,1,5046,1}, +{0xFA4E,5047,1,5047,1}, +{0xFA4F,5048,1,5048,1}, +{0xFA50,5049,1,5049,1}, +{0xFA51,5050,1,5050,1}, +{0xFA52,5051,1,5051,1}, +{0xFA53,5052,1,5052,1}, +{0xFA54,5053,1,5053,1}, +{0xFA55,5054,1,5054,1}, +{0xFA56,5055,1,5055,1}, +{0xFA57,5056,1,5056,1}, +{0xFA58,5057,1,5057,1}, +{0xFA59,5058,1,5058,1}, +{0xFA5A,5059,1,5059,1}, +{0xFA5B,5060,1,5060,1}, +{0xFA5C,5061,1,5061,1}, +{0xFA5D,5062,1,5062,1}, +{0xFA5E,5063,1,5063,1}, +{0xFA5F,5064,1,5064,1}, +{0xFA60,5065,1,5065,1}, +{0xFA61,5066,1,5066,1}, +{0xFA62,5067,1,5067,1}, +{0xFA63,5068,1,5068,1}, +{0xFA64,5069,1,5069,1}, +{0xFA65,5070,1,5070,1}, +{0xFA66,5071,1,5071,1}, +{0xFA67,5072,1,5072,1}, +{0xFA68,5073,1,5073,1}, +{0xFA69,5074,1,5074,1}, +{0xFA6A,5075,1,5075,1}, +{0xFA6B,5076,1,5076,1}, +{0xFA6C,5077,1,5077,1}, +{0xFA6D,5078,1,5078,1}, +{0xFA70,5079,1,5079,1}, +{0xFA71,5080,1,5080,1}, +{0xFA72,5081,1,5081,1}, +{0xFA73,5082,1,5082,1}, +{0xFA74,5083,1,5083,1}, +{0xFA75,5084,1,5084,1}, +{0xFA76,5085,1,5085,1}, +{0xFA77,5086,1,5086,1}, +{0xFA78,5087,1,5087,1}, +{0xFA79,5088,1,5088,1}, +{0xFA7A,5089,1,5089,1}, +{0xFA7B,5090,1,5090,1}, +{0xFA7C,5091,1,5091,1}, +{0xFA7D,5092,1,5092,1}, +{0xFA7E,5093,1,5093,1}, +{0xFA7F,5094,1,5094,1}, +{0xFA80,5095,1,5095,1}, +{0xFA81,5096,1,5096,1}, +{0xFA82,5097,1,5097,1}, +{0xFA83,5098,1,5098,1}, +{0xFA84,5099,1,5099,1}, +{0xFA85,5100,1,5100,1}, +{0xFA86,5101,1,5101,1}, +{0xFA87,5102,1,5102,1}, +{0xFA88,5103,1,5103,1}, +{0xFA89,5104,1,5104,1}, +{0xFA8A,5105,1,5105,1}, +{0xFA8B,5106,1,5106,1}, +{0xFA8C,5107,1,5107,1}, +{0xFA8D,5108,1,5108,1}, +{0xFA8E,5109,1,5109,1}, +{0xFA8F,5110,1,5110,1}, +{0xFA90,5111,1,5111,1}, +{0xFA91,5112,1,5112,1}, +{0xFA92,5113,1,5113,1}, +{0xFA93,5114,1,5114,1}, +{0xFA94,5115,1,5115,1}, +{0xFA95,5116,1,5116,1}, +{0xFA96,5117,1,5117,1}, +{0xFA97,5118,1,5118,1}, +{0xFA98,5119,1,5119,1}, +{0xFA99,5120,1,5120,1}, +{0xFA9A,5121,1,5121,1}, +{0xFA9B,5122,1,5122,1}, +{0xFA9C,5123,1,5123,1}, +{0xFA9D,5124,1,5124,1}, +{0xFA9E,5125,1,5125,1}, +{0xFA9F,5126,1,5126,1}, +{0xFAA0,5127,1,5127,1}, +{0xFAA1,5128,1,5128,1}, +{0xFAA2,5129,1,5129,1}, +{0xFAA3,5130,1,5130,1}, +{0xFAA4,5131,1,5131,1}, +{0xFAA5,5132,1,5132,1}, +{0xFAA6,5133,1,5133,1}, +{0xFAA7,5134,1,5134,1}, +{0xFAA8,5135,1,5135,1}, +{0xFAA9,5136,1,5136,1}, +{0xFAAA,5137,1,5137,1}, +{0xFAAB,5138,1,5138,1}, +{0xFAAC,5139,1,5139,1}, +{0xFAAD,5140,1,5140,1}, +{0xFAAE,5141,1,5141,1}, +{0xFAAF,5142,1,5142,1}, +{0xFAB0,5143,1,5143,1}, +{0xFAB1,5144,1,5144,1}, +{0xFAB2,5145,1,5145,1}, +{0xFAB3,5146,1,5146,1}, +{0xFAB4,5147,1,5147,1}, +{0xFAB5,5148,1,5148,1}, +{0xFAB6,5149,1,5149,1}, +{0xFAB7,5150,1,5150,1}, +{0xFAB8,5151,1,5151,1}, +{0xFAB9,5152,1,5152,1}, +{0xFABA,5153,1,5153,1}, +{0xFABB,5154,1,5154,1}, +{0xFABC,5155,1,5155,1}, +{0xFABD,5156,1,5156,1}, +{0xFABE,5157,1,5157,1}, +{0xFABF,5158,1,5158,1}, +{0xFAC0,5159,1,5159,1}, +{0xFAC1,5160,1,5160,1}, +{0xFAC2,5161,1,5161,1}, +{0xFAC3,5162,1,5162,1}, +{0xFAC4,5163,1,5163,1}, +{0xFAC5,5164,1,5164,1}, +{0xFAC6,5165,1,5165,1}, +{0xFAC7,5166,1,5166,1}, +{0xFAC8,5167,1,5167,1}, +{0xFAC9,5168,1,5168,1}, +{0xFACA,5169,1,5169,1}, +{0xFACB,5170,1,5170,1}, +{0xFACC,5171,1,5171,1}, +{0xFACD,5172,1,5172,1}, +{0xFACE,5173,1,5173,1}, +{0xFACF,5174,1,5174,1}, +{0xFAD0,5175,1,5175,1}, +{0xFAD1,5176,1,5176,1}, +{0xFAD2,5177,1,5177,1}, +{0xFAD3,5178,1,5178,1}, +{0xFAD4,5179,1,5179,1}, +{0xFAD5,5180,1,5180,1}, +{0xFAD6,5181,1,5181,1}, +{0xFAD7,5182,1,5182,1}, +{0xFAD8,5183,1,5183,1}, +{0xFAD9,5184,1,5184,1}, +{0xFB00,0,0,5185,2}, +{0xFB01,0,0,5187,2}, +{0xFB02,0,0,5189,2}, +{0xFB03,0,0,5191,3}, +{0xFB04,0,0,5194,3}, +{0xFB05,0,0,5197,2}, +{0xFB06,0,0,5199,2}, +{0xFB13,0,0,5201,2}, +{0xFB14,0,0,5203,2}, +{0xFB15,0,0,5205,2}, +{0xFB16,0,0,5207,2}, +{0xFB17,0,0,5209,2}, +{0xFB1D,5211,2,5211,2}, +{0xFB1F,5213,2,5213,2}, +{0xFB20,0,0,5215,1}, +{0xFB21,0,0,5216,1}, +{0xFB22,0,0,5217,1}, +{0xFB23,0,0,5218,1}, +{0xFB24,0,0,5219,1}, +{0xFB25,0,0,5220,1}, +{0xFB26,0,0,5221,1}, +{0xFB27,0,0,5222,1}, +{0xFB28,0,0,5223,1}, +{0xFB29,0,0,5224,1}, +{0xFB2A,5225,2,5225,2}, +{0xFB2B,5227,2,5227,2}, +{0xFB2C,5229,3,5229,3}, +{0xFB2D,5232,3,5232,3}, +{0xFB2E,5235,2,5235,2}, +{0xFB2F,5237,2,5237,2}, +{0xFB30,5239,2,5239,2}, +{0xFB31,5241,2,5241,2}, +{0xFB32,5243,2,5243,2}, +{0xFB33,5245,2,5245,2}, +{0xFB34,5247,2,5247,2}, +{0xFB35,5249,2,5249,2}, +{0xFB36,5251,2,5251,2}, +{0xFB38,5253,2,5253,2}, +{0xFB39,5255,2,5255,2}, +{0xFB3A,5257,2,5257,2}, +{0xFB3B,5259,2,5259,2}, +{0xFB3C,5261,2,5261,2}, +{0xFB3E,5263,2,5263,2}, +{0xFB40,5265,2,5265,2}, +{0xFB41,5267,2,5267,2}, +{0xFB43,5269,2,5269,2}, +{0xFB44,5271,2,5271,2}, +{0xFB46,5273,2,5273,2}, +{0xFB47,5275,2,5275,2}, +{0xFB48,5277,2,5277,2}, +{0xFB49,5279,2,5279,2}, +{0xFB4A,5281,2,5281,2}, +{0xFB4B,5283,2,5283,2}, +{0xFB4C,5285,2,5285,2}, +{0xFB4D,5287,2,5287,2}, +{0xFB4E,5289,2,5289,2}, +{0xFB4F,0,0,5291,2}, +{0xFB50,0,0,5293,1}, +{0xFB51,0,0,5294,1}, +{0xFB52,0,0,5295,1}, +{0xFB53,0,0,5296,1}, +{0xFB54,0,0,5297,1}, +{0xFB55,0,0,5298,1}, +{0xFB56,0,0,5299,1}, +{0xFB57,0,0,5300,1}, +{0xFB58,0,0,5301,1}, +{0xFB59,0,0,5302,1}, +{0xFB5A,0,0,5303,1}, +{0xFB5B,0,0,5304,1}, +{0xFB5C,0,0,5305,1}, +{0xFB5D,0,0,5306,1}, +{0xFB5E,0,0,5307,1}, +{0xFB5F,0,0,5308,1}, +{0xFB60,0,0,5309,1}, +{0xFB61,0,0,5310,1}, +{0xFB62,0,0,5311,1}, +{0xFB63,0,0,5312,1}, +{0xFB64,0,0,5313,1}, +{0xFB65,0,0,5314,1}, +{0xFB66,0,0,5315,1}, +{0xFB67,0,0,5316,1}, +{0xFB68,0,0,5317,1}, +{0xFB69,0,0,5318,1}, +{0xFB6A,0,0,5319,1}, +{0xFB6B,0,0,5320,1}, +{0xFB6C,0,0,5321,1}, +{0xFB6D,0,0,5322,1}, +{0xFB6E,0,0,5323,1}, +{0xFB6F,0,0,5324,1}, +{0xFB70,0,0,5325,1}, +{0xFB71,0,0,5326,1}, +{0xFB72,0,0,5327,1}, +{0xFB73,0,0,5328,1}, +{0xFB74,0,0,5329,1}, +{0xFB75,0,0,5330,1}, +{0xFB76,0,0,5331,1}, +{0xFB77,0,0,5332,1}, +{0xFB78,0,0,5333,1}, +{0xFB79,0,0,5334,1}, +{0xFB7A,0,0,5335,1}, +{0xFB7B,0,0,5336,1}, +{0xFB7C,0,0,5337,1}, +{0xFB7D,0,0,5338,1}, +{0xFB7E,0,0,5339,1}, +{0xFB7F,0,0,5340,1}, +{0xFB80,0,0,5341,1}, +{0xFB81,0,0,5342,1}, +{0xFB82,0,0,5343,1}, +{0xFB83,0,0,5344,1}, +{0xFB84,0,0,5345,1}, +{0xFB85,0,0,5346,1}, +{0xFB86,0,0,5347,1}, +{0xFB87,0,0,5348,1}, +{0xFB88,0,0,5349,1}, +{0xFB89,0,0,5350,1}, +{0xFB8A,0,0,5351,1}, +{0xFB8B,0,0,5352,1}, +{0xFB8C,0,0,5353,1}, +{0xFB8D,0,0,5354,1}, +{0xFB8E,0,0,5355,1}, +{0xFB8F,0,0,5356,1}, +{0xFB90,0,0,5357,1}, +{0xFB91,0,0,5358,1}, +{0xFB92,0,0,5359,1}, +{0xFB93,0,0,5360,1}, +{0xFB94,0,0,5361,1}, +{0xFB95,0,0,5362,1}, +{0xFB96,0,0,5363,1}, +{0xFB97,0,0,5364,1}, +{0xFB98,0,0,5365,1}, +{0xFB99,0,0,5366,1}, +{0xFB9A,0,0,5367,1}, +{0xFB9B,0,0,5368,1}, +{0xFB9C,0,0,5369,1}, +{0xFB9D,0,0,5370,1}, +{0xFB9E,0,0,5371,1}, +{0xFB9F,0,0,5372,1}, +{0xFBA0,0,0,5373,1}, +{0xFBA1,0,0,5374,1}, +{0xFBA2,0,0,5375,1}, +{0xFBA3,0,0,5376,1}, +{0xFBA4,0,0,5377,2}, +{0xFBA5,0,0,5379,2}, +{0xFBA6,0,0,5381,1}, +{0xFBA7,0,0,5382,1}, +{0xFBA8,0,0,5383,1}, +{0xFBA9,0,0,5384,1}, +{0xFBAA,0,0,5385,1}, +{0xFBAB,0,0,5386,1}, +{0xFBAC,0,0,5387,1}, +{0xFBAD,0,0,5388,1}, +{0xFBAE,0,0,5389,1}, +{0xFBAF,0,0,5390,1}, +{0xFBB0,0,0,5391,2}, +{0xFBB1,0,0,5393,2}, +{0xFBD3,0,0,5395,1}, +{0xFBD4,0,0,5396,1}, +{0xFBD5,0,0,5397,1}, +{0xFBD6,0,0,5398,1}, +{0xFBD7,0,0,5399,1}, +{0xFBD8,0,0,5400,1}, +{0xFBD9,0,0,5401,1}, +{0xFBDA,0,0,5402,1}, +{0xFBDB,0,0,5403,1}, +{0xFBDC,0,0,5404,1}, +{0xFBDD,0,0,5405,2}, +{0xFBDE,0,0,5407,1}, +{0xFBDF,0,0,5408,1}, +{0xFBE0,0,0,5409,1}, +{0xFBE1,0,0,5410,1}, +{0xFBE2,0,0,5411,1}, +{0xFBE3,0,0,5412,1}, +{0xFBE4,0,0,5413,1}, +{0xFBE5,0,0,5414,1}, +{0xFBE6,0,0,5415,1}, +{0xFBE7,0,0,5416,1}, +{0xFBE8,0,0,5417,1}, +{0xFBE9,0,0,5418,1}, +{0xFBEA,0,0,5419,3}, +{0xFBEB,0,0,5422,3}, +{0xFBEC,0,0,5425,3}, +{0xFBED,0,0,5428,3}, +{0xFBEE,0,0,5431,3}, +{0xFBEF,0,0,5434,3}, +{0xFBF0,0,0,5437,3}, +{0xFBF1,0,0,5440,3}, +{0xFBF2,0,0,5443,3}, +{0xFBF3,0,0,5446,3}, +{0xFBF4,0,0,5449,3}, +{0xFBF5,0,0,5452,3}, +{0xFBF6,0,0,5455,3}, +{0xFBF7,0,0,5458,3}, +{0xFBF8,0,0,5461,3}, +{0xFBF9,0,0,5464,3}, +{0xFBFA,0,0,5467,3}, +{0xFBFB,0,0,5470,3}, +{0xFBFC,0,0,5473,1}, +{0xFBFD,0,0,5474,1}, +{0xFBFE,0,0,5475,1}, +{0xFBFF,0,0,5476,1}, +{0xFC00,0,0,5477,3}, +{0xFC01,0,0,5480,3}, +{0xFC02,0,0,5483,3}, +{0xFC03,0,0,5486,3}, +{0xFC04,0,0,5489,3}, +{0xFC05,0,0,5492,2}, +{0xFC06,0,0,5494,2}, +{0xFC07,0,0,5496,2}, +{0xFC08,0,0,5498,2}, +{0xFC09,0,0,5500,2}, +{0xFC0A,0,0,5502,2}, +{0xFC0B,0,0,5504,2}, +{0xFC0C,0,0,5506,2}, +{0xFC0D,0,0,5508,2}, +{0xFC0E,0,0,5510,2}, +{0xFC0F,0,0,5512,2}, +{0xFC10,0,0,5514,2}, +{0xFC11,0,0,5516,2}, +{0xFC12,0,0,5518,2}, +{0xFC13,0,0,5520,2}, +{0xFC14,0,0,5522,2}, +{0xFC15,0,0,5524,2}, +{0xFC16,0,0,5526,2}, +{0xFC17,0,0,5528,2}, +{0xFC18,0,0,5530,2}, +{0xFC19,0,0,5532,2}, +{0xFC1A,0,0,5534,2}, +{0xFC1B,0,0,5536,2}, +{0xFC1C,0,0,5538,2}, +{0xFC1D,0,0,5540,2}, +{0xFC1E,0,0,5542,2}, +{0xFC1F,0,0,5544,2}, +{0xFC20,0,0,5546,2}, +{0xFC21,0,0,5548,2}, +{0xFC22,0,0,5550,2}, +{0xFC23,0,0,5552,2}, +{0xFC24,0,0,5554,2}, +{0xFC25,0,0,5556,2}, +{0xFC26,0,0,5558,2}, +{0xFC27,0,0,5560,2}, +{0xFC28,0,0,5562,2}, +{0xFC29,0,0,5564,2}, +{0xFC2A,0,0,5566,2}, +{0xFC2B,0,0,5568,2}, +{0xFC2C,0,0,5570,2}, +{0xFC2D,0,0,5572,2}, +{0xFC2E,0,0,5574,2}, +{0xFC2F,0,0,5576,2}, +{0xFC30,0,0,5578,2}, +{0xFC31,0,0,5580,2}, +{0xFC32,0,0,5582,2}, +{0xFC33,0,0,5584,2}, +{0xFC34,0,0,5586,2}, +{0xFC35,0,0,5588,2}, +{0xFC36,0,0,5590,2}, +{0xFC37,0,0,5592,2}, +{0xFC38,0,0,5594,2}, +{0xFC39,0,0,5596,2}, +{0xFC3A,0,0,5598,2}, +{0xFC3B,0,0,5600,2}, +{0xFC3C,0,0,5602,2}, +{0xFC3D,0,0,5604,2}, +{0xFC3E,0,0,5606,2}, +{0xFC3F,0,0,5608,2}, +{0xFC40,0,0,5610,2}, +{0xFC41,0,0,5612,2}, +{0xFC42,0,0,5614,2}, +{0xFC43,0,0,5616,2}, +{0xFC44,0,0,5618,2}, +{0xFC45,0,0,5620,2}, +{0xFC46,0,0,5622,2}, +{0xFC47,0,0,5624,2}, +{0xFC48,0,0,5626,2}, +{0xFC49,0,0,5628,2}, +{0xFC4A,0,0,5630,2}, +{0xFC4B,0,0,5632,2}, +{0xFC4C,0,0,5634,2}, +{0xFC4D,0,0,5636,2}, +{0xFC4E,0,0,5638,2}, +{0xFC4F,0,0,5640,2}, +{0xFC50,0,0,5642,2}, +{0xFC51,0,0,5644,2}, +{0xFC52,0,0,5646,2}, +{0xFC53,0,0,5648,2}, +{0xFC54,0,0,5650,2}, +{0xFC55,0,0,5652,2}, +{0xFC56,0,0,5654,2}, +{0xFC57,0,0,5656,2}, +{0xFC58,0,0,5658,2}, +{0xFC59,0,0,5660,2}, +{0xFC5A,0,0,5662,2}, +{0xFC5B,0,0,5664,2}, +{0xFC5C,0,0,5666,2}, +{0xFC5D,0,0,5668,2}, +{0xFC5E,0,0,5670,3}, +{0xFC5F,0,0,5673,3}, +{0xFC60,0,0,5676,3}, +{0xFC61,0,0,5679,3}, +{0xFC62,0,0,5682,3}, +{0xFC63,0,0,5685,3}, +{0xFC64,0,0,5688,3}, +{0xFC65,0,0,5691,3}, +{0xFC66,0,0,5694,3}, +{0xFC67,0,0,5697,3}, +{0xFC68,0,0,5700,3}, +{0xFC69,0,0,5703,3}, +{0xFC6A,0,0,5706,2}, +{0xFC6B,0,0,5708,2}, +{0xFC6C,0,0,5710,2}, +{0xFC6D,0,0,5712,2}, +{0xFC6E,0,0,5714,2}, +{0xFC6F,0,0,5716,2}, +{0xFC70,0,0,5718,2}, +{0xFC71,0,0,5720,2}, +{0xFC72,0,0,5722,2}, +{0xFC73,0,0,5724,2}, +{0xFC74,0,0,5726,2}, +{0xFC75,0,0,5728,2}, +{0xFC76,0,0,5730,2}, +{0xFC77,0,0,5732,2}, +{0xFC78,0,0,5734,2}, +{0xFC79,0,0,5736,2}, +{0xFC7A,0,0,5738,2}, +{0xFC7B,0,0,5740,2}, +{0xFC7C,0,0,5742,2}, +{0xFC7D,0,0,5744,2}, +{0xFC7E,0,0,5746,2}, +{0xFC7F,0,0,5748,2}, +{0xFC80,0,0,5750,2}, +{0xFC81,0,0,5752,2}, +{0xFC82,0,0,5754,2}, +{0xFC83,0,0,5756,2}, +{0xFC84,0,0,5758,2}, +{0xFC85,0,0,5760,2}, +{0xFC86,0,0,5762,2}, +{0xFC87,0,0,5764,2}, +{0xFC88,0,0,5766,2}, +{0xFC89,0,0,5768,2}, +{0xFC8A,0,0,5770,2}, +{0xFC8B,0,0,5772,2}, +{0xFC8C,0,0,5774,2}, +{0xFC8D,0,0,5776,2}, +{0xFC8E,0,0,5778,2}, +{0xFC8F,0,0,5780,2}, +{0xFC90,0,0,5782,2}, +{0xFC91,0,0,5784,2}, +{0xFC92,0,0,5786,2}, +{0xFC93,0,0,5788,2}, +{0xFC94,0,0,5790,2}, +{0xFC95,0,0,5792,2}, +{0xFC96,0,0,5794,2}, +{0xFC97,0,0,5796,3}, +{0xFC98,0,0,5799,3}, +{0xFC99,0,0,5802,3}, +{0xFC9A,0,0,5805,3}, +{0xFC9B,0,0,5808,3}, +{0xFC9C,0,0,5811,2}, +{0xFC9D,0,0,5813,2}, +{0xFC9E,0,0,5815,2}, +{0xFC9F,0,0,5817,2}, +{0xFCA0,0,0,5819,2}, +{0xFCA1,0,0,5821,2}, +{0xFCA2,0,0,5823,2}, +{0xFCA3,0,0,5825,2}, +{0xFCA4,0,0,5827,2}, +{0xFCA5,0,0,5829,2}, +{0xFCA6,0,0,5831,2}, +{0xFCA7,0,0,5833,2}, +{0xFCA8,0,0,5835,2}, +{0xFCA9,0,0,5837,2}, +{0xFCAA,0,0,5839,2}, +{0xFCAB,0,0,5841,2}, +{0xFCAC,0,0,5843,2}, +{0xFCAD,0,0,5845,2}, +{0xFCAE,0,0,5847,2}, +{0xFCAF,0,0,5849,2}, +{0xFCB0,0,0,5851,2}, +{0xFCB1,0,0,5853,2}, +{0xFCB2,0,0,5855,2}, +{0xFCB3,0,0,5857,2}, +{0xFCB4,0,0,5859,2}, +{0xFCB5,0,0,5861,2}, +{0xFCB6,0,0,5863,2}, +{0xFCB7,0,0,5865,2}, +{0xFCB8,0,0,5867,2}, +{0xFCB9,0,0,5869,2}, +{0xFCBA,0,0,5871,2}, +{0xFCBB,0,0,5873,2}, +{0xFCBC,0,0,5875,2}, +{0xFCBD,0,0,5877,2}, +{0xFCBE,0,0,5879,2}, +{0xFCBF,0,0,5881,2}, +{0xFCC0,0,0,5883,2}, +{0xFCC1,0,0,5885,2}, +{0xFCC2,0,0,5887,2}, +{0xFCC3,0,0,5889,2}, +{0xFCC4,0,0,5891,2}, +{0xFCC5,0,0,5893,2}, +{0xFCC6,0,0,5895,2}, +{0xFCC7,0,0,5897,2}, +{0xFCC8,0,0,5899,2}, +{0xFCC9,0,0,5901,2}, +{0xFCCA,0,0,5903,2}, +{0xFCCB,0,0,5905,2}, +{0xFCCC,0,0,5907,2}, +{0xFCCD,0,0,5909,2}, +{0xFCCE,0,0,5911,2}, +{0xFCCF,0,0,5913,2}, +{0xFCD0,0,0,5915,2}, +{0xFCD1,0,0,5917,2}, +{0xFCD2,0,0,5919,2}, +{0xFCD3,0,0,5921,2}, +{0xFCD4,0,0,5923,2}, +{0xFCD5,0,0,5925,2}, +{0xFCD6,0,0,5927,2}, +{0xFCD7,0,0,5929,2}, +{0xFCD8,0,0,5931,2}, +{0xFCD9,0,0,5933,2}, +{0xFCDA,0,0,5935,2}, +{0xFCDB,0,0,5937,2}, +{0xFCDC,0,0,5939,2}, +{0xFCDD,0,0,5941,2}, +{0xFCDE,0,0,5943,2}, +{0xFCDF,0,0,5945,3}, +{0xFCE0,0,0,5948,3}, +{0xFCE1,0,0,5951,2}, +{0xFCE2,0,0,5953,2}, +{0xFCE3,0,0,5955,2}, +{0xFCE4,0,0,5957,2}, +{0xFCE5,0,0,5959,2}, +{0xFCE6,0,0,5961,2}, +{0xFCE7,0,0,5963,2}, +{0xFCE8,0,0,5965,2}, +{0xFCE9,0,0,5967,2}, +{0xFCEA,0,0,5969,2}, +{0xFCEB,0,0,5971,2}, +{0xFCEC,0,0,5973,2}, +{0xFCED,0,0,5975,2}, +{0xFCEE,0,0,5977,2}, +{0xFCEF,0,0,5979,2}, +{0xFCF0,0,0,5981,2}, +{0xFCF1,0,0,5983,2}, +{0xFCF2,0,0,5985,3}, +{0xFCF3,0,0,5988,3}, +{0xFCF4,0,0,5991,3}, +{0xFCF5,0,0,5994,2}, +{0xFCF6,0,0,5996,2}, +{0xFCF7,0,0,5998,2}, +{0xFCF8,0,0,6000,2}, +{0xFCF9,0,0,6002,2}, +{0xFCFA,0,0,6004,2}, +{0xFCFB,0,0,6006,2}, +{0xFCFC,0,0,6008,2}, +{0xFCFD,0,0,6010,2}, +{0xFCFE,0,0,6012,2}, +{0xFCFF,0,0,6014,2}, +{0xFD00,0,0,6016,2}, +{0xFD01,0,0,6018,2}, +{0xFD02,0,0,6020,2}, +{0xFD03,0,0,6022,2}, +{0xFD04,0,0,6024,2}, +{0xFD05,0,0,6026,2}, +{0xFD06,0,0,6028,2}, +{0xFD07,0,0,6030,2}, +{0xFD08,0,0,6032,2}, +{0xFD09,0,0,6034,2}, +{0xFD0A,0,0,6036,2}, +{0xFD0B,0,0,6038,2}, +{0xFD0C,0,0,6040,2}, +{0xFD0D,0,0,6042,2}, +{0xFD0E,0,0,6044,2}, +{0xFD0F,0,0,6046,2}, +{0xFD10,0,0,6048,2}, +{0xFD11,0,0,6050,2}, +{0xFD12,0,0,6052,2}, +{0xFD13,0,0,6054,2}, +{0xFD14,0,0,6056,2}, +{0xFD15,0,0,6058,2}, +{0xFD16,0,0,6060,2}, +{0xFD17,0,0,6062,2}, +{0xFD18,0,0,6064,2}, +{0xFD19,0,0,6066,2}, +{0xFD1A,0,0,6068,2}, +{0xFD1B,0,0,6070,2}, +{0xFD1C,0,0,6072,2}, +{0xFD1D,0,0,6074,2}, +{0xFD1E,0,0,6076,2}, +{0xFD1F,0,0,6078,2}, +{0xFD20,0,0,6080,2}, +{0xFD21,0,0,6082,2}, +{0xFD22,0,0,6084,2}, +{0xFD23,0,0,6086,2}, +{0xFD24,0,0,6088,2}, +{0xFD25,0,0,6090,2}, +{0xFD26,0,0,6092,2}, +{0xFD27,0,0,6094,2}, +{0xFD28,0,0,6096,2}, +{0xFD29,0,0,6098,2}, +{0xFD2A,0,0,6100,2}, +{0xFD2B,0,0,6102,2}, +{0xFD2C,0,0,6104,2}, +{0xFD2D,0,0,6106,2}, +{0xFD2E,0,0,6108,2}, +{0xFD2F,0,0,6110,2}, +{0xFD30,0,0,6112,2}, +{0xFD31,0,0,6114,2}, +{0xFD32,0,0,6116,2}, +{0xFD33,0,0,6118,2}, +{0xFD34,0,0,6120,2}, +{0xFD35,0,0,6122,2}, +{0xFD36,0,0,6124,2}, +{0xFD37,0,0,6126,2}, +{0xFD38,0,0,6128,2}, +{0xFD39,0,0,6130,2}, +{0xFD3A,0,0,6132,2}, +{0xFD3B,0,0,6134,2}, +{0xFD3C,0,0,6136,2}, +{0xFD3D,0,0,6138,2}, +{0xFD50,0,0,6140,3}, +{0xFD51,0,0,6143,3}, +{0xFD52,0,0,6146,3}, +{0xFD53,0,0,6149,3}, +{0xFD54,0,0,6152,3}, +{0xFD55,0,0,6155,3}, +{0xFD56,0,0,6158,3}, +{0xFD57,0,0,6161,3}, +{0xFD58,0,0,6164,3}, +{0xFD59,0,0,6167,3}, +{0xFD5A,0,0,6170,3}, +{0xFD5B,0,0,6173,3}, +{0xFD5C,0,0,6176,3}, +{0xFD5D,0,0,6179,3}, +{0xFD5E,0,0,6182,3}, +{0xFD5F,0,0,6185,3}, +{0xFD60,0,0,6188,3}, +{0xFD61,0,0,6191,3}, +{0xFD62,0,0,6194,3}, +{0xFD63,0,0,6197,3}, +{0xFD64,0,0,6200,3}, +{0xFD65,0,0,6203,3}, +{0xFD66,0,0,6206,3}, +{0xFD67,0,0,6209,3}, +{0xFD68,0,0,6212,3}, +{0xFD69,0,0,6215,3}, +{0xFD6A,0,0,6218,3}, +{0xFD6B,0,0,6221,3}, +{0xFD6C,0,0,6224,3}, +{0xFD6D,0,0,6227,3}, +{0xFD6E,0,0,6230,3}, +{0xFD6F,0,0,6233,3}, +{0xFD70,0,0,6236,3}, +{0xFD71,0,0,6239,3}, +{0xFD72,0,0,6242,3}, +{0xFD73,0,0,6245,3}, +{0xFD74,0,0,6248,3}, +{0xFD75,0,0,6251,3}, +{0xFD76,0,0,6254,3}, +{0xFD77,0,0,6257,3}, +{0xFD78,0,0,6260,3}, +{0xFD79,0,0,6263,3}, +{0xFD7A,0,0,6266,3}, +{0xFD7B,0,0,6269,3}, +{0xFD7C,0,0,6272,3}, +{0xFD7D,0,0,6275,3}, +{0xFD7E,0,0,6278,3}, +{0xFD7F,0,0,6281,3}, +{0xFD80,0,0,6284,3}, +{0xFD81,0,0,6287,3}, +{0xFD82,0,0,6290,3}, +{0xFD83,0,0,6293,3}, +{0xFD84,0,0,6296,3}, +{0xFD85,0,0,6299,3}, +{0xFD86,0,0,6302,3}, +{0xFD87,0,0,6305,3}, +{0xFD88,0,0,6308,3}, +{0xFD89,0,0,6311,3}, +{0xFD8A,0,0,6314,3}, +{0xFD8B,0,0,6317,3}, +{0xFD8C,0,0,6320,3}, +{0xFD8D,0,0,6323,3}, +{0xFD8E,0,0,6326,3}, +{0xFD8F,0,0,6329,3}, +{0xFD92,0,0,6332,3}, +{0xFD93,0,0,6335,3}, +{0xFD94,0,0,6338,3}, +{0xFD95,0,0,6341,3}, +{0xFD96,0,0,6344,3}, +{0xFD97,0,0,6347,3}, +{0xFD98,0,0,6350,3}, +{0xFD99,0,0,6353,3}, +{0xFD9A,0,0,6356,3}, +{0xFD9B,0,0,6359,3}, +{0xFD9C,0,0,6362,3}, +{0xFD9D,0,0,6365,3}, +{0xFD9E,0,0,6368,3}, +{0xFD9F,0,0,6371,3}, +{0xFDA0,0,0,6374,3}, +{0xFDA1,0,0,6377,3}, +{0xFDA2,0,0,6380,3}, +{0xFDA3,0,0,6383,3}, +{0xFDA4,0,0,6386,3}, +{0xFDA5,0,0,6389,3}, +{0xFDA6,0,0,6392,3}, +{0xFDA7,0,0,6395,3}, +{0xFDA8,0,0,6398,3}, +{0xFDA9,0,0,6401,3}, +{0xFDAA,0,0,6404,3}, +{0xFDAB,0,0,6407,3}, +{0xFDAC,0,0,6410,3}, +{0xFDAD,0,0,6413,3}, +{0xFDAE,0,0,6416,3}, +{0xFDAF,0,0,6419,3}, +{0xFDB0,0,0,6422,3}, +{0xFDB1,0,0,6425,3}, +{0xFDB2,0,0,6428,3}, +{0xFDB3,0,0,6431,3}, +{0xFDB4,0,0,6434,3}, +{0xFDB5,0,0,6437,3}, +{0xFDB6,0,0,6440,3}, +{0xFDB7,0,0,6443,3}, +{0xFDB8,0,0,6446,3}, +{0xFDB9,0,0,6449,3}, +{0xFDBA,0,0,6452,3}, +{0xFDBB,0,0,6455,3}, +{0xFDBC,0,0,6458,3}, +{0xFDBD,0,0,6461,3}, +{0xFDBE,0,0,6464,3}, +{0xFDBF,0,0,6467,3}, +{0xFDC0,0,0,6470,3}, +{0xFDC1,0,0,6473,3}, +{0xFDC2,0,0,6476,3}, +{0xFDC3,0,0,6479,3}, +{0xFDC4,0,0,6482,3}, +{0xFDC5,0,0,6485,3}, +{0xFDC6,0,0,6488,3}, +{0xFDC7,0,0,6491,3}, +{0xFDF0,0,0,6494,3}, +{0xFDF1,0,0,6497,3}, +{0xFDF2,0,0,6500,4}, +{0xFDF3,0,0,6504,4}, +{0xFDF4,0,0,6508,4}, +{0xFDF5,0,0,6512,4}, +{0xFDF6,0,0,6516,4}, +{0xFDF7,0,0,6520,4}, +{0xFDF8,0,0,6524,4}, +{0xFDF9,0,0,6528,3}, +{0xFDFA,0,0,6531,18}, +{0xFDFB,0,0,6549,8}, +{0xFDFC,0,0,6557,4}, +{0xFE10,0,0,6561,1}, +{0xFE11,0,0,6562,1}, +{0xFE12,0,0,6563,1}, +{0xFE13,0,0,6564,1}, +{0xFE14,0,0,6565,1}, +{0xFE15,0,0,6566,1}, +{0xFE16,0,0,6567,1}, +{0xFE17,0,0,6568,1}, +{0xFE18,0,0,6569,1}, +{0xFE19,0,0,6570,3}, +{0xFE30,0,0,6573,2}, +{0xFE31,0,0,6575,1}, +{0xFE32,0,0,6576,1}, +{0xFE33,0,0,6577,1}, +{0xFE34,0,0,6578,1}, +{0xFE35,0,0,6579,1}, +{0xFE36,0,0,6580,1}, +{0xFE37,0,0,6581,1}, +{0xFE38,0,0,6582,1}, +{0xFE39,0,0,6583,1}, +{0xFE3A,0,0,6584,1}, +{0xFE3B,0,0,6585,1}, +{0xFE3C,0,0,6586,1}, +{0xFE3D,0,0,6587,1}, +{0xFE3E,0,0,6588,1}, +{0xFE3F,0,0,6589,1}, +{0xFE40,0,0,6590,1}, +{0xFE41,0,0,6591,1}, +{0xFE42,0,0,6592,1}, +{0xFE43,0,0,6593,1}, +{0xFE44,0,0,6594,1}, +{0xFE47,0,0,6595,1}, +{0xFE48,0,0,6596,1}, +{0xFE49,0,0,6597,2}, +{0xFE4A,0,0,6599,2}, +{0xFE4B,0,0,6601,2}, +{0xFE4C,0,0,6603,2}, +{0xFE4D,0,0,6605,1}, +{0xFE4E,0,0,6606,1}, +{0xFE4F,0,0,6607,1}, +{0xFE50,0,0,6608,1}, +{0xFE51,0,0,6609,1}, +{0xFE52,0,0,6610,1}, +{0xFE54,0,0,6611,1}, +{0xFE55,0,0,6612,1}, +{0xFE56,0,0,6613,1}, +{0xFE57,0,0,6614,1}, +{0xFE58,0,0,6615,1}, +{0xFE59,0,0,6616,1}, +{0xFE5A,0,0,6617,1}, +{0xFE5B,0,0,6618,1}, +{0xFE5C,0,0,6619,1}, +{0xFE5D,0,0,6620,1}, +{0xFE5E,0,0,6621,1}, +{0xFE5F,0,0,6622,1}, +{0xFE60,0,0,6623,1}, +{0xFE61,0,0,6624,1}, +{0xFE62,0,0,6625,1}, +{0xFE63,0,0,6626,1}, +{0xFE64,0,0,6627,1}, +{0xFE65,0,0,6628,1}, +{0xFE66,0,0,6629,1}, +{0xFE68,0,0,6630,1}, +{0xFE69,0,0,6631,1}, +{0xFE6A,0,0,6632,1}, +{0xFE6B,0,0,6633,1}, +{0xFE70,0,0,6634,2}, +{0xFE71,0,0,6636,2}, +{0xFE72,0,0,6638,2}, +{0xFE74,0,0,6640,2}, +{0xFE76,0,0,6642,2}, +{0xFE77,0,0,6644,2}, +{0xFE78,0,0,6646,2}, +{0xFE79,0,0,6648,2}, +{0xFE7A,0,0,6650,2}, +{0xFE7B,0,0,6652,2}, +{0xFE7C,0,0,6654,2}, +{0xFE7D,0,0,6656,2}, +{0xFE7E,0,0,6658,2}, +{0xFE7F,0,0,6660,2}, +{0xFE80,0,0,6662,1}, +{0xFE81,0,0,6663,2}, +{0xFE82,0,0,6665,2}, +{0xFE83,0,0,6667,2}, +{0xFE84,0,0,6669,2}, +{0xFE85,0,0,6671,2}, +{0xFE86,0,0,6673,2}, +{0xFE87,0,0,6675,2}, +{0xFE88,0,0,6677,2}, +{0xFE89,0,0,6679,2}, +{0xFE8A,0,0,6681,2}, +{0xFE8B,0,0,6683,2}, +{0xFE8C,0,0,6685,2}, +{0xFE8D,0,0,6687,1}, +{0xFE8E,0,0,6688,1}, +{0xFE8F,0,0,6689,1}, +{0xFE90,0,0,6690,1}, +{0xFE91,0,0,6691,1}, +{0xFE92,0,0,6692,1}, +{0xFE93,0,0,6693,1}, +{0xFE94,0,0,6694,1}, +{0xFE95,0,0,6695,1}, +{0xFE96,0,0,6696,1}, +{0xFE97,0,0,6697,1}, +{0xFE98,0,0,6698,1}, +{0xFE99,0,0,6699,1}, +{0xFE9A,0,0,6700,1}, +{0xFE9B,0,0,6701,1}, +{0xFE9C,0,0,6702,1}, +{0xFE9D,0,0,6703,1}, +{0xFE9E,0,0,6704,1}, +{0xFE9F,0,0,6705,1}, +{0xFEA0,0,0,6706,1}, +{0xFEA1,0,0,6707,1}, +{0xFEA2,0,0,6708,1}, +{0xFEA3,0,0,6709,1}, +{0xFEA4,0,0,6710,1}, +{0xFEA5,0,0,6711,1}, +{0xFEA6,0,0,6712,1}, +{0xFEA7,0,0,6713,1}, +{0xFEA8,0,0,6714,1}, +{0xFEA9,0,0,6715,1}, +{0xFEAA,0,0,6716,1}, +{0xFEAB,0,0,6717,1}, +{0xFEAC,0,0,6718,1}, +{0xFEAD,0,0,6719,1}, +{0xFEAE,0,0,6720,1}, +{0xFEAF,0,0,6721,1}, +{0xFEB0,0,0,6722,1}, +{0xFEB1,0,0,6723,1}, +{0xFEB2,0,0,6724,1}, +{0xFEB3,0,0,6725,1}, +{0xFEB4,0,0,6726,1}, +{0xFEB5,0,0,6727,1}, +{0xFEB6,0,0,6728,1}, +{0xFEB7,0,0,6729,1}, +{0xFEB8,0,0,6730,1}, +{0xFEB9,0,0,6731,1}, +{0xFEBA,0,0,6732,1}, +{0xFEBB,0,0,6733,1}, +{0xFEBC,0,0,6734,1}, +{0xFEBD,0,0,6735,1}, +{0xFEBE,0,0,6736,1}, +{0xFEBF,0,0,6737,1}, +{0xFEC0,0,0,6738,1}, +{0xFEC1,0,0,6739,1}, +{0xFEC2,0,0,6740,1}, +{0xFEC3,0,0,6741,1}, +{0xFEC4,0,0,6742,1}, +{0xFEC5,0,0,6743,1}, +{0xFEC6,0,0,6744,1}, +{0xFEC7,0,0,6745,1}, +{0xFEC8,0,0,6746,1}, +{0xFEC9,0,0,6747,1}, +{0xFECA,0,0,6748,1}, +{0xFECB,0,0,6749,1}, +{0xFECC,0,0,6750,1}, +{0xFECD,0,0,6751,1}, +{0xFECE,0,0,6752,1}, +{0xFECF,0,0,6753,1}, +{0xFED0,0,0,6754,1}, +{0xFED1,0,0,6755,1}, +{0xFED2,0,0,6756,1}, +{0xFED3,0,0,6757,1}, +{0xFED4,0,0,6758,1}, +{0xFED5,0,0,6759,1}, +{0xFED6,0,0,6760,1}, +{0xFED7,0,0,6761,1}, +{0xFED8,0,0,6762,1}, +{0xFED9,0,0,6763,1}, +{0xFEDA,0,0,6764,1}, +{0xFEDB,0,0,6765,1}, +{0xFEDC,0,0,6766,1}, +{0xFEDD,0,0,6767,1}, +{0xFEDE,0,0,6768,1}, +{0xFEDF,0,0,6769,1}, +{0xFEE0,0,0,6770,1}, +{0xFEE1,0,0,6771,1}, +{0xFEE2,0,0,6772,1}, +{0xFEE3,0,0,6773,1}, +{0xFEE4,0,0,6774,1}, +{0xFEE5,0,0,6775,1}, +{0xFEE6,0,0,6776,1}, +{0xFEE7,0,0,6777,1}, +{0xFEE8,0,0,6778,1}, +{0xFEE9,0,0,6779,1}, +{0xFEEA,0,0,6780,1}, +{0xFEEB,0,0,6781,1}, +{0xFEEC,0,0,6782,1}, +{0xFEED,0,0,6783,1}, +{0xFEEE,0,0,6784,1}, +{0xFEEF,0,0,6785,1}, +{0xFEF0,0,0,6786,1}, +{0xFEF1,0,0,6787,1}, +{0xFEF2,0,0,6788,1}, +{0xFEF3,0,0,6789,1}, +{0xFEF4,0,0,6790,1}, +{0xFEF5,0,0,6791,3}, +{0xFEF6,0,0,6794,3}, +{0xFEF7,0,0,6797,3}, +{0xFEF8,0,0,6800,3}, +{0xFEF9,0,0,6803,3}, +{0xFEFA,0,0,6806,3}, +{0xFEFB,0,0,6809,2}, +{0xFEFC,0,0,6811,2}, +{0xFF01,0,0,6813,1}, +{0xFF02,0,0,6814,1}, +{0xFF03,0,0,6815,1}, +{0xFF04,0,0,6816,1}, +{0xFF05,0,0,6817,1}, +{0xFF06,0,0,6818,1}, +{0xFF07,0,0,6819,1}, +{0xFF08,0,0,6820,1}, +{0xFF09,0,0,6821,1}, +{0xFF0A,0,0,6822,1}, +{0xFF0B,0,0,6823,1}, +{0xFF0C,0,0,6824,1}, +{0xFF0D,0,0,6825,1}, +{0xFF0E,0,0,6826,1}, +{0xFF0F,0,0,6827,1}, +{0xFF10,0,0,6828,1}, +{0xFF11,0,0,6829,1}, +{0xFF12,0,0,6830,1}, +{0xFF13,0,0,6831,1}, +{0xFF14,0,0,6832,1}, +{0xFF15,0,0,6833,1}, +{0xFF16,0,0,6834,1}, +{0xFF17,0,0,6835,1}, +{0xFF18,0,0,6836,1}, +{0xFF19,0,0,6837,1}, +{0xFF1A,0,0,6838,1}, +{0xFF1B,0,0,6839,1}, +{0xFF1C,0,0,6840,1}, +{0xFF1D,0,0,6841,1}, +{0xFF1E,0,0,6842,1}, +{0xFF1F,0,0,6843,1}, +{0xFF20,0,0,6844,1}, +{0xFF21,0,0,6845,1}, +{0xFF22,0,0,6846,1}, +{0xFF23,0,0,6847,1}, +{0xFF24,0,0,6848,1}, +{0xFF25,0,0,6849,1}, +{0xFF26,0,0,6850,1}, +{0xFF27,0,0,6851,1}, +{0xFF28,0,0,6852,1}, +{0xFF29,0,0,6853,1}, +{0xFF2A,0,0,6854,1}, +{0xFF2B,0,0,6855,1}, +{0xFF2C,0,0,6856,1}, +{0xFF2D,0,0,6857,1}, +{0xFF2E,0,0,6858,1}, +{0xFF2F,0,0,6859,1}, +{0xFF30,0,0,6860,1}, +{0xFF31,0,0,6861,1}, +{0xFF32,0,0,6862,1}, +{0xFF33,0,0,6863,1}, +{0xFF34,0,0,6864,1}, +{0xFF35,0,0,6865,1}, +{0xFF36,0,0,6866,1}, +{0xFF37,0,0,6867,1}, +{0xFF38,0,0,6868,1}, +{0xFF39,0,0,6869,1}, +{0xFF3A,0,0,6870,1}, +{0xFF3B,0,0,6871,1}, +{0xFF3C,0,0,6872,1}, +{0xFF3D,0,0,6873,1}, +{0xFF3E,0,0,6874,1}, +{0xFF3F,0,0,6875,1}, +{0xFF40,0,0,6876,1}, +{0xFF41,0,0,6877,1}, +{0xFF42,0,0,6878,1}, +{0xFF43,0,0,6879,1}, +{0xFF44,0,0,6880,1}, +{0xFF45,0,0,6881,1}, +{0xFF46,0,0,6882,1}, +{0xFF47,0,0,6883,1}, +{0xFF48,0,0,6884,1}, +{0xFF49,0,0,6885,1}, +{0xFF4A,0,0,6886,1}, +{0xFF4B,0,0,6887,1}, +{0xFF4C,0,0,6888,1}, +{0xFF4D,0,0,6889,1}, +{0xFF4E,0,0,6890,1}, +{0xFF4F,0,0,6891,1}, +{0xFF50,0,0,6892,1}, +{0xFF51,0,0,6893,1}, +{0xFF52,0,0,6894,1}, +{0xFF53,0,0,6895,1}, +{0xFF54,0,0,6896,1}, +{0xFF55,0,0,6897,1}, +{0xFF56,0,0,6898,1}, +{0xFF57,0,0,6899,1}, +{0xFF58,0,0,6900,1}, +{0xFF59,0,0,6901,1}, +{0xFF5A,0,0,6902,1}, +{0xFF5B,0,0,6903,1}, +{0xFF5C,0,0,6904,1}, +{0xFF5D,0,0,6905,1}, +{0xFF5E,0,0,6906,1}, +{0xFF5F,0,0,6907,1}, +{0xFF60,0,0,6908,1}, +{0xFF61,0,0,6909,1}, +{0xFF62,0,0,6910,1}, +{0xFF63,0,0,6911,1}, +{0xFF64,0,0,6912,1}, +{0xFF65,0,0,6913,1}, +{0xFF66,0,0,6914,1}, +{0xFF67,0,0,6915,1}, +{0xFF68,0,0,6916,1}, +{0xFF69,0,0,6917,1}, +{0xFF6A,0,0,6918,1}, +{0xFF6B,0,0,6919,1}, +{0xFF6C,0,0,6920,1}, +{0xFF6D,0,0,6921,1}, +{0xFF6E,0,0,6922,1}, +{0xFF6F,0,0,6923,1}, +{0xFF70,0,0,6924,1}, +{0xFF71,0,0,6925,1}, +{0xFF72,0,0,6926,1}, +{0xFF73,0,0,6927,1}, +{0xFF74,0,0,6928,1}, +{0xFF75,0,0,6929,1}, +{0xFF76,0,0,6930,1}, +{0xFF77,0,0,6931,1}, +{0xFF78,0,0,6932,1}, +{0xFF79,0,0,6933,1}, +{0xFF7A,0,0,6934,1}, +{0xFF7B,0,0,6935,1}, +{0xFF7C,0,0,6936,1}, +{0xFF7D,0,0,6937,1}, +{0xFF7E,0,0,6938,1}, +{0xFF7F,0,0,6939,1}, +{0xFF80,0,0,6940,1}, +{0xFF81,0,0,6941,1}, +{0xFF82,0,0,6942,1}, +{0xFF83,0,0,6943,1}, +{0xFF84,0,0,6944,1}, +{0xFF85,0,0,6945,1}, +{0xFF86,0,0,6946,1}, +{0xFF87,0,0,6947,1}, +{0xFF88,0,0,6948,1}, +{0xFF89,0,0,6949,1}, +{0xFF8A,0,0,6950,1}, +{0xFF8B,0,0,6951,1}, +{0xFF8C,0,0,6952,1}, +{0xFF8D,0,0,6953,1}, +{0xFF8E,0,0,6954,1}, +{0xFF8F,0,0,6955,1}, +{0xFF90,0,0,6956,1}, +{0xFF91,0,0,6957,1}, +{0xFF92,0,0,6958,1}, +{0xFF93,0,0,6959,1}, +{0xFF94,0,0,6960,1}, +{0xFF95,0,0,6961,1}, +{0xFF96,0,0,6962,1}, +{0xFF97,0,0,6963,1}, +{0xFF98,0,0,6964,1}, +{0xFF99,0,0,6965,1}, +{0xFF9A,0,0,6966,1}, +{0xFF9B,0,0,6967,1}, +{0xFF9C,0,0,6968,1}, +{0xFF9D,0,0,6969,1}, +{0xFF9E,0,0,6970,1}, +{0xFF9F,0,0,6971,1}, +{0xFFA0,0,0,6972,1}, +{0xFFA1,0,0,6973,1}, +{0xFFA2,0,0,6974,1}, +{0xFFA3,0,0,6975,1}, +{0xFFA4,0,0,6976,1}, +{0xFFA5,0,0,6977,1}, +{0xFFA6,0,0,6978,1}, +{0xFFA7,0,0,6979,1}, +{0xFFA8,0,0,6980,1}, +{0xFFA9,0,0,6981,1}, +{0xFFAA,0,0,6982,1}, +{0xFFAB,0,0,6983,1}, +{0xFFAC,0,0,6984,1}, +{0xFFAD,0,0,6985,1}, +{0xFFAE,0,0,6986,1}, +{0xFFAF,0,0,6987,1}, +{0xFFB0,0,0,6988,1}, +{0xFFB1,0,0,6989,1}, +{0xFFB2,0,0,6990,1}, +{0xFFB3,0,0,6991,1}, +{0xFFB4,0,0,6992,1}, +{0xFFB5,0,0,6993,1}, +{0xFFB6,0,0,6994,1}, +{0xFFB7,0,0,6995,1}, +{0xFFB8,0,0,6996,1}, +{0xFFB9,0,0,6997,1}, +{0xFFBA,0,0,6998,1}, +{0xFFBB,0,0,6999,1}, +{0xFFBC,0,0,7000,1}, +{0xFFBD,0,0,7001,1}, +{0xFFBE,0,0,7002,1}, +{0xFFC2,0,0,7003,1}, +{0xFFC3,0,0,7004,1}, +{0xFFC4,0,0,7005,1}, +{0xFFC5,0,0,7006,1}, +{0xFFC6,0,0,7007,1}, +{0xFFC7,0,0,7008,1}, +{0xFFCA,0,0,7009,1}, +{0xFFCB,0,0,7010,1}, +{0xFFCC,0,0,7011,1}, +{0xFFCD,0,0,7012,1}, +{0xFFCE,0,0,7013,1}, +{0xFFCF,0,0,7014,1}, +{0xFFD2,0,0,7015,1}, +{0xFFD3,0,0,7016,1}, +{0xFFD4,0,0,7017,1}, +{0xFFD5,0,0,7018,1}, +{0xFFD6,0,0,7019,1}, +{0xFFD7,0,0,7020,1}, +{0xFFDA,0,0,7021,1}, +{0xFFDB,0,0,7022,1}, +{0xFFDC,0,0,7023,1}, +{0xFFE0,0,0,7024,1}, +{0xFFE1,0,0,7025,1}, +{0xFFE2,0,0,7026,1}, +{0xFFE3,0,0,7027,2}, +{0xFFE4,0,0,7029,1}, +{0xFFE5,0,0,7030,1}, +{0xFFE6,0,0,7031,1}, +{0xFFE8,0,0,7032,1}, +{0xFFE9,0,0,7033,1}, +{0xFFEA,0,0,7034,1}, +{0xFFEB,0,0,7035,1}, +{0xFFEC,0,0,7036,1}, +{0xFFED,0,0,7037,1}, +{0xFFEE,0,0,7038,1}, +{0x105C9,7039,2,7039,2}, +{0x105E4,7041,2,7041,2}, +{0x10781,0,0,7043,1}, +{0x10782,0,0,7044,1}, +{0x10783,0,0,7045,1}, +{0x10784,0,0,7046,1}, +{0x10785,0,0,7047,1}, +{0x10787,0,0,7048,1}, +{0x10788,0,0,7049,1}, +{0x10789,0,0,7050,1}, +{0x1078A,0,0,7051,1}, +{0x1078B,0,0,7052,1}, +{0x1078C,0,0,7053,1}, +{0x1078D,0,0,7054,1}, +{0x1078E,0,0,7055,1}, +{0x1078F,0,0,7056,1}, +{0x10790,0,0,7057,1}, +{0x10791,0,0,7058,1}, +{0x10792,0,0,7059,1}, +{0x10793,0,0,7060,1}, +{0x10794,0,0,7061,1}, +{0x10795,0,0,7062,1}, +{0x10796,0,0,7063,1}, +{0x10797,0,0,7064,1}, +{0x10798,0,0,7065,1}, +{0x10799,0,0,7066,1}, +{0x1079A,0,0,7067,1}, +{0x1079B,0,0,7068,1}, +{0x1079C,0,0,7069,1}, +{0x1079D,0,0,7070,1}, +{0x1079E,0,0,7071,1}, +{0x1079F,0,0,7072,1}, +{0x107A0,0,0,7073,1}, +{0x107A1,0,0,7074,1}, +{0x107A2,0,0,7075,1}, +{0x107A3,0,0,7076,1}, +{0x107A4,0,0,7077,1}, +{0x107A5,0,0,7078,1}, +{0x107A6,0,0,7079,1}, +{0x107A7,0,0,7080,1}, +{0x107A8,0,0,7081,1}, +{0x107A9,0,0,7082,1}, +{0x107AA,0,0,7083,1}, +{0x107AB,0,0,7084,1}, +{0x107AC,0,0,7085,1}, +{0x107AD,0,0,7086,1}, +{0x107AE,0,0,7087,1}, +{0x107AF,0,0,7088,1}, +{0x107B0,0,0,7089,1}, +{0x107B2,0,0,7090,1}, +{0x107B3,0,0,7091,1}, +{0x107B4,0,0,7092,1}, +{0x107B5,0,0,7093,1}, +{0x107B6,0,0,7094,1}, +{0x107B7,0,0,7095,1}, +{0x107B8,0,0,7096,1}, +{0x107B9,0,0,7097,1}, +{0x107BA,0,0,7098,1}, +{0x1109A,7099,2,7099,2}, +{0x1109C,7101,2,7101,2}, +{0x110AB,7103,2,7103,2}, +{0x1112E,7105,2,7105,2}, +{0x1112F,7107,2,7107,2}, +{0x1134B,7109,2,7109,2}, +{0x1134C,7111,2,7111,2}, +{0x11383,7113,2,7113,2}, +{0x11385,7115,2,7115,2}, +{0x1138E,7117,2,7117,2}, +{0x11391,7119,2,7119,2}, +{0x113C5,7121,2,7121,2}, +{0x113C7,7123,2,7123,2}, +{0x113C8,7125,2,7125,2}, +{0x114BB,7127,2,7127,2}, +{0x114BC,7129,2,7129,2}, +{0x114BE,7131,2,7131,2}, +{0x115BA,7133,2,7133,2}, +{0x115BB,7135,2,7135,2}, +{0x11938,7137,2,7137,2}, +{0x16121,7139,2,7139,2}, +{0x16122,7141,2,7141,2}, +{0x16123,7143,2,7143,2}, +{0x16124,7145,2,7145,2}, +{0x16125,7147,2,7147,2}, +{0x16126,7149,3,7149,3}, +{0x16127,7152,3,7152,3}, +{0x16128,7155,3,7155,3}, +{0x16D68,7158,2,7158,2}, +{0x16D69,7160,2,7160,2}, +{0x16D6A,7162,3,7162,3}, +{0x1CCD6,0,0,7165,1}, +{0x1CCD7,0,0,7166,1}, +{0x1CCD8,0,0,7167,1}, +{0x1CCD9,0,0,7168,1}, +{0x1CCDA,0,0,7169,1}, +{0x1CCDB,0,0,7170,1}, +{0x1CCDC,0,0,7171,1}, +{0x1CCDD,0,0,7172,1}, +{0x1CCDE,0,0,7173,1}, +{0x1CCDF,0,0,7174,1}, +{0x1CCE0,0,0,7175,1}, +{0x1CCE1,0,0,7176,1}, +{0x1CCE2,0,0,7177,1}, +{0x1CCE3,0,0,7178,1}, +{0x1CCE4,0,0,7179,1}, +{0x1CCE5,0,0,7180,1}, +{0x1CCE6,0,0,7181,1}, +{0x1CCE7,0,0,7182,1}, +{0x1CCE8,0,0,7183,1}, +{0x1CCE9,0,0,7184,1}, +{0x1CCEA,0,0,7185,1}, +{0x1CCEB,0,0,7186,1}, +{0x1CCEC,0,0,7187,1}, +{0x1CCED,0,0,7188,1}, +{0x1CCEE,0,0,7189,1}, +{0x1CCEF,0,0,7190,1}, +{0x1CCF0,0,0,7191,1}, +{0x1CCF1,0,0,7192,1}, +{0x1CCF2,0,0,7193,1}, +{0x1CCF3,0,0,7194,1}, +{0x1CCF4,0,0,7195,1}, +{0x1CCF5,0,0,7196,1}, +{0x1CCF6,0,0,7197,1}, +{0x1CCF7,0,0,7198,1}, +{0x1CCF8,0,0,7199,1}, +{0x1CCF9,0,0,7200,1}, +{0x1D15E,7201,2,7201,2}, +{0x1D15F,7203,2,7203,2}, +{0x1D160,7205,3,7205,3}, +{0x1D161,7208,3,7208,3}, +{0x1D162,7211,3,7211,3}, +{0x1D163,7214,3,7214,3}, +{0x1D164,7217,3,7217,3}, +{0x1D1BB,7220,2,7220,2}, +{0x1D1BC,7222,2,7222,2}, +{0x1D1BD,7224,3,7224,3}, +{0x1D1BE,7227,3,7227,3}, +{0x1D1BF,7230,3,7230,3}, +{0x1D1C0,7233,3,7233,3}, +{0x1D400,0,0,7236,1}, +{0x1D401,0,0,7237,1}, +{0x1D402,0,0,7238,1}, +{0x1D403,0,0,7239,1}, +{0x1D404,0,0,7240,1}, +{0x1D405,0,0,7241,1}, +{0x1D406,0,0,7242,1}, +{0x1D407,0,0,7243,1}, +{0x1D408,0,0,7244,1}, +{0x1D409,0,0,7245,1}, +{0x1D40A,0,0,7246,1}, +{0x1D40B,0,0,7247,1}, +{0x1D40C,0,0,7248,1}, +{0x1D40D,0,0,7249,1}, +{0x1D40E,0,0,7250,1}, +{0x1D40F,0,0,7251,1}, +{0x1D410,0,0,7252,1}, +{0x1D411,0,0,7253,1}, +{0x1D412,0,0,7254,1}, +{0x1D413,0,0,7255,1}, +{0x1D414,0,0,7256,1}, +{0x1D415,0,0,7257,1}, +{0x1D416,0,0,7258,1}, +{0x1D417,0,0,7259,1}, +{0x1D418,0,0,7260,1}, +{0x1D419,0,0,7261,1}, +{0x1D41A,0,0,7262,1}, +{0x1D41B,0,0,7263,1}, +{0x1D41C,0,0,7264,1}, +{0x1D41D,0,0,7265,1}, +{0x1D41E,0,0,7266,1}, +{0x1D41F,0,0,7267,1}, +{0x1D420,0,0,7268,1}, +{0x1D421,0,0,7269,1}, +{0x1D422,0,0,7270,1}, +{0x1D423,0,0,7271,1}, +{0x1D424,0,0,7272,1}, +{0x1D425,0,0,7273,1}, +{0x1D426,0,0,7274,1}, +{0x1D427,0,0,7275,1}, +{0x1D428,0,0,7276,1}, +{0x1D429,0,0,7277,1}, +{0x1D42A,0,0,7278,1}, +{0x1D42B,0,0,7279,1}, +{0x1D42C,0,0,7280,1}, +{0x1D42D,0,0,7281,1}, +{0x1D42E,0,0,7282,1}, +{0x1D42F,0,0,7283,1}, +{0x1D430,0,0,7284,1}, +{0x1D431,0,0,7285,1}, +{0x1D432,0,0,7286,1}, +{0x1D433,0,0,7287,1}, +{0x1D434,0,0,7288,1}, +{0x1D435,0,0,7289,1}, +{0x1D436,0,0,7290,1}, +{0x1D437,0,0,7291,1}, +{0x1D438,0,0,7292,1}, +{0x1D439,0,0,7293,1}, +{0x1D43A,0,0,7294,1}, +{0x1D43B,0,0,7295,1}, +{0x1D43C,0,0,7296,1}, +{0x1D43D,0,0,7297,1}, +{0x1D43E,0,0,7298,1}, +{0x1D43F,0,0,7299,1}, +{0x1D440,0,0,7300,1}, +{0x1D441,0,0,7301,1}, +{0x1D442,0,0,7302,1}, +{0x1D443,0,0,7303,1}, +{0x1D444,0,0,7304,1}, +{0x1D445,0,0,7305,1}, +{0x1D446,0,0,7306,1}, +{0x1D447,0,0,7307,1}, +{0x1D448,0,0,7308,1}, +{0x1D449,0,0,7309,1}, +{0x1D44A,0,0,7310,1}, +{0x1D44B,0,0,7311,1}, +{0x1D44C,0,0,7312,1}, +{0x1D44D,0,0,7313,1}, +{0x1D44E,0,0,7314,1}, +{0x1D44F,0,0,7315,1}, +{0x1D450,0,0,7316,1}, +{0x1D451,0,0,7317,1}, +{0x1D452,0,0,7318,1}, +{0x1D453,0,0,7319,1}, +{0x1D454,0,0,7320,1}, +{0x1D456,0,0,7321,1}, +{0x1D457,0,0,7322,1}, +{0x1D458,0,0,7323,1}, +{0x1D459,0,0,7324,1}, +{0x1D45A,0,0,7325,1}, +{0x1D45B,0,0,7326,1}, +{0x1D45C,0,0,7327,1}, +{0x1D45D,0,0,7328,1}, +{0x1D45E,0,0,7329,1}, +{0x1D45F,0,0,7330,1}, +{0x1D460,0,0,7331,1}, +{0x1D461,0,0,7332,1}, +{0x1D462,0,0,7333,1}, +{0x1D463,0,0,7334,1}, +{0x1D464,0,0,7335,1}, +{0x1D465,0,0,7336,1}, +{0x1D466,0,0,7337,1}, +{0x1D467,0,0,7338,1}, +{0x1D468,0,0,7339,1}, +{0x1D469,0,0,7340,1}, +{0x1D46A,0,0,7341,1}, +{0x1D46B,0,0,7342,1}, +{0x1D46C,0,0,7343,1}, +{0x1D46D,0,0,7344,1}, +{0x1D46E,0,0,7345,1}, +{0x1D46F,0,0,7346,1}, +{0x1D470,0,0,7347,1}, +{0x1D471,0,0,7348,1}, +{0x1D472,0,0,7349,1}, +{0x1D473,0,0,7350,1}, +{0x1D474,0,0,7351,1}, +{0x1D475,0,0,7352,1}, +{0x1D476,0,0,7353,1}, +{0x1D477,0,0,7354,1}, +{0x1D478,0,0,7355,1}, +{0x1D479,0,0,7356,1}, +{0x1D47A,0,0,7357,1}, +{0x1D47B,0,0,7358,1}, +{0x1D47C,0,0,7359,1}, +{0x1D47D,0,0,7360,1}, +{0x1D47E,0,0,7361,1}, +{0x1D47F,0,0,7362,1}, +{0x1D480,0,0,7363,1}, +{0x1D481,0,0,7364,1}, +{0x1D482,0,0,7365,1}, +{0x1D483,0,0,7366,1}, +{0x1D484,0,0,7367,1}, +{0x1D485,0,0,7368,1}, +{0x1D486,0,0,7369,1}, +{0x1D487,0,0,7370,1}, +{0x1D488,0,0,7371,1}, +{0x1D489,0,0,7372,1}, +{0x1D48A,0,0,7373,1}, +{0x1D48B,0,0,7374,1}, +{0x1D48C,0,0,7375,1}, +{0x1D48D,0,0,7376,1}, +{0x1D48E,0,0,7377,1}, +{0x1D48F,0,0,7378,1}, +{0x1D490,0,0,7379,1}, +{0x1D491,0,0,7380,1}, +{0x1D492,0,0,7381,1}, +{0x1D493,0,0,7382,1}, +{0x1D494,0,0,7383,1}, +{0x1D495,0,0,7384,1}, +{0x1D496,0,0,7385,1}, +{0x1D497,0,0,7386,1}, +{0x1D498,0,0,7387,1}, +{0x1D499,0,0,7388,1}, +{0x1D49A,0,0,7389,1}, +{0x1D49B,0,0,7390,1}, +{0x1D49C,0,0,7391,1}, +{0x1D49E,0,0,7392,1}, +{0x1D49F,0,0,7393,1}, +{0x1D4A2,0,0,7394,1}, +{0x1D4A5,0,0,7395,1}, +{0x1D4A6,0,0,7396,1}, +{0x1D4A9,0,0,7397,1}, +{0x1D4AA,0,0,7398,1}, +{0x1D4AB,0,0,7399,1}, +{0x1D4AC,0,0,7400,1}, +{0x1D4AE,0,0,7401,1}, +{0x1D4AF,0,0,7402,1}, +{0x1D4B0,0,0,7403,1}, +{0x1D4B1,0,0,7404,1}, +{0x1D4B2,0,0,7405,1}, +{0x1D4B3,0,0,7406,1}, +{0x1D4B4,0,0,7407,1}, +{0x1D4B5,0,0,7408,1}, +{0x1D4B6,0,0,7409,1}, +{0x1D4B7,0,0,7410,1}, +{0x1D4B8,0,0,7411,1}, +{0x1D4B9,0,0,7412,1}, +{0x1D4BB,0,0,7413,1}, +{0x1D4BD,0,0,7414,1}, +{0x1D4BE,0,0,7415,1}, +{0x1D4BF,0,0,7416,1}, +{0x1D4C0,0,0,7417,1}, +{0x1D4C1,0,0,7418,1}, +{0x1D4C2,0,0,7419,1}, +{0x1D4C3,0,0,7420,1}, +{0x1D4C5,0,0,7421,1}, +{0x1D4C6,0,0,7422,1}, +{0x1D4C7,0,0,7423,1}, +{0x1D4C8,0,0,7424,1}, +{0x1D4C9,0,0,7425,1}, +{0x1D4CA,0,0,7426,1}, +{0x1D4CB,0,0,7427,1}, +{0x1D4CC,0,0,7428,1}, +{0x1D4CD,0,0,7429,1}, +{0x1D4CE,0,0,7430,1}, +{0x1D4CF,0,0,7431,1}, +{0x1D4D0,0,0,7432,1}, +{0x1D4D1,0,0,7433,1}, +{0x1D4D2,0,0,7434,1}, +{0x1D4D3,0,0,7435,1}, +{0x1D4D4,0,0,7436,1}, +{0x1D4D5,0,0,7437,1}, +{0x1D4D6,0,0,7438,1}, +{0x1D4D7,0,0,7439,1}, +{0x1D4D8,0,0,7440,1}, +{0x1D4D9,0,0,7441,1}, +{0x1D4DA,0,0,7442,1}, +{0x1D4DB,0,0,7443,1}, +{0x1D4DC,0,0,7444,1}, +{0x1D4DD,0,0,7445,1}, +{0x1D4DE,0,0,7446,1}, +{0x1D4DF,0,0,7447,1}, +{0x1D4E0,0,0,7448,1}, +{0x1D4E1,0,0,7449,1}, +{0x1D4E2,0,0,7450,1}, +{0x1D4E3,0,0,7451,1}, +{0x1D4E4,0,0,7452,1}, +{0x1D4E5,0,0,7453,1}, +{0x1D4E6,0,0,7454,1}, +{0x1D4E7,0,0,7455,1}, +{0x1D4E8,0,0,7456,1}, +{0x1D4E9,0,0,7457,1}, +{0x1D4EA,0,0,7458,1}, +{0x1D4EB,0,0,7459,1}, +{0x1D4EC,0,0,7460,1}, +{0x1D4ED,0,0,7461,1}, +{0x1D4EE,0,0,7462,1}, +{0x1D4EF,0,0,7463,1}, +{0x1D4F0,0,0,7464,1}, +{0x1D4F1,0,0,7465,1}, +{0x1D4F2,0,0,7466,1}, +{0x1D4F3,0,0,7467,1}, +{0x1D4F4,0,0,7468,1}, +{0x1D4F5,0,0,7469,1}, +{0x1D4F6,0,0,7470,1}, +{0x1D4F7,0,0,7471,1}, +{0x1D4F8,0,0,7472,1}, +{0x1D4F9,0,0,7473,1}, +{0x1D4FA,0,0,7474,1}, +{0x1D4FB,0,0,7475,1}, +{0x1D4FC,0,0,7476,1}, +{0x1D4FD,0,0,7477,1}, +{0x1D4FE,0,0,7478,1}, +{0x1D4FF,0,0,7479,1}, +{0x1D500,0,0,7480,1}, +{0x1D501,0,0,7481,1}, +{0x1D502,0,0,7482,1}, +{0x1D503,0,0,7483,1}, +{0x1D504,0,0,7484,1}, +{0x1D505,0,0,7485,1}, +{0x1D507,0,0,7486,1}, +{0x1D508,0,0,7487,1}, +{0x1D509,0,0,7488,1}, +{0x1D50A,0,0,7489,1}, +{0x1D50D,0,0,7490,1}, +{0x1D50E,0,0,7491,1}, +{0x1D50F,0,0,7492,1}, +{0x1D510,0,0,7493,1}, +{0x1D511,0,0,7494,1}, +{0x1D512,0,0,7495,1}, +{0x1D513,0,0,7496,1}, +{0x1D514,0,0,7497,1}, +{0x1D516,0,0,7498,1}, +{0x1D517,0,0,7499,1}, +{0x1D518,0,0,7500,1}, +{0x1D519,0,0,7501,1}, +{0x1D51A,0,0,7502,1}, +{0x1D51B,0,0,7503,1}, +{0x1D51C,0,0,7504,1}, +{0x1D51E,0,0,7505,1}, +{0x1D51F,0,0,7506,1}, +{0x1D520,0,0,7507,1}, +{0x1D521,0,0,7508,1}, +{0x1D522,0,0,7509,1}, +{0x1D523,0,0,7510,1}, +{0x1D524,0,0,7511,1}, +{0x1D525,0,0,7512,1}, +{0x1D526,0,0,7513,1}, +{0x1D527,0,0,7514,1}, +{0x1D528,0,0,7515,1}, +{0x1D529,0,0,7516,1}, +{0x1D52A,0,0,7517,1}, +{0x1D52B,0,0,7518,1}, +{0x1D52C,0,0,7519,1}, +{0x1D52D,0,0,7520,1}, +{0x1D52E,0,0,7521,1}, +{0x1D52F,0,0,7522,1}, +{0x1D530,0,0,7523,1}, +{0x1D531,0,0,7524,1}, +{0x1D532,0,0,7525,1}, +{0x1D533,0,0,7526,1}, +{0x1D534,0,0,7527,1}, +{0x1D535,0,0,7528,1}, +{0x1D536,0,0,7529,1}, +{0x1D537,0,0,7530,1}, +{0x1D538,0,0,7531,1}, +{0x1D539,0,0,7532,1}, +{0x1D53B,0,0,7533,1}, +{0x1D53C,0,0,7534,1}, +{0x1D53D,0,0,7535,1}, +{0x1D53E,0,0,7536,1}, +{0x1D540,0,0,7537,1}, +{0x1D541,0,0,7538,1}, +{0x1D542,0,0,7539,1}, +{0x1D543,0,0,7540,1}, +{0x1D544,0,0,7541,1}, +{0x1D546,0,0,7542,1}, +{0x1D54A,0,0,7543,1}, +{0x1D54B,0,0,7544,1}, +{0x1D54C,0,0,7545,1}, +{0x1D54D,0,0,7546,1}, +{0x1D54E,0,0,7547,1}, +{0x1D54F,0,0,7548,1}, +{0x1D550,0,0,7549,1}, +{0x1D552,0,0,7550,1}, +{0x1D553,0,0,7551,1}, +{0x1D554,0,0,7552,1}, +{0x1D555,0,0,7553,1}, +{0x1D556,0,0,7554,1}, +{0x1D557,0,0,7555,1}, +{0x1D558,0,0,7556,1}, +{0x1D559,0,0,7557,1}, +{0x1D55A,0,0,7558,1}, +{0x1D55B,0,0,7559,1}, +{0x1D55C,0,0,7560,1}, +{0x1D55D,0,0,7561,1}, +{0x1D55E,0,0,7562,1}, +{0x1D55F,0,0,7563,1}, +{0x1D560,0,0,7564,1}, +{0x1D561,0,0,7565,1}, +{0x1D562,0,0,7566,1}, +{0x1D563,0,0,7567,1}, +{0x1D564,0,0,7568,1}, +{0x1D565,0,0,7569,1}, +{0x1D566,0,0,7570,1}, +{0x1D567,0,0,7571,1}, +{0x1D568,0,0,7572,1}, +{0x1D569,0,0,7573,1}, +{0x1D56A,0,0,7574,1}, +{0x1D56B,0,0,7575,1}, +{0x1D56C,0,0,7576,1}, +{0x1D56D,0,0,7577,1}, +{0x1D56E,0,0,7578,1}, +{0x1D56F,0,0,7579,1}, +{0x1D570,0,0,7580,1}, +{0x1D571,0,0,7581,1}, +{0x1D572,0,0,7582,1}, +{0x1D573,0,0,7583,1}, +{0x1D574,0,0,7584,1}, +{0x1D575,0,0,7585,1}, +{0x1D576,0,0,7586,1}, +{0x1D577,0,0,7587,1}, +{0x1D578,0,0,7588,1}, +{0x1D579,0,0,7589,1}, +{0x1D57A,0,0,7590,1}, +{0x1D57B,0,0,7591,1}, +{0x1D57C,0,0,7592,1}, +{0x1D57D,0,0,7593,1}, +{0x1D57E,0,0,7594,1}, +{0x1D57F,0,0,7595,1}, +{0x1D580,0,0,7596,1}, +{0x1D581,0,0,7597,1}, +{0x1D582,0,0,7598,1}, +{0x1D583,0,0,7599,1}, +{0x1D584,0,0,7600,1}, +{0x1D585,0,0,7601,1}, +{0x1D586,0,0,7602,1}, +{0x1D587,0,0,7603,1}, +{0x1D588,0,0,7604,1}, +{0x1D589,0,0,7605,1}, +{0x1D58A,0,0,7606,1}, +{0x1D58B,0,0,7607,1}, +{0x1D58C,0,0,7608,1}, +{0x1D58D,0,0,7609,1}, +{0x1D58E,0,0,7610,1}, +{0x1D58F,0,0,7611,1}, +{0x1D590,0,0,7612,1}, +{0x1D591,0,0,7613,1}, +{0x1D592,0,0,7614,1}, +{0x1D593,0,0,7615,1}, +{0x1D594,0,0,7616,1}, +{0x1D595,0,0,7617,1}, +{0x1D596,0,0,7618,1}, +{0x1D597,0,0,7619,1}, +{0x1D598,0,0,7620,1}, +{0x1D599,0,0,7621,1}, +{0x1D59A,0,0,7622,1}, +{0x1D59B,0,0,7623,1}, +{0x1D59C,0,0,7624,1}, +{0x1D59D,0,0,7625,1}, +{0x1D59E,0,0,7626,1}, +{0x1D59F,0,0,7627,1}, +{0x1D5A0,0,0,7628,1}, +{0x1D5A1,0,0,7629,1}, +{0x1D5A2,0,0,7630,1}, +{0x1D5A3,0,0,7631,1}, +{0x1D5A4,0,0,7632,1}, +{0x1D5A5,0,0,7633,1}, +{0x1D5A6,0,0,7634,1}, +{0x1D5A7,0,0,7635,1}, +{0x1D5A8,0,0,7636,1}, +{0x1D5A9,0,0,7637,1}, +{0x1D5AA,0,0,7638,1}, +{0x1D5AB,0,0,7639,1}, +{0x1D5AC,0,0,7640,1}, +{0x1D5AD,0,0,7641,1}, +{0x1D5AE,0,0,7642,1}, +{0x1D5AF,0,0,7643,1}, +{0x1D5B0,0,0,7644,1}, +{0x1D5B1,0,0,7645,1}, +{0x1D5B2,0,0,7646,1}, +{0x1D5B3,0,0,7647,1}, +{0x1D5B4,0,0,7648,1}, +{0x1D5B5,0,0,7649,1}, +{0x1D5B6,0,0,7650,1}, +{0x1D5B7,0,0,7651,1}, +{0x1D5B8,0,0,7652,1}, +{0x1D5B9,0,0,7653,1}, +{0x1D5BA,0,0,7654,1}, +{0x1D5BB,0,0,7655,1}, +{0x1D5BC,0,0,7656,1}, +{0x1D5BD,0,0,7657,1}, +{0x1D5BE,0,0,7658,1}, +{0x1D5BF,0,0,7659,1}, +{0x1D5C0,0,0,7660,1}, +{0x1D5C1,0,0,7661,1}, +{0x1D5C2,0,0,7662,1}, +{0x1D5C3,0,0,7663,1}, +{0x1D5C4,0,0,7664,1}, +{0x1D5C5,0,0,7665,1}, +{0x1D5C6,0,0,7666,1}, +{0x1D5C7,0,0,7667,1}, +{0x1D5C8,0,0,7668,1}, +{0x1D5C9,0,0,7669,1}, +{0x1D5CA,0,0,7670,1}, +{0x1D5CB,0,0,7671,1}, +{0x1D5CC,0,0,7672,1}, +{0x1D5CD,0,0,7673,1}, +{0x1D5CE,0,0,7674,1}, +{0x1D5CF,0,0,7675,1}, +{0x1D5D0,0,0,7676,1}, +{0x1D5D1,0,0,7677,1}, +{0x1D5D2,0,0,7678,1}, +{0x1D5D3,0,0,7679,1}, +{0x1D5D4,0,0,7680,1}, +{0x1D5D5,0,0,7681,1}, +{0x1D5D6,0,0,7682,1}, +{0x1D5D7,0,0,7683,1}, +{0x1D5D8,0,0,7684,1}, +{0x1D5D9,0,0,7685,1}, +{0x1D5DA,0,0,7686,1}, +{0x1D5DB,0,0,7687,1}, +{0x1D5DC,0,0,7688,1}, +{0x1D5DD,0,0,7689,1}, +{0x1D5DE,0,0,7690,1}, +{0x1D5DF,0,0,7691,1}, +{0x1D5E0,0,0,7692,1}, +{0x1D5E1,0,0,7693,1}, +{0x1D5E2,0,0,7694,1}, +{0x1D5E3,0,0,7695,1}, +{0x1D5E4,0,0,7696,1}, +{0x1D5E5,0,0,7697,1}, +{0x1D5E6,0,0,7698,1}, +{0x1D5E7,0,0,7699,1}, +{0x1D5E8,0,0,7700,1}, +{0x1D5E9,0,0,7701,1}, +{0x1D5EA,0,0,7702,1}, +{0x1D5EB,0,0,7703,1}, +{0x1D5EC,0,0,7704,1}, +{0x1D5ED,0,0,7705,1}, +{0x1D5EE,0,0,7706,1}, +{0x1D5EF,0,0,7707,1}, +{0x1D5F0,0,0,7708,1}, +{0x1D5F1,0,0,7709,1}, +{0x1D5F2,0,0,7710,1}, +{0x1D5F3,0,0,7711,1}, +{0x1D5F4,0,0,7712,1}, +{0x1D5F5,0,0,7713,1}, +{0x1D5F6,0,0,7714,1}, +{0x1D5F7,0,0,7715,1}, +{0x1D5F8,0,0,7716,1}, +{0x1D5F9,0,0,7717,1}, +{0x1D5FA,0,0,7718,1}, +{0x1D5FB,0,0,7719,1}, +{0x1D5FC,0,0,7720,1}, +{0x1D5FD,0,0,7721,1}, +{0x1D5FE,0,0,7722,1}, +{0x1D5FF,0,0,7723,1}, +{0x1D600,0,0,7724,1}, +{0x1D601,0,0,7725,1}, +{0x1D602,0,0,7726,1}, +{0x1D603,0,0,7727,1}, +{0x1D604,0,0,7728,1}, +{0x1D605,0,0,7729,1}, +{0x1D606,0,0,7730,1}, +{0x1D607,0,0,7731,1}, +{0x1D608,0,0,7732,1}, +{0x1D609,0,0,7733,1}, +{0x1D60A,0,0,7734,1}, +{0x1D60B,0,0,7735,1}, +{0x1D60C,0,0,7736,1}, +{0x1D60D,0,0,7737,1}, +{0x1D60E,0,0,7738,1}, +{0x1D60F,0,0,7739,1}, +{0x1D610,0,0,7740,1}, +{0x1D611,0,0,7741,1}, +{0x1D612,0,0,7742,1}, +{0x1D613,0,0,7743,1}, +{0x1D614,0,0,7744,1}, +{0x1D615,0,0,7745,1}, +{0x1D616,0,0,7746,1}, +{0x1D617,0,0,7747,1}, +{0x1D618,0,0,7748,1}, +{0x1D619,0,0,7749,1}, +{0x1D61A,0,0,7750,1}, +{0x1D61B,0,0,7751,1}, +{0x1D61C,0,0,7752,1}, +{0x1D61D,0,0,7753,1}, +{0x1D61E,0,0,7754,1}, +{0x1D61F,0,0,7755,1}, +{0x1D620,0,0,7756,1}, +{0x1D621,0,0,7757,1}, +{0x1D622,0,0,7758,1}, +{0x1D623,0,0,7759,1}, +{0x1D624,0,0,7760,1}, +{0x1D625,0,0,7761,1}, +{0x1D626,0,0,7762,1}, +{0x1D627,0,0,7763,1}, +{0x1D628,0,0,7764,1}, +{0x1D629,0,0,7765,1}, +{0x1D62A,0,0,7766,1}, +{0x1D62B,0,0,7767,1}, +{0x1D62C,0,0,7768,1}, +{0x1D62D,0,0,7769,1}, +{0x1D62E,0,0,7770,1}, +{0x1D62F,0,0,7771,1}, +{0x1D630,0,0,7772,1}, +{0x1D631,0,0,7773,1}, +{0x1D632,0,0,7774,1}, +{0x1D633,0,0,7775,1}, +{0x1D634,0,0,7776,1}, +{0x1D635,0,0,7777,1}, +{0x1D636,0,0,7778,1}, +{0x1D637,0,0,7779,1}, +{0x1D638,0,0,7780,1}, +{0x1D639,0,0,7781,1}, +{0x1D63A,0,0,7782,1}, +{0x1D63B,0,0,7783,1}, +{0x1D63C,0,0,7784,1}, +{0x1D63D,0,0,7785,1}, +{0x1D63E,0,0,7786,1}, +{0x1D63F,0,0,7787,1}, +{0x1D640,0,0,7788,1}, +{0x1D641,0,0,7789,1}, +{0x1D642,0,0,7790,1}, +{0x1D643,0,0,7791,1}, +{0x1D644,0,0,7792,1}, +{0x1D645,0,0,7793,1}, +{0x1D646,0,0,7794,1}, +{0x1D647,0,0,7795,1}, +{0x1D648,0,0,7796,1}, +{0x1D649,0,0,7797,1}, +{0x1D64A,0,0,7798,1}, +{0x1D64B,0,0,7799,1}, +{0x1D64C,0,0,7800,1}, +{0x1D64D,0,0,7801,1}, +{0x1D64E,0,0,7802,1}, +{0x1D64F,0,0,7803,1}, +{0x1D650,0,0,7804,1}, +{0x1D651,0,0,7805,1}, +{0x1D652,0,0,7806,1}, +{0x1D653,0,0,7807,1}, +{0x1D654,0,0,7808,1}, +{0x1D655,0,0,7809,1}, +{0x1D656,0,0,7810,1}, +{0x1D657,0,0,7811,1}, +{0x1D658,0,0,7812,1}, +{0x1D659,0,0,7813,1}, +{0x1D65A,0,0,7814,1}, +{0x1D65B,0,0,7815,1}, +{0x1D65C,0,0,7816,1}, +{0x1D65D,0,0,7817,1}, +{0x1D65E,0,0,7818,1}, +{0x1D65F,0,0,7819,1}, +{0x1D660,0,0,7820,1}, +{0x1D661,0,0,7821,1}, +{0x1D662,0,0,7822,1}, +{0x1D663,0,0,7823,1}, +{0x1D664,0,0,7824,1}, +{0x1D665,0,0,7825,1}, +{0x1D666,0,0,7826,1}, +{0x1D667,0,0,7827,1}, +{0x1D668,0,0,7828,1}, +{0x1D669,0,0,7829,1}, +{0x1D66A,0,0,7830,1}, +{0x1D66B,0,0,7831,1}, +{0x1D66C,0,0,7832,1}, +{0x1D66D,0,0,7833,1}, +{0x1D66E,0,0,7834,1}, +{0x1D66F,0,0,7835,1}, +{0x1D670,0,0,7836,1}, +{0x1D671,0,0,7837,1}, +{0x1D672,0,0,7838,1}, +{0x1D673,0,0,7839,1}, +{0x1D674,0,0,7840,1}, +{0x1D675,0,0,7841,1}, +{0x1D676,0,0,7842,1}, +{0x1D677,0,0,7843,1}, +{0x1D678,0,0,7844,1}, +{0x1D679,0,0,7845,1}, +{0x1D67A,0,0,7846,1}, +{0x1D67B,0,0,7847,1}, +{0x1D67C,0,0,7848,1}, +{0x1D67D,0,0,7849,1}, +{0x1D67E,0,0,7850,1}, +{0x1D67F,0,0,7851,1}, +{0x1D680,0,0,7852,1}, +{0x1D681,0,0,7853,1}, +{0x1D682,0,0,7854,1}, +{0x1D683,0,0,7855,1}, +{0x1D684,0,0,7856,1}, +{0x1D685,0,0,7857,1}, +{0x1D686,0,0,7858,1}, +{0x1D687,0,0,7859,1}, +{0x1D688,0,0,7860,1}, +{0x1D689,0,0,7861,1}, +{0x1D68A,0,0,7862,1}, +{0x1D68B,0,0,7863,1}, +{0x1D68C,0,0,7864,1}, +{0x1D68D,0,0,7865,1}, +{0x1D68E,0,0,7866,1}, +{0x1D68F,0,0,7867,1}, +{0x1D690,0,0,7868,1}, +{0x1D691,0,0,7869,1}, +{0x1D692,0,0,7870,1}, +{0x1D693,0,0,7871,1}, +{0x1D694,0,0,7872,1}, +{0x1D695,0,0,7873,1}, +{0x1D696,0,0,7874,1}, +{0x1D697,0,0,7875,1}, +{0x1D698,0,0,7876,1}, +{0x1D699,0,0,7877,1}, +{0x1D69A,0,0,7878,1}, +{0x1D69B,0,0,7879,1}, +{0x1D69C,0,0,7880,1}, +{0x1D69D,0,0,7881,1}, +{0x1D69E,0,0,7882,1}, +{0x1D69F,0,0,7883,1}, +{0x1D6A0,0,0,7884,1}, +{0x1D6A1,0,0,7885,1}, +{0x1D6A2,0,0,7886,1}, +{0x1D6A3,0,0,7887,1}, +{0x1D6A4,0,0,7888,1}, +{0x1D6A5,0,0,7889,1}, +{0x1D6A8,0,0,7890,1}, +{0x1D6A9,0,0,7891,1}, +{0x1D6AA,0,0,7892,1}, +{0x1D6AB,0,0,7893,1}, +{0x1D6AC,0,0,7894,1}, +{0x1D6AD,0,0,7895,1}, +{0x1D6AE,0,0,7896,1}, +{0x1D6AF,0,0,7897,1}, +{0x1D6B0,0,0,7898,1}, +{0x1D6B1,0,0,7899,1}, +{0x1D6B2,0,0,7900,1}, +{0x1D6B3,0,0,7901,1}, +{0x1D6B4,0,0,7902,1}, +{0x1D6B5,0,0,7903,1}, +{0x1D6B6,0,0,7904,1}, +{0x1D6B7,0,0,7905,1}, +{0x1D6B8,0,0,7906,1}, +{0x1D6B9,0,0,7907,1}, +{0x1D6BA,0,0,7908,1}, +{0x1D6BB,0,0,7909,1}, +{0x1D6BC,0,0,7910,1}, +{0x1D6BD,0,0,7911,1}, +{0x1D6BE,0,0,7912,1}, +{0x1D6BF,0,0,7913,1}, +{0x1D6C0,0,0,7914,1}, +{0x1D6C1,0,0,7915,1}, +{0x1D6C2,0,0,7916,1}, +{0x1D6C3,0,0,7917,1}, +{0x1D6C4,0,0,7918,1}, +{0x1D6C5,0,0,7919,1}, +{0x1D6C6,0,0,7920,1}, +{0x1D6C7,0,0,7921,1}, +{0x1D6C8,0,0,7922,1}, +{0x1D6C9,0,0,7923,1}, +{0x1D6CA,0,0,7924,1}, +{0x1D6CB,0,0,7925,1}, +{0x1D6CC,0,0,7926,1}, +{0x1D6CD,0,0,7927,1}, +{0x1D6CE,0,0,7928,1}, +{0x1D6CF,0,0,7929,1}, +{0x1D6D0,0,0,7930,1}, +{0x1D6D1,0,0,7931,1}, +{0x1D6D2,0,0,7932,1}, +{0x1D6D3,0,0,7933,1}, +{0x1D6D4,0,0,7934,1}, +{0x1D6D5,0,0,7935,1}, +{0x1D6D6,0,0,7936,1}, +{0x1D6D7,0,0,7937,1}, +{0x1D6D8,0,0,7938,1}, +{0x1D6D9,0,0,7939,1}, +{0x1D6DA,0,0,7940,1}, +{0x1D6DB,0,0,7941,1}, +{0x1D6DC,0,0,7942,1}, +{0x1D6DD,0,0,7943,1}, +{0x1D6DE,0,0,7944,1}, +{0x1D6DF,0,0,7945,1}, +{0x1D6E0,0,0,7946,1}, +{0x1D6E1,0,0,7947,1}, +{0x1D6E2,0,0,7948,1}, +{0x1D6E3,0,0,7949,1}, +{0x1D6E4,0,0,7950,1}, +{0x1D6E5,0,0,7951,1}, +{0x1D6E6,0,0,7952,1}, +{0x1D6E7,0,0,7953,1}, +{0x1D6E8,0,0,7954,1}, +{0x1D6E9,0,0,7955,1}, +{0x1D6EA,0,0,7956,1}, +{0x1D6EB,0,0,7957,1}, +{0x1D6EC,0,0,7958,1}, +{0x1D6ED,0,0,7959,1}, +{0x1D6EE,0,0,7960,1}, +{0x1D6EF,0,0,7961,1}, +{0x1D6F0,0,0,7962,1}, +{0x1D6F1,0,0,7963,1}, +{0x1D6F2,0,0,7964,1}, +{0x1D6F3,0,0,7965,1}, +{0x1D6F4,0,0,7966,1}, +{0x1D6F5,0,0,7967,1}, +{0x1D6F6,0,0,7968,1}, +{0x1D6F7,0,0,7969,1}, +{0x1D6F8,0,0,7970,1}, +{0x1D6F9,0,0,7971,1}, +{0x1D6FA,0,0,7972,1}, +{0x1D6FB,0,0,7973,1}, +{0x1D6FC,0,0,7974,1}, +{0x1D6FD,0,0,7975,1}, +{0x1D6FE,0,0,7976,1}, +{0x1D6FF,0,0,7977,1}, +{0x1D700,0,0,7978,1}, +{0x1D701,0,0,7979,1}, +{0x1D702,0,0,7980,1}, +{0x1D703,0,0,7981,1}, +{0x1D704,0,0,7982,1}, +{0x1D705,0,0,7983,1}, +{0x1D706,0,0,7984,1}, +{0x1D707,0,0,7985,1}, +{0x1D708,0,0,7986,1}, +{0x1D709,0,0,7987,1}, +{0x1D70A,0,0,7988,1}, +{0x1D70B,0,0,7989,1}, +{0x1D70C,0,0,7990,1}, +{0x1D70D,0,0,7991,1}, +{0x1D70E,0,0,7992,1}, +{0x1D70F,0,0,7993,1}, +{0x1D710,0,0,7994,1}, +{0x1D711,0,0,7995,1}, +{0x1D712,0,0,7996,1}, +{0x1D713,0,0,7997,1}, +{0x1D714,0,0,7998,1}, +{0x1D715,0,0,7999,1}, +{0x1D716,0,0,8000,1}, +{0x1D717,0,0,8001,1}, +{0x1D718,0,0,8002,1}, +{0x1D719,0,0,8003,1}, +{0x1D71A,0,0,8004,1}, +{0x1D71B,0,0,8005,1}, +{0x1D71C,0,0,8006,1}, +{0x1D71D,0,0,8007,1}, +{0x1D71E,0,0,8008,1}, +{0x1D71F,0,0,8009,1}, +{0x1D720,0,0,8010,1}, +{0x1D721,0,0,8011,1}, +{0x1D722,0,0,8012,1}, +{0x1D723,0,0,8013,1}, +{0x1D724,0,0,8014,1}, +{0x1D725,0,0,8015,1}, +{0x1D726,0,0,8016,1}, +{0x1D727,0,0,8017,1}, +{0x1D728,0,0,8018,1}, +{0x1D729,0,0,8019,1}, +{0x1D72A,0,0,8020,1}, +{0x1D72B,0,0,8021,1}, +{0x1D72C,0,0,8022,1}, +{0x1D72D,0,0,8023,1}, +{0x1D72E,0,0,8024,1}, +{0x1D72F,0,0,8025,1}, +{0x1D730,0,0,8026,1}, +{0x1D731,0,0,8027,1}, +{0x1D732,0,0,8028,1}, +{0x1D733,0,0,8029,1}, +{0x1D734,0,0,8030,1}, +{0x1D735,0,0,8031,1}, +{0x1D736,0,0,8032,1}, +{0x1D737,0,0,8033,1}, +{0x1D738,0,0,8034,1}, +{0x1D739,0,0,8035,1}, +{0x1D73A,0,0,8036,1}, +{0x1D73B,0,0,8037,1}, +{0x1D73C,0,0,8038,1}, +{0x1D73D,0,0,8039,1}, +{0x1D73E,0,0,8040,1}, +{0x1D73F,0,0,8041,1}, +{0x1D740,0,0,8042,1}, +{0x1D741,0,0,8043,1}, +{0x1D742,0,0,8044,1}, +{0x1D743,0,0,8045,1}, +{0x1D744,0,0,8046,1}, +{0x1D745,0,0,8047,1}, +{0x1D746,0,0,8048,1}, +{0x1D747,0,0,8049,1}, +{0x1D748,0,0,8050,1}, +{0x1D749,0,0,8051,1}, +{0x1D74A,0,0,8052,1}, +{0x1D74B,0,0,8053,1}, +{0x1D74C,0,0,8054,1}, +{0x1D74D,0,0,8055,1}, +{0x1D74E,0,0,8056,1}, +{0x1D74F,0,0,8057,1}, +{0x1D750,0,0,8058,1}, +{0x1D751,0,0,8059,1}, +{0x1D752,0,0,8060,1}, +{0x1D753,0,0,8061,1}, +{0x1D754,0,0,8062,1}, +{0x1D755,0,0,8063,1}, +{0x1D756,0,0,8064,1}, +{0x1D757,0,0,8065,1}, +{0x1D758,0,0,8066,1}, +{0x1D759,0,0,8067,1}, +{0x1D75A,0,0,8068,1}, +{0x1D75B,0,0,8069,1}, +{0x1D75C,0,0,8070,1}, +{0x1D75D,0,0,8071,1}, +{0x1D75E,0,0,8072,1}, +{0x1D75F,0,0,8073,1}, +{0x1D760,0,0,8074,1}, +{0x1D761,0,0,8075,1}, +{0x1D762,0,0,8076,1}, +{0x1D763,0,0,8077,1}, +{0x1D764,0,0,8078,1}, +{0x1D765,0,0,8079,1}, +{0x1D766,0,0,8080,1}, +{0x1D767,0,0,8081,1}, +{0x1D768,0,0,8082,1}, +{0x1D769,0,0,8083,1}, +{0x1D76A,0,0,8084,1}, +{0x1D76B,0,0,8085,1}, +{0x1D76C,0,0,8086,1}, +{0x1D76D,0,0,8087,1}, +{0x1D76E,0,0,8088,1}, +{0x1D76F,0,0,8089,1}, +{0x1D770,0,0,8090,1}, +{0x1D771,0,0,8091,1}, +{0x1D772,0,0,8092,1}, +{0x1D773,0,0,8093,1}, +{0x1D774,0,0,8094,1}, +{0x1D775,0,0,8095,1}, +{0x1D776,0,0,8096,1}, +{0x1D777,0,0,8097,1}, +{0x1D778,0,0,8098,1}, +{0x1D779,0,0,8099,1}, +{0x1D77A,0,0,8100,1}, +{0x1D77B,0,0,8101,1}, +{0x1D77C,0,0,8102,1}, +{0x1D77D,0,0,8103,1}, +{0x1D77E,0,0,8104,1}, +{0x1D77F,0,0,8105,1}, +{0x1D780,0,0,8106,1}, +{0x1D781,0,0,8107,1}, +{0x1D782,0,0,8108,1}, +{0x1D783,0,0,8109,1}, +{0x1D784,0,0,8110,1}, +{0x1D785,0,0,8111,1}, +{0x1D786,0,0,8112,1}, +{0x1D787,0,0,8113,1}, +{0x1D788,0,0,8114,1}, +{0x1D789,0,0,8115,1}, +{0x1D78A,0,0,8116,1}, +{0x1D78B,0,0,8117,1}, +{0x1D78C,0,0,8118,1}, +{0x1D78D,0,0,8119,1}, +{0x1D78E,0,0,8120,1}, +{0x1D78F,0,0,8121,1}, +{0x1D790,0,0,8122,1}, +{0x1D791,0,0,8123,1}, +{0x1D792,0,0,8124,1}, +{0x1D793,0,0,8125,1}, +{0x1D794,0,0,8126,1}, +{0x1D795,0,0,8127,1}, +{0x1D796,0,0,8128,1}, +{0x1D797,0,0,8129,1}, +{0x1D798,0,0,8130,1}, +{0x1D799,0,0,8131,1}, +{0x1D79A,0,0,8132,1}, +{0x1D79B,0,0,8133,1}, +{0x1D79C,0,0,8134,1}, +{0x1D79D,0,0,8135,1}, +{0x1D79E,0,0,8136,1}, +{0x1D79F,0,0,8137,1}, +{0x1D7A0,0,0,8138,1}, +{0x1D7A1,0,0,8139,1}, +{0x1D7A2,0,0,8140,1}, +{0x1D7A3,0,0,8141,1}, +{0x1D7A4,0,0,8142,1}, +{0x1D7A5,0,0,8143,1}, +{0x1D7A6,0,0,8144,1}, +{0x1D7A7,0,0,8145,1}, +{0x1D7A8,0,0,8146,1}, +{0x1D7A9,0,0,8147,1}, +{0x1D7AA,0,0,8148,1}, +{0x1D7AB,0,0,8149,1}, +{0x1D7AC,0,0,8150,1}, +{0x1D7AD,0,0,8151,1}, +{0x1D7AE,0,0,8152,1}, +{0x1D7AF,0,0,8153,1}, +{0x1D7B0,0,0,8154,1}, +{0x1D7B1,0,0,8155,1}, +{0x1D7B2,0,0,8156,1}, +{0x1D7B3,0,0,8157,1}, +{0x1D7B4,0,0,8158,1}, +{0x1D7B5,0,0,8159,1}, +{0x1D7B6,0,0,8160,1}, +{0x1D7B7,0,0,8161,1}, +{0x1D7B8,0,0,8162,1}, +{0x1D7B9,0,0,8163,1}, +{0x1D7BA,0,0,8164,1}, +{0x1D7BB,0,0,8165,1}, +{0x1D7BC,0,0,8166,1}, +{0x1D7BD,0,0,8167,1}, +{0x1D7BE,0,0,8168,1}, +{0x1D7BF,0,0,8169,1}, +{0x1D7C0,0,0,8170,1}, +{0x1D7C1,0,0,8171,1}, +{0x1D7C2,0,0,8172,1}, +{0x1D7C3,0,0,8173,1}, +{0x1D7C4,0,0,8174,1}, +{0x1D7C5,0,0,8175,1}, +{0x1D7C6,0,0,8176,1}, +{0x1D7C7,0,0,8177,1}, +{0x1D7C8,0,0,8178,1}, +{0x1D7C9,0,0,8179,1}, +{0x1D7CA,0,0,8180,1}, +{0x1D7CB,0,0,8181,1}, +{0x1D7CE,0,0,8182,1}, +{0x1D7CF,0,0,8183,1}, +{0x1D7D0,0,0,8184,1}, +{0x1D7D1,0,0,8185,1}, +{0x1D7D2,0,0,8186,1}, +{0x1D7D3,0,0,8187,1}, +{0x1D7D4,0,0,8188,1}, +{0x1D7D5,0,0,8189,1}, +{0x1D7D6,0,0,8190,1}, +{0x1D7D7,0,0,8191,1}, +{0x1D7D8,0,0,8192,1}, +{0x1D7D9,0,0,8193,1}, +{0x1D7DA,0,0,8194,1}, +{0x1D7DB,0,0,8195,1}, +{0x1D7DC,0,0,8196,1}, +{0x1D7DD,0,0,8197,1}, +{0x1D7DE,0,0,8198,1}, +{0x1D7DF,0,0,8199,1}, +{0x1D7E0,0,0,8200,1}, +{0x1D7E1,0,0,8201,1}, +{0x1D7E2,0,0,8202,1}, +{0x1D7E3,0,0,8203,1}, +{0x1D7E4,0,0,8204,1}, +{0x1D7E5,0,0,8205,1}, +{0x1D7E6,0,0,8206,1}, +{0x1D7E7,0,0,8207,1}, +{0x1D7E8,0,0,8208,1}, +{0x1D7E9,0,0,8209,1}, +{0x1D7EA,0,0,8210,1}, +{0x1D7EB,0,0,8211,1}, +{0x1D7EC,0,0,8212,1}, +{0x1D7ED,0,0,8213,1}, +{0x1D7EE,0,0,8214,1}, +{0x1D7EF,0,0,8215,1}, +{0x1D7F0,0,0,8216,1}, +{0x1D7F1,0,0,8217,1}, +{0x1D7F2,0,0,8218,1}, +{0x1D7F3,0,0,8219,1}, +{0x1D7F4,0,0,8220,1}, +{0x1D7F5,0,0,8221,1}, +{0x1D7F6,0,0,8222,1}, +{0x1D7F7,0,0,8223,1}, +{0x1D7F8,0,0,8224,1}, +{0x1D7F9,0,0,8225,1}, +{0x1D7FA,0,0,8226,1}, +{0x1D7FB,0,0,8227,1}, +{0x1D7FC,0,0,8228,1}, +{0x1D7FD,0,0,8229,1}, +{0x1D7FE,0,0,8230,1}, +{0x1D7FF,0,0,8231,1}, +{0x1E030,0,0,8232,1}, +{0x1E031,0,0,8233,1}, +{0x1E032,0,0,8234,1}, +{0x1E033,0,0,8235,1}, +{0x1E034,0,0,8236,1}, +{0x1E035,0,0,8237,1}, +{0x1E036,0,0,8238,1}, +{0x1E037,0,0,8239,1}, +{0x1E038,0,0,8240,1}, +{0x1E039,0,0,8241,1}, +{0x1E03A,0,0,8242,1}, +{0x1E03B,0,0,8243,1}, +{0x1E03C,0,0,8244,1}, +{0x1E03D,0,0,8245,1}, +{0x1E03E,0,0,8246,1}, +{0x1E03F,0,0,8247,1}, +{0x1E040,0,0,8248,1}, +{0x1E041,0,0,8249,1}, +{0x1E042,0,0,8250,1}, +{0x1E043,0,0,8251,1}, +{0x1E044,0,0,8252,1}, +{0x1E045,0,0,8253,1}, +{0x1E046,0,0,8254,1}, +{0x1E047,0,0,8255,1}, +{0x1E048,0,0,8256,1}, +{0x1E049,0,0,8257,1}, +{0x1E04A,0,0,8258,1}, +{0x1E04B,0,0,8259,1}, +{0x1E04C,0,0,8260,1}, +{0x1E04D,0,0,8261,1}, +{0x1E04E,0,0,8262,1}, +{0x1E04F,0,0,8263,1}, +{0x1E050,0,0,8264,1}, +{0x1E051,0,0,8265,1}, +{0x1E052,0,0,8266,1}, +{0x1E053,0,0,8267,1}, +{0x1E054,0,0,8268,1}, +{0x1E055,0,0,8269,1}, +{0x1E056,0,0,8270,1}, +{0x1E057,0,0,8271,1}, +{0x1E058,0,0,8272,1}, +{0x1E059,0,0,8273,1}, +{0x1E05A,0,0,8274,1}, +{0x1E05B,0,0,8275,1}, +{0x1E05C,0,0,8276,1}, +{0x1E05D,0,0,8277,1}, +{0x1E05E,0,0,8278,1}, +{0x1E05F,0,0,8279,1}, +{0x1E060,0,0,8280,1}, +{0x1E061,0,0,8281,1}, +{0x1E062,0,0,8282,1}, +{0x1E063,0,0,8283,1}, +{0x1E064,0,0,8284,1}, +{0x1E065,0,0,8285,1}, +{0x1E066,0,0,8286,1}, +{0x1E067,0,0,8287,1}, +{0x1E068,0,0,8288,1}, +{0x1E069,0,0,8289,1}, +{0x1E06A,0,0,8290,1}, +{0x1E06B,0,0,8291,1}, +{0x1E06C,0,0,8292,1}, +{0x1E06D,0,0,8293,1}, +{0x1EE00,0,0,8294,1}, +{0x1EE01,0,0,8295,1}, +{0x1EE02,0,0,8296,1}, +{0x1EE03,0,0,8297,1}, +{0x1EE05,0,0,8298,1}, +{0x1EE06,0,0,8299,1}, +{0x1EE07,0,0,8300,1}, +{0x1EE08,0,0,8301,1}, +{0x1EE09,0,0,8302,1}, +{0x1EE0A,0,0,8303,1}, +{0x1EE0B,0,0,8304,1}, +{0x1EE0C,0,0,8305,1}, +{0x1EE0D,0,0,8306,1}, +{0x1EE0E,0,0,8307,1}, +{0x1EE0F,0,0,8308,1}, +{0x1EE10,0,0,8309,1}, +{0x1EE11,0,0,8310,1}, +{0x1EE12,0,0,8311,1}, +{0x1EE13,0,0,8312,1}, +{0x1EE14,0,0,8313,1}, +{0x1EE15,0,0,8314,1}, +{0x1EE16,0,0,8315,1}, +{0x1EE17,0,0,8316,1}, +{0x1EE18,0,0,8317,1}, +{0x1EE19,0,0,8318,1}, +{0x1EE1A,0,0,8319,1}, +{0x1EE1B,0,0,8320,1}, +{0x1EE1C,0,0,8321,1}, +{0x1EE1D,0,0,8322,1}, +{0x1EE1E,0,0,8323,1}, +{0x1EE1F,0,0,8324,1}, +{0x1EE21,0,0,8325,1}, +{0x1EE22,0,0,8326,1}, +{0x1EE24,0,0,8327,1}, +{0x1EE27,0,0,8328,1}, +{0x1EE29,0,0,8329,1}, +{0x1EE2A,0,0,8330,1}, +{0x1EE2B,0,0,8331,1}, +{0x1EE2C,0,0,8332,1}, +{0x1EE2D,0,0,8333,1}, +{0x1EE2E,0,0,8334,1}, +{0x1EE2F,0,0,8335,1}, +{0x1EE30,0,0,8336,1}, +{0x1EE31,0,0,8337,1}, +{0x1EE32,0,0,8338,1}, +{0x1EE34,0,0,8339,1}, +{0x1EE35,0,0,8340,1}, +{0x1EE36,0,0,8341,1}, +{0x1EE37,0,0,8342,1}, +{0x1EE39,0,0,8343,1}, +{0x1EE3B,0,0,8344,1}, +{0x1EE42,0,0,8345,1}, +{0x1EE47,0,0,8346,1}, +{0x1EE49,0,0,8347,1}, +{0x1EE4B,0,0,8348,1}, +{0x1EE4D,0,0,8349,1}, +{0x1EE4E,0,0,8350,1}, +{0x1EE4F,0,0,8351,1}, +{0x1EE51,0,0,8352,1}, +{0x1EE52,0,0,8353,1}, +{0x1EE54,0,0,8354,1}, +{0x1EE57,0,0,8355,1}, +{0x1EE59,0,0,8356,1}, +{0x1EE5B,0,0,8357,1}, +{0x1EE5D,0,0,8358,1}, +{0x1EE5F,0,0,8359,1}, +{0x1EE61,0,0,8360,1}, +{0x1EE62,0,0,8361,1}, +{0x1EE64,0,0,8362,1}, +{0x1EE67,0,0,8363,1}, +{0x1EE68,0,0,8364,1}, +{0x1EE69,0,0,8365,1}, +{0x1EE6A,0,0,8366,1}, +{0x1EE6C,0,0,8367,1}, +{0x1EE6D,0,0,8368,1}, +{0x1EE6E,0,0,8369,1}, +{0x1EE6F,0,0,8370,1}, +{0x1EE70,0,0,8371,1}, +{0x1EE71,0,0,8372,1}, +{0x1EE72,0,0,8373,1}, +{0x1EE74,0,0,8374,1}, +{0x1EE75,0,0,8375,1}, +{0x1EE76,0,0,8376,1}, +{0x1EE77,0,0,8377,1}, +{0x1EE79,0,0,8378,1}, +{0x1EE7A,0,0,8379,1}, +{0x1EE7B,0,0,8380,1}, +{0x1EE7C,0,0,8381,1}, +{0x1EE7E,0,0,8382,1}, +{0x1EE80,0,0,8383,1}, +{0x1EE81,0,0,8384,1}, +{0x1EE82,0,0,8385,1}, +{0x1EE83,0,0,8386,1}, +{0x1EE84,0,0,8387,1}, +{0x1EE85,0,0,8388,1}, +{0x1EE86,0,0,8389,1}, +{0x1EE87,0,0,8390,1}, +{0x1EE88,0,0,8391,1}, +{0x1EE89,0,0,8392,1}, +{0x1EE8B,0,0,8393,1}, +{0x1EE8C,0,0,8394,1}, +{0x1EE8D,0,0,8395,1}, +{0x1EE8E,0,0,8396,1}, +{0x1EE8F,0,0,8397,1}, +{0x1EE90,0,0,8398,1}, +{0x1EE91,0,0,8399,1}, +{0x1EE92,0,0,8400,1}, +{0x1EE93,0,0,8401,1}, +{0x1EE94,0,0,8402,1}, +{0x1EE95,0,0,8403,1}, +{0x1EE96,0,0,8404,1}, +{0x1EE97,0,0,8405,1}, +{0x1EE98,0,0,8406,1}, +{0x1EE99,0,0,8407,1}, +{0x1EE9A,0,0,8408,1}, +{0x1EE9B,0,0,8409,1}, +{0x1EEA1,0,0,8410,1}, +{0x1EEA2,0,0,8411,1}, +{0x1EEA3,0,0,8412,1}, +{0x1EEA5,0,0,8413,1}, +{0x1EEA6,0,0,8414,1}, +{0x1EEA7,0,0,8415,1}, +{0x1EEA8,0,0,8416,1}, +{0x1EEA9,0,0,8417,1}, +{0x1EEAB,0,0,8418,1}, +{0x1EEAC,0,0,8419,1}, +{0x1EEAD,0,0,8420,1}, +{0x1EEAE,0,0,8421,1}, +{0x1EEAF,0,0,8422,1}, +{0x1EEB0,0,0,8423,1}, +{0x1EEB1,0,0,8424,1}, +{0x1EEB2,0,0,8425,1}, +{0x1EEB3,0,0,8426,1}, +{0x1EEB4,0,0,8427,1}, +{0x1EEB5,0,0,8428,1}, +{0x1EEB6,0,0,8429,1}, +{0x1EEB7,0,0,8430,1}, +{0x1EEB8,0,0,8431,1}, +{0x1EEB9,0,0,8432,1}, +{0x1EEBA,0,0,8433,1}, +{0x1EEBB,0,0,8434,1}, +{0x1F100,0,0,8435,2}, +{0x1F101,0,0,8437,2}, +{0x1F102,0,0,8439,2}, +{0x1F103,0,0,8441,2}, +{0x1F104,0,0,8443,2}, +{0x1F105,0,0,8445,2}, +{0x1F106,0,0,8447,2}, +{0x1F107,0,0,8449,2}, +{0x1F108,0,0,8451,2}, +{0x1F109,0,0,8453,2}, +{0x1F10A,0,0,8455,2}, +{0x1F110,0,0,8457,3}, +{0x1F111,0,0,8460,3}, +{0x1F112,0,0,8463,3}, +{0x1F113,0,0,8466,3}, +{0x1F114,0,0,8469,3}, +{0x1F115,0,0,8472,3}, +{0x1F116,0,0,8475,3}, +{0x1F117,0,0,8478,3}, +{0x1F118,0,0,8481,3}, +{0x1F119,0,0,8484,3}, +{0x1F11A,0,0,8487,3}, +{0x1F11B,0,0,8490,3}, +{0x1F11C,0,0,8493,3}, +{0x1F11D,0,0,8496,3}, +{0x1F11E,0,0,8499,3}, +{0x1F11F,0,0,8502,3}, +{0x1F120,0,0,8505,3}, +{0x1F121,0,0,8508,3}, +{0x1F122,0,0,8511,3}, +{0x1F123,0,0,8514,3}, +{0x1F124,0,0,8517,3}, +{0x1F125,0,0,8520,3}, +{0x1F126,0,0,8523,3}, +{0x1F127,0,0,8526,3}, +{0x1F128,0,0,8529,3}, +{0x1F129,0,0,8532,3}, +{0x1F12A,0,0,8535,3}, +{0x1F12B,0,0,8538,1}, +{0x1F12C,0,0,8539,1}, +{0x1F12D,0,0,8540,2}, +{0x1F12E,0,0,8542,2}, +{0x1F130,0,0,8544,1}, +{0x1F131,0,0,8545,1}, +{0x1F132,0,0,8546,1}, +{0x1F133,0,0,8547,1}, +{0x1F134,0,0,8548,1}, +{0x1F135,0,0,8549,1}, +{0x1F136,0,0,8550,1}, +{0x1F137,0,0,8551,1}, +{0x1F138,0,0,8552,1}, +{0x1F139,0,0,8553,1}, +{0x1F13A,0,0,8554,1}, +{0x1F13B,0,0,8555,1}, +{0x1F13C,0,0,8556,1}, +{0x1F13D,0,0,8557,1}, +{0x1F13E,0,0,8558,1}, +{0x1F13F,0,0,8559,1}, +{0x1F140,0,0,8560,1}, +{0x1F141,0,0,8561,1}, +{0x1F142,0,0,8562,1}, +{0x1F143,0,0,8563,1}, +{0x1F144,0,0,8564,1}, +{0x1F145,0,0,8565,1}, +{0x1F146,0,0,8566,1}, +{0x1F147,0,0,8567,1}, +{0x1F148,0,0,8568,1}, +{0x1F149,0,0,8569,1}, +{0x1F14A,0,0,8570,2}, +{0x1F14B,0,0,8572,2}, +{0x1F14C,0,0,8574,2}, +{0x1F14D,0,0,8576,2}, +{0x1F14E,0,0,8578,3}, +{0x1F14F,0,0,8581,2}, +{0x1F16A,0,0,8583,2}, +{0x1F16B,0,0,8585,2}, +{0x1F16C,0,0,8587,2}, +{0x1F190,0,0,8589,2}, +{0x1F200,0,0,8591,2}, +{0x1F201,0,0,8593,2}, +{0x1F202,0,0,8595,1}, +{0x1F210,0,0,8596,1}, +{0x1F211,0,0,8597,1}, +{0x1F212,0,0,8598,1}, +{0x1F213,0,0,8599,2}, +{0x1F214,0,0,8601,1}, +{0x1F215,0,0,8602,1}, +{0x1F216,0,0,8603,1}, +{0x1F217,0,0,8604,1}, +{0x1F218,0,0,8605,1}, +{0x1F219,0,0,8606,1}, +{0x1F21A,0,0,8607,1}, +{0x1F21B,0,0,8608,1}, +{0x1F21C,0,0,8609,1}, +{0x1F21D,0,0,8610,1}, +{0x1F21E,0,0,8611,1}, +{0x1F21F,0,0,8612,1}, +{0x1F220,0,0,8613,1}, +{0x1F221,0,0,8614,1}, +{0x1F222,0,0,8615,1}, +{0x1F223,0,0,8616,1}, +{0x1F224,0,0,8617,1}, +{0x1F225,0,0,8618,1}, +{0x1F226,0,0,8619,1}, +{0x1F227,0,0,8620,1}, +{0x1F228,0,0,8621,1}, +{0x1F229,0,0,8622,1}, +{0x1F22A,0,0,8623,1}, +{0x1F22B,0,0,8624,1}, +{0x1F22C,0,0,8625,1}, +{0x1F22D,0,0,8626,1}, +{0x1F22E,0,0,8627,1}, +{0x1F22F,0,0,8628,1}, +{0x1F230,0,0,8629,1}, +{0x1F231,0,0,8630,1}, +{0x1F232,0,0,8631,1}, +{0x1F233,0,0,8632,1}, +{0x1F234,0,0,8633,1}, +{0x1F235,0,0,8634,1}, +{0x1F236,0,0,8635,1}, +{0x1F237,0,0,8636,1}, +{0x1F238,0,0,8637,1}, +{0x1F239,0,0,8638,1}, +{0x1F23A,0,0,8639,1}, +{0x1F23B,0,0,8640,1}, +{0x1F240,0,0,8641,3}, +{0x1F241,0,0,8644,3}, +{0x1F242,0,0,8647,3}, +{0x1F243,0,0,8650,3}, +{0x1F244,0,0,8653,3}, +{0x1F245,0,0,8656,3}, +{0x1F246,0,0,8659,3}, +{0x1F247,0,0,8662,3}, +{0x1F248,0,0,8665,3}, +{0x1F250,0,0,8668,1}, +{0x1F251,0,0,8669,1}, +{0x1FBF0,0,0,8670,1}, +{0x1FBF1,0,0,8671,1}, +{0x1FBF2,0,0,8672,1}, +{0x1FBF3,0,0,8673,1}, +{0x1FBF4,0,0,8674,1}, +{0x1FBF5,0,0,8675,1}, +{0x1FBF6,0,0,8676,1}, +{0x1FBF7,0,0,8677,1}, +{0x1FBF8,0,0,8678,1}, +{0x1FBF9,0,0,8679,1}, +{0x2F800,8680,1,8680,1}, +{0x2F801,8681,1,8681,1}, +{0x2F802,8682,1,8682,1}, +{0x2F803,8683,1,8683,1}, +{0x2F804,8684,1,8684,1}, +{0x2F805,8685,1,8685,1}, +{0x2F806,8686,1,8686,1}, +{0x2F807,8687,1,8687,1}, +{0x2F808,8688,1,8688,1}, +{0x2F809,8689,1,8689,1}, +{0x2F80A,8690,1,8690,1}, +{0x2F80B,8691,1,8691,1}, +{0x2F80C,8692,1,8692,1}, +{0x2F80D,8693,1,8693,1}, +{0x2F80E,8694,1,8694,1}, +{0x2F80F,8695,1,8695,1}, +{0x2F810,8696,1,8696,1}, +{0x2F811,8697,1,8697,1}, +{0x2F812,8698,1,8698,1}, +{0x2F813,8699,1,8699,1}, +{0x2F814,8700,1,8700,1}, +{0x2F815,8701,1,8701,1}, +{0x2F816,8702,1,8702,1}, +{0x2F817,8703,1,8703,1}, +{0x2F818,8704,1,8704,1}, +{0x2F819,8705,1,8705,1}, +{0x2F81A,8706,1,8706,1}, +{0x2F81B,8707,1,8707,1}, +{0x2F81C,8708,1,8708,1}, +{0x2F81D,8709,1,8709,1}, +{0x2F81E,8710,1,8710,1}, +{0x2F81F,8711,1,8711,1}, +{0x2F820,8712,1,8712,1}, +{0x2F821,8713,1,8713,1}, +{0x2F822,8714,1,8714,1}, +{0x2F823,8715,1,8715,1}, +{0x2F824,8716,1,8716,1}, +{0x2F825,8717,1,8717,1}, +{0x2F826,8718,1,8718,1}, +{0x2F827,8719,1,8719,1}, +{0x2F828,8720,1,8720,1}, +{0x2F829,8721,1,8721,1}, +{0x2F82A,8722,1,8722,1}, +{0x2F82B,8723,1,8723,1}, +{0x2F82C,8724,1,8724,1}, +{0x2F82D,8725,1,8725,1}, +{0x2F82E,8726,1,8726,1}, +{0x2F82F,8727,1,8727,1}, +{0x2F830,8728,1,8728,1}, +{0x2F831,8729,1,8729,1}, +{0x2F832,8730,1,8730,1}, +{0x2F833,8731,1,8731,1}, +{0x2F834,8732,1,8732,1}, +{0x2F835,8733,1,8733,1}, +{0x2F836,8734,1,8734,1}, +{0x2F837,8735,1,8735,1}, +{0x2F838,8736,1,8736,1}, +{0x2F839,8737,1,8737,1}, +{0x2F83A,8738,1,8738,1}, +{0x2F83B,8739,1,8739,1}, +{0x2F83C,8740,1,8740,1}, +{0x2F83D,8741,1,8741,1}, +{0x2F83E,8742,1,8742,1}, +{0x2F83F,8743,1,8743,1}, +{0x2F840,8744,1,8744,1}, +{0x2F841,8745,1,8745,1}, +{0x2F842,8746,1,8746,1}, +{0x2F843,8747,1,8747,1}, +{0x2F844,8748,1,8748,1}, +{0x2F845,8749,1,8749,1}, +{0x2F846,8750,1,8750,1}, +{0x2F847,8751,1,8751,1}, +{0x2F848,8752,1,8752,1}, +{0x2F849,8753,1,8753,1}, +{0x2F84A,8754,1,8754,1}, +{0x2F84B,8755,1,8755,1}, +{0x2F84C,8756,1,8756,1}, +{0x2F84D,8757,1,8757,1}, +{0x2F84E,8758,1,8758,1}, +{0x2F84F,8759,1,8759,1}, +{0x2F850,8760,1,8760,1}, +{0x2F851,8761,1,8761,1}, +{0x2F852,8762,1,8762,1}, +{0x2F853,8763,1,8763,1}, +{0x2F854,8764,1,8764,1}, +{0x2F855,8765,1,8765,1}, +{0x2F856,8766,1,8766,1}, +{0x2F857,8767,1,8767,1}, +{0x2F858,8768,1,8768,1}, +{0x2F859,8769,1,8769,1}, +{0x2F85A,8770,1,8770,1}, +{0x2F85B,8771,1,8771,1}, +{0x2F85C,8772,1,8772,1}, +{0x2F85D,8773,1,8773,1}, +{0x2F85E,8774,1,8774,1}, +{0x2F85F,8775,1,8775,1}, +{0x2F860,8776,1,8776,1}, +{0x2F861,8777,1,8777,1}, +{0x2F862,8778,1,8778,1}, +{0x2F863,8779,1,8779,1}, +{0x2F864,8780,1,8780,1}, +{0x2F865,8781,1,8781,1}, +{0x2F866,8782,1,8782,1}, +{0x2F867,8783,1,8783,1}, +{0x2F868,8784,1,8784,1}, +{0x2F869,8785,1,8785,1}, +{0x2F86A,8786,1,8786,1}, +{0x2F86B,8787,1,8787,1}, +{0x2F86C,8788,1,8788,1}, +{0x2F86D,8789,1,8789,1}, +{0x2F86E,8790,1,8790,1}, +{0x2F86F,8791,1,8791,1}, +{0x2F870,8792,1,8792,1}, +{0x2F871,8793,1,8793,1}, +{0x2F872,8794,1,8794,1}, +{0x2F873,8795,1,8795,1}, +{0x2F874,8796,1,8796,1}, +{0x2F875,8797,1,8797,1}, +{0x2F876,8798,1,8798,1}, +{0x2F877,8799,1,8799,1}, +{0x2F878,8800,1,8800,1}, +{0x2F879,8801,1,8801,1}, +{0x2F87A,8802,1,8802,1}, +{0x2F87B,8803,1,8803,1}, +{0x2F87C,8804,1,8804,1}, +{0x2F87D,8805,1,8805,1}, +{0x2F87E,8806,1,8806,1}, +{0x2F87F,8807,1,8807,1}, +{0x2F880,8808,1,8808,1}, +{0x2F881,8809,1,8809,1}, +{0x2F882,8810,1,8810,1}, +{0x2F883,8811,1,8811,1}, +{0x2F884,8812,1,8812,1}, +{0x2F885,8813,1,8813,1}, +{0x2F886,8814,1,8814,1}, +{0x2F887,8815,1,8815,1}, +{0x2F888,8816,1,8816,1}, +{0x2F889,8817,1,8817,1}, +{0x2F88A,8818,1,8818,1}, +{0x2F88B,8819,1,8819,1}, +{0x2F88C,8820,1,8820,1}, +{0x2F88D,8821,1,8821,1}, +{0x2F88E,8822,1,8822,1}, +{0x2F88F,8823,1,8823,1}, +{0x2F890,8824,1,8824,1}, +{0x2F891,8825,1,8825,1}, +{0x2F892,8826,1,8826,1}, +{0x2F893,8827,1,8827,1}, +{0x2F894,8828,1,8828,1}, +{0x2F895,8829,1,8829,1}, +{0x2F896,8830,1,8830,1}, +{0x2F897,8831,1,8831,1}, +{0x2F898,8832,1,8832,1}, +{0x2F899,8833,1,8833,1}, +{0x2F89A,8834,1,8834,1}, +{0x2F89B,8835,1,8835,1}, +{0x2F89C,8836,1,8836,1}, +{0x2F89D,8837,1,8837,1}, +{0x2F89E,8838,1,8838,1}, +{0x2F89F,8839,1,8839,1}, +{0x2F8A0,8840,1,8840,1}, +{0x2F8A1,8841,1,8841,1}, +{0x2F8A2,8842,1,8842,1}, +{0x2F8A3,8843,1,8843,1}, +{0x2F8A4,8844,1,8844,1}, +{0x2F8A5,8845,1,8845,1}, +{0x2F8A6,8846,1,8846,1}, +{0x2F8A7,8847,1,8847,1}, +{0x2F8A8,8848,1,8848,1}, +{0x2F8A9,8849,1,8849,1}, +{0x2F8AA,8850,1,8850,1}, +{0x2F8AB,8851,1,8851,1}, +{0x2F8AC,8852,1,8852,1}, +{0x2F8AD,8853,1,8853,1}, +{0x2F8AE,8854,1,8854,1}, +{0x2F8AF,8855,1,8855,1}, +{0x2F8B0,8856,1,8856,1}, +{0x2F8B1,8857,1,8857,1}, +{0x2F8B2,8858,1,8858,1}, +{0x2F8B3,8859,1,8859,1}, +{0x2F8B4,8860,1,8860,1}, +{0x2F8B5,8861,1,8861,1}, +{0x2F8B6,8862,1,8862,1}, +{0x2F8B7,8863,1,8863,1}, +{0x2F8B8,8864,1,8864,1}, +{0x2F8B9,8865,1,8865,1}, +{0x2F8BA,8866,1,8866,1}, +{0x2F8BB,8867,1,8867,1}, +{0x2F8BC,8868,1,8868,1}, +{0x2F8BD,8869,1,8869,1}, +{0x2F8BE,8870,1,8870,1}, +{0x2F8BF,8871,1,8871,1}, +{0x2F8C0,8872,1,8872,1}, +{0x2F8C1,8873,1,8873,1}, +{0x2F8C2,8874,1,8874,1}, +{0x2F8C3,8875,1,8875,1}, +{0x2F8C4,8876,1,8876,1}, +{0x2F8C5,8877,1,8877,1}, +{0x2F8C6,8878,1,8878,1}, +{0x2F8C7,8879,1,8879,1}, +{0x2F8C8,8880,1,8880,1}, +{0x2F8C9,8881,1,8881,1}, +{0x2F8CA,8882,1,8882,1}, +{0x2F8CB,8883,1,8883,1}, +{0x2F8CC,8884,1,8884,1}, +{0x2F8CD,8885,1,8885,1}, +{0x2F8CE,8886,1,8886,1}, +{0x2F8CF,8887,1,8887,1}, +{0x2F8D0,8888,1,8888,1}, +{0x2F8D1,8889,1,8889,1}, +{0x2F8D2,8890,1,8890,1}, +{0x2F8D3,8891,1,8891,1}, +{0x2F8D4,8892,1,8892,1}, +{0x2F8D5,8893,1,8893,1}, +{0x2F8D6,8894,1,8894,1}, +{0x2F8D7,8895,1,8895,1}, +{0x2F8D8,8896,1,8896,1}, +{0x2F8D9,8897,1,8897,1}, +{0x2F8DA,8898,1,8898,1}, +{0x2F8DB,8899,1,8899,1}, +{0x2F8DC,8900,1,8900,1}, +{0x2F8DD,8901,1,8901,1}, +{0x2F8DE,8902,1,8902,1}, +{0x2F8DF,8903,1,8903,1}, +{0x2F8E0,8904,1,8904,1}, +{0x2F8E1,8905,1,8905,1}, +{0x2F8E2,8906,1,8906,1}, +{0x2F8E3,8907,1,8907,1}, +{0x2F8E4,8908,1,8908,1}, +{0x2F8E5,8909,1,8909,1}, +{0x2F8E6,8910,1,8910,1}, +{0x2F8E7,8911,1,8911,1}, +{0x2F8E8,8912,1,8912,1}, +{0x2F8E9,8913,1,8913,1}, +{0x2F8EA,8914,1,8914,1}, +{0x2F8EB,8915,1,8915,1}, +{0x2F8EC,8916,1,8916,1}, +{0x2F8ED,8917,1,8917,1}, +{0x2F8EE,8918,1,8918,1}, +{0x2F8EF,8919,1,8919,1}, +{0x2F8F0,8920,1,8920,1}, +{0x2F8F1,8921,1,8921,1}, +{0x2F8F2,8922,1,8922,1}, +{0x2F8F3,8923,1,8923,1}, +{0x2F8F4,8924,1,8924,1}, +{0x2F8F5,8925,1,8925,1}, +{0x2F8F6,8926,1,8926,1}, +{0x2F8F7,8927,1,8927,1}, +{0x2F8F8,8928,1,8928,1}, +{0x2F8F9,8929,1,8929,1}, +{0x2F8FA,8930,1,8930,1}, +{0x2F8FB,8931,1,8931,1}, +{0x2F8FC,8932,1,8932,1}, +{0x2F8FD,8933,1,8933,1}, +{0x2F8FE,8934,1,8934,1}, +{0x2F8FF,8935,1,8935,1}, +{0x2F900,8936,1,8936,1}, +{0x2F901,8937,1,8937,1}, +{0x2F902,8938,1,8938,1}, +{0x2F903,8939,1,8939,1}, +{0x2F904,8940,1,8940,1}, +{0x2F905,8941,1,8941,1}, +{0x2F906,8942,1,8942,1}, +{0x2F907,8943,1,8943,1}, +{0x2F908,8944,1,8944,1}, +{0x2F909,8945,1,8945,1}, +{0x2F90A,8946,1,8946,1}, +{0x2F90B,8947,1,8947,1}, +{0x2F90C,8948,1,8948,1}, +{0x2F90D,8949,1,8949,1}, +{0x2F90E,8950,1,8950,1}, +{0x2F90F,8951,1,8951,1}, +{0x2F910,8952,1,8952,1}, +{0x2F911,8953,1,8953,1}, +{0x2F912,8954,1,8954,1}, +{0x2F913,8955,1,8955,1}, +{0x2F914,8956,1,8956,1}, +{0x2F915,8957,1,8957,1}, +{0x2F916,8958,1,8958,1}, +{0x2F917,8959,1,8959,1}, +{0x2F918,8960,1,8960,1}, +{0x2F919,8961,1,8961,1}, +{0x2F91A,8962,1,8962,1}, +{0x2F91B,8963,1,8963,1}, +{0x2F91C,8964,1,8964,1}, +{0x2F91D,8965,1,8965,1}, +{0x2F91E,8966,1,8966,1}, +{0x2F91F,8967,1,8967,1}, +{0x2F920,8968,1,8968,1}, +{0x2F921,8969,1,8969,1}, +{0x2F922,8970,1,8970,1}, +{0x2F923,8971,1,8971,1}, +{0x2F924,8972,1,8972,1}, +{0x2F925,8973,1,8973,1}, +{0x2F926,8974,1,8974,1}, +{0x2F927,8975,1,8975,1}, +{0x2F928,8976,1,8976,1}, +{0x2F929,8977,1,8977,1}, +{0x2F92A,8978,1,8978,1}, +{0x2F92B,8979,1,8979,1}, +{0x2F92C,8980,1,8980,1}, +{0x2F92D,8981,1,8981,1}, +{0x2F92E,8982,1,8982,1}, +{0x2F92F,8983,1,8983,1}, +{0x2F930,8984,1,8984,1}, +{0x2F931,8985,1,8985,1}, +{0x2F932,8986,1,8986,1}, +{0x2F933,8987,1,8987,1}, +{0x2F934,8988,1,8988,1}, +{0x2F935,8989,1,8989,1}, +{0x2F936,8990,1,8990,1}, +{0x2F937,8991,1,8991,1}, +{0x2F938,8992,1,8992,1}, +{0x2F939,8993,1,8993,1}, +{0x2F93A,8994,1,8994,1}, +{0x2F93B,8995,1,8995,1}, +{0x2F93C,8996,1,8996,1}, +{0x2F93D,8997,1,8997,1}, +{0x2F93E,8998,1,8998,1}, +{0x2F93F,8999,1,8999,1}, +{0x2F940,9000,1,9000,1}, +{0x2F941,9001,1,9001,1}, +{0x2F942,9002,1,9002,1}, +{0x2F943,9003,1,9003,1}, +{0x2F944,9004,1,9004,1}, +{0x2F945,9005,1,9005,1}, +{0x2F946,9006,1,9006,1}, +{0x2F947,9007,1,9007,1}, +{0x2F948,9008,1,9008,1}, +{0x2F949,9009,1,9009,1}, +{0x2F94A,9010,1,9010,1}, +{0x2F94B,9011,1,9011,1}, +{0x2F94C,9012,1,9012,1}, +{0x2F94D,9013,1,9013,1}, +{0x2F94E,9014,1,9014,1}, +{0x2F94F,9015,1,9015,1}, +{0x2F950,9016,1,9016,1}, +{0x2F951,9017,1,9017,1}, +{0x2F952,9018,1,9018,1}, +{0x2F953,9019,1,9019,1}, +{0x2F954,9020,1,9020,1}, +{0x2F955,9021,1,9021,1}, +{0x2F956,9022,1,9022,1}, +{0x2F957,9023,1,9023,1}, +{0x2F958,9024,1,9024,1}, +{0x2F959,9025,1,9025,1}, +{0x2F95A,9026,1,9026,1}, +{0x2F95B,9027,1,9027,1}, +{0x2F95C,9028,1,9028,1}, +{0x2F95D,9029,1,9029,1}, +{0x2F95E,9030,1,9030,1}, +{0x2F95F,9031,1,9031,1}, +{0x2F960,9032,1,9032,1}, +{0x2F961,9033,1,9033,1}, +{0x2F962,9034,1,9034,1}, +{0x2F963,9035,1,9035,1}, +{0x2F964,9036,1,9036,1}, +{0x2F965,9037,1,9037,1}, +{0x2F966,9038,1,9038,1}, +{0x2F967,9039,1,9039,1}, +{0x2F968,9040,1,9040,1}, +{0x2F969,9041,1,9041,1}, +{0x2F96A,9042,1,9042,1}, +{0x2F96B,9043,1,9043,1}, +{0x2F96C,9044,1,9044,1}, +{0x2F96D,9045,1,9045,1}, +{0x2F96E,9046,1,9046,1}, +{0x2F96F,9047,1,9047,1}, +{0x2F970,9048,1,9048,1}, +{0x2F971,9049,1,9049,1}, +{0x2F972,9050,1,9050,1}, +{0x2F973,9051,1,9051,1}, +{0x2F974,9052,1,9052,1}, +{0x2F975,9053,1,9053,1}, +{0x2F976,9054,1,9054,1}, +{0x2F977,9055,1,9055,1}, +{0x2F978,9056,1,9056,1}, +{0x2F979,9057,1,9057,1}, +{0x2F97A,9058,1,9058,1}, +{0x2F97B,9059,1,9059,1}, +{0x2F97C,9060,1,9060,1}, +{0x2F97D,9061,1,9061,1}, +{0x2F97E,9062,1,9062,1}, +{0x2F97F,9063,1,9063,1}, +{0x2F980,9064,1,9064,1}, +{0x2F981,9065,1,9065,1}, +{0x2F982,9066,1,9066,1}, +{0x2F983,9067,1,9067,1}, +{0x2F984,9068,1,9068,1}, +{0x2F985,9069,1,9069,1}, +{0x2F986,9070,1,9070,1}, +{0x2F987,9071,1,9071,1}, +{0x2F988,9072,1,9072,1}, +{0x2F989,9073,1,9073,1}, +{0x2F98A,9074,1,9074,1}, +{0x2F98B,9075,1,9075,1}, +{0x2F98C,9076,1,9076,1}, +{0x2F98D,9077,1,9077,1}, +{0x2F98E,9078,1,9078,1}, +{0x2F98F,9079,1,9079,1}, +{0x2F990,9080,1,9080,1}, +{0x2F991,9081,1,9081,1}, +{0x2F992,9082,1,9082,1}, +{0x2F993,9083,1,9083,1}, +{0x2F994,9084,1,9084,1}, +{0x2F995,9085,1,9085,1}, +{0x2F996,9086,1,9086,1}, +{0x2F997,9087,1,9087,1}, +{0x2F998,9088,1,9088,1}, +{0x2F999,9089,1,9089,1}, +{0x2F99A,9090,1,9090,1}, +{0x2F99B,9091,1,9091,1}, +{0x2F99C,9092,1,9092,1}, +{0x2F99D,9093,1,9093,1}, +{0x2F99E,9094,1,9094,1}, +{0x2F99F,9095,1,9095,1}, +{0x2F9A0,9096,1,9096,1}, +{0x2F9A1,9097,1,9097,1}, +{0x2F9A2,9098,1,9098,1}, +{0x2F9A3,9099,1,9099,1}, +{0x2F9A4,9100,1,9100,1}, +{0x2F9A5,9101,1,9101,1}, +{0x2F9A6,9102,1,9102,1}, +{0x2F9A7,9103,1,9103,1}, +{0x2F9A8,9104,1,9104,1}, +{0x2F9A9,9105,1,9105,1}, +{0x2F9AA,9106,1,9106,1}, +{0x2F9AB,9107,1,9107,1}, +{0x2F9AC,9108,1,9108,1}, +{0x2F9AD,9109,1,9109,1}, +{0x2F9AE,9110,1,9110,1}, +{0x2F9AF,9111,1,9111,1}, +{0x2F9B0,9112,1,9112,1}, +{0x2F9B1,9113,1,9113,1}, +{0x2F9B2,9114,1,9114,1}, +{0x2F9B3,9115,1,9115,1}, +{0x2F9B4,9116,1,9116,1}, +{0x2F9B5,9117,1,9117,1}, +{0x2F9B6,9118,1,9118,1}, +{0x2F9B7,9119,1,9119,1}, +{0x2F9B8,9120,1,9120,1}, +{0x2F9B9,9121,1,9121,1}, +{0x2F9BA,9122,1,9122,1}, +{0x2F9BB,9123,1,9123,1}, +{0x2F9BC,9124,1,9124,1}, +{0x2F9BD,9125,1,9125,1}, +{0x2F9BE,9126,1,9126,1}, +{0x2F9BF,9127,1,9127,1}, +{0x2F9C0,9128,1,9128,1}, +{0x2F9C1,9129,1,9129,1}, +{0x2F9C2,9130,1,9130,1}, +{0x2F9C3,9131,1,9131,1}, +{0x2F9C4,9132,1,9132,1}, +{0x2F9C5,9133,1,9133,1}, +{0x2F9C6,9134,1,9134,1}, +{0x2F9C7,9135,1,9135,1}, +{0x2F9C8,9136,1,9136,1}, +{0x2F9C9,9137,1,9137,1}, +{0x2F9CA,9138,1,9138,1}, +{0x2F9CB,9139,1,9139,1}, +{0x2F9CC,9140,1,9140,1}, +{0x2F9CD,9141,1,9141,1}, +{0x2F9CE,9142,1,9142,1}, +{0x2F9CF,9143,1,9143,1}, +{0x2F9D0,9144,1,9144,1}, +{0x2F9D1,9145,1,9145,1}, +{0x2F9D2,9146,1,9146,1}, +{0x2F9D3,9147,1,9147,1}, +{0x2F9D4,9148,1,9148,1}, +{0x2F9D5,9149,1,9149,1}, +{0x2F9D6,9150,1,9150,1}, +{0x2F9D7,9151,1,9151,1}, +{0x2F9D8,9152,1,9152,1}, +{0x2F9D9,9153,1,9153,1}, +{0x2F9DA,9154,1,9154,1}, +{0x2F9DB,9155,1,9155,1}, +{0x2F9DC,9156,1,9156,1}, +{0x2F9DD,9157,1,9157,1}, +{0x2F9DE,9158,1,9158,1}, +{0x2F9DF,9159,1,9159,1}, +{0x2F9E0,9160,1,9160,1}, +{0x2F9E1,9161,1,9161,1}, +{0x2F9E2,9162,1,9162,1}, +{0x2F9E3,9163,1,9163,1}, +{0x2F9E4,9164,1,9164,1}, +{0x2F9E5,9165,1,9165,1}, +{0x2F9E6,9166,1,9166,1}, +{0x2F9E7,9167,1,9167,1}, +{0x2F9E8,9168,1,9168,1}, +{0x2F9E9,9169,1,9169,1}, +{0x2F9EA,9170,1,9170,1}, +{0x2F9EB,9171,1,9171,1}, +{0x2F9EC,9172,1,9172,1}, +{0x2F9ED,9173,1,9173,1}, +{0x2F9EE,9174,1,9174,1}, +{0x2F9EF,9175,1,9175,1}, +{0x2F9F0,9176,1,9176,1}, +{0x2F9F1,9177,1,9177,1}, +{0x2F9F2,9178,1,9178,1}, +{0x2F9F3,9179,1,9179,1}, +{0x2F9F4,9180,1,9180,1}, +{0x2F9F5,9181,1,9181,1}, +{0x2F9F6,9182,1,9182,1}, +{0x2F9F7,9183,1,9183,1}, +{0x2F9F8,9184,1,9184,1}, +{0x2F9F9,9185,1,9185,1}, +{0x2F9FA,9186,1,9186,1}, +{0x2F9FB,9187,1,9187,1}, +{0x2F9FC,9188,1,9188,1}, +{0x2F9FD,9189,1,9189,1}, +{0x2F9FE,9190,1,9190,1}, +{0x2F9FF,9191,1,9191,1}, +{0x2FA00,9192,1,9192,1}, +{0x2FA01,9193,1,9193,1}, +{0x2FA02,9194,1,9194,1}, +{0x2FA03,9195,1,9195,1}, +{0x2FA04,9196,1,9196,1}, +{0x2FA05,9197,1,9197,1}, +{0x2FA06,9198,1,9198,1}, +{0x2FA07,9199,1,9199,1}, +{0x2FA08,9200,1,9200,1}, +{0x2FA09,9201,1,9201,1}, +{0x2FA0A,9202,1,9202,1}, +{0x2FA0B,9203,1,9203,1}, +{0x2FA0C,9204,1,9204,1}, +{0x2FA0D,9205,1,9205,1}, +{0x2FA0E,9206,1,9206,1}, +{0x2FA0F,9207,1,9207,1}, +{0x2FA10,9208,1,9208,1}, +{0x2FA11,9209,1,9209,1}, +{0x2FA12,9210,1,9210,1}, +{0x2FA13,9211,1,9211,1}, +{0x2FA14,9212,1,9212,1}, +{0x2FA15,9213,1,9213,1}, +{0x2FA16,9214,1,9214,1}, +{0x2FA17,9215,1,9215,1}, +{0x2FA18,9216,1,9216,1}, +{0x2FA19,9217,1,9217,1}, +{0x2FA1A,9218,1,9218,1}, +{0x2FA1B,9219,1,9219,1}, +{0x2FA1C,9220,1,9220,1}, +{0x2FA1D,9221,1,9221,1}, +}; +const size_t k_decomp_rows_n = sizeof(k_decomp_rows)/sizeof(k_decomp_rows[0]); + +/* Primary composites: (starter, combining) -> composed. Sorted by (a, b). */ +const ComposeRow k_compose[] = { +{0x3C,0x338,0x226E}, +{0x3D,0x338,0x2260}, +{0x3E,0x338,0x226F}, +{0x41,0x300,0xC0}, +{0x41,0x301,0xC1}, +{0x41,0x302,0xC2}, +{0x41,0x303,0xC3}, +{0x41,0x304,0x100}, +{0x41,0x306,0x102}, +{0x41,0x307,0x226}, +{0x41,0x308,0xC4}, +{0x41,0x309,0x1EA2}, +{0x41,0x30A,0xC5}, +{0x41,0x30C,0x1CD}, +{0x41,0x30F,0x200}, +{0x41,0x311,0x202}, +{0x41,0x323,0x1EA0}, +{0x41,0x325,0x1E00}, +{0x41,0x328,0x104}, +{0x42,0x307,0x1E02}, +{0x42,0x323,0x1E04}, +{0x42,0x331,0x1E06}, +{0x43,0x301,0x106}, +{0x43,0x302,0x108}, +{0x43,0x307,0x10A}, +{0x43,0x30C,0x10C}, +{0x43,0x327,0xC7}, +{0x44,0x307,0x1E0A}, +{0x44,0x30C,0x10E}, +{0x44,0x323,0x1E0C}, +{0x44,0x327,0x1E10}, +{0x44,0x32D,0x1E12}, +{0x44,0x331,0x1E0E}, +{0x45,0x300,0xC8}, +{0x45,0x301,0xC9}, +{0x45,0x302,0xCA}, +{0x45,0x303,0x1EBC}, +{0x45,0x304,0x112}, +{0x45,0x306,0x114}, +{0x45,0x307,0x116}, +{0x45,0x308,0xCB}, +{0x45,0x309,0x1EBA}, +{0x45,0x30C,0x11A}, +{0x45,0x30F,0x204}, +{0x45,0x311,0x206}, +{0x45,0x323,0x1EB8}, +{0x45,0x327,0x228}, +{0x45,0x328,0x118}, +{0x45,0x32D,0x1E18}, +{0x45,0x330,0x1E1A}, +{0x46,0x307,0x1E1E}, +{0x47,0x301,0x1F4}, +{0x47,0x302,0x11C}, +{0x47,0x304,0x1E20}, +{0x47,0x306,0x11E}, +{0x47,0x307,0x120}, +{0x47,0x30C,0x1E6}, +{0x47,0x327,0x122}, +{0x48,0x302,0x124}, +{0x48,0x307,0x1E22}, +{0x48,0x308,0x1E26}, +{0x48,0x30C,0x21E}, +{0x48,0x323,0x1E24}, +{0x48,0x327,0x1E28}, +{0x48,0x32E,0x1E2A}, +{0x49,0x300,0xCC}, +{0x49,0x301,0xCD}, +{0x49,0x302,0xCE}, +{0x49,0x303,0x128}, +{0x49,0x304,0x12A}, +{0x49,0x306,0x12C}, +{0x49,0x307,0x130}, +{0x49,0x308,0xCF}, +{0x49,0x309,0x1EC8}, +{0x49,0x30C,0x1CF}, +{0x49,0x30F,0x208}, +{0x49,0x311,0x20A}, +{0x49,0x323,0x1ECA}, +{0x49,0x328,0x12E}, +{0x49,0x330,0x1E2C}, +{0x4A,0x302,0x134}, +{0x4B,0x301,0x1E30}, +{0x4B,0x30C,0x1E8}, +{0x4B,0x323,0x1E32}, +{0x4B,0x327,0x136}, +{0x4B,0x331,0x1E34}, +{0x4C,0x301,0x139}, +{0x4C,0x30C,0x13D}, +{0x4C,0x323,0x1E36}, +{0x4C,0x327,0x13B}, +{0x4C,0x32D,0x1E3C}, +{0x4C,0x331,0x1E3A}, +{0x4D,0x301,0x1E3E}, +{0x4D,0x307,0x1E40}, +{0x4D,0x323,0x1E42}, +{0x4E,0x300,0x1F8}, +{0x4E,0x301,0x143}, +{0x4E,0x303,0xD1}, +{0x4E,0x307,0x1E44}, +{0x4E,0x30C,0x147}, +{0x4E,0x323,0x1E46}, +{0x4E,0x327,0x145}, +{0x4E,0x32D,0x1E4A}, +{0x4E,0x331,0x1E48}, +{0x4F,0x300,0xD2}, +{0x4F,0x301,0xD3}, +{0x4F,0x302,0xD4}, +{0x4F,0x303,0xD5}, +{0x4F,0x304,0x14C}, +{0x4F,0x306,0x14E}, +{0x4F,0x307,0x22E}, +{0x4F,0x308,0xD6}, +{0x4F,0x309,0x1ECE}, +{0x4F,0x30B,0x150}, +{0x4F,0x30C,0x1D1}, +{0x4F,0x30F,0x20C}, +{0x4F,0x311,0x20E}, +{0x4F,0x31B,0x1A0}, +{0x4F,0x323,0x1ECC}, +{0x4F,0x328,0x1EA}, +{0x50,0x301,0x1E54}, +{0x50,0x307,0x1E56}, +{0x52,0x301,0x154}, +{0x52,0x307,0x1E58}, +{0x52,0x30C,0x158}, +{0x52,0x30F,0x210}, +{0x52,0x311,0x212}, +{0x52,0x323,0x1E5A}, +{0x52,0x327,0x156}, +{0x52,0x331,0x1E5E}, +{0x53,0x301,0x15A}, +{0x53,0x302,0x15C}, +{0x53,0x307,0x1E60}, +{0x53,0x30C,0x160}, +{0x53,0x323,0x1E62}, +{0x53,0x326,0x218}, +{0x53,0x327,0x15E}, +{0x54,0x307,0x1E6A}, +{0x54,0x30C,0x164}, +{0x54,0x323,0x1E6C}, +{0x54,0x326,0x21A}, +{0x54,0x327,0x162}, +{0x54,0x32D,0x1E70}, +{0x54,0x331,0x1E6E}, +{0x55,0x300,0xD9}, +{0x55,0x301,0xDA}, +{0x55,0x302,0xDB}, +{0x55,0x303,0x168}, +{0x55,0x304,0x16A}, +{0x55,0x306,0x16C}, +{0x55,0x308,0xDC}, +{0x55,0x309,0x1EE6}, +{0x55,0x30A,0x16E}, +{0x55,0x30B,0x170}, +{0x55,0x30C,0x1D3}, +{0x55,0x30F,0x214}, +{0x55,0x311,0x216}, +{0x55,0x31B,0x1AF}, +{0x55,0x323,0x1EE4}, +{0x55,0x324,0x1E72}, +{0x55,0x328,0x172}, +{0x55,0x32D,0x1E76}, +{0x55,0x330,0x1E74}, +{0x56,0x303,0x1E7C}, +{0x56,0x323,0x1E7E}, +{0x57,0x300,0x1E80}, +{0x57,0x301,0x1E82}, +{0x57,0x302,0x174}, +{0x57,0x307,0x1E86}, +{0x57,0x308,0x1E84}, +{0x57,0x323,0x1E88}, +{0x58,0x307,0x1E8A}, +{0x58,0x308,0x1E8C}, +{0x59,0x300,0x1EF2}, +{0x59,0x301,0xDD}, +{0x59,0x302,0x176}, +{0x59,0x303,0x1EF8}, +{0x59,0x304,0x232}, +{0x59,0x307,0x1E8E}, +{0x59,0x308,0x178}, +{0x59,0x309,0x1EF6}, +{0x59,0x323,0x1EF4}, +{0x5A,0x301,0x179}, +{0x5A,0x302,0x1E90}, +{0x5A,0x307,0x17B}, +{0x5A,0x30C,0x17D}, +{0x5A,0x323,0x1E92}, +{0x5A,0x331,0x1E94}, +{0x61,0x300,0xE0}, +{0x61,0x301,0xE1}, +{0x61,0x302,0xE2}, +{0x61,0x303,0xE3}, +{0x61,0x304,0x101}, +{0x61,0x306,0x103}, +{0x61,0x307,0x227}, +{0x61,0x308,0xE4}, +{0x61,0x309,0x1EA3}, +{0x61,0x30A,0xE5}, +{0x61,0x30C,0x1CE}, +{0x61,0x30F,0x201}, +{0x61,0x311,0x203}, +{0x61,0x323,0x1EA1}, +{0x61,0x325,0x1E01}, +{0x61,0x328,0x105}, +{0x62,0x307,0x1E03}, +{0x62,0x323,0x1E05}, +{0x62,0x331,0x1E07}, +{0x63,0x301,0x107}, +{0x63,0x302,0x109}, +{0x63,0x307,0x10B}, +{0x63,0x30C,0x10D}, +{0x63,0x327,0xE7}, +{0x64,0x307,0x1E0B}, +{0x64,0x30C,0x10F}, +{0x64,0x323,0x1E0D}, +{0x64,0x327,0x1E11}, +{0x64,0x32D,0x1E13}, +{0x64,0x331,0x1E0F}, +{0x65,0x300,0xE8}, +{0x65,0x301,0xE9}, +{0x65,0x302,0xEA}, +{0x65,0x303,0x1EBD}, +{0x65,0x304,0x113}, +{0x65,0x306,0x115}, +{0x65,0x307,0x117}, +{0x65,0x308,0xEB}, +{0x65,0x309,0x1EBB}, +{0x65,0x30C,0x11B}, +{0x65,0x30F,0x205}, +{0x65,0x311,0x207}, +{0x65,0x323,0x1EB9}, +{0x65,0x327,0x229}, +{0x65,0x328,0x119}, +{0x65,0x32D,0x1E19}, +{0x65,0x330,0x1E1B}, +{0x66,0x307,0x1E1F}, +{0x67,0x301,0x1F5}, +{0x67,0x302,0x11D}, +{0x67,0x304,0x1E21}, +{0x67,0x306,0x11F}, +{0x67,0x307,0x121}, +{0x67,0x30C,0x1E7}, +{0x67,0x327,0x123}, +{0x68,0x302,0x125}, +{0x68,0x307,0x1E23}, +{0x68,0x308,0x1E27}, +{0x68,0x30C,0x21F}, +{0x68,0x323,0x1E25}, +{0x68,0x327,0x1E29}, +{0x68,0x32E,0x1E2B}, +{0x68,0x331,0x1E96}, +{0x69,0x300,0xEC}, +{0x69,0x301,0xED}, +{0x69,0x302,0xEE}, +{0x69,0x303,0x129}, +{0x69,0x304,0x12B}, +{0x69,0x306,0x12D}, +{0x69,0x308,0xEF}, +{0x69,0x309,0x1EC9}, +{0x69,0x30C,0x1D0}, +{0x69,0x30F,0x209}, +{0x69,0x311,0x20B}, +{0x69,0x323,0x1ECB}, +{0x69,0x328,0x12F}, +{0x69,0x330,0x1E2D}, +{0x6A,0x302,0x135}, +{0x6A,0x30C,0x1F0}, +{0x6B,0x301,0x1E31}, +{0x6B,0x30C,0x1E9}, +{0x6B,0x323,0x1E33}, +{0x6B,0x327,0x137}, +{0x6B,0x331,0x1E35}, +{0x6C,0x301,0x13A}, +{0x6C,0x30C,0x13E}, +{0x6C,0x323,0x1E37}, +{0x6C,0x327,0x13C}, +{0x6C,0x32D,0x1E3D}, +{0x6C,0x331,0x1E3B}, +{0x6D,0x301,0x1E3F}, +{0x6D,0x307,0x1E41}, +{0x6D,0x323,0x1E43}, +{0x6E,0x300,0x1F9}, +{0x6E,0x301,0x144}, +{0x6E,0x303,0xF1}, +{0x6E,0x307,0x1E45}, +{0x6E,0x30C,0x148}, +{0x6E,0x323,0x1E47}, +{0x6E,0x327,0x146}, +{0x6E,0x32D,0x1E4B}, +{0x6E,0x331,0x1E49}, +{0x6F,0x300,0xF2}, +{0x6F,0x301,0xF3}, +{0x6F,0x302,0xF4}, +{0x6F,0x303,0xF5}, +{0x6F,0x304,0x14D}, +{0x6F,0x306,0x14F}, +{0x6F,0x307,0x22F}, +{0x6F,0x308,0xF6}, +{0x6F,0x309,0x1ECF}, +{0x6F,0x30B,0x151}, +{0x6F,0x30C,0x1D2}, +{0x6F,0x30F,0x20D}, +{0x6F,0x311,0x20F}, +{0x6F,0x31B,0x1A1}, +{0x6F,0x323,0x1ECD}, +{0x6F,0x328,0x1EB}, +{0x70,0x301,0x1E55}, +{0x70,0x307,0x1E57}, +{0x72,0x301,0x155}, +{0x72,0x307,0x1E59}, +{0x72,0x30C,0x159}, +{0x72,0x30F,0x211}, +{0x72,0x311,0x213}, +{0x72,0x323,0x1E5B}, +{0x72,0x327,0x157}, +{0x72,0x331,0x1E5F}, +{0x73,0x301,0x15B}, +{0x73,0x302,0x15D}, +{0x73,0x307,0x1E61}, +{0x73,0x30C,0x161}, +{0x73,0x323,0x1E63}, +{0x73,0x326,0x219}, +{0x73,0x327,0x15F}, +{0x74,0x307,0x1E6B}, +{0x74,0x308,0x1E97}, +{0x74,0x30C,0x165}, +{0x74,0x323,0x1E6D}, +{0x74,0x326,0x21B}, +{0x74,0x327,0x163}, +{0x74,0x32D,0x1E71}, +{0x74,0x331,0x1E6F}, +{0x75,0x300,0xF9}, +{0x75,0x301,0xFA}, +{0x75,0x302,0xFB}, +{0x75,0x303,0x169}, +{0x75,0x304,0x16B}, +{0x75,0x306,0x16D}, +{0x75,0x308,0xFC}, +{0x75,0x309,0x1EE7}, +{0x75,0x30A,0x16F}, +{0x75,0x30B,0x171}, +{0x75,0x30C,0x1D4}, +{0x75,0x30F,0x215}, +{0x75,0x311,0x217}, +{0x75,0x31B,0x1B0}, +{0x75,0x323,0x1EE5}, +{0x75,0x324,0x1E73}, +{0x75,0x328,0x173}, +{0x75,0x32D,0x1E77}, +{0x75,0x330,0x1E75}, +{0x76,0x303,0x1E7D}, +{0x76,0x323,0x1E7F}, +{0x77,0x300,0x1E81}, +{0x77,0x301,0x1E83}, +{0x77,0x302,0x175}, +{0x77,0x307,0x1E87}, +{0x77,0x308,0x1E85}, +{0x77,0x30A,0x1E98}, +{0x77,0x323,0x1E89}, +{0x78,0x307,0x1E8B}, +{0x78,0x308,0x1E8D}, +{0x79,0x300,0x1EF3}, +{0x79,0x301,0xFD}, +{0x79,0x302,0x177}, +{0x79,0x303,0x1EF9}, +{0x79,0x304,0x233}, +{0x79,0x307,0x1E8F}, +{0x79,0x308,0xFF}, +{0x79,0x309,0x1EF7}, +{0x79,0x30A,0x1E99}, +{0x79,0x323,0x1EF5}, +{0x7A,0x301,0x17A}, +{0x7A,0x302,0x1E91}, +{0x7A,0x307,0x17C}, +{0x7A,0x30C,0x17E}, +{0x7A,0x323,0x1E93}, +{0x7A,0x331,0x1E95}, +{0xA8,0x300,0x1FED}, +{0xA8,0x301,0x385}, +{0xA8,0x342,0x1FC1}, +{0xC2,0x300,0x1EA6}, +{0xC2,0x301,0x1EA4}, +{0xC2,0x303,0x1EAA}, +{0xC2,0x309,0x1EA8}, +{0xC4,0x304,0x1DE}, +{0xC5,0x301,0x1FA}, +{0xC6,0x301,0x1FC}, +{0xC6,0x304,0x1E2}, +{0xC7,0x301,0x1E08}, +{0xCA,0x300,0x1EC0}, +{0xCA,0x301,0x1EBE}, +{0xCA,0x303,0x1EC4}, +{0xCA,0x309,0x1EC2}, +{0xCF,0x301,0x1E2E}, +{0xD4,0x300,0x1ED2}, +{0xD4,0x301,0x1ED0}, +{0xD4,0x303,0x1ED6}, +{0xD4,0x309,0x1ED4}, +{0xD5,0x301,0x1E4C}, +{0xD5,0x304,0x22C}, +{0xD5,0x308,0x1E4E}, +{0xD6,0x304,0x22A}, +{0xD8,0x301,0x1FE}, +{0xDC,0x300,0x1DB}, +{0xDC,0x301,0x1D7}, +{0xDC,0x304,0x1D5}, +{0xDC,0x30C,0x1D9}, +{0xE2,0x300,0x1EA7}, +{0xE2,0x301,0x1EA5}, +{0xE2,0x303,0x1EAB}, +{0xE2,0x309,0x1EA9}, +{0xE4,0x304,0x1DF}, +{0xE5,0x301,0x1FB}, +{0xE6,0x301,0x1FD}, +{0xE6,0x304,0x1E3}, +{0xE7,0x301,0x1E09}, +{0xEA,0x300,0x1EC1}, +{0xEA,0x301,0x1EBF}, +{0xEA,0x303,0x1EC5}, +{0xEA,0x309,0x1EC3}, +{0xEF,0x301,0x1E2F}, +{0xF4,0x300,0x1ED3}, +{0xF4,0x301,0x1ED1}, +{0xF4,0x303,0x1ED7}, +{0xF4,0x309,0x1ED5}, +{0xF5,0x301,0x1E4D}, +{0xF5,0x304,0x22D}, +{0xF5,0x308,0x1E4F}, +{0xF6,0x304,0x22B}, +{0xF8,0x301,0x1FF}, +{0xFC,0x300,0x1DC}, +{0xFC,0x301,0x1D8}, +{0xFC,0x304,0x1D6}, +{0xFC,0x30C,0x1DA}, +{0x102,0x300,0x1EB0}, +{0x102,0x301,0x1EAE}, +{0x102,0x303,0x1EB4}, +{0x102,0x309,0x1EB2}, +{0x103,0x300,0x1EB1}, +{0x103,0x301,0x1EAF}, +{0x103,0x303,0x1EB5}, +{0x103,0x309,0x1EB3}, +{0x112,0x300,0x1E14}, +{0x112,0x301,0x1E16}, +{0x113,0x300,0x1E15}, +{0x113,0x301,0x1E17}, +{0x14C,0x300,0x1E50}, +{0x14C,0x301,0x1E52}, +{0x14D,0x300,0x1E51}, +{0x14D,0x301,0x1E53}, +{0x15A,0x307,0x1E64}, +{0x15B,0x307,0x1E65}, +{0x160,0x307,0x1E66}, +{0x161,0x307,0x1E67}, +{0x168,0x301,0x1E78}, +{0x169,0x301,0x1E79}, +{0x16A,0x308,0x1E7A}, +{0x16B,0x308,0x1E7B}, +{0x17F,0x307,0x1E9B}, +{0x1A0,0x300,0x1EDC}, +{0x1A0,0x301,0x1EDA}, +{0x1A0,0x303,0x1EE0}, +{0x1A0,0x309,0x1EDE}, +{0x1A0,0x323,0x1EE2}, +{0x1A1,0x300,0x1EDD}, +{0x1A1,0x301,0x1EDB}, +{0x1A1,0x303,0x1EE1}, +{0x1A1,0x309,0x1EDF}, +{0x1A1,0x323,0x1EE3}, +{0x1AF,0x300,0x1EEA}, +{0x1AF,0x301,0x1EE8}, +{0x1AF,0x303,0x1EEE}, +{0x1AF,0x309,0x1EEC}, +{0x1AF,0x323,0x1EF0}, +{0x1B0,0x300,0x1EEB}, +{0x1B0,0x301,0x1EE9}, +{0x1B0,0x303,0x1EEF}, +{0x1B0,0x309,0x1EED}, +{0x1B0,0x323,0x1EF1}, +{0x1B7,0x30C,0x1EE}, +{0x1EA,0x304,0x1EC}, +{0x1EB,0x304,0x1ED}, +{0x226,0x304,0x1E0}, +{0x227,0x304,0x1E1}, +{0x228,0x306,0x1E1C}, +{0x229,0x306,0x1E1D}, +{0x22E,0x304,0x230}, +{0x22F,0x304,0x231}, +{0x292,0x30C,0x1EF}, +{0x391,0x300,0x1FBA}, +{0x391,0x301,0x386}, +{0x391,0x304,0x1FB9}, +{0x391,0x306,0x1FB8}, +{0x391,0x313,0x1F08}, +{0x391,0x314,0x1F09}, +{0x391,0x345,0x1FBC}, +{0x395,0x300,0x1FC8}, +{0x395,0x301,0x388}, +{0x395,0x313,0x1F18}, +{0x395,0x314,0x1F19}, +{0x397,0x300,0x1FCA}, +{0x397,0x301,0x389}, +{0x397,0x313,0x1F28}, +{0x397,0x314,0x1F29}, +{0x397,0x345,0x1FCC}, +{0x399,0x300,0x1FDA}, +{0x399,0x301,0x38A}, +{0x399,0x304,0x1FD9}, +{0x399,0x306,0x1FD8}, +{0x399,0x308,0x3AA}, +{0x399,0x313,0x1F38}, +{0x399,0x314,0x1F39}, +{0x39F,0x300,0x1FF8}, +{0x39F,0x301,0x38C}, +{0x39F,0x313,0x1F48}, +{0x39F,0x314,0x1F49}, +{0x3A1,0x314,0x1FEC}, +{0x3A5,0x300,0x1FEA}, +{0x3A5,0x301,0x38E}, +{0x3A5,0x304,0x1FE9}, +{0x3A5,0x306,0x1FE8}, +{0x3A5,0x308,0x3AB}, +{0x3A5,0x314,0x1F59}, +{0x3A9,0x300,0x1FFA}, +{0x3A9,0x301,0x38F}, +{0x3A9,0x313,0x1F68}, +{0x3A9,0x314,0x1F69}, +{0x3A9,0x345,0x1FFC}, +{0x3AC,0x345,0x1FB4}, +{0x3AE,0x345,0x1FC4}, +{0x3B1,0x300,0x1F70}, +{0x3B1,0x301,0x3AC}, +{0x3B1,0x304,0x1FB1}, +{0x3B1,0x306,0x1FB0}, +{0x3B1,0x313,0x1F00}, +{0x3B1,0x314,0x1F01}, +{0x3B1,0x342,0x1FB6}, +{0x3B1,0x345,0x1FB3}, +{0x3B5,0x300,0x1F72}, +{0x3B5,0x301,0x3AD}, +{0x3B5,0x313,0x1F10}, +{0x3B5,0x314,0x1F11}, +{0x3B7,0x300,0x1F74}, +{0x3B7,0x301,0x3AE}, +{0x3B7,0x313,0x1F20}, +{0x3B7,0x314,0x1F21}, +{0x3B7,0x342,0x1FC6}, +{0x3B7,0x345,0x1FC3}, +{0x3B9,0x300,0x1F76}, +{0x3B9,0x301,0x3AF}, +{0x3B9,0x304,0x1FD1}, +{0x3B9,0x306,0x1FD0}, +{0x3B9,0x308,0x3CA}, +{0x3B9,0x313,0x1F30}, +{0x3B9,0x314,0x1F31}, +{0x3B9,0x342,0x1FD6}, +{0x3BF,0x300,0x1F78}, +{0x3BF,0x301,0x3CC}, +{0x3BF,0x313,0x1F40}, +{0x3BF,0x314,0x1F41}, +{0x3C1,0x313,0x1FE4}, +{0x3C1,0x314,0x1FE5}, +{0x3C5,0x300,0x1F7A}, +{0x3C5,0x301,0x3CD}, +{0x3C5,0x304,0x1FE1}, +{0x3C5,0x306,0x1FE0}, +{0x3C5,0x308,0x3CB}, +{0x3C5,0x313,0x1F50}, +{0x3C5,0x314,0x1F51}, +{0x3C5,0x342,0x1FE6}, +{0x3C9,0x300,0x1F7C}, +{0x3C9,0x301,0x3CE}, +{0x3C9,0x313,0x1F60}, +{0x3C9,0x314,0x1F61}, +{0x3C9,0x342,0x1FF6}, +{0x3C9,0x345,0x1FF3}, +{0x3CA,0x300,0x1FD2}, +{0x3CA,0x301,0x390}, +{0x3CA,0x342,0x1FD7}, +{0x3CB,0x300,0x1FE2}, +{0x3CB,0x301,0x3B0}, +{0x3CB,0x342,0x1FE7}, +{0x3CE,0x345,0x1FF4}, +{0x3D2,0x301,0x3D3}, +{0x3D2,0x308,0x3D4}, +{0x406,0x308,0x407}, +{0x410,0x306,0x4D0}, +{0x410,0x308,0x4D2}, +{0x413,0x301,0x403}, +{0x415,0x300,0x400}, +{0x415,0x306,0x4D6}, +{0x415,0x308,0x401}, +{0x416,0x306,0x4C1}, +{0x416,0x308,0x4DC}, +{0x417,0x308,0x4DE}, +{0x418,0x300,0x40D}, +{0x418,0x304,0x4E2}, +{0x418,0x306,0x419}, +{0x418,0x308,0x4E4}, +{0x41A,0x301,0x40C}, +{0x41E,0x308,0x4E6}, +{0x423,0x304,0x4EE}, +{0x423,0x306,0x40E}, +{0x423,0x308,0x4F0}, +{0x423,0x30B,0x4F2}, +{0x427,0x308,0x4F4}, +{0x42B,0x308,0x4F8}, +{0x42D,0x308,0x4EC}, +{0x430,0x306,0x4D1}, +{0x430,0x308,0x4D3}, +{0x433,0x301,0x453}, +{0x435,0x300,0x450}, +{0x435,0x306,0x4D7}, +{0x435,0x308,0x451}, +{0x436,0x306,0x4C2}, +{0x436,0x308,0x4DD}, +{0x437,0x308,0x4DF}, +{0x438,0x300,0x45D}, +{0x438,0x304,0x4E3}, +{0x438,0x306,0x439}, +{0x438,0x308,0x4E5}, +{0x43A,0x301,0x45C}, +{0x43E,0x308,0x4E7}, +{0x443,0x304,0x4EF}, +{0x443,0x306,0x45E}, +{0x443,0x308,0x4F1}, +{0x443,0x30B,0x4F3}, +{0x447,0x308,0x4F5}, +{0x44B,0x308,0x4F9}, +{0x44D,0x308,0x4ED}, +{0x456,0x308,0x457}, +{0x474,0x30F,0x476}, +{0x475,0x30F,0x477}, +{0x4D8,0x308,0x4DA}, +{0x4D9,0x308,0x4DB}, +{0x4E8,0x308,0x4EA}, +{0x4E9,0x308,0x4EB}, +{0x627,0x653,0x622}, +{0x627,0x654,0x623}, +{0x627,0x655,0x625}, +{0x648,0x654,0x624}, +{0x64A,0x654,0x626}, +{0x6C1,0x654,0x6C2}, +{0x6D2,0x654,0x6D3}, +{0x6D5,0x654,0x6C0}, +{0x928,0x93C,0x929}, +{0x930,0x93C,0x931}, +{0x933,0x93C,0x934}, +{0x9C7,0x9BE,0x9CB}, +{0x9C7,0x9D7,0x9CC}, +{0xB47,0xB3E,0xB4B}, +{0xB47,0xB56,0xB48}, +{0xB47,0xB57,0xB4C}, +{0xB92,0xBD7,0xB94}, +{0xBC6,0xBBE,0xBCA}, +{0xBC6,0xBD7,0xBCC}, +{0xBC7,0xBBE,0xBCB}, +{0xC46,0xC56,0xC48}, +{0xCBF,0xCD5,0xCC0}, +{0xCC6,0xCC2,0xCCA}, +{0xCC6,0xCD5,0xCC7}, +{0xCC6,0xCD6,0xCC8}, +{0xCCA,0xCD5,0xCCB}, +{0xD46,0xD3E,0xD4A}, +{0xD46,0xD57,0xD4C}, +{0xD47,0xD3E,0xD4B}, +{0xDD9,0xDCA,0xDDA}, +{0xDD9,0xDCF,0xDDC}, +{0xDD9,0xDDF,0xDDE}, +{0xDDC,0xDCA,0xDDD}, +{0x1025,0x102E,0x1026}, +{0x1B05,0x1B35,0x1B06}, +{0x1B07,0x1B35,0x1B08}, +{0x1B09,0x1B35,0x1B0A}, +{0x1B0B,0x1B35,0x1B0C}, +{0x1B0D,0x1B35,0x1B0E}, +{0x1B11,0x1B35,0x1B12}, +{0x1B3A,0x1B35,0x1B3B}, +{0x1B3C,0x1B35,0x1B3D}, +{0x1B3E,0x1B35,0x1B40}, +{0x1B3F,0x1B35,0x1B41}, +{0x1B42,0x1B35,0x1B43}, +{0x1E36,0x304,0x1E38}, +{0x1E37,0x304,0x1E39}, +{0x1E5A,0x304,0x1E5C}, +{0x1E5B,0x304,0x1E5D}, +{0x1E62,0x307,0x1E68}, +{0x1E63,0x307,0x1E69}, +{0x1EA0,0x302,0x1EAC}, +{0x1EA0,0x306,0x1EB6}, +{0x1EA1,0x302,0x1EAD}, +{0x1EA1,0x306,0x1EB7}, +{0x1EB8,0x302,0x1EC6}, +{0x1EB9,0x302,0x1EC7}, +{0x1ECC,0x302,0x1ED8}, +{0x1ECD,0x302,0x1ED9}, +{0x1F00,0x300,0x1F02}, +{0x1F00,0x301,0x1F04}, +{0x1F00,0x342,0x1F06}, +{0x1F00,0x345,0x1F80}, +{0x1F01,0x300,0x1F03}, +{0x1F01,0x301,0x1F05}, +{0x1F01,0x342,0x1F07}, +{0x1F01,0x345,0x1F81}, +{0x1F02,0x345,0x1F82}, +{0x1F03,0x345,0x1F83}, +{0x1F04,0x345,0x1F84}, +{0x1F05,0x345,0x1F85}, +{0x1F06,0x345,0x1F86}, +{0x1F07,0x345,0x1F87}, +{0x1F08,0x300,0x1F0A}, +{0x1F08,0x301,0x1F0C}, +{0x1F08,0x342,0x1F0E}, +{0x1F08,0x345,0x1F88}, +{0x1F09,0x300,0x1F0B}, +{0x1F09,0x301,0x1F0D}, +{0x1F09,0x342,0x1F0F}, +{0x1F09,0x345,0x1F89}, +{0x1F0A,0x345,0x1F8A}, +{0x1F0B,0x345,0x1F8B}, +{0x1F0C,0x345,0x1F8C}, +{0x1F0D,0x345,0x1F8D}, +{0x1F0E,0x345,0x1F8E}, +{0x1F0F,0x345,0x1F8F}, +{0x1F10,0x300,0x1F12}, +{0x1F10,0x301,0x1F14}, +{0x1F11,0x300,0x1F13}, +{0x1F11,0x301,0x1F15}, +{0x1F18,0x300,0x1F1A}, +{0x1F18,0x301,0x1F1C}, +{0x1F19,0x300,0x1F1B}, +{0x1F19,0x301,0x1F1D}, +{0x1F20,0x300,0x1F22}, +{0x1F20,0x301,0x1F24}, +{0x1F20,0x342,0x1F26}, +{0x1F20,0x345,0x1F90}, +{0x1F21,0x300,0x1F23}, +{0x1F21,0x301,0x1F25}, +{0x1F21,0x342,0x1F27}, +{0x1F21,0x345,0x1F91}, +{0x1F22,0x345,0x1F92}, +{0x1F23,0x345,0x1F93}, +{0x1F24,0x345,0x1F94}, +{0x1F25,0x345,0x1F95}, +{0x1F26,0x345,0x1F96}, +{0x1F27,0x345,0x1F97}, +{0x1F28,0x300,0x1F2A}, +{0x1F28,0x301,0x1F2C}, +{0x1F28,0x342,0x1F2E}, +{0x1F28,0x345,0x1F98}, +{0x1F29,0x300,0x1F2B}, +{0x1F29,0x301,0x1F2D}, +{0x1F29,0x342,0x1F2F}, +{0x1F29,0x345,0x1F99}, +{0x1F2A,0x345,0x1F9A}, +{0x1F2B,0x345,0x1F9B}, +{0x1F2C,0x345,0x1F9C}, +{0x1F2D,0x345,0x1F9D}, +{0x1F2E,0x345,0x1F9E}, +{0x1F2F,0x345,0x1F9F}, +{0x1F30,0x300,0x1F32}, +{0x1F30,0x301,0x1F34}, +{0x1F30,0x342,0x1F36}, +{0x1F31,0x300,0x1F33}, +{0x1F31,0x301,0x1F35}, +{0x1F31,0x342,0x1F37}, +{0x1F38,0x300,0x1F3A}, +{0x1F38,0x301,0x1F3C}, +{0x1F38,0x342,0x1F3E}, +{0x1F39,0x300,0x1F3B}, +{0x1F39,0x301,0x1F3D}, +{0x1F39,0x342,0x1F3F}, +{0x1F40,0x300,0x1F42}, +{0x1F40,0x301,0x1F44}, +{0x1F41,0x300,0x1F43}, +{0x1F41,0x301,0x1F45}, +{0x1F48,0x300,0x1F4A}, +{0x1F48,0x301,0x1F4C}, +{0x1F49,0x300,0x1F4B}, +{0x1F49,0x301,0x1F4D}, +{0x1F50,0x300,0x1F52}, +{0x1F50,0x301,0x1F54}, +{0x1F50,0x342,0x1F56}, +{0x1F51,0x300,0x1F53}, +{0x1F51,0x301,0x1F55}, +{0x1F51,0x342,0x1F57}, +{0x1F59,0x300,0x1F5B}, +{0x1F59,0x301,0x1F5D}, +{0x1F59,0x342,0x1F5F}, +{0x1F60,0x300,0x1F62}, +{0x1F60,0x301,0x1F64}, +{0x1F60,0x342,0x1F66}, +{0x1F60,0x345,0x1FA0}, +{0x1F61,0x300,0x1F63}, +{0x1F61,0x301,0x1F65}, +{0x1F61,0x342,0x1F67}, +{0x1F61,0x345,0x1FA1}, +{0x1F62,0x345,0x1FA2}, +{0x1F63,0x345,0x1FA3}, +{0x1F64,0x345,0x1FA4}, +{0x1F65,0x345,0x1FA5}, +{0x1F66,0x345,0x1FA6}, +{0x1F67,0x345,0x1FA7}, +{0x1F68,0x300,0x1F6A}, +{0x1F68,0x301,0x1F6C}, +{0x1F68,0x342,0x1F6E}, +{0x1F68,0x345,0x1FA8}, +{0x1F69,0x300,0x1F6B}, +{0x1F69,0x301,0x1F6D}, +{0x1F69,0x342,0x1F6F}, +{0x1F69,0x345,0x1FA9}, +{0x1F6A,0x345,0x1FAA}, +{0x1F6B,0x345,0x1FAB}, +{0x1F6C,0x345,0x1FAC}, +{0x1F6D,0x345,0x1FAD}, +{0x1F6E,0x345,0x1FAE}, +{0x1F6F,0x345,0x1FAF}, +{0x1F70,0x345,0x1FB2}, +{0x1F74,0x345,0x1FC2}, +{0x1F7C,0x345,0x1FF2}, +{0x1FB6,0x345,0x1FB7}, +{0x1FBF,0x300,0x1FCD}, +{0x1FBF,0x301,0x1FCE}, +{0x1FBF,0x342,0x1FCF}, +{0x1FC6,0x345,0x1FC7}, +{0x1FF6,0x345,0x1FF7}, +{0x1FFE,0x300,0x1FDD}, +{0x1FFE,0x301,0x1FDE}, +{0x1FFE,0x342,0x1FDF}, +{0x2190,0x338,0x219A}, +{0x2192,0x338,0x219B}, +{0x2194,0x338,0x21AE}, +{0x21D0,0x338,0x21CD}, +{0x21D2,0x338,0x21CF}, +{0x21D4,0x338,0x21CE}, +{0x2203,0x338,0x2204}, +{0x2208,0x338,0x2209}, +{0x220B,0x338,0x220C}, +{0x2223,0x338,0x2224}, +{0x2225,0x338,0x2226}, +{0x223C,0x338,0x2241}, +{0x2243,0x338,0x2244}, +{0x2245,0x338,0x2247}, +{0x2248,0x338,0x2249}, +{0x224D,0x338,0x226D}, +{0x2261,0x338,0x2262}, +{0x2264,0x338,0x2270}, +{0x2265,0x338,0x2271}, +{0x2272,0x338,0x2274}, +{0x2273,0x338,0x2275}, +{0x2276,0x338,0x2278}, +{0x2277,0x338,0x2279}, +{0x227A,0x338,0x2280}, +{0x227B,0x338,0x2281}, +{0x227C,0x338,0x22E0}, +{0x227D,0x338,0x22E1}, +{0x2282,0x338,0x2284}, +{0x2283,0x338,0x2285}, +{0x2286,0x338,0x2288}, +{0x2287,0x338,0x2289}, +{0x2291,0x338,0x22E2}, +{0x2292,0x338,0x22E3}, +{0x22A2,0x338,0x22AC}, +{0x22A8,0x338,0x22AD}, +{0x22A9,0x338,0x22AE}, +{0x22AB,0x338,0x22AF}, +{0x22B2,0x338,0x22EA}, +{0x22B3,0x338,0x22EB}, +{0x22B4,0x338,0x22EC}, +{0x22B5,0x338,0x22ED}, +{0x3046,0x3099,0x3094}, +{0x304B,0x3099,0x304C}, +{0x304D,0x3099,0x304E}, +{0x304F,0x3099,0x3050}, +{0x3051,0x3099,0x3052}, +{0x3053,0x3099,0x3054}, +{0x3055,0x3099,0x3056}, +{0x3057,0x3099,0x3058}, +{0x3059,0x3099,0x305A}, +{0x305B,0x3099,0x305C}, +{0x305D,0x3099,0x305E}, +{0x305F,0x3099,0x3060}, +{0x3061,0x3099,0x3062}, +{0x3064,0x3099,0x3065}, +{0x3066,0x3099,0x3067}, +{0x3068,0x3099,0x3069}, +{0x306F,0x3099,0x3070}, +{0x306F,0x309A,0x3071}, +{0x3072,0x3099,0x3073}, +{0x3072,0x309A,0x3074}, +{0x3075,0x3099,0x3076}, +{0x3075,0x309A,0x3077}, +{0x3078,0x3099,0x3079}, +{0x3078,0x309A,0x307A}, +{0x307B,0x3099,0x307C}, +{0x307B,0x309A,0x307D}, +{0x309D,0x3099,0x309E}, +{0x30A6,0x3099,0x30F4}, +{0x30AB,0x3099,0x30AC}, +{0x30AD,0x3099,0x30AE}, +{0x30AF,0x3099,0x30B0}, +{0x30B1,0x3099,0x30B2}, +{0x30B3,0x3099,0x30B4}, +{0x30B5,0x3099,0x30B6}, +{0x30B7,0x3099,0x30B8}, +{0x30B9,0x3099,0x30BA}, +{0x30BB,0x3099,0x30BC}, +{0x30BD,0x3099,0x30BE}, +{0x30BF,0x3099,0x30C0}, +{0x30C1,0x3099,0x30C2}, +{0x30C4,0x3099,0x30C5}, +{0x30C6,0x3099,0x30C7}, +{0x30C8,0x3099,0x30C9}, +{0x30CF,0x3099,0x30D0}, +{0x30CF,0x309A,0x30D1}, +{0x30D2,0x3099,0x30D3}, +{0x30D2,0x309A,0x30D4}, +{0x30D5,0x3099,0x30D6}, +{0x30D5,0x309A,0x30D7}, +{0x30D8,0x3099,0x30D9}, +{0x30D8,0x309A,0x30DA}, +{0x30DB,0x3099,0x30DC}, +{0x30DB,0x309A,0x30DD}, +{0x30EF,0x3099,0x30F7}, +{0x30F0,0x3099,0x30F8}, +{0x30F1,0x3099,0x30F9}, +{0x30F2,0x3099,0x30FA}, +{0x30FD,0x3099,0x30FE}, +{0x105D2,0x307,0x105C9}, +{0x105DA,0x307,0x105E4}, +{0x11099,0x110BA,0x1109A}, +{0x1109B,0x110BA,0x1109C}, +{0x110A5,0x110BA,0x110AB}, +{0x11131,0x11127,0x1112E}, +{0x11132,0x11127,0x1112F}, +{0x11347,0x1133E,0x1134B}, +{0x11347,0x11357,0x1134C}, +{0x11382,0x113C9,0x11383}, +{0x11384,0x113BB,0x11385}, +{0x1138B,0x113C2,0x1138E}, +{0x11390,0x113C9,0x11391}, +{0x113C2,0x113B8,0x113C7}, +{0x113C2,0x113C2,0x113C5}, +{0x113C2,0x113C9,0x113C8}, +{0x114B9,0x114B0,0x114BC}, +{0x114B9,0x114BA,0x114BB}, +{0x114B9,0x114BD,0x114BE}, +{0x115B8,0x115AF,0x115BA}, +{0x115B9,0x115AF,0x115BB}, +{0x11935,0x11930,0x11938}, +{0x1611E,0x1611E,0x16121}, +{0x1611E,0x1611F,0x16123}, +{0x1611E,0x16120,0x16125}, +{0x1611E,0x16129,0x16122}, +{0x16121,0x1611F,0x16126}, +{0x16121,0x16120,0x16128}, +{0x16122,0x1611F,0x16127}, +{0x16129,0x1611F,0x16124}, +{0x16D63,0x16D67,0x16D69}, +{0x16D67,0x16D67,0x16D68}, +{0x16D69,0x16D67,0x16D6A}, +}; +const size_t k_compose_n = sizeof(k_compose)/sizeof(k_compose[0]); + +/* Canonical combining class, run-length coded; class 0 is the default and absent. */ +const CccRow k_ccc[] = { +{0x300,0x314,230}, +{0x315,0x315,232}, +{0x316,0x319,220}, +{0x31A,0x31A,232}, +{0x31B,0x31B,216}, +{0x31C,0x320,220}, +{0x321,0x322,202}, +{0x323,0x326,220}, +{0x327,0x328,202}, +{0x329,0x333,220}, +{0x334,0x338,1}, +{0x339,0x33C,220}, +{0x33D,0x344,230}, +{0x345,0x345,240}, +{0x346,0x346,230}, +{0x347,0x349,220}, +{0x34A,0x34C,230}, +{0x34D,0x34E,220}, +{0x350,0x352,230}, +{0x353,0x356,220}, +{0x357,0x357,230}, +{0x358,0x358,232}, +{0x359,0x35A,220}, +{0x35B,0x35B,230}, +{0x35C,0x35C,233}, +{0x35D,0x35E,234}, +{0x35F,0x35F,233}, +{0x360,0x361,234}, +{0x362,0x362,233}, +{0x363,0x36F,230}, +{0x483,0x487,230}, +{0x591,0x591,220}, +{0x592,0x595,230}, +{0x596,0x596,220}, +{0x597,0x599,230}, +{0x59A,0x59A,222}, +{0x59B,0x59B,220}, +{0x59C,0x5A1,230}, +{0x5A2,0x5A7,220}, +{0x5A8,0x5A9,230}, +{0x5AA,0x5AA,220}, +{0x5AB,0x5AC,230}, +{0x5AD,0x5AD,222}, +{0x5AE,0x5AE,228}, +{0x5AF,0x5AF,230}, +{0x5B0,0x5B0,10}, +{0x5B1,0x5B1,11}, +{0x5B2,0x5B2,12}, +{0x5B3,0x5B3,13}, +{0x5B4,0x5B4,14}, +{0x5B5,0x5B5,15}, +{0x5B6,0x5B6,16}, +{0x5B7,0x5B7,17}, +{0x5B8,0x5B8,18}, +{0x5B9,0x5BA,19}, +{0x5BB,0x5BB,20}, +{0x5BC,0x5BC,21}, +{0x5BD,0x5BD,22}, +{0x5BF,0x5BF,23}, +{0x5C1,0x5C1,24}, +{0x5C2,0x5C2,25}, +{0x5C4,0x5C4,230}, +{0x5C5,0x5C5,220}, +{0x5C7,0x5C7,18}, +{0x610,0x617,230}, +{0x618,0x618,30}, +{0x619,0x619,31}, +{0x61A,0x61A,32}, +{0x64B,0x64B,27}, +{0x64C,0x64C,28}, +{0x64D,0x64D,29}, +{0x64E,0x64E,30}, +{0x64F,0x64F,31}, +{0x650,0x650,32}, +{0x651,0x651,33}, +{0x652,0x652,34}, +{0x653,0x654,230}, +{0x655,0x656,220}, +{0x657,0x65B,230}, +{0x65C,0x65C,220}, +{0x65D,0x65E,230}, +{0x65F,0x65F,220}, +{0x670,0x670,35}, +{0x6D6,0x6DC,230}, +{0x6DF,0x6E2,230}, +{0x6E3,0x6E3,220}, +{0x6E4,0x6E4,230}, +{0x6E7,0x6E8,230}, +{0x6EA,0x6EA,220}, +{0x6EB,0x6EC,230}, +{0x6ED,0x6ED,220}, +{0x711,0x711,36}, +{0x730,0x730,230}, +{0x731,0x731,220}, +{0x732,0x733,230}, +{0x734,0x734,220}, +{0x735,0x736,230}, +{0x737,0x739,220}, +{0x73A,0x73A,230}, +{0x73B,0x73C,220}, +{0x73D,0x73D,230}, +{0x73E,0x73E,220}, +{0x73F,0x741,230}, +{0x742,0x742,220}, +{0x743,0x743,230}, +{0x744,0x744,220}, +{0x745,0x745,230}, +{0x746,0x746,220}, +{0x747,0x747,230}, +{0x748,0x748,220}, +{0x749,0x74A,230}, +{0x7EB,0x7F1,230}, +{0x7F2,0x7F2,220}, +{0x7F3,0x7F3,230}, +{0x7FD,0x7FD,220}, +{0x816,0x819,230}, +{0x81B,0x823,230}, +{0x825,0x827,230}, +{0x829,0x82D,230}, +{0x859,0x85B,220}, +{0x897,0x898,230}, +{0x899,0x89B,220}, +{0x89C,0x89F,230}, +{0x8CA,0x8CE,230}, +{0x8CF,0x8D3,220}, +{0x8D4,0x8E1,230}, +{0x8E3,0x8E3,220}, +{0x8E4,0x8E5,230}, +{0x8E6,0x8E6,220}, +{0x8E7,0x8E8,230}, +{0x8E9,0x8E9,220}, +{0x8EA,0x8EC,230}, +{0x8ED,0x8EF,220}, +{0x8F0,0x8F0,27}, +{0x8F1,0x8F1,28}, +{0x8F2,0x8F2,29}, +{0x8F3,0x8F5,230}, +{0x8F6,0x8F6,220}, +{0x8F7,0x8F8,230}, +{0x8F9,0x8FA,220}, +{0x8FB,0x8FF,230}, +{0x93C,0x93C,7}, +{0x94D,0x94D,9}, +{0x951,0x951,230}, +{0x952,0x952,220}, +{0x953,0x954,230}, +{0x9BC,0x9BC,7}, +{0x9CD,0x9CD,9}, +{0x9FE,0x9FE,230}, +{0xA3C,0xA3C,7}, +{0xA4D,0xA4D,9}, +{0xABC,0xABC,7}, +{0xACD,0xACD,9}, +{0xB3C,0xB3C,7}, +{0xB4D,0xB4D,9}, +{0xBCD,0xBCD,9}, +{0xC3C,0xC3C,7}, +{0xC4D,0xC4D,9}, +{0xC55,0xC55,84}, +{0xC56,0xC56,91}, +{0xCBC,0xCBC,7}, +{0xCCD,0xCCD,9}, +{0xD3B,0xD3C,9}, +{0xD4D,0xD4D,9}, +{0xDCA,0xDCA,9}, +{0xE38,0xE39,103}, +{0xE3A,0xE3A,9}, +{0xE48,0xE4B,107}, +{0xEB8,0xEB9,118}, +{0xEBA,0xEBA,9}, +{0xEC8,0xECB,122}, +{0xF18,0xF19,220}, +{0xF35,0xF35,220}, +{0xF37,0xF37,220}, +{0xF39,0xF39,216}, +{0xF71,0xF71,129}, +{0xF72,0xF72,130}, +{0xF74,0xF74,132}, +{0xF7A,0xF7D,130}, +{0xF80,0xF80,130}, +{0xF82,0xF83,230}, +{0xF84,0xF84,9}, +{0xF86,0xF87,230}, +{0xFC6,0xFC6,220}, +{0x1037,0x1037,7}, +{0x1039,0x103A,9}, +{0x108D,0x108D,220}, +{0x135D,0x135F,230}, +{0x1714,0x1715,9}, +{0x1734,0x1734,9}, +{0x17D2,0x17D2,9}, +{0x17DD,0x17DD,230}, +{0x18A9,0x18A9,228}, +{0x1939,0x1939,222}, +{0x193A,0x193A,230}, +{0x193B,0x193B,220}, +{0x1A17,0x1A17,230}, +{0x1A18,0x1A18,220}, +{0x1A60,0x1A60,9}, +{0x1A75,0x1A7C,230}, +{0x1A7F,0x1A7F,220}, +{0x1AB0,0x1AB4,230}, +{0x1AB5,0x1ABA,220}, +{0x1ABB,0x1ABC,230}, +{0x1ABD,0x1ABD,220}, +{0x1ABF,0x1AC0,220}, +{0x1AC1,0x1AC2,230}, +{0x1AC3,0x1AC4,220}, +{0x1AC5,0x1AC9,230}, +{0x1ACA,0x1ACA,220}, +{0x1ACB,0x1ADC,230}, +{0x1ADD,0x1ADD,220}, +{0x1AE0,0x1AE5,230}, +{0x1AE6,0x1AE6,220}, +{0x1AE7,0x1AEA,230}, +{0x1AEB,0x1AEB,234}, +{0x1B34,0x1B34,7}, +{0x1B44,0x1B44,9}, +{0x1B6B,0x1B6B,230}, +{0x1B6C,0x1B6C,220}, +{0x1B6D,0x1B73,230}, +{0x1BAA,0x1BAB,9}, +{0x1BE6,0x1BE6,7}, +{0x1BF2,0x1BF3,9}, +{0x1C37,0x1C37,7}, +{0x1CD0,0x1CD2,230}, +{0x1CD4,0x1CD4,1}, +{0x1CD5,0x1CD9,220}, +{0x1CDA,0x1CDB,230}, +{0x1CDC,0x1CDF,220}, +{0x1CE0,0x1CE0,230}, +{0x1CE2,0x1CE8,1}, +{0x1CED,0x1CED,220}, +{0x1CF4,0x1CF4,230}, +{0x1CF8,0x1CF9,230}, +{0x1DC0,0x1DC1,230}, +{0x1DC2,0x1DC2,220}, +{0x1DC3,0x1DC9,230}, +{0x1DCA,0x1DCA,220}, +{0x1DCB,0x1DCC,230}, +{0x1DCD,0x1DCD,234}, +{0x1DCE,0x1DCE,214}, +{0x1DCF,0x1DCF,220}, +{0x1DD0,0x1DD0,202}, +{0x1DD1,0x1DF5,230}, +{0x1DF6,0x1DF6,232}, +{0x1DF7,0x1DF8,228}, +{0x1DF9,0x1DF9,220}, +{0x1DFA,0x1DFA,218}, +{0x1DFB,0x1DFB,230}, +{0x1DFC,0x1DFC,233}, +{0x1DFD,0x1DFD,220}, +{0x1DFE,0x1DFE,230}, +{0x1DFF,0x1DFF,220}, +{0x20D0,0x20D1,230}, +{0x20D2,0x20D3,1}, +{0x20D4,0x20D7,230}, +{0x20D8,0x20DA,1}, +{0x20DB,0x20DC,230}, +{0x20E1,0x20E1,230}, +{0x20E5,0x20E6,1}, +{0x20E7,0x20E7,230}, +{0x20E8,0x20E8,220}, +{0x20E9,0x20E9,230}, +{0x20EA,0x20EB,1}, +{0x20EC,0x20EF,220}, +{0x20F0,0x20F0,230}, +{0x2CEF,0x2CF1,230}, +{0x2D7F,0x2D7F,9}, +{0x2DE0,0x2DFF,230}, +{0x302A,0x302A,218}, +{0x302B,0x302B,228}, +{0x302C,0x302C,232}, +{0x302D,0x302D,222}, +{0x302E,0x302F,224}, +{0x3099,0x309A,8}, +{0xA66F,0xA66F,230}, +{0xA674,0xA67D,230}, +{0xA69E,0xA69F,230}, +{0xA6F0,0xA6F1,230}, +{0xA806,0xA806,9}, +{0xA82C,0xA82C,9}, +{0xA8C4,0xA8C4,9}, +{0xA8E0,0xA8F1,230}, +{0xA92B,0xA92D,220}, +{0xA953,0xA953,9}, +{0xA9B3,0xA9B3,7}, +{0xA9C0,0xA9C0,9}, +{0xAAB0,0xAAB0,230}, +{0xAAB2,0xAAB3,230}, +{0xAAB4,0xAAB4,220}, +{0xAAB7,0xAAB8,230}, +{0xAABE,0xAABF,230}, +{0xAAC1,0xAAC1,230}, +{0xAAF6,0xAAF6,9}, +{0xABED,0xABED,9}, +{0xFB1E,0xFB1E,26}, +{0xFE20,0xFE26,230}, +{0xFE27,0xFE2D,220}, +{0xFE2E,0xFE2F,230}, +{0x101FD,0x101FD,220}, +{0x102E0,0x102E0,220}, +{0x10376,0x1037A,230}, +{0x10A0D,0x10A0D,220}, +{0x10A0F,0x10A0F,230}, +{0x10A38,0x10A38,230}, +{0x10A39,0x10A39,1}, +{0x10A3A,0x10A3A,220}, +{0x10A3F,0x10A3F,9}, +{0x10AE5,0x10AE5,230}, +{0x10AE6,0x10AE6,220}, +{0x10D24,0x10D27,230}, +{0x10D69,0x10D6D,230}, +{0x10EAB,0x10EAC,230}, +{0x10EFA,0x10EFB,220}, +{0x10EFD,0x10EFF,220}, +{0x10F46,0x10F47,220}, +{0x10F48,0x10F4A,230}, +{0x10F4B,0x10F4B,220}, +{0x10F4C,0x10F4C,230}, +{0x10F4D,0x10F50,220}, +{0x10F82,0x10F82,230}, +{0x10F83,0x10F83,220}, +{0x10F84,0x10F84,230}, +{0x10F85,0x10F85,220}, +{0x11046,0x11046,9}, +{0x11070,0x11070,9}, +{0x1107F,0x1107F,9}, +{0x110B9,0x110B9,9}, +{0x110BA,0x110BA,7}, +{0x11100,0x11102,230}, +{0x11133,0x11134,9}, +{0x11173,0x11173,7}, +{0x111C0,0x111C0,9}, +{0x111CA,0x111CA,7}, +{0x11235,0x11235,9}, +{0x11236,0x11236,7}, +{0x112E9,0x112E9,7}, +{0x112EA,0x112EA,9}, +{0x1133B,0x1133C,7}, +{0x1134D,0x1134D,9}, +{0x11366,0x1136C,230}, +{0x11370,0x11374,230}, +{0x113CE,0x113D0,9}, +{0x11442,0x11442,9}, +{0x11446,0x11446,7}, +{0x1145E,0x1145E,230}, +{0x114C2,0x114C2,9}, +{0x114C3,0x114C3,7}, +{0x115BF,0x115BF,9}, +{0x115C0,0x115C0,7}, +{0x1163F,0x1163F,9}, +{0x116B6,0x116B6,9}, +{0x116B7,0x116B7,7}, +{0x1172B,0x1172B,9}, +{0x11839,0x11839,9}, +{0x1183A,0x1183A,7}, +{0x1193D,0x1193E,9}, +{0x11943,0x11943,7}, +{0x119E0,0x119E0,9}, +{0x11A34,0x11A34,9}, +{0x11A47,0x11A47,9}, +{0x11A99,0x11A99,9}, +{0x11C3F,0x11C3F,9}, +{0x11D42,0x11D42,7}, +{0x11D44,0x11D45,9}, +{0x11D97,0x11D97,9}, +{0x11F41,0x11F42,9}, +{0x1612F,0x1612F,9}, +{0x16AF0,0x16AF4,1}, +{0x16B30,0x16B36,230}, +{0x16FF0,0x16FF1,6}, +{0x1BC9E,0x1BC9E,1}, +{0x1D165,0x1D166,216}, +{0x1D167,0x1D169,1}, +{0x1D16D,0x1D16D,226}, +{0x1D16E,0x1D172,216}, +{0x1D17B,0x1D182,220}, +{0x1D185,0x1D189,230}, +{0x1D18A,0x1D18B,220}, +{0x1D1AA,0x1D1AD,230}, +{0x1D242,0x1D244,230}, +{0x1E000,0x1E006,230}, +{0x1E008,0x1E018,230}, +{0x1E01B,0x1E021,230}, +{0x1E023,0x1E024,230}, +{0x1E026,0x1E02A,230}, +{0x1E08F,0x1E08F,230}, +{0x1E130,0x1E136,230}, +{0x1E2AE,0x1E2AE,230}, +{0x1E2EC,0x1E2EF,230}, +{0x1E4EC,0x1E4ED,232}, +{0x1E4EE,0x1E4EE,220}, +{0x1E4EF,0x1E4EF,230}, +{0x1E5EE,0x1E5EE,230}, +{0x1E5EF,0x1E5EF,220}, +{0x1E6E3,0x1E6E3,230}, +{0x1E6E6,0x1E6E6,230}, +{0x1E6EE,0x1E6EF,230}, +{0x1E6F5,0x1E6F5,230}, +{0x1E8D0,0x1E8D6,220}, +{0x1E944,0x1E949,230}, +{0x1E94A,0x1E94A,7}, +}; +const size_t k_ccc_n = sizeof(k_ccc)/sizeof(k_ccc[0]); + +} /* namespace rad */ diff --git a/core/util/rad_util.cpp b/core/util/rad_util.cpp new file mode 100644 index 00000000..aa53fef8 --- /dev/null +++ b/core/util/rad_util.cpp @@ -0,0 +1,307 @@ +/* rad_util.cpp -- logging, error strings, dtype arithmetic and tensor helpers. The bedrock every + * other translation unit links against. + */ +#include +#include "../rad_internal.h" + +#include +#include +#include +#include +#include +#include + +namespace rad { + +/* ------------------------------------------------------------------ logging */ + +/* THE LEVEL COMES FROM THE ENVIRONMENT, because nothing in the tree calls `log_set_level`. Without + * that, the level is Info for the life of every process and every RAD_DEBUG and RAD_TRACE site in + * the engine is unreachable code that reads like a diagnostic somebody could turn on -- the + * sampler's mask timing, the grammar's admissible-token count, the drafter's per-position trace, + * the step loop's batch dump. RADIANCE_LOG=error|warn|info|debug|trace reaches them. + * + * Read once, on first use, because this is called from the step path on every logged line. The + * setter stays: a host embedding the engine as a library has no environment to speak through. */ +static Log level_from_env() { + const char* v = std::getenv("RADIANCE_LOG"); + if (!v || !*v) return Log::Info; + if (!std::strcmp(v, "error")) return Log::Error; + if (!std::strcmp(v, "warn")) return Log::Warn; + if (!std::strcmp(v, "info")) return Log::Info; + if (!std::strcmp(v, "debug")) return Log::Debug; + if (!std::strcmp(v, "trace")) return Log::Trace; + /* Not a level. Said at the level that is always on, rather than silently ignored -- a + * misspelt knob that changes nothing looks exactly like a knob that does not work. */ + std::fprintf(stderr, "E RADIANCE_LOG='%s' is not error|warn|info|debug|trace; using info\n", v); + return Log::Info; +} + +static Log g_level = level_from_env(); +void log_set_level(Log l) { g_level = l; } +Log log_level() { return g_level; } + +static const char* level_tag(Log l) { + switch (l) { + case Log::Error: return "E"; + case Log::Warn: return "W"; + case Log::Info: return "I"; + case Log::Debug: return "D"; + default: return "T"; + } +} + +/* Colour only when stderr is a terminal. Piped or redirected it prints ordinary lines, which is + * the same rule the live view follows (spec §16). */ +static const char* level_colour(Log l) { + if (!isatty(2)) return ""; + switch (l) { + case Log::Error: return "\033[31m"; + case Log::Warn: return "\033[33m"; + case Log::Debug: return "\033[36m"; + case Log::Trace: return "\033[90m"; + default: return ""; + } +} + +/* Thread-local because the ranks' declare threads run concurrently; a plain global would have + * whichever rank last entered a scope tagging every other rank's lines. */ +static thread_local int g_log_rank = -1; +static bool g_rank_tags = false; + +void log_rank_tags(bool on) { g_rank_tags = on; } +LogRank::LogRank(int rank) : prev_(g_log_rank) { g_log_rank = rank; } +LogRank::~LogRank() { g_log_rank = prev_; } + +void log_emit(Log l, const char* file, int line, const char* fmt, ...) { + const char* base = std::strrchr(file, '/'); + base = base ? base + 1 : file; + + char msg[4096]; + va_list ap; + va_start(ap, fmt); + vsnprintf(msg, sizeof msg, fmt, ap); + va_end(ap); + + const char* col = level_colour(l); + const char* rst = col[0] ? "\033[0m" : ""; + + char rank[16] = ""; + if (g_rank_tags && g_log_rank >= 0) snprintf(rank, sizeof rank, "[%d]", g_log_rank); + + /* Debug and Trace carry the source site; Info and above do not, because an operator reading + * a normal startup does not care which file said it. */ + if ((int)l >= (int)Log::Debug) + fprintf(stderr, "%s%s%s%s %s:%d %s\n", col, level_tag(l), rank, rst, base, line, msg); + else + fprintf(stderr, "%s%s%s%s %s\n", col, level_tag(l), rank, rst, msg); +} + +void fatal(const char* fmt, ...) { + char msg[4096]; + va_list ap; + va_start(ap, fmt); + vsnprintf(msg, sizeof msg, fmt, ap); + va_end(ap); + fprintf(stderr, "%sradiance: fatal: %s%s\n", isatty(2) ? "\033[31m" : "", msg, + isatty(2) ? "\033[0m" : ""); + fflush(stderr); + _exit(70); +} + +std::string fmt(const char* f, ...) { + va_list ap; + va_start(ap, f); + va_list ap2; + va_copy(ap2, ap); + int n = vsnprintf(nullptr, 0, f, ap); + va_end(ap); + std::string s; + if (n > 0) { + s.resize((size_t)n); + vsnprintf(s.data(), (size_t)n + 1, f, ap2); + } + va_end(ap2); + return s; +} + +uint64_t rad_mono_ns() { + return (uint64_t)std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()).count(); +} + +std::string humanb(int64_t b) { + static const char* u[] = { "B", "KiB", "MiB", "GiB", "TiB" }; + double v = (double)b; + int i = 0; + while (v >= 1024.0 && i < 4) { v /= 1024.0; ++i; } + return i == 0 ? fmt("%lld B", (long long)b) : fmt("%.2f %s", v, u[i]); +} + +std::vector split_ws(std::string_view s) { + std::vector out; + size_t i = 0; + while (i < s.size()) { + while (i < s.size() && (s[i] == ' ' || s[i] == '\t' || s[i] == ',')) ++i; + size_t j = i; + while (j < s.size() && s[j] != ' ' && s[j] != '\t' && s[j] != ',') ++j; + if (j > i) out.push_back(s.substr(i, j - i)); + i = j; + } + return out; +} + +/* ------------------------------------------------------------------ Geometry */ +/* Small, linear-scanned, and that is correct: an op has a handful of parameters and the selector + * touches this at declare, not per step. A hash map here would be slower and less predictable. */ +void Geometry::set_i(std::string_view k, long long v) { + for (size_t i = 0; i < keys_.size(); ++i) + if (keys_[i] == k) { kinds_[i] = RAD_P_INT; ivals_[i] = v; dirty_ = true; return; } + keys_.emplace_back(k); + svals_.emplace_back(); + ivals_.push_back(v); + dvals_.push_back(0.0); + kinds_.push_back(RAD_P_INT); + dirty_ = true; +} + +void Geometry::set_f(std::string_view k, double v) { + for (size_t i = 0; i < keys_.size(); ++i) + if (keys_[i] == k) { kinds_[i] = RAD_P_F64; dvals_[i] = v; dirty_ = true; return; } + keys_.emplace_back(k); + svals_.emplace_back(); + ivals_.push_back(0); + dvals_.push_back(v); + kinds_.push_back(RAD_P_F64); + dirty_ = true; +} + +void Geometry::set_s(std::string_view k, std::string_view v) { + for (size_t i = 0; i < keys_.size(); ++i) + if (keys_[i] == k) { kinds_[i] = RAD_P_STR; svals_[i] = std::string(v); dirty_ = true; return; } + keys_.emplace_back(k); + svals_.emplace_back(v); + ivals_.push_back(0); + dvals_.push_back(0.0); + kinds_.push_back(RAD_P_STR); + dirty_ = true; +} + +bool Geometry::get_i(std::string_view k, long long* out) const { + for (size_t i = 0; i < keys_.size(); ++i) + if (keys_[i] == k && kinds_[i] == RAD_P_INT) { if (out) *out = ivals_[i]; return true; } + return false; +} + +bool Geometry::get_f(std::string_view k, double* out) const { + for (size_t i = 0; i < keys_.size(); ++i) + if (keys_[i] == k && kinds_[i] == RAD_P_F64) { if (out) *out = dvals_[i]; return true; } + return false; +} + +const char* Geometry::get_s(std::string_view k) const { + for (size_t i = 0; i < keys_.size(); ++i) + if (keys_[i] == k && kinds_[i] == RAD_P_STR) return svals_[i].c_str(); + return nullptr; +} + +bool Geometry::has(std::string_view k) const { + for (auto& s : keys_) if (s == k) return true; + return false; +} + +void Geometry::rebuild() const { + auto* self = const_cast(this); + self->view_.clear(); + self->view_.reserve(keys_.size()); + for (size_t i = 0; i < keys_.size(); ++i) { + RadParam p{}; + p.key = keys_[i].c_str(); + p.kind = kinds_[i]; + p.ival = ivals_[i]; + p.dval = dvals_[i]; + p.sval = kinds_[i] == RAD_P_STR ? svals_[i].c_str() : nullptr; + self->view_.push_back(p); + } + dirty_ = false; +} + +const RadParam* Geometry::params() const { if (dirty_) rebuild(); return view_.data(); } +int Geometry::n_params() const { if (dirty_) rebuild(); return (int)view_.size(); } + +std::string Geometry::str() const { + std::string s; + for (size_t i = 0; i < keys_.size(); ++i) { + if (i) s += ' '; + s += keys_[i]; + s += '='; + if (kinds_[i] == RAD_P_STR) s += svals_[i]; + else if (kinds_[i] == RAD_P_F64) s += fmt("%g", dvals_[i]); + else s += fmt("%lld", ivals_[i]); + } + return s; +} + +/* ------------------------------------------------------------------ constraint matching */ +/* A constraint whose key the geometry does not carry does NOT hold. That is libr4d's rule and the + * reason its two-shot all-reduce rows have to precede the one-shot ones: a query that omits `hops` + * fails the row that needs it, so the more constrained row can never be reached unless it is + * asked for. Making the absence a failure is what makes "ask for hops=2 to be handed the two-shot" + * mean something. */ +bool constraint_holds(const RadConstraint& c, const Geometry& g) { + if (c.op == RAD_C_IN) { + const char* v = g.get_s(c.key); + if (!v) { + /* An integer geometry against a string set: compare its decimal form, so + * C_IN("causal", "0 1") works against causal=1. */ + long long iv; + if (!g.get_i(c.key, &iv)) return false; + std::string s = fmt("%lld", iv); + for (auto tok : split_ws(c.sval ? c.sval : "")) if (tok == s) return true; + return false; + } + for (auto tok : split_ws(c.sval ? c.sval : "")) if (tok == v) return true; + return false; + } + + long long v; + if (!g.get_i(c.key, &v)) return false; + switch (c.op) { + case RAD_C_EQ: return v == c.ival; + case RAD_C_LE: return v <= c.ival; + case RAD_C_GE: return v >= c.ival; + case RAD_C_DIV: return c.ival != 0 && (v % c.ival) == 0; + default: return false; + } +} + +std::string constraint_why(const RadConstraint& c, const Geometry& g) { + static const char* opname[] = { "==", "<=", ">=", "%", "in" }; + const char* on = (c.op >= 0 && c.op <= 4) ? opname[c.op] : "?"; + + if (c.op == RAD_C_IN) { + const char* v = g.get_s(c.key); + long long iv; + std::string have = v ? std::string(v) + : (g.get_i(c.key, &iv) ? fmt("%lld", iv) : std::string("")); + return fmt("%s in {%s}, have %s", c.key, c.sval ? c.sval : "", have.c_str()); + } + long long v; + if (!g.get_i(c.key, &v)) return fmt("%s %s %lld, but the query did not name %s", + c.key, on, c.ival, c.key); + if (c.op == RAD_C_DIV) return fmt("%s %% %lld == 0, have %lld", c.key, c.ival, v); + return fmt("%s %s %lld, have %lld", c.key, on, c.ival, v); +} + +} /* namespace rad */ + +/* ------------------------------------------------------------------ the C surface + * + * EMPTY, AND THAT IS THE POINT. rad_strerror, the four dtype helpers, the three tensor helpers + * and rad_args_geti/gets are `static inline` in the ABI headers. Defined here instead -- declared + * in abi/, defined in rad_core -- they would be callable by everything EXCEPT the plugins that + * want them most; see the long note above rad_strerror in rad_types.h for the failure that + * motivates the arrangement and for what it costs. + * + * Nothing belongs here. A helper a plugin may need belongs in the header; a helper only the + * core needs belongs in namespace rad above, not behind extern "C". */ diff --git a/data/kernels.rkb b/data/kernels.rkb new file mode 100644 index 00000000..ec30ae5a Binary files /dev/null and b/data/kernels.rkb differ diff --git a/data/kernels_moe.rkb b/data/kernels_moe.rkb new file mode 100644 index 00000000..8699238a Binary files /dev/null and b/data/kernels_moe.rkb differ diff --git a/data/recipes/minicpm5-2b-bf16-dspark.recipe b/data/recipes/minicpm5-2b-bf16-dspark.recipe new file mode 100644 index 00000000..820ee770 --- /dev/null +++ b/data/recipes/minicpm5-2b-bf16-dspark.recipe @@ -0,0 +1,18 @@ +# minicpm5-2b-bf16-dspark.recipe -- MiniCPM5-2B in bf16 as the checkpoint ships it, with the DSpark +# drafter merged in (--draft-model). Every weight of the model itself, the lm_head included, is the +# checkpoint's own; the drafter is quantised as in minicpm5-2b-dspark.recipe, because the DSpark +# block reads its weights in one form only: block fp8, and the vocabulary head as 2-bit codes (the +# head only proposes; the model's own bf16 lm_head scores every token it accepts). +# +# rad-convert --draft-model \ +# --tokenizer /tokenizer.json \ +# --recipe data/recipes/minicpm5-2b-bf16-dspark.recipe -o minicpm5-2b-bf16.rad + +dspark.draft_head.weight rtn codes=u2 zero=u8 group=128 scale=f16 +dspark.fc.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dspark.blk.*.attn_q.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dspark.blk.*.attn_k.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dspark.blk.*.attn_v.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dspark.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dspark.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dspark.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 diff --git a/data/recipes/minicpm5-2b-dspark.recipe b/data/recipes/minicpm5-2b-dspark.recipe new file mode 100644 index 00000000..1dd442a2 --- /dev/null +++ b/data/recipes/minicpm5-2b-dspark.recipe @@ -0,0 +1,29 @@ +# minicpm5-2b-dspark.recipe -- MiniCPM5-2B with the DSpark drafter, as the minicpm5-2b-dspark.rad +# container serves it (scripts/convdspark.sh). +# +# OpenBMB publishes MiniCPM5-2B in bf16 only, so every linear is made block fp8 here: one amax a +# 128x128 block, scale = amax/448 rounded to bf16. The checkpoint then serves through llama_dense_fp8 +# with the graph llama_fp8 declares over an fp8 release. Also: +# +# - the lm_head, block fp8: the widest GEMM in the model at half the bytes +# - the drafter's linears, block fp8 from its bf16 release +# - the drafter's 2-bit copy of the target's head (u2 codes, an f16 scale and a u8 zero a group +# of 128), read by its draft passes only +# +# Every norm, the embedding and the drafter's Markov codebooks stay bf16. + +output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dspark.draft_head.weight rtn codes=u2 zero=u8 group=128 scale=f16 + +blk.*.attn_qkv.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 + +dspark.fc.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dspark.blk.*.attn_q.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dspark.blk.*.attn_k.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dspark.blk.*.attn_v.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dspark.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dspark.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dspark.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 diff --git a/data/recipes/q36-35b-a3b-fp8.recipe b/data/recipes/q36-35b-a3b-fp8.recipe new file mode 100644 index 00000000..73130733 --- /dev/null +++ b/data/recipes/q36-35b-a3b-fp8.recipe @@ -0,0 +1,15 @@ +# q36-35b-a3b-fp8.recipe -- Qwen3.6-35B-A3B-FP8 with its MTP head, as the q36-35b-a3b-fp8.rad +# container serves it. +# +# rad-convert --recipe data/recipes/q36-35b-a3b-fp8.recipe \ +# -o q36-35b-a3b-fp8.rad +# +# The linears -- attention, delta net, shared and routed experts, the MTP layer's -- are +# block-scaled fp8 in the checkpoint and kept as they are. What the recipe adds: +# +# - the lm_head, block fp8: the widest GEMM in the model at half the bytes +# - the MTP head's 2-bit copy of the lm_head (u2 codes, an f16 scale and a u8 zero a group of +# 128), which the draft rounds read in place of the full head + +output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +mtp.draft_head.weight rtn codes=u2 zero=u8 group=128 scale=f16 diff --git a/data/recipes/q38-27b-bf16.recipe b/data/recipes/q38-27b-bf16.recipe new file mode 100644 index 00000000..b64acc90 --- /dev/null +++ b/data/recipes/q38-27b-bf16.recipe @@ -0,0 +1,11 @@ +# q38-27b-bf16.recipe -- Qwen3.8-27B (the bf16 release), as the q38-27b-bf16.rad container serves +# it. +# +# rad-convert --recipe data/recipes/q38-27b-bf16.recipe \ +# -o q38-27b-bf16.rad +# +# Every weight is served at the checkpoint's own precision except the lm_head, which is block fp8: +# the widest GEMM in the model at half the bytes, read through the fp8 logits kernel. Without this +# rule the same checkpoint loads directly and the head is read as bf16. + +output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 diff --git a/data/recipes/q38-27b-fp8-df2.recipe b/data/recipes/q38-27b-fp8-df2.recipe new file mode 100644 index 00000000..90381541 --- /dev/null +++ b/data/recipes/q38-27b-fp8-df2.recipe @@ -0,0 +1,28 @@ +# q38-27b-fp8-df2.recipe -- Qwen3.8-27B-FP8 with the DFlash2 drafter, as the q38-27b-fp8-df2.rad +# container serves it. +# +# rad-convert --draft-model \ +# --recipe data/recipes/q38-27b-fp8-df2.recipe -o q38-27b-fp8-df2.rad +# +# The trunk's linears are block-scaled fp8 in the checkpoint and kept as they are; the norms, the +# embedding, the delta net's a/b projection and the vision tower are bf16 and kept as they are. +# What the recipe adds: +# +# - the lm_head, block fp8: the widest GEMM in the model at half the bytes +# - the drafter's linears, block fp8 from its bf16 release: it is read whole on every decode +# step, and a draft is verified, so its precision can move acceptance and never an emitted token +# - the drafter's 2-bit copy of the target's head (u2 codes, an f16 scale and a u8 zero a group +# of 128), read by its draft rounds only +# +# The drafter's selector projection, codebooks and convolution weights stay bf16. + +output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.draft_head.weight rtn codes=u2 zero=u8 group=128 scale=f16 + +dflash.fc.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_q.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_k.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_v.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 diff --git a/data/recipes/qwen4exp-w4-hc8m-pe.recipe b/data/recipes/qwen4exp-w4-hc8m-pe.recipe new file mode 100644 index 00000000..52a64d36 --- /dev/null +++ b/data/recipes/qwen4exp-w4-hc8m-pe.recipe @@ -0,0 +1,65 @@ +# qwen4exp-w4-hc8m-pe.recipe -- qwen4exp-w4-hc8m.recipe with the routed experts quantised by GPTQ +# against the bf16 model's own Hessians -- each expert's own for `down`, the layer's for `gate_up` -- +# and the ten experts that carry the most of their layer's output kept plain bf16 +# (docs/MOE-W4.md, "Protected experts"). +# +# CALIB=DIR rad-convert \ +# --recipe data/recipes/qwen4exp-w4-hc8m-pe.recipe --reuse q38-flashnext-w4-mtp-hc8m.rad \ +# -o q38-flashnext-w4-mtp-hc8m-pe.rad +# +# DIR holds those Hessians, recorded from the bf16 model (docs/MOE-W4.md, "Calibration"); --reuse +# copies every weight whose rule is the same as in qwen4exp-w4-hc8m.recipe. Everything not named +# here is served as the checkpoint holds it; the first rule that matches a weight decides it. + +# The protected experts, from a 1M-token recording of the bf16 model on the calibration corpus: +# an expert whose share of its layer's down-input energy is at least 3% and at least three times its +# share of the routing, and on each rank's half of the layer an even count -- the four-bit GEMM takes +# the rest as two equal tables by parity -- by adding that half's next most energetic expert +# (407/496, 350/292, 290/392 and 445,143/399,122 below). Layer 47's expert 445 alone carries 64% of +# its layer's down-input energy from 0.4% of the routing. +blk.34.ffn_*_exps.407.weight cast dtype=bf16 +blk.34.ffn_*_exps.496.weight cast dtype=bf16 +blk.44.ffn_*_exps.292.weight cast dtype=bf16 +blk.44.ffn_*_exps.350.weight cast dtype=bf16 +blk.46.ffn_*_exps.290.weight cast dtype=bf16 +blk.46.ffn_*_exps.392.weight cast dtype=bf16 +blk.47.ffn_*_exps.122.weight cast dtype=bf16 +blk.47.ffn_*_exps.143.weight cast dtype=bf16 +blk.47.ffn_*_exps.399.weight cast dtype=bf16 +blk.47.ffn_*_exps.445.weight cast dtype=bf16 + +# Every other routed expert, trunk and MTP layer alike: int4, a bf16 scale a group of 128, rotated +# by the 128-wide Hadamard, chosen by GPTQ against $CALIB. The MTP layer has no recording and is +# rounded to nearest, which libquant says on stderr. +blk.*.ffn_*_exps.*.weight gptq codes=i4 group=128 scale=bf16 transform=fwht128 calib=$CALIB + +# Every connection's two mixing matrices -- the 96 trunk connections, the final mixer and the MTP +# head's three -- as E4M3 rows with an f32 scale a group of each row. A 128x128 block cannot cover +# them: lowrank is 320, 2.5 blocks. Down is [320, 10240] and takes a scale every 128 columns; up is +# [10240, 320] and takes four scales a row, 80 columns each. +*_hc_down.weight rtn codes=fp8_e4m3 group=128 scale=f32 +*_hc_up.weight rtn codes=fp8_e4m3 group=80 scale=f32 + +# The MTP head's fc_hidden and fc_embedding, the same rows. They only ever change the drafts. +mtp.fc_hidden.weight rtn codes=fp8_e4m3 group=128 scale=f32 +mtp.fc_embedding.weight rtn codes=fp8_e4m3 group=128 scale=f32 + +# The block-scaled fp8 linears. The QSA indexer's projection is not one of them: its top-k is a +# hard choice between blocks, and keeping it as the checkpoint holds it costs 20 MB. +blk.*.attn_qg.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.attn_k.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.attn_v.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.ssm_inz.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.ssm_out.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.ffn_gate_up_shexp.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.ffn_down_shexp.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 + +# The lm_head, block fp8. +output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 + +# The n-gram table at one fixed E4M3 scale; qwen4exp-w4.recipe says where the value comes from. +blk.*.ple_ngram.weight rtn codes=fp8_e4m3 block=*x* scale=bf16 rule=fixed scale_value=1.99317932128906e-4 + +# The MTP head's 2-bit draft head. +mtp.draft_head.weight rtn codes=u2 zero=u8 group=128 scale=f16 diff --git a/data/recipes/qwen4exp-w4-hc8m.recipe b/data/recipes/qwen4exp-w4-hc8m.recipe new file mode 100644 index 00000000..8d34d7ed --- /dev/null +++ b/data/recipes/qwen4exp-w4-hc8m.recipe @@ -0,0 +1,46 @@ +# qwen4exp-w4-hc8m.recipe -- Qwen3.8-Flash-Next from its bf16 checkpoint, as the +# q38-flashnext-w4-mtp-hc8m.rad container serves it: qwen4exp-w4.recipe, plus the gated-residual +# mixing matrices and the MTP head's two entry matrices as E4M3 rows. +# +# rad-convert --recipe data/recipes/qwen4exp-w4-hc8m.recipe \ +# -o q38-flashnext-w4-mtp-hc8m.rad +# +# The uncensored release (orcarouter/Qwen3.8-Flash-Next-Uncensored) takes the same recipe. +# Everything not named here is served as the checkpoint holds it; the first rule that matches a +# weight decides it. The routed experts' GPTQ form is one rule ahead of this file: +# --quant 'blk.*.ffn_*_exps.*.weight=gptq:codes=i4,group=128,scale=bf16,transform=fwht128,calib=$CALIB' + +# The routed experts, trunk and MTP layer alike: int4, a bf16 scale a group of 128, rotated by the +# 128-wide Hadamard. qwen4exp-w4.recipe says why. +blk.*.ffn_*_exps.*.weight rtn codes=i4 group=128 scale=bf16 transform=fwht128 + +# Every connection's two mixing matrices -- the 96 trunk connections, the final mixer and the MTP +# head's three -- as E4M3 rows with an f32 scale a group of each row. A 128x128 block cannot cover +# them: lowrank is 320, 2.5 blocks. Down is [320, 10240] and takes a scale every 128 columns; up is +# [10240, 320] and takes four scales a row, 80 columns each. +*_hc_down.weight rtn codes=fp8_e4m3 group=128 scale=f32 +*_hc_up.weight rtn codes=fp8_e4m3 group=80 scale=f32 + +# The MTP head's fc_hidden and fc_embedding, the same rows. They only ever change the drafts. +mtp.fc_hidden.weight rtn codes=fp8_e4m3 group=128 scale=f32 +mtp.fc_embedding.weight rtn codes=fp8_e4m3 group=128 scale=f32 + +# The block-scaled fp8 linears. The QSA indexer's projection is not one of them: its top-k is a +# hard choice between blocks, and keeping it as the checkpoint holds it costs 20 MB. +blk.*.attn_qg.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.attn_k.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.attn_v.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.ssm_inz.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.ssm_out.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.ffn_gate_up_shexp.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.ffn_down_shexp.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 + +# The lm_head, block fp8. +output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 + +# The n-gram table at one fixed E4M3 scale; qwen4exp-w4.recipe says where the value comes from. +blk.*.ple_ngram.weight rtn codes=fp8_e4m3 block=*x* scale=bf16 rule=fixed scale_value=1.99317932128906e-4 + +# The MTP head's 2-bit draft head. +mtp.draft_head.weight rtn codes=u2 zero=u8 group=128 scale=f16 diff --git a/data/recipes/qwen4exp-w4.recipe b/data/recipes/qwen4exp-w4.recipe new file mode 100644 index 00000000..28d0241d --- /dev/null +++ b/data/recipes/qwen4exp-w4.recipe @@ -0,0 +1,48 @@ +# qwen4exp-w4.recipe -- Qwen3.8-Flash-Next from its bf16 checkpoint, as the +# q38-flashnext-w4-mtp.rad container serves it: fp8 linears, four-bit rotated experts, the n-gram +# table at E4M3, the MTP head with its 2-bit draft head; the gated-residual mixing matrices and the +# MTP head's fc matrices stay bf16 (qwen4exp-w4-hc8m.recipe makes those E4M3 too). +# +# rad-convert --recipe data/recipes/qwen4exp-w4.recipe \ +# -o q38-flashnext-w4-mtp.rad +# +# The checkpoint carries no quantization_config, so everything not named here is served as the +# checkpoint holds it: every norm gain, A_log, dt_bias, conv1d, the delta net's a/b projections +# (48 rows, not a whole scale block), the router and shared-expert gate, the QSA indexer's +# projection, the embedding, the PLE projections and the hyper-connection weights. Rank-1 weights a +# pattern happens to match are declined by the quantiser and kept as they are. The first rule that +# matches a weight decides it. + +# The routed experts, trunk and MTP layer alike: int4 codes, a bf16 scale a group of 128 along K, +# each row rotated by the 128-wide Hadamard first. The experts are 112.8 GiB at E4M3 and do not fit +# two cards; at four bits they do. Round-to-nearest with absmax scales; the calibrated GPTQ form of +# the same encoding is one rule ahead of this file: +# --quant 'blk.*.ffn_*_exps.*.weight=gptq:codes=i4,group=128,scale=bf16,transform=fwht128,calib=$CALIB' +blk.*.ffn_*_exps.*.weight rtn codes=i4 group=128 scale=bf16 transform=fwht128 + +# The block-scaled fp8 linears: E4M3 codes, a bf16 scale a 128x128 block. The QSA indexer's +# projection is not one of them: its top-k is a hard choice between blocks, and keeping it as the +# checkpoint holds it costs 20 MB. +blk.*.attn_qg.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.attn_k.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.attn_v.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.ssm_inz.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.ssm_out.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.ffn_gate_up_shexp.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.ffn_down_shexp.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 + +# The lm_head, block fp8: the widest GEMM in the model at half the bytes. +output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 + +# The n-gram table, 51B parameters: E4M3 with ONE scale for all 320 million rows, fixed rather than +# measured -- an absmax over the whole table cannot be taken a block of rows at a time, and the +# table streams. 1.99317932128906e-4 is bf16 0x3951, the value Qwen3.8-Flash-Next-FP8 ships in its +# own `ngram_embedding.weight_scale`; it sits on a three-octave plateau (2^-13..2^-10 give rel_l2 +# 0.02662 to five digits) with 1.7x headroom over the table's absmax. +blk.*.ple_ngram.weight rtn codes=fp8_e4m3 block=*x* scale=bf16 rule=fixed scale_value=1.99317932128906e-4 + +# The MTP head's 2-bit copy of the lm_head -- u2 codes, an f16 scale and a u8 zero a group of 128 -- +# which the draft rounds read in place of the full head. A draft is verified by the trunk, so this +# moves acceptance and never an emitted token. +mtp.draft_head.weight rtn codes=u2 zero=u8 group=128 scale=f16 diff --git a/data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe b/data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe new file mode 100644 index 00000000..f35c61cd --- /dev/null +++ b/data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe @@ -0,0 +1,80 @@ +# qwen4exp-w4nl64-i8-hc8m.recipe -- Qwen3.8-Flash-Next from its bf16 checkpoint as it is served +# (the w4nl64-i8lm.rad container): the routed experts as rotated u4 codes into the w4nl +# codebook with one E4M3 scale a (row, 64 of K) under a fixed f32 of 2^-13 (libr4d's w4nl64a8h), +# the codes chosen by GPTQ and three sweeps of coordinate descent; ten protected experts plain +# bf16; the trunk's block linears and the lm_head int8, served W8A8; the connections' mixing +# matrices and the MTP head's fc matrices E4M3; the n-gram table at one fixed E4M3 scale. +# +# Measured with the engine's KL mode against the bf16 model (docs/MOE-W4.md, "What is served"): +# mean KL 0.0789 and top-1 agreement 92.85% over the whole corpus, where a second bf16 +# implementation scores 0.0399 / 95.13%; 0.0239 / 94.57% on text and assistant turns. +# +# CALIB=DIR rad-convert \ +# --recipe data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe -o w4nl64-i8lm.rad +# +# DIR holds each layer's pooled Grams, recorded from ten million tokens of the bf16 model, and each +# expert's own down Gram, from one million tokens with the per-expert tap, side by side; libquant +# takes an expert's own wherever it holds at least 4096 rows and the layer's otherwise +# (docs/MOE-W4.md, "Calibration"). A variant of this recipe converted with --reuse w4nl64-i8lm.rad +# re-quantises only the weights whose rule changed. +# +# Everything not named here is served as the checkpoint holds it; the first rule that matches a +# weight decides it. + +# The protected experts, from a 1M-token recording of the bf16 model on the calibration corpus: +# an expert whose share of its layer's down-input energy is at least 3% and at least three times its +# share of the routing, and on each rank's half of the layer an even count -- the four-bit GEMM takes +# the rest as two equal tables by parity -- by adding that half's next most energetic expert +# (407/496, 350/292, 290/392 and 445,143/399,122 below). Layer 47's expert 445 alone carries 64% of +# its layer's down-input energy from 0.4% of the routing. +blk.34.ffn_*_exps.407.weight cast dtype=bf16 +blk.34.ffn_*_exps.496.weight cast dtype=bf16 +blk.44.ffn_*_exps.292.weight cast dtype=bf16 +blk.44.ffn_*_exps.350.weight cast dtype=bf16 +blk.46.ffn_*_exps.290.weight cast dtype=bf16 +blk.46.ffn_*_exps.392.weight cast dtype=bf16 +blk.47.ffn_*_exps.122.weight cast dtype=bf16 +blk.47.ffn_*_exps.143.weight cast dtype=bf16 +blk.47.ffn_*_exps.399.weight cast dtype=bf16 +blk.47.ffn_*_exps.445.weight cast dtype=bf16 + +# Every other routed expert, trunk and MTP layer alike: u4 codes into the w4nl table, rotated by +# the 128-wide Hadamard, an E4M3 scale a group of 64 under the fixed 2^-13 searched for least error +# as stored, the codes chosen by GPTQ against $CALIB and then swept three times by coordinate +# descent. The experts' scales sit between 2^-15 and 2^-10.6, inside E4M3's normal range under +# 2^-13 with four binades either side; one past its top would be held there and said on stderr. +# The MTP layer has no recording and is rounded to nearest, which libquant says on stderr. +blk.*.ffn_*_exps.*.weight gptq table=w4nl group=64 scale=fp8_e4m3 scale2=f32 block2=*x* scale2_value=0.0001220703125 transform=fwht128 rule=search cd=3 calib=$CALIB + +# Every connection's two mixing matrices -- the 96 trunk connections, the final mixer and the MTP +# head's three -- as E4M3 rows with an f32 scale a group of each row. A 128x128 block cannot cover +# them: lowrank is 320, 2.5 blocks. Down is [320, 10240] and takes a scale every 128 columns; up is +# [10240, 320] and takes four scales a row, 80 columns each. +*_hc_down.weight rtn codes=fp8_e4m3 group=128 scale=f32 +*_hc_up.weight rtn codes=fp8_e4m3 group=80 scale=f32 + +# The MTP head's fc_hidden and fc_embedding, the same rows. They only ever change the drafts. +mtp.fc_hidden.weight rtn codes=fp8_e4m3 group=128 scale=f32 +mtp.fc_embedding.weight rtn codes=fp8_e4m3 group=128 scale=f32 + +# The trunk's block linears as int8, a scale per 128 columns of a row searched for least error. +# The QSA indexer's projection is not one of them: its top-k is a hard choice between blocks, and +# keeping it as the checkpoint holds it costs 20 MB. +blk.*.attn_qg.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search +blk.*.attn_k.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search +blk.*.attn_v.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search +blk.*.attn_output.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search +blk.*.ssm_inz.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search +blk.*.ssm_out.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search +blk.*.ffn_gate_up_shexp.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search +blk.*.ffn_down_shexp.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search + +# The lm_head, int8 with a bf16 scale a row per 128 columns (logits_gemm_i8): at E4M3 it costs +# ~0.6 points of top-1 on its own. +output.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search + +# The n-gram table at one fixed E4M3 scale; qwen4exp-w4.recipe says where the value comes from. +blk.*.ple_ngram.weight rtn codes=fp8_e4m3 block=*x* scale=bf16 rule=fixed scale_value=1.99317932128906e-4 + +# The MTP head's 2-bit draft head. +mtp.draft_head.weight rtn codes=u2 zero=u8 group=128 scale=f16 diff --git a/data/recipes/qwen4exp-w5dn64-i8-hc8m.recipe b/data/recipes/qwen4exp-w5dn64-i8-hc8m.recipe new file mode 100644 index 00000000..08cfb328 --- /dev/null +++ b/data/recipes/qwen4exp-w5dn64-i8-hc8m.recipe @@ -0,0 +1,79 @@ +# qwen4exp-w5dn64-i8-hc8m.recipe -- qwen4exp-w4nl64-i8-hc8m.recipe with every routed expert's DOWN +# projection at five bits: u5 codes into libquant's 32-level w5nl table at the same E4M3 scale a +# (row, 64 of K) under the fixed 2^-13 (libr4d's w5nl64a8h), GPTQ and three sweeps of coordinate +# descent. gate_up stays w4nl64a8h. Down is a third of an expert's weights and the larger share of +# its output error (held-out relative error 0.094 against gate_up's 0.064), so the fifth bit goes +# there first: +8% of the experts' bytes for 72% less of down's error energy. +# +# Against the served recipe, qwen4exp-w4nl64-i8-hc8m.recipe (docs/MOE-W4.md): mean KL 0.0789 -> +# 0.0717, top-1 92.85% -> 93.34%; and decode +4%, prefill -19% at two cards, the larger experts +# leaving fewer of them resident. It is not the served recipe because of that prefill cost. +# +# CALIB=DIR rad-convert \ +# --recipe data/recipes/qwen4exp-w5dn64-i8-hc8m.recipe --reuse w4nl64-i8lm.rad \ +# -o w5dn64-i8lm.rad +# +# DIR is the served recipe's calibration directory; --reuse copies the trunk and the gate_up +# projections. Everything not named here is served as the checkpoint holds it; the first rule that +# matches a weight decides it. + +# The protected experts, from a 1M-token recording of the bf16 model on the calibration corpus: +# an expert whose share of its layer's down-input energy is at least 3% and at least three times its +# share of the routing, and on each rank's half of the layer an even count -- the four-bit GEMM takes +# the rest as two equal tables by parity -- by adding that half's next most energetic expert +# (407/496, 350/292, 290/392 and 445,143/399,122 below). Layer 47's expert 445 alone carries 64% of +# its layer's down-input energy from 0.4% of the routing. +blk.34.ffn_*_exps.407.weight cast dtype=bf16 +blk.34.ffn_*_exps.496.weight cast dtype=bf16 +blk.44.ffn_*_exps.292.weight cast dtype=bf16 +blk.44.ffn_*_exps.350.weight cast dtype=bf16 +blk.46.ffn_*_exps.290.weight cast dtype=bf16 +blk.46.ffn_*_exps.392.weight cast dtype=bf16 +blk.47.ffn_*_exps.122.weight cast dtype=bf16 +blk.47.ffn_*_exps.143.weight cast dtype=bf16 +blk.47.ffn_*_exps.399.weight cast dtype=bf16 +blk.47.ffn_*_exps.445.weight cast dtype=bf16 + +# Every other routed expert, trunk and MTP layer alike: its down projection as u5 codes into the +# w5nl table and its gate_up as u4 codes into the w4nl table, both rotated by the 128-wide +# Hadamard, an E4M3 scale a group of 64 under the fixed 2^-13 searched for least error as stored, +# the codes chosen by GPTQ against $CALIB and then swept three times by coordinate descent. The +# experts' scales sit between 2^-15 and 2^-10.6 under w4nl's top level of 22, and half a binade +# lower under w5nl's 30 -- inside E4M3's normal range under 2^-13 either way, with binades to +# spare; one past its top would be held there and said on stderr. The MTP layer has no recording +# and is rounded to nearest, which libquant says on stderr. +blk.*.ffn_down_exps.*.weight gptq table=w5nl group=64 scale=fp8_e4m3 scale2=f32 block2=*x* scale2_value=0.0001220703125 transform=fwht128 rule=search cd=3 calib=$CALIB +blk.*.ffn_*_exps.*.weight gptq table=w4nl group=64 scale=fp8_e4m3 scale2=f32 block2=*x* scale2_value=0.0001220703125 transform=fwht128 rule=search cd=3 calib=$CALIB + +# Every connection's two mixing matrices -- the 96 trunk connections, the final mixer and the MTP +# head's three -- as E4M3 rows with an f32 scale a group of each row. A 128x128 block cannot cover +# them: lowrank is 320, 2.5 blocks. Down is [320, 10240] and takes a scale every 128 columns; up is +# [10240, 320] and takes four scales a row, 80 columns each. +*_hc_down.weight rtn codes=fp8_e4m3 group=128 scale=f32 +*_hc_up.weight rtn codes=fp8_e4m3 group=80 scale=f32 + +# The MTP head's fc_hidden and fc_embedding, the same rows. They only ever change the drafts. +mtp.fc_hidden.weight rtn codes=fp8_e4m3 group=128 scale=f32 +mtp.fc_embedding.weight rtn codes=fp8_e4m3 group=128 scale=f32 + +# The trunk's block linears as int8, a scale per 128 columns of a row searched for least error. +# The QSA indexer's projection is not one of them: its top-k is a hard choice between blocks, and +# keeping it as the checkpoint holds it costs 20 MB. +blk.*.attn_qg.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search +blk.*.attn_k.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search +blk.*.attn_v.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search +blk.*.attn_output.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search +blk.*.ssm_inz.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search +blk.*.ssm_out.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search +blk.*.ffn_gate_up_shexp.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search +blk.*.ffn_down_shexp.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search + +# The lm_head, int8 with a bf16 scale a row per 128 columns (logits_gemm_i8): at E4M3 it costs +# ~0.6 points of top-1 on its own. +output.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search + +# The n-gram table at one fixed E4M3 scale; qwen4exp-w4.recipe says where the value comes from. +blk.*.ple_ngram.weight rtn codes=fp8_e4m3 block=*x* scale=bf16 rule=fixed scale_value=1.99317932128906e-4 + +# The MTP head's 2-bit draft head. +mtp.draft_head.weight rtn codes=u2 zero=u8 group=128 scale=f16 diff --git a/deploy/compose/.env.example b/deploy/compose/.env.example new file mode 100644 index 00000000..81525f84 --- /dev/null +++ b/deploy/compose/.env.example @@ -0,0 +1,24 @@ +# Copy to .env in this directory; docker compose reads it on every command. + +# The image to run: the published one, or radiance:latest for one built here with docker/build.sh +# (which also tags radiance: and radiance:). +RADIANCE_IMAGE=stilldeadcode/radiance:latest + +# Directory holding the .rad containers, mounted read-only at /models. +RADIANCE_MODELS=/srv/models/rad + +# Writable directory mounted at /data: the prefix cache's disk tier lives under it. +RADIANCE_STATE=/srv/radiance + +# Every request but /health, /ping and the dashboard page must carry `Authorization: Bearer `. +RADIANCE_API_KEY= + +# The port the server listens on. +PORT=8000 + +# The user the server runs as, and the host's GPU device groups: +# id -u; id -g; getent group render | cut -d: -f3; getent group video | cut -d: -f3 +RADIANCE_UID=1000 +RADIANCE_GID=1000 +RENDER_GID= +VIDEO_GID= diff --git a/deploy/compose/common.yaml b/deploy/compose/common.yaml new file mode 100644 index 00000000..1fa27eab --- /dev/null +++ b/deploy/compose/common.yaml @@ -0,0 +1,48 @@ +# The service every model file in this directory extends. It holds what any radiance container +# needs on an AMD host; a model file adds only its container and its flags. +# +# Each model takes both cards (--tp 2) and the same port, so run one at a time: +# docker compose -f flashnext.yaml up -d start (it comes back after a reboot) +# docker compose -f flashnext.yaml logs -f follow the log +# docker compose -f flashnext.yaml down stop +# +# Settings come from .env beside this file (see .env.example). +services: + radiance: + image: ${RADIANCE_IMAGE:-stilldeadcode/radiance:latest} + restart: unless-stopped + init: true + # Host networking: the server binds the host's own addresses, IPv4 and IPv6, with no NAT + # between it and a reverse proxy. + network_mode: host + # The host user, so the prefix cache's files on disk belong to that user and not to root. + user: "${RADIANCE_UID:-1000}:${RADIANCE_GID:-1000}" + devices: + - /dev/kfd + - /dev/dri + group_add: + - "${RENDER_GID:?set RENDER_GID in .env}" + - "${VIDEO_GID:?set VIDEO_GID in .env}" + # Docker's default seccomp profile refuses io_uring, which the n-gram table's reads from the + # container go through, and the NUMA binding calls (mbind, set_mempolicy) the ROCm runtime + # makes for host memory. + security_opt: + - seccomp=unconfined + ulimits: + memlock: -1 + volumes: + - ${RADIANCE_MODELS:?set RADIANCE_MODELS in .env}:/models:ro + - ${RADIANCE_STATE:?set RADIANCE_STATE in .env}:/data + # A server finishes the step in flight and releases the cards on SIGTERM. + stop_grace_period: 60s + healthcheck: + test: ["CMD", "busybox", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:${PORT:-8000}/health"] + interval: 30s + timeout: 5s + retries: 3 + start_period: 15m + logging: + driver: json-file + options: + max-size: 100m + max-file: "5" diff --git a/deploy/compose/flashnext-bf16.yaml b/deploy/compose/flashnext-bf16.yaml new file mode 100644 index 00000000..c442e83b --- /dev/null +++ b/deploy/compose/flashnext-bf16.yaml @@ -0,0 +1,16 @@ +# Qwen3.8-Flash-Next exactly as the checkpoint ships it, bf16 throughout (335 GiB). Larger than +# both cards and the host pool together, so the routed experts that fit neither are read from the +# container on every pass (--weights-disk-tier) and a step takes tens of seconds whatever its +# size. A reference to calibrate and compare against, not a production server: 32K of context +# keeps QSA's score plane for a 32K-token step at 1 GiB. +name: radiance-flashnext-bf16 +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-flashnext-bf16 + command: > + --model /models/qwen3.8-flash-next-bf16.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --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 diff --git a/deploy/compose/flashnext.yaml b/deploy/compose/flashnext.yaml new file mode 100644 index 00000000..d6b81cec --- /dev/null +++ b/deploy/compose/flashnext.yaml @@ -0,0 +1,18 @@ +# Qwen3.8-Flash-Next, the production container (data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe): +# int8 trunk and lm_head, routed experts as 4-bit codebook codes at E4M3 scales. The experts that +# do not fit VRAM are streamed from a pinned host pool; idle sessions move to host memory and then +# to disk under /data/kvcache/flashnext. +name: radiance-flashnext +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-flashnext + command: > + --model /models/qwen3.8-next-flash-fp8-iq4r-moe.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --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 + --prefix-cache-host-mib 4096 --prefix-cache-dir /data/kvcache/flashnext + --prefix-cache-disk-mib 131072 + --num-speculative-tokens 3 --max-num-batched-tokens 2048 diff --git a/deploy/compose/minicpm5-2b-bf16.yaml b/deploy/compose/minicpm5-2b-bf16.yaml new file mode 100644 index 00000000..3b8fc69e --- /dev/null +++ b/deploy/compose/minicpm5-2b-bf16.yaml @@ -0,0 +1,12 @@ +# MiniCPM5-2B in bf16 as the checkpoint ships it, with its DSpark drafter merged in +# (data/recipes/minicpm5-2b-bf16-dspark.recipe). The context is the checkpoint's trained 131072 tokens. +name: radiance-minicpm5-2b-bf16 +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-minicpm5-2b-bf16 + command: > + --model /models/minicpm5-2b-bf16.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 2 --max-num-seqs 8 --max-model-len 131072 --kv-cache-dtype fp8 + --gpu-headroom-mib 160 --max-num-batched-tokens 512 diff --git a/deploy/compose/minicpm5-2b.yaml b/deploy/compose/minicpm5-2b.yaml new file mode 100644 index 00000000..2110b287 --- /dev/null +++ b/deploy/compose/minicpm5-2b.yaml @@ -0,0 +1,12 @@ +# MiniCPM5-2B with its DSpark drafter merged into the container. The context is the checkpoint's +# trained 131072 tokens. +name: radiance-minicpm5-2b +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-minicpm5-2b + command: > + --model /models/minicpm5-2b-fp8.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 2 --max-num-seqs 8 --max-model-len 131072 --kv-cache-dtype fp8 + --gpu-headroom-mib 160 --max-num-batched-tokens 512 diff --git a/deploy/compose/qwen3.6-35b-a3b.yaml b/deploy/compose/qwen3.6-35b-a3b.yaml new file mode 100644 index 00000000..fc93c97c --- /dev/null +++ b/deploy/compose/qwen3.6-35b-a3b.yaml @@ -0,0 +1,10 @@ +# Qwen3.6-35B-A3B, FP8 as published: a 256-expert MoE that fits both cards whole. +name: radiance-qwen3.6-35b-a3b +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-qwen3.6-35b-a3b + command: > + --model /models/qwen3.6-35b-a3b-fp8.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 2 --max-num-seqs 8 --max-model-len 200000 --kv-cache-dtype fp8 diff --git a/deploy/compose/qwen3.8-27b-bf16.yaml b/deploy/compose/qwen3.8-27b-bf16.yaml new file mode 100644 index 00000000..03a42ac6 --- /dev/null +++ b/deploy/compose/qwen3.8-27b-bf16.yaml @@ -0,0 +1,10 @@ +# Qwen3.8-27B in bf16, the checkpoint's own weights: half each card is weights, the rest is cache. +name: radiance-qwen3.8-27b-bf16 +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-qwen3.8-27b-bf16 + command: > + --model /models/qwen3.8-27b-bf16.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 2 --max-num-seqs 8 --max-model-len 200000 --kv-cache-dtype fp8 diff --git a/deploy/compose/qwen3.8-27b-fp8.yaml b/deploy/compose/qwen3.8-27b-fp8.yaml new file mode 100644 index 00000000..098f24fd --- /dev/null +++ b/deploy/compose/qwen3.8-27b-fp8.yaml @@ -0,0 +1,11 @@ +# Qwen3.8-27B, FP8 as published, with its DFlash2 block-diffusion drafter merged into the +# container; the speculation depth is the drafter's own operating point. +name: radiance-qwen3.8-27b-fp8 +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-qwen3.8-27b-fp8 + command: > + --model /models/qwen3.8-27b-fp8.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 2 --max-num-seqs 8 --max-model-len 200000 --kv-cache-dtype fp8 diff --git a/docker/build.sh b/docker/build.sh new file mode 100755 index 00000000..ead01197 --- /dev/null +++ b/docker/build.sh @@ -0,0 +1,55 @@ +#!/bin/sh +# docker/build.sh -- build the radiance image from a commit with BuildKit (docker buildx) and tag it. +# +# The build context is `git archive` of the commit, so the image holds exactly what is committed: +# no build trees, no uncommitted edits, no model files. With -s the archive is streamed over ssh +# to another machine's own `docker buildx`, which builds and keeps the image; that machine needs +# Docker with buildx and nothing else. +# +# docker/build.sh HEAD, here +# docker/build.sh -s HOST HEAD, built on and kept by HOST +# docker/build.sh -r COMMIT another commit +# docker/build.sh -t 'gfx1200;gfx1201' other GPU architectures (default gfx1201) +# docker/build.sh -j 8 fewer compile jobs, for a host that is also serving +# docker/build.sh --target build stop at a stage (tagged radiance-), e.g. for the +# GPU test suites +# +# Tags: radiance:, radiance:, radiance:latest. +set -e +cd "$(dirname "$0")/.." + +REV=HEAD +HOST= +TARGETS=gfx1201 +JOBS= +STAGE= +while [ $# -gt 0 ]; do + case "$1" in + -s) shift; HOST="$1" ;; + -r) shift; REV="$1" ;; + -t) shift; TARGETS="$1" ;; + -j) shift; JOBS="$1" ;; + --target) shift; STAGE="$1" ;; + *) echo "docker/build.sh: unknown option $1" >&2; exit 2 ;; + esac + shift +done + +SHA=$(git rev-parse --short=12 "$REV^{commit}") +VERSION=$(git show "$SHA:CMakeLists.txt" | sed -n 's/^project(radiance VERSION \([0-9.]*\).*/\1/p') +[ -n "$VERSION" ] || { echo "docker/build.sh: no project version in CMakeLists.txt" >&2; exit 1; } + +if [ -n "$STAGE" ]; then + TAGS="-t radiance-$STAGE --target $STAGE" +else + TAGS="-t radiance:$VERSION -t radiance:$SHA -t radiance:latest" +fi +CMD="docker buildx build --load --build-arg GPU_TARGETS='$TARGETS' --build-arg JOBS='$JOBS'" +CMD="$CMD --build-arg VERSION='$VERSION' --build-arg REVISION='$SHA' $TAGS -" + +echo "radiance $VERSION ($SHA) for $TARGETS${HOST:+ on $HOST}${STAGE:+, stage $STAGE}" +if [ -n "$HOST" ]; then + git archive --format=tar "$SHA" | ssh "$HOST" "$CMD" +else + git archive --format=tar "$SHA" | sh -c "$CMD" +fi diff --git a/docker/licenses.sh b/docker/licenses.sh new file mode 100755 index 00000000..b6e66b4e --- /dev/null +++ b/docker/licenses.sh @@ -0,0 +1,108 @@ +#!/bin/sh +# docker/licenses.sh ROOT FILE... -- the licenses of everything in the runtime image that radiance +# did not write. +# +# FILE... are the paths, in the build image, of every file copied into ROOT from outside the +# radiance install: the shared libraries, comgr, busybox, the GPU name table. Each is traced to the +# package that installed it, or to the FFmpeg stage's /opt/ffmpeg. Every package's license files +# are copied to ROOT/usr/share/doc//, the license texts Debian's copyright files refer to +# go to ROOT/usr/share/common-licenses/, and ROOT/usr/share/doc/THIRD-PARTY lists each component +# with its version, its license files and where its source is. A file that no package owns, or a +# package that ships no license file, stops the build: the image would hold software whose license +# is not recorded. +set -eu +R=$1; shift +D=$R/usr/share/doc +W=$(mktemp -d) +mkdir -p "$D" + +owner() { # owner PATH -- the package that installed PATH, under any name usrmerge gives it + for p in "$1" "$(readlink -f "$1")"; do + for q in "$p" "/usr$p" "${p#/usr}"; do + o=$(dpkg-query -S "$q" 2>/dev/null | grep -v "^diversion " | head -1) || continue + [ -n "$o" ] && { echo "${o%%:*}"; return 0; } + done + done + return 1 +} + +licfiles() { # licfiles PACKAGE -- the license files PACKAGE installed that are present + { dpkg-query -L "$1" | grep -iE '/(copyright|licen[cs]e[^/]*|copying[^/]*|notice[^/]*)$' || true + echo "/usr/share/doc/$1/copyright"; } | + while read -r f; do [ -f "$f" ] && readlink -f "$f"; done | sort -u +} + +ffmpeg= +for f in "$@"; do + case "$f" in + /opt/ffmpeg/*) ffmpeg=1 ;; + *) p=$(owner "$f") || { echo "licenses.sh: no package owns $f" >&2; exit 1; } + echo "$p $(basename "$f")" >> "$W/owned" ;; + esac +done + +rocm=$(cat /opt/rocm/.info/version 2>/dev/null || echo unknown) +{ + cat </, and the license +texts those files refer to are in /usr/share/common-licenses/. + +The Ubuntu and ROCm packages are the distributions' binaries, copied unmodified. The source of an +Ubuntu package is its source package at the version listed: \`apt-get source NAME=VERSION\`, or +the Launchpad page given. The ROCm libraries are from AMD's ROCm $rocm; their source is at +https://github.com/ROCm. +EOF + if [ -n "$ffmpeg" ]; then + cat <&2; exit 1; } + mkdir -p "$D/$p" + dest="" + for l in $lic; do + t="$D/$p/$(basename "$l")" + if [ -e "$t" ] && ! cmp -s "$l" "$t"; then + t="$D/$p/$(basename "$(dirname "$l")")-$(basename "$l")" + fi + cp "$l" "$t" + dest="$dest${dest:+, }${t#"$R"}" + done + ver=$(dpkg-query -W -f='${Version}' "$p") + src=$(dpkg-query -W -f='${source:Package} ${source:Version}' "$p") + echo + echo "$p $ver" + case "$(dpkg-query -L "$p")" in + */opt/rocm*) echo " source: ROCm $rocm, https://github.com/ROCm" ;; + *) echo " source: $src (Ubuntu), https://launchpad.net/ubuntu/+source/${src% *}/${src#* }" ;; + esac + echo " files: $files" + echo " license: $dest" + done +} > "$W/THIRD-PARTY" +mv "$W/THIRD-PARTY" "$D/THIRD-PARTY" + +if [ -n "$ffmpeg" ]; then + mkdir -p "$D/ffmpeg" + cp /opt/ffmpeg/share/doc/ffmpeg/* "$D/ffmpeg/" +fi +mkdir -p "$R/usr/share" +cp -a /usr/share/common-licenses "$R/usr/share/" +rm -rf "$W" diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md new file mode 100644 index 00000000..e68ee8f4 --- /dev/null +++ b/docs/ARCHITECTURES.md @@ -0,0 +1,334 @@ +# Architectures — the geometry, and the traps that stay plausible when wrong + +One architecture plugin claims one **(architecture id, quantisation descriptor)** pair — that is the +selection key of `spec.md` §2.4, and it is why a family with two checkpoint formats is two `.so` +files rather than one that branches. `rad-convert` normalises whatever it read (safetensors or GGUF) +into the id an architecture plugin claims. + +| plugin | id | quantisation | what it serves | +|---|---|---|---| +| `arch/llama_fp8` | `llama` | `fp8_e4m3` | the plain LLaMA decoder, from a checkpoint that already holds E4M3 codes and a `weight_scale_inv` plane | +| `arch/llama_dense_fp8` | `llama` | *(empty)* | the same graph from a bf16 checkpoint; `rad-convert` quantises. MiniCPM5-2B | +| `arch/qwen35_bf16` | `qwen35` | *(empty)* | the Qwen3.5/3.6/3.8 dense hybrid, served bf16 | +| `arch/qwen35_fp8` | `qwen35` | `fp8_e4m3` | the same, block-scaled FP8 weights and activations | +| `arch/qwen35moe_fp8` | `qwen35moe` | `fp8_e4m3` | `qwen35_fp8` with the feed-forward routed | +| `arch/qwen4exp_fp8` | `qwen4exp` | *(empty)* | Qwen4-Exp (Qwen3.8-Flash-Next), a bf16 checkpoint quantised at convert | + +This document is the geometry of each, and the handful of readings that are **arithmetically +silent** — wrong in a way that produces fluent output and no error anywhere. + +## The rule that applies to all of them + +**`head_dim` is READ, never derived.** On the Qwen hybrids `head_dim` is 256 while +`hidden_size / num_attention_heads` is 213, so a derived value makes every downstream shape silently +wrong — the projection widths, the KV page size, the attention kernel's band. `core/engine_bringup.cpp` +takes it from the container's meta and says so at the line that does it. + +--- + +# `llama` — the plain decoder + +`model_type: llama` with `LlamaForCausalLM`, the most widely shared decoder shape there is. Every +layer is full attention; there is no gated delta net, no layer schedule, no output gate and no +per-head q/k norm, which is precisely what separates this plugin from `qwen35_fp8`. + +MiniCPM5-2B is what it exists for: 42 layers, hidden 2048, 16 query heads over 2 KV heads at +`head_dim` 128, SwiGLU at 6144, RMS norms, full rotary at theta 5e6, an untied 130560-row head, and +no biases anywhere. + +**Two checkpoint formats, one graph.** OpenBMB publishes MiniCPM5-2B in bf16 and nothing else, so +"MiniCPM5-2B FP8A8" is a statement about what this engine *runs*, not about what the checkpoint +holds. `llama_dense_fp8` declares the empty quantisation descriptor and the recipe +`data/recipes/minicpm5-2b-dspark.recipe` does the work at conversion — libquant's `rtn`, one amax +per 128x128 block, `scale = amax/448` rounded to bf16 — so the container holds the encoding a +checkpoint that shipped fp8 would. Both plugins declare the same ops over the same encoding, and the +kernels lay it out the same way at load, so nothing downstream can tell which one ran. For the same +reason the bf16 checkpoint itself is not served directly: its linears are not the fp8 this plugin +reads. + +What is fp8: `self_attn.{q,k,v,o}_proj` and `mlp.{gate,up,down}_proj`, each with a bf16 +`[N/128][K/128]` scale plane. What is not: every norm and the embedding. The lm_head is declared at +whatever the source holds — bf16 from a checkpoint, fp8 where the recipe made it so — and the +selection picks the GEMM that reads it. Both vocabulary edges are row-sharded. + +--- + +# `qwen35` — the hybrid Gated DeltaNet / gated-attention family + +Qwen3.5, Qwen3.6 and Qwen3.8 dense models share this architecture; HuggingFace calls it +`model_type: qwen3_5` (`Qwen3_5ForConditionalGeneration`) and GGUF calls it `qwen35`. + +## Qwen3.8-27B-FP8, exactly + +``` +64 layers, full_attention_interval 4 -> layers 3,7,...,63 are FULL ATTENTION (16 of them) + the other 48 are GATED DELTA NET +hidden_size 5120 intermediate_size 17408 vocab_size 248320 +num_attention_heads 24 num_key_value_heads 4 head_dim 256 -> GQA 6 +attn_output_gate true -> gated attention +partial_rotary_factor 0.25 -> RoPE over 64 of the 256 head dims +mrope_interleaved true, mrope_section [11, 11, 10] -> MROPE, not plain rope +rope_theta 1e7 rms_norm_eps 1e-6 max_position_embeddings 262144 + +linear_num_key_heads 16 linear_key_head_dim 128 +linear_num_value_heads 48 linear_value_head_dim 128 -> GDN GQA 3:1 +linear_conv_kernel_dim 4 mamba_ssm_dtype float32 output_gate_type swish +mtp_num_hidden_layers 1 tie_word_embeddings false +quantization: fp8 e4m3, activation_scheme "dynamic", per-weight `weight_scale_inv` +vision: 27 blocks, hidden 1152, 16 heads -> head_dim 72, patch 16, out_hidden_size 5120 +``` + +### Why this lines up with libr4d + +Every geometry above lines up with a libr4d entry point, which is the strongest available evidence +that the kernel-plugin constraint model is the right shape. + +| model geometry | libr4d entry point | +|---|---| +| head_dim 256, GQA 6, paged block 16 | `attn_prefill_h256_gqa6_*`, `attn_decode_h256_gqa6_*` | +| linear k128 / v128, chunk 64 | `gdn_chunk_scan_k128_v128_c64_bf16`, `gdn_kkt_solve_k128_c64_bf16` | +| conv width 4, k128 | `gdn_conv_prep_w4_h128_bf16`, `gdn_conv_update_w4_h128_bf16` | +| recurrent state fp32 | `gdn_recurrent_update_k128_v128_bf16_fp32state` | +| gated attention, interleaved q/gate | `qk_norm_rope_gate` (reads the q/gate interleave off the operand's row pitch) | +| GDN gated norm over an interleaved z | `gdn_gated_norm_had_quant_i8` (`zgrp`/`zblk`) | +| vision head_dim 72 | `attn_vit_h72_bf16` | + +## Tensor names — the FP8 safetensors checkpoint + +Sharded one file per layer (`layers-N.safetensors`), plus `outside.safetensors` and +`mtp.safetensors`. Every FP8 weight carries a companion `weight_scale_inv`; the norms, biases, +`A_log`, `dt_bias` and `conv1d` stay bf16. + +**Full-attention layer** (`model.language_model.layers.N.`): +``` +input_layernorm.weight post_attention_layernorm.weight +self_attn.q_proj.weight (+_scale_inv) [5120, 12288] = 24 heads x 256 x 2, query and GATE +self_attn.k_proj.weight (+_scale_inv) [5120, 1024] +self_attn.v_proj.weight (+_scale_inv) [5120, 1024] +self_attn.o_proj.weight (+_scale_inv) [6144, 5120] +self_attn.q_norm.weight [256] self_attn.k_norm.weight [256] +mlp.{gate,up}_proj.weight (+_scale_inv) [5120, 17408] +mlp.down_proj.weight (+_scale_inv) [17408, 5120] +``` + +**Linear (GDN) layer**: +``` +input_layernorm.weight post_attention_layernorm.weight +linear_attn.in_proj_qkv.weight (+_scale_inv) [5120, 10240] = 2*16*128 + 48*128 +linear_attn.in_proj_z.weight (+_scale_inv) [5120, 6144] = 48*128 +linear_attn.in_proj_a.weight [5120, 48] +linear_attn.in_proj_b.weight [5120, 48] +linear_attn.conv1d.weight [10240, 1, 4] +linear_attn.A_log [48] linear_attn.dt_bias [48] linear_attn.norm.weight [128] +linear_attn.out_proj.weight (+_scale_inv) [6144, 5120] +mlp.{gate,up,down}_proj as above +``` + +**Model level**: `model.language_model.embed_tokens.weight`, `model.language_model.norm.weight`, +`lm_head.weight` (**not tied** on this model), and the MTP head: `mtp.fc.weight`, +`mtp.norm.weight`, `mtp.pre_fc_norm_embedding.weight`, `mtp.pre_fc_norm_hidden.weight`. + +## The full-attention layer — gated attention + +`q_proj` produces the query **and a gate, interleaved per head**: for each of the 24 heads the +first 256 elements are the query and the next 256 are the gate, so both are strided views with +pitch 512 rather than a contiguous split. + +``` +qg = gemm(x, q_proj) [n_tok, 12288] +k, v = gemm(x, k_proj), gemm(x, v_proj) [n_tok, 1024] +q = rmsnorm(view(qg, off 0, pitch 512), q_norm) per head, over 256 +k = rmsnorm(k, k_norm) per head +gate = view(qg, off 256, pitch 512) +q, k = mrope(q, k, positions, sections [11,11,10], rotary dims 64 of 256) +o = attn_paged(q, k, v) scale = 1/sqrt(256) +o = o * sigmoid(gate) <-- the gate. output_gate_type "swish" names the + GDN gate, not this one; this one is a sigmoid +out = gemm(o, o_proj) +``` + +`qk_norm_rope_gate` does the two norms, the rope and the gate extraction in one kernel and takes the +interleaving off the `q_gate` operand's own row pitch, so the projection is declared as it is laid +out rather than converted at load. Declare it first and fall back to the unfused sequence. + +## The linear layer — gated delta net + +``` +qkv = gemm(x, in_proj_qkv) [n_tok, 10240] +z = gemm(x, in_proj_z) [n_tok, 6144] +b = sigmoid(gemm(x, in_proj_b)) [n_tok, 48] -> beta +a = gemm(x, in_proj_a) [n_tok, 48] +g = softplus(a + dt_bias) * A_log_term +conv = silu(causal_conv1d(qkv, conv1d, conv_state)) depthwise, width 4, 10240 channels +q,k,v = strided views of conv: q at 0 (16x128), k at 2048 (16x128), v at 4096 (48x128) +q, k = l2_norm(q), l2_norm(k) <-- L2, NOT rmsnorm +o = delta rule: chunked scan at prefill, recurrent update at decode +o = rmsnorm(o, linear_attn.norm) * silu(z) the gated norm +out = gemm(o, out_proj) +``` + +`linear_num_value_heads` (48) is three times `linear_num_key_heads` (16), so q and k are shared +across three value heads. libr4d's GDN kernels take `H` and `Hg` separately for exactly this. + +## Things that stay plausible when wrong, so get them right + +- **`q`/`k` use L2 normalisation, not RMS.** Different op, different arithmetic. +- **`A_log` is a log.** In the GGUF conversion `ssm_a` is already `-exp(A_log)`; in *this* + safetensors checkpoint the tensor is named `A_log` and the exponent has **not** been taken. The + converter is the component that decides which convention reaches the kernel, and it must say so. +- **The GDN output gate is `silu` here and `sigmoid` on Qwen4-Exp.** `RMSNormGated` defaults to silu + and every Qwen3.5/3.6 release leaves it there; Qwen4-Exp states `output_gate_type: "sigmoid"` and + means it. A gate of `sigmoid(z)` where the model wants `silu(z)` rescales every value head's + output — a config read, not a kernel to write. `arch/common/rad_block_gdn_fp8.h` refuses anything + but those two names. +- **Two readings the checkpoint cannot settle by inspection.** The rope convention (`neox`, halves, + against `gptj`, adjacent pairs) and which half of each head's `q|gate` pair is the query are both + self-consistent either way, and the sigmoid accepts either half — so no per-op check can reach + them. The MTP head's concat order (hidden-first or embedding-first) is the third of the same kind. + Each is a declared knob at the site that reads it, for the same reason. + +## KV groups + +Three of them, which is why hybrid KV groups are first-class rather than an extension: + +| group | kind | geometry | +|---|---|---| +| full attention | `RAD_KV_FULL` | 16 layers, head_dim 256, 4 KV heads; block size from the resolved kernel | +| GDN recurrent state | `RAD_KV_LINEAR` | 48 layers, 48 states of 128 x 128 | +| GDN conv state | `RAD_KV_CONV` | 48 layers, 2*16 + 48 = 80 heads x 128 = 10240 channels, a rolling `conv_width - 1 + n_spec` window | + +**The recurrent state is f32 by default**, which is 48 x 128 x 128 x 4 = 3 MiB a layer and +**144 MiB across the 48 linear layers, per sequence** — and it is what the prefix-cache checkpoint +of `spec.md` §7.3 snapshots. Its read and write are most of what the two GDN kernels do, so halving +its width halves one of the largest kernels after the fp8 GEMMs. libr4d compiles an f16 form and +argues the numerics where the kernel lives — the elements are O(0.1) with no range problem and +f16's eleven mantissa bits put the round-trip error at 5e-4 relative. It is **off by default +anyway**, because it changes generated text without being asked to; nothing about the container +changes between the two, so there is no re-convert. How a speculative step keeps the state it can +roll back is `docs/OPS.md`'s `state_form`. + +## FP8 + +`quant_method: fp8`, `fmt: e4m3`, `activation_scheme: dynamic`, and a `weight_scale_inv` beside +every quantised weight — DeepSeek-style block scaling, 128x128. Activations are quantised at +runtime, which is what "dynamic" means and what makes the activation quantiser an op rather than a +constant. The vision tower's first several blocks are in `modules_to_not_convert` and stay bf16. + +**libr4d reads those bytes directly, so `rad-convert` COPIES**: no permutation, no repacking, no +dequantisation, and a `.rad` costs what the checkpoint does. That is the whole reason this plugin +family exists — widening a 27B FP8 checkpoint to bf16 doubles the weight bytes; `qwen35_bf16` is the +plugin for a checkpoint that is bf16 to begin with. +The rows are `gemm_fp8a16_nt_m1`, `gemm_fp8a8_nt_m16`, `gemm_fp8a8_gated_nt_m16` and +`gemm_fp8a8_tiled`. + +**The shipped path is `fp8a8`**, and the reason is a band and not a preference. `dtype` is ONE string +per declared op, so a linear is `fp8a16` or `fp8a8` and cannot be both. `fp8a16` reads a bf16 +activation directly and needs no quantise launch, which is strictly better — and its kernel serves +`M <= 1`, which is a single-sequence decode and nothing else. `fp8a8`'s two kernels cover every M +between them, and the price is one `quant_act_fp8` launch per activation that feeds a GEMM — *per +activation*, not per linear, which is why the quantiser is its own struct rather than a step inside +the linear. + +**The scale plane is a WEIGHT operand**: `gemm_nt_q` takes `a, a_scale, b, b_scale`, and `b` and +`b_scale` are two declarations over the planes of one logical weight (`RadWeightDecl::planes`). +Each is placed, moved and sharded on its own — the engine cuts a row-sharded scale plane on its +block boundary exactly as it cuts the codes beside it. + +## `qwen35moe` + +This architecture with the MLP replaced by a router plus experts, and *only* that: the gated +attention, the gated delta net, the layer schedule, the rope, the vocabulary edges and the MTP head +are identical, and the places where a routed feed-forward differs are behind one conditional in the +shared source. It is a second translation unit rather than a branch on `n_expert` because the id is +half the selection key — one `.so` cannot claim both, and an operator looking at what is installed +should see two plugins for two architectures. + +--- + +# `qwen4exp` — Qwen4-Exp / Qwen3.8-Flash-Next + +`model_type: qwen4_exp`, a subclass of `Qwen3_5MoeTextModel` — so most of it is composition over the +blocks above. What is genuinely new is small and named: the gated residual, the n-gram/PLE layer, +QSA's indexer, stacked dense expert tensors, GQA 12, and the delta net's sigmoid output gate. + +``` +48 layers of 12 x (3 x GatedDeltaNet -> MoE, then 1 x QSA -> MoE) +hidden_size 2560 hc_count 4 -> the residual stream is 10240 +512 experts of 640 at top-10, plus a shared expert of 640 +24 query heads, 2 KV heads, head_dim 256 -> GQA 12 +vocab 248320 max_position_embeddings 262144 +indexer_n_heads 4 indexer_head_dim 128 indexer_budget 2048 indexer_compress_ratio 4 +mtp_num_hidden_layers 1 output_gate_type sigmoid +``` + +**The residual stream is four times as wide, and the blocks do not own their norms.** There is no +`input_layernorm`, no `post_attention_layernorm` and no final `norm` in this checkpoint. In their +place every block has a gated residual connection — a grouped norm over the 10240 stream, a low-rank +data-dependent read gate that mixes the four sub-streams down to 2560, and four data-dependent +scalars that gain the block's output back into all four. 96 of them, plus a 97th with no write half +that collapses the stream for the lm_head. The consequence for the blocks is that they run in their +"input is already normed and quantised" mode and therefore give up two fusions — the residual add +folded into the next norm, and the all-reduce folded into it. + +**What each weight is stored as is the recipe's decision.** The checkpoint is bf16 throughout and +carries no `quantization_config` at all, so the plugin's descriptor is the empty one: `rad-convert` +quantises by a recipe, and the plugin reads each weight's encoding from the container and declares +the op that reads it. The block linears — `self_attn.{q,k,v,o}_proj`, +`linear_attn.{in_proj_qkv, in_proj_z, out_proj}`, the shared expert's three — are block fp8 or +int8 (served W8A8). Every routed expert's gate_up and down is fp8, bf16, or one of the four- and +five-bit forms of `docs/MOE-W4.md`. +Each connection's two mixing matrices and the MTP head's `fc_hidden` / `fc_embedding` are E4M3 rows +or bf16: the low-rank width is 320, which is 2.5 scale blocks, so they are scaled a row group at a +time rather than block-scaled. The lm_head is whatever a `logits_gemm` kernel reads. Every norm +gain, `A_log`, `dt_bias`, `conv1d`, `in_proj_a` and `in_proj_b` (48 rows is not a whole scale +block), the router, `shared_expert_gate` and `embed_tokens` stay bf16. +`data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe` is the served choice: four-bit codebook experts with +ten protected experts left bf16, int8 block linears and lm_head, E4M3 mixing and MTP fc matrices, +and the n-gram table at one fixed E4M3 scale. + +**Tensor parallel splits every expert's width, unevenly.** `moe_intermediate_size` is 640 = 5 x 128, +so an even share at tp2 is 320, which is not a whole number of 128-column blocks — and the fp8 +scale block, the four-bit scale group and the rotation all sit on them. So each rank takes three +blocks of the experts of one parity and two of the other's (`moe_gemm_q`'s two tables in +`docs/OPS.md`), the router stays replicated so both ranks agree on the routing, each rank computes +its slice of every routed expert, and the block's existing end-of-block all-reduce sums the +partials. No all-to-all, no extra collective. The shared expert's 640 columns split the same way, +three blocks on rank 0 and two on rank 1. + +**Four-bit experts are what make it fit.** 512 experts of 640 over 48 layers is 112.8 GiB of expert +weight at E4M3 and twice that at bf16. `--weights-disk-tier` serves what fits neither VRAM nor the +host pool from the container file, but a routed expert is then read a layer at a time and a step is +paced by the drive. At four bits an expert unit is 2.42 MiB instead of 4.69 and the per-rank share +fits VRAM plus a few GiB of pinned host. `docs/MOE-W4.md` is the format. + +**PLE / the n-gram embedding is 51B of the model's 180B parameters** — a 320,001,536-row table of +160-dim embeddings, gathered 16 rows a token by a hash of the last three token ids, read once at +layer 1 and injected into the wide stream. Without it this is a 125B model missing a third of its +parameters. + +**QSA** picks the best `indexer_budget / indexer_compress_ratio` = 512 blocks of 4 tokens for each +query and attends to those alone. Below `indexer_budget + indexer_compress_ratio - 1` = 2051 tokens +of context every complete block is selected, so QSA is dense causal attention bit for bit — which is +why a prefill below the bound runs the cheaper dense attention, and is the property any change to it +is argued against. `docs/QSA.md` is the decomposition. + +The vision tower is declared when the container carries one and `--mm-max-patches` is not 0 +(`arch/common/rad_block_vit.h`, `spec.md` §11). + +--- + +# Two rules about measuring these + +**A bisect knob is not a deployment knob.** Several switches here ablate a block or a layer range; +they produce a DIFFERENT MODEL and exist so that a wrong distribution can be attributed to a block +when nothing compares a whole layer against an oracle. A serve that sets one is a serve that is not +running the model, and the plugin says so at declare time. **Knobs are documented where they are +read** — a table of them in a document goes stale silently and ends up naming variables nothing +reads. + +**THE SAMPLE SIZE IS PART OF THE RESULT.** Top-1 agreement between two numeric formats is one +Bernoulli trial per prompt, so at p ≈ 0.93 its standard error is 2.8 points at N = 80 and 2.0 at +N = 160 — wide enough that formats which differ by less than that rank in any order. Rank with a +graded statistic that has thousands of samples rather than hundreds (the mean |delta| over the +logits row, or the per-position KL of `radiance --kld-ref`), and confirm any ordering at N ≥ 160 +before acting on it. diff --git a/docs/DOCKER.md b/docs/DOCKER.md new file mode 100644 index 00000000..efc5817b --- /dev/null +++ b/docs/DOCKER.md @@ -0,0 +1,141 @@ +# Radiance in a container + +The repository builds into one Docker image that holds the engine, its plugins, its tools and the +recipes, and nothing else: it is assembled from scratch out of the install tree and exactly the +shared libraries that tree loads. The host needs Docker, an AMD GPU and an `amdgpu` kernel driver +that supports ROCm 7.2. It does not need ROCm itself, a compiler, or ffmpeg. + +The image is published as [`stilldeadcode/radiance`](https://hub.docker.com/r/stilldeadcode/radiance), +with its kernels built for `gfx1201`: `docker pull stilldeadcode/radiance`. Build it yourself for +other cards or another commit. The examples below use `radiance`, the tag a local build gets; with +the published image, write `stilldeadcode/radiance` instead. + +Besides radiance (Apache-2.0, `/opt/radiance/share/doc/radiance/`), the image holds glibc, +libstdc++, the ROCm runtime, FFmpeg, busybox and a few other libraries, each under its own license, +GPL and LGPL among them. `/usr/share/doc/THIRD-PARTY` in the image lists every one with its exact +version, its license files and where its source is; `docker/licenses.sh` writes it during the build +and stops the build if a file in the image cannot be traced to a package. + +## Build the image + +```sh +docker/build.sh # HEAD, tagged radiance:, radiance:, radiance:latest +docker/build.sh -s gpu-host # stream the commit over ssh; gpu-host builds and keeps the image +docker/build.sh -j 8 # cap compile jobs (a device kernel takes 2-3 GB under hipcc) +docker/build.sh -t 'gfx1200;gfx1201' # GPU architectures to compile kernels for (default gfx1201) +docker/build.sh -r # any other commit +docker/build.sh --target build # stop at a stage, tagged radiance- +``` + +The context the script sends is `git archive` of the commit, so the image holds exactly what is +committed: no build directory, no uncommitted edit, no model file. It builds with BuildKit +(`docker buildx`), which runs independent stages side by side and caches each one; with `-s` only +the remote machine needs buildx. + +The `Dockerfile` has three stages: + +| stage | what it does | +|---|---| +| `ffmpeg` | FFmpeg 8.1 with only the demuxers `core/mm/media.cpp` admits and the decoders their streams carry (still images, H.264, HEVC, VP8, VP9, AV1 through dav1d, MPEG-1/2/4, Theora, FLV/H.263). The distribution's build brings about 200 packages of encoders, filters and display libraries the engine never calls | +| `build` | `rocm/dev-ubuntu-24.04:7.2.4` plus cmake, ninja and g++-14. Configures with the kernels compiled for `GPU_TARGETS`, builds, and installs to `/opt/radiance`. Device code is not stored compressed: the engine's AQL backend reads the fat binaries itself and refuses a compressed bundle | +| `test` | `ctest -LE gpu`: every suite that runs without a card. The image is only produced if they pass | +| `rootfs` | The install tree, stripped, plus every shared library its binaries and plugins load (resolved by `ldd`, glibc and the ROCm runtime included) in one directory the loader searches by default, `amdgpu.ids`, and a static busybox. Every ELF file is then resolved from inside a chroot of the tree, so the build fails on a library the image lacks | +| `runtime` | `FROM scratch` and the rootfs. This is the image that ships | + +The largest single file is comgr (about 150 MB), which the HIP runtime cannot initialise a device +without. There is no distribution in the shipped image: no package manager and no shell beyond busybox +(`docker exec -it sh`). JPEG XL input is refused by name, since its decoder needs libjxl. + +A build container has no card to enumerate, so the GPU architecture must be named. A bare-metal +`./build.sh` detects it instead. `libr4d` builds for gfx12 targets only; any other target in the +list just gets no RDNA4 kernels. + +The ROCm version in the image has to be one the host's kernel driver supports. It is a build +argument (`ROCM_VERSION`, default 7.2.4). + +The GPU suites (`mem_test`, `r4d_selftest`, `kbench`) need the card to themselves. They run from +the `build` stage: + +```sh +docker/build.sh --target 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 +``` + +## Run it + +The entrypoint is `radiance`. Every other tool (`rad-convert`, `rad-info`, `rad-kbench`, +`rad-tune`, `rad-schemas`, `rad-tokcheck`) is on `PATH`, and the recipes are in +`/opt/radiance/share/radiance/recipes/`. + +```sh +docker run --rm -v /srv/models/rad:/models:ro --entrypoint rad-info radiance /models/m.rad + +docker run -d --name radiance --network host --init \ + --device /dev/kfd --device /dev/dri --security-opt seccomp=unconfined \ + --group-add "$(getent group render | cut -d: -f3)" \ + --group-add "$(getent group video | cut -d: -f3)" \ + -v /srv/models/rad:/models:ro \ + radiance --model /models/m.rad --tp 2 --host :: --port 8000 +``` + +Every one of these options is needed: + +- **`--device /dev/kfd --device /dev/dri`**, plus the `render` and `video` groups, give the + container the GPUs. +- **`--security-opt seccomp=unconfined`**: Docker's default seccomp profile refuses io_uring. + Qwen3.8-Flash-Next's n-gram embedding table is read from the container through io_uring, so + without this the model cannot serve. The profile also refuses the NUMA binding calls the ROCm + runtime makes for host memory. +- **`--init`**: the engine is not PID 1. It finishes its step and releases the cards on SIGTERM. +- **`--network host`**: the server binds the host's addresses directly, IPv4 and IPv6, with no + NAT in front of it. + +The image sets `GPU_MAX_ALLOC_PERCENT=100` and `GPU_MAX_HEAP_SIZE=100`. The HIP runtime's defaults +cap one allocation, and the heap, below what the placement plan hands out. + +**A plugin of your own** — a kernel library for another card, an architecture, a quantiser — is +mounted and put first on the search path; nothing in the image changes: + +```sh +docker run ... -v /srv/radiance-plugins:/plugins:ro \ + -e RADIANCE_HOME=/plugins:/opt/radiance/share/radiance \ + radiance --model /models/m.rad +``` + +`/plugins` holds any of `kernels/`, `architectures/` and `quantizers/`, built against the same +radiance version (`docs/PLUGIN.md` §13). The engine in the image starts on any AMD GPU family: the +image's `GPU_TARGETS` are what its bundled kernel library, libr4d, is compiled for, not a limit on +the cards the engine runs on. + +## Compose + +`deploy/compose/` has one file per model and a `common.yaml` that each of them extends: + +| file | container | what it is | +|---|---|---| +| `flashnext.yaml` | `qwen3.8-next-flash-fp8-iq4r-moe.rad` | Qwen3.8-Flash-Next, 4-bit codebook experts and an int8 trunk; MTP depth 3; idle sessions kept in host memory and on disk | +| `flashnext-bf16.yaml` | `qwen3.8-flash-next-bf16.rad` | Qwen3.8-Flash-Next in bf16, streamed from the disk tier. A reference, not a production server | +| `qwen3.6-35b-a3b.yaml` | `qwen3.6-35b-a3b-fp8.rad` | Qwen3.6-35B-A3B, FP8 | +| `qwen3.8-27b-fp8.yaml` | `qwen3.8-27b-fp8.rad` | Qwen3.8-27B FP8 with its DFlash2 drafter and vision tower | +| `qwen3.8-27b-bf16.yaml` | `qwen3.8-27b-bf16.rad` | Qwen3.8-27B in bf16 | +| `minicpm5-2b.yaml` | `minicpm5-2b-fp8.rad` | MiniCPM5-2B FP8 with its DSpark drafter | +| `minicpm5-2b-bf16.yaml` | `minicpm5-2b-bf16.rad` | MiniCPM5-2B in bf16 with its DSpark drafter | + +The container names are the files the README's model table downloads or converts. + +Copy the directory to the serving host and fill in `.env` from `.env.example`. It sets the image, +the models directory (mounted read-only at `/models`), a writable state directory (`/data`, where +the prefix cache's disk tier lives), the API key, the port, and the user and GPU groups the server +runs as. Then: + +```sh +docker compose -f flashnext.yaml up -d # start; restarts with the Docker daemon +docker compose -f flashnext.yaml logs -f # follow the log +docker compose -f flashnext.yaml down # stop +``` + +Each model takes both cards and the same port, so run one at a time: `down` one before `up` on +another. The server runs as the host user given in `.env`, so the files it writes under `/data` +belong to that user. `/health`, `/ping` and the dashboard page answer without the API key, and the +health check fetches `/health` with busybox's `wget`. diff --git a/docs/GUIDE.md b/docs/GUIDE.md new file mode 100644 index 00000000..452bd78b --- /dev/null +++ b/docs/GUIDE.md @@ -0,0 +1,1267 @@ +# Radiance — user guide + +Radiance is an inference server: it loads a model and answers OpenAI-compatible HTTP requests. +This guide takes you from an empty machine to a running server, and then through operating one. + +There is no Python anywhere — not in the engine, not in the tools, not in the build. Everything +below is C++, CMake and shell. + +**Where to go from here** + +| If you want | Read | +|---|---| +| to get something running | this file, in order | +| every flag of one tool | [TOOLS.md](TOOLS.md) | +| to write a kernel library for your card | [PLUGIN.md](PLUGIN.md) | +| to know why it is built this way | `../spec.md` — the design, and it is binding | + +--- + +## 0. The whole thing in five commands + +```sh +./build.sh # build and test +export RADIANCE_HOME=$PWD/build/radiance_home + +scripts/hfget.sh Qwen/Qwen3.8-Flash-Next ~/ckpt # get a checkpoint +build/bin/rad-convert ~/ckpt -o ~/m.rad \ + --recipe data/recipes/qwen4exp-w4.recipe # quantise it into a container +build/bin/radiance --model ~/m.rad --port 8000 # serve it +``` + +A checkpoint served at its own precision needs no container at all: `radiance --model ~/ckpt` +reads it as it stands (§3.4). + +Then: + +```sh +curl -s localhost:8000/v1/chat/completions -H 'Content-Type: application/json' \ + -d '{"model":"m","messages":[{"role":"user","content":"hi"}],"max_tokens":50}' \ + | jq -r '.choices[0].message.content' +``` + +and open `http://localhost:8000/` for the dashboard. Everything below is the detail behind those +five lines. + +--- + +## 1. Install + +**Or skip this section and run the container image**: `docker/build.sh` builds the engine inside +the ROCm toolchain image, tests it and produces an image that needs only Docker and the `amdgpu` +driver on the host. [`DOCKER.md`](DOCKER.md) covers it, along with ready compose files per model. + +### 1.1 What you need + +| | | +|---|---| +| **Required** | Linux, a C++20 compiler, CMake 3.21+, Ninja, pthreads | +| **Optional** | ROCm with `hipcc`, for AMD device kernels. Without it you get the host backend. Set `ROCM_PATH` if it is not at `/opt/rocm` | +| **Optional** | OpenMP, used by the host kernel libraries if present | +| **For the shell harnesses** | `curl` and `jq` | + +Everything else is vendored in `vendor/` — the HTTP server, the JSON library and the llama.cpp +lifts. There is nothing to `apt install` beyond a toolchain. + +**A machine with no GPU is a supported configuration.** The host backend is a real implementation, +not a stub: the core, scheduler, planner, tokeniser, server and `libref` all run through it and +the full test suite passes. It is slow, and it will not serve a production model — but it is a +complete development and inspection environment. + +### 1.2 Build + +```sh +git clone radiance && cd radiance +./build.sh +``` + +That configures, builds and runs the tests. It detects your situation: if `hipcc` is present and a +card can be enumerated, device kernels are compiled for that card's architecture; otherwise you +get the host backend. + +Options: + +```sh +./build.sh -c # wipe the build directory first +./build.sh --no-hip # force the host backend even where hipcc exists +./build.sh --debug # -DCMAKE_BUILD_TYPE=Debug +./build.sh --asan # AddressSanitizer +./build.sh -b mybuild # build into mybuild/ instead of build/ +``` + +Or drive CMake yourself: + +```sh +cmake -S . -B build -G Ninja +cmake --build build -j +ctest --test-dir build --output-on-failure +``` + +### 1.3 Check that it works + +```sh +ctest --test-dir build --output-on-failure # everything (a few minutes) +ctest --test-dir build -LE slow # the fast inner loop (~1 s) +ctest --test-dir build -LE gpu # skip anything needing a card +``` + +Three of them are worth knowing by name, because they are the ones that actually check kernels: + +- **`kbench` / `kbench_moe`** (label `slow`) replay a recorded fixture — every kernel every loaded + library supplies, checked against `libref`'s recorded answers on seeded inputs. **No model file is + needed**, which is what makes this runnable on a build machine. It also regression-tests `libref` + itself, which a live oracle never can. +- **`r4d_selftest`** (labels `slow`, `gpu`) checks libr4d's fusion claims by `memcmp` against the + unfused kernels it says it replaces. +- **`ops_doc`** (fast) checks that `docs/OPS.md` still agrees with what the plugins declare. A + document that is wrong is worse than one that is missing, because it is read instead of the source. + +You can also run the kernel check by hand: + +```sh +build/bin/rad-kbench --home build/radiance_home --max-cases 1 +``` + +### 1.4 Install to a prefix + +```sh +cmake -S . -B build -G Ninja -DCMAKE_INSTALL_PREFIX=/usr/local +cmake --build build -j +sudo cmake --install build +``` + +What lands where: + +``` +/bin/ radiance, rad-convert, rad-info, + rad-kbench, rad-tune, rad-schemas, rad-tokcheck +/include/ the ABI headers — all a plugin compiles against +/lib/cmake/radiance/ the package config, for find_package(radiance) +/share/radiance/ $RADIANCE_HOME: kernels/, architectures/, quantizers/, kernels*.rkb +``` + +### 1.5 `$RADIANCE_HOME` + +This is the directory the engine and every tool scan at startup: + +``` +$RADIANCE_HOME/ + kernels/ kernel libraries libr4d.so, libref.so, libavx.so, yours.so + architectures/ architecture plugins qwen4exp_fp8.so, llama_fp8.so, ... + quantizers/ quantiser plugins libquant.so + kernels.rkb the recorded kernel fixtures rad-kbench replays (and kernels_moe.rkb) + tune/ per-machine tuning caches rad-tune writes +``` + +It defaults to the install prefix's `share/radiance`. Override it with `--radiance-home DIRS` or the +`RADIANCE_HOME` environment variable — a search path: homes separated by `:`, the first winning, +each holding any of the directories above. A directory of your own plugins goes ahead of an +installation's without copying it, and `rad-info --plugins` prints what the path offers: + +```sh +RADIANCE_HOME=$HOME/radiance-plugins:/opt/radiance/share/radiance rad-info --plugins +``` + +**Running from a build tree**, the home is `build/radiance_home` and the plugins are already in it: + +```sh +export RADIANCE_HOME=$PWD/build/radiance_home +build/bin/radiance --model m.rad +``` + +Adding support for a new card means dropping an `.so` into `kernels/` — not forking the engine. +The engine's own device code is built for every AMD GPU family, so one engine binary starts on any +card; a kernel library whose code objects hold nothing for the card is left out of selection when +it loads, and says so. `docs/PLUGIN.md` §10 is a library for a card the engine has never seen. + +### 1.6 Building for a card you do not have + +Device kernels are compiled for the architectures the machine reports. To target others: + +```sh +cmake -S . -B build -G Ninja -DRAD_GPU_TARGETS='gfx1201;gfx1200' +``` + +Which of those actually get kernels is decided by the libraries present; each one declares the +architectures it serves and stays out of a build targeting anything else. The engine's own device +code is built for every family's generic target besides, whatever is named here. + +--- + +## 2. Five things to know before you start + +**1. A model is a checkpoint served as it stands, or a `.rad` container.** A checkpoint whose +weights are bf16, f16, f32 or block-scaled fp8 is served at that precision straight from its +directory. Anything that needs quantising is quantised once, by `rad-convert` and a recipe, into a +container. A container holds each weight as the planes of its *encoding* — codes, scales, zero +points, a rotation — in one canonical arrangement, plus the tokeniser, the chat template, the +metadata, the recipe it was quantised with and optionally a draft head. No kernel library is named +in either: the kernels rearrange the planes into their own layouts as the model loads, so a kernel +library can change without a reconvert. + +**2. Kernels are plugins, and the order matters.** The engine resolves every op in the model +against an ordered list of kernel libraries: first one that matches an op wins. `--kernels +mylib,libref` states that order. With no list, the loader orders what it finds and puts a +library that declares itself a reference implementation last. + +Three ship with the tree: + +| library | | +|---|---| +| `libr4d` | the device library: AMD RDNA4 (`gfx12xx`). Paged and dense attention, gated delta net, P2P all-reduce, skinny and tiled quantised GEMM, rotate-and-quantise fusions. Built when ROCm is present and the build targets a `gfx12` card | +| `libref` | every op naively and generically. The last-resort fallback **and** the correctness oracle `rad-kbench` measures against | +| `libavx` | the host library: the same vocabulary in hand-written x86 SIMD, dispatched by CPU feature at load. Serves every op placed on the host, the n-gram embedding's gather among them. Built on x86-64 | + +A library states the architectures it serves and stays out of a build targeting anything else, so a +tree configured for a card it does not cover still builds and still runs. + +**3. Architectures are plugins too.** `arch//` declares a model family's graph. Six ship: + +| plugin | serves | +|---|---| +| `llama_fp8`, `llama_dense_fp8` | LLaMA-shaped decoders — MiniCPM5, Llama 3, anything reporting `model_type: llama` | +| `qwen35_bf16` | Qwen3.5 / 3.6 / 3.8 dense (0.8B–27B), bf16 | +| `qwen35_fp8` | the same, block-scaled fp8 | +| `qwen35moe_fp8` | Qwen3.5 / 3.6 MoE (35B-A3B), 256 experts, 8 a token | +| `qwen4exp_fp8` | Qwen4-Exp / Qwen3.8-Flash-Next — hybrid Gated DeltaNet + gated attention, 512 experts | + +**4. Falling back to the reference library is a fatal error, not a warning.** `libref` implements +every op naively and generically. It is the oracle and the last resort. If your model resolves any +op to it, the engine **refuses to start** and names the ops, because serving from it would be +orders of magnitude slow with nothing in the output to say so. That list of ops is exactly the +work a new kernel library has to do. `--debug-accept-reference-kernels` overrides it for bring-up. + +**5. Every pool is budgeted explicitly.** There is no profiling pass and no utilisation fraction. +The trade between KV blocks and resident weights is real, workload-dependent and **yours to make**. +An engine that quietly re-optimises the split is an engine whose benchmarks do not reproduce. + +--- + +## 3. Get a model in + +### 3.1 Download a checkpoint + +```sh +scripts/hfget.sh Qwen/Qwen3.8-Flash-Next ~/models/Qwen/Qwen3.8-Flash-Next +``` + +`curl` and `jq`, nothing else. Re-running resumes: a file whose local size already matches is +skipped and a short one is continued. It also skips duplicate weight formats — if a repo carries +`.safetensors` it will not also pull the `.bin`, the ONNX export and the GGUF. + +Set `HF_TOKEN` for a gated or private repo. `HFGET_JOBS` sets concurrency (default 4). + +### 3.2 Convert it + +```sh +rad-convert ~/models/Qwen/Qwen3.8-27B-FP8 -o ~/models/rad/q38-27b-fp8.rad --home $RADIANCE_HOME +``` + +Input is a `.gguf`, a `.safetensors`, or a directory holding a checkpoint. What happens: the +architecture plugin declares the model's graph and its name map says which checkpoint tensors make +each weight; every op is resolved against the kernel hierarchy and every resolved kernel is asked +whether it reads the encoding each weight will have; then each weight is written once, as its +encoding's planes, and the tokeniser and chat template are baked in. + +**A recipe decides what is quantised.** With none, every weight keeps the checkpoint's encoding, +which is right for a bf16 or block-fp8 checkpoint served at its own precision. A model whose served +form needs quantisation work — Flash-Next's four-bit experts, an fp8 head made from a bf16 one — +names it in rules from weight names to quantisers: + +```sh +rad-convert ~/models/Qwen/Qwen3.8-Flash-Next -o ~/models/rad/flashnext-w4.rad \ + --recipe data/recipes/qwen4exp-w4.recipe --home $RADIANCE_HOME +``` + +`qwen4exp-w4.recipe` rounds the experts to nearest and needs nothing but the checkpoint. The +production Flash-Next container, `w4nl64-i8lm.rad`, is built by +`data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe`, whose expert rule is GPTQ against recorded Grams: +it expands `$CALIB` from the environment, so it is run as `CALIB=DIR rad-convert ...` with `DIR` +holding a calibration run's files. The recipe's header and [MOE-W4.md](MOE-W4.md) say what that +directory must hold and how it is recorded. + +``` +# data/recipes/... -- PATTERN QUANTISER OPTIONS; the first match decides +blk.*.ffn_*_exps.*.weight gptq codes=i4 group=128 scale=bf16 transform=fwht128 calib=$CALIB +output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +``` + +Every weight it quantises is measured against the source and the worst are printed. The recipe +syntax, the quantisers and their options are in [TOOLS.md](TOOLS.md#recipes). + +Because it runs the same declare phase the engine does, everything that can refuse has refused by +the time the I/O starts — including a recipe no loaded kernel can serve. On a large checkpoint that +I/O is an hour, so check the plan first: + +```sh +rad-convert -o out.rad --recipe r.recipe --plan-only -v +``` + +Useful variants: + +```sh +# Merge a separate drafter checkpoint (DSpark, DFlash2) into the container +rad-convert $SRC -o out.rad --draft-model ~/models/openbmb/MiniCPM5-2B-DSpark + +# Re-quantise some weights and copy the rest from an earlier container +rad-convert $SRC -o new.rad --recipe new.recipe --reuse old.rad +``` + +The conversions of record live in `scripts/convfn.sh` and `scripts/convdspark.sh`, with their +recipes in `data/recipes/`. + +### 3.3 Look at what you built + +```sh +rad-info ~/models/rad/flashnext-w4.rad +``` + +``` +flashnext-w4.rad + format RAD2, 166.4 GiB, little-endian + architecture qwen4exp + model Qwen3.8-Flash-Next + source quant (none) + recipe 14 line(s) -- --recipe prints it + created by rad-convert ... + + section offset bytes count + strings 256 1.2 MiB - + metadata 1258752 8.4 KiB 214 + ... +``` + +`rad-info` opens the file read-only and loads no plugins. It lists every weight with its encoding +and what made it — the checkpoint as it stood, or the recipe rule's quantiser and options. + +```sh +rad-info --meta m.rad # just the metadata table +rad-info --vocab m.rad # vocab summary and normaliser chain +rad-info --recipe m.rad # the recipe it was converted with +rad-info -v m.rad # every tensor +``` + +### 3.4 Or skip the container + +```sh +radiance --model ~/models/Qwen/Qwen3.8-27B-FP8 +``` + +`--model` takes a checkpoint directory, a `.safetensors`, an index or a `.gguf`, and serves it at +its own precision. Its `config.json` (or the GGUF header) is the metadata, the `tokenizer.json` and +chat template beside it are the tokeniser, and `generation_config.json` gives the sampling defaults. +The weights are read once, at load, by every relayout worker at once. + +**Nothing is quantised at load.** A weight the architecture plugin reads in another encoding than +the checkpoint holds is named at startup, and the remedy is a container with a recipe that says +what it becomes. MiniCPM5-2B is one: OpenBMB ships it in bf16, and `llama_dense_fp8` reads fp8. + +What a container has that a checkpoint does not: + +| | | +|---|---| +| the file and mapped tiers | a checkpoint is neither grouped nor aligned for them, so every weight must fit VRAM or the host pool, and a weight only a host kernel reads (the n-gram table) cannot be served | +| a merged drafter | `--draft-model` is `rad-convert`'s; a checkpoint serves the draft head it ships, if any | +| a placement profile | worth about a point of expert hit rate | + +A GGUF is read when its architecture plugin maps llama.cpp's tensor names; the shipped plugins map +HuggingFace's, so a model of a shipped architecture is converted from its safetensors release. + +--- + +## 4. Serve it + +### 4.1 The simplest run + +```sh +radiance --model ~/models/rad/flashnext-w4.rad +``` + +It claims the card (less `--gpu-headroom-mib`, default 96 MiB), splits it between weights and KV +cache, loads, and serves on `http://0.0.0.0:8000`. The startup log states every budget before +anything is allocated. + +```sh +radiance --model m.rad --port 8100 --host 127.0.0.1 +``` + +### 4.2 Look before you leap + +```sh +radiance --model m.rad --debug-graph +``` + +Prints the entire declared graph — every op, the kernel each one resolved to, and why — then exits +without serving. This is the first thing to run against a new container or a new kernel library. + +```sh +radiance --model m.rad --debug-selection # just the selection table +radiance --model m.rad --debug-placement # just the placement plan +``` + +### 4.3 Memory: how the card gets split + +The card is split into **resident weights** and the **paged KV pool**. You can state the split +outright: + +```sh +radiance --model m.rad --vram-weights-mib 24000 --vram-kv-mib 6000 +``` + +or let the engine derive it from the card and tell it only the ratio: + +```sh +radiance --model m.rad --expert-vs-cache-ratio 0.82 +``` + +`--expert-vs-cache-ratio` is the **weights** share of what is claimed. 0.75 (the default) gives +three quarters to weights and a quarter to KV. + +**This flag decides whether multi-turn works, which is more than the split it names.** The KV side +is not only concurrency: prefix caching holds a finished sequence's blocks so the next turn can +reuse them. When the pool cannot hold the *live sessions*, the cache drops prefixes the next turn +wanted and that turn re-prefills its whole context. At long contexts that is two orders of magnitude +of time-to-first-token, bought back for a fraction of a percent of the decode step. + +Measured on Qwen3.8-Flash-Next at a 200K context, two ~184K-token sessions, byte-identical text: + +| ratio | turn 1 | turn 2 | prefix hit | +|---|---|---|---| +| 0.87 | 207.4 s | 173.0 s | 0.0% | +| 0.82 | 227.7 s | **3.0 s** | 99.0% | + +Same model, same prompts. The only difference is whether the pool could hold both sessions. 57x on +the second turn, paid for with ~10% on the cold first turn and ~1.4% of the decode step — experts +lose 5% of the elastic pool and the MoE GEMM is residency-bound. + +The cliff is sharp and it is worth knowing where: at this shape 0.84 is **not** enough (49.7% hit, +one of the two sessions), and watching `kv_util` finds it — between 0.75 and 0.81 of the pool the +hit rate falls from 80.7% to 49.4%. + +To size it yourself: work out what a token of context costs across **all** paged groups for your +model (the startup log prints this), multiply by the context you actually serve, multiply by the +sessions you want live at once, and give the KV side at least that. + +Worked, on Qwen3.8-Flash-Next: two paged groups share one token axis — `kv_attn` at 26.00 KiB and +`kv_qsa_bkey` at 3.25 KiB per 4-token block — so a token of context costs **7.32 KiB**, and a +200K-token sequence is 1.43 GiB. A prefix-cached session occupies roughly 1.8x its context in pool +tokens, so two live 184K sessions want ~662K pool-tokens. That is the number the KV side has to +clear. + +What is claimed is not all of the card. The **activation arena** — scratch for the largest step +the engine may run — is taken off the budget *before* it is split, so it is paid for by both +sides. It grows with `--max-num-batched-tokens`, which is why raising the prefill chunk costs +resident experts (§4.5). + +**Most of the arena is lent back while the steps are small.** A decode step is a few dozen rows +of the 2048 a prefill chunk carries, so the engine asks the architecture plugin to declare its +activations again at smaller step sizes (the decode rows rounded up to a power of two and at least +256, then four times that, up to the step budget) and packs each into the bottom of the arena. While the recent steps fit a smaller size, the top of the arena holds expert +weights; the first step that needs more takes it back before it runs — a change of address for +the units there, not a copy. Startup prints what each size lends (`activation arena: lends ...`). +A plugin opts in (`RadArchProbe::shape_probe_ok`); one that does not keeps its whole arena. + +Related flags: + +```sh +--gpu-headroom-mib 96 # VRAM left unclaimed on every card +--kv-cache-dtype fp8 # halve what a token of context costs (a real quantisation) +--host-pool-mib 8192 # pinned host tier for weights +--weights-disk-tier # stream what fits neither from the container; needs O_DIRECT +``` + +**A model larger than the card and the host pool together still serves with +`--weights-disk-tier`** -- and every step is then paced by the drive, which is the trade the flag +names. A routed expert that fits neither VRAM nor the pinned pool lives in the container and +nowhere else; before each routed layer's first expert op, on every pass, the engine reads all of +that layer's on-disk experts into one of two VRAM buffers (a router's picks are not known on the +host, and a prefill chunk routes to nearly all of them anyway). The two buffers come out of the +weight budget -- the plan report's `file buffers` line -- and the reads go through four 32 MiB +pinned windows out of `--host-pool-mib` as long runs of the container, skipping resident experts. +What it is for: serving a checkpoint as it ships to calibrate or compare against, not a +production deployment. The bf16 Qwen3.8-Flash-Next (335 GiB) runs at two cards this way at about +28 s a step, and that step costs the same at one token as at 32K, so give it large prefill steps: + +```sh +rad-convert ~/models/Qwen/Qwen3.8-Flash-Next -o flashnext-bf16.rad --max-ctx 4096 # no recipe: bf16 +radiance --model flashnext-bf16.rad --tp 2 --placement expert_tiered --weights-disk-tier \ + --host-pool-mib 12288 --deterministic --gpu-headroom-mib 768 \ + --max-num-seqs 32 --max-num-batched-tokens 32768 --num-speculative-tokens 0 +``` + +A production server leaves the flag off, so a budget that does not fit is refused at startup +rather than served from the drive. + +**The KV pool is elastic on every run and there is no flag for it.** It holds the blocks it is +actually using plus a buffer it derives — one prefill chunk, or the largest shortfall the +admission path has met in the last few seconds, whichever is larger — and the expert plane grows +into whatever it releases. A pool that held every block it was carved for whether or not a token +was in it would, on a model whose experts do not fit, stream weight over the link for the whole +run to pay for cache nobody is using. + +What it leans on is `--gpu-headroom-mib`. That reserve is what the card keeps for allocations +this engine does not make — chief among them a kernel's code object, which HIP loads on the +kernel's *first launch*, not at startup. A deployment whose budget settles *below* its stated +headroom has already spent it, and the slab growing into what is left collides with the first +kernel that has never run: a draft head's, a sampler chain's, whatever the early requests did not +reach. It fails its load and faults inside the HIP runtime, which arrives as a segfault in a +kernel that is correct, on a server that had been serving fine. + +Startup measures that shortfall and holds it back on top of the reserve, so a run that did not +quite keep its headroom is safe rather than fatal — but it is costing you the VRAM twice. Raise +`--gpu-headroom-mib` past the number startup names, so the budget resolver sees it and the expert +plane is sized against it instead of trimmed afterwards. + +### 4.4 Long context + +```sh +radiance --model m.rad --max-model-len 200000 --kv-cache-dtype fp8 \ + --expert-vs-cache-ratio 0.82 --max-num-seqs 8 +``` + +`--max-model-len` does not reserve anything per request — it sets the worst case the pool is sized +against. `0` takes the model's training context. + +`--kv-cache-dtype fp8` is an E4M3 cache with per-(sequence, head) descales. It halves what a token +of context costs, which at a production context is most of the pool. It is a real quantisation and +the model computes a slightly different function with it, so it is stated rather than inferred. +Every architecture serves both widths, and the flag sets every attention cache of the deployment — +a drafter's (DSpark, DFlash2) as well as the trunk's. The delta-net state and the QSA indexer's +key tail are recurrent state rather than an attention cache and keep their own widths. + +### 4.5 Prefill speed: the chunk + +A long prompt is prefilled in chunks, and `--max-num-batched-tokens` is how big one is. It is the +single biggest lever on time-to-first-token on a mixture-of-experts model, because a chunk sweeps +the whole expert plane once however many tokens are in it — so four times the chunk is a quarter +of the sweeps. + +```sh +radiance --model m.rad --max-num-batched-tokens 2048 +``` + +On a 48-layer MoE at 200K context on two cards, prompts of 8K and 24K tokens: + +| chunk asked for | 512 | 1024 | **2048** | 4096 | +|---|---|---|---|---| +| chunk actually run | 512 | 1024 | **2048** | 2048 | +| prefill | 1750 tok/s | 2200 | **2706** | 2620 | + +At full context the same change is the difference between waiting and waiting a lot: a +185,253-token prompt prefills in **91 s at a 2048 chunk against 138 s at 512**. + +**The 4096 column is the trap, and the engine warns about it.** On a hybrid model the chunk is +clamped to `--checkpoint-interval` (2048 by default) *before* the token budget, so asking for 4096 +runs 2048 chunks and pays for 4096 anyway: the activation arena grows with the budget and is +charged to the VRAM budget *before* it is split between weights and KV, so the expert plane loses +residency for a chunk it never got. Startup prints which of the two bound it: + +``` +chunk geometry: quantum 64 (attn block ..., state chunk ...), checkpoint interval 2048, +max_tok 4096 -> prefill chunks of at most 2048 (the checkpoint interval, not the budget) +``` + +Read that line, and `RADIANCE_LOG_STEPS=1` prints the token count of every step if you want to see +it per step. + +Raising both — `--max-num-batched-tokens 4096 --checkpoint-interval 4096`, which does run 4096 +chunks — does not help either: 2610 tok/s against 2748, because the arena takes +another 239 resident experts (9219 to 8980) and the extra amortisation does not pay for them. On +a model whose prefill is bound by the link carrying non-resident experts, the chunk stops winning +as soon as it starts costing residency. + +**It does not cost the requests already running.** A longer chunk holds the device longer per +step, so a decode step queued behind one waits longer — but the prefill it is queued behind +finishes sooner, and that is the larger term. Four decoders with a long prompt landing beside +them finished in 29.5 s at a 2048 chunk against 31.9 s at 512. + +**And check it did not cost you the prefix cache.** The arena it grows is charged before the +split (§4.3), so the KV pool shrinks a little — here 516,864 → 499,920 pool tokens, 3.3% — and +§4.3's cliff is sharp enough that 3% is worth confirming rather than assuming. On this shape it +costs nothing: two ~180K sessions, first turns back to back, then the first session's second turn. + +| chunk | session A turn 1 | session B turn 1 | A turn 2 | cached | evictions | +|---|---|---|---|---|---| +| 512 | 137.7 s | 130.0 s | 1.42 s | 178,176 of 179,585 | 0 | +| 2048 | **90.6 s** | **93.2 s** | **0.97 s** | 178,176 of 179,585 | 0 | + +Identical hit, no evictions, `kv_util` 0.70 → 0.73. Turn one is 34% faster and turn two stays +where it was. Do this on your own shape before you keep the change: `prefix_hit_rate` and +`prefix_evictions` on `/stats` are the two numbers, and the failure looks like turn two taking +as long as turn one. + +**What it does cost is decode, and it is small.** The 239 resident experts the arena takes have to +come from somewhere, and steady-state decode is where. Decode step time from `scripts/cstep2.sh`, +which divides by the decode step counter rather than by wall clock, two passes each, generations +long enough that no sequence retires inside the window: + +| chunk | one stream | eight streams | +|---|---|---| +| 512 | 22.35 / 22.29 ms/step | 39.52 / 40.52 ms/step | +| 2048 | 22.42 / 22.48 ms/step | 39.52 / 40.73 ms/step | + +**+0.6% on a single-stream decode step**; at eight streams the difference is 0.11 ms, below what +the harness resolves. Against a prefill that is 55% faster and a first turn that goes from 138 s +to 91 s, that is the right side of the trade — but it is a real cost and it lands on every turn, +so measure it on your own shape rather than taking the sign on faith. + +**Changing it changes the text.** A different chunk is a different batch shape, so the sums inside +a prefill run in a different order, and at a tie that is a different token. A fixed prompt at a +fixed seed gives one answer at 512 and a different one at 2048, and each is byte-identical across +runs and server restarts at its own setting. Reproducibility holds *at a configuration*, which is what it claims; this flag is part of the +configuration in the same way `--tp` and `--num-speculative-tokens` are. Pin it before you record +anything you intend to compare against later. + + +### 4.6 Speculative decoding + +If the container carries a draft head, it is used by default at the depth the plugin states: + +```sh +radiance --model m.rad # auto: the drafter's own operating point +radiance --model m.rad --num-speculative-tokens 0 # off +radiance --model m.rad --num-speculative-tokens 3 # a stated depth +``` + +There is **no `--draft-model`**. This engine loads its drafter from the container — merge one at +conversion time with `rad-convert --draft-model DIR`, or use an MTP head that already ships inside +the target checkpoint, which needs no flag at all. Passing `--draft-model` to the engine is an +error that says so rather than being quietly ignored. + +When you measure speculation, **measure step time, not tokens per second.** + +### 4.7 Two cards + +```sh +radiance --model m.rad --tp 2 +radiance --model m.rad --tp 2 --tp-wire wht6 --tp-wire-min-kb 128 +``` + +`--tp-wire` chooses the cross-rank all-reduce payload. `exact` (default) is the bf16 all-reduce. +`wht6` accepts a lossy wire: a Walsh-Hadamard-rotated 6-bit payload, 2.4× smaller over PCIe. The +sum a rank receives is then not the sum it would have received and nothing downstream can tell, +which is why it is a named flag and not a heuristic. + +`--tp-wire-min-kb` is the floor below which messages are still served exactly — 128 KiB leaves +single-sequence decode exact and compresses prefill, which is where the win is. + +On a model with a gated residual (Qwen3.8-Flash-Next) the all-reduce rides inside the residual's +write, with the MoE gather in front of it, on either wire: the rotated forms of `ar_hc_write` and +`ar_gather_hc_write` produce the same bytes as the unfused chain on the same wire. There `wht6` is +worth +5.6–6.3% of prefill at a 2048-token chunk (20K prompt 5556 → 5908 tok/s; a 23K extension at +81K depth 4998 → 5278) and −1.3% of the eight-stream decode step; one-stream decode stays exact. + +### 4.8 Finished conversations: copied to host, VRAM given up on demand + +By default a finished conversation's KV blocks stay in VRAM, held by the prefix cache, until the +cache evicts them under pressure — and an evicted prefix is re-prefilled from scratch next turn. + +With a host tier, a conversation is **copied** to host memory the moment its request finishes, and +keeps its VRAM copy. From then on it is *clean*: its VRAM can be given up for nothing, and it is, +as soon as something wants it — the expert slab's loan, or a request the pool cannot otherwise +serve. A conversation that comes back before that resumes from VRAM; one that comes back after is +restored from host memory and keeps its host copy, so its next turn copies only what that turn +added. There is no idle threshold on the way out of VRAM. + +With a disk tier the same happens one level down: every host copy is written on to disk in the +background and keeps its host slot, and once the write has landed the slot can be given up for +nothing. A full host tier gives up its oldest slots when a new copy or a restore needs one, so a +conversation that no longer fits in host memory is on disk already rather than lost. + +```sh +radiance --model m.rad \ + --prefix-cache-host-mib 8192 \ + --prefix-cache-disk-mib 65536 --prefix-cache-dir /var/cache/radiance +``` + +- `--prefix-cache-host-mib N` — **this is the switch.** Without a size, nothing is copied. Part of + it goes to linear-state snapshots on a hybrid model; startup says how many. Size it for the + conversations you expect to come back: one that does not fit comes back from disk instead. +- `--prefix-cache-disk-mib N` — the disk tier's size. Everything that reaches host memory is + written here too, so it sees the same bytes the host tier does. +- `--prefix-cache-dir DIR` — where the disk tier lives. **Not `--weights-disk-tier`**, which is about + *weights*. The disk tier holds conversation content unencrypted. +- Recovering a 200K-token turn costs a copy over PCIe; recomputing it costs minutes. + +On a hybrid model this includes the recurrent state, not just the attention blocks — restoring the +blocks alone leaves the session re-running every linear layer over its whole transcript, which +every hit-rate counter reports as a hit. `/sessions` shows what is stored, where, and whether the +linear half is being served. + +### 4.9 What a request that sets no sampler fields gets + +Resolution order, first one that exists wins: + +1. `--temp` / `--top-k` / `--top-p` / `--min-p` on the command line +2. `--generation-config PATH` — a `generation_config.json` +3. the container's own `generation.*` metadata +4. `.generation.json` beside the container +5. the built-in defaults + +```sh +radiance --model m.rad --temp 0.7 --top-p 0.8 --top-k 20 +``` + +**`--reasoning-effort` is worth knowing about.** It is the default for chat requests that do not +set one, and the value goes to the model's chat template verbatim — so the legal set is the +template's. Qwen3.8 takes `xhigh|medium|low` and **defaults to `xhigh`**, which on a short task can +spend the entire token budget inside `` and return a turn with empty content and +`finish_reason: "length"`. `"none"` turns thinking off. + +```sh +radiance --model m.rad --reasoning-effort medium +``` + +### 4.10 Every flag + +`radiance --help` prints this table. Grouped here by what you are doing: + +**Model and plugins** + +| flag | | +|---|---| +| `--model PATH` | the `.rad` container, or a checkpoint served as it stands (§3.4) (**required**) | +| `--radiance-home DIR` | where `kernels/` and `architectures/` live | +| `--kernels LIST` | kernel plugin hierarchy, comma-separated, first wins | + +**Batch shape** + +| flag | default | | +|---|---|---| +| `--max-num-batched-tokens N` | 8192 | largest token count one step may carry | +| `--max-num-seqs N` | 256 | largest number of sequences one step may carry | +| `--max-model-len N` | 0 | context bound; 0 takes the model's training context | + +**Memory** + +| flag | default | | +|---|---|---| +| `--gpu-headroom-mib N` | 96 | VRAM left unclaimed on every card | +| `--expert-vs-cache-ratio R` | 0.75 | weights share of what is claimed | +| `--vram-weights-mib N` | derive | the resident weight slab | +| `--vram-kv-mib N` | derive | the paged KV pool | +| `--kv-cache-dtype T` | bf16 | `bf16` or `fp8` | +| `--host-pool-mib N` | 0 | pinned host tier (weights) | +| `--weights-disk-tier` | off | read weights that fit neither VRAM nor the host pool from the container (O_DIRECT); routed experts a layer at a time | + +**Idle session tiers** + +| flag | default | | +|---|---|---| +| `--prefix-cache-host-mib N` | 0 (off) | copy finished conversations' KV to host memory | +| `--prefix-cache-disk-mib N` | 0 (off) | and copy them on to disk | +| `--prefix-cache-dir DIR` | — | where the disk tier keeps them | + +**Placement and state** + +| flag | default | | +|---|---|---| +| `--placement MODE` | auto | `all_vram`, `layer_offload`, `expert_tiered`, `auto` | +| `--deterministic` | off | pin placement to the loader's plan, so the resident set cannot change under the heat engine | +| `--checkpoint-interval N` | 2048 | linear-attention state checkpoint interval, in tokens | +| `--checkpoint-slots N` | 8 | linear-state snapshots the server may hold at once, **in total**, not per sequence. A cap, not a charge: slots are backed as they are taken, so unused ones cost no VRAM. Raising it trades addressable context, since the range comes out of the KV pool | +| `--checkpoint-policy NAME` | geometric-backoff | also `tip-only`, `keep-all` | +| `--no-prefix-cache` | — | disable prefix caching | + +**Parallel** + +| flag | default | | +|---|---|---| +| `--tp N` | 1 | tensor-parallel ranks | +| `--tp-wire MODE` | exact | `exact` or `wht6` | +| `--tp-wire-min-kb N` | 128 | smallest all-reduce the `wht6` wire is used for | + +**Speculation** + +| flag | default | | +|---|---|---| +| `--num-speculative-tokens N` | auto | speculative window; 0 disables | +| `--draft-model PATH` | — | **not implemented** — merge at convert time | + +**Server** + +| flag | default | | +|---|---|---| +| `--host ADDR` | 0.0.0.0 | listen address | +| `--port N` | 8000 | listen port | +| `--api-key KEY` | — | require `Authorization: Bearer KEY` on every request but `/health`, `/ping` and the dashboard page (§6.6) | +| `--mm-max-patches N` | auto | patches one vision-encoder pass carries, and so the largest image (a patch is 16x16 pixels). `auto` is 16384 when the container carries a vision tower; 0 serves text only and keeps the tower off the card | +| `--generation-config PATH` | — | sampler defaults from a `generation_config.json` | +| `--temp F`, `--top-k N`, `--top-p F`, `--min-p F` | from container | sampler defaults | +| `--reasoning-effort S` | template's own | default `reasoning_effort` for chat | + +**Quality measurement** — instead of serving; see [TOOLS.md](TOOLS.md#the-kl-mode) + +| flag | | +|---|---| +| `--kld-record DIR` | run `--kld-corpus` through prefill and write this model's log-probabilities at every scored position to `DIR`: the reference a quantised model is measured against | +| `--kld-ref DIR` | score this model against the reference in `DIR`: mean, median, 99/99.9/99.99th percentile KL divergence and top-1 agreement | +| `--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` | + +**Diagnostics** + +| flag | | +|---|---| +| `--debug-graph` | print the declared graph and exit | +| `--debug-selection` | print the selection table | +| `--debug-placement` | print the placement plan | +| `--debug-accept-reference-kernels` | serve even when ops resolve to `libref`. **Not a production configuration** | +| `--profile-ops` | per-op device timing | +| `--live` | the live terminal view | +| `-v` / `-vv` | verbose / very verbose | + +--- + +## 5. Talk to it + +### 5.1 The endpoints + +| | | +|---|---| +| `POST /v1/chat/completions` | chat, with tools, reasoning and streaming | +| `POST /v1/completions` | raw text completion | +| `POST /v1/embeddings` | needs a model with an embedding head, else 501 | +| `GET /v1/models`, `/v1/models/:id` | what is loaded | +| `GET /health`, `/ping`, `POST /ping` | liveness | +| `GET /load` | current load | +| `GET /version` | server version | +| `GET /server_info` | the whole configuration of the running engine | +| `GET /metrics` | Prometheus | +| `POST /tokenize`, `POST /detokenize` | | +| `GET /get_tokenizer_info` | | +| `POST /reset_prefix_cache` | drop every cached prefix | +| `GET /` or `/dashboard` | the web dashboard | +| `GET /stats`, `/graph`, `/sessions` | the JSON the dashboard is drawn from | + +Method spellings follow vLLM's, including the ones that look odd: `/tokenize` is POST because its +input is a body, and `/ping` answers both GET and POST because different load balancers send +different ones. + +### 5.2 Chat + +```sh +curl -s http://localhost:8000/v1/chat/completions \ + -H 'Content-Type: application/json' \ + -d '{ + "model": "m", + "messages": [{"role": "user", "content": "Explain merge sort briefly."}], + "max_tokens": 200, + "temperature": 0.7 + }' | jq -r '.choices[0].message.content' +``` + +If the container carries no chat template this endpoint answers **501** and the startup log says +so — use `/v1/completions` instead. + +**Turning thinking off.** Three spellings reach the server for one question; all work: + +```json +{"chat_template_kwargs": {"enable_thinking": false}} +{"enable_thinking": false} +{"reasoning_effort": "none"} +``` + +Reasoning text comes back in `choices[].message.reasoning_content`, separate from `content`. + +### 5.3 Streaming + +```sh +curl -N http://localhost:8000/v1/chat/completions \ + -H 'Content-Type: application/json' \ + -d '{"model":"m","messages":[{"role":"user","content":"Count to ten."}], + "max_tokens":100,"stream":true, + "stream_options":{"include_usage":true}}' +``` + +Server-sent events, OpenAI's delta format, terminated by `data: [DONE]`. + +### 5.4 Tool calls + +```sh +curl -s http://localhost:8000/v1/chat/completions \ + -H 'Content-Type: application/json' \ + -d '{ + "model": "m", + "messages": [{"role":"user","content":"What is in /etc/hosts?"}], + "tools": [{ + "type": "function", + "function": { + "name": "read", + "description": "read a file", + "parameters": {"type":"object", + "properties":{"path":{"type":"string"}}, + "required":["path"]} + } + }], + "tool_choice": "auto", + "max_tokens": 300 + }' | jq '.choices[0].message.tool_calls' +``` + +Calls come back in `message.tool_calls` with `finish_reason: "tool_calls"`. No `` or +`` markup ever reaches `content`. `scripts/mctools.sh` and `scripts/mcstream.sh` assert +exactly that, including on raw streamed fragments — content cannot be retracted once sent, so a +repair applied at the end is not a fix. + +### 5.5 Constrained output + +```sh +# JSON object +-d '{"model":"m","messages":[...],"response_format":{"type":"json_object"}}' + +# a JSON schema +-d '{"model":"m","messages":[...], + "response_format":{"type":"json_schema", + "json_schema":{"schema":{"type":"object", + "properties":{"city":{"type":"string"},"pop":{"type":"integer"}}, + "required":["city","pop"]}}}}' + +# a GBNF grammar directly (cannot be combined with response_format) +-d '{"model":"m","prompt":"...","grammar":"root ::= \"yes\" | \"no\""}' +``` + +**On chat, a constraint passes through the chat template and may not survive it.** The template +gets to rewrite or drop `grammar` and `response_format` — a tool-calling template produces its own +grammar, for instance — so whether a constraint can be enforced is a property of the model's +template and not only of the server. When the one you asked for is not there at the end, the +request is **refused**: + +``` +grammar: this model's chat template produced no grammar for it, so the constraint could not +be enforced +``` + +That is the refused-not-ignored rule (§5.8) doing its job: an unconstrained 200 would leave you +parsing free prose against a schema you were told was enforced. `/v1/completions` has no template +in the way, so the same grammar works there — which is why the example above uses it. + +### 5.6 Completions, embeddings, tokenising + +```sh +curl -s http://localhost:8000/v1/completions -H 'Content-Type: application/json' \ + -d '{"model":"m","prompt":"def fib(n):","max_tokens":128,"temperature":0}' + +curl -s http://localhost:8000/v1/embeddings -H 'Content-Type: application/json' \ + -d '{"model":"m","input":"hello"}' + +curl -s http://localhost:8000/tokenize -H 'Content-Type: application/json' \ + -d '{"prompt":"hello world","return_token_strs":true}' + +curl -s http://localhost:8000/tokenize -H 'Content-Type: application/json' \ + -d '{"messages":[{"role":"user","content":"hi"}]}' # applies the chat template + +curl -s http://localhost:8000/detokenize -H 'Content-Type: application/json' \ + -d '{"tokens":[15339,1917]}' +``` + +`/tokenize` takes `prompt` **or** `messages`, not both. + +### 5.7 Request fields + +| field | notes | +|---|---| +| `model` | accepted and not enforced — one server serves one model | +| `messages` / `prompt` / `input` | chat / completion / embedding | +| `max_tokens`, `max_completion_tokens` | default 512. Clamped to what the context leaves rather than refused — see §5.8 | +| `temperature` | [0, 2] | +| `top_p` | (0, 1] | +| `top_k` | ≥ 0, 0 disables | +| `min_p`, `typical_p` | | +| `presence_penalty`, `frequency_penalty` | [-2, 2] | +| `repetition_penalty`, `repeat_last_n` | | +| `xtc_probability`, `xtc_threshold` | | +| `dry_multiplier`, `dry_base`, `dry_allowed_length`, `dry_penalty_last_n`, `dry_sequence_breakers` | | +| `seed` | absent means "pick one" — **not** seed 0 | +| `n` | 1–8. Fan-out over the same prompt; the prefix cache makes it nearly free after the first | +| `priority` | | +| `stop` | a string or an array | +| `ignore_eos` | generate to `max_tokens` whatever the model emits | +| `stream`, `stream_options.include_usage` | | +| `logprobs`, `top_logprobs` | **not implemented** — refused, not returned as nulls. `/server_info` reports `logprobs: false` | +| `tools`, `tool_choice`, `parallel_tool_calls` | chat only | +| `add_generation_prompt`, `chat_template_kwargs` | chat only | +| `reasoning_effort`, `enable_thinking` | chat only | +| `response_format` | chat only. Mutually exclusive with `grammar` | +| `grammar` | a GBNF grammar directly. On chat it passes through the chat template and a template that drops it makes the request a refusal — see §5.5 | +| `echo` | `/v1/completions` only | +| `encoding_format` | `/v1/embeddings` only: `float` or `base64`. `dimensions` is refused — the embedding width is fixed | + +Any field the request omits keeps the deployment default (§4.9). A field the request names wins. + +### 5.8 A parameter this server does not implement is **refused**, not ignored + +This is the one place radiance deliberately differs from what an OpenAI client may expect, and it +will be the first thing you hit pointing an existing client at it: + +```json +{"error": {"message": "mirostat: mirostat is not one of the device samplers (spec 13)", ...}} +``` + +The rule is that **a request that returns 200 means every field of it was honoured**. Silently +dropping a sampler setting and answering 200 is how a deployment ends up serving a model at +settings nobody chose. + +Three lists decide it: + +- **Accepted** — the table above. +- **Inert** — OpenAI metadata that genuinely does nothing anywhere, accepted and ignored so the + official SDKs work: `user`, `metadata`, `store`, `service_tier`, `safety_identifier`, + `prompt_cache_key`. +- **Refused with a reason** — known, not implemented, each named: + +| refused | because | +|---|---| +| `logit_bias` | the device sampler has no per-token bias stage | +| `functions`, `function_call` | deprecated — send `tools` / `tool_choice` | +| `best_of` | sampling n candidates and returning the best is not implemented | +| `suffix` | infilling is not implemented | +| `mirostat`, `mirostat_tau`, `mirostat_eta` | not one of the device samplers | +| `top_n_sigma`, `dynatemp_range`, `dynatemp_exponent` | not one of the device samplers | +| `lora` | explicitly out of scope | +| `modalities`, `audio`, `prediction` | not implemented | +| `continue_final_message` | assistant prefill is not implemented | +| `cache_prompt` | prefix caching is a server-wide setting, not per request | + +Anything else unrecognised is refused too, naming the key. + +**The one exception is `max_tokens`.** If `prompt + max_tokens` would exceed the context, the +server clamps `max_tokens` to what is left and serves the request: + +``` +prompt 72,170 + max_tokens 128,000 > 200,000 context + -> served with max_tokens 127,830 +``` + +It is an exception because the other keys are *settings* — dropping one serves a different model +than the caller asked for — and this one is a *bound*, whose whole purpose is to stop generation +early and which the context was going to stop earlier anyway. Refusing would not produce more +tokens than clamping does; it would produce none. The completion ends with `finish_reason: +"length"` and `usage` reports what it actually got, so the caller can still see what happened, and +`-v` logs the adjustment. + +A prompt that does not fit **on its own** is still a 400 — there is no window to generate into, so +no `max_tokens` would have made it servable — and the error names how many tokens have to go: + +``` +prompt: 220470 prompt tokens does not fit the 200000 token context, which leaves nothing to +generate into; shorten the prompt by at least 20471 tokens +``` + +At the boundary, where an off-by-one would hide: a 198,729-token prompt asking for `max_tokens` +128,000 against a 200,000 context is served, generates **1,271** tokens — exactly the room left — +and ends `finish_reason: "length"`. `POST /tokenize` is how to size a prompt that +precisely without running the model. + +--- + +## 6. Operate it + +### 6.1 The dashboard + +Open `http://:/` in a browser. Three tabs: + +**Dashboard** — the live strip across the top (decode step time, decode and prefill throughput, +requests in flight, KV cache in VRAM, draft acceptance), then cards for the batch, memory and +interconnect, and the expert plane. + +The **KV cache** meter splits what it is holding into two segments: + +``` +KV cache 3.3 GiB / 4.5 GiB · 390.1k tok · 75.5% +▓▓░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ +20.8k tok in flight · 369.3k held for the next turn +``` + +The full-strength segment is live requests; the ghost segment is **prefix cache** — finished turns +kept so the next turn need not re-prefill. Held is not a second pool: it gives way the moment a +live request needs it. A high held figure with a high hit rate is the cache doing its job, not a +leak. Both segments take their warning colour from the *total* fill, since what causes preemption +is the pool being full. + +**Sessions** — one row per stored conversation: how many tokens, which tier it is in, and whether +its linear half is still reachable. Sizes **overlap and cannot be added up**: two sessions sharing +a system prompt share the blocks for it, which is the whole point of a prefix cache. + +On a hybrid model, a session with blocks but no reachable snapshot reuses **zero** tokens — the +scheduler clamps reuse to the last linear checkpoint. That verdict is the headline of the tab. + +**Model** — the resolved graph: every op, which library serves it, and what did not resolve. + +### 6.2 The JSON behind it + +```sh +curl -s localhost:8000/stats | jq # counters, memory, throughput +curl -s localhost:8000/sessions | jq # what is stored and where +curl -s localhost:8000/graph | jq # the resolved kernel graph +curl -s localhost:8000/server_info | jq # model, cards, KV, draft depth, wire +``` + +`/server_info` is the operator's first question asked of a process that is already running: which +model, on how many cards, with how much KV, drafting how deeply, over which wire. All of it is in +the startup log too — but a startup log is on a machine, in a file, from a process that may have +been restarted since. + +### 6.3 Metrics + +`GET /metrics` is Prometheus text. Two families: + +**`vllm:` — the compatibility set**, so existing dashboards work: `num_requests_running`, +`num_requests_waiting`, `num_preemptions_total`, `gpu_cache_usage_perc`, `kv_cache_usage_perc`, +`gpu_prefix_cache_hit_rate`, `prompt_tokens_total`, `generation_tokens_total`, +`time_to_first_token_seconds`, `time_per_output_token_seconds`, `inter_token_latency_seconds`, +`request_prompt_tokens`, `request_generation_tokens`, `request_success_total`, … + +**`radiance:` — what this engine actually has**: + +| | | +|---|---| +| `engine_steps_total`, `_decode_total`, `_prefill_total`, `_mixed_total` | step counts by kind | +| `engine_step_seconds_total`, `_decode_total` | **the honest step time denominator** | +| `decode_tokens_total`, `prefill_tokens_total` | | +| `decode_tokens_per_second`, `prefill_tokens_per_second` | | +| `draft_tokens_total`, `draft_accepted_total`, `draft_acceptance_ratio` | | +| `draft_position_reached_total`, `draft_position_acceptance_ratio` | acceptance by position in the window | +| `decode_rows_unspeculated_total` | rows that never drafted at all | +| `attn_cached_tokens_total`, `linear_cached_tokens_total` | prefix reuse, both halves | +| `linear_checkpoints_written_total`, `linear_prefix_cache_hit_rate` | | +| `prefix_cache_evictions_total`, `prefix_cache_ckpt_evictions_total` | | +| `num_requests_preempted` | | +| `http_queue_depth`, `http_responses_total`, `http_admission_rejected_total` | | +| `client_disconnect_total`, `stream_overflow_total` | | + +Two traps worth naming: + +- **`draft_acceptance_ratio` is conditional on having drafted.** It reads healthy while + tokens-per-step collapses. The quantity that separates the two is blocks per step — + `draft_tokens_total / depth` over `engine_steps_decode_total`. `scripts/mcdecl.sh` measures it. +- **Step time is not wall-clock over steps.** Use `engine_step_seconds_decode_total / + engine_steps_decode_total`, which charges only decode. Wall-clock charges idle and prefill to it. + +### 6.4 The live terminal view + +```sh +radiance --model m.rad --live +``` + +Cards, throughput, draft acceptance and the expert plane, redrawn in place. **Redirected it prints +one greppable `key=value` line instead**, so it is usable from a script: + +```sh +radiance --model m.rad --live >> serve.log 2>&1 +``` + +The step counter is the field that tells a stalled loop from an idle one: throughput decays toward +zero on its own, but a step count frozen between two draws means the loop itself stopped. + +### 6.5 Logging + +```sh +RADIANCE_LOG=debug radiance --model m.rad # error|warn|info|debug|trace +radiance --model m.rad -v # same as debug +radiance --model m.rad -vv # same as trace +``` + +### 6.6 Security + +**There is no TLS, and without `--api-key` there is no authentication.** CORS is on. + +```sh +radiance --model m.rad --api-key "$KEY" +``` + +With a key, every request must carry `Authorization: Bearer KEY` or it is answered 401 — +`/tokenize` and `/server_info` included, since they hand out the vocabulary, the chat template and +the configuration. Three paths are exempt: `/health` and `/ping`, because a load balancer cannot +carry a bearer token and an authenticated probe is a server that reports itself down, and the +dashboard page itself (`/`, `/dashboard`), which holds no data — on a 401 it shows a key field, +keeps the key in the browser's storage and sends it on every fetch of data it makes. + +The key is checked, not encrypted: on any network you do not control, bind to localhost and put a +TLS-terminating reverse proxy in front: + +```sh +radiance --model m.rad --host 127.0.0.1 --port 8000 --api-key "$KEY" +``` + +Also note `--prefix-cache-disk-mib` writes **conversation content unencrypted** under `--prefix-cache-dir`. + +### 6.7 Restarting and stopping + +Nothing here is a daemon; run it under systemd, a supervisor or `nohup`. `scripts/fnstop.sh` stops +a running server and waits for the process to actually go — which matters, because VRAM is not +released until it does. + +--- + +## 7. When something goes wrong + +| What you see | What it means | What to do | +|---|---|---| +| `N declared op(s) resolve to libref` and the engine exits | No kernel library covers those ops on this card. Serving from the reference implementation would be orders of magnitude slow with nothing to say so | Install a library that covers them, or accept the cost with `--debug-accept-reference-kernels`. The named ops are exactly what a new library must implement | +| `did not fit` at load, naming a weight class or a KV group | The split left one side too little. A routed expert cannot be served from the file tier, so it has nowhere else to go | If **weights** did not fit: **raise** `--expert-vs-cache-ratio`, lower `--max-model-len` or `--max-num-seqs`, or add `--host-pool-mib`. If a **KV group** did not fit: lower the ratio, or `--kv-cache-dtype fp8`. The plan report names which, by class, with the shortfall | +| `chat is 501` in the startup line | The container carries no chat template | Re-convert with `--tokenizer`, and check that a `chat_template.jinja` sits beside `tokenizer_config.json` in the checkpoint. Meanwhile use `/v1/completions` | +| `does not read '' encoded ` at startup | No loaded kernel takes that weight's encoding for the op that reads it | Convert with a recipe that writes an encoding a loaded kernel reads, or load the library that reads it | +| Prefix hit rate 0% and every turn re-prefills | The KV pool cannot hold the live sessions, so the cache evicts what the next turn wanted | Lower `--expert-vs-cache-ratio` (more to KV), or `--kv-cache-dtype fp8`, or fewer/shorter sessions. See §4.3 | +| The server dies with no log line, on a request it had been serving fine | A kernel whose code object had never been loaded could not be: the card has no room left. HIP faults inside the launch rather than returning an error, so there is nothing to print | A card that never met `--gpu-headroom-mib` — see §4.3. Raise the headroom past the shortfall startup names. `coredumpctl info` names the kernel; `AMD_LOG_LEVEL=1` prints `HSA_STATUS_ERROR_OUT_OF_RESOURCES` just above the fault | +| KV in VRAM stays high with one session and nothing moves | The idle tiers are **off** — they are sized, and with no size nothing is copied | Pass `--prefix-cache-host-mib N` | +| `out of memory` / `the carve reserved N of address space and the card would not back it` | Something else is holding VRAM | Check with `rocm-smi`; stop the other process. The budget is stated before allocation, so the log says what it asked for | +| `--draft-model is not implemented` | This engine loads its drafter from the container | `rad-convert --draft-model DIR` at conversion time | +| `context_length_exceeded` on a request | The **prompt alone** does not fit the context. `max_tokens` is clamped rather than refused, so this fires only when there is no room left to generate at all | Shorten the prompt by the number of tokens the message names, or raise `--max-model-len` if the model allows it | +| `unknown option '--foo'` and the engine exits | Deliberate. A typo in a budget flag is the difference between the plan you asked for and one the planner invented | Check `radiance --help` | +| Empty `content` and `finish_reason: "length"` on short chat turns | The template's default `reasoning_effort` spent the budget inside `` | `--reasoning-effort medium`, or `"reasoning_effort": "none"` per request | +| `401` with `invalid api key` | The server was started with `--api-key` | Send `Authorization: Bearer KEY` (§6.6) | + +First three things to run when a server will not start: + +```sh +rad-info m.rad # is the container what you think it is? +radiance --model m.rad --debug-graph # does every op resolve? +rad-kbench --home $RADIANCE_HOME --max-cases 1 # are the kernels correct at all? +``` + +--- + +## 8. Environment + +**Operator-facing** + +| | | +|---|---| +| `RADIANCE_HOME` | where `kernels/`, `architectures/` and `quantizers/` live; a `:`-separated search path, the first home winning. Same as `--radiance-home` | +| `RADIANCE_KERNELS` | default kernel hierarchy, comma-separated. Same as `--kernels`, read by the engine *and* every tool, so a plugin validated with `rad-kbench` can be served without editing launchers | +| `RADIANCE_LOG` | `error` \| `warn` \| `info` \| `debug` \| `trace` | +| `ROCM_PATH` | where ROCm lives, if not `/opt/rocm` | +| `HF_TOKEN` | for `scripts/hfget.sh` on a gated repo | + +**Tooling** + +| | | +|---|---| +| `RADIANCE_TUNE` | pin a kernel's tunable axes instead of reading the tune cache — `op:key=value[,key=value][;op:...]`. For comparing tunings, not for deployment | +| `RADIANCE_CALIB_DIR` | where an engine run writes calibration data for a recipe's `gptq calib=DIR` | +| `RADIANCE_CALIB_TOKENS` | with `RADIANCE_CALIB_DIR`, the tokens the calibration tap accumulates before it writes and switches itself off (default 65536) | +| `RADIANCE_PROFILE_EVERY` | with `--profile-ops`, dump the per-op table every N steps (default 32) | +| `RADIANCE_LOG_STEPS` | log one line per step: its phase, sequences, and each one's token count and context (§4.5) | + +There is also a family of instruments for engine development — `RADIANCE_DEBUG_*` (residual probes, +idle scrubs, routing and issue dumps), `RADIANCE_OP_ORACLE*` (named ops checked against `libref` on +the operands the model issued; `scripts/oracle.sh` drives it) and `RADIANCE_OP_REPEAT` (named ops +run a second time on the same inputs, to ask whether a kernel is a function of them). They are +instruments, not features; grep `getenv` if you need one, and read the comment beside it first. + +--- + +## 9. Further reading + +| | | +|---|---| +| `spec.md` | the design, and it is binding. Start here for *why* | +| [TOOLS.md](TOOLS.md) | every flag of every tool, and the shell harnesses | +| [PLUGIN.md](PLUGIN.md) | writing a kernel plugin: exports, constraints, hooks, out-of-tree build | +| [OPS.md](OPS.md) | the conventional op vocabulary. Held to the registries by `ctest -R ops_doc` | +| [ARCHITECTURES.md](ARCHITECTURES.md) | per-architecture geometry, and the traps that stay plausible when they are wrong | +| [IMPLEMENTATION.md](IMPLEMENTATION.md) | layout, build and conventions for working on the engine | +| [KERNELS.md](KERNELS.md) | what `rad-kbench` last measured | +| [QSA.md](QSA.md), [MOE-W4.md](MOE-W4.md) | the sparse-attention indexer; the four-bit expert format | diff --git a/docs/IMPLEMENTATION.md b/docs/IMPLEMENTATION.md new file mode 100644 index 00000000..6c7b4cf0 --- /dev/null +++ b/docs/IMPLEMENTATION.md @@ -0,0 +1,107 @@ +# Radiance — implementation brief + +Read `spec.md` first; it is the design and it is binding. This file is the mechanical part: who +owns what, how it builds, and the conventions that keep ten people's code looking like one +person's. + +## The host backend is the primary target, not a fallback + +Everything except the device kernels builds, tests and runs through the **host device backend**: +`cmake` with no ROCm must configure, build, test and run, and `RAD_HIP_FOUND` gates only the HIP +backend and the device kernels. A machine with no card is a complete development environment for +the core, the tools, the architecture plugins and `libref`, and the suite runs in full there. + +## Layout and ownership + +``` +abi/ THE ABI, and all a plugin compiles against. Frozen — do not edit quietly +core/rad_internal.h shared internals: logging, Geometry, constraint matching +core/util/ logging, error strings, dtype arithmetic, tensor helpers: the bedrock +core/device/ device backends: host, and aql (HSA queues the engine writes; HIP for memory) +core/plugin/ plugin loader, kernel registry, op schemas, selector, bucket tables +core/build/ the declare phase: builder, weight manifest, buffer plan, graph dump +core/runtime/ the run phase: RadCtx, rad_issue, the arena +core/mem/ pools, slab, KV block manager, prefix cache +core/sched/ scheduler, RadBatch construction, request lifecycle +core/place/ placement planner, the mover, the heat engine +core/sample/ device sampler dispatch + the host reference chain + grammar bitmask +core/text/ tokeniser, chat template, tool parsing, detokenisation +core/mm/ image and video decoding, and the processor that turns frames into patches +core/format/ the .rad reader and writer, safetensors, recipes, the imatrix, the tune cache +core/server/ HTTP, OpenAI-compatible endpoints, /metrics, the dashboard +core/kld.* the KL mode: --kld-record / --kld-ref +core/engine* the thing that ties them together, and `radiance` the binary +libref/ every op, naively, correct, host domain: the fallback and the oracle +libr4d/ the RDNA4 (gfx12xx) kernel library: kernels, rows, layouts, fusion claims +libavx/ the same vocabulary in x86 SIMD, host domain: the production host kernels, + built on every x86-64 build because an op placed on the host cannot run on libref +libquant/ the built-in quantisers rad-convert's recipes name: grids, transforms, rtn, gptq +arch// one architecture plugin per directory +tools/ rad-info, rad-kbench, rad-convert, rad-tune, rad-schemas, rad-tokcheck, + rad-chatparse, rad-gbnf-check +cmake/ rad_add_plugin, and the package config an out-of-tree plugin find_package()s +scripts/ shell harnesses for serving, tracing and profiling a running engine +data/ kernels.rkb and kernels_moe.rkb: recorded references rad-kbench replays with + no model. Two, because no one container declares the whole vocabulary. + recipes/: the quantisation recipes of the containers this tree serves +docs/KERNELS.md what rad-kbench last measured, generated and checked in +vendor/ llama.cpp lifts, tracked to an upstream commit, patched not edited +tests/ ctest +``` + +Each directory has its own `CMakeLists.txt` and each owner writes only inside their own. The +top-level file already exists; add `add_subdirectory` lines there only if your directory is new. + +## Build + +```sh +cmake -S . -B build -G Ninja # host backend; no ROCm required +cmake --build build -j +ctest --test-dir build --output-on-failure +``` + +Your directory must compile and its tests must pass **before you report done**. A component that +does not build is not a component. + +## Conventions + +**No Python in the engine, its tools, its build or its test suite.** This is the project's +founding constraint — `spec.md` opens with it. Tests are C++ and CTest. The one Python file under +`tests/`, `mkgolden.py`, is run by hand against transformers to regenerate the reference numbers in +`tests/mm_golden.h`; nothing in the build or the suite calls it. + +**C ABI at plugin boundaries, C++20 inside.** `abi/` is C and must stay compilable as C. +Everything under `core/` is C++20 and may use the standard library freely. + +**Errors are values.** Return `RAD_OK` or a negative `RAD_E_*`. Do not throw across a function +that a plugin or the run phase can call. `fatal()` is for broken invariants only. + +**Nothing unimplemented returns success.** A function you have not written yet returns +`RAD_E_UNSUPPORTED` and logs once at Warn with its own name. A stub that returns 0 is how a +project ends with fluent wrong output and no way to bisect it (`spec.md` §17). + +**No allocation and no synchronisation on the step path.** The arena is sized at declare. If you +find yourself wanting a `malloc` inside `rad_arch_step` or inside the scheduler's per-step work, +that is a declare-phase bug. + +**`rad_memset_async` refuses `RAD_MEM_HOST` on a card, and the host backend cannot reproduce that.** +`RAD_MEM_HOST` is pageable memory the GPU has never been shown, so the device backend returns +`RAD_E_UNSUPPORTED` naming the rule (`core/device/aql.cpp`). On the host backend every kind of +memory is the same memory, so a memset added to a path that runs on host memory passes in a no-ROCm +build and fails on a card. Use `RAD_MEM_HOST_PINNED` or `RAD_MEM_HOST_MAPPED`, or memset on the +host. `rad_memcpy_async` accepts pageable memory but bounces it through pinned memory and WAITS, +so a pageable copy on the step path is a host stall; `aql_pageable_bytes()` counts them. + +**Kernel plugins launch with `hipLaunchKernel` and the engine dispatches them.** On a card every +stream is an HSA queue the engine owns and writes AQL packets into itself (`core/device/aql.cpp`); +the executable defines `hipLaunchKernel` and HIP's kernel registration hooks, so a plugin built by +hipcc needs nothing special. What a plugin must NOT do with an engine stream is call any other HIP +stream API: `hipEventRecord` and `hipStreamWaitEvent` are refused by name, and anything else would +be handed to HIP as a stream HIP does not own. Use `rad_event_*` and `rad_memcpy_async`. + +**Comments explain the decision, not the syntax.** The spec's voice: say why this and not the +obvious alternative, and name the cost when there is one. `libr4d/r4d_rows.cpp` is the model. +Do not write `// increment i`. + +**Naming.** `rad_` prefix on everything with external linkage. Files are named for what they +provide. `snake_case` for functions and variables, `PascalCase` for types. diff --git a/docs/KERNELS.md b/docs/KERNELS.md new file mode 100644 index 00000000..db0642d3 --- /dev/null +++ b/docs/KERNELS.md @@ -0,0 +1,1851 @@ +# radiance kernel libraries + +Generated by `rad-kbench`. Every kernel every loaded library supplies, run on the same bytes +and timed in the same pass. Correctness, completeness and speed are three readings of one +run, because they are not separable: a library that is fastest on the ops it has and absent +on the rest is slower end to end than one that is uniformly mediocre. + +- fixture: `data/kernels.rkb`, 537 case(s) recorded 2026-09-21 from `q38-27b-fp8-df2.rad` +- libraries: `libr4d@0.5.0 libref@0.1.0` +- reference: `libref` -- every correctness number is relative to it, so it has none of its own +- 1067 case(s) checked, 1067 passed, 0 failed, 7 skipped, 0 capped; worst rel_l2 4.270e-03 + +## Libraries + +`ops` is how many of the 89-op vocabulary this library has a row for, and `graph` how many of +the 32 ops THIS container's declared graph asks for. The two differ on purpose: a library can +be complete for one model and full of holes for the next. + +`rows` is how many kernel rows the library declares and `run` how many of them a case in this +pass actually reached. The gap is the real coverage number: a library can be complete for the +vocabulary, pass everything it ran, and still have rows nothing has executed since they were +written -- see **Rows nothing ran** below for which. + +| library | version | domain | rows | run | ops | graph | cases | pass | fail | worst rel_l2 | median us | +|---|---|---|---|---|---|---|---|---|---|---|---| +| `libr4d` | 0.5.0 | device+host | 118 | 36 of 118 | 79 of 89 | 32 of 32 | 537 | 537 | 0 | 4.27e-03 | 12.96 | +| `libref` (oracle) | 0.1.0 | host | 70 | 31 of 70 | 70 of 89 | 32 of 32 | 530 | 530 | 0 | 0.00e+00 | - | + +Rows declaring an optional hook, which is what separates a library that merely runs from one +the core can tune, fuse and check against a container: + +| library | tunable rows | fusion claims | weight layouts | +|---|---|---|---| +| `libr4d` | 33 | 5 | 18 | +| `libref` | 0 | 0 | 0 | + +## Rows nothing ran + +67 of 188 declared row(s) were reached by a case in this pass. + +`libr4d` -- 82 row(s) not reached: + +| kernel | op | +|---|---| +| `ar_gather_2rank` | `all_gather` | +| `ar_ln_had_quant_i8` | `ar_ln_had_quant_i8` | +| `ar_oneshot_2rank_exact` | `all_reduce` | +| `ar_oneshot_2rank_wht6` | `all_reduce` | +| `ar_oneshot_4rank_exact` | `all_reduce` | +| `ar_oneshot_8rank_exact` | `all_reduce` | +| `ar_rmsnorm_quant_fp8` | `ar_rmsnorm_quant_fp8` | +| `ar_twoshot_4rank_exact` | `all_reduce` | +| `ar_twoshot_4rank_ti8` | `all_reduce` | +| `ar_twoshot_8rank_exact` | `all_reduce` | +| `attn_decode_h128_gqa4_fp8kv` | `attn_paged` | +| `attn_decode_h128_gqa8_bf16kv` | `attn_paged` | +| `attn_decode_h128_gqa8_fp8kv` | `attn_paged` | +| `attn_decode_h256_gqa12_bf16kv` | `attn_paged` | +| `attn_decode_h256_gqa12_fp8kv` | `attn_paged` | +| `attn_decode_h256_gqa6_fp8kv` | `attn_paged` | +| `attn_decode_h256_gqa8_bf16kv` | `attn_paged` | +| `attn_decode_h256_gqa8_fp8kv` | `attn_paged` | +| `attn_prefill_h128_gqa8_bf16kv` | `attn_paged` | +| `attn_prefill_h128_gqa8_fp8kv` | `attn_paged` | +| `attn_prefill_h256_gqa12_bf16kv` | `attn_paged` | +| `attn_prefill_h256_gqa12_fp8kv` | `attn_paged` | +| `attn_prefill_h256_gqa6_fp8kv` | `attn_paged` | +| `attn_prefill_h256_gqa8_bf16kv` | `attn_paged` | +| `attn_prefill_h256_gqa8_fp8kv` | `attn_paged` | +| `attn_vit_h72_bf16` | `attn_dense` | +| `dequant_w4_bf16` | `dequant_w4` | +| `dflash_conv_t2_g16_bf16` | `dflash_conv` | +| `dflash_select_bf16` | `dflash_select` | +| `embed_lookup_q_host` | `embed_lookup_q` | +| `gate_quant_fp8` | `gate_quant_fp8` | +| `gated_had_quant_fp8` | `gated_had_quant_fp8` | +| `gated_had_quant_i8` | `gated_had_quant_i8` | +| `gated_quant_fp8` | `gated_quant_fp8` | +| `gather_rows_u8` | `gather_rows` | +| `gdn_gated_norm_had_quant_i8` | `gdn_gated_norm_had_quant_i8` | +| `gemm_fp8a16_nt_m1` | `gemm_nt_q` | +| `gemm_fp8a8_gated_nt_m16` | `gemm_nt_q_gated` | +| `gemm_mxfp4a8_nt_m64` | `gemm_nt_q` | +| `gemm_w2a8_nt` | `gemm_nt_q` | +| `gemm_w4a16_nt_m64` | `gemm_nt_q` | +| `gemm_w4a8_nt_m64` | `gemm_nt_q` | +| `gemm_w4a8_prefill` | `gemm_nt_q` | +| `gemm_w4a8_tiled` | `gemm_nt_q` | +| `gemm_w8a16_nt_m64` | `gemm_nt_q` | +| `gemm_w8a8_nt_m64` | `gemm_nt_q` | +| `gemm_w8a8_tiled` | `gemm_nt_q` | +| `gram_accum` | `gram_accum` | +| `had_quant_act_fp8` | `had_quant_act_fp8` | +| `had_quant_act_i8` | `had_quant_act_i8` | +| `hc_enter_bf16` | `hc_enter` | +| `hc_read_bf16` | `hc_read` | +| `hc_write_bf16` | `hc_write` | +| `kv_store_fp8` | `kv_store` | +| `logit_rerank` | `logit_rerank` | +| `logits_gemm_bf16` | `logits_gemm` | +| `moe_gather_bf16` | `moe_gather` | +| `moe_gemm_fp8a8` | `moe_gemm_q` | +| `moe_gemm_w4a8` | `moe_gemm_q` | +| `moe_scatter_i32` | `moe_scatter` | +| `mtp_enter_bf16` | `mtp_enter` | +| `mul_bf16` | `mul` | +| `ngram_ids_i32` | `ngram_ids` | +| `ple_conv_bf16` | `ple_conv` | +| `ple_gate_bf16` | `ple_gate` | +| `qk_norm_rope_gate` | `qk_norm_rope_gate` | +| `qsa_block_key_bf16` | `qsa_block_key` | +| `qsa_score_bf16` | `qsa_score` | +| `qsa_select_i32` | `qsa_select` | +| `qsa_tail_store_bf16` | `qsa_tail_store` | +| `qsa_work_bf16` | `qsa_work` | +| `quant_act_i8` | `quant_act_i8` | +| `rmsnorm_had_quant_i8` | `rmsnorm_had_quant_i8` | +| `rmsnorm_quant_fp8` | `rmsnorm_quant_fp8` | +| `router_topk_bf16` | `router_topk` | +| `router_topk_scatter_bf16` | `router_topk_scatter` | +| `rowtopk_merge` | `row_topk_merge` | +| `sample_chain_f32` | `sample_chain` | +| `sample_merge_topk_f32` | `sample_merge_topk` | +| `scale_rows_bf16` | `scale_rows` | +| `scatter_rows_u8` | `scatter_rows` | +| `sigmoid_bf16` | `sigmoid` | + +`libref` -- 39 row(s) not reached: + +| kernel | op | +|---|---| +| `ref_all_gather` | `all_gather` | +| `ref_all_reduce` | `all_reduce` | +| `ref_attn_dense` | `attn_dense` | +| `ref_dequant` | `dequant` | +| `ref_embed_lookup_q` | `embed_lookup_q` | +| `ref_gated_had_quant_i8` | `gated_had_quant_i8` | +| `ref_gelu` | `gelu` | +| `ref_gemm_nt_bias` | `gemm_nt_bias` | +| `ref_gemm_nt_q_bias` | `gemm_nt_q_bias` | +| `ref_gram_accum` | `gram_accum` | +| `ref_had_quant_act_fp8` | `had_quant_act_fp8` | +| `ref_had_quant_act_i8` | `had_quant_act_i8` | +| `ref_hc_enter` | `hc_enter` | +| `ref_hc_read` | `hc_read` | +| `ref_hc_write` | `hc_write` | +| `ref_layernorm` | `layernorm` | +| `ref_logit_rerank` | `logit_rerank` | +| `ref_logits_gemm` | `logits_gemm` | +| `ref_moe_gather` | `moe_gather` | +| `ref_moe_gemm` | `moe_gemm` | +| `ref_moe_gemm_q` | `moe_gemm_q` | +| `ref_moe_scatter` | `moe_scatter` | +| `ref_mtp_enter` | `mtp_enter` | +| `ref_mul` | `mul` | +| `ref_ngram_ids` | `ngram_ids` | +| `ref_ple_conv` | `ple_conv` | +| `ref_ple_gate` | `ple_gate` | +| `ref_qk_norm_rope` | `qk_norm_rope` | +| `ref_quant_act_i8` | `quant_act_i8` | +| `ref_rmsnorm_add` | `rmsnorm_add` | +| `ref_rmsnorm_had_quant_i8` | `rmsnorm_had_quant_i8` | +| `ref_router_topk` | `router_topk` | +| `ref_row_topk_merge` | `row_topk_merge` | +| `ref_sample_merge_topk` | `sample_merge_topk` | +| `ref_scale_rows` | `scale_rows` | +| `ref_scatter_rows` | `scatter_rows` | +| `ref_sigmoid` | `sigmoid` | +| `ref_silu` | `silu` | +| `ref_softmax` | `softmax` | + + +## Completeness + +One row per op in the vocabulary. A cell names the DOMAIN the library serves that op in, or `-` +where it has no row at all. `graph` marks the ops this container's declared program asks for -- +an empty cell on a marked row is a hole a real model falls into, and one on an unmarked row is +not. + +| op | graph | libr4d | libref | +|---|---|---|---| +| `add` | yes | device | host | +| `all_gather` | | device | host | +| `all_reduce` | | device | host | +| `ar_ln_had_quant_i8` | | device | - | +| `ar_rmsnorm_quant_fp8` | | device | - | +| `attn_dense` | | device | host | +| `attn_paged` | yes | device | host | +| `cast` | yes | device | host | +| `dequant` | | - | host | +| `dequant_w4` | | device | - | +| `dflash_conv` | | device | - | +| `dflash_select` | | device | - | +| `embed_lookup` | yes | device | host | +| `embed_lookup_q` | | host | host | +| `gate_quant_fp8` | | device | - | +| `gated_had_quant_fp8` | | device | - | +| `gated_had_quant_i8` | | device | host | +| `gated_quant_fp8` | | device | - | +| `gather_rows` | yes | device | host | +| `gdn_chunk_scan` | yes | device | host | +| `gdn_conv_prep` | yes | device | host | +| `gdn_conv_update` | yes | device | host | +| `gdn_gated_norm_had_quant_i8` | | device | - | +| `gdn_gated_rmsnorm` | yes | device | host | +| `gdn_kkt_solve` | yes | device | host | +| `gdn_recurrent_update` | yes | device | host | +| `gelu` | | - | host | +| `gemm_nt` | yes | device | host | +| `gemm_nt_bias` | | - | host | +| `gemm_nt_q` | yes | device | host | +| `gemm_nt_q_bias` | | - | host | +| `gemm_nt_q_gated` | | device | - | +| `gram_accum` | | device | host | +| `had_quant_act_fp8` | | device | host | +| `had_quant_act_i8` | | device | host | +| `hc_enter` | | device | host | +| `hc_read` | | device | host | +| `hc_write` | | device | host | +| `kv_store` | yes | device | host | +| `layernorm` | | - | host | +| `logit_rerank` | | device | host | +| `logits_gemm` | yes | device | host | +| `moe_gather` | | device | host | +| `moe_gemm` | | - | host | +| `moe_gemm_q` | | device | host | +| `moe_scatter` | | device | host | +| `mtp_enter` | | device | host | +| `mul` | | device | host | +| `ngram_ids` | | device | host | +| `ple_conv` | | device | host | +| `ple_gate` | | device | host | +| `qk_norm_rope` | | - | host | +| `qk_norm_rope_gate` | | device | - | +| `qsa_block_key` | | device | - | +| `qsa_score` | | device | - | +| `qsa_select` | | device | - | +| `qsa_tail_store` | | device | - | +| `qsa_work` | | device | - | +| `quant_act_fp8` | yes | device | host | +| `quant_act_i8` | | device | host | +| `rmsnorm` | yes | device | host | +| `rmsnorm_add` | | - | host | +| `rmsnorm_had_quant_i8` | | device | host | +| `rmsnorm_quant_fp8` | | device | - | +| `rope` | yes | device | host | +| `rope_table` | yes | device | host | +| `router_topk` | | device | host | +| `router_topk_scatter` | | device | - | +| `row_topk` | yes | device | host | +| `row_topk_merge` | | device | host | +| `sample_argmax` | yes | device | host | +| `sample_chain` | | device | - | +| `sample_dry` | yes | device | host | +| `sample_mask` | yes | device | host | +| `sample_merge_topk` | | device | host | +| `sample_minp` | yes | device | host | +| `sample_penalties` | yes | device | host | +| `sample_pick` | yes | device | host | +| `sample_temp` | yes | device | host | +| `sample_topk` | yes | device | host | +| `sample_topp` | yes | device | host | +| `sample_typical` | yes | device | host | +| `sample_xtc` | yes | device | host | +| `scale_rows` | | device | host | +| `scatter_rows` | | device | host | +| `sigmoid` | | device | host | +| `silu` | | - | host | +| `silu_mul` | yes | device | host | +| `softmax` | | - | host | + +## Correctness + +979 distinct case(s) over 1067 check(s). `n` is how many times the case ran -- one per layer, +typically -- and `rel_l2` is the WORST of them, because one layer disagreeing is the finding. +`(synth w)` means this op's weights are not in the container and were drawn instead, so the +case proves the arithmetic and not the artifact. + +| op | kernel | library | domain | geometry | tuned | n | verdict | rel_l2 | tol | +|---|---|---|---|---|---|---|---|---|---| +| `cast` | `cast_bf16_bf16` | libr4d | device | `n=5120 from=bf16 to=bf16 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `cast` | `ref_cast` | libref | host | `n=5120 from=bf16 to=bf16 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `cast` | `cast_bf16_bf16` | libr4d | device | `n=5120 from=bf16 to=bf16 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `cast` | `ref_cast` | libref | host | `n=5120 from=bf16 to=bf16 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `cast` | `cast_bf16_bf16` | libr4d | device | `n=5120 from=bf16 to=bf16 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `cast` | `ref_cast` | libref | host | `n=5120 from=bf16 to=bf16 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `cast` | `cast_bf16_bf16` | libr4d | device | `n=5120 from=bf16 to=bf16 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `cast` | `ref_cast` | libref | host | `n=5120 from=bf16 to=bf16 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `cast` | `cast_bf16_bf16` | libr4d | device | `n=5120 from=bf16 to=bf16 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `cast` | `ref_cast` | libref | host | `n=5120 from=bf16 to=bf16 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `cast` | `cast_bf16_bf16` | libr4d | device | `n=5120 from=bf16 to=bf16 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `cast` | `ref_cast` | libref | host | `n=5120 from=bf16 to=bf16 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `cast` | `cast_bf16_bf16` | libr4d | device | `n=5120 from=bf16 to=bf16 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `cast` | `ref_cast` | libref | host | `n=5120 from=bf16 to=bf16 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `cast` | `cast_bf16_bf16` | libr4d | device | `n=5120 from=bf16 to=bf16 M=128` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `cast` | `ref_cast` | libref | host | `n=5120 from=bf16 to=bf16 M=128` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `cast` | `cast_bf16_bf16` | libr4d | device | `n=5120 from=bf16 to=bf16 M=256` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `cast` | `ref_cast` | libref | host | `n=5120 from=bf16 to=bf16 M=256` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `cast` | `cast_bf16_bf16` | libr4d | device | `n=5120 from=bf16 to=bf16 M=512` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `cast` | `ref_cast` | libref | host | `n=5120 from=bf16 to=bf16 M=512` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `embed_lookup` | `embed_lookup_bf16` | libr4d | device | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=1` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `embed_lookup` | `ref_embed_lookup` | libref | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=1` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `embed_lookup` | `embed_lookup_bf16` | libr4d | device | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=2` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `embed_lookup` | `ref_embed_lookup` | libref | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=2` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `embed_lookup` | `embed_lookup_bf16` | libr4d | device | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=4` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `embed_lookup` | `ref_embed_lookup` | libref | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=4` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `embed_lookup` | `embed_lookup_bf16` | libr4d | device | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=8` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `embed_lookup` | `ref_embed_lookup` | libref | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=8` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `embed_lookup` | `embed_lookup_bf16` | libr4d | device | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=16` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `embed_lookup` | `ref_embed_lookup` | libref | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=16` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `embed_lookup` | `embed_lookup_bf16` | libr4d | device | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=32` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `embed_lookup` | `ref_embed_lookup` | libref | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=32` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `embed_lookup` | `embed_lookup_bf16` | libr4d | device | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=64` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `embed_lookup` | `ref_embed_lookup` | libref | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=64` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `embed_lookup` | `embed_lookup_bf16` | libr4d | device | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=128` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `embed_lookup` | `ref_embed_lookup` | libref | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=128` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `embed_lookup` | `embed_lookup_bf16` | libr4d | device | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=256` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `embed_lookup` | `ref_embed_lookup` | libref | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=256` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `embed_lookup` | `embed_lookup_bf16` | libr4d | device | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=512` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `embed_lookup` | `ref_embed_lookup` | libref | host | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=512` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `rope_table` | `rope_table_f32` | libr4d | device | `rot=64 theta=1e+07 scale=1 dtype=f32 M=1` | - | 1 | ok | 0.00e+00 | 1e-05 | +| `rope_table` | `ref_rope_table` | libref | host | `rot=64 theta=1e+07 scale=1 dtype=f32 M=1` | - | 1 | ok | 0.00e+00 | 1e-05 | +| `rope_table` | `rope_table_f32` | libr4d | device | `rot=64 theta=1e+07 scale=1 dtype=f32 M=2` | - | 1 | ok | 3.76e-09 | 1e-05 | +| `rope_table` | `ref_rope_table` | libref | host | `rot=64 theta=1e+07 scale=1 dtype=f32 M=2` | - | 1 | ok | 0.00e+00 | 1e-05 | +| `rope_table` | `rope_table_f32` | libr4d | device | `rot=64 theta=1e+07 scale=1 dtype=f32 M=4` | - | 1 | ok | 1.27e-08 | 1e-05 | +| `rope_table` | `ref_rope_table` | libref | host | `rot=64 theta=1e+07 scale=1 dtype=f32 M=4` | - | 1 | ok | 0.00e+00 | 1e-05 | +| `rope_table` | `rope_table_f32` | libr4d | device | `rot=64 theta=1e+07 scale=1 dtype=f32 M=8` | - | 1 | ok | 2.47e-08 | 1e-05 | +| `rope_table` | `ref_rope_table` | libref | host | `rot=64 theta=1e+07 scale=1 dtype=f32 M=8` | - | 1 | ok | 0.00e+00 | 1e-05 | +| `rope_table` | `rope_table_f32` | libr4d | device | `rot=64 theta=1e+07 scale=1 dtype=f32 M=16` | - | 1 | ok | 4.99e-08 | 1e-05 | +| `rope_table` | `ref_rope_table` | libref | host | `rot=64 theta=1e+07 scale=1 dtype=f32 M=16` | - | 1 | ok | 0.00e+00 | 1e-05 | +| `rope_table` | `rope_table_f32` | libr4d | device | `rot=64 theta=1e+07 scale=1 dtype=f32 M=32` | - | 1 | ok | 7.51e-08 | 1e-05 | +| `rope_table` | `ref_rope_table` | libref | host | `rot=64 theta=1e+07 scale=1 dtype=f32 M=32` | - | 1 | ok | 0.00e+00 | 1e-05 | +| `rope_table` | `rope_table_f32` | libr4d | device | `rot=64 theta=1e+07 scale=1 dtype=f32 M=64` | - | 1 | ok | 1.62e-07 | 1e-05 | +| `rope_table` | `ref_rope_table` | libref | host | `rot=64 theta=1e+07 scale=1 dtype=f32 M=64` | - | 1 | ok | 0.00e+00 | 1e-05 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=16384 K=5120 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=16384 K=5120 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 4.61e-09 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=16384 K=5120 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 9.84e-09 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=16384 K=5120 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 1.08e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=16384 K=5120 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 6.91e-05 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=16384 K=5120 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 1.24e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=16384 K=5120 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 7.57e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=16384 K=5120 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 7.95e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=16384 K=5120 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 1.10e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=16384 K=5120 group=128 dtype=fp8a8 M=130` | - | 1 | ok | 2.88e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=130` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=16384 K=5120 group=128 dtype=fp8a8 M=260` | - | 1 | ok | 2.65e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=260` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=16384 K=5120 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 1.04e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=16384 K=5120 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=96 K=5120 dtype=bf16 M=1 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 | +| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=96 K=5120 dtype=bf16 M=1 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 | +| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=96 K=5120 dtype=bf16 M=2 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 | +| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=96 K=5120 dtype=bf16 M=2 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 | +| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=96 K=5120 dtype=bf16 M=4 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 | +| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=96 K=5120 dtype=bf16 M=4 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 | +| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=96 K=5120 dtype=bf16 M=8 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 6.00e-06 | 8e-03 | +| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=96 K=5120 dtype=bf16 M=8 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 | +| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=96 K=5120 dtype=bf16 M=16 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 1.57e-07 | 8e-03 | +| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=96 K=5120 dtype=bf16 M=16 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 | +| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | device | `N=96 K=5120 dtype=bf16 M=17 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 | +| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=96 K=5120 dtype=bf16 M=17 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 | +| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | device | `N=96 K=5120 dtype=bf16 M=34 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 3.35e-14 | 8e-03 | +| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=96 K=5120 dtype=bf16 M=34 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 | +| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | device | `N=96 K=5120 dtype=bf16 M=68 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 2.93e-09 | 8e-03 | +| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=96 K=5120 dtype=bf16 M=68 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 | +| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | device | `N=96 K=5120 dtype=bf16 M=136 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 5.00e-07 | 8e-03 | +| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=96 K=5120 dtype=bf16 M=136 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 | +| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | device | `N=96 K=5120 dtype=bf16 M=272 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 6.98e-07 | 8e-03 | +| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=96 K=5120 dtype=bf16 M=272 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 | +| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | device | `N=96 K=5120 dtype=bf16 M=512 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 3.23e-07 | 8e-03 | +| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=96 K=5120 dtype=bf16 M=512 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 | +| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 chunk=64 conv_width=4 M=1` | - | 1 | ok | 1.91e-07 | 2e-02 | +| `gdn_conv_prep` | `ref_gdn_conv_prep` | libref | host | `head_k=128 head_v=128 chunk=64 conv_width=4 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 chunk=64 conv_width=4 M=2` | - | 1 | ok | 5.92e-08 | 2e-02 | +| `gdn_conv_prep` | `ref_gdn_conv_prep` | libref | host | `head_k=128 head_v=128 chunk=64 conv_width=4 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 chunk=64 conv_width=4 M=4` | - | 1 | ok | 3.02e-07 | 2e-02 | +| `gdn_conv_prep` | `ref_gdn_conv_prep` | libref | host | `head_k=128 head_v=128 chunk=64 conv_width=4 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 chunk=64 conv_width=4 M=8` | - | 1 | ok | 7.31e-08 | 2e-02 | +| `gdn_conv_prep` | `ref_gdn_conv_prep` | libref | host | `head_k=128 head_v=128 chunk=64 conv_width=4 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 chunk=64 conv_width=4 M=16` | - | 1 | ok | 1.31e-07 | 2e-02 | +| `gdn_conv_prep` | `ref_gdn_conv_prep` | libref | host | `head_k=128 head_v=128 chunk=64 conv_width=4 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 chunk=64 conv_width=4 M=32` | - | 1 | ok | 8.24e-08 | 2e-02 | +| `gdn_conv_prep` | `ref_gdn_conv_prep` | libref | host | `head_k=128 head_v=128 chunk=64 conv_width=4 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 chunk=64 conv_width=4 M=64` | - | 1 | ok | 2.81e-07 | 2e-02 | +| `gdn_conv_prep` | `ref_gdn_conv_prep` | libref | host | `head_k=128 head_v=128 chunk=64 conv_width=4 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 chunk=64 conv_width=4 M=128` | - | 1 | ok | 9.72e-05 | 2e-02 | +| `gdn_conv_prep` | `ref_gdn_conv_prep` | libref | host | `head_k=128 head_v=128 chunk=64 conv_width=4 M=128` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 chunk=64 conv_width=4 M=256` | - | 1 | ok | 1.14e-07 | 2e-02 | +| `gdn_conv_prep` | `ref_gdn_conv_prep` | libref | host | `head_k=128 head_v=128 chunk=64 conv_width=4 M=256` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 chunk=64 conv_width=4 M=512` | - | 1 | ok | 1.18e-07 | 2e-02 | +| `gdn_conv_prep` | `ref_gdn_conv_prep` | libref | host | `head_k=128 head_v=128 chunk=64 conv_width=4 M=512` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | device | `head_k=128 M=1 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_kkt_solve` | `ref_gdn_kkt_solve` | libref | host | `head_k=128 M=1 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | device | `head_k=128 M=2 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_kkt_solve` | `ref_gdn_kkt_solve` | libref | host | `head_k=128 M=2 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | device | `head_k=128 M=4 chunk=64` | - | 1 | ok | 1.63e-05 | 2e-02 | +| `gdn_kkt_solve` | `ref_gdn_kkt_solve` | libref | host | `head_k=128 M=4 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | device | `head_k=128 M=8 chunk=64` | - | 1 | ok | 2.72e-05 | 2e-02 | +| `gdn_kkt_solve` | `ref_gdn_kkt_solve` | libref | host | `head_k=128 M=8 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | device | `head_k=128 M=16 chunk=64` | - | 1 | ok | 3.85e-05 | 2e-02 | +| `gdn_kkt_solve` | `ref_gdn_kkt_solve` | libref | host | `head_k=128 M=16 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | device | `head_k=128 M=32 chunk=64` | - | 1 | ok | 2.54e-05 | 2e-02 | +| `gdn_kkt_solve` | `ref_gdn_kkt_solve` | libref | host | `head_k=128 M=32 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | device | `head_k=128 M=64 chunk=64` | - | 1 | ok | 7.76e-05 | 2e-02 | +| `gdn_kkt_solve` | `ref_gdn_kkt_solve` | libref | host | `head_k=128 M=64 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | device | `head_k=128 M=128 chunk=64` | - | 1 | ok | 8.13e-05 | 2e-02 | +| `gdn_kkt_solve` | `ref_gdn_kkt_solve` | libref | host | `head_k=128 M=128 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | device | `head_k=128 M=256 chunk=64` | - | 1 | ok | 5.42e-05 | 2e-02 | +| `gdn_kkt_solve` | `ref_gdn_kkt_solve` | libref | host | `head_k=128 M=256 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | device | `head_k=128 M=512 chunk=64` | - | 1 | ok | 1.76e-05 | 2e-02 | +| `gdn_kkt_solve` | `ref_gdn_kkt_solve` | libref | host | `head_k=128 M=512 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | device | `head_k=128 head_v=128 scale=0.0883883 M=1 chunk=64` | - | 1 | ok | 2.37e-03 | 2e-02 | +| `gdn_chunk_scan` | `ref_gdn_chunk_scan` | libref | host | `head_k=128 head_v=128 scale=0.0883883 M=1 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | device | `head_k=128 head_v=128 scale=0.0883883 M=2 chunk=64` | - | 1 | ok | 2.48e-03 | 2e-02 | +| `gdn_chunk_scan` | `ref_gdn_chunk_scan` | libref | host | `head_k=128 head_v=128 scale=0.0883883 M=2 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | device | `head_k=128 head_v=128 scale=0.0883883 M=4 chunk=64` | - | 1 | ok | 2.63e-03 | 2e-02 | +| `gdn_chunk_scan` | `ref_gdn_chunk_scan` | libref | host | `head_k=128 head_v=128 scale=0.0883883 M=4 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | device | `head_k=128 head_v=128 scale=0.0883883 M=8 chunk=64` | - | 1 | ok | 2.48e-03 | 2e-02 | +| `gdn_chunk_scan` | `ref_gdn_chunk_scan` | libref | host | `head_k=128 head_v=128 scale=0.0883883 M=8 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | device | `head_k=128 head_v=128 scale=0.0883883 M=16 chunk=64` | - | 1 | ok | 2.76e-03 | 2e-02 | +| `gdn_chunk_scan` | `ref_gdn_chunk_scan` | libref | host | `head_k=128 head_v=128 scale=0.0883883 M=16 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | device | `head_k=128 head_v=128 scale=0.0883883 M=32 chunk=64` | - | 1 | ok | 3.40e-03 | 2e-02 | +| `gdn_chunk_scan` | `ref_gdn_chunk_scan` | libref | host | `head_k=128 head_v=128 scale=0.0883883 M=32 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | device | `head_k=128 head_v=128 scale=0.0883883 M=64 chunk=64` | - | 1 | ok | 3.33e-03 | 2e-02 | +| `gdn_chunk_scan` | `ref_gdn_chunk_scan` | libref | host | `head_k=128 head_v=128 scale=0.0883883 M=64 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | device | `head_k=128 head_v=128 scale=0.0883883 M=128 chunk=64` | - | 1 | ok | 4.27e-03 | 2e-02 | +| `gdn_chunk_scan` | `ref_gdn_chunk_scan` | libref | host | `head_k=128 head_v=128 scale=0.0883883 M=128 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | device | `head_k=128 head_v=128 scale=0.0883883 M=256 chunk=64` | - | 1 | ok | 3.48e-03 | 2e-02 | +| `gdn_chunk_scan` | `ref_gdn_chunk_scan` | libref | host | `head_k=128 head_v=128 scale=0.0883883 M=256 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | device | `head_k=128 head_v=128 scale=0.0883883 M=512 chunk=64` | - | 1 | ok | 3.64e-03 | 2e-02 | +| `gdn_chunk_scan` | `ref_gdn_chunk_scan` | libref | host | `head_k=128 head_v=128 scale=0.0883883 M=512 chunk=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | device | `channels=128 eps=1e-06 act=silu M=1` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_gated_rmsnorm` | `ref_gdn_gated_rmsnorm` | libref | host | `channels=128 eps=1e-06 act=silu M=1` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | device | `channels=128 eps=1e-06 act=silu M=2` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_gated_rmsnorm` | `ref_gdn_gated_rmsnorm` | libref | host | `channels=128 eps=1e-06 act=silu M=2` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | device | `channels=128 eps=1e-06 act=silu M=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_gated_rmsnorm` | `ref_gdn_gated_rmsnorm` | libref | host | `channels=128 eps=1e-06 act=silu M=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | device | `channels=128 eps=1e-06 act=silu M=8` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_gated_rmsnorm` | `ref_gdn_gated_rmsnorm` | libref | host | `channels=128 eps=1e-06 act=silu M=8` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | device | `channels=128 eps=1e-06 act=silu M=16` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_gated_rmsnorm` | `ref_gdn_gated_rmsnorm` | libref | host | `channels=128 eps=1e-06 act=silu M=16` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | device | `channels=128 eps=1e-06 act=silu M=32` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_gated_rmsnorm` | `ref_gdn_gated_rmsnorm` | libref | host | `channels=128 eps=1e-06 act=silu M=32` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | device | `channels=128 eps=1e-06 act=silu M=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_gated_rmsnorm` | `ref_gdn_gated_rmsnorm` | libref | host | `channels=128 eps=1e-06 act=silu M=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | device | `channels=128 eps=1e-06 act=silu M=128` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_gated_rmsnorm` | `ref_gdn_gated_rmsnorm` | libref | host | `channels=128 eps=1e-06 act=silu M=128` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | device | `channels=128 eps=1e-06 act=silu M=256` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_gated_rmsnorm` | `ref_gdn_gated_rmsnorm` | libref | host | `channels=128 eps=1e-06 act=silu M=256` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | device | `channels=128 eps=1e-06 act=silu M=512` | - | 1 | ok | 5.73e-08 | 2e-02 | +| `gdn_gated_rmsnorm` | `ref_gdn_gated_rmsnorm` | libref | host | `channels=128 eps=1e-06 act=silu M=512` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 conv_width=4 q_len=1` | - | 1 | ok | 4.95e-08 | 2e-02 | +| `gdn_conv_update` | `ref_gdn_conv_update` | libref | host | `head_k=128 head_v=128 conv_width=4 q_len=1` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 conv_width=4 q_len=2` | - | 1 | ok | 2.45e-08 | 2e-02 | +| `gdn_conv_update` | `ref_gdn_conv_update` | libref | host | `head_k=128 head_v=128 conv_width=4 q_len=2` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 conv_width=4 q_len=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_conv_update` | `ref_gdn_conv_update` | libref | host | `head_k=128 head_v=128 conv_width=4 q_len=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 conv_width=4 q_len=8` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_conv_update` | `ref_gdn_conv_update` | libref | host | `head_k=128 head_v=128 conv_width=4 q_len=8` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 conv_width=4 q_len=16` | - | 1 | ok | 2.62e-07 | 2e-02 | +| `gdn_conv_update` | `ref_gdn_conv_update` | libref | host | `head_k=128 head_v=128 conv_width=4 q_len=16` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 conv_width=4 q_len=32` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_conv_update` | `ref_gdn_conv_update` | libref | host | `head_k=128 head_v=128 conv_width=4 q_len=32` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 conv_width=4 q_len=64` | - | 1 | ok | 1.94e-07 | 2e-02 | +| `gdn_conv_update` | `ref_gdn_conv_update` | libref | host | `head_k=128 head_v=128 conv_width=4 q_len=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 conv_width=4 q_len=128` | - | 1 | ok | 3.51e-08 | 2e-02 | +| `gdn_conv_update` | `ref_gdn_conv_update` | libref | host | `head_k=128 head_v=128 conv_width=4 q_len=128` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 conv_width=4 q_len=256` | - | 1 | ok | 7.97e-08 | 2e-02 | +| `gdn_conv_update` | `ref_gdn_conv_update` | libref | host | `head_k=128 head_v=128 conv_width=4 q_len=256` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | device | `head_k=128 head_v=128 conv_width=4 q_len=512` | - | 1 | ok | 3.09e-08 | 2e-02 | +| `gdn_conv_update` | `ref_gdn_conv_update` | libref | host | `head_k=128 head_v=128 conv_width=4 q_len=512` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | device | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=1` | - | 1 | ok | 6.79e-08 | 2e-02 | +| `gdn_recurrent_update` | `ref_gdn_recurrent_update` | libref | host | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=1` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | device | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=2` | - | 1 | ok | 7.98e-08 | 2e-02 | +| `gdn_recurrent_update` | `ref_gdn_recurrent_update` | libref | host | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=2` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | device | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=4` | - | 1 | ok | 8.22e-08 | 2e-02 | +| `gdn_recurrent_update` | `ref_gdn_recurrent_update` | libref | host | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | device | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=8` | - | 1 | ok | 6.98e-08 | 2e-02 | +| `gdn_recurrent_update` | `ref_gdn_recurrent_update` | libref | host | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=8` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | device | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=16` | - | 1 | ok | 8.01e-08 | 2e-02 | +| `gdn_recurrent_update` | `ref_gdn_recurrent_update` | libref | host | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=16` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | device | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=32` | - | 1 | ok | 2.62e-06 | 2e-02 | +| `gdn_recurrent_update` | `ref_gdn_recurrent_update` | libref | host | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=32` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | device | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=64` | - | 1 | ok | 6.90e-08 | 2e-02 | +| `gdn_recurrent_update` | `ref_gdn_recurrent_update` | libref | host | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | device | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=128` | - | 1 | ok | 9.63e-08 | 2e-02 | +| `gdn_recurrent_update` | `ref_gdn_recurrent_update` | libref | host | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=128` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | device | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=256` | - | 1 | ok | 3.17e-07 | 2e-02 | +| `gdn_recurrent_update` | `ref_gdn_recurrent_update` | libref | host | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=256` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | device | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=512` | - | 1 | ok | 1.14e-07 | 2e-02 | +| `gdn_recurrent_update` | `ref_gdn_recurrent_update` | libref | host | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=512` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=6144 group=128 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=6144 group=128 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=6144 group=128 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=6144 group=128 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=6144 group=128 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=6144 group=128 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=6144 group=128 dtype=bf16 M=8` | - | 1 | ok | 5.86e-15 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=6144 group=128 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=6144 group=128 dtype=bf16 M=16` | - | 1 | ok | 3.00e-15 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=6144 group=128 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=6144 group=128 dtype=bf16 M=32` | - | 1 | ok | 1.42e-15 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=6144 group=128 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=6144 group=128 dtype=bf16 M=64` | - | 1 | ok | 7.18e-16 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=6144 group=128 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=6144 group=128 dtype=bf16 M=128` | - | 1 | ok | 6.10e-16 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=6144 group=128 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=6144 group=128 dtype=bf16 M=256` | - | 1 | ok | 8.61e-16 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=6144 group=128 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=6144 group=128 dtype=bf16 M=512` | - | 1 | ok | 1.63e-15 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=6144 group=128 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=6144 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=6144 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 9.54e-16 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=6144 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 7.22e-09 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=6144 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 7.08e-11 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=6144 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 3.90e-10 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=6144 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 6.07e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=6144 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 2.05e-11 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=6144 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 3.11e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=5120 K=6144 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 3.59e-09 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=5120 K=6144 group=128 dtype=fp8a8 M=130` | - | 1 | ok | 1.79e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=130` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=5120 K=6144 group=128 dtype=fp8a8 M=260` | - | 1 | ok | 7.15e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=260` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=5120 K=6144 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 1.60e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=6144 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 7.15e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 2.20e-09 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 2.87e-09 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 1.33e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 2.57e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 3.15e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 9.74e-09 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 2.38e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 9.90e-09 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 M=130` | - | 1 | ok | 2.27e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=130` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 M=260` | - | 1 | ok | 1.92e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=260` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=34816 K=5120 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 4.64e-09 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=34816 K=5120 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=17408 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 8.01e-05 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=17408 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 3.56e-13 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=17408 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 5.04e-11 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=17408 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 4.56e-09 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=17408 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 5.84e-12 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=17408 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 6.06e-10 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=17408 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 6.89e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=17408 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 4.32e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=5120 K=17408 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 1.29e-07 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=5120 K=17408 group=128 dtype=fp8a8 M=130` | - | 1 | ok | 3.36e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=130` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=5120 K=17408 group=128 dtype=fp8a8 M=260` | - | 1 | ok | 4.29e-09 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=260` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=5120 K=17408 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 2.83e-09 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=17408 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=12288 K=5120 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=12288 K=5120 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 3.47e-09 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=12288 K=5120 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 1.32e-12 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=12288 K=5120 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 2.21e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=12288 K=5120 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 2.59e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=12288 K=5120 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 7.04e-10 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=12288 K=5120 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 3.35e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=12288 K=5120 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 9.76e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=12288 K=5120 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 2.33e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=12288 K=5120 group=128 dtype=fp8a8 M=130` | - | 1 | ok | 4.36e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=130` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=12288 K=5120 group=128 dtype=fp8a8 M=260` | - | 1 | ok | 6.33e-09 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=260` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=12288 K=5120 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 2.25e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=12288 K=5120 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=1024 K=5120 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=1024 K=5120 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=1024 K=5120 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=1024 K=5120 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 1.33e-15 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=1024 K=5120 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=1024 K=5120 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 1.69e-07 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=1024 K=5120 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 9.42e-09 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=1024 K=5120 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 3.27e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=1024 K=5120 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 5.99e-11 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=1024 K=5120 group=128 dtype=fp8a8 M=130` | - | 1 | ok | 2.53e-07 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=130` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=1024 K=5120 group=128 dtype=fp8a8 M=260` | - | 1 | ok | 2.85e-07 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=260` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=1024 K=5120 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 1.22e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=1024 K=5120 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=128` | - | 1 | ok | 1.20e-07 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=256` | - | 1 | ok | 5.69e-08 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=512` | - | 1 | ok | 2.35e-07 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=32` | - | 1 | ok | 2.29e-13 | 2e-02 | +| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=64` | - | 1 | ok | 8.50e-12 | 2e-02 | +| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=128` | - | 1 | ok | 7.48e-09 | 2e-02 | +| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=128` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=256` | - | 1 | ok | 9.03e-09 | 2e-02 | +| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=256` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=512` | - | 1 | ok | 4.07e-10 | 2e-02 | +| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=512` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=128` | - | 1 | ok | 7.06e-11 | 2e-02 | +| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=128` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=256` | - | 1 | ok | 1.79e-10 | 2e-02 | +| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=256` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `rope_bf16` | libr4d | device | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=512` | - | 1 | ok | 6.95e-09 | 2e-02 | +| `rope` | `ref_rope` | libref | host | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=512` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `attn_paged` | `attn_decode_h256_gqa6_bf16kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=1 splits=0` | - | 3 | ok | 2.29e-03 | 3e-02 | +| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=1 splits=0` | - | 3 | ok | 0.00e+00 | 3e-02 | +| `attn_paged` | `attn_decode_h256_gqa6_bf16kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=2 splits=0` | - | 3 | ok | 2.16e-03 | 3e-02 | +| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=2 splits=0` | - | 3 | ok | 0.00e+00 | 3e-02 | +| `attn_paged` | `attn_decode_h256_gqa6_bf16kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=4 splits=0` | - | 3 | ok | 1.83e-03 | 3e-02 | +| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=4 splits=0` | - | 3 | ok | 0.00e+00 | 3e-02 | +| `attn_paged` | `attn_decode_h256_gqa6_bf16kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=5 splits=0` | - | 3 | ok | 2.17e-03 | 3e-02 | +| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=5 splits=0` | - | 3 | ok | 0.00e+00 | 3e-02 | +| `attn_paged` | `attn_decode_h256_gqa6_bf16kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=6 splits=0` | - | 3 | ok | 2.09e-03 | 3e-02 | +| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=6 splits=0` | - | 3 | ok | 0.00e+00 | 3e-02 | +| `attn_paged` | `attn_decode_h256_gqa6_bf16kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=8 splits=0` | - | 3 | ok | 2.07e-03 | 3e-02 | +| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=8 splits=0` | - | 3 | ok | 0.00e+00 | 3e-02 | +| `attn_paged` | `attn_decode_h256_gqa6_bf16kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=9 splits=0` | - | 3 | ok | 2.31e-03 | 3e-02 | +| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=9 splits=0` | - | 3 | ok | 0.00e+00 | 3e-02 | +| `attn_paged` | `attn_decode_h256_gqa6_bf16kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=10 splits=0` | - | 3 | ok | 1.96e-03 | 3e-02 | +| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=10 splits=0` | - | 3 | ok | 0.00e+00 | 3e-02 | +| `attn_paged` | `attn_prefill_h256_gqa6_bf16kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=11` | - | 3 | ok | 1.62e-03 | 3e-02 | +| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=11` | - | 3 | ok | 0.00e+00 | 3e-02 | +| `attn_paged` | `attn_prefill_h256_gqa6_bf16kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=16` | - | 3 | ok | 1.59e-03 | 3e-02 | +| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=16` | - | 3 | ok | 0.00e+00 | 3e-02 | +| `attn_paged` | `attn_prefill_h256_gqa6_bf16kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=17` | - | 3 | ok | 1.59e-03 | 3e-02 | +| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=17` | - | 3 | ok | 0.00e+00 | 3e-02 | +| `attn_paged` | `attn_prefill_h256_gqa6_bf16kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=34` | - | 3 | ok | 1.70e-03 | 3e-02 | +| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=34` | - | 3 | ok | 0.00e+00 | 3e-02 | +| `attn_paged` | `attn_prefill_h256_gqa6_bf16kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=68` | - | 3 | ok | 1.36e-03 | 3e-02 | +| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=68` | - | 3 | ok | 0.00e+00 | 3e-02 | +| `attn_paged` | `attn_prefill_h256_gqa6_bf16kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=136` | - | 3 | ok | 1.72e-03 | 3e-02 | +| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=136` | - | 3 | ok | 0.00e+00 | 3e-02 | +| `attn_paged` | `attn_prefill_h256_gqa6_bf16kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=272` | - | 3 | ok | 1.92e-03 | 3e-02 | +| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=272` | - | 3 | ok | 0.00e+00 | 3e-02 | +| `attn_paged` | `attn_prefill_h256_gqa6_bf16kv` | libr4d | device | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=512` | - | 3 | ok | 1.71e-03 | 3e-02 | +| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=512` | - | 3 | ok | 0.00e+00 | 3e-02 | +| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `kv_store` | `ref_kv_store` | libref | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `kv_store` | `ref_kv_store` | libref | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `kv_store` | `ref_kv_store` | libref | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `kv_store` | `ref_kv_store` | libref | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `kv_store` | `ref_kv_store` | libref | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `kv_store` | `ref_kv_store` | libref | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `kv_store` | `ref_kv_store` | libref | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `kv_store` | `ref_kv_store` | libref | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `kv_store` | `ref_kv_store` | libref | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `kv_store` | `ref_kv_store` | libref | host | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `add` | `add_bf16` | libr4d | device | `n=5120 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `add` | `ref_add` | libref | host | `n=5120 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `add` | `add_bf16` | libr4d | device | `n=5120 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `add` | `ref_add` | libref | host | `n=5120 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `add` | `add_bf16` | libr4d | device | `n=5120 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `add` | `ref_add` | libref | host | `n=5120 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `add` | `add_bf16` | libr4d | device | `n=5120 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `add` | `ref_add` | libref | host | `n=5120 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `add` | `add_bf16` | libr4d | device | `n=5120 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `add` | `ref_add` | libref | host | `n=5120 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `add` | `add_bf16` | libr4d | device | `n=5120 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `add` | `ref_add` | libref | host | `n=5120 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `add` | `add_bf16` | libr4d | device | `n=5120 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `add` | `ref_add` | libref | host | `n=5120 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `add` | `add_bf16` | libr4d | device | `n=5120 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `add` | `ref_add` | libref | host | `n=5120 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `add` | `add_bf16` | libr4d | device | `n=5120 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `add` | `ref_add` | libref | host | `n=5120 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `add` | `add_bf16` | libr4d | device | `n=5120 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `add` | `ref_add` | libref | host | `n=5120 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=2` | - | 1 | ok | 4.90e-04 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=4` | - | 1 | ok | 6.58e-07 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=8` | - | 1 | ok | 1.43e-06 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=16` | - | 1 | ok | 2.14e-06 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=32` | - | 1 | ok | 7.14e-05 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=64` | - | 1 | ok | 2.30e-06 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=128` | - | 1 | ok | 2.38e-04 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=256` | - | 1 | ok | 2.78e-04 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=512` | - | 1 | ok | 2.32e-06 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `gather_rows` | `gather_rows_bf16` | libr4d | device | `n=5120 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `gather_rows` | `ref_gather_rows` | libref | host | `n=5120 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `gather_rows` | `gather_rows_bf16` | libr4d | device | `n=5120 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `gather_rows` | `ref_gather_rows` | libref | host | `n=5120 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `gather_rows` | `gather_rows_bf16` | libr4d | device | `n=5120 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `gather_rows` | `ref_gather_rows` | libref | host | `n=5120 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `gather_rows` | `gather_rows_bf16` | libr4d | device | `n=5120 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `gather_rows` | `ref_gather_rows` | libref | host | `n=5120 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `gather_rows` | `gather_rows_bf16` | libr4d | device | `n=5120 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `gather_rows` | `ref_gather_rows` | libref | host | `n=5120 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `gather_rows` | `gather_rows_bf16` | libr4d | device | `n=5120 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `gather_rows` | `ref_gather_rows` | libref | host | `n=5120 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `gather_rows` | `gather_rows_bf16` | libr4d | device | `n=5120 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `gather_rows` | `ref_gather_rows` | libref | host | `n=5120 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `logits_gemm` | `logits_gemm_fp8` | libr4d | device | `n_vocab=248320 n_embd=5120 dtype=bf16 M=1` | - | 1 | ok | 1.62e-03 | 8e-03 | +| `logits_gemm` | `logits_gemm_fp8` | libr4d | device | `n_vocab=248320 n_embd=5120 dtype=bf16 M=2` | - | 1 | ok | 1.56e-03 | 8e-03 | +| `logits_gemm` | `logits_gemm_fp8` | libr4d | device | `n_vocab=248320 n_embd=5120 dtype=bf16 M=4` | - | 1 | ok | 1.59e-03 | 8e-03 | +| `logits_gemm` | `logits_gemm_fp8` | libr4d | device | `n_vocab=248320 n_embd=5120 dtype=bf16 M=8` | - | 1 | ok | 1.63e-03 | 8e-03 | +| `logits_gemm` | `logits_gemm_fp8` | libr4d | device | `n_vocab=248320 n_embd=5120 dtype=bf16 M=16` | - | 1 | ok | 1.53e-03 | 8e-03 | +| `logits_gemm` | `logits_gemm_fp8` | libr4d | device | `n_vocab=248320 n_embd=5120 dtype=bf16 M=32` | - | 1 | ok | 1.60e-03 | 8e-03 | +| `logits_gemm` | `logits_gemm_fp8` | libr4d | device | `n_vocab=248320 n_embd=5120 dtype=bf16 M=64` | - | 1 | ok | 1.64e-03 | 8e-03 | +| `attn_paged` | `attn_decode_h128_gqa4_bf16kv` | libr4d | device | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=1 splits=0` | - | 3 | ok | 2.24e-03 | 3e-02 | +| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=1 splits=0` | - | 3 | ok | 0.00e+00 | 3e-02 | +| `attn_paged` | `attn_decode_h128_gqa4_bf16kv` | libr4d | device | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=2 splits=0` | - | 3 | ok | 1.94e-03 | 3e-02 | +| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=2 splits=0` | - | 3 | ok | 0.00e+00 | 3e-02 | +| `attn_paged` | `attn_decode_h128_gqa4_bf16kv` | libr4d | device | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=4 splits=0` | - | 3 | ok | 2.13e-03 | 3e-02 | +| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=4 splits=0` | - | 3 | ok | 0.00e+00 | 3e-02 | +| `attn_paged` | `attn_decode_h128_gqa4_bf16kv` | libr4d | device | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=5 splits=0` | - | 3 | ok | 2.16e-03 | 3e-02 | +| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=5 splits=0` | - | 3 | ok | 0.00e+00 | 3e-02 | +| `attn_paged` | `attn_decode_h128_gqa4_bf16kv` | libr4d | device | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=6 splits=0` | - | 3 | ok | 2.25e-03 | 3e-02 | +| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=6 splits=0` | - | 3 | ok | 0.00e+00 | 3e-02 | +| `attn_paged` | `attn_decode_h128_gqa4_bf16kv` | libr4d | device | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=8 splits=0` | - | 3 | ok | 2.09e-03 | 3e-02 | +| `attn_paged` | `ref_attn_paged` | libref | host | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=8 splits=0` | - | 3 | ok | 0.00e+00 | 3e-02 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=25600 group=128 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=25600 group=128 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=25600 group=128 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=25600 group=128 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=25600 group=128 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=25600 group=128 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=25600 group=128 dtype=bf16 M=8` | - | 1 | ok | 1.39e-15 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=25600 group=128 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=25600 group=128 dtype=bf16 M=16` | - | 1 | ok | 2.12e-15 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=25600 group=128 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=25600 group=128 dtype=bf16 M=32` | - | 1 | ok | 2.19e-15 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=25600 group=128 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=25600 group=128 dtype=bf16 M=64` | - | 1 | ok | 7.04e-16 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=25600 group=128 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=25600 group=128 dtype=bf16 M=128` | - | 1 | ok | 1.79e-15 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=25600 group=128 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=25600 group=128 dtype=bf16 M=256` | - | 1 | ok | 1.13e-15 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=25600 group=128 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=25600 group=128 dtype=bf16 M=512` | - | 1 | ok | 1.20e-15 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=25600 group=128 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=25600 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 3.97e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=25600 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=25600 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 3.11e-09 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=25600 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=25600 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 1.23e-04 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=25600 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=25600 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 6.38e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=25600 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=25600 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 1.22e-11 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=25600 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=25600 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 3.50e-09 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=25600 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=25600 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 2.55e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=25600 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=25600 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 9.19e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=25600 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=5120 K=25600 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 9.45e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=25600 group=128 dtype=fp8a8 M=65` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=5120 K=25600 group=128 dtype=fp8a8 M=130` | - | 1 | ok | 3.35e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=25600 group=128 dtype=fp8a8 M=130` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=5120 K=25600 group=128 dtype=fp8a8 M=260` | - | 1 | ok | 1.37e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=25600 group=128 dtype=fp8a8 M=260` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | device | `N=5120 K=25600 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 1.84e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=25600 group=128 dtype=fp8a8 M=512` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=2` | - | 1 | ok | 9.52e-05 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=4` | - | 1 | ok | 1.23e-06 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=8` | - | 1 | ok | 9.37e-07 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=16` | - | 1 | ok | 7.01e-05 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=32` | - | 1 | ok | 2.35e-06 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=64` | - | 1 | ok | 2.66e-06 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=128` | - | 1 | ok | 2.29e-06 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=256` | - | 1 | ok | 1.84e-04 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=512` | - | 1 | ok | 1.03e-04 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=5120 group=128 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=5120 group=128 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=5120 group=128 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=5120 group=128 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=5120 group=128 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=5120 group=128 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=5120 group=128 dtype=bf16 M=8` | - | 1 | ok | 6.84e-15 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=5120 group=128 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=5120 group=128 dtype=bf16 M=16` | - | 1 | ok | 3.60e-15 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=5120 group=128 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=5120 group=128 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=5120 group=128 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=5120 group=128 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=5120 group=128 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=5120 group=128 dtype=bf16 M=128` | - | 1 | ok | 4.46e-16 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=5120 group=128 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=5120 group=128 dtype=bf16 M=256` | - | 1 | ok | 1.10e-15 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=5120 group=128 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=5120 group=128 dtype=bf16 M=512` | - | 1 | ok | 1.45e-15 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=5120 group=128 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=256` | - | 1 | ok | 9.96e-07 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | device | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rmsnorm` | `ref_rmsnorm` | libref | host | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 4e-03 | +| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=1` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=1` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=2` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=2` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=8` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=8` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=16` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=16` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=32` | - | 1 | ok | 1.24e-12 | 2e-02 | +| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=32` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=64` | - | 1 | ok | 5.15e-08 | 2e-02 | +| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=128` | - | 1 | ok | 4.52e-09 | 2e-02 | +| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=128` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=256` | - | 1 | ok | 1.25e-07 | 2e-02 | +| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=256` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=512` | - | 1 | ok | 1.28e-07 | 2e-02 | +| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=512` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `kv_store` | `ref_kv_store` | libref | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `kv_store` | `ref_kv_store` | libref | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `kv_store` | `ref_kv_store` | libref | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `kv_store` | `ref_kv_store` | libref | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `kv_store` | `ref_kv_store` | libref | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `kv_store` | `ref_kv_store` | libref | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `kv_store` | `ref_kv_store` | libref | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `kv_store` | `ref_kv_store` | libref | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=128` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `kv_store` | `ref_kv_store` | libref | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=256` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `kv_store` | `kv_store_bf16` | libr4d | device | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `kv_store` | `ref_kv_store` | libref | host | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=512` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=4096 group=128 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=4096 group=128 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=4096 group=128 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=4096 group=128 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=4096 group=128 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=4096 group=128 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=4096 group=128 dtype=bf16 M=8` | - | 1 | ok | 8.74e-15 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=4096 group=128 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=4096 group=128 dtype=bf16 M=16` | - | 1 | ok | 4.38e-15 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=4096 group=128 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=4096 group=128 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=4096 group=128 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=4096 group=128 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=4096 group=128 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=17408 group=128 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=17408 group=128 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=17408 group=128 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=17408 group=128 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=17408 group=128 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=17408 group=128 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=17408 group=128 dtype=bf16 M=8` | - | 1 | ok | 2.17e-15 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=17408 group=128 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=17408 group=128 dtype=bf16 M=16` | - | 1 | ok | 2.05e-15 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=17408 group=128 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=17408 group=128 dtype=bf16 M=32` | - | 1 | ok | 7.41e-07 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=17408 group=128 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | device | `n=17408 group=128 dtype=bf16 M=64` | - | 1 | ok | 1.02e-15 | 1e-06 | +| `quant_act_fp8` | `ref_quant_act_fp8` | libref | host | `n=17408 group=128 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 1e-06 | +| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=1280 K=5120 dtype=bf16 M=1 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 | +| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=1280 K=5120 dtype=bf16 M=1 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 | +| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=1280 K=5120 dtype=bf16 M=2 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 5.38e-13 | 8e-03 | +| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=1280 K=5120 dtype=bf16 M=2 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 | +| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=1280 K=5120 dtype=bf16 M=4 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 1.22e-06 | 8e-03 | +| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=1280 K=5120 dtype=bf16 M=4 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 | +| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=1280 K=5120 dtype=bf16 M=8 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 1.96e-09 | 8e-03 | +| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=1280 K=5120 dtype=bf16 M=8 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 | +| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=1280 K=5120 dtype=bf16 M=16 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 3.50e-08 | 8e-03 | +| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=1280 K=5120 dtype=bf16 M=16 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 | +| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | device | `N=1280 K=5120 dtype=bf16 M=17 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 3.62e-07 | 8e-03 | +| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=1280 K=5120 dtype=bf16 M=17 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 | +| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | device | `N=1280 K=5120 dtype=bf16 M=34 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 1.88e-07 | 8e-03 | +| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=1280 K=5120 dtype=bf16 M=34 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 | +| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | device | `N=1280 K=5120 dtype=bf16 M=64 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 1.56e-07 | 8e-03 | +| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=1280 K=5120 dtype=bf16 M=64 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=4096 K=5120 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=4096 K=5120 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=4096 K=5120 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 8.03e-12 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=4096 K=5120 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=4096 K=5120 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 3.96e-09 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=4096 K=5120 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=4096 K=5120 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 7.55e-09 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=4096 K=5120 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=4096 K=5120 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 7.63e-09 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=4096 K=5120 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=4096 K=5120 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 5.48e-14 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=4096 K=5120 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=4096 K=5120 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 3.41e-09 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=4096 K=5120 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=4096 K=5120 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 1.58e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=4096 K=5120 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=4096 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 2.13e-09 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=4096 group=128 dtype=fp8a8 M=1` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=4096 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 1.71e-07 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=4096 group=128 dtype=fp8a8 M=2` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=4096 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 1.44e-07 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=4096 group=128 dtype=fp8a8 M=4` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=4096 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 1.74e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=4096 group=128 dtype=fp8a8 M=8` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=4096 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=4096 group=128 dtype=fp8a8 M=9` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=4096 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 2.59e-12 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=4096 group=128 dtype=fp8a8 M=18` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=4096 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 4.58e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=4096 group=128 dtype=fp8a8 M=36` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | device | `N=5120 K=4096 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 6.74e-08 | 3e-02 | +| `gemm_nt_q` | `ref_gemm_nt_q` | libref | host | `N=5120 K=4096 group=128 dtype=fp8a8 M=64` | - | 1 | ok | 0.00e+00 | 3e-02 | +| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=1` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=1` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=2` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=2` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=8` | - | 1 | ok | 8.88e-11 | 2e-02 | +| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=8` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=16` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=16` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=32` | - | 1 | ok | 2.19e-08 | 2e-02 | +| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=32` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `rope` | `rope_bf16` | libr4d | device | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=64` | - | 1 | ok | 2.71e-10 | 2e-02 | +| `rope` | `ref_rope` | libref | host | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `silu_mul` | `silu_mul_bf16` | libr4d | device | `n=17408 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `silu_mul` | `ref_silu_mul` | libref | host | `n=17408 dtype=bf16 M=1` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `silu_mul` | `silu_mul_bf16` | libr4d | device | `n=17408 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `silu_mul` | `ref_silu_mul` | libref | host | `n=17408 dtype=bf16 M=2` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `silu_mul` | `silu_mul_bf16` | libr4d | device | `n=17408 dtype=bf16 M=4` | - | 1 | ok | 3.60e-08 | 6e-03 | +| `silu_mul` | `ref_silu_mul` | libref | host | `n=17408 dtype=bf16 M=4` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `silu_mul` | `silu_mul_bf16` | libr4d | device | `n=17408 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `silu_mul` | `ref_silu_mul` | libref | host | `n=17408 dtype=bf16 M=8` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `silu_mul` | `silu_mul_bf16` | libr4d | device | `n=17408 dtype=bf16 M=16` | - | 1 | ok | 9.74e-09 | 6e-03 | +| `silu_mul` | `ref_silu_mul` | libref | host | `n=17408 dtype=bf16 M=16` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `silu_mul` | `silu_mul_bf16` | libr4d | device | `n=17408 dtype=bf16 M=32` | - | 1 | ok | 2.45e-08 | 6e-03 | +| `silu_mul` | `ref_silu_mul` | libref | host | `n=17408 dtype=bf16 M=32` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `silu_mul` | `silu_mul_bf16` | libr4d | device | `n=17408 dtype=bf16 M=64` | - | 1 | ok | 7.13e-09 | 6e-03 | +| `silu_mul` | `ref_silu_mul` | libref | host | `n=17408 dtype=bf16 M=64` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `gather_rows` | `gather_rows_bf16` | libr4d | device | `n=5120 dtype=bf16 M=56` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `gather_rows` | `ref_gather_rows` | libref | host | `n=5120 dtype=bf16 M=56` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `row_topk` | `rowtopk_bf16` | libr4d | device | `N=248320 R=16 dtype=bf16 M=1 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `row_topk` | `ref_row_topk` | libref | host | `N=248320 R=16 dtype=bf16 M=1 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `row_topk` | `rowtopk_bf16` | libr4d | device | `N=248320 R=16 dtype=bf16 M=2 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `row_topk` | `ref_row_topk` | libref | host | `N=248320 R=16 dtype=bf16 M=2 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `row_topk` | `rowtopk_bf16` | libr4d | device | `N=248320 R=16 dtype=bf16 M=4 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `row_topk` | `ref_row_topk` | libref | host | `N=248320 R=16 dtype=bf16 M=4 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `row_topk` | `rowtopk_bf16` | libr4d | device | `N=248320 R=16 dtype=bf16 M=8 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `row_topk` | `ref_row_topk` | libref | host | `N=248320 R=16 dtype=bf16 M=8 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `row_topk` | `rowtopk_bf16` | libr4d | device | `N=248320 R=16 dtype=bf16 M=16 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `row_topk` | `ref_row_topk` | libref | host | `N=248320 R=16 dtype=bf16 M=16 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `row_topk` | `rowtopk_bf16` | libr4d | device | `N=248320 R=16 dtype=bf16 M=32 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `row_topk` | `ref_row_topk` | libref | host | `N=248320 R=16 dtype=bf16 M=32 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `row_topk` | `rowtopk_bf16` | libr4d | device | `N=248320 R=16 dtype=bf16 M=56 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `row_topk` | `ref_row_topk` | libref | host | `N=248320 R=16 dtype=bf16 M=56 nch=0 pt1=8` | - | 1 | ok | 0.00e+00 | 6e-03 | +| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=256 K=5120 dtype=bf16 M=1 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 | +| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=256 K=5120 dtype=bf16 M=1 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 | +| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=256 K=5120 dtype=bf16 M=2 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 4.58e-08 | 8e-03 | +| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=256 K=5120 dtype=bf16 M=2 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 | +| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=256 K=5120 dtype=bf16 M=4 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 | +| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=256 K=5120 dtype=bf16 M=4 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 | +| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=256 K=5120 dtype=bf16 M=8 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 | +| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=256 K=5120 dtype=bf16 M=8 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 | +| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | device | `N=256 K=5120 dtype=bf16 M=16 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 8.65e-05 | 8e-03 | +| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=256 K=5120 dtype=bf16 M=16 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 | +| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | device | `N=256 K=5120 dtype=bf16 M=17 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 1.75e-11 | 8e-03 | +| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=256 K=5120 dtype=bf16 M=17 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 | +| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | device | `N=256 K=5120 dtype=bf16 M=34 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 4.00e-06 | 8e-03 | +| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=256 K=5120 dtype=bf16 M=34 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 | +| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | device | `N=256 K=5120 dtype=bf16 M=56 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 3.03e-07 | 8e-03 | +| `gemm_nt` | `ref_gemm_nt` | libref | host | `N=256 K=5120 dtype=bf16 M=56 wv=1 sk=0 mb=0 npw=1 nt=1` | - | 1 | ok | 0.00e+00 | 8e-03 | +| `sample_penalties` | `sample_penalties_f32` | libr4d | device | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_penalties` | `ref_sample_penalties` | libref | host | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_penalties` | `sample_penalties_f32` | libr4d | device | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_penalties` | `ref_sample_penalties` | libref | host | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_penalties` | `sample_penalties_f32` | libr4d | device | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_penalties` | `ref_sample_penalties` | libref | host | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_penalties` | `sample_penalties_f32` | libr4d | device | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_penalties` | `ref_sample_penalties` | libref | host | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_penalties` | `sample_penalties_f32` | libr4d | device | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_penalties` | `ref_sample_penalties` | libref | host | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_penalties` | `sample_penalties_f32` | libr4d | device | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_penalties` | `ref_sample_penalties` | libref | host | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_penalties` | `sample_penalties_f32` | libr4d | device | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_penalties` | `ref_sample_penalties` | libref | host | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_dry` | `sample_dry_f32` | libr4d | device | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_dry` | `ref_sample_dry` | libref | host | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_dry` | `sample_dry_f32` | libr4d | device | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_dry` | `ref_sample_dry` | libref | host | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_dry` | `sample_dry_f32` | libr4d | device | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_dry` | `ref_sample_dry` | libref | host | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_dry` | `sample_dry_f32` | libr4d | device | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_dry` | `ref_sample_dry` | libref | host | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_dry` | `sample_dry_f32` | libr4d | device | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_dry` | `ref_sample_dry` | libref | host | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_dry` | `sample_dry_f32` | libr4d | device | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_dry` | `ref_sample_dry` | libref | host | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_dry` | `sample_dry_f32` | libr4d | device | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_dry` | `ref_sample_dry` | libref | host | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_temp` | `sample_temp_f32` | libr4d | device | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_temp` | `ref_sample_temp` | libref | host | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_temp` | `sample_temp_f32` | libr4d | device | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_temp` | `ref_sample_temp` | libref | host | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_temp` | `sample_temp_f32` | libr4d | device | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_temp` | `ref_sample_temp` | libref | host | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_temp` | `sample_temp_f32` | libr4d | device | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_temp` | `ref_sample_temp` | libref | host | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_temp` | `sample_temp_f32` | libr4d | device | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_temp` | `ref_sample_temp` | libref | host | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_temp` | `sample_temp_f32` | libr4d | device | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_temp` | `ref_sample_temp` | libref | host | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_temp` | `sample_temp_f32` | libr4d | device | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_temp` | `ref_sample_temp` | libref | host | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_mask` | `sample_mask_f32` | libr4d | device | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_mask` | `ref_sample_mask` | libref | host | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_mask` | `sample_mask_f32` | libr4d | device | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_mask` | `ref_sample_mask` | libref | host | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_mask` | `sample_mask_f32` | libr4d | device | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_mask` | `ref_sample_mask` | libref | host | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_mask` | `sample_mask_f32` | libr4d | device | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_mask` | `ref_sample_mask` | libref | host | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_mask` | `sample_mask_f32` | libr4d | device | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_mask` | `ref_sample_mask` | libref | host | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_mask` | `sample_mask_f32` | libr4d | device | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_mask` | `ref_sample_mask` | libref | host | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_mask` | `sample_mask_f32` | libr4d | device | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_mask` | `ref_sample_mask` | libref | host | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_topk` | `sample_topk_f32` | libr4d | device | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_topk` | `ref_sample_topk` | libref | host | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_topk` | `sample_topk_f32` | libr4d | device | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_topk` | `ref_sample_topk` | libref | host | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_topk` | `sample_topk_f32` | libr4d | device | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_topk` | `ref_sample_topk` | libref | host | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_topk` | `sample_topk_f32` | libr4d | device | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_topk` | `ref_sample_topk` | libref | host | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_topk` | `sample_topk_f32` | libr4d | device | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_topk` | `ref_sample_topk` | libref | host | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_topk` | `sample_topk_f32` | libr4d | device | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_topk` | `ref_sample_topk` | libref | host | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_topk` | `sample_topk_f32` | libr4d | device | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_topk` | `ref_sample_topk` | libref | host | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_argmax` | `sample_argmax_f32` | libr4d | device | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_argmax` | `ref_sample_argmax` | libref | host | `n_vocab=248320 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_argmax` | `sample_argmax_f32` | libr4d | device | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_argmax` | `ref_sample_argmax` | libref | host | `n_vocab=248320 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_argmax` | `sample_argmax_f32` | libr4d | device | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_argmax` | `ref_sample_argmax` | libref | host | `n_vocab=248320 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_argmax` | `sample_argmax_f32` | libr4d | device | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_argmax` | `ref_sample_argmax` | libref | host | `n_vocab=248320 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_argmax` | `sample_argmax_f32` | libr4d | device | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_argmax` | `ref_sample_argmax` | libref | host | `n_vocab=248320 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_argmax` | `sample_argmax_f32` | libr4d | device | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_argmax` | `ref_sample_argmax` | libref | host | `n_vocab=248320 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_argmax` | `sample_argmax_f32` | libr4d | device | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_argmax` | `ref_sample_argmax` | libref | host | `n_vocab=248320 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_topp` | `sample_topp_f32` | libr4d | device | `n_cand=1024 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_topp` | `ref_sample_topp` | libref | host | `n_cand=1024 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_topp` | `sample_topp_f32` | libr4d | device | `n_cand=1024 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_topp` | `ref_sample_topp` | libref | host | `n_cand=1024 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_topp` | `sample_topp_f32` | libr4d | device | `n_cand=1024 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_topp` | `ref_sample_topp` | libref | host | `n_cand=1024 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_topp` | `sample_topp_f32` | libr4d | device | `n_cand=1024 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_topp` | `ref_sample_topp` | libref | host | `n_cand=1024 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_topp` | `sample_topp_f32` | libr4d | device | `n_cand=1024 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_topp` | `ref_sample_topp` | libref | host | `n_cand=1024 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_topp` | `sample_topp_f32` | libr4d | device | `n_cand=1024 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_topp` | `ref_sample_topp` | libref | host | `n_cand=1024 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_topp` | `sample_topp_f32` | libr4d | device | `n_cand=1024 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_topp` | `ref_sample_topp` | libref | host | `n_cand=1024 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_minp` | `sample_minp_f32` | libr4d | device | `n_cand=1024 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_minp` | `ref_sample_minp` | libref | host | `n_cand=1024 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_minp` | `sample_minp_f32` | libr4d | device | `n_cand=1024 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_minp` | `ref_sample_minp` | libref | host | `n_cand=1024 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_minp` | `sample_minp_f32` | libr4d | device | `n_cand=1024 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_minp` | `ref_sample_minp` | libref | host | `n_cand=1024 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_minp` | `sample_minp_f32` | libr4d | device | `n_cand=1024 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_minp` | `ref_sample_minp` | libref | host | `n_cand=1024 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_minp` | `sample_minp_f32` | libr4d | device | `n_cand=1024 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_minp` | `ref_sample_minp` | libref | host | `n_cand=1024 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_minp` | `sample_minp_f32` | libr4d | device | `n_cand=1024 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_minp` | `ref_sample_minp` | libref | host | `n_cand=1024 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_minp` | `sample_minp_f32` | libr4d | device | `n_cand=1024 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_minp` | `ref_sample_minp` | libref | host | `n_cand=1024 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_typical` | `sample_typical_f32` | libr4d | device | `n_cand=1024 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_typical` | `ref_sample_typical` | libref | host | `n_cand=1024 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_typical` | `sample_typical_f32` | libr4d | device | `n_cand=1024 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_typical` | `ref_sample_typical` | libref | host | `n_cand=1024 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_typical` | `sample_typical_f32` | libr4d | device | `n_cand=1024 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_typical` | `ref_sample_typical` | libref | host | `n_cand=1024 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_typical` | `sample_typical_f32` | libr4d | device | `n_cand=1024 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_typical` | `ref_sample_typical` | libref | host | `n_cand=1024 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_typical` | `sample_typical_f32` | libr4d | device | `n_cand=1024 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_typical` | `ref_sample_typical` | libref | host | `n_cand=1024 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_typical` | `sample_typical_f32` | libr4d | device | `n_cand=1024 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_typical` | `ref_sample_typical` | libref | host | `n_cand=1024 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_typical` | `sample_typical_f32` | libr4d | device | `n_cand=1024 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_typical` | `ref_sample_typical` | libref | host | `n_cand=1024 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_xtc` | `sample_xtc_f32` | libr4d | device | `n_cand=1024 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_xtc` | `ref_sample_xtc` | libref | host | `n_cand=1024 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_xtc` | `sample_xtc_f32` | libr4d | device | `n_cand=1024 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_xtc` | `ref_sample_xtc` | libref | host | `n_cand=1024 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_xtc` | `sample_xtc_f32` | libr4d | device | `n_cand=1024 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_xtc` | `ref_sample_xtc` | libref | host | `n_cand=1024 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_xtc` | `sample_xtc_f32` | libr4d | device | `n_cand=1024 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_xtc` | `ref_sample_xtc` | libref | host | `n_cand=1024 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_xtc` | `sample_xtc_f32` | libr4d | device | `n_cand=1024 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_xtc` | `ref_sample_xtc` | libref | host | `n_cand=1024 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_xtc` | `sample_xtc_f32` | libr4d | device | `n_cand=1024 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_xtc` | `ref_sample_xtc` | libref | host | `n_cand=1024 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_xtc` | `sample_xtc_f32` | libr4d | device | `n_cand=1024 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_xtc` | `ref_sample_xtc` | libref | host | `n_cand=1024 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_pick` | `sample_pick_f32` | libr4d | device | `n_cand=1024 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_pick` | `ref_sample_pick` | libref | host | `n_cand=1024 M=1` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_pick` | `sample_pick_f32` | libr4d | device | `n_cand=1024 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_pick` | `ref_sample_pick` | libref | host | `n_cand=1024 M=2` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_pick` | `sample_pick_f32` | libr4d | device | `n_cand=1024 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_pick` | `ref_sample_pick` | libref | host | `n_cand=1024 M=4` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_pick` | `sample_pick_f32` | libr4d | device | `n_cand=1024 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_pick` | `ref_sample_pick` | libref | host | `n_cand=1024 M=8` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_pick` | `sample_pick_f32` | libr4d | device | `n_cand=1024 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_pick` | `ref_sample_pick` | libref | host | `n_cand=1024 M=16` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_pick` | `sample_pick_f32` | libr4d | device | `n_cand=1024 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_pick` | `ref_sample_pick` | libref | host | `n_cand=1024 M=32` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_pick` | `sample_pick_f32` | libr4d | device | `n_cand=1024 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 | +| `sample_pick` | `ref_sample_pick` | libref | host | `n_cand=1024 M=64` | - | 1 | ok | 0.00e+00 | 2e-02 | + +## Speed + +> **These times rank kernels; they do not size a roofline.** Every launch in a timed +> run reuses one set of operands, so a weight that fits in the last-level cache is +> read from cache after the first launch, and a bandwidth-bound kernel can read +> several times its true rate. Ranking two kernels at one shape is what these times are +> for; a roofline is not. +> +> `operands` is the total the case ALLOCATED, not what the kernel read: a gather +> touches M rows of a table, not the table. Dividing the two columns produces a +> bandwidth figure this tool cannot stand behind, which is why it does not print one. +> +> The `libref` column is ONE untimed-warmup call, not a median of reps: it is there to +> show the order of magnitude a reference implementation costs, which is the reason the +> device kernels exist. It is not a measurement of a library anyone tunes. +> +> `spread` is how far the fastest and slowest timed rep were apart, as a percent of +> the median. Each case is warmed with untimed launches first, because these cards sit in +> a low-power state whenever nothing is running and the ramp back up is longer than a +> short timed window -- but a warm-up is not a guarantee, and a wide spread is what marks +> a number the card was still ramping through. Read a row with a large one as an order of +> magnitude, not a measurement. + +| op | kernel | library | geometry | us | spread | libref us | x | operands | +|---|---|---|---|---|---|---|---|---| +| `logits_gemm` | `logits_gemm_fp8` | libr4d | `n_vocab=248320 n_embd=5120 dtype=bf16 M=64` | 3712.35 | 0% | - | - | 2.43 GiB | +| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=512` | 2804.57 | 0% | - | - | 1.52 GiB | +| `logits_gemm` | `logits_gemm_fp8` | libr4d | `n_vocab=248320 n_embd=5120 dtype=bf16 M=32` | 2475.88 | 0% | - | - | 2.40 GiB | +| `logits_gemm` | `logits_gemm_fp8` | libr4d | `n_vocab=248320 n_embd=5120 dtype=bf16 M=16` | 2142.16 | 0% | - | - | 2.38 GiB | +| `logits_gemm` | `logits_gemm_fp8` | libr4d | `n_vocab=248320 n_embd=5120 dtype=bf16 M=8` | 2114.68 | 0% | - | - | 2.38 GiB | +| `logits_gemm` | `logits_gemm_fp8` | libr4d | `n_vocab=248320 n_embd=5120 dtype=bf16 M=4` | 2092.86 | 0% | - | - | 2.37 GiB | +| `logits_gemm` | `logits_gemm_fp8` | libr4d | `n_vocab=248320 n_embd=5120 dtype=bf16 M=2` | 2075.97 | 0% | - | - | 2.37 GiB | +| `logits_gemm` | `logits_gemm_fp8` | libr4d | `n_vocab=248320 n_embd=5120 dtype=bf16 M=1` | 2038.46 | 0% | - | - | 2.37 GiB | +| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=256` | 1406.26 | 0% | - | - | 779.05 MiB | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 M=512` | 1358.00 | 1% | - | - | 206.60 MiB | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 M=260` | 1031.50 | 0% | - | - | 188.60 MiB | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=5120 K=25600 group=128 dtype=fp8a8 M=512` | 1002.50 | 1% | - | - | 142.91 MiB | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=5120 K=25600 group=128 dtype=fp8a8 M=260` | 887.98 | 3% | - | - | 134.10 MiB | +| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=128` | 706.45 | 0% | - | - | 389.52 MiB | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=5120 K=17408 group=128 dtype=fp8a8 M=512` | 679.02 | 0% | - | - | 98.78 MiB | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 M=130` | 675.48 | 1% | - | - | 179.31 MiB | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=16384 K=5120 group=128 dtype=fp8a8 M=512` | 643.75 | 0% | - | - | 98.59 MiB | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=5120 K=17408 group=128 dtype=fp8a8 M=260` | 602.97 | 0% | - | - | 92.00 MiB | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=5120 K=25600 group=128 dtype=fp8a8 M=130` | 587.22 | 1% | - | - | 129.56 MiB | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=16384 K=5120 group=128 dtype=fp8a8 M=260` | 507.22 | 1% | - | - | 89.44 MiB | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=12288 K=5120 group=128 dtype=fp8a8 M=512` | 473.86 | 0% | - | - | 74.59 MiB | +| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 conv_width=4 q_len=512` | 456.53 | 0% | - | - | 30.12 MiB | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=5120 K=25600 group=128 dtype=fp8a8 M=65` | 416.22 | 0% | - | - | 127.29 MiB | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=5120 K=17408 group=128 dtype=fp8a8 M=130` | 391.21 | 3% | - | - | 88.51 MiB | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 M=65` | 386.91 | 1% | - | - | 174.66 MiB | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=12288 K=5120 group=128 dtype=fp8a8 M=260` | 361.39 | 0% | - | - | 67.41 MiB | +| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=64` | 353.11 | 0% | - | - | 194.76 MiB | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=16384 K=5120 group=128 dtype=fp8a8 M=130` | 334.85 | 1% | - | - | 84.73 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 M=64` | 322.94 | 2% | - | - | 174.59 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 M=36` | 319.42 | 0% | - | - | 172.59 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 M=18` | 304.22 | 0% | - | - | 171.31 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 M=9` | 303.48 | 0% | - | - | 170.66 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 M=8` | 302.87 | 0% | - | - | 170.59 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 M=4` | 299.38 | 0% | - | - | 170.31 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 M=2` | 297.78 | 0% | - | - | 170.16 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=34816 K=5120 group=128 dtype=fp8a8 M=1` | 296.97 | 0% | - | - | 170.09 MiB | +| `sample_topk` | `sample_topk_f32` | libr4d | `n_vocab=248320 M=64` | 296.07 | 0% | - | - | 60.69 MiB | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=5120 K=17408 group=128 dtype=fp8a8 M=65` | 281.73 | 0% | - | - | 86.76 MiB | +| `attn_paged` | `attn_prefill_h256_gqa6_bf16kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=512` | 265.83 | 2% | - | - | 14.00 MiB | +| `sample_topk` | `sample_topk_f32` | libr4d | `n_vocab=248320 M=32` | 253.05 | 0% | - | - | 30.35 MiB | +| `sample_topk` | `sample_topk_f32` | libr4d | `n_vocab=248320 M=16` | 252.63 | 0% | - | - | 15.17 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=25600 group=128 dtype=fp8a8 M=64` | 240.22 | 0% | - | - | 127.25 MiB | +| `attn_paged` | `attn_prefill_h256_gqa6_bf16kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=272` | 236.02 | 0% | - | - | 7.44 MiB | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=12288 K=5120 group=128 dtype=fp8a8 M=130` | 229.21 | 2% | - | - | 63.71 MiB | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=5120 K=6144 group=128 dtype=fp8a8 M=512` | 221.47 | 0% | - | - | 38.10 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=25600 group=128 dtype=fp8a8 M=36` | 219.95 | 0% | - | - | 126.27 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=25600 group=128 dtype=fp8a8 M=18` | 219.81 | 0% | - | - | 125.64 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=25600 group=128 dtype=fp8a8 M=9` | 213.95 | 0% | - | - | 125.33 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=25600 group=128 dtype=fp8a8 M=8` | 213.66 | 0% | - | - | 125.29 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=25600 group=128 dtype=fp8a8 M=4` | 213.24 | 0% | - | - | 125.16 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=25600 group=128 dtype=fp8a8 M=2` | 212.55 | 0% | - | - | 125.09 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=25600 group=128 dtype=fp8a8 M=1` | 212.21 | 0% | - | - | 125.05 MiB | +| `attn_paged` | `attn_prefill_h256_gqa6_bf16kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=136` | 211.11 | 1% | - | - | 3.75 MiB | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=16384 K=5120 group=128 dtype=fp8a8 M=65` | 209.33 | 0% | - | - | 82.37 MiB | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=5120 K=6144 group=128 dtype=fp8a8 M=260` | 206.42 | 1% | - | - | 34.11 MiB | +| `attn_paged` | `attn_prefill_h256_gqa6_bf16kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=68` | 195.89 | 8% | - | - | 1.91 MiB | +| `attn_paged` | `attn_prefill_h256_gqa6_bf16kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=34` | 195.70 | 2% | - | - | 1008.02 KiB | +| `attn_paged` | `attn_prefill_h256_gqa6_bf16kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=11` | 195.68 | 1% | - | - | 328.01 KiB | +| `attn_paged` | `attn_prefill_h256_gqa6_bf16kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=16` | 195.59 | 4% | - | - | 448.01 KiB | +| `attn_paged` | `attn_prefill_h256_gqa6_bf16kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=17` | 195.42 | 4% | - | - | 536.01 KiB | +| `sample_topk` | `sample_topk_f32` | libr4d | `n_vocab=248320 M=1` | 189.89 | 0% | - | - | 971.09 KiB | +| `sample_topk` | `sample_topk_f32` | libr4d | `n_vocab=248320 M=8` | 189.73 | 0% | - | - | 7.59 MiB | +| `sample_topk` | `sample_topk_f32` | libr4d | `n_vocab=248320 M=4` | 187.49 | 0% | - | - | 3.79 MiB | +| `sample_topk` | `sample_topk_f32` | libr4d | `n_vocab=248320 M=2` | 186.34 | 0% | - | - | 1.90 MiB | +| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 conv_width=4 q_len=256` | 176.56 | 0% | - | - | 15.12 MiB | +| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=32` | 175.39 | 0% | - | - | 97.38 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=17408 group=128 dtype=fp8a8 M=64` | 169.57 | 0% | - | - | 86.73 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=17408 group=128 dtype=fp8a8 M=36` | 151.93 | 0% | - | - | 85.98 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=16384 K=5120 group=128 dtype=fp8a8 M=64` | 150.40 | 1% | - | - | 82.33 MiB | +| `row_topk` | `rowtopk_bf16` | libr4d | `N=248320 R=16 dtype=bf16 M=56 nch=0 pt1=8` | 148.94 | 1% | - | - | 26.54 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=17408 group=128 dtype=fp8a8 M=18` | 148.54 | 0% | - | - | 85.49 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=17408 group=128 dtype=fp8a8 M=9` | 145.17 | 0% | - | - | 85.25 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=17408 group=128 dtype=fp8a8 M=8` | 145.02 | 0% | - | - | 85.23 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=16384 K=5120 group=128 dtype=fp8a8 M=36` | 142.37 | 0% | - | - | 81.32 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=17408 group=128 dtype=fp8a8 M=4` | 142.36 | 0% | - | - | 85.12 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=17408 group=128 dtype=fp8a8 M=2` | 139.57 | 0% | - | - | 85.06 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=17408 group=128 dtype=fp8a8 M=1` | 139.26 | 0% | - | - | 85.04 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=16384 K=5120 group=128 dtype=fp8a8 M=18` | 134.58 | 1% | - | - | 80.66 MiB | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=5120 K=6144 group=128 dtype=fp8a8 M=130` | 134.57 | 4% | - | - | 32.06 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=16384 K=5120 group=128 dtype=fp8a8 M=9` | 132.75 | 0% | - | - | 80.34 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=16384 K=5120 group=128 dtype=fp8a8 M=8` | 132.71 | 1% | - | - | 80.30 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=16384 K=5120 group=128 dtype=fp8a8 M=4` | 130.76 | 0% | - | - | 80.15 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=16384 K=5120 group=128 dtype=fp8a8 M=2` | 130.05 | 0% | - | - | 80.08 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=16384 K=5120 group=128 dtype=fp8a8 M=1` | 129.22 | 1% | - | - | 80.05 MiB | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=12288 K=5120 group=128 dtype=fp8a8 M=65` | 118.06 | 0% | - | - | 61.86 MiB | +| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | `head_k=128 head_v=128 scale=0.0883883 M=512 chunk=64` | 105.41 | 0% | - | - | 25.19 MiB | +| `sample_pick` | `sample_pick_f32` | libr4d | `n_cand=1024 M=64` | 102.31 | 0% | - | - | 518.25 KiB | +| `sample_pick` | `sample_pick_f32` | libr4d | `n_cand=1024 M=16` | 101.77 | 0% | - | - | 129.56 KiB | +| `row_topk` | `rowtopk_bf16` | libr4d | `N=248320 R=16 dtype=bf16 M=32 nch=0 pt1=8` | 101.14 | 0% | - | - | 15.16 MiB | +| `sample_pick` | `sample_pick_f32` | libr4d | `n_cand=1024 M=8` | 101.04 | 0% | - | - | 64.78 KiB | +| `sample_pick` | `sample_pick_f32` | libr4d | `n_cand=1024 M=1` | 98.74 | 0% | - | - | 8.10 KiB | +| `sample_pick` | `sample_pick_f32` | libr4d | `n_cand=1024 M=32` | 96.05 | 0% | - | - | 259.12 KiB | +| `sample_pick` | `sample_pick_f32` | libr4d | `n_cand=1024 M=4` | 95.44 | 0% | - | - | 32.39 KiB | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=5120 K=6144 group=128 dtype=fp8a8 M=65` | 94.74 | 0% | - | - | 31.03 MiB | +| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 conv_width=4 q_len=128` | 86.13 | 0% | - | - | 7.62 MiB | +| `sample_typical` | `sample_typical_f32` | libr4d | `n_cand=1024 M=32` | 77.72 | 0% | - | - | 259.00 KiB | +| `sample_typical` | `sample_typical_f32` | libr4d | `n_cand=1024 M=2` | 74.34 | 0% | - | - | 16.19 KiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=12288 K=5120 group=128 dtype=fp8a8 M=64` | 70.24 | 2% | - | - | 61.83 MiB | +| `row_topk` | `rowtopk_bf16` | libr4d | `N=248320 R=16 dtype=bf16 M=16 nch=0 pt1=8` | 69.07 | 20% | - | - | 7.58 MiB | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=1024 K=5120 group=128 dtype=fp8a8 M=260` | 68.43 | 1% | - | - | 6.82 MiB | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=1024 K=5120 group=128 dtype=fp8a8 M=130` | 65.02 | 0% | - | - | 5.91 MiB | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=1024 K=5120 group=128 dtype=fp8a8 M=65` | 62.33 | 0% | - | - | 5.45 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=12288 K=5120 group=128 dtype=fp8a8 M=36` | 61.12 | 2% | - | - | 61.03 MiB | +| `sample_pick` | `sample_pick_f32` | libr4d | `n_cand=1024 M=2` | 60.10 | 0% | - | - | 16.20 KiB | +| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=16` | 59.40 | 1% | - | - | 48.69 MiB | +| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | `head_k=128 head_v=128 scale=0.0883883 M=256 chunk=64` | 57.93 | 1% | - | - | 15.59 MiB | +| `row_topk` | `rowtopk_bf16` | libr4d | `N=248320 R=16 dtype=bf16 M=8 nch=0 pt1=8` | 54.04 | 0% | - | - | 3.79 MiB | +| `sample_typical` | `sample_typical_f32` | libr4d | `n_cand=1024 M=64` | 53.11 | 0% | - | - | 518.00 KiB | +| `sample_typical` | `sample_typical_f32` | libr4d | `n_cand=1024 M=16` | 50.60 | 0% | - | - | 129.50 KiB | +| `gemm_nt_q` | `gemm_fp8a8_tiled` | libr4d | `N=1024 K=5120 group=128 dtype=fp8a8 M=512` | 49.01 | 0% | - | - | 8.58 MiB | +| `sample_topp` | `sample_topp_f32` | libr4d | `n_cand=1024 M=32` | 47.65 | 0% | - | - | 259.00 KiB | +| `row_topk` | `rowtopk_bf16` | libr4d | `N=248320 R=16 dtype=bf16 M=4 nch=0 pt1=8` | 46.87 | 0% | - | - | 1.90 MiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=25600 group=128 dtype=bf16 M=512` | 46.44 | 2% | - | - | 37.89 MiB | +| `row_topk` | `rowtopk_bf16` | libr4d | `N=248320 R=16 dtype=bf16 M=1 nch=0 pt1=8` | 46.33 | 0% | - | - | 485.25 KiB | +| `sample_argmax` | `sample_argmax_f32` | libr4d | `n_vocab=248320 M=64` | 46.00 | 1% | - | - | 60.63 MiB | +| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 conv_width=4 q_len=64` | 45.64 | 0% | - | - | 3.87 MiB | +| `row_topk` | `rowtopk_bf16` | libr4d | `N=248320 R=16 dtype=bf16 M=2 nch=0 pt1=8` | 45.49 | 0% | - | - | 970.50 KiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=6144 group=128 dtype=fp8a8 M=64` | 44.85 | 1% | - | - | 31.02 MiB | +| `sample_topp` | `sample_topp_f32` | libr4d | `n_cand=1024 M=1` | 44.54 | 0% | - | - | 8.09 KiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=12288 K=5120 group=128 dtype=fp8a8 M=18` | 44.18 | 0% | - | - | 60.52 MiB | +| `sample_topp` | `sample_topp_f32` | libr4d | `n_cand=1024 M=64` | 43.76 | 0% | - | - | 518.00 KiB | +| `sample_topp` | `sample_topp_f32` | libr4d | `n_cand=1024 M=4` | 43.46 | 0% | - | - | 32.38 KiB | +| `sample_topp` | `sample_topp_f32` | libr4d | `n_cand=1024 M=8` | 42.74 | 0% | - | - | 64.75 KiB | +| `sample_topp` | `sample_topp_f32` | libr4d | `n_cand=1024 M=16` | 42.67 | 0% | - | - | 129.50 KiB | +| `sample_temp` | `sample_temp_f32` | libr4d | `n_vocab=248320 M=64` | 42.62 | 0% | - | - | 60.63 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=12288 K=5120 group=128 dtype=fp8a8 M=8` | 41.39 | 0% | - | - | 60.24 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=12288 K=5120 group=128 dtype=fp8a8 M=9` | 41.36 | 1% | - | - | 60.26 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=12288 K=5120 group=128 dtype=fp8a8 M=4` | 40.72 | 1% | - | - | 60.12 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=12288 K=5120 group=128 dtype=fp8a8 M=2` | 40.67 | 1% | - | - | 60.06 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=12288 K=5120 group=128 dtype=fp8a8 M=1` | 40.47 | 1% | - | - | 60.04 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=6144 group=128 dtype=fp8a8 M=36` | 39.60 | 1% | - | - | 30.57 MiB | +| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 chunk=64 conv_width=4 M=512` | 36.38 | 1% | - | - | 20.42 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=4096 K=5120 group=128 dtype=fp8a8 M=64` | 36.37 | 1% | - | - | 20.82 MiB | +| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | `head_k=128 head_v=128 scale=0.0883883 M=128 chunk=64` | 33.63 | 0% | - | - | 10.80 MiB | +| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=8` | 33.08 | 0% | - | - | 24.35 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=4096 group=128 dtype=fp8a8 M=64` | 32.38 | 0% | - | - | 20.89 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=4096 K=5120 group=128 dtype=fp8a8 M=36` | 32.33 | 0% | - | - | 20.46 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=6144 group=128 dtype=fp8a8 M=18` | 31.25 | 1% | - | - | 30.29 MiB | +| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 chunk=64 conv_width=4 M=256` | 30.91 | 0% | - | - | 10.28 MiB | +| `sample_typical` | `sample_typical_f32` | libr4d | `n_cand=1024 M=8` | 30.55 | 0% | - | - | 64.75 KiB | +| `sample_typical` | `sample_typical_f32` | libr4d | `n_cand=1024 M=4` | 30.19 | 0% | - | - | 32.38 KiB | +| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 chunk=64 conv_width=4 M=64` | 29.90 | 0% | - | - | 2.67 MiB | +| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 chunk=64 conv_width=4 M=128` | 29.84 | 0% | - | - | 5.21 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=6144 group=128 dtype=fp8a8 M=9` | 28.58 | 0% | - | - | 30.15 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=6144 group=128 dtype=fp8a8 M=8` | 28.40 | 2% | - | - | 30.13 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=4096 group=128 dtype=fp8a8 M=36` | 28.35 | 0% | - | - | 20.50 MiB | +| `sample_temp` | `sample_temp_f32` | libr4d | `n_vocab=248320 M=32` | 28.20 | 1% | - | - | 30.32 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=6144 group=128 dtype=fp8a8 M=4` | 28.06 | 1% | - | - | 30.07 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=6144 group=128 dtype=fp8a8 M=1` | 27.86 | 1% | - | - | 30.02 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=6144 group=128 dtype=fp8a8 M=2` | 27.73 | 1% | - | - | 30.04 MiB | +| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | `N=96 K=5120 dtype=bf16 M=512 wv=1 sk=0 mb=0 npw=1 nt=1` | 26.76 | 1% | - | - | 6.03 MiB | +| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | `N=1280 K=5120 dtype=bf16 M=64 wv=1 sk=0 mb=0 npw=1 nt=1` | 25.80 | 0% | - | - | 13.28 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=4096 K=5120 group=128 dtype=fp8a8 M=18` | 25.64 | 1% | - | - | 20.23 MiB | +| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 conv_width=4 q_len=32` | 25.56 | 3% | - | - | 1.99 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=1024 K=5120 group=128 dtype=fp8a8 M=64` | 25.28 | 0% | - | - | 5.45 MiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=25600 group=128 dtype=bf16 M=256` | 25.08 | 0% | - | - | 18.95 MiB | +| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=4` | 24.56 | 2% | - | - | 12.17 MiB | +| `attn_paged` | `attn_decode_h256_gqa6_bf16kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=10 splits=0` | 24.10 | 5% | - | - | 304.01 KiB | +| `attn_paged` | `attn_decode_h256_gqa6_bf16kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=9 splits=0` | 23.29 | 2% | - | - | 280.01 KiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=4096 K=5120 group=128 dtype=fp8a8 M=8` | 23.22 | 1% | - | - | 20.11 MiB | +| `attn_paged` | `attn_decode_h256_gqa6_bf16kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=8 splits=0` | 23.15 | 2% | - | - | 256.01 KiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=4096 K=5120 group=128 dtype=fp8a8 M=9` | 23.10 | 1% | - | - | 20.12 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=4096 K=5120 group=128 dtype=fp8a8 M=4` | 23.03 | 0% | - | - | 20.05 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=4096 K=5120 group=128 dtype=fp8a8 M=2` | 22.86 | 1% | - | - | 20.03 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=4096 K=5120 group=128 dtype=fp8a8 M=1` | 22.82 | 1% | - | - | 20.02 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=4096 group=128 dtype=fp8a8 M=18` | 22.59 | 0% | - | - | 20.25 MiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=512` | 22.47 | 0% | - | - | 10.01 MiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=512` | 22.45 | 1% | - | - | 10.01 MiB | +| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | `head_k=128 head_v=128 scale=0.0883883 M=64 chunk=64` | 21.74 | 0% | - | - | 8.40 MiB | +| `attn_paged` | `attn_decode_h256_gqa6_bf16kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=6 splits=0` | 21.38 | 5% | - | - | 208.01 KiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=1024 K=5120 group=128 dtype=fp8a8 M=36` | 21.02 | 0% | - | - | 5.25 MiB | +| `sample_argmax` | `sample_argmax_f32` | libr4d | `n_vocab=248320 M=32` | 20.89 | 0% | - | - | 30.32 MiB | +| `attn_paged` | `attn_decode_h256_gqa6_bf16kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=2 splits=0` | 20.84 | 3% | - | - | 112.01 KiB | +| `attn_paged` | `attn_decode_h256_gqa6_bf16kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=1 splits=0` | 20.64 | 2% | - | - | 88.01 KiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=4096 group=128 dtype=fp8a8 M=8` | 20.18 | 0% | - | - | 20.11 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=4096 group=128 dtype=fp8a8 M=9` | 20.17 | 0% | - | - | 20.13 MiB | +| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 chunk=64 conv_width=4 M=32` | 19.78 | 0% | - | - | 1.40 MiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=6144 group=128 dtype=bf16 M=512` | 19.67 | 1% | - | - | 9.09 MiB | +| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | `head_k=128 head_v=128 scale=0.0883883 M=32 chunk=64` | 19.63 | 1% | - | - | 7.20 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=4096 group=128 dtype=fp8a8 M=1` | 19.41 | 1% | - | - | 20.02 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=4096 group=128 dtype=fp8a8 M=2` | 19.38 | 1% | - | - | 20.03 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=5120 K=4096 group=128 dtype=fp8a8 M=4` | 19.35 | 0% | - | - | 20.06 MiB | +| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | `N=1280 K=5120 dtype=bf16 M=34 wv=1 sk=0 mb=0 npw=1 nt=1` | 19.20 | 83% | - | - | 12.92 MiB | +| `add` | `add_bf16` | libr4d | `n=5120 dtype=bf16 M=512` | 19.17 | 0% | - | - | 15.00 MiB | +| `attn_paged` | `attn_decode_h256_gqa6_bf16kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=5 splits=0` | 18.91 | 3% | - | - | 184.01 KiB | +| `attn_paged` | `attn_decode_h256_gqa6_bf16kv` | libr4d | `head_dim=256 gqa=6 causal=1 window=0 n_head=24 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=4 splits=0` | 18.52 | 4% | - | - | 160.01 KiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=5120 group=128 dtype=bf16 M=512` | 18.37 | 1% | - | - | 7.58 MiB | +| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | `head_k=128 head_v=128 scale=0.0883883 M=16 chunk=64` | 18.30 | 0% | - | - | 6.60 MiB | +| `embed_lookup` | `embed_lookup_bf16` | libr4d | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=512` | 18.28 | 0% | - | - | 2.37 GiB | +| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | `head_k=128 head_v=128 scale=0.0883883 M=8 chunk=64` | 17.94 | 1% | - | - | 6.30 MiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=25600 group=128 dtype=bf16 M=128` | 17.80 | 0% | - | - | 9.47 MiB | +| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | `head_k=128 head_v=128 scale=0.0883883 M=4 chunk=64` | 17.70 | 0% | - | - | 6.15 MiB | +| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | `head_k=128 head_v=128 scale=0.0883883 M=1 chunk=64` | 17.70 | 0% | - | - | 6.04 MiB | +| `gdn_chunk_scan` | `gdn_chunk_scan_k128_v128_c64_bf16` | libr4d | `head_k=128 head_v=128 scale=0.0883883 M=2 chunk=64` | 17.65 | 1% | - | - | 6.07 MiB | +| `sample_argmax` | `sample_argmax_f32` | libr4d | `n_vocab=248320 M=16` | 16.60 | 1% | - | - | 15.16 MiB | +| `sample_argmax` | `sample_argmax_f32` | libr4d | `n_vocab=248320 M=8` | 16.49 | 1% | - | - | 7.58 MiB | +| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | `N=96 K=5120 dtype=bf16 M=272 wv=1 sk=0 mb=0 npw=1 nt=1` | 16.38 | 1% | - | - | 3.64 MiB | +| `sample_argmax` | `sample_argmax_f32` | libr4d | `n_vocab=248320 M=4` | 16.33 | 1% | - | - | 3.79 MiB | +| `sample_argmax` | `sample_argmax_f32` | libr4d | `n_vocab=248320 M=1` | 16.29 | 0% | - | - | 970.10 KiB | +| `sample_argmax` | `sample_argmax_f32` | libr4d | `n_vocab=248320 M=2` | 16.24 | 0% | - | - | 1.89 MiB | +| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=512` | 16.17 | 1% | - | - | 6.00 MiB | +| `sample_temp` | `sample_temp_f32` | libr4d | `n_vocab=248320 M=2` | 15.54 | 7% | - | - | 1.89 MiB | +| `attn_paged` | `attn_decode_h128_gqa4_bf16kv` | libr4d | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=8 splits=0` | 15.44 | 6% | - | - | 192.01 KiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=512` | 15.31 | 0% | - | - | 512.50 KiB | +| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=2` | 15.19 | 0% | - | - | 6.09 MiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=25600 group=128 dtype=bf16 M=1` | 15.02 | 1% | - | - | 75.78 KiB | +| `attn_paged` | `attn_decode_h128_gqa4_bf16kv` | libr4d | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=6 splits=0` | 14.99 | 4% | - | - | 160.01 KiB | +| `attn_paged` | `attn_decode_h128_gqa4_bf16kv` | libr4d | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=5 splits=0` | 14.97 | 2% | - | - | 144.01 KiB | +| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | `head_k=128 M=512 chunk=64` | 14.96 | 0% | - | - | 5.19 MiB | +| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 conv_width=4 q_len=16` | 14.90 | 0% | - | - | 1.05 MiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=25600 group=128 dtype=bf16 M=2` | 14.85 | 1% | - | - | 151.56 KiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=25600 group=128 dtype=bf16 M=64` | 14.79 | 0% | - | - | 4.74 MiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=25600 group=128 dtype=bf16 M=4` | 14.67 | 1% | - | - | 303.12 KiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=25600 group=128 dtype=bf16 M=8` | 14.61 | 1% | - | - | 606.25 KiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=25600 group=128 dtype=bf16 M=16` | 14.56 | 0% | - | - | 1.18 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=1024 K=5120 group=128 dtype=fp8a8 M=18` | 14.55 | 0% | - | - | 5.13 MiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=25600 group=128 dtype=bf16 M=32` | 14.52 | 0% | - | - | 2.37 MiB | +| `sample_temp` | `sample_temp_f32` | libr4d | `n_vocab=248320 M=16` | 14.39 | 0% | - | - | 15.16 MiB | +| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 chunk=64 conv_width=4 M=16` | 14.35 | 1% | - | - | 789.39 KiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=256` | 13.95 | 2% | - | - | 5.01 MiB | +| `sample_temp` | `sample_temp_f32` | libr4d | `n_vocab=248320 M=1` | 13.90 | 0% | - | - | 970.09 KiB | +| `sample_mask` | `sample_mask_f32` | libr4d | `n_vocab=248320 M=1` | 13.89 | 0% | - | - | 1000.41 KiB | +| `embed_lookup` | `embed_lookup_bf16` | libr4d | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=256` | 13.89 | 1% | - | - | 2.37 GiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=256` | 13.89 | 0% | - | - | 5.01 MiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=256` | 13.88 | 2% | - | - | 256.50 KiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=6144 group=128 dtype=bf16 M=256` | 13.87 | 1% | - | - | 4.55 MiB | +| `attn_paged` | `attn_decode_h128_gqa4_bf16kv` | libr4d | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=4 splits=0` | 13.87 | 3% | - | - | 128.01 KiB | +| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=256` | 13.83 | 0% | - | - | 2.13 MiB | +| `add` | `add_bf16` | libr4d | `n=5120 dtype=bf16 M=256` | 13.83 | 0% | - | - | 7.50 MiB | +| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=256` | 13.82 | 0% | - | - | 2.13 MiB | +| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=256` | 13.82 | 0% | - | - | 513.00 KiB | +| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=32` | 13.82 | 1% | - | - | 256.12 KiB | +| `attn_paged` | `attn_decode_h128_gqa4_bf16kv` | libr4d | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=2 splits=0` | 13.79 | 8% | - | - | 96.01 KiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=256` | 13.78 | 0% | - | - | 128.25 KiB | +| `attn_paged` | `attn_decode_h128_gqa4_bf16kv` | libr4d | `head_dim=128 gqa=4 causal=0 window=2048 n_head=32 block_size=16 max_seqs=8 max_ctx=262144 q_dtype=bf16 kv_dtype=bf16 q_len=1 splits=0` | 13.77 | 2% | - | - | 80.01 KiB | +| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=128` | 13.77 | 0% | - | - | 256.50 KiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=5120 group=128 dtype=bf16 M=256` | 13.75 | 0% | - | - | 3.79 MiB | +| `sample_mask` | `sample_mask_f32` | libr4d | `n_vocab=248320 M=64` | 13.56 | 1% | - | - | 62.53 MiB | +| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=256` | 13.32 | 6% | - | - | 513.00 KiB | +| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | `N=1280 K=5120 dtype=bf16 M=17 wv=1 sk=0 mb=0 npw=1 nt=1` | 13.24 | 1% | - | - | 12.71 MiB | +| `silu_mul` | `silu_mul_bf16` | libr4d | `n=17408 dtype=bf16 M=64` | 13.20 | 0% | - | - | 6.38 MiB | +| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=512` | 13.01 | 11% | - | - | 1.00 MiB | +| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=1280 K=5120 dtype=bf16 M=16 wv=1 sk=0 mb=0 npw=1 nt=1` | 12.64 | 1% | - | - | 12.70 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=1024 K=5120 group=128 dtype=fp8a8 M=9` | 12.60 | 0% | - | - | 5.06 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=1024 K=5120 group=128 dtype=fp8a8 M=8` | 12.54 | 1% | - | - | 5.06 MiB | +| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | `head_k=128 M=256 chunk=64` | 12.52 | 0% | - | - | 2.59 MiB | +| `gdn_recurrent_update` | `gdn_recurrent_update_k128_v128_bf16_fp32state` | libr4d | `head_k=128 head_v=128 n_head_v=48 scale=0.0883883 eps=1e-06 act=silu q_len=1` | 12.23 | 1% | - | - | 3.04 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=1024 K=5120 group=128 dtype=fp8a8 M=1` | 12.14 | 1% | - | - | 5.01 MiB | +| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | `N=96 K=5120 dtype=bf16 M=136 wv=1 sk=0 mb=0 npw=1 nt=1` | 12.12 | 2% | - | - | 2.29 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=1024 K=5120 group=128 dtype=fp8a8 M=4` | 12.10 | 0% | - | - | 5.03 MiB | +| `gemm_nt_q` | `gemm_fp8a8_nt_m16` | libr4d | `N=1024 K=5120 group=128 dtype=fp8a8 M=2` | 12.01 | 1% | - | - | 5.01 MiB | +| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=1280 K=5120 dtype=bf16 M=8 wv=1 sk=0 mb=0 npw=1 nt=1` | 11.95 | 1% | - | - | 12.60 MiB | +| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=1280 K=5120 dtype=bf16 M=4 wv=1 sk=0 mb=0 npw=1 nt=1` | 11.77 | 0% | - | - | 12.55 MiB | +| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=1280 K=5120 dtype=bf16 M=1 wv=1 sk=0 mb=0 npw=1 nt=1` | 11.76 | 1% | - | - | 12.51 MiB | +| `silu_mul` | `silu_mul_bf16` | libr4d | `n=17408 dtype=bf16 M=4` | 11.73 | 1% | - | - | 408.00 KiB | +| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=1280 K=5120 dtype=bf16 M=2 wv=1 sk=0 mb=0 npw=1 nt=1` | 11.72 | 0% | - | - | 12.52 MiB | +| `silu_mul` | `silu_mul_bf16` | libr4d | `n=17408 dtype=bf16 M=32` | 11.68 | 1% | - | - | 3.19 MiB | +| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | `head_k=128 M=128 chunk=64` | 11.68 | 0% | - | - | 1.30 MiB | +| `silu_mul` | `silu_mul_bf16` | libr4d | `n=17408 dtype=bf16 M=2` | 11.66 | 1% | - | - | 204.00 KiB | +| `silu_mul` | `silu_mul_bf16` | libr4d | `n=17408 dtype=bf16 M=8` | 11.62 | 0% | - | - | 816.00 KiB | +| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 chunk=64 conv_width=4 M=8` | 11.62 | 1% | - | - | 464.89 KiB | +| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=64` | 11.62 | 6% | - | - | 512.25 KiB | +| `silu_mul` | `silu_mul_bf16` | libr4d | `n=17408 dtype=bf16 M=1` | 11.62 | 1% | - | - | 102.00 KiB | +| `silu_mul` | `silu_mul_bf16` | libr4d | `n=17408 dtype=bf16 M=16` | 11.60 | 1% | - | - | 1.59 MiB | +| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | `head_k=128 M=64 chunk=64` | 11.30 | 1% | - | - | 664.01 KiB | +| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=512` | 11.22 | 12% | - | - | 4.13 MiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=17408 group=128 dtype=bf16 M=64` | 11.18 | 1% | - | - | 3.22 MiB | +| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=512` | 11.18 | 15% | - | - | 4.13 MiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=17408 group=128 dtype=bf16 M=32` | 10.97 | 2% | - | - | 1.61 MiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=17408 group=128 dtype=bf16 M=1` | 10.96 | 2% | - | - | 51.53 KiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=17408 group=128 dtype=bf16 M=8` | 10.95 | 1% | - | - | 412.25 KiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=17408 group=128 dtype=bf16 M=4` | 10.88 | 1% | - | - | 206.12 KiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=17408 group=128 dtype=bf16 M=2` | 10.88 | 2% | - | - | 103.06 KiB | +| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=256` | 10.85 | 115% | - | - | 3.00 MiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=17408 group=128 dtype=bf16 M=16` | 10.83 | 1% | - | - | 824.50 KiB | +| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | `head_k=128 M=32 chunk=64` | 10.66 | 1% | - | - | 332.01 KiB | +| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 chunk=64 conv_width=4 M=4` | 10.49 | 4% | - | - | 302.64 KiB | +| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | `head_k=128 M=1 chunk=64` | 10.43 | 2% | - | - | 10.38 KiB | +| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | `head_k=128 M=4 chunk=64` | 10.43 | 1% | - | - | 41.51 KiB | +| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | `head_k=128 M=2 chunk=64` | 10.34 | 1% | - | - | 20.76 KiB | +| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | `head_k=128 M=8 chunk=64` | 10.26 | 3% | - | - | 83.01 KiB | +| `gdn_kkt_solve` | `gdn_kkt_solve_k128_c64_bf16` | libr4d | `head_k=128 M=16 chunk=64` | 10.14 | 2% | - | - | 166.01 KiB | +| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | `N=96 K=5120 dtype=bf16 M=68 wv=1 sk=0 mb=0 npw=1 nt=1` | 10.14 | 1% | - | - | 1.61 MiB | +| `sample_temp` | `sample_temp_f32` | libr4d | `n_vocab=248320 M=8` | 10.00 | 1% | - | - | 7.58 MiB | +| `sample_dry` | `sample_dry_f32` | libr4d | `n_vocab=248320 M=32` | 9.54 | 3% | - | - | 30.32 MiB | +| `sample_dry` | `sample_dry_f32` | libr4d | `n_vocab=248320 M=64` | 9.45 | 0% | - | - | 60.65 MiB | +| `cast` | `cast_bf16_bf16` | libr4d | `n=5120 from=bf16 to=bf16 M=512` | 9.33 | 4% | - | - | 10.00 MiB | +| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 chunk=64 conv_width=4 M=2` | 9.28 | 2% | - | - | 221.52 KiB | +| `sample_mask` | `sample_mask_f32` | libr4d | `n_vocab=248320 M=32` | 8.97 | 4% | - | - | 31.26 MiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=128` | 8.78 | 1% | - | - | 2.51 MiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=128` | 8.77 | 4% | - | - | 2.51 MiB | +| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=128` | 8.09 | 12% | - | - | 1.50 MiB | +| `gdn_conv_prep` | `gdn_conv_prep_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 chunk=64 conv_width=4 M=1` | 7.57 | 0% | - | - | 180.95 KiB | +| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | `N=256 K=5120 dtype=bf16 M=56 wv=1 sk=0 mb=0 npw=1 nt=1` | 7.47 | 1% | - | - | 3.07 MiB | +| `sample_penalties` | `sample_penalties_f32` | libr4d | `n_vocab=248320 M=64` | 7.10 | 2% | - | - | 60.65 MiB | +| `sample_penalties` | `sample_penalties_f32` | libr4d | `n_vocab=248320 M=32` | 7.08 | 1% | - | - | 30.32 MiB | +| `sample_penalties` | `sample_penalties_f32` | libr4d | `n_vocab=248320 M=16` | 7.06 | 0% | - | - | 15.16 MiB | +| `sample_penalties` | `sample_penalties_f32` | libr4d | `n_vocab=248320 M=4` | 7.01 | 0% | - | - | 3.79 MiB | +| `gather_rows` | `gather_rows_bf16` | libr4d | `n=5120 dtype=bf16 M=1` | 6.92 | 1% | - | - | 50.00 KiB | +| `sample_xtc` | `sample_xtc_f32` | libr4d | `n_cand=1024 M=8` | 6.91 | 2% | - | - | 64.75 KiB | +| `embed_lookup` | `embed_lookup_bf16` | libr4d | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=2` | 6.81 | 3% | - | - | 2.37 GiB | +| `sample_xtc` | `sample_xtc_f32` | libr4d | `n_cand=1024 M=32` | 6.73 | 6% | - | - | 259.00 KiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=6144 group=128 dtype=bf16 M=128` | 6.72 | 3% | - | - | 2.27 MiB | +| `embed_lookup` | `embed_lookup_bf16` | libr4d | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=128` | 6.71 | 1% | - | - | 2.37 GiB | +| `embed_lookup` | `embed_lookup_bf16` | libr4d | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=4` | 6.67 | 1% | - | - | 2.37 GiB | +| `embed_lookup` | `embed_lookup_bf16` | libr4d | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=16` | 6.67 | 3% | - | - | 2.37 GiB | +| `embed_lookup` | `embed_lookup_bf16` | libr4d | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=64` | 6.67 | 0% | - | - | 2.37 GiB | +| `embed_lookup` | `embed_lookup_bf16` | libr4d | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=8` | 6.67 | 3% | - | - | 2.37 GiB | +| `embed_lookup` | `embed_lookup_bf16` | libr4d | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=1` | 6.65 | 1% | - | - | 2.37 GiB | +| `embed_lookup` | `embed_lookup_bf16` | libr4d | `n_embd=5120 n_vocab=248320 dtype=bf16 vocab_offset=0 M=32` | 6.65 | 1% | - | - | 2.37 GiB | +| `sample_xtc` | `sample_xtc_f32` | libr4d | `n_cand=1024 M=64` | 6.65 | 1% | - | - | 518.00 KiB | +| `sample_xtc` | `sample_xtc_f32` | libr4d | `n_cand=1024 M=16` | 6.62 | 0% | - | - | 129.50 KiB | +| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 conv_width=4 q_len=8` | 6.61 | 5% | - | - | 600.04 KiB | +| `gather_rows` | `gather_rows_bf16` | libr4d | `n=5120 dtype=bf16 M=2` | 6.59 | 2% | - | - | 100.01 KiB | +| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | `N=256 K=5120 dtype=bf16 M=34 wv=1 sk=0 mb=0 npw=1 nt=1` | 6.58 | 1% | - | - | 2.85 MiB | +| `gather_rows` | `gather_rows_bf16` | libr4d | `n=5120 dtype=bf16 M=56` | 6.52 | 2% | - | - | 2.73 MiB | +| `gather_rows` | `gather_rows_bf16` | libr4d | `n=5120 dtype=bf16 M=4` | 6.50 | 0% | - | - | 200.02 KiB | +| `gather_rows` | `gather_rows_bf16` | libr4d | `n=5120 dtype=bf16 M=8` | 6.44 | 0% | - | - | 400.03 KiB | +| `gather_rows` | `gather_rows_bf16` | libr4d | `n=5120 dtype=bf16 M=16` | 6.41 | 3% | - | - | 800.06 KiB | +| `sample_temp` | `sample_temp_f32` | libr4d | `n_vocab=248320 M=4` | 6.41 | 2% | - | - | 3.79 MiB | +| `gather_rows` | `gather_rows_bf16` | libr4d | `n=5120 dtype=bf16 M=64` | 6.39 | 1% | - | - | 3.13 MiB | +| `gather_rows` | `gather_rows_bf16` | libr4d | `n=5120 dtype=bf16 M=32` | 6.37 | 0% | - | - | 1.56 MiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=6144 group=128 dtype=bf16 M=2` | 6.30 | 2% | - | - | 36.38 KiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=6144 group=128 dtype=bf16 M=1` | 6.23 | 5% | - | - | 18.19 KiB | +| `sample_mask` | `sample_mask_f32` | libr4d | `n_vocab=248320 M=16` | 6.23 | 7% | - | - | 15.63 MiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=6144 group=128 dtype=bf16 M=4` | 6.12 | 7% | - | - | 72.75 KiB | +| `sample_topp` | `sample_topp_f32` | libr4d | `n_cand=1024 M=2` | 6.11 | 5% | - | - | 16.19 KiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=6144 group=128 dtype=bf16 M=64` | 6.09 | 5% | - | - | 1.14 MiB | +| `sample_xtc` | `sample_xtc_f32` | libr4d | `n_cand=1024 M=4` | 6.06 | 5% | - | - | 32.38 KiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=64` | 6.03 | 4% | - | - | 1.26 MiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=6144 group=128 dtype=bf16 M=16` | 6.01 | 5% | - | - | 291.00 KiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=5120 group=128 dtype=bf16 M=128` | 5.98 | 5% | - | - | 1.89 MiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=6144 group=128 dtype=bf16 M=32` | 5.96 | 5% | - | - | 582.00 KiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=64` | 5.95 | 9% | - | - | 1.26 MiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=6144 group=128 dtype=bf16 M=8` | 5.93 | 2% | - | - | 145.50 KiB | +| `sample_minp` | `sample_minp_f32` | libr4d | `n_cand=1024 M=32` | 5.82 | 0% | - | - | 259.00 KiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=5120 group=128 dtype=bf16 M=8` | 5.77 | 5% | - | - | 121.25 KiB | +| `sample_minp` | `sample_minp_f32` | libr4d | `n_cand=1024 M=64` | 5.75 | 4% | - | - | 518.00 KiB | +| `sample_xtc` | `sample_xtc_f32` | libr4d | `n_cand=1024 M=1` | 5.74 | 2% | - | - | 8.09 KiB | +| `sample_xtc` | `sample_xtc_f32` | libr4d | `n_cand=1024 M=2` | 5.74 | 2% | - | - | 16.19 KiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=5120 group=128 dtype=bf16 M=32` | 5.73 | 5% | - | - | 485.00 KiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=5120 group=128 dtype=bf16 M=64` | 5.72 | 6% | - | - | 970.00 KiB | +| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=64` | 5.70 | 7% | - | - | 768.25 KiB | +| `sample_typical` | `sample_typical_f32` | libr4d | `n_cand=1024 M=1` | 5.67 | 1% | - | - | 8.09 KiB | +| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 conv_width=4 q_len=4` | 5.65 | 6% | - | - | 360.03 KiB | +| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=256 K=5120 dtype=bf16 M=16 wv=1 sk=0 mb=0 npw=1 nt=1` | 5.65 | 7% | - | - | 2.66 MiB | +| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=512` | 5.65 | 2% | - | - | 1.00 MiB | +| `add` | `add_bf16` | libr4d | `n=5120 dtype=bf16 M=64` | 5.65 | 5% | - | - | 1.88 MiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=5120 group=128 dtype=bf16 M=2` | 5.64 | 7% | - | - | 30.31 KiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=5120 group=128 dtype=bf16 M=1` | 5.62 | 5% | - | - | 15.16 KiB | +| `add` | `add_bf16` | libr4d | `n=5120 dtype=bf16 M=128` | 5.61 | 6% | - | - | 3.75 MiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=5120 group=128 dtype=bf16 M=4` | 5.58 | 6% | - | - | 60.62 KiB | +| `sample_minp` | `sample_minp_f32` | libr4d | `n_cand=1024 M=2` | 5.57 | 5% | - | - | 16.19 KiB | +| `sample_minp` | `sample_minp_f32` | libr4d | `n_cand=1024 M=8` | 5.55 | 7% | - | - | 64.75 KiB | +| `add` | `add_bf16` | libr4d | `n=5120 dtype=bf16 M=32` | 5.54 | 4% | - | - | 960.00 KiB | +| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | `N=256 K=5120 dtype=bf16 M=17 wv=1 sk=0 mb=0 npw=1 nt=1` | 5.53 | 5% | - | - | 2.67 MiB | +| `cast` | `cast_bf16_bf16` | libr4d | `n=5120 from=bf16 to=bf16 M=256` | 5.51 | 5% | - | - | 5.00 MiB | +| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=256 K=5120 dtype=bf16 M=2 wv=1 sk=0 mb=0 npw=1 nt=1` | 5.47 | 11% | - | - | 2.52 MiB | +| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=256 K=5120 dtype=bf16 M=1 wv=1 sk=0 mb=0 npw=1 nt=1` | 5.47 | 6% | - | - | 2.51 MiB | +| `sample_minp` | `sample_minp_f32` | libr4d | `n_cand=1024 M=16` | 5.46 | 2% | - | - | 129.50 KiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=5120 group=128 dtype=bf16 M=16` | 5.45 | 7% | - | - | 242.50 KiB | +| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=96 K=5120 dtype=bf16 M=16 wv=1 sk=0 mb=0 npw=1 nt=1` | 5.41 | 10% | - | - | 1.10 MiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=16` | 5.40 | 11% | - | - | 330.00 KiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=2` | 5.40 | 8% | - | - | 50.00 KiB | +| `sample_minp` | `sample_minp_f32` | libr4d | `n_cand=1024 M=4` | 5.39 | 6% | - | - | 32.38 KiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=2` | 5.39 | 10% | - | - | 50.00 KiB | +| `add` | `add_bf16` | libr4d | `n=5120 dtype=bf16 M=8` | 5.38 | 11% | - | - | 240.00 KiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=4096 group=128 dtype=bf16 M=32` | 5.36 | 4% | - | - | 388.00 KiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=32` | 5.34 | 8% | - | - | 650.00 KiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=8` | 5.33 | 10% | - | - | 170.00 KiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=16` | 5.32 | 0% | - | - | 330.00 KiB | +| `add` | `add_bf16` | libr4d | `n=5120 dtype=bf16 M=4` | 5.32 | 6% | - | - | 120.00 KiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=4096 group=128 dtype=bf16 M=2` | 5.30 | 8% | - | - | 24.25 KiB | +| `add` | `add_bf16` | libr4d | `n=5120 dtype=bf16 M=16` | 5.30 | 7% | - | - | 480.00 KiB | +| `add` | `add_bf16` | libr4d | `n=5120 dtype=bf16 M=1` | 5.30 | 6% | - | - | 30.00 KiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=1` | 5.27 | 7% | - | - | 30.00 KiB | +| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=256 K=5120 dtype=bf16 M=8 wv=1 sk=0 mb=0 npw=1 nt=1` | 5.24 | 6% | - | - | 2.58 MiB | +| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=256 K=5120 dtype=bf16 M=4 wv=1 sk=0 mb=0 npw=1 nt=1` | 5.24 | 8% | - | - | 2.54 MiB | +| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 conv_width=4 q_len=1` | 5.22 | 2% | - | - | 180.02 KiB | +| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | `N=96 K=5120 dtype=bf16 M=17 wv=1 sk=0 mb=0 npw=1 nt=1` | 5.22 | 7% | - | - | 1.11 MiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=1` | 5.21 | 10% | - | - | 30.00 KiB | +| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=96 K=5120 dtype=bf16 M=4 wv=1 sk=0 mb=0 npw=1 nt=1` | 5.20 | 4% | - | - | 1000.75 KiB | +| `gemm_nt` | `gemm_bf16_nt_m64` | libr4d | `N=96 K=5120 dtype=bf16 M=34 wv=1 sk=0 mb=0 npw=1 nt=1` | 5.19 | 7% | - | - | 1.28 MiB | +| `add` | `add_bf16` | libr4d | `n=5120 dtype=bf16 M=2` | 5.19 | 7% | - | - | 60.00 KiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=4096 group=128 dtype=bf16 M=64` | 5.15 | 8% | - | - | 776.00 KiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=4096 group=128 dtype=bf16 M=16` | 5.14 | 7% | - | - | 194.00 KiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=4` | 5.14 | 7% | - | - | 90.00 KiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=8` | 5.13 | 7% | - | - | 170.00 KiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=1 dtype=bf16 M=32` | 5.12 | 5% | - | - | 650.00 KiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=4096 group=128 dtype=bf16 M=4` | 5.10 | 7% | - | - | 48.50 KiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=4096 group=128 dtype=bf16 M=8` | 5.09 | 4% | - | - | 97.00 KiB | +| `gdn_conv_update` | `gdn_conv_update_w4_h128_bf16` | libr4d | `head_k=128 head_v=128 conv_width=4 q_len=2` | 5.09 | 8% | - | - | 240.02 KiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=5120 eps=1e-06 wadd=0 dtype=bf16 M=4` | 5.06 | 3% | - | - | 90.00 KiB | +| `quant_act_fp8` | `quant_act_fp8` | libr4d | `n=4096 group=128 dtype=bf16 M=1` | 4.97 | 3% | - | - | 12.12 KiB | +| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=96 K=5120 dtype=bf16 M=8 wv=1 sk=0 mb=0 npw=1 nt=1` | 4.95 | 2% | - | - | 1.02 MiB | +| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=96 K=5120 dtype=bf16 M=1 wv=1 sk=0 mb=0 npw=1 nt=1` | 4.81 | 4% | - | - | 970.19 KiB | +| `sample_mask` | `sample_mask_f32` | libr4d | `n_vocab=248320 M=8` | 4.72 | 3% | - | - | 7.82 MiB | +| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=16` | 4.67 | 1% | - | - | 128.06 KiB | +| `gemm_nt` | `gemm_bf16_nt_m16` | libr4d | `N=96 K=5120 dtype=bf16 M=2 wv=1 sk=0 mb=0 npw=1 nt=1` | 4.67 | 0% | - | - | 980.38 KiB | +| `sample_minp` | `sample_minp_f32` | libr4d | `n_cand=1024 M=1` | 4.67 | 1% | - | - | 8.09 KiB | +| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=64` | 4.53 | 2% | - | - | 128.25 KiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=512` | 4.46 | 2% | - | - | 256.25 KiB | +| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=128` | 4.30 | 2% | - | - | 1.13 MiB | +| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=128` | 4.29 | 1% | - | - | 1.13 MiB | +| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=32` | 4.29 | 0% | - | - | 384.12 KiB | +| `cast` | `cast_bf16_bf16` | libr4d | `n=5120 from=bf16 to=bf16 M=128` | 4.27 | 1% | - | - | 2.50 MiB | +| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=64` | 4.17 | 1% | - | - | 640.25 KiB | +| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=1` | 4.16 | 2% | - | - | 196.00 KiB | +| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=1` | 4.15 | 1% | - | - | 196.00 KiB | +| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=32` | 4.14 | 3% | - | - | 384.12 KiB | +| `sample_mask` | `sample_mask_f32` | libr4d | `n_vocab=248320 M=4` | 4.12 | 1% | - | - | 3.91 MiB | +| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=2` | 4.12 | 1% | - | - | 200.01 KiB | +| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=64` | 4.11 | 4% | - | - | 640.25 KiB | +| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=8` | 4.08 | 1% | - | - | 64.03 KiB | +| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=4` | 4.08 | 2% | - | - | 208.02 KiB | +| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=2` | 4.06 | 3% | - | - | 200.01 KiB | +| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=32` | 4.06 | 1% | - | - | 64.12 KiB | +| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=32` | 4.06 | 2% | - | - | 384.12 KiB | +| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=4` | 4.05 | 2% | - | - | 208.02 KiB | +| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=128` | 4.05 | 0% | - | - | 256.50 KiB | +| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=16` | 4.05 | 4% | - | - | 256.06 KiB | +| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=16` | 4.03 | 1% | - | - | 192.06 KiB | +| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=2` | 4.03 | 4% | - | - | 16.01 KiB | +| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=8` | 4.03 | 1% | - | - | 224.03 KiB | +| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=256 n_head_kv=4 block_size=16 kv_dtype=bf16 M=16` | 4.01 | 0% | - | - | 256.06 KiB | +| `kv_store` | `kv_store_bf16` | libr4d | `head_dim=128 n_head_kv=8 block_size=16 kv_dtype=bf16 M=8` | 4.00 | 4% | - | - | 224.03 KiB | +| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=1` | 3.99 | 1% | - | - | 8.00 KiB | +| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=32 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=4` | 3.98 | 3% | - | - | 32.02 KiB | +| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=1` | 3.94 | 0% | - | - | 2.00 KiB | +| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=2` | 3.93 | 1% | - | - | 4.01 KiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=1` | 3.93 | 2% | - | - | 1.50 KiB | +| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=4` | 3.93 | 3% | - | - | 8.02 KiB | +| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=1` | 3.93 | 1% | - | - | 2.00 KiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=2` | 3.92 | 6% | - | - | 2.50 KiB | +| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=2` | 3.89 | 1% | - | - | 4.01 KiB | +| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=8` | 3.89 | 0% | - | - | 96.03 KiB | +| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=4` | 3.89 | 1% | - | - | 48.02 KiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=4` | 3.88 | 6% | - | - | 4.50 KiB | +| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=16` | 3.88 | 1% | - | - | 32.06 KiB | +| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=64` | 3.88 | 1% | - | - | 128.25 KiB | +| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=2` | 3.87 | 1% | - | - | 24.01 KiB | +| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | `channels=128 eps=1e-06 act=silu M=1` | 3.87 | 1% | - | - | 1.25 KiB | +| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=8` | 3.87 | 1% | - | - | 16.03 KiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=1` | 3.87 | 3% | - | - | 768 B | +| `cast` | `cast_bf16_bf16` | libr4d | `n=5120 from=bf16 to=bf16 M=64` | 3.86 | 1% | - | - | 1.25 MiB | +| `rope` | `rope_bf16` | libr4d | `head_dim=128 n_head=8 n_head_kv=0 theta=1e+07 scale=1 mode=neox M=4` | 3.86 | 1% | - | - | 8.02 KiB | +| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=24 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=1` | 3.86 | 6% | - | - | 12.00 KiB | +| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | `channels=128 eps=1e-06 act=silu M=512` | 3.85 | 2% | - | - | 384.50 KiB | +| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=16` | 3.85 | 1% | - | - | 32.06 KiB | +| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=32` | 3.84 | 0% | - | - | 64.12 KiB | +| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | `channels=128 eps=1e-06 act=silu M=2` | 3.84 | 1% | - | - | 2.00 KiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=8` | 3.83 | 2% | - | - | 8.50 KiB | +| `rope` | `rope_bf16` | libr4d | `head_dim=256 n_head=4 n_head_kv=0 theta=1e+07 scale=1 mode=mrope rotary_dim=64 M=8` | 3.82 | 0% | - | - | 16.03 KiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=2` | 3.82 | 2% | - | - | 1.25 KiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=16` | 3.81 | 7% | - | - | 8.25 KiB | +| `rope_table` | `rope_table_f32` | libr4d | `rot=64 theta=1e+07 scale=1 dtype=f32 M=8` | 3.81 | 3% | - | - | 2.03 KiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=16` | 3.81 | 1% | - | - | 16.50 KiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=32` | 3.81 | 1% | - | - | 32.50 KiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=8` | 3.80 | 4% | - | - | 4.25 KiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=4` | 3.79 | 1% | - | - | 2.25 KiB | +| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | `channels=128 eps=1e-06 act=silu M=4` | 3.79 | 1% | - | - | 3.50 KiB | +| `rope_table` | `rope_table_f32` | libr4d | `rot=64 theta=1e+07 scale=1 dtype=f32 M=1` | 3.79 | 1% | - | - | 260 B | +| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | `channels=128 eps=1e-06 act=silu M=256` | 3.78 | 6% | - | - | 192.50 KiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=128` | 3.78 | 3% | - | - | 128.50 KiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=32` | 3.78 | 1% | - | - | 16.25 KiB | +| `sample_mask` | `sample_mask_f32` | libr4d | `n_vocab=248320 M=2` | 3.77 | 0% | - | - | 1.95 MiB | +| `rope_table` | `rope_table_f32` | libr4d | `rot=64 theta=1e+07 scale=1 dtype=f32 M=16` | 3.76 | 2% | - | - | 4.06 KiB | +| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | `channels=128 eps=1e-06 act=silu M=8` | 3.76 | 5% | - | - | 6.50 KiB | +| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | `channels=128 eps=1e-06 act=silu M=64` | 3.76 | 4% | - | - | 48.50 KiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=256 eps=1e-06 wadd=1 dtype=bf16 M=64` | 3.75 | 2% | - | - | 64.50 KiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=64` | 3.75 | 1% | - | - | 32.25 KiB | +| `rope_table` | `rope_table_f32` | libr4d | `rot=64 theta=1e+07 scale=1 dtype=f32 M=64` | 3.75 | 4% | - | - | 16.25 KiB | +| `rope_table` | `rope_table_f32` | libr4d | `rot=64 theta=1e+07 scale=1 dtype=f32 M=2` | 3.75 | 4% | - | - | 520 B | +| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | `channels=128 eps=1e-06 act=silu M=128` | 3.74 | 1% | - | - | 96.50 KiB | +| `rope_table` | `rope_table_f32` | libr4d | `rot=64 theta=1e+07 scale=1 dtype=f32 M=4` | 3.73 | 1% | - | - | 1.02 KiB | +| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | `channels=128 eps=1e-06 act=silu M=16` | 3.72 | 1% | - | - | 12.50 KiB | +| `gdn_gated_rmsnorm` | `gdn_gated_rmsnorm_h128_bf16` | libr4d | `channels=128 eps=1e-06 act=silu M=32` | 3.70 | 3% | - | - | 24.50 KiB | +| `cast` | `cast_bf16_bf16` | libr4d | `n=5120 from=bf16 to=bf16 M=2` | 3.70 | 5% | - | - | 40.00 KiB | +| `cast` | `cast_bf16_bf16` | libr4d | `n=5120 from=bf16 to=bf16 M=32` | 3.70 | 4% | - | - | 640.00 KiB | +| `rope_table` | `rope_table_f32` | libr4d | `rot=64 theta=1e+07 scale=1 dtype=f32 M=32` | 3.70 | 0% | - | - | 8.12 KiB | +| `rmsnorm` | `rmsnorm_bf16` | libr4d | `n=128 eps=1e-06 wadd=0 dtype=bf16 M=128` | 3.70 | 5% | - | - | 64.25 KiB | +| `cast` | `cast_bf16_bf16` | libr4d | `n=5120 from=bf16 to=bf16 M=16` | 3.59 | 0% | - | - | 320.00 KiB | +| `cast` | `cast_bf16_bf16` | libr4d | `n=5120 from=bf16 to=bf16 M=4` | 3.56 | 3% | - | - | 80.00 KiB | +| `cast` | `cast_bf16_bf16` | libr4d | `n=5120 from=bf16 to=bf16 M=8` | 3.56 | 1% | - | - | 160.00 KiB | +| `cast` | `cast_bf16_bf16` | libr4d | `n=5120 from=bf16 to=bf16 M=1` | 3.50 | 2% | - | - | 20.00 KiB | +| `sample_penalties` | `sample_penalties_f32` | libr4d | `n_vocab=248320 M=2` | 3.40 | 9% | - | - | 1.90 MiB | +| `sample_dry` | `sample_dry_f32` | libr4d | `n_vocab=248320 M=16` | 3.39 | 0% | - | - | 15.16 MiB | +| `sample_penalties` | `sample_penalties_f32` | libr4d | `n_vocab=248320 M=8` | 3.39 | 2% | - | - | 7.58 MiB | +| `sample_dry` | `sample_dry_f32` | libr4d | `n_vocab=248320 M=8` | 3.39 | 1% | - | - | 7.58 MiB | +| `sample_dry` | `sample_dry_f32` | libr4d | `n_vocab=248320 M=4` | 3.38 | 2% | - | - | 3.79 MiB | +| `sample_dry` | `sample_dry_f32` | libr4d | `n_vocab=248320 M=1` | 3.37 | 0% | - | - | 970.34 KiB | +| `sample_penalties` | `sample_penalties_f32` | libr4d | `n_vocab=248320 M=1` | 3.37 | 5% | - | - | 970.34 KiB | +| `sample_dry` | `sample_dry_f32` | libr4d | `n_vocab=248320 M=2` | 3.37 | 0% | - | - | 1.90 MiB | + +## Memory safety + +Every device allocation in this run -- every operand and every kernel's own scratch -- was +made with a poisoned 256-byte margin on both sides, the kernel was handed the middle, and the +margins were read back and verified after the checked launch. It catches an out-of-bounds +WRITE, which is the one that corrupts a neighbouring tensor and surfaces as wrong output three +ops later in a kernel that is correct. An out-of-bounds READ it cannot see. + +AMD's amdgcn AddressSanitizer (`/opt/rocm/amdgcn/bitcode/asanrtl.bc`) is not an option on every +card: its shadow is page-fault based and needs `xnack+`, which RDNA does not implement -- +`rocminfo` reports `XNACK enabled: NO` there. The margins are what replaces it. + +- 537 case(s) ran inside guarded allocations +- 0 wrote outside one + +## Not covered + +A skip is a real answer: the tool declined rather than invent an extent, a dtype or an +oracle it does not have. Each line below is a gap in COVERAGE, not a failing kernel. + +**Collective ops are not checked here and cannot be.** `all_reduce`, `all_gather` and the +fused all-reduce forms establish one instance across ranks through a rendezvous over peer +memory: a single process has nobody to reduce with, and a kernel waiting for a peer that +never arrives hangs rather than failing. They appear in the completeness matrix because the +rows exist; they carry no correctness or speed number because producing one needs a second +rank, and that is a different harness. + +| what | cases | +|---|---| +| logits_gemm (reference was recorded through logits_gemm_fp8's weight layout, which ref_logits_gemm does not implement; only that row can reproduce it) | 7 | + +## Static and dynamic analysis + +Advisory, and generated separately from the measurements above: +`tools/kbench-analysis.sh` runs on a machine that need not have a GPU. + +### clang-tidy + +`bugprone-*`, `clang-analyzer-*` and `performance-*` over every host translation unit +(`libref/`, `core/`, `tools/`). HIP units are excluded: clang-tidy cannot replay the +offload flags and reports `__device__` as an error rather than analysing the body. + +- 195 warning(s) + +| check | count | +|---|---| +| `[bugprone-unchecked-string-to-number-conversion]` | 49 | +| `[bugprone-assignment-in-if-condition]` | 41 | +| `[performance-enum-size]` | 18 | +| `[performance-inefficient-vector-operation]` | 10 | +| `[bugprone-multi-level-implicit-pointer-conversion]` | 10 | +| `[bugprone-misplaced-widening-cast]` | 9 | +| `[bugprone-implicit-widening-of-multiplication-result]` | 9 | +| `[bugprone-suspicious-string-compare]` | 8 | +| `[bugprone-branch-clone]` | 6 | +| `[performance-inefficient-string-concatenation]` | 5 | +| `[performance-unnecessary-value-param]` | 3 | +| `[bugprone-throwing-static-initialization]` | 3 | +| `[bugprone-signed-char-misuse]` | 2 | +| `[bugprone-incorrect-roundings]` | 2 | +| `[performance-no-int-to-ptr]` | 1 | +| `[bugprone-integer-division]` | 1 | +| `[bugprone-exception-escape]` | 1 | +| `[bugprone-empty-catch]` | 1 | + +### AddressSanitizer + UndefinedBehaviorSanitizer + +A sanitised replay of the whole fixture. Host code only -- see the note in the +**Memory safety** section for why the device side cannot be sanitised on this card. + +- 0 report(s) + diff --git a/docs/MOE-W4.md b/docs/MOE-W4.md new file mode 100644 index 00000000..fba291bc --- /dev/null +++ b/docs/MOE-W4.md @@ -0,0 +1,394 @@ +# The four-bit MoE expert format + +Qwen3.8-Flash-Next has 512 experts of 640 over 48 layers. At E4M3 that is **112.8 GiB of expert +weight** against two 32 GB cards. Splitting the experts over the two ranks halves the per-rank +share and the placement planner still refuses 26 GiB. A routed weight can be served from the file +tier (`--weights-disk-tier`), but it is then read a layer at a time and a step is paced by the +drive. Pinned host memory does not close it either on a host with 64 GB of RAM (2 x 34.78 GiB). + +So four bits is not an optimisation here. It is what lets the model run from VRAM and host memory: +an expert unit is 2.42 MiB instead of 4.69, the per-rank share is ~29 GiB, and that fits VRAM plus +a few GiB of pinned host. + +## What is served + +Qwen3.8-Flash-Next is served as `w4nl64-i8lm.rad`, built by +`data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe` with `CALIB=` naming the calibration Grams +(below, "Calibration"): the routed experts at `w4nl64a8h` (the w4nl codebook below, an E4M3 scale +a row and group of 64, GPTQ and three sweeps of coordinate descent), ten protected experts bf16, +and the trunk's block linears and the lm_head **int8, served W8A8** -- `gemm_i8a8_nt_m16` / +`gemm_i8a8_tiled` and `logits_gemm_i8` (docs/OPS.md), every quantising producer writing the int8 +codes its consumer reads, so an int8 trunk adds no quantiser launch. How each step moved the model, by the engine's KL mode against the +bf16 model over the same 83K positions (docs/TOOLS.md, "The KL mode"): + +| | all: mean KL | all: top-1 | text + assistant: mean KL | text + assistant: top-1 | +|---|---|---|---|---| +| int4 `-8..7`, round to nearest, E4M3 trunk (`qwen4exp-w4-hc8m.recipe`) | 0.1357 | 90.35% | 0.0440 | 92.46% | +| `w4nla8h` experts, GPTQ | 0.1098 | 91.36% | 0.0363 | 93.30% | +| + int8 W8A8 trunk | 0.0841 | 92.46% | 0.0277 | 94.07% | +| + int8 lm_head | 0.0830 | 92.84% | 0.0265 | 94.54% | +| **+ E4M3 scales a 64, coordinate descent (`w4nl64a8h`) -- served** | **0.0789** | **92.85%** | **0.0239** | **94.57%** | +| + every down projection at five bits (`w5nl64a8h`) -- not served | 0.0717 | 93.34% | 0.0204 | 95.10% | +| a second bf16 implementation (the floor) | 0.0399 | 95.13% | 0.0111 | 96.44% | + +The served container's tail: median 0.0037, p99 1.65, p99.9 5.33. **The floor is not zero and is +most of the overall mean**: the tool-documentation system prompts in the corpus are numerically +chaotic, and two bf16 implementations already disagree there at KL 0.142 -- so text and assistant +turns are the slice comparable with other quantisers' published numbers, and the overall mean of +~0.04 is the floor itself rather than a target a quantised model can reach. + +What it costs, two cards, production flags, against `w4nla8h` with the same trunk: decode +15.28 -> 15.32 ms a step (+0.3%), a 26K-token prefill 6539 -> 6442 tokens a second (-1.5%). The +five-bit down projections cost decode +4% and prefill **-19%**: the experts are 8% larger, fewer of +them fit beside the KV cache (137.5 resident a layer against 149), and a prefill streams the rest. + +**Where the rest of the loss is.** Emulated with the experts of some layers left bf16 and the rest +as served (an HF reference with the container's quantisers, which matches the engine to 0.001): + +| | all: mean KL | all: top-1 | text + assistant | system / user | +|---|---|---|---|---| +| served | 0.0789 | 92.85% | 0.0239 | 0.2732 | +| every down projection bf16 | 0.0700 | 93.61% | 0.0203 | 0.2456 | +| layers 16-31 bf16 | 0.0631 | 93.51% | 0.0226 | 0.2064 | + +Both are a third of the experts' bytes. Five-bit down projections already take ~80% of what bf16 +down projections would; layers 16-31 hold more of the overall mean -- almost all of it on the +chaotic system and user turns -- and text and assistant turns are most sensitive in layers 24-39. +Round-to-nearest experts in one group of eight layers at a time, the rest bf16, put the excess +over the floor at .012, .017, .031, .026, .020 and .009 for layers 0-7 through 40-47. + +**What did not pay**, measured: GPTQ's act order (no change once the +weight is rotated), its dampening at 0.003 and 0.03 (within 0.4%), a codebook of the layer's own +(Lloyd's fit is the same in every layer) or one refitted at groups of 64 or for the E4M3 grid +(worse), a power-of-two sub-scale a 32 under the 64-wide scale (0.0679 -> 0.0675), +a 256-word two-dimensional codebook a pair of weights (10% less error than the scalar table, for an +LDS lookup a byte), more protected bf16 experts (+4% bytes for 7% less error), and E4M3 scales a 32 +(13% less error energy for +13-18% on the expert GEMMs). + +**Further quality levers**, in order: five bits on both projections of layers +16-31 (the same +8% as the down projections, ~0.066 expected); fewer layers at five bits for a +smaller prefill cost; and `--expert-vs-cache-ratio`, which buys the residency back with KV +capacity. The formats, the kernel and a layer's own choice of form are all in the tree. + +## The stored plane + +Row-major packed nibbles, two's complement `-8..7`, with a **bf16 scale per (row, group of 128 +along K)** -- not the fp8 path's 128x128 tile scale, which would spend all sixteen levels on the +largest row in a block. The kernel is `moe_gemm_w4a8` (libr4d), which is the fp8 kernel with the +LDS staging and the scale fold changed: the integers `-8..7` are exact in E4M3, so a code expands +losslessly and the existing fp8 WMMA loop is untouched. + +The encodings are **not interchangeable**: + +| encoding | kernel dtype | what it means | +|---|---|---| +| `i4*bf16[1x128]` | `w4a8` | int4 codes, a bf16 scale per row and group of 128 along K | +| `i4*bf16[1x128]/fwht128` | `w4a8h` | the same, with a 128-wide Walsh-Hadamard along K applied before quantising | +| `affine:codes=u4[1x1],scale=bf16[1x128],table=f32{1x16}/fwht128` | `w4nla8h` | the rotated plane with the codes indexing the `w4nl` codebook (below) | +| `affine:codes=u4[1x1],scale=fp8_e4m3[1x64],scale.1=f32[*x*],table=f32{1x16}/fwht128` | `w4nl64a8h` | the codebook with an E4M3 scale a row and group of **64**, under one fixed f32 (below) -- the same bytes | +| `affine:codes=u4[1x1],scale=fp8_e4m3[1x32],scale.1=f32[*x*],table=f32{1x16}/fwht128` | `w4nl32a8h` | the same at a group of **32**, +0.125 bits a weight | +| `affine:codes=u5[1x1],scale=fp8_e4m3[1x64],scale.1=f32[*x*],table=f32{1x32}/fwht128` | `w5nl64a8h` | `w4nl64a8h` with **five-bit** codes into the 32-level `w5nl` codebook (below), +1 bit a weight | + +The first two have the same planes, extents and byte count and differ only in the transform; the +container says which encoding each expert has. The architecture plugin asks for the first expert's encoding (`rad_weight_encoding`) and +declares the matching kernels, and a kernel that does not read an encoding is not a candidate for +it -- a rotated container cannot be served unrotated. libr4d reorders each row's nibbles into the +order its unpack reads when the experts load; the container holds them in the canonical order. The +activation side is `had_quant_act_fp8` / `gated_had_quant_fp8`, which are the ordinary fp8 +quantisers with `r4d_fwht_wave<128>` between the load and the absmax -- free, because that +kernel's mapping (one wave a 128-column group, four consecutive columns a lane) is already the +transform's. + +**The residual factor is not split.** `H` is symmetric, so ` = 128 `, and the whole +factor of 128 is folded into the **stored weight scale** by the quantiser (`bf16(amax/7) / 128`). The +int8 rotated ops fold `1/sqrt(group)` into each side; these fold nothing at runtime. That the fold +goes entirely into the stored scale rather than being split is normative in `docs/OPS.md` +(*Quantisation and rotation*, the `group` parameter under the `had_*` FP8 forms), which is also +where the cost of splitting it is stated. + +## The w4nl codebook + +A Hadamard-rotated expert weight is close to normal, and sixteen evenly spaced levels are not the +best sixteen for a normal value: the outer levels are rarely used and the inner ones are too far +apart. `w4nla8h` keeps everything about the rotated plane -- the bytes a code, the bf16 scale a row +and group of 128, the rotation, the activation quantiser, the GEMM -- and changes only what a code +stands for: + + codes 0..7 1.125 3.25 5.5 8 11 14 18 22 + codes 8..15 the same, negated + +Lloyd's quantiser fitted to the rotated, amax-normalised experts of Qwen3.8-Flash-Next gives the +same levels in every layer and both projections once each is rounded to E4M3, and every one is +exact in E4M3 -- so the kernel expands a code to the byte the fp8 WMMA reads with no rounding, as +it does `-8..7`. The decode is the same three byte permutes with another four dwords in them: the +table is a kernel argument (`r4d_args.h`, `kW4IntPerm` / `kW4nlPerm`), so both formats are one +code path and the same fifteen VALU per eight weights. + +In libquant it is the named codebook `table=w4nl`, which a recipe pairs with `rule=search` (each +group's scale searched for least error, from 0.70 to 1.10 of amax / 22 and each candidate's +least-squares refit) and `gptq`. **An encoding cannot say what its table holds**, so the codes view +selects the `table` plane beside the codes, and the relayout compares it with the kernel's value +for value before it serves a byte: a container quantised against any other table of the same shape +is refused at load. + +Measured as held-out output error (`sqrt(tr(dW H dW^T) / tr(W H W^T))`, the layer's pooled gate_up +Gram and each expert's own down Gram, 6 experts in each of 7 layers), at the same 4.125 bits a +weight: + +| | gate_up | down | +|---|---|---| +| `-8..7`, scale amax/8 | 0.0889 | 0.1048 | +| `-8..7`, searched scale | 0.0849 | 0.1005 | +| `w4nl`, searched scale | 0.0755 | 0.0896 | +| `-8..7` + GPTQ | 0.0629 | 0.0832 | +| `w4nl` + GPTQ | **0.0547** | **0.0720** | + +`-8..7` at amax/7, what `w4a8h` containers were converted with, is a further ~10% worse than the +first row. Halving the group to 64 at bf16 scales (+3% of the expert bytes) does less than the +codebook does for nothing -- and at E4M3 scales it costs nothing at all (below). + +## Finer groups at the same bytes: E4M3 scales under a fixed 2^-13 + +A bf16 scale a 128 is sixteen bits a 128; an E4M3 scale a 64 is the same sixteen. What an E4M3 +scale lacks is range, and the experts do not need it: with the rotation's 1/128 folded in, the +scales of Qwen3.8-Flash-Next's routed experts at a 64 sit between 2^-15 and 2^-10.6 (every 37th +expert of eight layers), so under one fixed factor of **2^-13** each is a normal E4M3 value with +four binades to spare either side -- and E4M3's three mantissa bits are the same in every binade, +so a per-row second level would buy range nobody uses and no precision. The factor is libr4d's +`kW4G64Scale`; a container states it as libquant's fixed second level (`scale2=f32 block2=*x* +scale2_value=0.0001220703125`), and the scale view's relayout compares it with the kernel's before +it serves a byte, as the codes view does the table. libquant searches each group's scale **as +stored**: once the second level is known the first is searched again over the E4M3 values it can +take, or the rounding gives back most of what the search won. + +The kernel stages a 128-wide tile's E4M3 scales as one 16- or 32-bit load, sums each scale group's +WMMA in its own accumulator -- folding a group as it ends would make the next group's WMMA wait on +its results -- and folds them together at the end of the tile. Held-out output error, GPTQ + `w4nl` +(layer 20 and 28's experts): + +| | gate_up | down | bits a weight | +|---|---|---|---| +| bf16 a 128 (`w4nla8h`) | 0.0683 / 0.0708 | 0.0842 / 0.0957 | 4.125 | +| E4M3 a 64 under 2^-13 (`w4nl64a8h`) | 0.0655 / 0.0679 | 0.0807 / 0.0917 | 4.125 | +| E4M3 a 32 under 2^-13 (`w4nl32a8h`) | -- / 0.0632 | -- / 0.0850 | 4.25 | + +and three sweeps of coordinate descent after GPTQ (libquant `cd=3`) take another ~2% off either. +What the finer groups cost in the GEMM, against `w4nla8h` at a decode step's 4 tokens and a +2048-token chunk: `w4nl64a8h` +4% / +2% and +7% / +4% (gate_up / down); `w4nl32a8h` +13% / +15% +and +18% / +11% -- the 32-wide form is for the layers that need it, not the model. + +## Five bits where the error is: w5nl64a8h + +The 64-wide form at one more bit a weight. libquant's `table=w5nl` is Lloyd's quantiser with +sixteen magnitudes, fitted to the rotated experts at groups of 64 as `w4nl` was -- the same to +three places in every layer and both projections -- and rounded to E4M3 at the top level (30) that +leaves the sixteen distinct and moves them least: 0.8125, 2.5, 4, 5.5, 7.5, 9, 11, 12, 14, 16, 18, +20, 22, 24, 26, 30, then their negatives. The order makes a code's high bit its sign, so the +kernel expands the low four bits exactly as a `w4nl` code -- out of the sixteen magnitudes -- and +sets each byte's sign from a bit plane stored after the row's nibbles. That plane is a dword a 32 +elements, transposed so that a shift by m puts the signs of the expansion's output dword m on +E4M3's sign bits at once: two VALU per four weights. + +Held-out output error under the production quantiser (GPTQ, an E4M3 scale a 64 under 2^-13, three +sweeps of coordinate descent), layers 20 and 28: + +| | gate_up | down | +|---|---|---| +| `w4nl64a8h` | 0.0638 | 0.0943 | +| `w5nl64a8h` | 0.0335 | 0.0501 | + +-- 72% less error energy for 25% more expert bytes on whatever it is applied to. In the GEMM +against `w4nl64a8h`, at a 2048-token chunk: +19% gate_up, +8% down, most of it the extra bytes +streamed. At a decode step the projection reads 25% more from DRAM. (`r4d_selftest --perfmoe` at a +decode step's 4 tokens times one routing again and again, so its experts sit in the 64 MB last-level +cache: there the five-bit gate_up falls out of it and reads 3x slower, which a served decode step, +reading ~3 GB of experts, never sees.) + +Every down projection at five bits (`data/recipes/qwen4exp-w5dn64-i8-hc8m.recipe`) is measured in +"What is served" above: 0.0717 / 93.34% against 0.0789 / 92.85%, for -19% prefill. + +**WHERE IT GOES IS A PER-PROJECTION, PER-LAYER CHOICE.** The codebook forms at E4M3 scales -- +`w4nl64a8h`, `w4nl32a8h`, `w5nl64a8h` -- share the rotated input, the scale views and the +accumulators and differ only in the GEMM's dtype, so a recipe may put any projection of any layer +in any of them, and the MoE block takes each layer's two from that layer's own experts. + +## Rotation alone is expected to be worse + +A rotation fixes **range**, and a group-128 absmax already handles range. Measured on the 27B, +Hadamard was **2x worse** for RTN int4, and e4m3 activations went 0.02024 -> 0.02254 KL under one. +The rotation is here because it is the substrate an error-feedback packer needs underneath it -- +the pair is what gets measured, not this half: a recipe asks for `transform=fwht128` together with +`gptq`, not on its own. + +## Calibration, and why it is a separate run + +GPTQ needs `H = sum over tokens of x x^T` for the layer's real input. That needs the model +**running**, and a container has to be written before it can be served. So the order is a +bootstrap: + +1. **convert with plain absmax** -- the experts quantised by `rtn` +2. **serve that** with `RADIANCE_CALIB_DIR` set, and push a corpus through prefill +3. **convert again**, the experts quantised by `gptq calib=` + +The production recipe takes the second route below instead: its Grams are recorded from the bf16 +checkpoint. + +A second moment is robust to the small perturbation the first container's own error puts on the +activation, which is what makes step 2 legitimate. + +**Or calibrate the checkpoint as it ships, with no bootstrap at all.** Converted without a recipe, +Flash-Next is a 335 GiB bf16 container, and `--weights-disk-tier` serves it at two cards by reading +each routed layer's non-resident experts from the container a pass at a time (GUIDE.md §4.3). Its +tap reads the bf16 activation the bf16 experts multiply -- no upstream layer quantised -- and writes +its Hessians in the model's own domain; a rotated recipe's GPTQ reads them rotated into its own. +Whole experts per rank, which a calibration run wants anyway. A step reads about 100 GiB a rank from +the drive and grows only slowly with what it carries -- 50 s at ~32K tokens, 59 s at ~55K -- so +drive it with large prefill steps: `--max-num-batched-tokens 65536 --max-num-seqs 64`, about 96 +requests in flight, and `--expert-vs-cache-ratio 0.5` so the cache share holds 64 sequences' +recurrent state. That records ~930 tokens a second, ten million tokens in three hours. + +**The corpus is what the Hessian is of, so it has to look like the traffic.** A few thousand +tokens of one repeated sentence gives a Gram whose energy sits in a handful of directions, and GPTQ +then hides its error in the directions the corpus never excites -- an in-sample number that says +nothing. Score on Hessians from a held-out slice of the corpus, never on the ones the weight was +fitted to. + +**A million tokens is enough for the tap's Hessians; the held-out slice wants more.** The tap pools +a layer's Gram over every expert, and on Flash-Next one recorded from 10M tokens beat one from 1M by +under 1% on 1.8M held-out tokens (GPTQ on gate_up, layers 0-47), with no change on down or under +AutoRound. What the larger corpus does fix is the scoring: the gap between in-sample and held-out +error drops from up to 3% to under 1% on gate_up, and a 113K-token held-out slice put layer 47's +down GPTQ at 0.49x RTN where 1.8M tokens say 0.60x. + +```sh +# 1. the uncalibrated container: the recipe's expert rule is rtn, int4 g128 rotated +rad-convert -o model-absmax.rad --recipe data/recipes/qwen4exp-w4.recipe + +# 2. the calibration run. Stops at RADIANCE_CALIB_TOKENS (default 65536) and writes once. +RADIANCE_CALIB_DIR= RADIANCE_CALIB_TOKENS=65536 \ + radiance --model model-absmax.rad ... +# ...then drive prompts at max_tokens=1 until it prints +# radiance: calibration wrote layer Hessians after N tokens to + +# 3. the calibrated convert: a --quant rule ahead of the recipe's own puts the experts through +# GPTQ against calib=$CALIB (a recipe whose expert rule names calib=$CALIB itself, as the +# production one does, needs no --quant) +CALIB= rad-convert -o model-gptq.rad \ + --recipe data/recipes/qwen4exp-w4.recipe --reuse model-absmax.rad \ + --quant 'blk.*.ffn_*_exps.*.weight=gptq:codes=i4,group=128,scale=bf16,transform=fwht128,calib=$CALIB' +``` + +`--reuse` in step 3 copies every weight whose encoding, quantiser and options did not change -- all +but the experts -- from the first container. **The format is a property of the container**: each +expert's encoding is in its entry, the plugin reads it from there, and the recipe that made it is +in the header (`rad-info --recipe`), `calib=` included, so a reader can tell an error-feedback +plane from a plain absmax one. + +The files are `gram.r..bin`: a 32-byte `RADGRAM2` header (`k`, `rank`, `rows`, `domain`) +then `k*k` f32. `domain` is what the tap summed: 0 for the model's own activation, 128 for the +rotated one a `w4a8h` container's kernel multiplies; libquant brings every file into the domain the +recipe's grid quantises in before summing them, so a bf16 model's Hessians serve a rotated recipe. +**Named after the weight they will pack, minus the expert index**, because that is +the whole protocol between the engine and the quantiser -- `gptq` is given a directory and a weight +name, and strips `..weight` to find its file. A name of the tap's own +would have made the quantiser carry a per-architecture table. + +**`down` gets a Hessian an expert.** A routed expert's `down` input is its own intermediate units, +so channel `i` of one expert has nothing to do with channel `i` of another, and a Gram pooled over a +layer's experts describes none of them: on Flash-Next a typical expert's own profile has a median +cosine of 0.15-0.87 with the pool, and in the last layers the pool *is* one expert. The tap also +sums each local expert's rows into its own Gram -- the same `gram_accum` once an expert over its run +of the sorted rows, into a layer-sized scratch that comes back to the host every pass (640^2 f32 for +256 experts a rank is 10 GB a rank as packed triangles) -- and writes +`gram.r.blk.L.ffn_down_exps..bin` beside the pooled file. libquant reads an expert's own +file when it holds at least 4K rows and the layer's otherwise. Fitted to its own Gram, a Flash-Next +expert's down projection comes out 20-55% below round-to-nearest on its own held-out Gram, where the +pooled Gram bought 0-10%; the super experts gain most (layer 47's expert 399: 0.204 rounded, 0.137 +pooled, 0.065 own). Under ~2K rows the own fit fits its rows and can lose to rounding, which is why +the threshold: below it sit 0.6% of the routed rows. The per-layer sync it costs roughly +halves a disk-tier recording's throughput, which is why the per-expert sets are recorded from a +million tokens. + +Three things about the tap worth knowing before reading its numbers: + +- **The gate_up tap is the unsorted activation and loses nothing.** Every token is routed to + exactly `top_k` experts, so the gathered distribution IS the token distribution times `top_k`, + and GPTQ is invariant to a positive scale on H. `top_k` times cheaper for the same matrix. +- **It taps the quantiser's output, not the bf16 before it.** The Hessian wanted is of the operand + the expert GEMM actually contracts -- and under `w4a8h` that is the only form the activation has. +- **Per rank, and the quantiser sums.** Under expert parallelism a rank's `down` input is only the + tokens routed to its own experts. Its gate_up input is the whole token set on every rank, so + summing those double-counts by `world` -- a positive scale, harmless. One rule beats two. + +## Protected experts + +**A few experts carry a large share of a layer's output, and those are kept plain bf16.** In +Flash-Next's last layers one expert's `down` input holds a sixth of the layer's energy from a third +of a percent of its routing, nearly all of it in one channel (layer 47, expert 445). Four bits cost +it the same *relative* error as any expert -- about 12% of its output under its own profile -- but its +output is that much larger, so the absolute error is too. unsloth's GGUFs upcast the whole layer's +`down` for this (a GGUF type is per tensor, and a tensor is all 512 experts); a container keeps an +expert's encoding per expert, so here only those experts are kept, at ~7 MB each. + +A recipe names them with a rule ahead of the expert rule, `blk.47.ffn_*_exps.445.weight cast +dtype=bf16`, and the layer serves them apart: the sort places them last (`moe_scatter`'s `protect`), +the four-bit GEMMs serve the other experts, and a bf16 `moe_gemm` pair serves the trailing run of the +offsets, writing the routed rows the four-bit `down` GEMM left zero. Their weights are the layer's +static weights, not expert slots -- a container's experts in a layer are one fixed-size unit each -- +so they are always resident and the file tier never reads them. Where every rank holds a slice of +every expert, it holds an even slice of these too -- 320 of the 640 intermediate units at two ranks, +since a bf16 expert has no scale blocks to respect -- and the block's all-reduce sums the partials. +The count must keep the rest even, because the four-bit GEMM takes them as two equal tables by parity. + +## The quantiser + +`gptq` in libquant (`libquant/lq_gptq.{h,cpp}`), over any grid `rtn` takes. H is damped by 1% of its mean diagonal, inverted, and re-factorised +into the upper triangle `U` with `U^T U = H^-1`; then columns are quantised left to right and each +column's rounding error is pushed into the columns to its right, weighted by `U`. Blocked 128 +columns at a time so `U` is streamed once rather than once per row, and parallel over rows because +the recursion is independent in the row index. + +**The scale grid is fixed from the weight before any code is chosen** -- the "static groups" +variant. The scales are then exactly the ones `rtn` writes for the same weight, which +`tests/relayout_parity_test.cpp` checks, and the grid does not depend on the order the columns are +visited in. + +**Cost.** Budget tens of minutes of extra convert time for a 48-layer container, and ~1.3 GB of +factor cache held for its duration. The quantiser is OpenMP-parallel over rows, so the wall time +falls with core count; the cache is a property of the model, not of the machine. The factorisation +is per layer and projection, not per expert: 512 experts share one factor. + +**A weight with no calibration file is packed the uncalibrated way and says so on stderr** -- so a +typo'd directory is a message, not a silent quality regression. + +## What is measured + +- `r4d_selftest --case moe_gemm_w4a8` -- the kernel against an independent host decode of the same + planes, both M bands, through the relayout the loader runs. +- `quant_test` -- **GPTQ against the objective it minimises**. The metric is + `||X (W - W')^T||^2 = sum over rows of e H e^T` and *not* rel_l2 on the weight: error feedback + makes the weight worse in the plain sense, deliberately. The control is no Hessian at all, under + which `gptq` must produce `rtn`'s planes **byte for byte**. +- `r4d_selftest --case had_quant_act_fp8` -- every format against the exact f32 dot product, + which is the only way to see whether the quantiser's `fwht_inplace` and the device's + `r4d_fwht_wave` are the same transform, and whether the kernel decodes the `w4nl` codes as their + table entries. 0.2015 (`w4a8`), 0.1307 (`w4a8h`), 0.0991 (`w4nla8h`, round to nearest at + amax / 22), 0.0761 (`w4nl64a8h`), 0.0625 (`w4nl32a8h`) and 0.0469 (`w5nl64a8h`) on a source + with outlier channels; the negative control (rotate the activation, not the weight) measures + 5.32. +- `relayout_parity_test` -- the `w4nla8h` plane's stored bytes pinned, its inverse giving back the + codes and the table, and a container quantised against another sixteen-entry table refused at + relayout; the same for `w4nl64a8h`, `w4nl32a8h` and `w5nl64a8h`, with a second level other than + 2^-13 refused, a 32-entry table other than `w5nl` refused, and each refusing the others' + encodings. `r4d_selftest --case moe_gemm_w4a8` also checks `w5nl64a8h`'s arranged row bit for + bit against the statement in r4d_layout.cpp, and its inverse. +- `r4d_selftest --case gram_accum` -- the accumulator against an f64 host Gram, **launched twice + over a seeded buffer**, because a kernel that stored instead of adding would agree with any + single-call oracle. + +**The end-to-end quality of a container against the bf16 model** is the engine's KL mode +([TOOLS.md](TOOLS.md#the-kl-mode)): the full-vocabulary KL at every position of a fixed corpus, +its mean and its tail percentiles, and the top-1 agreement. It needs the **full 48-layer +container**: the 4-layer bring-up slice cannot resolve a difference this small -- its residual +probe reads the same to within 1% for fp8, `w4a8`, `w4a8h` and GPTQ alike, which says only that +all four compute the same function. diff --git a/docs/OPS.md b/docs/OPS.md new file mode 100644 index 00000000..1e0d2423 --- /dev/null +++ b/docs/OPS.md @@ -0,0 +1,1405 @@ +# The conventional op vocabulary + +Op names are free strings (`spec.md` §2.3) and the core never learns one. But `libref` +cannot implement an op it has never heard of, so **ref's op list is the conventional vocabulary**: +an architecture plugin that stays inside it is guaranteed to run somewhere, and one that invents +an op has no fallback for it (`spec.md` §17). + +This file is that list. `libref/` holds the authoritative `RadOpSchema` rows; this is what +they say, in a form an architecture plugin author reads first. + +**AND IT IS CHECKED.** `tests/CMakeLists.txt` registers `ops_doc`, which dumps every plugin's +schemas with `rad-schemas` and holds every table row below to them — op for op, parameter for +parameter, operand for operand, including the optional markers and the `w` that makes an operand a +weight. Run it by hand as: + + tools/ops_doc_check.sh docs/OPS.md build/bin/rad-schemas build/radiance_home/kernels/*.so + +A row that is a PROPOSAL rather than a description carries a FOURTH COLUMN saying so and is exempt +from the check. That is how an op the vocabulary has agreed on but no plugin declares yet stays in +this document without being a lie, and it is the only way one may. + +An op that a kernel library serves and this document omits gets written against a GUESS at its +schema, and no fallback absorbs a wrong guess — `qk_norm_rope_gate` and `qk_norm_rope` differ in +exactly the way a guess gets wrong, one taking a `theta` and the other a precomputed cos/sin table. +**A document that is WRONG is worse than one that is missing**, because it is read instead of the +source. + +**A ROW HERE DOES NOT MEAN THERE IS A HOST KERNEL.** A table marked **device-only** is declared by +libr4d and by nothing else, so its ops have no oracle for `rad-kbench` and no host fallback: an +architecture that reaches for one is choosing to run on this library or not at all. That is a +legitimate choice — every fusion in this document is one — but it is a choice, and it should be +made knowingly. + +## Conventions + +- Operands are **positional**, in the order given. `w` marks a weight operand, `→` the outputs. +- A tensor's leading dimension is tokens unless stated. Everything is contiguous unless an op + says otherwise; strides are the kernel's business, not the schema's. +- `dtype` is always present and always a string. It names the **operand combination**, which is + why a weight format and an activation format share one key: `bf16`, `f16`/`fp16`, `f32`/`fp32`, + `fp8_e4m3`, `fp8a8`, `fp8a16`, `w4`, `w4a8`, `w4a8_asym`, `w4a8h`, `w8a8`, `w4a16`, `w8a16`, + `w2a8`, `mxfp4a8`. `w4a8h` is `w4a8` with a `group`-wide Walsh–Hadamard along K baked into the + stored weight (`docs/MOE-W4.md`), `w4a8_asym` the unsigned-nibble-minus-zero-point grid rather + than the symmetric one, and `fp8a8`/`fp8a16` say whether a block-scaled E4M3 weight is met by + an fp8 activation or a bf16 one. `q_dtype` and `kv_dtype` are the same key split in two where + attention reads two formats at once. +- `M` is the ranged parameter wherever a token count appears. **At most one ranged parameter per + op** — that is what keeps `rad_issue` a single integer on the hot path. +- Every op below returns `RAD_OK` or a negative `RAD_E_*`. There is no partial success. +- In a row, `?` marks an optional operand, `/opt` an optional parameter and `/der` a derived one, + and none of the three is decoration: `/der` says the KERNEL supplies the value rather than the + caller, an omitted optional parameter is one a kernel will ignore when a caller passes it, and a + constraint on an `:f64` key never matches, because a tolerance is not a predicate. + +## How a schema is written + +`libref` and `libr4d` implement the same ops from opposite ends, and a schema they do not agree on +cannot be loaded at all — the loader refuses the whole plugin on any one conflict, which makes +every other row of it unreachable and `rad-kbench` unrunnable. Four rules settle every case, and +they are why `gdn_conv_prep` and `gdn_recurrent_update` carry the long operand lists they do. + +### The four rules that resolve every case + +1. **Operands are the UNION, and anything only one implementation needs is `optional`.** A schema + that lacks an operand cannot express the call at all, so the narrower reading always loses. An + implementation ignores an optional operand it does not use; it cannot invent one it needs. +2. **Parameters are the UNION, and anything only one implementation needs is `optional`.** Same + argument. A constraint on an absent key simply does not hold, which is the correct answer and + is how `hops` works. +3. **A float-valued parameter is `RAD_P_F64`.** `eps`, `scale`, `theta`, `softplus_thr`, `l2_eps`, + `wadd`. A `"%.9g"` string round-trips an IEEE single exactly and is unreadable in a graph dump, + which is the whole of the argument against spelling them as strings. **Constraints never match + on a float** — a tolerance is not a predicate, and a kernel that cares about `eps` to that + precision has a bug. +4. **An enumerated parameter is `RAD_P_STR` with named values.** `act` is `"silu"` or `"sigmoid"`, + not `0` or `1`. A graph dump reading `act=1` is precisely the "unclear what actually runs" + complaint this engine exists to answer; a plugin's launch adapter maps the name to whatever + integer its kernel wants. + +The union rule has exactly two deliberate exceptions, both on the gated delta net and both argued +where those ops are described: `cu` and `num_accepted` are REQUIRED, because an op that lets the +caller omit either is an op whose contract is optional. + +### Parameters the kernel supplies + +`attn_paged.block_size`, `gdn_chunk_scan.chunk`, `gdn_kkt_solve.chunk` and `gdn_conv_prep.chunk` +are supplied by the **kernel**, not the caller (`spec.md` §7.2, and `RAD_DERIVED` in `rad_abi.h`). +Constraints on them are skipped during matching and the winning kernel's `RAD_C_EQ` value is +written into the resolved geometry afterwards. Declaring them `RAD_REQUIRED` makes them +unselectable: a constraint whose key the geometry lacks does not hold, so a kernel compiled for +`block_size == 16` could never be reached by the query whose answer was to be read off it. + +`gdn_conv_prep.chunk` has a cost the other three do not: nothing in conv_prep's operands carries +the chunk length, so `libref`, which declares no `RAD_C_EQ` to answer with, returns `RAD_E_SHAPE` +by name when a caller omits it rather than quietly treating the whole sequence as one chunk. +libr4d supplies 64. + +`all_reduce.hops` is `RAD_OPTIONAL` — a one-shot/two-shot distinction the caller may state and +usually should not. `all_reduce.exact` stays `RAD_REQUIRED`: a caller that does not say it will +accept a lossy wire gets no kernel rather than the quantised one. + +### Weight operands, and the weight TABLE + +- **`RAD_OPD_WEIGHT`** — the issue names one weight handle, and the kernel receives that weight's + bytes, its dtype and its declared shape. +- **`RAD_OPD_WTAB`** — the issue names the FIRST handle of a run and the run's length, and the + kernel receives a device array of `n` pointers, one per entry. + +`RAD_WTAB(h, n)` in `abi/rad_runtime.h` is the issue-side spelling, and `rad_decl_weight` handing +out consecutive indices is what makes a declaration loop over experts produce such a run. + +**Why it is a table and not a base plus a stride.** A layer's experts are separate movement units +(`spec.md` §4.1): after placement one is in VRAM, the next is streamed over the link and the third +is still on disk. `base + e * stride` describes exactly one of those cases — the one where nothing +was offloaded — and expert offload is the reason the placement engine exists. So the core resolves +every handle in the run the way it resolves any weight (residency table, mover event, use note) and +uploads a pointer array, rebuilding it only when a pointer actually moved. + +**What the kernel sees.** `RadTensor::data` points at the pointer array; `shape[0]` is the entry +count and **`stride[0]` is 0**, which is the marker. `dtype` and the trailing extents and strides +are ONE entry's, and every entry of a run must agree about them — the core refuses the issue by +name if they do not, because a table whose entries have different shapes is a table the kernel +cannot walk. A kernel may also accept the STACKED form (an ordinary rank-3 tensor with a real +leading stride): `rad-kbench` replaying a fixture has nowhere to put a pointer array, and both +libref and libr4d read either, so a described case runs against the same bytes the engine would +hand it. + +**How the declaration divides.** An op may carry several table operands — `moe_gemm_q` has four, +the codes and the scale planes of its even experts and of its odd ones. Whatever is left after the fixed weight positions have taken one each +is split EVENLY across the table positions, in declaration order, and a division that does not come +out whole is refused at declare. That is exactly right for the case tables exist for: every table of +one MoE op takes one weight per expert. + +## What the loader enforces + +**A kernel plugin must declare a `RadOpSchema` for every op it has a `RadKernelInfo` row for.** +The loader checks this after the whole hierarchy is open — deferred to the end because an override +plugin may legitimately rely on the schema of the plugin below it — and refuses the load naming the +plugin and the op. Without the rule, a typo and an unimplemented op are the same diagnostic. + +The first plugin in hierarchy order to declare an op **fixes its schema**. A later plugin declaring +the same op name with a *different* schema is refused at load with both plugins named; declaring it +identically is fine and is what every plugin implementing a shared op does. Since arguments are +positional, two disagreeing schemas would make the same call mean different things depending on +which plugin won selection — silent numerical garbage rather than a diagnosable failure. + +`build/bin/rad-schemas a.so b.so` prints and diffs what plugins actually declare. Run it before +adding a kernel plugin; "refused at load" names one op and leaves you to find the rest. + +--- + +## Elementwise and norms + +| op | params | operands | +|---|---|---| +| `rmsnorm` | `M`(range) `n` `eps`:f64 `dtype` `wadd`:f64/opt | `x`, `w`w → `y` | +| `rmsnorm_add` | `M`(range) `n` `eps`:f64 `dtype` `wadd`:f64/opt | `x`, `residual`, `w`w → `y`, `residual_out` | +| `hc_enter` | `M`(range) `n` `hc` `dtype` | `x` → `h` | +| `hc_read` | `M`(range) `n` `hc` `lowrank` `eps`:f64 `dtype` `wadd`:f64/opt `inject`/opt `group`/opt `rotate`/opt `mix`/opt | `h`, `w`w, `mix_down`w, `mix_up`w, `inject_w`w? → `x`, `inj`?, `q`?, `scale`?, `rq`?, `rscale`? | +| `hc_write` | `M`(range) `n` `hc` `dtype` | `y`, `inj`, `h`:inout | +| `layernorm` | `M`(range) `n` `eps`:f64 `dtype` | `x`, `w`w, `b`w? → `y` | +| `grid_embed` | `M`(range) `n` `side` `dtype` | `x`:inout, `table`w, `coord` | +| `add` | `M`(range) `n` `dtype` | `a`, `b` → `y` | +| `mul` | `M`(range) `n` `dtype` | `a`, `b` → `y` | +| `silu_mul` | `M`(range) `n` `dtype` | `gate_up` → `y` (splits `[M,2n]` into gate·up) | +| `gelu` / `silu` | `M`(range) `n` `dtype` | `x` → `y` | +| `cast` | `M`(range) `n` `from` `to` | `x` → `y` | +| `softmax` | `M`(range) `n` `dtype` | `x` → `y` | +| `sigmoid` | `M`(range) `n` `dtype` | `x` → `y` | +| `silu` | `M` `n` `dtype` | `x` → `y` | + +`gelu` and `silu` are two ops with one schema, and `silu` carries a row of its own because a row +names one op. + +`rmsnorm_add` exists because the residual add and the next norm are one pass in every real +implementation. A plugin asks for it first and falls back to `add` + `rmsnorm` (`spec.md` §2.3). + +`hc_read` / `hc_write` are the GATED RESIDUAL pair, which is what a hyper-connection model has +instead of a pre-norm and a residual add. The stream is `hc` times the model width and every block +reads a mix of the `hc` sub-streams and writes back into all of them, both gated by data: + + hc_read N = grouped_rmsnorm(h) one rsqrt per n-wide stream, one hc*n gain + g = sigmoid(mix_up @ silu(mix_down @ N / hc)) + x = mean over the hc streams of g * N + inj[s] = 2 * sigmoid(inject_w[s] . N / hc) + hc_write h[s] += inj[s] * y + +Three facts that are not derivable from the others and that a second implementation has to match: +the mix is a MEAN over the streams and not a sum; there is a separate `/ hc` inside each of the two +gate arguments; and **`hc_write` adds into the UNNORMED `h`** -- the normalisation is consumed by +the block input and the gates and never enters the residual. Writing into `N` instead re-normalises +the stream 96 times over and still produces fluent text. + +`inject_w` absent is the final mixer, which collapses the wide stream to one and has nothing to +write back; `group` absent is a read whose consumer wants bf16. Otherwise the fp8 form of `x` comes +out of the same pass, because a model with 96 connections cannot afford a separate quantise launch +at each of them -- and it is quantised from the NARROWED `x`, not from the accumulator, so a fused +kernel and the reference agree bit for bit. `rotate` adds `rq`/`rscale`: `had_quant_act_fp8` of the +same stored `x`, each group rotated by an unnormalised Hadamard before its absmax, for a consumer +whose weight plane carries the rotation (the w4a8h experts) -- which then needs no quantise launch +of its own either. + +`mix` is the mixing matrices' STORED format: `bf16`, or `e4m3` -- rows of E4M3 codes with f32 +scales in each row's own tail, a 128-column group for `mix_down` and a quarter row for `mix_up`. +It changes the bytes a step reads, not the arithmetic above; the two matrices are replicated on +every rank and read once a connection, so at 96 connections the format is worth half of 1.26 GB a +step on Qwen3.8-Flash-Next. + +`mul`'s `b` operand may have extent 1 on any dimension where `a` does not, and is broadcast along +it. Every other elementwise op keeps the strict same-shape rule. + +`sigmoid`, with a broadcast-capable `mul`, is what a gated shared expert needs +(`ffn_gate_inp_shexp`). Without it the shared expert runs ungated, which is a different model. + +## Quantisation and rotation + +| op | params | operands | +|---|---|---| +| `quant_act_i8` | `M`(range) `n` `group` `dtype` | `x` → `q`, `scale`, `asum`? | +| `had_quant_act_i8` | `M`(range) `n` `group` `dtype` | `x` → `q`, `scale` | +| `rmsnorm_had_quant_i8` | `M`(range) `n` `eps`:f64 `group` `dtype` `wadd`:f64/opt | `x`, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`? | +| `gated_had_quant_i8` | `M`(range) `n` `group` `dtype` `act`:str/opt `mode`/opt | `a`, `b`? → `q`, `scale` | +| `dequant` | `M`(range) `n` `group` `dtype` | `q`, `scale` → `y` | +| `gram_accum` | `M`(range) `n` `group` `dtype` | `a`, `a_scale`?, `h`:inout | + +`gram_accum` is the odd one here and belongs in this table anyway, because it characterises a +quantiser's output: `h[k1][k2] += sum over rows of dequant(a)[m][k1] * dequant(a)[m][k2]`, in f32. +That is the Hessian a GPTQ packer needs, over exactly the operand the consuming GEMM contracts. +**`h` is `[n, n]` and INOUT** -- a caller zeroes it once and drives a whole calibration corpus +through the graph, so each launch adds its own block; an implementation that stored instead of +added would agree on one call and disagree on a corpus. It is **not** `gemm_nt` with a transposed +operand: that op contracts the LAST axis of both sides and this one contracts the FIRST, so +expressing it as a GEMM would need `x` materialised transposed. It is also the one op in this +document that **no forward pass issues** -- it runs under a calibration flag and its result is +read at convert time, in another process, through a file. + +**`a_scale` is optional, and `dtype` says which reading `a` takes.** `fp8a8` is E4M3 codes with +an f32 dequant scale per (row, `group` columns): the tap of a model whose expert GEMM contracts a +quantised activation. `bf16` is a plain activation read as it stands, with no `a_scale` and no +grouping: the tap of a model served at bf16, whose expert GEMM contracts exactly that. + +**Two activation widths are in use, and which one a linear takes is the WEIGHT's question rather +than a preference.** Where the checkpoint already ships E4M3 weights and a block scale plane, the +activation follows the weight: `fp8a8` is the shipped path (`arch/common/rad_fp8.h`), because the +`fp8a16` form that would read a bf16 activation directly and skip the quantise launch has a kernel +only at `M <= 1` — a single-sequence decode and nothing else. Where the engine quantises the +activation itself, it is **rotated int8**: the rotation is a per-group Walsh–Hadamard, and it is +what makes a single scale per row viable at all, which is what an int8 row buys over a row of +floats each carrying its own exponent. + +**`group` MEANS TWO DIFFERENT THINGS IN THIS TABLE**, and a kernel that reads it the other way is +wrong rather than slow. `libref/ref_quant.cpp` is the definition; this is what it says. + +- **`quant_act_i8`, `dequant`** — `group` is the number of **contiguous elements sharing one f32 + scale**, so `scale` is `[M, ceil(n/group)]`. `group <= 0` or `group >= n` means one scale per + ROW. For `dequant` the same reading, inverted: the scale stream's extent says how many groups + there are and `group` says how wide each one is. +- **every `had_*` INT8 form** — `group` is the **Walsh–Hadamard rotation width** (libr4d spells it + `had`), and the int8 scale is per **ROW**, carrying the `1/sqrt(group)` normalisation. That is + the reading the prose above forces: a per-group rotation is what makes a single scale per row + viable, so the rotation width and the scale granularity cannot be the same number. +- **the `had_*` FP8 forms** (`had_quant_act_fp8`, `gated_had_quant_fp8`) — `group` is **both**, and + that is not an inconsistency but a different bargain. They exist for a four-bit MoE expert whose + scale grid is already one bf16 per (row, 128 of K); making the rotation the same 128 lines the + two up, so the scale is per group here and shaped `[M, n/group]` exactly as `quant_act_fp8`'s is. + They also do **no normalisation at all**: ` = group * `, and the whole residual + factor is folded into the **stored weight scale** at convert, where dividing a bf16 by a power of + two is exact. Splitting it as the int8 forms do would round `amax/7/sqrt(group)` into bf16 and + land a ~0.2% multiplicative error on every group. `n` must be a multiple of `group`: a rotation + block cannot straddle the end of a row. +- **`quant_act_i8g`, `had_quant_act_i8g`** — `quant_act_fp8`'s grouping and scale shape at INT8 + codes: one f32 scale per `group` of a row, `amax / 127` (1 for a zero group), each code the value + over it rounded to nearest even and clamped to +-127. They are the activation side of the int8 + W8A8 trunk (`gemm_nt_q` at `dtype=i8a8`), which is why they are not `quant_act_i8`: that op's scale + is per row unless asked otherwise, and an int8 GEMM folding a scale per K block needs the block. + The `had_` form rotates first, as `had_quant_act_fp8` does. + +The rotation is unnormalised butterflies at ascending strides `1, 2, 4, ... group/2`, pairing `i` +with `i + h` where `(i & h) == 0`. The `1/sqrt(group)` is folded into the scale rather than applied +to the values -- dividing every element by a constant cannot change which int8 code it rounds to, +and folding it costs nothing. A rotation block may not cross a tensor-parallel shard boundary, so +the width has to divide the PER-RANK `n`. + +`gated_had_quant_i8` serves two readings of its input: the gate and up as two operands, which is +libr4d's, and one fused `gate_up` `[M, 2n]` with the gate first, which is what a fused gate_up +projection produces. Two operands with the second optional expresses both — a caller with a fused +buffer passes it as `a` and omits `b` — and `mode` is optional because it is libr4d's integer +spelling of `act`, not the vocabulary's. + +### The fp8 fusions + +| op | params | operands | +|---|---|---| +| `quant_act_fp8` | `M` `n` `group` `dtype` | `x` → `q`, `scale` | +| `had_quant_act_fp8` | `M` `n` `group` `dtype` | `x` → `q`, `scale` | +| `rmsnorm_quant_fp8` | `M` `n` `eps`:f64 `group` `dtype` `wadd`:f64/opt | `x`, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`? | +| `gated_quant_fp8` | `M` `n` `group` `dtype` `act`:str/opt | `gate_up` → `q`, `scale`, `out_bf16`? | +| `gemm_nt_q_gated` | `M` `N` `K` `group` `dtype` `act` | `a`, `a_scale`, `b`w, `b_scale`w → `q`, `scale`, `out_bf16`? | + +### The int8 and gated fp8 fusions — device-only + +| op | params | operands | +|---|---|---| +| `quant_act_i8g` | `M` `n` `group` `dtype` | `x` → `q`, `scale` | +| `had_quant_act_i8g` | `M` `n` `group` `dtype` | `x` → `q`, `scale` | +| `gated_had_quant_fp8` | `M` `n` `group` `dtype` `act`:str/opt | `gate_up` → `q`, `scale`, `out_bf16`? | +| `gate_quant_fp8` | `M` `n` `group` `dtype` `act`:str/opt | `gate`, `x` → `q`, `scale`, `out_bf16`? | + +`gemm_nt_q_gated` is the row above pulled into the projection that feeds it: `gemm_nt_q` over a +`[N, K]` gate_up plane — `N` is the WEIGHT's rows, twice the fused width, gate half first — with +`gated_quant_fp8`'s pass in the epilogue, so the `[M, N]` bf16 tensor between them is never +written. It is a separate schema and not a flag on `gemm_nt_q` because it does not produce that +op's `y`, and an architecture that resolved it into `gemm_nt_q`'s operand list would hand the GEMM +a buffer of half the width it expects. `act` is REQUIRED here, unlike the quantiser's: an +implementation is free to compile one gate and an optional parameter would let it resolve for +another. + +`out_bf16` is not an optimisation: the unfused pair leaves a bf16 tensor behind and the codes are +taken over *that*, so a layer with a bf16 consumer of the post-norm value must ask for it or the +fusion is a different function. `residual` present is the `fused_add_rms_norm` form. + +### `dequant_w4` — device-only + +`libref` declares `dequant` and nothing else declares `dequant_w4`, so this op is not negotiated +between plugins the way the shared ones are: it is libr4d's own, spelled libr4d's way. + +| op | params | operands | +|---|---|---| +| `dequant_w4` | `N` `K` `group` `dtype` `twos` | `wq`w, `ws`w → `y` | + +`twos` selects the symmetric two's-complement nibble over the asymmetric unsigned-nibble-minus- +zero-point grid. The two differ by bit 3, so the wrong one is not a refusal, it is wrong output. + +**`wq` and `ws` are WEIGHT operands**, and the `w` marker is the load-bearing part of that. Spelt +as plain inputs they name the same bytes, and the core stops resolving their handles and stops +waiting on the mover's event — a read of weight bytes that may not have arrived yet. + +## GEMM + +| op | params | operands | +|---|---|---| +| `gemm_nt` | `M`(range) `N` `K` `dtype` | `a`, `b`w → `y` | +| `gemm_nt_bias` | `M`(range) `N` `K` `dtype` `act`/opt | `a`, `b`w, `bias`w, `res`? → `y` | +| `gemm_nt_q` | `M`(range) `N` `K` `group` `dtype` | `a`, `a_scale`?, `b`w, `b_scale`w → `y`; `a_sum`?, `b_ref`w? | +| `gemm_nt_q_bias` | `M`(range) `N` `K` `group` `dtype` | `a`, `a_scale`, `b`w, `b_scale`w, `bias`w → `y` | + +`nt` is A row-major `[M,K]` times B **transposed** `[N,K]`, giving `[M,N]` — the layout every +weight in a transformer already has. `dtype` distinguishes `bf16` from `w4a8`, so one op name +covers the family and the selector picks by the quant string. That is deliberate: an architecture +plugin that switches quant changes one string, not its op names. + +`gemm_nt_q` takes activation scales as an operand because the quantiser produced them; a kernel +that folds dequantisation into its epilogue still receives them. + +## Attention + +| op | params | operands | +|---|---|---| +| `attn_paged` | `q_len`(range) `head_dim` `gqa` `block_size`/der `causal` `window` `q_dtype` `kv_dtype` `scale`:f64/opt `max_ctx`/opt `n_head`/opt `max_seqs`/opt | `q`, `kv_cache`, `block_table`, `seqused`, `k_descale`?, `v_descale`?, `cu_seqlens`? → `out` | +| `attn_dense` | `M`(range) `head_dim` `gqa` `causal` `dtype` `scale`:f64/opt `max_seqlen`/opt | `q`, `k`, `v`, `cu_seqlens` → `out` | +| `kv_store` | `M`(range) `head_dim` `n_head_kv` `block_size` `kv_dtype` `k_scale`:f64/opt `v_scale`:f64/opt | `k`, `v`, `slot_mapping`, `kv_cache`:inout | +| `rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `scale`:f64 `mode` `rotary_dim`/opt `sections`/opt | `qkv`:inout, `positions` | +| `rope_table` | `M`(range) `rot` `theta`:f64 `scale`:f64 `dtype` | `positions` → `cos_sin` | +| `qk_norm_rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `wadd`:f64/opt | `qkv`:inout, `positions`, `q_w`w, `k_w`w | + +`attn_paged` is the ranged op whose band is `q_len`, not `M`: one query row at decode, up to 64 at +a speculative verify, thousands in a prefill chunk, and libr4d has a different kernel for each +band. `block_size` is **read off the resolved kernel**, not chosen — declare the group, declare +the op, then ask `rad_kv_block_size()` (`spec.md` §7.2). + +`cu_seqlens` is optional and makes the batch **ragged**: `[n_seq+1]` i32, sequence `s` owning query +rows `[cu[s], cu[s+1])` of the dense `q` and `out` blocks. Absent, every sequence must present the +same query length and `total_q` must divide `n_seq`. Pass it: a mixed step — one sequence's prefill +chunk beside other sequences' decode rows, which carry their own verify windows and so are not one +row each — is what the scheduler builds whenever prefill and decode coexist, and it does not +satisfy the uniform form. `q_len` is then the batch MAXIMUM, which is what selects the band; the +per-sequence lengths come from `cu_seqlens` alone. + +`attn_dense` is the vision tower's: non-causal, nothing paged, `cu_seqlens` bounding one image per +entry so a whole batch is one launch. `q`, `k` and `v` may each be `[tokens, heads, head_dim]` or +`[tokens, heads * head_dim]`, and the second form may be a column slice of a fused projection read +at that projection's row pitch -- which is how a tower's `[q|k|v]` row reaches it without a copy. + +**`rope`'s multi-component modes.** `mrope`, `imrope` and `axial` rotate with NeoX pairing and let +several position components drive different frequencies. `positions` is then `[C, M]`, +component-major, and `sections` names how many of the `rotary_dim / 2` frequencies each component +owns: `mrope` gives contiguous runs of them to components 0, 1, ... (Qwen2-VL); `imrope` interleaves +-- component 1 takes frequency `i` where `i % 3 == 1` and `i < 3 * s1`, component 2 where +`i % 3 == 2` and `i < 3 * s2`, component 0 the rest (Qwen3-VL); `axial` gives contiguous runs AND +restarts the frequency ladder in each, `theta^(-2j / (2 s_c))` for the run's `j`-th frequency (a +vision tower's 2-D rotary over row and column). With `[M]` positions every component is that one +position, so `mrope` and `imrope` over a text batch are `neox` exactly. + +**`gemm_nt_bias`'s epilogue** is a linear layer's: the biased product rounded to `y`'s dtype, then +`act` of it (`none`, `gelu` exact, `gelu_tanh`) rounded, then `res` added and rounded -- each step +what a separate tensor would hold, so the fused form is the unfused chain to the bit. + +**`grid_embed`** adds a learned `side x side` position table resampled to each row's grid: `coord` +is `[4, M]` (row, column, grid height, grid width), sampled bilinearly with the grid's corners on the +table's (align_corners), edge taps clamped, the four taps summed in f32 and rounded to `x`'s dtype +before the add. + +| op | params | operands | +|---|---|---| +| `attn_paged_gate_quant` | `q_len`(range) `head_dim` `gqa` `block_size` `causal` `window` `q_dtype` `kv_dtype` `scale`:f64/opt `max_ctx`/opt `n_head`/opt `max_seqs`/opt:capacity `group` `act` | `q`, `kv_cache`, `block_table`, `seqused`, `k_descale`?, `v_descale`?, `cu_seqlens`? → `out`; `gate` → `q8`, `q8_scale` | + +**`attn_paged_gate_quant` is `attn_paged` followed by `gate_quant_fp8` over its output**, the +second op finished inside the first's split-KV merge. A merge row is one (token, head) pair of +`head_dim` columns, which is exactly a `gate_quant_fp8` row, so the merged values are gated +(`bf16(sigmoid(gate))`, rounded before the multiply), rounded, written to `out` and quantised to +E4M3 with one scale per 128 columns while they are still in registers. It is byte-for-byte the +pair, checked by `r4d_selftest` at both merge forms and over a bf16 and an E4M3 cache. `block_size` is required rather than derived +because the cache's page size is `attn_paged`'s to answer; the caller passes the value it read. The +gated attention block takes it on the QSA sparse path, where every launch is one query row a +sequence and the decode kernel serves every chunk -- the whole step in one launch, which is why +`max_seqs` is a capacity: the block declares it at the step size, and the activation arena's +smaller declares bound it lower. + +### The KV cache is an operand + +`attn_paged` and `kv_store` take the group's cache as operand 1, passed as `RAD_KV(group, layer)`. +`RadKVGroupBatch` carries the slot mapping, the block table and the sequence lengths, but the pool +base belongs to the block manager and not to the batch. + +### `qk_norm_rope_gate` — device-only + +| op | params | operands | +|---|---|---| +| `qk_norm_rope_gate` | `M` `head_dim` `n_head` `n_head_kv` `rot` `q_dtype` `eps`:f64/opt `wadd`:f64/opt `cs_f32`/opt `pos_i64`/opt | `q_gate`?, `k`, `cos_sin`, `positions`, `q_w`w?, `k_w`w → `q_out`?, `k_out`, `gate_out`? | + +It splits an interleaved `[q|gate]` projection per head, RMS-norms q and k over the +head, applies partial NeoX rope and copies the gate — four launches a layer in one. **It is NOT +`qk_norm_rope`** in the attention table above, which takes `theta`: this one takes a +PRECOMPUTED `cos_sin` table (`rope_table` builds it) and a different operand list, which is why it +carries its own name. `rot` is the rotary width, `cs_f32` and `pos_i64` state the widths of the +table and the position vector, and `gate_out` is optional — a caller that already reads the gate at +its column offset inside the projection passes none. + +**`n_head` 0 IS THE K-ONLY FORM**, and it is the half of this op that has nothing to do with +gating. The `k` side is the plain reader — one head per `head_dim` columns, taken at the +OPERAND's own row pitch, written contiguously to `k_out` — and the only thing the q side adds is +the `[q|gate]` split. So an input that is already plain asks for `n_head` 0 and passes no +`q_gate`, no `q_w` and no `q_out`. The QSA indexer's query heads are that shape: `heads` of them +inside a `heads + 1` projection, which is a stride no rank-2 view can express and would otherwise +be `heads` separate `rmsnorm` launches plus a `rope`. At 4 heads over 12 trunk layers and 4 MTP +passes that is 80 launches a step for ~7 µs of work each; as one op it is 16. + +| op | params | operands | +|---|---|---| +| `qk_norm_rope_gate_kv_store` | `M` `head_dim` `n_head` `n_head_kv` `rot` `q_dtype` `eps`:f64/opt `wadd`:f64/opt `cs_f32`/opt `pos_i64`/opt `block_size` `kv_dtype` `k_scale`:f64/opt `v_scale`:f64/opt | `q_gate`?, `k`, `cos_sin`, `positions`, `q_w`w?, `k_w`w → `q_out`?, `k_out`, `gate_out`?; `v`, `slot_mapping`, `kv_cache`:inout | + +**`qk_norm_rope_gate_kv_store` is the prologue followed by `kv_store`**, in one launch. A k head's +block already holds its token's rotated k one element a lane, so it writes that element and the +head's v element into the cache at the token's slot as well. The `k` the store reads is `k_out` +and is not an operand of its own, which is why the tail adds only `v`, `slot_mapping` and +`kv_cache`; every parameter is one of the two ops' own. It is byte-for-byte the pair at either +cache width: the store converts the rotated k exactly as `k_out` stores it, a bf16 cache takes the +two values as they are, and the E4M3 conversion rounds each element on its own. + +**It IS byte-identical to the kernels it replaces**, and the check is in `r4d_selftest` rather than +in an argument — two rows, one for the `[q|gate]` form and one for the K-only form on a strided +projection. Byte equality and not a tolerance, and the difference between the two is the whole +reason: fold the sum of squares over eight consecutive elements a lane where `rmsnorm` folds it +over one and the two agree to a ULP, which a RELATIVE bound calls ok — but a ULP in the mean square +is a ULP in the normed value, and a rotated element is a difference of two products, so where those +nearly cancel the ULP comes out as a few percent and the transcript moves after a few dozen steps. +The kernel reproduces the reference's fold exactly: the widths above the head dim contribute zeros +and adding 0.0f is exact, so a block sum over 8 wave partials and over 32 are the same number. + +## Mixture of experts + +| op | params | operands | +|---|---|---| +| `router_topk` | `M`(range) `n_expert` `top_k` `norm` `dtype` | `logits` → `expert_ids`, `expert_w` | +| `moe_scatter` | `M`(range) `n_expert` `top_k` `expert_base`/opt `protect`:str/opt | `expert_ids` → `sorted_tok`, `expert_offset`, `expert_count` | +| `router_topk_scatter` | `M`(range) `n_expert` `n_local`/opt `top_k` `norm` `dtype` `expert_base`/opt `protect`:str/opt | `logits` → `expert_ids`, `expert_w`, `sorted_tok`, `expert_offset`, `expert_count` | +| `moe_gemm` | `M`(range) `N` `K` `n_expert` `top_k` `a_order` `dtype` | `a`, `w`wt, `sorted_tok`, `expert_offset` → `y` | +| `moe_gather` | `M`(range) `n` `top_k` `dtype` `act`:str/opt | `y_expert`, `expert_w`, `sorted_tok`, `shared`?, `shared_gate`? → `y` | +| `row_topk` | `M`(range) `N` `R` `vocab_off`/opt `dtype` | `x` → `idx`, `val`, `pairs`? | +| `row_topk_merge` | `M` `R` `world_size` `dtype` | `gathered` → `idx`, `val` | +| `logit_rerank` | `M`(range) `R` `n_vocab` `n_embd` `vocab_off`/opt `dtype` | `x`, `head`w, `idx_in` → `idx`, `val`, `pairs`? | + +`row_topk` and `row_topk_merge` are a pair, and the second only means anything with the first's +optional half. A vocab-sharded head produces logits for its own slice and nothing else, so its +top-R is over that slice: `vocab_off` shifts the columns reported into GLOBAL ids, and `pairs` +writes the same R entries as `[M, R, 2]` (an int32 id in the first float slot, its value in the +second) -- the plane `core/sample/sampler.h` holds as `buf_pairs_`, and the one the +sampler's own vocab-parallel path gathers. An `all_gather` with `row = R*2` concatenates those +into `[M, world_size * R, 2]`, rank r's at `[r*R, (r+1)*R)`, and `row_topk_merge` reduces it to +the global top-R. **The merge is exact, not approximate**: a candidate in the global top-R is in +its own shard's top-R, and both stages break ties on the lower id, so the result equals a top-R +over the unsharded plane element for element. A slot a shard could not fill carries id -1 in +`pairs` and is dropped -- a sentinel rather than a -inf value, because a masked logit takes that +value legitimately. + +`logit_rerank` is the second half of a COARSE top-R. A speculative step can afford a cheap draft +head -- the target verifies every proposal, so a worse draft costs acceptance and never a token -- +but a head quantised hard enough to be cheap also picks a different top-1 often enough to matter. +So the coarse head proposes R and this op scores those R, and only those R, against the +full-precision head the trunk already carries: a few hundred KB a row against a few hundred MB, for +an answer that agrees with the exact argmax on almost every row. `idx_in` carries GLOBAL ids as +`row_topk` reports them and `vocab_off` is this rank's first column, so under vocab-parallel +drafting each rank rescores the candidates it owns and the existing `all_gather` + `row_topk_merge` +still finds the global winner -- it needs no collective of its own. Ties break on the LOWER id, the +rule the other two use, so a tie inside a shard and a tie between shards resolve alike. + +**`router_topk_scatter` is those two in one launch**, and it exists because neither of them is +work. At a decode shape each is a SINGLE 256-thread workgroup ranking about a kilobyte — the +selection is a wave a row and four rows is one workgroup; the sort is one workgroup by +construction — so each costs the one-workgroup dispatch floor and almost nothing else. At 52 of +each per step that is ~1.0 ms, 3.6% of the decode step, for two dispatches. The chain is closed: +the sort reads `expert_ids` and nothing else, and `expert_ids` is exactly what the selection +writes, so a launch between them buys only a barrier and `__syncthreads()` is that barrier. + +**Two expert counts, and they are not the same number.** `n_expert` is the ROUTER's — it is +replicated and every rank picks from every expert — while `n_local` is THIS RANK's slice, which is +what the sort runs over and what sizes `expert_offset` and `expert_count` — half of the router's +on Qwen3.8-Flash-Next when its experts are divided between two ranks, as a calibration run divides +them. `n_local` absent means the slice is the router, which is every deployment that gives each +rank a slice of every expert instead. + +**Bounded, and it refuses rather than falling back.** Only `moe_scatter`'s single-workgroup form is +fusible (`M * top_k <= 1024`); above it the sort is three launches, which exist to keep it stable +without an atomic deciding the order. That bound is the decode band by construction — eight +sequences at depth 3 and top_k 10 is 320 slots — and a prefill chunk is past it, which is also +where the pair is amortised over real work and a fusion would buy nothing. A caller past the bound +gets a refusal, not a silent change of cost. + +`moe_scatter`'s output is what `rad_route_report` hands the heat engine. The histogram is read +back asynchronously and consumed on the next step; nothing here blocks the compute stream +(`spec.md` §5.5). + +**`protect` sorts a few experts last.** A layer that keeps some experts at a higher precision than +the rest serves them with a second grouped GEMM, and a grouped GEMM takes one contiguous run of the +offsets. So `protect` lists local experts (ascending, at most eight) that the sort places after +every other expert, in the order listed, with the rest closed up: `expert_offset` and +`expert_count` are then in that order, the regular experts are `[0, n - p)` of the offsets and the +protected ones `[n - p, n)`. A `moe_gemm` handed the trailing run (offsets that begin above zero) +serves those rows and leaves the ones below untouched. + +**`moe_gather` folds the shared expert in when `shared` and `shared_gate` are given**, computing +`y = bf16(shared * act(shared_gate)) + bf16(gathered)` in one pass -- which is `scale_rows`' own +fused gate-and-add form, taken one op further back so the bf16 plane between the two never +exists. BOTH NARROWS ARE PART OF THE CONTRACT: the unfused pair writes the gather to a bf16 +buffer and narrows the product before the sum, so an implementation that carried either in f32 +would move the last bit of every channel. `act` is "sigmoid" or "none" and applies to the +SCALAR, the same spelling `scale_rows` uses. It is worth a pair of operands because a shared arm +that cannot be width-sharded runs on ONE RANK, so the op it replaces is a dispatch a layer that +every other rank waits out inside the block's all-reduce. + +### The quantised and gated arms + +| op | params | operands | +|---|---|---| +| `moe_gemm_q` | `M`(range) `N` `K` `n_expert` `top_k` `group` `a_order` `dtype` `N_odd`/opt `K_odd`/opt `parts`/opt | `a`, `a_scale`?, `w`wt, `w_scale`wt, `sorted_tok`, `expert_offset`, `w_odd`wt, `w_odd_scale`wt → `y` | +| `scale_rows` | `M`(range) `n` `act` `dtype` | `x`, `s`, `add`? → `y` | + +The `wt` suffix is the table form and `w` alone is an ordinary weight operand; `moe_gemm`'s row +further up carries the same suffix, because its weight list is a per-expert pointer table. The +arithmetic is unchanged by that — a kernel may also be handed the stacked reading, an ordinary +rank-3 tensor with a real leading stride, and computes the same function from it. + +**`moe_gemm_q`'s experts are two tables by parity.** `w`/`w_scale` hold the even-numbered experts +at `[N, K]` and `w_odd`/`w_odd_scale` the odd ones at `[N_odd, K_odd]` (defaulting to `N`, `K`); +expert `e` is entry `e / 2` of its class. Every entry of one table shares a geometry, and a rank +that holds an uneven slice of every expert's width — three 128-column blocks of one parity's +experts and two of the other's, which is how a five-block expert splits across two ranks evenly on +average — has two. `parts` stacked parts run along both the weight rows and the output columns (two +for a fused gate/up); the output is `max(N, N_odd)` wide, and a narrower class fills the leading +columns of each output part and writes zeros after them, so the gated quantiser behind it reads +one layout for every row. Under the equal-division rule above the op's weight list is the even +class's codes, its scales, then the odd class's codes and scales. + +### `a_order`: which rows a grouped GEMM's activation has + +A routed block runs two `moe_gemm_q` ops and **they disagree about what a row of `a` is**, which is +why this is a parameter and not a convention. + +- The **gate_up** projection reads the block's normed input: one row per **token**. A sorted row + `i` belongs to the pair `sorted_tok[i] = token * top_k + slot`, so it must gather + `a[sorted_tok[i] / top_k]`. That is `a_order = "token"`, the default. +- The **down** projection reads gate_up's output through the gated quantiser, which is already one + row per **(token, slot)** in the scatter's own order. Row `i` is row `i`. That is + `a_order = "sorted"`. + +`a_scale` has a row for every row `a` has, either way. + +**Why it is said and not derived.** The row count gives it away — `M` against `M * top_k` — and +deriving it is the tempting shortcut. It is also the shortcut no harness catches: a kernel and a +reference that *both* gather agree to 1e-4 on every case, and `rad-kbench` builds each operand from +the op's own shape hook, so a hook describing `a` at the extent the gather wants builds a case that +is self-consistent and wrong. Served, the down projection hands every slot of a token the *first* +slot's intermediate — at decode, where a step carries one token, all `top_k` experts read slot 0 — +and the model runs, and answers fluently, and gets facts wrong. An operand whose meaning changes +with its extent cannot be checked by a harness that sizes the operand from the same reading. + +**`moe_gemm_q` is a separate op and not a `dtype` on `moe_gemm`**, for the same reason `gemm_nt_q` +is separate from `gemm_nt`: the operand LIST differs, operands are positional, and an op whose +count depends on a string means different things to different kernels. The group sub-sum is +accumulated from the raw codes and scaled once per group, exactly as `gemm_nt_q` does — the two +references have to agree in the last bits or `rad-kbench` blames a kernel for a choice made in +`libref`. + +**`moe_gemm` itself is what a model served at bf16 runs**, and libr4d serves it at `dtype` bf16: +one weight table of the checkpoint's own row-major `[N, K]` planes, read with no layout hook, so a +container stores an expert as the safetensors file holds it. It has no parity classes and no +`parts` — those exist because a quantised expert's width must fall on its scale blocks, and an +unscaled plane has none — and its rows go through the same run grouping and the same three forms +as `moe_gemm_q`'s kernels, byte-identical to each other. + +**`scale_rows` is the per-token scalar gate**, and it exists because `mul`'s broadcast is the wrong +one. `mul` lets `b` carry a single ROW broadcast down the rows; a shared-expert gate is a single +COLUMN broadcast across them — `y[m, i] = x[m, i] * act(s[m])` — and adding a second broadcast rule +to `mul` would make the two ambiguous exactly when `rows == n`. `act` is `"sigmoid"` or `"none"`. +Qwen3.5-MoE's `shared_expert_gate` is a `[1, n_embd]` projection whose one output per token gates +the shared expert's contribution, and this is that multiply. + +## Linear attention (gated delta net) + +| op | params | operands | +|---|---|---| +| `gdn_conv_prep` | `M`(range) `head_k` `head_v` `chunk`/der `conv_width` `l2_eps`:f64/opt `softplus_thr`:f64/opt | `x`, `w`w, `b`w?, `A_log`w, `dt_bias`w, `conv_state`:inout, `cu`, `a`?, `b_gate`?, `cache_idx`?, `has_init`? → `q`,`k`,`v`,`g`,`beta` | +| `gdn_conv_update` | `q_len`(range) `head_k` `head_v` `conv_width` `max_query_len`/opt | `x`, `w`w, `b`w?, `conv_state`:inout, `state_idx`, `num_accepted`, `cu` → `q`,`k`,`v` | +| `gdn_kkt_solve` | `M`(range) `head_k` `chunk`/der | `k`, `beta`, `g`, `cu` → `A` | +| `gdn_chunk_scan` | `M`(range) `head_k` `head_v` `chunk`/der `scale`:f64/opt `state_fp16`/opt | `q`,`k`,`v`,`A`,`g`,`beta`,`h0`?,`cu` → `o`, `ht`?; `state_idx`? | +| `gdn_recurrent_update` | `q_len`(range) `head_k` `head_v` `n_head_v`/opt `scale`:f64/opt `eps`:f64/opt `l2_eps`:f64/opt `softplus_thr`:f64/opt `act`:str/opt `state_fp16`/opt `state_form`:str/opt | `q`,`k`,`v`,`a`,`b`,`A_log`w,`dt_bias`w,`state`:inout,`state_idx`,`num_accepted`,`cu`,`z`?,`norm_w`w? → `o`,`o_q`?,`o_scale`? | +| `gdn_conv_recurrent_update` | `q_len`(range) `head_k` `head_v` `conv_width` `n_head_v`/opt `scale`:f64/opt `eps`:f64/opt `l2_eps`:f64/opt `softplus_thr`:f64/opt `act`:str/opt `state_fp16`/opt `state_form`:str/opt | `x`, `conv_w`w, `conv_b`w?, `conv_state`:inout, `conv_idx`, `a`,`b`,`A_log`w,`dt_bias`w,`state`:inout,`state_idx`,`num_accepted`,`cu`,`z`,`norm_w`w → `o`,`o_q`?,`o_scale`? | +| `gdn_gated_rmsnorm` | `M`(range) `channels` `eps`:f64 `act`:str | `x`, `z`, `w`w → `o` | + +**A linear-attention kernel pair must support speculative rollback.** The recurrent state and the +conv window have already absorbed rejected tokens, so `num_accepted` is a required operand and the +state cache is a rolling window of `conv_width-1 + n_spec` entries read at the slot the last +accepted token left. A rejection is a change of read offset, not a recompute. This is part of the +schema, not an assumption (`spec.md` §10). + +**`num_accepted` is ONE-BASED.** It counts the tokens the previous step committed: the one it was +given, plus however many of its drafts survived. So 1 is an ordinary decode step that drafted +nothing, which is exactly what these kernels assume when the operand is absent, and 0 is not a +value either of them can read -- `gdn_conv_update` reads its window at `num_accepted - 1`. + +**`state_form` says what the state cache MEANS, and there are two answers.** `per_candidate` -- +the default, and what this table's operand description above says -- writes one full state per +candidate token and needs `1 + n_spec` distinct slots in `state_idx`. `anchor` keeps ONE committed +state a sequence and replays the accepted prefix onto it out of a scratch slot, which is two slots +whatever the draft depth. The two produce the SAME `o` from a COMPLETELY DIFFERENT `state`, so an +implementation that serves one and is handed the other computes a correct answer to the other +question and disagrees with a checker on every element of the cache while agreeing on every +element of the output. That is why it is declared and not inferred: the index row's width does not +say which, and neither does anything else a kernel can see. + +A caller declares it; an implementation that serves only one form REFUSES the other by name. +libref serves `per_candidate`. The engine picks the form from whether the deployment speculates, +which is the same condition that sizes the state pool. + +It is also REQUIRED rather than optional, which is one of the two places the union rule is +deliberately not applied: an op that lets the caller omit `num_accepted` is an op whose rollback +contract is optional. A non-speculative decode passes all ones. + +**`state_idx` is `[n_seq, W]`, and W is the group's, not the op's.** One column is the sequence's +state. A kernel that needs somewhere to put what it cannot commit yet may ask for more, and the +columns after the first are ITS scratch: the caller stages the row, zeroes every slot it names when +the sequence is admitted, zeroes the scratch again after any step that ran a different path over +the same sequence (a chunked prefill commits the state directly and writes no scratch), and +otherwise does not look inside. `gdn_chunk_scan` takes the same row and reads column 0. + +The point of that freedom is what libr4d does with it. One state per candidate token is the plain +reading of "the next step reads the slot the last accepted token left", and on Qwen3.8-27B it is +1.3 GiB a sequence. Instead libr4d keeps ONE committed state and, beside it, the few hundred floats +a head that each token's rank-1 update needs; the next step replays the accepted prefix onto the +state out of that block and starts from a state carrying exactly the tokens that survived. Two +slots a sequence instead of `1 + n_spec`, and less write traffic than the per-candidate form. + +Two consequences worth naming. A zeroed scratch block replays as the identity, which is what makes +"zero it and pass `num_accepted` 1" the correct handover out of a prefill. And **libref is +not a meaningful oracle for `gdn_recurrent_update` while that layout is in use** -- ref implements +the per-candidate reading, so it would decode another plugin's scratch as its own. The end-to-end +check that does hold is stronger anyway: greedy speculation must emit the same bytes as greedy +without it. + +**Every gdn kernel takes `cu`, decode included, and that is the other place the union rule is not +applied.** `gdn_conv_update` and `gdn_recurrent_update` run off the one cumulative-lengths tensor +on the one step, and both open by reading `cu[n]` and `cu[n+1]` before any null test — the number +of sequences is `cu`'s length minus one and nothing else in the argument list carries it. A caller +working from a schema that made `cu` optional passes a null and faults on the dereference rather +than being refused. + +**`gdn_conv_recurrent_update` is the decode pair as one launch**: `gdn_conv_update` followed by +`gdn_recurrent_update`, with the convolution computed where the recurrence reads it, so `q`, `k` +and `v` are never written. The operands are the convolution's inputs -- `conv_idx` is its +`state_idx` -- and then the recurrence's without those three; the parameters are the union of the +two ops' under their own names, and both ops' rollback and state contracts hold unchanged. `z` and +`norm_w` are required, because the fold serves the decode shape, where the fused row norm already +puts one workgroup on each (sequence, value head). It is byte-identical to the pair. libr4d +rewrites a key head's conv state once all the value heads reading it have read it, by an arrival +count, so nothing waits on another workgroup. + +**The output gate `z` may be a COLUMN SLICE, on both `gdn_recurrent_update` and +`gdn_gated_rmsnorm`.** The fp8 delta-net block projects `[q|k|v|z]` in one GEMM +(`arch/common/rad_block_gdn_fp8.h`), so the gate is the right-hand `n_head_v * head_v` columns of a +wider row and its `(token, head)` rows are NOT evenly spaced: heads are `head_v` apart inside a +token and the next token is the slice's own stride away. An implementation that reads one pitch off +`z` walks into the next token after `n_head_v` rows and is wrong without being out of bounds. The +three spellings a caller may hand over are `[tokens, heads, head_v]`, a flat +`[tokens, heads*head_v]` buffer of its own, and that slice; the first two are the same arithmetic +and the third is what needs the token stride carried separately. + +## Collectives + +| op | params | operands | +|---|---|---| +| `all_reduce` | `world_size` `numel` `dtype` `exact` `min_bytes`/opt `hops`/opt | `x`:inout, `y`:out? | +| `all_gather` | `world_size` `numel` `dtype` `row`/opt | `x` → `y` | + +`exact` separates the exact sum from the quantised wire, and a caller has to say which it wants: a +request that does not declare it will accept a lossy wire gets no kernel rather than the quantised +one. `hops` separates one-shot from two-shot at a width that has both. Both are libr4d's rules and +they are right. + +`min_bytes` is the byte floor under which a LOSSY row must serve the message exactly anyway, and it +is a parameter rather than a constant in the library because it is a property of the link and not +of the kernel. Compression only pays once the transfer is bandwidth-bound: a decode step +all-reduces a handful of residual rows and the exact kernel already moves that at most of what the +interconnect delivers, so the rotate, the pack and the unpack cost more than the bytes they remove. +A row selected for `exact=0` therefore decides the ROW once, at declare, and the WIRE per launch. +Absent, the plugin uses its own measured default. + +`all_gather.row` is one row of a rank's contribution, in elements. Absent or `0`, `y` is the plain +concatenation — rank `r`'s slice at `r * numel`. Present, the placement is row-interleaved: `x` is +`[rows][row]` and `y` is `[rows][world_size][row]`, which is what a vocab-parallel candidate merge +reads, because it takes one row of gathered candidates per sampled position at a single row stride. + +**`-ffp-contract=off` is mandatory for any quantised cross-rank op.** Two ranks see the two +dequantised products in the opposite order, and contracting either into an FMA makes them disagree +by ~1 ULP, which breaks the replicated-state invariant. The build sets it globally for device code. + +### The collectives that carry a norm — device-only + +| op | params | operands | +|---|---|---| +| `ar_rmsnorm_quant_fp8` | `M` `n` `eps`:f64 `group` `world_size` `dtype` `wadd`:f64/opt `wire`/opt | `x`:inout, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`? | +| `ar_hc_write` | `M`(range) `n` `hc` `world_size` `dtype` `wire`/opt | `y`:inout, `inj`, `h`:inout | +| `ar_gather_hc_write` | `M`(range) `n` `hc` `top_k` `world_size` `dtype` `act`/opt `wire`/opt | `y_expert`, `expert_w`, `sorted_tok`, `shared`?, `shared_gate`?, `y`:inout, `inj`, `h`:inout | +| `ar_ln_had_quant_i8` | `M` `n` `eps`:f64 `group` `world_size` `dtype` `wadd`:f64/opt `wire`/opt | `x`, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`? | +| `gdn_gated_norm_had_quant_i8` | `M` `n` `head_dim` `group` `eps`:f64 `dtype` `zgrp`/opt `zblk`/opt | `x`, `z`, `w`w → `q`, `scale` | + +`wire` is the payload width on the link: 0 is exact bf16, 6 the rotated six-bit form. It is a +property of the LINK and not of the kernel, which is why it is a parameter — see `all_reduce`'s +`min_bytes` for the same argument. `x` is INOUT on `ar_rmsnorm_quant_fp8`: it is both the message +and the input, and the reduced sum lands in it. + +`ar_hc_write` is `all_reduce` of `y` followed by `hc_write` of the reduced `y`, for a block whose +output feeds a gated residual rather than a norm. `y` is INOUT for the same reason `x` is above. +It serves both wires, one op a wire: a caller declares the rotated form beside the exact one and +issues whichever the step's message goes out on, and a `wire` of 6 is 6 at every size. + +`ar_gather_hc_write` is `moe_gather` followed by `ar_hc_write`: the gather's output IS the +message, so `y` is written by the gather half before it is reduced in place, and the five gather +operands and `act` mean exactly what they mean on `moe_gather`. `wire` is `ar_hc_write`'s. On +either wire, byte-identical to the three kernels it stands in for. + +## Vocabulary edges + +| op | params | operands | +|---|---|---| +| `embed_lookup` | `M`(range) `n_embd` `n_vocab` `dtype` `vocab_offset`/opt `wscale`:f64/opt | `tokens`, `wte`w → `x` | +| `embed_lookup_q` | `M`(range) `n_embd` `n_vocab` `dtype` `vocab_offset`/opt `wscale`:f64/opt | `tokens`, `wte`w, `scale`w? → `x`, `ahead`? | +| `logits_gemm` | `M`(range) `n_vocab` `n_embd` `dtype` | `x`, `lm_head`w → `logits` | +| `ngram_ids` | `M`(range) `heads` `ngram` `eos` | `tok`, `state`:inout, `cu`, `mult`w, `vocab_sizes`w, `offsets`w, `cache_idx`?, `has_init`?, `num_accepted`? → `ids`, `ahead_ids`? | +| `ple_gate` | `M`(range) `n` `hc` `eps`:f64 `dtype` `wadd`:f64/opt `gate_eps`:f64/opt | `k`, `q`, `v`, `w_key`w, `w_query`w, `w_conv`w → `gv`, `gvn` | +| `ple_conv` | `M`(range) `n` `width` `dilation` `dtype` | `x`, `w`w, `conv_state`:inout, `cu`, `resid`?, `cache_idx`?, `has_init`?, `num_accepted`? → `y` | + +Separate from `gemm_nt` because `lm_head` is its own access class (`RAD_ACCESS_VOCAB`) and because +the sampler wants to fuse against it: at a 151K vocab and batch 256 the logits are ~77 MiB a step, +and the distributed top-k means a rank never materialises a full row (`spec.md` §9, §13). + +### `gather_rows` + +| op | params | operands | +|---|---|---| +| `gather_rows` | `M`(range) `n` `dtype` | `x`, `idx` → `y` | + +`gather_rows` is not a convenience. Without it a plugin computes logits for **every** token in a +prefill chunk instead of the last one per sequence — `n_tok / n_seq` times too much work, and at +`max_tok` 8192 against a 248K vocab the logits buffer alone is 8 GiB. It is the op that turns +"correct" into "affordable". + + +### `scatter_rows` + +| op | params | operands | +|---|---|---| +| `scatter_rows` | `M`(range) `n` `dtype` | `v`, `idx`, `x`:inout | + +`x[idx[i], :] = v[i, :]`, the mirror of `gather_rows`, and `x` is **inout** because the write is +partial: rows no index names keep what they held. That is what makes it usable against a pool other +sequences are also in — an op that returned a fresh `x` would have to copy everything it was not +asked to change. + +Two rules differ from the gather, and both follow from the destination being live memory rather +than a fresh buffer: + +- **A negative index writes nothing.** `gather_rows` reads a zero row for one, which is the padding + convention a short prefill chunk leaves behind. On this side a zero fill would be data loss. +- **Indices must be distinct**, declared with `RAD_OPD_F_IDX_UNIQUE` rather than left to prose. Two + rows landing on one destination has no defined winner on a parallel machine, so permitting it + would make this an op whose reference implementation and whose real kernel are allowed to + disagree — which is exactly what the oracle exists to rule out. + +It exists for the same reason `gather_rows` does: the alternative is `M` separate transfers, and +where this op is used a row is a few hundred bytes, so that is dispatch cost with the data as a +rounding error. The caller is the KV tier traffic (`core/mem/kvtier.h`). A paged pool is +**layer-major**, so within one layer a group's blocks are dense rows of `layer_bytes_per_block()` +— which makes packing an arbitrary set of them exactly a gather and restoring them exactly a +scatter, one launch per (group, layer) however many blocks are moving. + +**At `dtype` u8 the rows are opaque bytes**, and libr4d supplies that width as its own kernel pair +rather than widening the bf16 one. What moves is whatever the attention kernel wrote; calling it +bf16 would matter, because `libref` is the oracle for every op here and its bf16 path loads through +float, which is not guaranteed to return a NaN payload unchanged. At u8 every value is 0..255, +float carries it exactly, and oracle and kernel agree bit for bit on any payload at all. + +### `embed_lookup`'s `vocab_offset` + +`vocab_offset` (optional, default 0) is the first vocabulary row this rank holds. With it, +`n_vocab` is THIS RANK'S row count -- the meaning it already carries for `logits_gemm` -- and the +table covers global ids `[vocab_offset, vocab_offset + n_vocab)`. **Token ids stay GLOBAL**: a rank +subtracts the offset and writes a zero row for an id belonging to another rank, exactly as it does +for the negative padding id, so summing the ranks reconstructs `x`. Every token lands on exactly +one rank, which is why the `all_reduce` that follows is declared `exact` rather than taking the +model's wire setting: it sums disjoint rows, so a lossy wire would be loss on a value that is +already the answer. + +Without it the embedding must be REPLICATED while `lm_head` is row-sharded, and asymmetric sharding +of the two ends of the same vocabulary is not a design, it is an omission. The table is bf16 even +in the fp8 checkpoint, so replicating it costs 248320 x 5120 x 2 = 2.43 GiB on every card -- +memory the split hands to the KV cache instead. + +One thing is given up and it is worth naming: under a split this kernel can no longer tell a +garbage id from another rank's token, so the "an id at or above `n_vocab` fails the launch" check +holds only where the rank holds the WHOLE vocabulary -- `world_size` 1, not merely `vocab_offset` +0. **Rank 0 of a vocab-parallel split has offset 0** and legitimately sees ids past its own slice +on most steps, so a check keyed on the offset alone refuses correct calls. Bounding ids is the +caller's, and the tokeniser and the sampler both already are. + +### `embed_lookup_q`, the host gather + +**A gather from a table quantised with ONE scale for all of it**: `x[m] = wte[id] * scale[0]`. +Padding and bounds behave exactly as `embed_lookup`'s — a negative id writes a zero row, an id past +the table fails the launch. + +**Why one scale is enough**, measured on the bf16 original: E4M3 carries its own exponent, a row's +dynamic range in this table is only 2.3×, and the scale sits on a **three-octave plateau** where +2⁻¹³ through 2⁻¹⁰ all give rel_l2 0.02662 to five digits. A per-row scale buys 2.9%. +Qwen3.8-Flash-Next-FP8 ships exactly this: 128 E4M3 shards and a single bf16 `weight_scale` of +1.9932e-4. + +**A separate op and not a `dtype` on `embed_lookup`.** The operand list differs — there is a scale +— and operands are positional, so an op whose count depends on a string means different things to +different kernels. It is `gemm_nt_q`'s argument against being a `dtype` on `gemm_nt`. Adding the +scale to `embed_lookup` as an optional operand would also have moved `x` from slot 2 to slot 3 for +every caller in the tree. + +**It runs on the HOST, served by libavx; no device library has a row for it.** The table it +gathers from is 51.2 GB and cannot go anywhere else: staging a whole movement unit to use 5 KB is +the wrong shape, pinning it for zero-copy needs all 51.2 GB pinned in host RAM, and +`hipHostRegister` on the container's mapping would force all of it resident. The container is +mmapped, so the table is at a host address on open. libavx keeps the rows a gather +has touched in a row cache of its own and reads a miss straight from the file with O_DIRECT +(`libavx/avx_ngram.cpp`): the page cache would map a 4 KiB page per 160-byte row. + +The placement planner runs an op on the host when **every weight operand of it** is `Site::Host`, +which is why the table must be a weight operand at all: `gather_rows` takes a plain `IN` operand and +would never trigger it. And the host kernel has to live in a production plugin — libavx, the host +kernel library — because `rad_gate_reference_kernels` refuses to serve on libref by design. + +### `ngram_ids`, and the gather that is not an op + +**Qwen4-Exp's Per-Layer Embedding gives one layer a second embedding table addressed by a HASH of +the last `ngram` tokens.** Qwen3.8-Flash-Next's is 320,001,536 rows of 160 — 102 GB, 51 of the +model's 180 billion parameters — read sixteen rows a token. `ngram_ids` computes those row ids: + + mixed(k) = t0*mult[0] ^ t1*mult[1] ^ ... ^ tk*mult[k] + ids[h] = remainder(mixed(b+1), vocab_sizes[h]) + offsets[h] + +where `heads` is `ngram - 1` equal blocks and block `b` uses the `(b+2)`-gram. `t_s` is the token +`s` positions back, **or the EOS token if the shift would cross one** — and once a shift falls back +to EOS every deeper shift does too. `mult`, `vocab_sizes` and `offsets` are weights because the +checkpoint carries them; the reference builds them from a seed and a prime search at construction +time, and re-deriving sixteen numbers the container already holds would be a second source for them. + +**`state` is a rolling window of committed ids**, `ngram - 1 + n_spec` deep, read at +`num_accepted - 1` and rewritten in the layout `ple_conv` describes below — operand for operand, +including the two layouts `num_accepted`'s presence chooses between. **A cold window is EOS and not +zero**, which is the one place it differs from a convolution window: zero is a real token id. + +**The ids are a STATE and not a plain input**, and the reason is that the contract is already paid +for. A state needs a rollback contract and an input does not, which reads like an argument for the +input — but the dilated convolution downstream carries a 9-timestep window with exactly this +contract, so PLE pays for `num_accepted`, `cache_idx` and `has_init` regardless, and against that a +plain input costs *more*. Nothing in the engine derives "the ids before this step": `DeriveInput` +carries positions and cu_seqlens and no token ids at all, so an input would mean a new core +derivation and a widened `DeriveFn` signature to serve one op. `RAD_KV_CONV` is already +"per-sequence, a rolling window of width-1 + num_spec entries", and `conv_state_index` already +derives the read cursor for it. + +**The gather is `embed_lookup_q`, not `gather_rows`.** The table has to be a WEIGHT operand or +`Site::Host` is unreachable, because the planner puts an op on the host only when every weight +operand of it is `Site::Host`, and `gather_rows` takes a plain `IN` operand. + +**`ahead_ids` and `ahead`: the next chunk's rows, a step early.** A prefill chunk gathers `heads` +rows a token and, on text the row cache has not seen, most of them are random reads of the +container file — ~30 ms a 2048-token chunk on an NVMe, with the card idle behind the host-site op. +The next chunk of the prompt is already known (`RadBatch::n_ahead`, which stores it in `token_ids` +after the step's own tokens), so: + +- `ngram_ids` with `ahead_ids` present reads `tok` that many tokens past the step's, as a + continuation of the LAST sequence, and writes their ids there — exactly the ids the step that + runs those tokens will compute, since it hashes the same history. The window it writes back is + the step's own and never sees them. +- `embed_lookup_q` with `ahead` present may start reading those rows once its own are gathered. + No output depends on it, so a kernel may ignore it; libavx's row hands them to a reader thread + that fills its row cache while the step runs, and the next call finds them there. + +### `ple_gate`, and what the convolution branch does not see + +PLE's mixing coefficient is a **dot product between the n-gram embedding and the residual stream** — +one scalar per hyper-connection stream, per token: + + K[c] = grouped_rmsnorm(k)[c] * (w_key + wadd) k is key_proj(embedding) + Q[c] = grouped_rmsnorm(q)[c] * (w_query + wadd) q is the INCOMING hc stream + s[c] = sum_d K[c][d] * Q[c][d] / sqrt(n) + s[c] = sign(s[c]) * sqrt(max(|s[c]|, gate_eps)) + gv[c] = sigmoid(s[c]) * v v is value_proj(embedding), ONE row + gvn = grouped_rmsnorm(gv) * (w_conv + wadd) + +**The signed square root keeps the sign**, so a stream whose embedding opposes the residual gets a +gate below a half rather than a gate of zero. The clamp is on the **magnitude** and the sign comes +from the **original**, which matters at exactly one value: torch's `sign(0)` is 0, so a dot product +of exactly zero comes out as zero and not as `sqrt(gate_eps)`. Clamping first and re-signing the +clamped value would give 1e-3 there. + +**Both outputs leave the op.** The dilated convolution that follows reads the *normed* copy and the +residual add reads the *un-normed* one — two different tensors, and recomputing either outside +would be a second definition of the norm. + +**AND THE CONVOLUTION BRANCH DOES NOT SEE THE GATE.** `gv[c]` is a scalar times one shared `v` row, +and `norm_conv`'s rms is taken per `n`-wide stream — so the gate appears in both the numerator and +the rms and divides straight back out. `gvn[c][d]` is `v[d]/rms(v)` times its gain, whatever the +gate did. This is a sharp invariant to check a kernel against: a fused implementation whose `gvn` +varies with the gate has folded something it should not have. It is *not* a shortcut to take — +`gv` is narrowed to its dtype before the third norm reads it, so computing `gvn` from `v` directly +would differ in the last bits. + +**One op and not six.** Three grouped norms, a reduction, a scalar nonlinearity and a broadcast +multiply over tensors that are all `[M, hc*n]` — 10240 wide here — would be six launches against a +~4.5 µs per-kernel floor, every one of them memory-bound. `hc_read` is the same argument at the +same width. + +### `ple_conv`: a dilated convolution cache is not a conv cache + + y[t] = resid[t] + silu( sum_j w[c][j] * x[t - (width-1-j)*dilation] ) + +**The dilation changes how deep the history is, and that is the whole trap.** At Qwen4-Exp's width +4 and dilation 3 the taps are **9, 6, 3 and 0** timesteps back, so a sequence carries +`(width-1)*dilation = 9` timesteps — not `width-1 = 3`. A cache sized for the undilated width keeps +only the three most recent values and reads zeros where the deepest tap belongs, which is a model +that generates fluently from a slightly wrong context. + +The state is `[n_slots, n, state_len]` with slot `i` holding the value at relative position +`i - (width-1)*dilation`, which is `gdn_conv_prep`'s convention with the dilation folded in. +`has_init` 0 means that window is **zeros** rather than whatever the slot last held — without it a +fresh sequence landing on a recycled slot convolves the previous sequence's tail into its first +nine tokens. + +**`num_accepted` shifts the READ offset, and its presence picks what the step leaves behind.** The +manager sizes the state `(width-1)*dilation + n_spec` deep so a speculative step can read at an +offset inside it. What the next step's offset must find is the history ending at the last token +this step *committed*, and which token that is depends on the kind of step: + +- **Present — a decode step**, any of whose drafts a verify may reject. The window is rewritten the + way `gdn_conv_update` rewrites its own: the history read, shifted down by one, then every input of + the step, so slot `i` holds position `i + 1` of (window read ++ step). A next step that kept `k` + of these tokens reads at `k - 1` and finds the history ending at the `k`-th. It needs + `(width-1)*dilation - 1` slots plus one a token, which a step of `1 + n_spec` tokens gets. +- **Absent — every token commits**, which is the prefill chunk. The read is at offset zero and the + last `(width-1)*dilation` inputs land at offset zero, where the next step's `num_accepted` of 1 + reads them. + +The two agree when the step has one token, and no single layout can serve both at several: at +offset zero one must hold the history ending at the step's first token and the other the history +ending at its last. An architecture therefore issues the op once over its decode rows and once over +its prefill rows, as it already does the two `gdn` convolutions. + +**One op where the gated delta net has two.** `gdn_conv_prep` and `gdn_conv_update` are separate +because the work *around* their convolutions differs — one splits a fused projection and takes an +l2 norm, the other does not. PLE's convolution is the same arithmetic at prefill and at decode, so +it takes the union of the two contracts instead: `has_init` is prefill's question and +`num_accepted` is decode's. + +The residual add is folded in because the reference is `gv + silu(conv(gvn))` and the two tensors +are both `[M, hc*n]` — 10240 wide here. `resid` absent leaves the plain convolution. + +## Sampling + +Every sampler is a kernel, not a host lift. `llama.cpp`'s chain is kept as a **host reference** +that `rad-kbench` compares the device samplers against (`spec.md` §13). + +**EVERY PER-REQUEST SCALAR IS AN OPERAND, NOT A PARAMETER.** `params` is `[M]` rows of +`RadSampleParams` (`abi/rad_sample.h`), uploaded once a step, and it carries `temp`, +`top_k`, `top_p`, `min_p`, `typical_p`, the three penalties, the DRY and XTC settings, the seed and +position, the history window and the grammar's `mask_row`. Not one of them is in a params cell +below, and the reason is that a parameter is GEOMETRY: the selector matches on it and freezes it at +declare (`spec.md` §2.2), so two requests in one batch with different `top_p` would be two +resolutions of one op — which is not something a batch can contain. + +| op | params | operands | +|---|---|---| +| `sample_penalties` | `M`(range) `n_vocab` `vocab_off`/opt | `logits`:inout, `params`, `history` | +| `sample_temp` | `M`(range) `n_vocab` | `logits`:inout, `params` | +| `sample_topk` | `M`(range) `n_vocab` `vocab_off`/opt | `logits`, `params` → `cand_idx`, `cand_val`, `pairs`? | +| `sample_topp` | `M`(range) `n_cand` | `cand_idx`:inout, `cand_val`:inout, `params` | +| `sample_minp` | `M`(range) `n_cand` | `cand_idx`:inout, `cand_val`:inout, `params` | +| `sample_mask` | `M`(range) `n_vocab` | `logits`:inout, `params`, `bitmask` | +| `sample_pick` | `M`(range) `n_cand` | `cand_idx`, `cand_val`, `params` → `token` | +| `sample_argmax` | `M`(range) `n_vocab` | `logits`, `params` → `token` | +| `sample_merge_topk` | `M`(range) `n_cand` | `gathered`, `params` → `cand_idx`, `cand_val` | + +`sample_mask` is where a GBNF grammar lands: the state machine stays on host and what crosses is a +token bitmask per sequence, 19 KiB at a 151K vocab, cheap enough to upload every step. + +### Stages the decomposed chain does not carry + +| op | params | operands | +|---|---|---| +| `sample_dry` | `M` `n_vocab` `vocab_off`/opt | `logits`:inout, `params`, `history`, `breakers`? | +| `sample_typical` | `M` `n_cand` | `cand_idx`:inout, `cand_val`:inout, `params` | +| `sample_xtc` | `M` `n_cand` | `cand_idx`:inout, `cand_val`:inout, `params` | +| `sample_chain` | `M` `n_vocab` `temp`:f64/opt `p`:f64/opt `min_p`:f64/opt `k`/opt | `logits`, `query`?, `u` → `draw` | + +`sample_dry` penalises each token that would extend a repeated suffix of the history ONCE, by its +longest such repeat — llama.cpp's DRY. The sequence breakers are strings, so they are resolved +against the vocabulary on the host: the row's `dry_rep_limit` carries the repeat limit the most +recent breaker imposes, and the optional `breakers` plane, one byte beside every history token, +marks the tokens that are whole breakers and are never penalised. Absent, no token is exempt. + +`sample_penalties` and `sample_dry` read GLOBAL token ids from `history` and write this rank's +logits, so under a split vocabulary they take `vocab_off`, as `sample_topk` does, and a token +outside the shard is another rank's to penalise. Their `penalty_last_n` / `dry_penalty_last_n` +window is llama.cpp's: 0 turns the stage off for the row, and a negative value takes the whole +history. + +`sample_typical` is locally-typical sampling and is NOT a prefix of the descending candidate order — +that order and the probability order disagree, which is why it narrows in place rather than +truncating. `sample_chain` is the whole chain in one kernel for the speculative verify: `query` is +the drafted token per position (absent at the last one), `u` is TWO uniforms a position, and `draw` +is `{u32 tok, u32 tok_excl, f32 p_query}` — the rejection test's three values. It stands beside the +decomposed stages rather than replacing them; both are declared and the band decides. + +### The vocabulary-parallel chain + +When `lm_head` is row-sharded, a rank's logits row covers only its own slice of the vocabulary, and +two things follow. `sample_argmax` becomes unusable — its answer is a LOCAL column index, which is +a different token — so a greedy request is staged at `top_k = 1` and takes the chain instead. And +`sample_topk` writes an optional third output, `pairs`: its candidates as (u32 GLOBAL id, f32 +logit), with the rank's `vocab_off` already added, which is what `all_gather` moves and +`sample_merge_topk` reads. + +`sample_merge_topk` **re-applies the row's `top_k`**, and that is why it takes `params`. Every rank +ran its own top-k before the gather, so the merged set holds up to `world_size * k` candidates +where the request asked for `k`, and no stage after it narrows again. At `k = 1` the difference is +not a slightly wider support: `sample_pick` is a DRAW, so a greedy row with two live candidates +returns whichever one the request's seed happens to select. + +**`gathered` is `world_size` SORTED RUNS, and the merge relies on it.** Each rank's `sample_topk` +writes its `n_cand` pairs in descending (logit, lower id first) order with its holes at the tail, +and the all-gather lays a row's runs side by side. libr4d's merge therefore runs only the merge +stages of its sorting network when the runs are a power of two long and fill the row -- 11 passes +over two runs of 1024 where a full sort is 66 -- and the whole network otherwise. A producer that +hands it unsorted runs gets a wrong order, not a slow one. + +## Sparse attention (QSA) — device-only + +| op | params | operands | +|---|---|---| +| `qsa_block_key` | `M`(range) `n` `ratio` `rotary_dim` `pos0`/opt `block_size`/opt `eps`:f64 `theta`:f64 `scale`:f64/opt `wadd`:f64/opt `dtype` `mode`/opt `sections`/opt | `k`, `w`w, `page`?, `pos`? → `out` | +| `qsa_score` | `M`(range) `n` `heads` `blocks` `seqs` `dtype` | `q`, `bk`, `bt`, `cu`, `nc` → `score` | +| `qsa_select` | `M`(range) `blocks` `topk` `ratio` `seqs` | `score`, `bt`, `nc`, `pos`, `cu` → `sel`, `nsel`, `seqused` | +| `qsa_tail_store` | `M`(range) `n` `ratio` `ring` `seqs` `dtype` | `k`, `pos`, `cu`, `state`:inout, `sidx` | +| `qsa_work` | `M`(range) `n` `ratio` `ring` `seqs` `work` `dtype` | `k`, `pos`, `cu`, `state`, `sidx`, `bt`, `rope`? → `stage`, `page`, `bpos`, `nc` | + +Five ops decompose one thing: an indexer that scores blocks of key history against the query and +hands `attn_paged` a shorter block table. `docs/QSA.md` is that decomposition; these are the +schemas, and `arch/common/rad_qsa.h` issues all five. + +`qsa_block_key` builds the **compressed key**: one vector per `ratio` tokens of key history, which +is what the indexer's block scores are taken against. + +``` +out[b] = rope( rmsnorm( mean over j