Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1e968f6e1d | ||
|
|
b068190326 | ||
|
|
b93b531f63 | ||
|
|
c527863248 | ||
|
|
7a1ae22690 | ||
|
|
efff69be1d | ||
|
|
34ee08ea5e | ||
|
|
743b7e1a6a | ||
|
|
73c3dc38be | ||
|
|
e173365823 | ||
|
|
76dd0019ac | ||
|
|
a378b41abb | ||
|
|
0d95046f6f | ||
|
|
29f981fd6c | ||
|
|
171dcee15b | ||
|
|
3a48ee78de | ||
|
|
9967158d4a | ||
|
|
753e9c598b | ||
|
|
c2bd41fe95 | ||
|
|
368d0363eb | ||
|
|
846e52148a | ||
|
|
833173cc04 | ||
|
|
d0f6f332ff | ||
|
|
29bfe8f00c | ||
|
|
fb716830c2 | ||
|
|
2381591823 | ||
|
|
c37f47cc78 | ||
|
|
f6a9467cb5 | ||
|
|
d10b64f9e5 | ||
|
|
7c7f755931 | ||
|
|
dc339b4cd2 | ||
|
|
9a2747eaef | ||
|
|
e35052abfe | ||
|
|
93389679e8 | ||
|
|
45109ebb45 | ||
|
|
ab4ae529f8 | ||
|
|
05033f3911 | ||
|
|
0895588b76 | ||
|
|
191972eb75 | ||
|
|
bdb50b2a9c | ||
|
|
e366777a0f | ||
|
|
d49d664381 | ||
|
|
0a4cf9b893 | ||
|
|
d90d90e43a | ||
|
|
dd6a7071a8 | ||
|
|
8bde9f9c16 | ||
|
|
997e1ae05f | ||
|
|
d59e0bb003 | ||
|
|
2c9ffc2888 | ||
|
|
dbd4e164b3 | ||
|
|
b9229091a9 | ||
|
|
cb5e812ccc | ||
|
|
c045ff85e9 | ||
|
|
921b02b60b | ||
|
|
77c266ce8f | ||
|
|
3259b4a8a2 | ||
|
|
61cf8b7b1a | ||
|
|
73bfc310aa | ||
|
|
dd3310849a | ||
|
|
8b825a941c | ||
|
|
c37ce73d72 | ||
|
|
73620ef00e | ||
|
|
f1d9afadfa | ||
|
|
d5b65cddc6 | ||
|
|
4ab587a8a2 | ||
|
|
32fa1a27ec | ||
|
|
04405089cb | ||
|
|
9137948b95 | ||
|
|
d6b506fe4f | ||
|
|
ec65b8cbeb | ||
|
|
c17f5fdc89 | ||
|
|
a19cbcae85 | ||
|
|
3491aca6fe | ||
|
|
6091039926 | ||
|
|
cfe03f8ad8 | ||
|
|
9e9fce3aca | ||
|
|
ffa235bf0f | ||
|
|
e45bb596f4 | ||
|
|
9af15f3a6e | ||
|
|
5681da471c | ||
|
|
36e3b78c76 | ||
|
|
1213c05cd8 | ||
|
|
3402acf82d | ||
|
|
89cee7ce41 | ||
|
|
6a2ee986d6 | ||
|
|
7e796642e6 | ||
|
|
9238b1f23d | ||
|
|
6b4a67f52e | ||
|
|
a97985e7c2 | ||
|
|
7c0bd03841 | ||
|
|
d5b584a4c1 | ||
|
|
3a3345951f | ||
|
|
86128c2e75 | ||
|
|
7fd2cd7fa6 | ||
|
|
7d840861af | ||
|
|
05af4db458 | ||
|
|
ac79f4dc8a | ||
|
|
6fa7707dff | ||
|
|
ee5fcf1024 | ||
|
|
432b50d7dd | ||
|
|
32cdaa5cc7 | ||
|
|
d579bd7d45 | ||
|
|
1e27172c14 | ||
|
|
76727fa050 | ||
|
|
82da8eab69 | ||
|
|
73691a1189 | ||
|
|
92eb44619b | ||
|
|
e31be583a9 | ||
|
|
33778b2b8c | ||
|
|
6fd7421f79 | ||
|
|
59d36ae928 | ||
|
|
2af7fa4022 | ||
|
|
d23c3e0d17 | ||
|
|
e95d397288 | ||
|
|
7001841e45 | ||
|
|
82b5835c02 | ||
|
|
9f5feb24ee | ||
|
|
92b8aaff2b | ||
|
|
2d93182213 | ||
|
|
017cf52218 | ||
|
|
5acdab7eb7 | ||
|
|
ffdf1f2ced | ||
|
|
3e629e7a27 | ||
|
|
7be92ec8f4 | ||
|
|
cd48c61daf | ||
|
|
fd54038b8c | ||
|
|
43d97cb9e6 | ||
|
|
31a3ddd24f | ||
|
|
9fc7e5f1ff | ||
|
|
d72b00bfdb | ||
|
|
45963012ee | ||
|
|
82445ca71f | ||
|
|
1936bc881f | ||
|
|
7843a3d400 | ||
|
|
6e14caaedd | ||
|
|
d7aa401568 | ||
|
|
075dfefe54 | ||
|
|
0eeee5bb3a | ||
|
|
d0f639bd06 | ||
|
|
6b394ccca6 | ||
|
|
2149a1a757 | ||
|
|
72947681c3 | ||
|
|
b60e329d93 | ||
|
|
709d9beb1b | ||
|
|
41c0d25233 | ||
|
|
ee65352d7d | ||
|
|
a4845834ea | ||
|
|
469441d90f | ||
|
|
e466fa07e2 | ||
|
|
2f56e3c477 | ||
|
|
c36e6fa2b3 | ||
|
|
f1d4a54581 | ||
|
|
e6c8a3d7fa | ||
|
|
4252353bc2 | ||
|
|
fe899bf60c | ||
|
|
63d35ff791 | ||
|
|
bc2e6ba614 | ||
|
|
bfae23e368 | ||
|
|
bb4dddc424 | ||
|
|
20d6c2119f | ||
|
|
3e0c114cd7 | ||
|
|
ee2ba24083 | ||
|
|
140987fa7b | ||
|
|
146318894d | ||
|
|
8f795c1022 | ||
|
|
b8fab2c871 | ||
|
|
10f3d6875b | ||
|
|
7cf4c005e1 | ||
|
|
966bda899a | ||
|
|
6df26315b9 | ||
|
|
6c11671bdd | ||
|
|
09fb41735b | ||
|
|
d008fdb32b | ||
|
|
01b816f8a0 | ||
|
|
f48786483d | ||
|
|
8e3463c173 | ||
|
|
8ddb77e03c | ||
|
|
ae74a8aebf |
No files matched your search
@@ -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
|
||||
@@ -1,18 +0,0 @@
|
||||
# .forker.yaml — per-mirror configuration for Repo Forker.
|
||||
#
|
||||
# The upstream URL, its token, and the Gitea REMOTE/TOKEN are NOT set
|
||||
# here: they live in the container (environment or the UI's mirror
|
||||
# registry). Everything below is non-secret per-mirror behavior.
|
||||
#
|
||||
# Flat `key: value` only (the parser is a grep) — no nesting.
|
||||
|
||||
enabled: true
|
||||
mirror_tags: true
|
||||
mirror_prune: true
|
||||
mirror_branches: "*"
|
||||
on_new_tag: true
|
||||
mirror_upstream_releases: true
|
||||
sync_interval: 0
|
||||
build_cmd: ""
|
||||
build_script: ""
|
||||
artifacts: ""
|
||||
@@ -0,0 +1,8 @@
|
||||
/build*/
|
||||
compile_commands.json
|
||||
*.o
|
||||
*.so
|
||||
*.rad
|
||||
/sync-jarvis.sh
|
||||
__pycache__/
|
||||
.cache/
|
||||
+353
@@ -0,0 +1,353 @@
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
# VERSION is the server release that /version reports. The plugin ABI version is separate and is
|
||||
# read from abi/rad_abi.h below.
|
||||
project(radiance VERSION 1.7.0 LANGUAGES C CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 20)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
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()
|
||||
|
||||
# A cache STRING, not option(): option() is boolean, so AUTO would collapse to OFF and skip
|
||||
# detection.
|
||||
set(RAD_WITH_HIP "AUTO" CACHE STRING "ON | OFF | AUTO -- build the HIP backend and device kernels")
|
||||
set_property(CACHE RAD_WITH_HIP PROPERTY STRINGS ON OFF AUTO)
|
||||
set(RAD_WITH_FFMPEG "AUTO" CACHE STRING
|
||||
"ON | OFF | AUTO -- decode image, video and audio parts with libavformat/libavcodec/libswscale/libswresample")
|
||||
set_property(CACHE RAD_WITH_FFMPEG PROPERTY STRINGS ON OFF AUTO)
|
||||
option(RAD_BUILD_TESTS "Build the test suite" ON)
|
||||
option(RAD_ASAN "Build host code with AddressSanitizer and UBSan" OFF)
|
||||
option(RAD_TSAN "Build host code with ThreadSanitizer" OFF)
|
||||
# LLVM 24's VOPD pairing is not repeatable unless patched (docker/llvm-vopd-pairing.patch); when
|
||||
# OFF, pairing is disabled on LLVM 24. See rad_hip_repeatable in cmake/RadAddPlugin.cmake.
|
||||
option(RAD_HIP_VOPD_REPEATABLE "The HIP compiler's VOPD pairing is repeatable (the image's LLVM 24 is)" OFF)
|
||||
|
||||
# ---------------------------------------------------------------- HIP detection
|
||||
# RAD_GPU_TARGETS lists the offload architectures device kernels are compiled for. Which cards the
|
||||
# engine serves is decided by the installed kernel plugins, not here (spec §18). Unset means
|
||||
# enumerate this machine's devices with the ROCm toolchain.
|
||||
#
|
||||
# A kernel library covering only some architectures narrows the list with rad_plugin_gpu_targets()
|
||||
# and skips itself when the intersection is empty (libr4d is RDNA4-only).
|
||||
#
|
||||
# Without ROCm the host backend is built, a supported configuration that exercises everything
|
||||
# except device kernels.
|
||||
set(RAD_HIP_FOUND OFF)
|
||||
if(NOT RAD_WITH_HIP STREQUAL "OFF")
|
||||
find_program(RAD_HIPCC hipcc HINTS /opt/rocm/bin /opt/rocm/llvm/bin ENV ROCM_PATH)
|
||||
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 / offload-arch print one architecture per visible device, integrated graphics
|
||||
# included. Plugins filter the list to what they serve.
|
||||
find_program(RAD_ARCH_TOOL NAMES amdgpu-arch offload-arch
|
||||
HINTS /opt/rocm/bin /opt/rocm/llvm/bin ENV ROCM_PATH)
|
||||
if(RAD_ARCH_TOOL)
|
||||
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)
|
||||
# No card attached: do not guess an architecture. Decline the device build and say how to
|
||||
# request one.
|
||||
set(RAD_HIP_FOUND OFF)
|
||||
message(WARNING
|
||||
"radiance: hipcc was found but no AMD GPU could be enumerated, so this build has no device "
|
||||
"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"
|
||||
" Expected on a machine without ROCm, wrong on one with cards. Looked in /opt/rocm/bin, "
|
||||
"/opt/rocm/llvm/bin and $ROCM_PATH.")
|
||||
endif()
|
||||
|
||||
# ASan + UBSan for host code only. AMD's amdgcn ASan needs xnack+ for its page-fault-based shadow,
|
||||
# and RDNA has no xnack, so the generator expressions keep the flags off HIP. Device kernels rely on
|
||||
# rad-kbench's red zones instead: a poisoned margin around every operand and scratch allocation,
|
||||
# checked after the launch, which catches out-of-bounds writes.
|
||||
#
|
||||
# TSan, likewise host code only, for the threaded host paths (scheduler, server, stager, tokenizer
|
||||
# cache). libgomp is not instrumented, so tests run it with one thread (tests/CMakeLists.txt).
|
||||
if(RAD_ASAN AND RAD_TSAN)
|
||||
message(FATAL_ERROR "RAD_ASAN and RAD_TSAN cannot be combined; use a build directory for each.")
|
||||
endif()
|
||||
if(RAD_ASAN)
|
||||
add_compile_options($<$<COMPILE_LANGUAGE:CXX>:-fsanitize=address,undefined>
|
||||
$<$<COMPILE_LANGUAGE:CXX>:-fno-omit-frame-pointer>
|
||||
$<$<COMPILE_LANGUAGE:CXX>:-fno-sanitize-recover=all>)
|
||||
add_link_options(-fsanitize=address,undefined)
|
||||
endif()
|
||||
if(RAD_TSAN)
|
||||
add_compile_options($<$<COMPILE_LANGUAGE:CXX>:-fsanitize=thread>
|
||||
$<$<COMPILE_LANGUAGE:CXX>:-fno-omit-frame-pointer>)
|
||||
add_link_options(-fsanitize=thread)
|
||||
endif()
|
||||
|
||||
add_compile_options(-Wall -Wextra -Wno-unused-parameter -Wno-missing-field-initializers)
|
||||
|
||||
# Before the ABI: its INSTALL_INTERFACE path uses CMAKE_INSTALL_INCLUDEDIR, which would otherwise
|
||||
# expand to nothing and silently export the wrong include directory.
|
||||
include(GNUInstallDirs)
|
||||
|
||||
# ---------------------------------------------------------------- the ABI
|
||||
# Header-only, and the only thing plugins compile against.
|
||||
add_library(rad_abi INTERFACE)
|
||||
# Plugins link radiance::abi: an ALIAS here, an imported target when installed, so rad_add_plugin
|
||||
# (cmake/RadAddPlugin.cmake) needs one body for both.
|
||||
add_library(radiance::abi ALIAS rad_abi)
|
||||
set_target_properties(rad_abi PROPERTIES EXPORT_NAME abi)
|
||||
# CMAKE_INSTALL_FULL_DATADIR, not a literal "share", so it follows the plugin install destination.
|
||||
set(RAD_DEFAULT_HOME "${CMAKE_INSTALL_FULL_DATADIR}/radiance" CACHE STRING "default $RADIANCE_HOME")
|
||||
target_include_directories(rad_abi INTERFACE
|
||||
# abi/, not the repo root, so a plugin sees only the ABI headers, never core/ or arch/.
|
||||
# Generator expressions because the target is exported, and install(EXPORT) rejects a source
|
||||
# path. Plugins write `#include "rad_abi.h"` both in-tree and installed.
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/abi>
|
||||
$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}/radiance>)
|
||||
target_compile_definitions(rad_abi INTERFACE RAD_DEFAULT_HOME="${RAD_DEFAULT_HOME}")
|
||||
|
||||
if(RAD_HIP_FOUND)
|
||||
target_compile_definitions(rad_abi INTERFACE RAD_HAVE_HIP=1)
|
||||
# Host translation units such as core/device/hip.cpp use the ordinary C++ compiler and need the
|
||||
# HIP headers explicitly.
|
||||
#
|
||||
# SYSTEM: hipcc already has this directory as a system include. A plain -I would take precedence
|
||||
# and make ROCm headers warn in every plugin (rad_abi is an INTERFACE dependency of all of them).
|
||||
#
|
||||
# BUILD_INTERFACE only: the path is this machine's. The installed package config finds the
|
||||
# headers on the consumer's machine (cmake/radiance-config.cmake.in).
|
||||
get_filename_component(RAD_ROCM_BIN "${RAD_HIPCC}" DIRECTORY)
|
||||
get_filename_component(RAD_ROCM_ROOT "${RAD_ROCM_BIN}" DIRECTORY)
|
||||
if(EXISTS "${RAD_ROCM_ROOT}/include/hip/hip_runtime.h")
|
||||
set(RAD_ROCM_INCLUDE "${RAD_ROCM_ROOT}/include")
|
||||
elseif(EXISTS "/opt/rocm/include/hip/hip_runtime.h")
|
||||
set(RAD_ROCM_INCLUDE "/opt/rocm/include")
|
||||
endif()
|
||||
if(RAD_ROCM_INCLUDE)
|
||||
target_include_directories(rad_abi SYSTEM INTERFACE $<BUILD_INTERFACE:${RAD_ROCM_INCLUDE}>)
|
||||
else()
|
||||
message(FATAL_ERROR
|
||||
"hipcc is at ${RAD_HIPCC} but hip/hip_runtime.h is not under ${RAD_ROCM_ROOT}/include "
|
||||
"or /opt/rocm/include. Set ROCM_PATH.")
|
||||
endif()
|
||||
target_compile_definitions(rad_abi INTERFACE __HIP_PLATFORM_AMD__=1)
|
||||
endif()
|
||||
|
||||
set(RAD_PLUGIN_OUT ${CMAKE_BINARY_DIR}/radiance_home)
|
||||
file(MAKE_DIRECTORY ${RAD_PLUGIN_OUT}/kernels ${RAD_PLUGIN_OUT}/architectures)
|
||||
|
||||
# Recorded kernel fixtures, copied into the build's $RADIANCE_HOME (where rad-kbench looks; an
|
||||
# installed prefix has no source tree). data/kernels.rkb lets rad-kbench run with no model: it holds
|
||||
# geometries, input seeds and libref's answers reduced to a norm and a sample. Re-record with a 27B
|
||||
# container:
|
||||
#
|
||||
# rad-kbench -m <model.rad> --max-cases 1 --record data/kernels.rkb
|
||||
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()
|
||||
|
||||
# A recording covers one container's geometries, and no single model declares the whole vocabulary.
|
||||
# The 27B is dense with a DFlash2 drafter and gqa 6; the 35B-A3B is routed (moe_gemm_q,
|
||||
# router_topk, moe_scatter, moe_gather, scale_rows) with an MTP head and gqa 8. Re-record with
|
||||
#
|
||||
# rad-kbench -m <model.rad> --max-cases 1 --record data/kernels_moe.rkb
|
||||
#
|
||||
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/data/kernels_moe.rkb)
|
||||
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/data/kernels_moe.rkb
|
||||
${RAD_PLUGIN_OUT}/kernels_moe.rkb COPYONLY)
|
||||
install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/data/kernels_moe.rkb
|
||||
DESTINATION ${CMAKE_INSTALL_DATADIR}/radiance)
|
||||
endif()
|
||||
# The downloader behind `radiance --model <owner/name>` (core/hf_model.cpp). The engine looks in
|
||||
# <bin>/../libexec/radiance/, so the build tree mirrors that layout.
|
||||
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/scripts/hfget.sh
|
||||
${CMAKE_BINARY_DIR}/libexec/radiance/hfget.sh COPYONLY)
|
||||
install(PROGRAMS ${CMAKE_CURRENT_SOURCE_DIR}/scripts/hfget.sh
|
||||
DESTINATION ${CMAKE_INSTALL_LIBEXECDIR}/radiance)
|
||||
|
||||
# rad-export (a finetune to a .rad with the stock model's recipe) runs on the host, beside the
|
||||
# trainer. It is installed with the tools so the image hands it out
|
||||
# (`docker run --entrypoint busybox <image> cat /opt/radiance/bin/rad-export`), though the image
|
||||
# has no Python to run it.
|
||||
install(PROGRAMS ${CMAKE_CURRENT_SOURCE_DIR}/tools/rad-export
|
||||
DESTINATION ${CMAKE_INSTALL_BINDIR})
|
||||
|
||||
# rad_add_plugin() and rad_hipify(), shared with the installed package config. The variables it
|
||||
# expects are all set above.
|
||||
include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/RadAddPlugin.cmake)
|
||||
|
||||
if(RAD_HIP_FOUND)
|
||||
string(TOUPPER "${CMAKE_BUILD_TYPE}" RAD_CFG_UPPER)
|
||||
# The HIP language (CMake >= 3.21): device sources are LANGUAGE HIP and everything else stays on
|
||||
# the C++ compiler. Do not set CMAKE_CXX_COMPILER to hipcc; after project() it is silently
|
||||
# ignored. CMake refuses hipcc as CMAKE_HIP_COMPILER, so this is ROCm's clang++. ROCm 7.2 /
|
||||
# LLVM 22 requires a global address space for __builtin_amdgcn_global_load_tr_b128_v8i16, hence
|
||||
# the cast in libr4d/r4d_common.h.
|
||||
enable_language(HIP)
|
||||
rad_hip_rule_fixes()
|
||||
|
||||
# Device optimisation level for every config. Depending on its version, CMake leaves
|
||||
# CMAKE_HIP_FLAGS_<CONFIG> empty (device code at -O0 with asserts) or, from CMake 4.4, pre-fills
|
||||
# the host-style '-O2 -g -DNDEBUG'. At -O0 decode reads weights at ~7 GB/s on a ~640 GB/s card.
|
||||
# -O3 for kernels; no -g on the device, where it slows compiles and inhibits scheduling.
|
||||
#
|
||||
# The assignment is unconditional (FORCE) because a guard cannot tell a toolchain default from an
|
||||
# operator's choice. Override by name with RAD_HIP_FLAGS_<CONFIG>.
|
||||
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
|
||||
# Image, video and audio request parts are decoded by libavformat/libavcodec and converted by
|
||||
# libswscale/libswresample (core/mm/media.cpp). Without them the engine serves text and refuses media
|
||||
# parts. Tri-state like HIP, so a machine with the libraries does not silently build without them.
|
||||
set(RAD_FFMPEG_FOUND OFF)
|
||||
if(NOT RAD_WITH_FFMPEG STREQUAL "OFF")
|
||||
find_package(PkgConfig QUIET)
|
||||
if(PkgConfig_FOUND)
|
||||
pkg_check_modules(RAD_FFMPEG QUIET IMPORTED_TARGET libavformat libavcodec libavutil libswscale
|
||||
libswresample)
|
||||
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/libswresample were not found.")
|
||||
else()
|
||||
message(STATUS "radiance: no libavformat -- image, video and audio input will be refused")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
add_subdirectory(vendor)
|
||||
add_subdirectory(core)
|
||||
# Kernel plugins, one root directory each. Each holds its kernels, row table and layouts and links
|
||||
# only rad_abi, exactly like a plugin written out of tree.
|
||||
add_subdirectory(libref)
|
||||
# libquant: the built-in quantisers, the third plugin kind (spec §4.5). Host C++, built everywhere:
|
||||
# rad-convert drives it and the oracle decodes through it.
|
||||
add_subdirectory(libquant)
|
||||
if(RAD_HIP_FOUND AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/libr4d/CMakeLists.txt)
|
||||
add_subdirectory(libr4d)
|
||||
endif()
|
||||
# libavx: the production host kernels (x86 SIMD, dispatched by CPU feature), built on every x86-64.
|
||||
# Not optional: host-placed ops need a kernel other than the oracle (rad_gate_reference_kernels
|
||||
# refuses libref), and a table too large for the card, such as the n-gram embedding's gather, runs
|
||||
# on the host every step. Also builds standalone without ROCm (`cmake -S libavx -B build-avx`).
|
||||
if(CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64|amd64)$")
|
||||
add_subdirectory(libavx)
|
||||
endif()
|
||||
add_subdirectory(arch)
|
||||
add_subdirectory(tools)
|
||||
if(RAD_BUILD_TESTS)
|
||||
enable_testing()
|
||||
add_subdirectory(tests)
|
||||
endif()
|
||||
|
||||
# ---------------------------------------------------------------- the installed package
|
||||
# Install-only rules for `find_package(radiance)`; they do not affect the build tree.
|
||||
#
|
||||
# (a) The ABI headers, which include only each other and C standard headers. arch/common/ is
|
||||
# installed by arch/CMakeLists.txt. Under include/radiance/ to avoid clashes in shared prefixes such
|
||||
# as /usr; the include spelling is unchanged because the target's include path is radiance/ itself.
|
||||
install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/abi/
|
||||
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/radiance
|
||||
FILES_MATCHING PATTERN "*.h")
|
||||
|
||||
# (b) The ABI target as radiance::abi. It carries the include path, RAD_DEFAULT_HOME and RAD_HAVE_HIP,
|
||||
# the flags a plugin must be compiled with to load in this engine.
|
||||
install(TARGETS rad_abi EXPORT radianceTargets)
|
||||
install(EXPORT radianceTargets
|
||||
NAMESPACE radiance::
|
||||
FILE radianceTargets.cmake
|
||||
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/radiance)
|
||||
|
||||
# (c) The package config. Its version is the ABI version, read from the header: the loader requires
|
||||
# an exact RAD_ABI_VERSION match (core/plugin/loader.cpp), which SameMajorVersion with the ABI as
|
||||
# the major expresses to CMake.
|
||||
file(STRINGS "${CMAKE_CURRENT_SOURCE_DIR}/abi/rad_abi.h" RAD_ABI_VERSION_LINE
|
||||
REGEX "^#define[ \t]+RAD_ABI_VERSION[ \t]")
|
||||
string(REGEX MATCH "[0-9]+" RAD_ABI_VERSION "${RAD_ABI_VERSION_LINE}")
|
||||
if(NOT RAD_ABI_VERSION)
|
||||
message(FATAL_ERROR
|
||||
"could not read RAD_ABI_VERSION out of abi/rad_abi.h; the package config cannot state the "
|
||||
"plugin compatibility it is built for without it.")
|
||||
endif()
|
||||
|
||||
include(CMakePackageConfigHelpers)
|
||||
|
||||
# PATH_VARS, so the config resolves these relative to where the package is found, which keeps
|
||||
# staged (DESTDIR) and relocated installs working.
|
||||
set(RAD_HOME_RELDIR "${CMAKE_INSTALL_DATADIR}/radiance")
|
||||
set(RAD_INCLUDE_RELDIR "${CMAKE_INSTALL_INCLUDEDIR}/radiance")
|
||||
configure_package_config_file(
|
||||
${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 config includes this exact file, so there is one copy for both builds.
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/cmake/RadAddPlugin.cmake
|
||||
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/radiance)
|
||||
|
||||
# (d) License and notices. Apache-2.0 and the bundled components' licenses require them to travel
|
||||
# with every copy, including images built from the install.
|
||||
install(FILES LICENSE NOTICE DESTINATION ${CMAKE_INSTALL_DOCDIR})
|
||||
install(FILES vendor/llama/LICENSE
|
||||
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME llama.cpp.LICENSE)
|
||||
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)
|
||||
install(FILES core/server/LICENSE.lfm
|
||||
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME liquidai-d1.LICENSE)
|
||||
@@ -0,0 +1,81 @@
|
||||
{
|
||||
"version": 6,
|
||||
"cmakeMinimumRequired": { "major": 3, "minor": 25, "patch": 0 },
|
||||
"configurePresets": [
|
||||
{
|
||||
"name": "default",
|
||||
"displayName": "RelWithDebInfo in build/, HIP when a card is found",
|
||||
"generator": "Ninja",
|
||||
"binaryDir": "${sourceDir}/build"
|
||||
},
|
||||
{
|
||||
"name": "asan",
|
||||
"displayName": "AddressSanitizer + UBSan, host backend, in build-asan/",
|
||||
"inherits": "default",
|
||||
"binaryDir": "${sourceDir}/build-asan",
|
||||
"cacheVariables": { "RAD_ASAN": "ON", "RAD_TSAN": "OFF", "RAD_WITH_HIP": "OFF" }
|
||||
},
|
||||
{
|
||||
"name": "tsan",
|
||||
"displayName": "ThreadSanitizer, host backend, in build-tsan/",
|
||||
"inherits": "default",
|
||||
"binaryDir": "${sourceDir}/build-tsan",
|
||||
"cacheVariables": { "RAD_TSAN": "ON", "RAD_ASAN": "OFF", "RAD_WITH_HIP": "OFF" }
|
||||
}
|
||||
],
|
||||
"buildPresets": [
|
||||
{ "name": "default", "configurePreset": "default" },
|
||||
{ "name": "asan", "configurePreset": "asan" },
|
||||
{ "name": "tsan", "configurePreset": "tsan" }
|
||||
],
|
||||
"testPresets": [
|
||||
{
|
||||
"name": "base",
|
||||
"hidden": true,
|
||||
"configurePreset": "default",
|
||||
"output": { "outputOnFailure": true },
|
||||
"execution": { "jobs": 8, "noTestsAction": "error" }
|
||||
},
|
||||
{
|
||||
"name": "fast",
|
||||
"displayName": "The inner loop: no slow, gpu, oot or perf test",
|
||||
"inherits": "base",
|
||||
"filter": { "include": { "label": "^fast$" } }
|
||||
},
|
||||
{
|
||||
"name": "host",
|
||||
"displayName": "Everything that runs without a card, except the out-of-tree rebuild",
|
||||
"inherits": "base",
|
||||
"filter": { "exclude": { "label": "^(gpu|oot)$" } }
|
||||
},
|
||||
{
|
||||
"name": "full",
|
||||
"displayName": "Every test",
|
||||
"inherits": "base"
|
||||
},
|
||||
{
|
||||
"name": "gpu",
|
||||
"displayName": "The tests that need a card, one at a time",
|
||||
"inherits": "base",
|
||||
"filter": { "include": { "label": "^gpu$" } }
|
||||
},
|
||||
{
|
||||
"name": "perf",
|
||||
"displayName": "The wall-clock checks, one at a time",
|
||||
"inherits": "base",
|
||||
"filter": { "include": { "label": "^perf$" } }
|
||||
},
|
||||
{
|
||||
"name": "asan",
|
||||
"displayName": "The fast tier under AddressSanitizer + UBSan",
|
||||
"inherits": "fast",
|
||||
"configurePreset": "asan"
|
||||
},
|
||||
{
|
||||
"name": "tsan",
|
||||
"displayName": "The fast tier under ThreadSanitizer",
|
||||
"inherits": "fast",
|
||||
"configurePreset": "tsan"
|
||||
}
|
||||
]
|
||||
}
|
||||
+289
@@ -0,0 +1,289 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
#
|
||||
# radiance as a container image: the engine, plugins and tools built in the ROCm toolchain image,
|
||||
# the host test suite run against that build, and a FROM scratch runtime image holding the install
|
||||
# tree and exactly the shared libraries it loads (no distribution, no package manager, only a
|
||||
# static busybox).
|
||||
#
|
||||
# docker/build.sh # the usual way (BuildKit / buildx)
|
||||
# docker buildx build -t radiance . # the same, by hand
|
||||
# docker buildx build --build-arg GPU_TARGETS="gfx1200;gfx1201" -t radiance .
|
||||
#
|
||||
# Stages:
|
||||
# ffmpeg FFmpeg with only the demuxers core/mm/media.cpp admits, the decoders their streams
|
||||
# need (pictures, video, audio with swresample) and the three encoders the images API
|
||||
# writes (png, mjpeg, libwebp); the distribution's build pulls ~200 unused packages
|
||||
# llvm ROCm's libLLVM rebuilt from ROCm's llvm-project at the commit the image's clang
|
||||
# reports, with docker/llvm-vopd-pairing.patch, which makes LLVM 24's device code
|
||||
# repeatable across builds (cmake/RadAddPlugin.cmake, rad_hip_repeatable)
|
||||
# build ROCm dev image + cmake/ninja/g++-14; configures, builds and installs to /stage, with
|
||||
# device code compiled by ROCm's clang from a shadow ROCm tree using the llvm stage's
|
||||
# libLLVM
|
||||
# test docker/llvm-check.sh, then the host-only ctest suites
|
||||
# rootfs the stripped install tree plus every library its binaries and plugins load (resolved
|
||||
# by ldd), copied into one directory and checked from inside a chroot
|
||||
# runtime FROM scratch + rootfs; the shipped image
|
||||
#
|
||||
# Device code is not built with --offload-compress: the AQL backend reads the fat binaries itself
|
||||
# and refuses a compressed bundle.
|
||||
#
|
||||
# GPU_TARGETS must be named: a build container has no card to detect, unlike a bare-metal
|
||||
# ./build.sh. They are the targets of the shipped kernel libraries; libr4d serves RDNA4 only and
|
||||
# drops every architecture outside gfx12. The engine's own kernels carry the generic family
|
||||
# targets and run on every AMD GPU family, so a kernel library for another card is added by
|
||||
# mounting it on the search path:
|
||||
# docker run ... -v /my/plugins:/plugins -e RADIANCE_HOME=/plugins:/opt/radiance/share/radiance
|
||||
#
|
||||
# The image's ROCm userspace must be supported by the host's amdgpu kernel driver; it is pinned to
|
||||
# the serving host's version, so move both together. From ROCm 10 on, the dev image is published
|
||||
# only as the -full tag.
|
||||
|
||||
ARG ROCM_VERSION=10.1.0-full
|
||||
ARG UBUNTU_VERSION=24.04
|
||||
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 \
|
||||
libwebp-dev \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
WORKDIR /tmp
|
||||
# Demuxers: media.cpp's kFormats whitelist. Decoders: what those containers carry -- still
|
||||
# images, H.264 and HEVC (MP4, MOV, HEIF), VP8 and VP9 (WebM, WebP), AV1 through dav1d (WebM, MP4,
|
||||
# AVIF), MPEG-1/2/4, Theora and the FLV/H.263 family. JPEG XL is recognised and refused by name
|
||||
# (its only decoder is libjxl's). Encoders: the image output formats of media.cpp encode_image
|
||||
# (png, jpeg as mjpeg, webp through libwebp). No protocols: media.cpp reads from memory through its
|
||||
# own I/O context.
|
||||
RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
|
||||
curl -fsSL "https://ffmpeg.org/releases/ffmpeg-${FFMPEG_VERSION}.tar.xz" -o ffmpeg.tar.xz \
|
||||
&& echo "${FFMPEG_SHA256} ffmpeg.tar.xz" | sha256sum -c - \
|
||||
&& 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 --enable-swresample \
|
||||
--enable-zlib --enable-libdav1d --enable-libwebp \
|
||||
--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,wav,w64,mp3,flac,aac,aiff \
|
||||
--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,pcm_u8,pcm_s16le,pcm_s16be,pcm_s24le,pcm_s24be,pcm_s32le,pcm_s32be,pcm_f32le,pcm_f32be,pcm_f64le,pcm_alaw,pcm_mulaw,mp3float,mp2float,flac,vorbis,opus,aac \
|
||||
--enable-encoder=png,mjpeg,libwebp \
|
||||
--enable-parser=h264,hevc,vp8,vp9,av1,mpeg4video,mpegvideo,mjpeg,png,gif,bmp,webp,vp3,qoi,pnm,h263,jpegxl,mpegaudio,flac,aac,vorbis,opus \
|
||||
&& 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
|
||||
|
||||
# ------------------------------------------------------------------------------------------- llvm
|
||||
FROM rocm/dev-ubuntu-${UBUNTU_VERSION}:${ROCM_VERSION} AS llvm
|
||||
ARG JOBS=
|
||||
# clang, lld and the offload tools all load lib/llvm/lib/libLLVM.so, so this stage rebuilds only
|
||||
# that file: ROCm's llvm-project at exactly the commit `clang --version` names (the stage stops if
|
||||
# clang names none or the patch does not apply), configured as ROCm's
|
||||
# lib/cmake/llvm/LLVMConfig.cmake records -- Release without assertions, AMDGPU;SPIRV;X86, every
|
||||
# component in the dylib, no RTTI or exceptions, zlib and zstd from rocm_sysdeps -- and compiled
|
||||
# by ROCm's own clang and lld. With VOPD pairing off it produces
|
||||
# ROCm's code byte for byte; docker/llvm-check.sh holds the build stage to that. The fetch is
|
||||
# sparse and depth one: llvm/ plus the cmake/, libc/ and third-party/ directories configure reads,
|
||||
# without tests or documentation.
|
||||
RUN apt-get update \
|
||||
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
|
||||
git cmake ninja-build ca-certificates \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
COPY docker/llvm-vopd-pairing.patch /tmp/
|
||||
RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
|
||||
set -e; L=/opt/rocm/lib/llvm; S=/opt/rocm/lib/rocm_sysdeps; \
|
||||
rev=$($L/bin/clang --version | sed -n 's|.*ROCm/llvm-project.git \([0-9a-f]\{40\}\).*|\1|p'); \
|
||||
[ -n "$rev" ] || { echo "llvm: no ROCm/llvm-project commit in: $($L/bin/clang --version | head -1)" >&2; exit 1; }; \
|
||||
git init -q /llvm-project; cd /llvm-project; \
|
||||
git remote add origin https://github.com/ROCm/llvm-project.git; \
|
||||
git sparse-checkout set --no-cone '/*' '!/*/' /cmake/ /libc/ /llvm/ /third-party/ \
|
||||
'!/llvm/test/' '!/llvm/unittests/' '!/llvm/docs/' '!/llvm/benchmarks/'; \
|
||||
git fetch -q --depth 1 --filter=blob:none origin "$rev"; \
|
||||
git checkout -q FETCH_HEAD; \
|
||||
git apply /tmp/llvm-vopd-pairing.patch; \
|
||||
cmake -G Ninja -S llvm -B /build-llvm -DCMAKE_BUILD_TYPE=Release -DLLVM_ENABLE_ASSERTIONS=OFF \
|
||||
-DLLVM_TARGETS_TO_BUILD="AMDGPU;SPIRV;X86" -DLLVM_BUILD_LLVM_DYLIB=ON -DLLVM_LINK_LLVM_DYLIB=ON \
|
||||
-DLLVM_DYLIB_COMPONENTS=all -DLLVM_ENABLE_RTTI=OFF -DLLVM_ENABLE_EH=OFF -DLLVM_ENABLE_FFI=OFF \
|
||||
-DLLVM_ENABLE_LIBXML2=OFF -DLLVM_ENABLE_LIBEDIT=OFF -DLLVM_ENABLE_CURL=OFF \
|
||||
-DLLVM_ENABLE_HTTPLIB=OFF -DLLVM_ENABLE_TELEMETRY=ON -DLLVM_ENABLE_PLUGINS=ON \
|
||||
-DLLVM_ENABLE_LIBPFM=OFF \
|
||||
-DLLVM_ENABLE_ZLIB=FORCE_ON -DZLIB_INCLUDE_DIR=$S/include -DZLIB_LIBRARY=$S/lib/librocm_sysdeps_z.so.1 \
|
||||
-DLLVM_ENABLE_ZSTD=FORCE_ON -Dzstd_INCLUDE_DIR=$S/include -Dzstd_LIBRARY=$S/lib/librocm_sysdeps_zstd.so.1 \
|
||||
-DLLVM_INCLUDE_TESTS=OFF -DLLVM_INCLUDE_BENCHMARKS=OFF -DLLVM_INCLUDE_EXAMPLES=OFF \
|
||||
-DLLVM_INCLUDE_DOCS=OFF -DLLVM_BUILD_TOOLS=OFF -DLLVM_USE_LINKER=lld -DLLVM_PARALLEL_LINK_JOBS=2 \
|
||||
-DCMAKE_C_COMPILER=$L/bin/clang -DCMAKE_CXX_COMPILER=$L/bin/clang++ > /tmp/llvm-configure.log 2>&1 \
|
||||
|| { tail -40 /tmp/llvm-configure.log >&2; exit 1; }; \
|
||||
ninja -C /build-llvm ${JOBS:+-j${JOBS}} LLVM > /tmp/llvm-build.log 2>&1 \
|
||||
|| { grep -m20 -B2 -A8 'error' /tmp/llvm-build.log >&2; exit 1; }; \
|
||||
so=$(basename $(readlink -f $L/lib/libLLVM.so)); \
|
||||
mkdir -p /out; cp /build-llvm/lib/$so /out/; \
|
||||
rm -rf /build-llvm /llvm-project
|
||||
|
||||
# ------------------------------------------------------------------------------------------ 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 lower it on a host that is also serving.
|
||||
ARG JOBS=
|
||||
|
||||
# g++-14 rather than the default 13: hipcc compiles device-side translation units against its
|
||||
# libstdc++, which is also the runtime image's. gawk: tools/ops_doc_check.sh uses gensub, which
|
||||
# mawk lacks. libdav1d7 and libwebp7 are the runtime libraries of the ffmpeg stage's AV1 decoder
|
||||
# and WebP encoder; busybox-static goes into the runtime image.
|
||||
RUN apt-get update \
|
||||
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
|
||||
cmake ninja-build pkg-config g++-14 gawk libdav1d7 libwebp7 busybox-static \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY --from=ffmpeg /opt/ffmpeg /opt/ffmpeg
|
||||
# Register ROCm's library directory beside FFmpeg's: the ROCm 10 images register none, and the
|
||||
# rootfs stage resolves the installed binaries' libraries with ldd.
|
||||
RUN echo /opt/ffmpeg/lib > /etc/ld.so.conf.d/ffmpeg.conf \
|
||||
&& echo /opt/rocm/lib > /etc/ld.so.conf.d/rocm.conf && ldconfig
|
||||
|
||||
ENV ROCM_PATH=/opt/rocm HIP_PATH=/opt/rocm CC=gcc-14 CXX=g++-14 \
|
||||
PKG_CONFIG_PATH=/opt/ffmpeg/lib/pkgconfig
|
||||
|
||||
# The HIP compiler: ROCm's clang loading the llvm stage's libLLVM. ROCm's tools find libraries
|
||||
# through RPATHs relative to themselves ($ORIGIN/../lib for libLLVM, which LD_LIBRARY_PATH cannot
|
||||
# override, plus $ORIGIN/../../rocm_sysdeps/lib and $ORIGIN/../../../lib), so the compiler runs
|
||||
# from /opt/rocm-repeatable, a shadow of the whole ROCm tree at the same depth. Every entry links
|
||||
# back into /opt/rocm except lib/llvm/bin (real copies of the executables) and the rebuilt
|
||||
# libLLVM. Only compiling uses it. The build passes --rocm-path=/opt/rocm so headers and device
|
||||
# libraries are ROCm's and linked plugins record /opt/rocm/lib. Without it clang treats its own
|
||||
# tree as ROCm, and the HIP runtime would reach comgr through the rebuilt libLLVM, which lacks the
|
||||
# libstdc++ symbols ROCm's GCC-built one re-exports for comgr. The rootfs stage refuses any
|
||||
# library resolved through the shadow tree.
|
||||
COPY --from=llvm /out/ /tmp/llvm-out/
|
||||
RUN set -e; R=/opt/rocm; D=/opt/rocm-repeatable; L=lib/llvm; \
|
||||
so=$(basename $(readlink -f $R/$L/lib/libLLVM.so)); \
|
||||
[ -f /tmp/llvm-out/$so ] || { echo "the llvm stage built no $so" >&2; exit 1; }; \
|
||||
mkdir -p $D/$L/lib; \
|
||||
for e in $R/*; do n=${e##*/}; [ $n = lib ] || ln -s $e $D/$n; done; \
|
||||
for e in $R/lib/*; do n=${e##*/}; [ $n = llvm ] || ln -s $e $D/lib/$n; done; \
|
||||
for e in $R/$L/*; do n=${e##*/}; [ $n = bin ] || [ $n = lib ] || ln -s $e $D/$L/$n; done; \
|
||||
cp -a $R/$L/bin $D/$L/; \
|
||||
for e in $R/$L/lib/*; do n=${e##*/}; \
|
||||
if [ $n = $so ]; then mv /tmp/llvm-out/$so $D/$L/lib/; \
|
||||
elif [ -L $e ] && [ "$(readlink $e)" = $so ]; then ln -s $so $D/$L/lib/$n; \
|
||||
else ln -s $e $D/$L/lib/$n; fi; \
|
||||
done; \
|
||||
rm -rf /tmp/llvm-out
|
||||
|
||||
WORKDIR /src
|
||||
COPY . .
|
||||
|
||||
# The prefix is fixed at configure time because the default $RADIANCE_HOME is compiled in as
|
||||
# <prefix>/share/radiance; DESTDIR stages the tree without moving that default.
|
||||
# oom_score_adj 1000: on a host that is also serving, the OOM killer takes the compiler first.
|
||||
RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
|
||||
cmake -S . -B /build -G Ninja \
|
||||
-DCMAKE_INSTALL_PREFIX=/opt/radiance \
|
||||
-DRAD_WITH_HIP=ON -DRAD_WITH_FFMPEG=ON \
|
||||
"-DRAD_GPU_TARGETS=${GPU_TARGETS}" \
|
||||
-DCMAKE_HIP_COMPILER=/opt/rocm-repeatable/lib/llvm/bin/clang++ -DCMAKE_HIP_COMPILER_ROCM_ROOT=/opt/rocm \
|
||||
-DCMAKE_HIP_FLAGS=--rocm-path=/opt/rocm \
|
||||
-DRAD_HIP_VOPD_REPEATABLE=ON \
|
||||
&& 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
|
||||
ARG JOBS=
|
||||
# Host-only: a build container has no /dev/kfd. The `gpu`-labelled tests (the *_card entries,
|
||||
# r4d_selftest, kbench) run against a card from this stage:
|
||||
# docker buildx build --target build -t radiance-build . && docker run --rm \
|
||||
# --device /dev/kfd --device /dev/dri --security-opt seccomp=unconfined radiance-build \
|
||||
# ctest --test-dir /build -L gpu --output-on-failure
|
||||
# Tests run JOBS at a time (default one per two hardware threads, about one per core on an SMT
|
||||
# machine: the per-binary CPU budgets in tests/CMakeLists.txt hold for tests that do not share a
|
||||
# core); the `perf` entries, which assert wall-clock costs, run alone (RUN_SERIAL). The build sandbox forbids io_uring, so avx_check skips its
|
||||
# file-backed gather case. The `oot` suite (every shipped plugin rebuilt against the installed
|
||||
# package) repeats this stage's whole compile, so it runs from the development tree instead
|
||||
# (tests/oot_plugins.sh).
|
||||
RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
|
||||
bash /src/docker/llvm-check.sh /build \
|
||||
&& ctest --test-dir /build -LE 'gpu|oot' -j"${JOBS:-$(( ($(nproc) + 1) / 2 ))}" --output-on-failure \
|
||||
&& touch /build/host-tests-passed
|
||||
|
||||
# ----------------------------------------------------------------------------------------- rootfs
|
||||
FROM build AS rootfs
|
||||
# hfget.sh (fetches the Hugging Face repo a --model id names) needs curl, jq and a CA bundle.
|
||||
# Installed here rather than in `build` so changing them does not recompile the engine.
|
||||
RUN apt-get update \
|
||||
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
|
||||
curl jq ca-certificates \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
# The marker makes this stage, and so the shipped image, depend on the test stage.
|
||||
COPY --from=test /build/host-tests-passed /rootfs/opt/radiance/share/radiance/.host-tests-passed
|
||||
# Every library the binaries and plugins load, plus comgr (opened by the HIP runtime at run time
|
||||
# and required to initialise a device), goes into one directory the loader searches by default:
|
||||
# no ld.so.cache, no LD_LIBRARY_PATH. ROCm's libdrm_amdgpu has the card name table compiled in, so
|
||||
# no amdgpu.ids is copied. A static busybox provides the health check's wget and a shell for
|
||||
# `docker exec`; curl, jq and the CA bundle are for hfget.sh (the bundle is ca-certificates'
|
||||
# Mozilla set, named by that directory in the license list). docker/licenses.sh records each
|
||||
# file's package, license and source in /usr/share/doc/THIRD-PARTY. Finally every ELF file is
|
||||
# resolved from inside the tree, so none depends on a library the image lacks.
|
||||
RUN set -e; R=/rootfs; L=$R/usr/lib/x86_64-linux-gnu; \
|
||||
mkdir -p $L $R/lib64 $R/usr/bin $R/bin $R/etc/ssl/certs $R/data $R/tmp; \
|
||||
chmod 1777 $R/tmp; \
|
||||
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 /usr/bin/curl /usr/bin/jq /opt/rocm/lib/libamd_comgr.so.3; do ldd "$f"; done \
|
||||
| awk '/=> \//{print $3} /^\t\/lib64\//{print $1}' | sort -u); \
|
||||
if echo "$libs" | grep /opt/rocm-repeatable/; then \
|
||||
echo "these resolve through the compiler's shadow ROCm tree, not /opt/rocm" >&2; exit 1; fi; \
|
||||
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 /bin/busybox $R/usr/bin/busybox; ln -s /usr/bin/busybox $R/bin/sh; \
|
||||
cp /usr/bin/curl /usr/bin/jq $R/usr/bin/; \
|
||||
cp /etc/ssl/certs/ca-certificates.crt $R/etc/ssl/certs/; \
|
||||
sh /src/docker/licenses.sh $R $libs /opt/rocm/lib/libamd_comgr.so.3 /bin/busybox \
|
||||
/usr/bin/curl /usr/bin/jq /usr/share/ca-certificates/mozilla; \
|
||||
for f in $(cd $R && find opt/radiance usr/lib -type f -exec sh -c 'head -c4 "$1" | grep -q ELF' _ {} \; -print) \
|
||||
usr/bin/curl usr/bin/jq; 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; \
|
||||
chroot $R /usr/bin/curl --version > /dev/null; chroot $R /usr/bin/jq --version > /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/ /
|
||||
|
||||
# Let one allocation take the whole card and the HIP heap grow to all of VRAM; the runtime's
|
||||
# defaults cap both below what the placement plan hands out.
|
||||
ENV PATH=/opt/radiance/bin:/usr/bin:/bin \
|
||||
GPU_MAX_ALLOC_PERCENT=100 \
|
||||
GPU_MAX_HEAP_SIZE=100
|
||||
|
||||
WORKDIR /data
|
||||
EXPOSE 8000
|
||||
ENTRYPOINT ["radiance"]
|
||||
CMD ["--help"]
|
||||
@@ -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.
|
||||
@@ -0,0 +1,49 @@
|
||||
radiance
|
||||
Copyright 2026 Deadcode and the radiance contributors
|
||||
|
||||
Written by Deadcode, with contributions from tcclaviger (the N-rank all-reduce kernels), ggz14 (the
|
||||
MXFP4 GEMM, the A-tiled MXFP4 prefill GEMM and the GDN kernels' overflow guards), slydlake (the
|
||||
MXFP4 decode and prefill GEMMs, the MXFP4 linear and the DFlash2 drafter's MXFP4 linears, stop
|
||||
strings after the reasoning block, and the draft refill on a prefix hit), goodman-b (four-rank
|
||||
tensor parallelism for Qwen3.8-Flash-Next, the four-rank collectives ending the link hold
|
||||
themselves, their selftest cases and the TP4 lever map), keptn42 (the four-rank all-reduce served in
|
||||
place, the fused four-rank writes, the n-gram table in RAM, the four-class expert split, the Grafana
|
||||
dashboard, the routed GEMM's decode loads and run search, the gated residual's prefill read form and
|
||||
row groups, the fused router launch, the adaptive draft window, the MoE prefill forms, the sorted
|
||||
operand's decode kernel, two K blocks a pass for up to 80 routed rows, --prefill-span, the towers'
|
||||
lookup tables counted once, and for Gemma 4 its assistant head as a drafter that reads the trunk's
|
||||
cache, bf16 checkpoints, the fused w4a8 decode step, the vision tower and window snapshots that let
|
||||
a prefix hit resume), mechkbfan (the token embedding in the pinned host pool), Code000 (the n-gram
|
||||
gather on the card and the MTP head's history-pass skip), baKon (three-rank tensor parallelism,
|
||||
serving any world size from the shipped container, the request log, an uneven world's per-rank KV
|
||||
and weights split, --rope-scaling, the model entry's context length, root and capabilities, /props,
|
||||
the three-rank two-shot all-reduce and tiered-int8 wire, the diagnosis of the three-rank lossy-wire
|
||||
crash, cardclock.py, --busy-prefill-chunk, curl, jq and a CA bundle in the image with hfget.sh under
|
||||
its busybox, rad-export, and carrying Smellyyyy's --prefill-interleave), hazyumps (static YaRN for
|
||||
the Qwen rotary paths), malic (ParoQuant: its MXFP4, int5 and int4 checkpoints imported and served,
|
||||
the Givens rotation as stages and as dense per-group matrices on the matrix cores, and the 5- and
|
||||
4-bit asymmetric GEMMs), Perire (Gemma 4 26B-A4B with z-lab's DFlash drafter: its plugin, its
|
||||
kernels in libr4d -- the windowed paged attention, pair_argmax, the fused sandwich joins and
|
||||
expert_scale -- and the host emulator that tests them, the prefill split into two slices with their
|
||||
all-reduces beside the compute, and the vocabulary-sharded draft head), redxherring (--model taking
|
||||
a Hugging Face repo id), Smellyyyy (--prefill-interleave), gearwave00001 (/v1/messages as Claude
|
||||
Code sends it), devmilan (the NVFP4 and FP8 compressed-tensors imports), sfjes (Gemma 4 31B dense:
|
||||
its plugin, its two attention classes and their kernels, and prefix reuse that leaves a windowed
|
||||
group alone) and zivius (LiquidAI's LFM2 and LFM2-VL and d1's /v1/systemone, after the design of
|
||||
their Codeberg PR 50, and Qwen3-ASR with /v1/audio/transcriptions and /v1/realtime).
|
||||
|
||||
This product includes software from the following projects, each under the MIT License. The
|
||||
license text is in the file named beside each.
|
||||
|
||||
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
|
||||
|
||||
core/server/systemone.cpp carries text from Liquid AI's d1 (prompt.py and api.py in the
|
||||
LiquidAI/d1-3B repository): the prompt it renders, its question blocks, the option codes and their
|
||||
fallback codebook and the answer spellings, unchanged, in code rewritten in C++. That text is Liquid
|
||||
AI, Inc.'s, under the LFM Open License v1.0, whose terms -- including its limit on commercial use --
|
||||
apply to it; the license is in core/server/LICENSE.lfm.
|
||||
@@ -0,0 +1,248 @@
|
||||
# radiance
|
||||
|
||||
An LLM and image-generation inference server for AMD GPUs, in C++ and HIP. Its HTTP API speaks
|
||||
OpenAI's chat, completions, Responses and images APIs, Anthropic's Messages API and llama-server's
|
||||
native one, so their clients and SDKs work unchanged. Model architectures, kernel libraries and
|
||||
quantisers are `.so` plugins; the ones in this tree are built and loaded the same way a third
|
||||
party's are ([`docs/PLUGIN.md`](docs/PLUGIN.md)).
|
||||
|
||||
The bundled device kernels (`libr4d`) target AMD RDNA4 (`gfx1200`, `gfx1201`). The serve flags
|
||||
below are for two 32 GB cards (Radeon AI PRO R9700). The engine starts on any AMD GPU family;
|
||||
another card needs a kernel library for it. A machine with no GPU builds the host backend, whose
|
||||
AVX-512/AVX2 kernels (`libavx`) serve every model here: the small ones (EmbeddingGemma 2,
|
||||
Qwen3-ASR, the 0.8B-3B models) at interactive speed on a desktop CPU, the 27B and larger far more
|
||||
slowly than a card.
|
||||
|
||||
To support the development of radiance: [Patreon](https://patreon.com/StillDeadCode).
|
||||
|
||||
## 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.8-27B MXFP4 (AMD Quark AWQ), DFlash2 drafter, vision | `qwen3.8-27b-mxfp4.rad` (19 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-27b-mxfp4) | `qwen3.8-27b-mxfp4.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` |
|
||||
| Gemma 4 31B: GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-w4a8) | `gemma4-31b-w4a8.yaml` |
|
||||
| Qwen-Image 2.1 FP8: text to image and image edits | `qwen-image-2.1-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-fp8) | `qwen-image-2.1.yaml` |
|
||||
| Qwen-Image 2.1 Turbo FP8: the same in 8 steps | `qwen-image-2.1-turbo-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-turbo-fp8) | `qwen-image-2.1-turbo.yaml` |
|
||||
| Qwen3.8-27B ParoQuant int4, int5 or MXFP4 (learned rotations), DFlash2 drafter, vision | `qwen3.8-27b-paro-int4.rad` (19 GiB; int5 22 GiB) | [convert](#convert-a-checkpoint) | `qwen3.8-27b-paro.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` |
|
||||
| EmbeddingGemma 2 bf16: text, image, video and audio embeddings, one card | `embeddinggemma2-bf16.rad` (1.4 GiB) | [convert](#convert-a-checkpoint) | `embeddinggemma2.yaml` |
|
||||
| Qwen3-ASR 1.7B bf16: speech to text, `/v1/audio/transcriptions` and live over `/v1/realtime`, 30 languages, one card | the checkpoint as it ships (4.1 GiB) | [Qwen/Qwen3-ASR-1.7B-hf](https://huggingface.co/Qwen/Qwen3-ASR-1.7B-hf) | — |
|
||||
|
||||
A container holds everything the server needs: the weights, the tokeniser, the chat template and
|
||||
any drafter. Each download link's repository has the recipe and the exact command that made the
|
||||
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
|
||||
```
|
||||
|
||||
The Gemma 4 container is keptn42's: GPTQ calibrated in transformers, with an int8 lm_head; its
|
||||
repository has the recipe and the calibration step. To convert Google's bf16 checkpoint yourself,
|
||||
`data/recipes/gemma4-31b-dense-bf16-w4a8.recipe` quantises without calibration (round-to-nearest
|
||||
with a scale search, bf16 lm_head); see [Convert a checkpoint](#convert-a-checkpoint). On two R9700s
|
||||
that container decodes at 103 tok/s on prose and 141 on code, against 112 and 150 for keptn42's,
|
||||
and accepts 0.46 of its drafts on prose against 0.50.
|
||||
|
||||
The ParoQuant containers keep the trunk exactly as the ParoQuant releases ship it, with the learned
|
||||
Givens rotations it was trained in. Convert int4 from `z-lab/Qwen3.8-27B-PARO`, int5 from
|
||||
`Launch80/Qwen3.8-27B-PARO-int5` and MXFP4 from `MisterSnrub/Qwen3.8-27B-PARO-MXFP4-v2`, each with
|
||||
`data/recipes/q38-27b-paro-mxfp4-df2.recipe` and the DFlash2 drafter. A ParoQuant container made
|
||||
before 1.5.0 is refused at startup; convert it again with the old one as `--reuse`, which copies
|
||||
every tensor that did not change.
|
||||
|
||||
The Qwen-Image containers serve OpenAI's images API (`/v1/images/generations`, `/v1/images/edits`):
|
||||
pictures from a prompt, and edits of up to ten pictures with an optional mask, 2048x2048 by default.
|
||||
On two R9700s a 2048x2048 picture takes 61 s at the base model's 40 steps and 13 s with Turbo (56 and
|
||||
12 s with `--tp-wire wht6`); 1024x1024 takes 6 s and 2.6 s. Qwen-Image 2.1 is under Qwen's research
|
||||
license, which is non-commercial.
|
||||
|
||||
## Run with Docker
|
||||
|
||||
The host needs Docker and an `amdgpu` driver that supports ROCm 10.1; it does not need ROCm. The
|
||||
card needs Resizable BAR on (Above 4G Decoding and Resizable BAR in the firmware setup). The image
|
||||
is [`stilldeadcode/radiance`](https://hub.docker.com/r/stilldeadcode/radiance), with its kernels
|
||||
built for `gfx1201`. Pull it, clone this repository for its compose files, then start a model from
|
||||
one of them:
|
||||
|
||||
```sh
|
||||
docker pull stilldeadcode/radiance
|
||||
git clone https://codeberg.org/StillDeadcode/radiance.git
|
||||
cp -r radiance/deploy/compose ~/radiance-compose && cd ~/radiance-compose
|
||||
cp .env.example .env # set RADIANCE_MODELS, RADIANCE_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 listens on the same port and most use both cards, so run one at a time. Running without
|
||||
compose, and the reason for each `docker run` option, is in [`docs/DOCKER.md`](docs/DOCKER.md).
|
||||
|
||||
To build the image yourself, for example for other cards, run `docker/build.sh -t 'gfx1200;gfx1201'`
|
||||
in the clone (it needs `docker buildx` and tests the build as it goes). Then set
|
||||
`RADIANCE_IMAGE=radiance:latest` in `.env`.
|
||||
|
||||
## Build from source
|
||||
|
||||
You need Linux, git, a C++20 compiler, CMake 3.21+ and Ninja. For the device kernels you also need
|
||||
ROCm 10.1 or 7.2 (`hipcc`; set `ROCM_PATH` if it is not `/opt/rocm`). Clone the repository and
|
||||
build in it:
|
||||
|
||||
```sh
|
||||
git clone https://codeberg.org/StillDeadcode/radiance.git && cd radiance
|
||||
./build.sh # configure, build for the cards present, run the fast tests
|
||||
./build.sh --no-hip # host backend only
|
||||
cmake -S . -B build -G Ninja -DRAD_GPU_TARGETS='gfx1201' # build for cards this machine lacks
|
||||
```
|
||||
|
||||
To install, name the prefix when the build directory is first configured
|
||||
(`-DCMAKE_INSTALL_PREFIX=/opt/radiance`), build, then run `cmake --install build`. The default
|
||||
plugin path, `<prefix>/share/radiance`, is compiled in from that first configure, so
|
||||
`cmake --install build --prefix DIR` alone gives a tree that looks for its plugins elsewhere. The
|
||||
prefix gets `bin/`, `include/radiance/`, `lib/cmake/radiance/`, `libexec/radiance/`,
|
||||
`share/radiance/` and `share/doc/radiance/`.
|
||||
|
||||
With ROCm 10.1 the build turns the compiler's VOPD pairing (dual-issue instruction pairs) off: its
|
||||
LLVM 24 pairs in an order that follows heap addresses, so two builds of the same source can differ.
|
||||
The Docker image builds its compiler with the fix and keeps the pairing, which is 1.4-3.5% faster
|
||||
on the fp8 prefill GEMMs; a compiler that has the same fix is declared with
|
||||
`-DRAD_HIP_VOPD_REPEATABLE=ON`. ROCm 7.2 is unaffected.
|
||||
|
||||
## Run without Docker
|
||||
|
||||
```sh
|
||||
export RADIANCE_HOME=$PWD/build/radiance_home # the plugins; an install finds its own
|
||||
build/bin/radiance --model /srv/models/rad/minicpm5-2b-fp8.rad --port 8000 <flags>
|
||||
build/bin/radiance --model StillDeadcode/minicpm5-2b-fp8 --port 8000 <flags>
|
||||
```
|
||||
|
||||
`--model` also takes a Hugging Face repo id, as vLLM does. The server fetches the repo with `curl`
|
||||
and `jq` (`scripts/hfget.sh`) into `~/.cache/radiance/hf` (`--download-dir` puts it elsewhere),
|
||||
serves the container it holds, and checks it for changes at every start; a start that cannot reach
|
||||
the hub serves the copy it has. The Docker image carries both tools; in a container,
|
||||
`--download-dir` must name a writable mount, since the compose files mount `/models` read-only.
|
||||
|
||||
These rows match the compose files, minus Flash-Next's `--prefix-cache-mib`; the three- and
|
||||
four-rank rows have no compose file. The other models' flags are in their compose files.
|
||||
|
||||
| model | flags |
|
||||
|---|---|
|
||||
| Qwen3.8-Flash-Next | `--tp 2 --tp-wire wht6 --max-num-seqs 8 --max-model-len 200000 --placement expert_tiered --host-pool-mib 12288 --gpu-headroom-mib 96 --kv-cache-dtype fp8 --num-speculative-tokens 3 --max-num-batched-tokens 2048` |
|
||||
| Qwen3.8-Flash-Next, four ranks | `--tp 4 --max-num-seqs 8 --max-model-len 200000 --placement expert_tiered --host-pool-mib 12288 --gpu-headroom-mib 96 --kv-cache-dtype fp8 --num-speculative-tokens 3 --max-num-batched-tokens 2048` |
|
||||
| Qwen3.8-Flash-Next, three ranks (the shipped container as it is, [`docs/TP3.md`](docs/TP3.md)) | `--tp 3 --max-num-seqs 8 --max-model-len 200000 --placement expert_tiered --host-pool-mib 8192 --gpu-headroom-mib 96 --kv-cache-dtype fp8 --num-speculative-tokens 3 --max-num-batched-tokens 2048` |
|
||||
| Qwen3.8-27B FP8 and MXFP4, Qwen3.6-35B-A3B | `--tp 2 --max-num-seqs 32 --max-model-len 200000 --kv-cache-dtype fp8` |
|
||||
| Qwen3.8-27B bf16 | `--tp 2 --max-num-seqs 8 --max-model-len 200000 --kv-cache-dtype fp8` |
|
||||
| MiniCPM5-2B FP8 and bf16 | `--tp 2 --max-num-seqs 32 --max-model-len 131072 --kv-cache-dtype fp8 --gpu-headroom-mib 160 --max-num-batched-tokens 512` |
|
||||
| Qwen3.8-Flash-Next bf16 | `--tp 2 --max-model-len 32768 --placement expert_tiered --weights-disk-tier --host-pool-mib 12288 --gpu-headroom-mib 768 --deterministic --max-num-seqs 32 --max-num-batched-tokens 32768 --num-speculative-tokens 0` |
|
||||
| Qwen-Image 2.1 and 2.1 Turbo | `--tp 2 --tp-wire wht6` |
|
||||
|
||||
Every model here runs at up to 32 sequences a step. The Flash-Next rows (except the bf16 reference)
|
||||
and the 27B in bf16 keep 8: on a hybrid model each sequence holds its own recurrent state, and 32 of
|
||||
them take that memory from the attention cache and, on Flash-Next, from the expert slab. See
|
||||
[`docs/GUIDE.md`](docs/GUIDE.md) §4.4.
|
||||
|
||||
At `--tp 4`, decode and verify steps carry the exact all-reduce in the gated residual's write, with
|
||||
the MoE gather in front of it; a prefill chunk runs the unfused chain. That chain's exact
|
||||
all-reduce is one-shot up to 1 MiB a message and two-shot above, which sends half the bytes on a
|
||||
prefill chunk; both produce the same bits. The four-rank row runs exact. At three and four ranks
|
||||
`--tp-wire wht6` selects a different lossy wire, tiered int8 over the two-shot, above
|
||||
`--tp-wire-min-kb`. Eight ranks have no lossy wire, so `--tp 8 --tp-wire wht6` stops at startup
|
||||
naming the all-reduce.
|
||||
|
||||
Four ranks is a capacity configuration: its per-step rate against `--tp 2` on the same cards has
|
||||
not been measured, and its tiering flags are the two-rank recipe carried over. As at two ranks, each
|
||||
rank owns a slice of every expert's width: each parity's 128-column blocks are cut contiguously over
|
||||
the ranks and the odd block alternates with the parity, so every rank's share is whole blocks and
|
||||
every block has one owner. The resident expert bytes per rank are smaller, so the elastic window
|
||||
has a different shape: read the boot log's `elastic` line and re-derive `--host-pool-mib` before
|
||||
trusting it.
|
||||
|
||||
`--host-pool-mib` is pinned on every card, so the four-rank row pins 4 × 12 GiB = 48 GiB of RAM
|
||||
that nothing else can use and the kernel cannot swap out. The amdgpu driver caps what all processes
|
||||
together pin at the machine's RAM less 1/64 and 1.5 GiB; the pool is locked user memory, which
|
||||
`ttm.pages_limit` does not count. A 64 GiB machine serves `flashnext-tp1.yaml` with 49 GiB pinned
|
||||
([`docs/GUIDE.md`](docs/GUIDE.md) §7).
|
||||
|
||||
Add `--api-key KEY` to require `Authorization: Bearer KEY` (or `X-Api-Key: KEY`). `--debug-graph`
|
||||
prints every op and the kernel it resolved to, then exits without serving. A chat request:
|
||||
|
||||
```sh
|
||||
curl -s localhost:8000/v1/chat/completions -H 'Content-Type: application/json' \
|
||||
-d '{"model":"m","messages":[{"role":"user","content":"hi"}],"max_tokens":50}'
|
||||
```
|
||||
|
||||
An image model answers OpenAI's images API instead, with base64 pictures:
|
||||
|
||||
```sh
|
||||
curl -s localhost:8000/v1/images/generations -H 'Content-Type: application/json' \
|
||||
-d '{"prompt":"a lighthouse on a cliff at sunset, oil painting","size":"1024x1024"}' \
|
||||
| python3 -c 'import sys,json,base64; open("out.png","wb").write(base64.b64decode(json.load(sys.stdin)["data"][0]["b64_json"]))'
|
||||
```
|
||||
|
||||
`http://localhost:8000/` is the dashboard. [`docs/GUIDE.md`](docs/GUIDE.md) covers the API, memory
|
||||
budgets, long context, speculative decoding and operating a server.
|
||||
|
||||
## Convert a checkpoint
|
||||
|
||||
`rad-convert` turns a Hugging Face checkpoint into a container, quantising what a recipe in
|
||||
`data/recipes/` names. Download checkpoints with `scripts/hfget.sh <org/repo> <dir>`.
|
||||
|
||||
```sh
|
||||
build/bin/rad-convert /srv/models/hf/Qwen/Qwen3.8-27B -o qwen3.8-27b-bf16.rad \
|
||||
--recipe data/recipes/q38-27b-bf16.recipe
|
||||
build/bin/rad-convert /srv/models/hf/Qwen/Qwen3.8-Flash-Next -o qwen3.8-flash-next-bf16.rad --max-ctx 4096
|
||||
build/bin/rad-convert /srv/models/hf/google/gemma-4-31B-it -o gemma4-31b-w4a8.rad \
|
||||
--recipe data/recipes/gemma4-31b-dense-bf16-w4a8.recipe \
|
||||
--set quantization_config.quant_method=compressed-tensors \
|
||||
--draft-model /srv/models/hf/google/gemma-4-31B-it-assistant
|
||||
build/bin/rad-convert /srv/models/hf/z-lab/Qwen3.8-27B-PARO -o qwen3.8-27b-paro-int4.rad \
|
||||
--recipe data/recipes/q38-27b-paro-mxfp4-df2.recipe \
|
||||
--draft-model /srv/models/hf/z-lab/Qwen3.8-27B-DFlash2
|
||||
```
|
||||
|
||||
With Docker, use `docker run --rm -v /srv/models:/models --entrypoint rad-convert stilldeadcode/radiance ...`.
|
||||
In the image the recipes are in `/opt/radiance/share/radiance/recipes/`. A checkpoint served at its
|
||||
own precision needs no container: `radiance --model /srv/models/hf/Qwen/Qwen3.8-27B-FP8`. A release
|
||||
someone else quantised is read as it ships when the engine serves its form (block-scaled FP8,
|
||||
Quark's MXFP4) and converted from its exact dequantisation when it does not: compressed-tensors'
|
||||
NVFP4 to the MXFP4 kernels, AutoRound and GPTQ int4 to int8. [docs/GUIDE.md](docs/GUIDE.md) names
|
||||
the recipes of record with their `rad-convert` commands.
|
||||
|
||||
## Test
|
||||
|
||||
```sh
|
||||
ctest --test-dir build -L fast -j8 # the inner loop, under 15 s; build.sh runs it
|
||||
ctest --test-dir build -LE 'gpu|oot' -j8 # everything that runs without a card (about 5 minutes)
|
||||
ctest --test-dir build -L gpu # the card tests; they need the cards to themselves
|
||||
ctest --test-dir build -L oot # rebuilds every bundled plugin out of tree against an install
|
||||
```
|
||||
|
||||
`CMakePresets.json` names the same runs (`ctest --preset fast`, `host`, `gpu`, `full`, `asan`), and
|
||||
[`docs/GUIDE.md`](docs/GUIDE.md) §1.3 describes the tiers and the test binaries' options.
|
||||
|
||||
## Documentation
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| [`docs/GUIDE.md`](docs/GUIDE.md) | installing, converting, serving, the HTTP API, operating a server |
|
||||
| [`docs/TOOLS.md`](docs/TOOLS.md) | every flag of every tool, and the recipe syntax |
|
||||
| [`docs/DOCKER.md`](docs/DOCKER.md) | the image and the compose files |
|
||||
| [`docs/PLUGIN.md`](docs/PLUGIN.md) | writing a kernel library, architecture or quantiser plugin, including one for another AMD card |
|
||||
| [`docs/ARCHITECTURES.md`](docs/ARCHITECTURES.md) | the supported model families and their geometry |
|
||||
| [`docs/TP3.md`](docs/TP3.md) | any world size: the attention world and uneven delta-net heads; three ranks |
|
||||
| [`docs/OPS.md`](docs/OPS.md), [`docs/KERNELS.md`](docs/KERNELS.md) | the op vocabulary, and what `rad-kbench` last measured |
|
||||
| [`spec.md`](spec.md) | the design |
|
||||
|
||||
## License
|
||||
|
||||
[Apache-2.0](LICENSE), copyright Deadcode and the radiance contributors. Keep [`NOTICE`](NOTICE)
|
||||
with any copy or derivative. It credits the authors and lists the MIT-licensed code the tree
|
||||
includes. The model weights are not covered: each keeps the license of the model it was converted
|
||||
from. The Docker image also holds third-party libraries under their own licenses, GPL and LGPL
|
||||
among them; `/usr/share/doc/THIRD-PARTY` in the image lists each one with its version and source.
|
||||
+534
@@ -0,0 +1,534 @@
|
||||
/* rad_abi.h -- the plugin ABI. This file and rad_types.h are the contract between the engine and
|
||||
* an .so it loads. The interface is plain C: C++ across an .so boundary invites ABI mismatches,
|
||||
* and this is the boundary where users substitute their own builds. See spec.md §2.
|
||||
*/
|
||||
#ifndef RAD_ABI_H
|
||||
#define RAD_ABI_H
|
||||
|
||||
#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, and a plugin that does not report exactly this version is refused at
|
||||
* load with both versions printed. A new optional export (e.g. rad_plugin_reference) is not a
|
||||
* change of shape: a plugin without it gets the default. */
|
||||
#define RAD_ABI_VERSION 17u
|
||||
|
||||
/* ================================================================== plugin identity */
|
||||
/* One value per plugin, not flags (QUANT is 3). RAD_PLUGIN_QUANT is a quantiser plugin:
|
||||
* rad_quant.h is its whole contract. */
|
||||
enum { RAD_PLUGIN_KERNEL = 1, RAD_PLUGIN_ARCH = 2, RAD_PLUGIN_QUANT = 3 };
|
||||
|
||||
typedef struct RadPluginInfo {
|
||||
uint32_t kind; /* one of RAD_PLUGIN_KERNEL, _ARCH, _QUANT */
|
||||
const char* name; /* "libr4d", "libref", "qwen3_dense_bf16" */
|
||||
const char* version;
|
||||
const char* description;
|
||||
/* The devices this build can run on, spelled as RadDeviceProps::arch. "host" for a library of
|
||||
* CPU kernels, which run anywhere; "" for a plugin that claims nothing. A binary built for
|
||||
* several architectures lists them separated by spaces or commas. */
|
||||
const char* build_target;
|
||||
} RadPluginInfo;
|
||||
|
||||
/* 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 constraints. Declare resolves both domains where both exist, so the core can
|
||||
* change execution site at runtime without re-resolving (spec §2.1). */
|
||||
enum { RAD_DOMAIN_DEVICE = 0, RAD_DOMAIN_HOST = 1, RAD_N_DOMAINS = 2 };
|
||||
|
||||
/* ================================================================== kernel arguments */
|
||||
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. Inline definitions, because a plugin links only the ABI headers and
|
||||
* nothing of the engine's. See the note in rad_types.h. */
|
||||
static inline int rad_args_geti(const RadArgs* a, const char* key, long long* out) {
|
||||
if (!a || !key) return 0;
|
||||
for (int i = 0; i < a->n_p; ++i)
|
||||
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 hold per-instance state that is set up once rather than per launch: libr4d's
|
||||
* all-reduce exchanges peer signal buffers and IPC handles across ranks before the first call,
|
||||
* and a kernel that JITs or loads a config table does it here, off the hot path.
|
||||
*
|
||||
* init is called once per resolved instance (one op, one band, one domain), after selection and
|
||||
* before load, with the frozen geometry. The pointer it returns (or null) is handed back in
|
||||
* RadArgs.instance. A negative status aborts startup. */
|
||||
typedef int (*RadInitFn) (const RadParam* p, int n_p, int rank, int world_size,
|
||||
void** out_instance);
|
||||
typedef void (*RadFiniFn) (void* instance);
|
||||
|
||||
/* The launch. Must not allocate and must not synchronise. Returns RAD_OK or negative; a negative
|
||||
* return aborts the step and fails its requests, naming the kernel and the geometry. A launch
|
||||
* handed `link_gate` may return RAD_LINK_ENDED instead of RAD_OK (rad_kernel_collective). */
|
||||
typedef int (*RadLaunchFn) (const RadArgs* a, RadStream stream);
|
||||
|
||||
/* 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 the weight's encoding. spec.md §4.1, §4.3.
|
||||
*
|
||||
* A container holds each weight's encoding (codes, scales and zero points as canonical planes,
|
||||
* rad_encoding.h) and nothing shaped for a kernel. The kernel that reads a weight describes the
|
||||
* form it wants here, and the loader converts when the model loads. The conversion is lossless: a
|
||||
* relayout moves bits and derives only what a reader of the planes could derive (a fragment order,
|
||||
* a scale repeated into a row's tail, a reference exponent that is a row's maximum). Choosing
|
||||
* numbers is the quantiser's job (rad_quant.h); a kernel doing it here would make the served
|
||||
* numbers depend on which library loaded the container. So a kernel library may change any layout
|
||||
* without containers being converted again. */
|
||||
typedef struct RadLayout {
|
||||
const char* tag; /* stable name of the arrangement, for messages and for checking
|
||||
* that every kernel reading one weight wants the same bytes */
|
||||
uint32_t dtype; /* the stored dtype, possibly a plugin-private one */
|
||||
uint32_t rank;
|
||||
int64_t shape[RAD_MAX_RANK]; /* the stored shape, which may differ from the logical one */
|
||||
int64_t 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 RadWeightDecl::planes order. Each plane is this rank's slice, dense: rank
|
||||
* 2, [rows, cols] in the plane's own elements, every row starting on a byte and
|
||||
* rad_dtype_bytes(dtype, cols) long. Here the planes carry their geometry and a null `data`.
|
||||
*
|
||||
* RAD_OK `out` describes the stored form, and `relayout` will produce it.
|
||||
* RAD_E_UNSUPPORTED stored as is: the one selected plane, bytes unchanged. This is most
|
||||
* weights, and what a kernel with no hook gets. Only such a weight can be
|
||||
* read where it lies in the container (the file and mapped tiers).
|
||||
* RAD_E_DTYPE the kernel does not read this encoding (an fp8 GEMM handed int4, a rotated
|
||||
* weight to a kernel that does not rotate its activation). A declare-time
|
||||
* error naming the weight, the encoding and the kernel.
|
||||
* RAD_E_SHAPE the selected planes, or their extents, are not what the kernel reads. */
|
||||
typedef int (*RadLayoutFn)(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
|
||||
const int* sel, const RadTensor* planes, int n_planes,
|
||||
RadLayout* out);
|
||||
|
||||
/* Write the stored form `layout` described into `dst`, `dst_bytes` long, from the planes, which
|
||||
* now carry their bytes. Pure host code, run by the loader on a pool behind the container read,
|
||||
* so it has to keep pace with the disk. */
|
||||
typedef int (*RadRelayoutFn)(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
|
||||
const int* sel, const RadTensor* planes, int n_planes, void* dst,
|
||||
int64_t dst_bytes);
|
||||
|
||||
/* The inverse: recover the planes from a stored form. `planes` arrive with their geometry and a
|
||||
* buffer each.
|
||||
*
|
||||
* A tool checking a kernel against the oracle holds the stored bytes, but libref reads canonical
|
||||
* planes; given the stored bytes it answers a permuted question, and the comparison reports an
|
||||
* error the size of two unrelated tensors against a correct kernel. Only the plugin knows its
|
||||
* permutation. A kernel that relayouts without an inverse is not at fault, only not checkable
|
||||
* against a dense oracle, and the tools report it by name. */
|
||||
typedef int (*RadUnrelayoutFn)(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
|
||||
const int* sel, const void* src, int64_t src_bytes,
|
||||
const RadTensor* planes, int n_planes);
|
||||
|
||||
/* ================================================================== operand description */
|
||||
/* How big operand i of an op is, and what values it may hold.
|
||||
*
|
||||
* A schema names operands and their roles but not their extents, which are in general not
|
||||
* derivable from the parameters (the run phase supplies them at issue). A tool that calls an op
|
||||
* cold, such as a correctness check or a benchmark, asks the kernel through this hook instead of
|
||||
* keeping its own table of ops.
|
||||
*
|
||||
* The fill domain matters as much as the shape. A gated-delta-net `g` is an intra-chunk cumulative
|
||||
* sum of log-decays: non-increasing and never positive, since each decay e^{g_i - g_j} with j <= i
|
||||
* is <= 1 only because g is monotone. Fed normals, the oracle overflows to 2e38 and the comparison
|
||||
* measures the test rather than the kernel. The same holds for a sigmoid gate, a lower-triangular
|
||||
* factor and every index operand: a KV slot indexes n_blocks * block_size positions and a
|
||||
* block-table entry n_blocks, and a draw outside that range tests out-of-range handling instead. */
|
||||
enum {
|
||||
RAD_FILL_NORMAL = 0, /* standard normals -- the default for a float operand */
|
||||
RAD_FILL_SIGMOID = 1, /* (0, 1): a gate */
|
||||
RAD_FILL_GATE_CUMSUM = 2, /* non-increasing and <= 0, reset every `fill_chunk` rows */
|
||||
RAD_FILL_TRI_LOWER = 3, /* zero above the diagonal within a `fill_chunk` block */
|
||||
RAD_FILL_INDEX = 4, /* integers; see idx_max / idx_const / the IDX flags */
|
||||
/* Unit L2 norm along the last dimension. The gated-delta-net key is normalised by qk_norm
|
||||
* before the solve, which inverts I + tril(beta k k^T, -1). With unit normals over a 128-wide
|
||||
* head the off-diagonals are ~100x too large, the matrix is ill-conditioned, and two
|
||||
* summation orders disagree by its condition number. Like SIGMOID and GATE_CUMSUM, this puts
|
||||
* the operand in the domain the op is actually given. */
|
||||
RAD_FILL_UNIT_ROW = 5,
|
||||
/* The samplers' `params` plane: [rows, 24] 32-bit words, each row a RadSampleParams
|
||||
* (rad_sample.h) as a request sets it, its flags agreeing with its fields. Drawn as numbers,
|
||||
* the integer fields and `flags` are bit patterns (a window is all or nothing, a mask row is
|
||||
* never in range, each flag is a coin toss) and XTC's threshold is past any probability, so
|
||||
* the mask and XTC stages do nothing and the others act on a random part of the rows.
|
||||
* Row 0 switches every stage on; every other row switches each stage on or leaves it at its
|
||||
* identity at random, and a minority is greedy. `fill_chunk` is the width of the op's history
|
||||
* plane (0 when it has none: the window is then empty) and `idx_max` the row count of its
|
||||
* bitmask plane (0 when it has none: `mask_row` is then -1). A tool that does not know the
|
||||
* value draws normals. */
|
||||
RAD_FILL_SAMPLE_PARAMS = 6,
|
||||
};
|
||||
|
||||
enum {
|
||||
/* An optional operand this geometry does not pass. One entry per schema operand is still
|
||||
* emitted, since that count catches a hook that drifted from its schema; a null
|
||||
* RadTensor.data marks the absence. */
|
||||
RAD_OPD_F_ABSENT = 1u << 0,
|
||||
/* A scatter destination: no value may repeat. Two tokens on one slot make the store a race
|
||||
* that two implementations resolve differently. A read-side index (a gather row, a
|
||||
* block-table entry) may repeat. */
|
||||
RAD_OPD_F_IDX_UNIQUE = 1u << 1,
|
||||
/* Cumulative sequence lengths, [0, ..., T]: the batch's shape, not a draw. */
|
||||
RAD_OPD_F_IDX_CU = 1u << 2,
|
||||
/* A routing histogram's offsets, [0, ..., idx_max - 1]: non-decreasing, first 0, last the row
|
||||
* count, each bucket a run of random length (moe_scatter's `expert_offset`). A uniform draw is
|
||||
* a malformed histogram that two correct implementations may read differently. Additive:
|
||||
* RAD_ABI_VERSION does not move, and a tool that does not know the flag draws as before. */
|
||||
RAD_OPD_F_IDX_PREFIX = 1u << 3,
|
||||
/* A token history, [rows, width] ids in [0, idx_max): each row repeats itself as generated
|
||||
* text does, drawing on a few ids spread over the range and copying runs of its own earlier
|
||||
* tokens. A uniform draw over a vocabulary never repeats, so a frequency penalty never counts
|
||||
* past one and DRY (which penalises the token that would extend a repeated suffix) never
|
||||
* finds a repeat. Additive, as IDX_PREFIX: a tool that does not know the flag draws uniform
|
||||
* ids. */
|
||||
RAD_OPD_F_IDX_HISTORY = 1u << 4,
|
||||
};
|
||||
|
||||
typedef struct RadOpdDesc {
|
||||
uint32_t dtype;
|
||||
uint32_t rank;
|
||||
int64_t shape[RAD_MAX_RANK];
|
||||
|
||||
uint32_t fill; /* RAD_FILL_* */
|
||||
/* The reset width for GATE_CUMSUM and TRI_LOWER; the history plane's width for
|
||||
* SAMPLE_PARAMS. */
|
||||
int64_t fill_chunk;
|
||||
|
||||
/* RAD_FILL_INDEX only, except that SAMPLE_PARAMS reads `idx_max` as its bitmask plane's row
|
||||
* count. `idx_max` is the exclusive upper bound of the draw; 0 means the leading extent of the
|
||||
* previous operand, the common case for a gather. `idx_const` >= 0 sets every element to that
|
||||
* value instead of drawing. `seqused` needs it: a random context length shorter than the query
|
||||
* makes causal attention read a prefix that does not exist. */
|
||||
int64_t idx_max;
|
||||
int64_t idx_const; /* -1 to draw */
|
||||
|
||||
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. Returns RAD_OK, or RAD_E_UNSUPPORTED when
|
||||
* this geometry lacks what the description needs; a caller skips and counts that instead of
|
||||
* guessing an extent.
|
||||
*
|
||||
* Pure host code, no device memory, no side effects: it is called before anything is allocated. */
|
||||
typedef int (*RadShapeFn)(const RadParam* p, int n_p, int operand, RadOpdDesc* out);
|
||||
|
||||
|
||||
/* ================================================================== tunable instantiation */
|
||||
/* A kernel is a family: tile sizes, split counts, waves per block. Which member is fastest
|
||||
* depends on the shape and the machine and must be measured there (spec §15). A library declares
|
||||
* the axes here and the core takes their cross product. Axes rather than a list of named
|
||||
* combinations, because a hand-enumerated list has holes (a shape with 40 rows of work runs a
|
||||
* 64-row tile), and because it keeps the tuning policy out of the launch adapter, where an
|
||||
* out-of-tree author could not write it.
|
||||
*
|
||||
* The chosen values arrive as ordinary parameters appended to RadArgs::p, with no variant index:
|
||||
* the kernel reads `sk` with the same rad_args_geti() it reads `M` with. */
|
||||
typedef struct RadTunable {
|
||||
const char* key; /* the kernel's own name for the axis: "sk", "bm", "npw" */
|
||||
const int64_t* values; /* legal values, ascending; the core tries exactly these */
|
||||
int n_values;
|
||||
/* The value used when this machine has no measurement for this instantiation (a fresh
|
||||
* install, an untuned shape, a cache from another card). There is no fallback beneath it, so
|
||||
* it must be launchable: the loader checks it appears in `values` and refuses the plugin by
|
||||
* name if not. */
|
||||
int64_t deflt;
|
||||
const char* doc; /* what the axis does, for the tuner's report */
|
||||
} RadTunable;
|
||||
|
||||
/* Whether a combination is legal at this geometry. Cross-axis rules live here because independent
|
||||
* axis lists cannot express them: libr4d's skinny GEMM needs `wv * sk * 32` inside the block bound
|
||||
* and `K % (sk * unit) == 0`.
|
||||
*
|
||||
* `p` is the resolved geometry, `choice` the candidate as key/value parameters. Pure host code,
|
||||
* called once per candidate before anything is allocated.
|
||||
*
|
||||
* Returns 1 for legal and 0 for skip, which is not an error: a kernel may serve a subset of its
|
||||
* cross product, and the tuner reports the candidate as skipped. Null means every combination is
|
||||
* legal. */
|
||||
typedef int (*RadTuneValidFn)(const RadParam* p, int n_p, const RadParam* choice, int n_choice);
|
||||
/* ================================================================== op schemas */
|
||||
/* A parameter is supplied by the caller (REQUIRED), may be supplied (OPTIONAL), or is supplied by
|
||||
* the kernel (DERIVED).
|
||||
*
|
||||
* DERIVED breaks a circularity. The paged block size comes from the resolved attention kernel, not
|
||||
* a core constant (spec §7.2; libr4d is compiled for 16). But a constraint whose key the geometry
|
||||
* does not carry does not hold (which is also why libr4d's two-shot all-reduce rows must precede
|
||||
* the one-shot ones), so a kernel constrained to block_size == 16 could never be selected by a
|
||||
* query that omits block_size.
|
||||
*
|
||||
* So constraints on a DERIVED parameter are skipped during matching, and the winning kernel's
|
||||
* RAD_C_EQ value for that key is written into the resolved geometry. A caller that supplies one
|
||||
* pins it and it matches normally, so a forced block size is refused by name rather than silently
|
||||
* substituted. A kernel with no EQ on a derived key leaves it unset, and rad_kv_block_size()
|
||||
* reports that rather than returning zero. */
|
||||
enum { RAD_OPTIONAL = 0, RAD_REQUIRED = 1, RAD_DERIVED = 2 };
|
||||
|
||||
/* What a parameter means to the core. The core carries almost every parameter opaquely, which is
|
||||
* what lets a third party add an op. The exception is the sequence chunk: a linear-state scan is
|
||||
* compiled for one tile length, and the scheduler must cut its steps on a multiple of it or a
|
||||
* chunk straddles a sequence boundary. The schema names that role so the core does not have to
|
||||
* find the parameter by guessing its spelling. */
|
||||
/* RAD_PROLE_CAPACITY marks a count the kernel is handed as a bound and never writes past its
|
||||
* operands for: it launches, loops and writes by the extents of the tensors it is given. That lets
|
||||
* the activation arena be declared again at a smaller step (RadBuildCtx::shape_probe) while the
|
||||
* kernel keeps the geometry it was selected with, including the real declare's value here. It is
|
||||
* the kernel's claim to make; without it, a fixed parameter that differs between the two declares
|
||||
* refuses the smaller size. */
|
||||
enum { RAD_PROLE_NONE = 0, RAD_PROLE_SEQ_CHUNK = 1, RAD_PROLE_CAPACITY = 2 };
|
||||
|
||||
typedef struct RadParamSpec {
|
||||
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 only which operands are weights (issue resolves
|
||||
* a handle and waits on the mover) and which are written (the buffer planner computes liveness). */
|
||||
/* RAD_OPD_WTAB is a weight operand whose issue names a run of weights (a MoE layer's experts);
|
||||
* the kernel is handed a device array of pointers. It is a separate role, not a flag on
|
||||
* RAD_OPD_WEIGHT, so a tool reading the schema knows the operand is not one plane it can describe
|
||||
* with one shape: see RAD_WTAB in rad_runtime.h. */
|
||||
enum { RAD_OPD_IN = 0, RAD_OPD_OUT = 1, RAD_OPD_INOUT = 2, RAD_OPD_WEIGHT = 3,
|
||||
RAD_OPD_WTAB = 4 };
|
||||
|
||||
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
|
||||
*
|
||||
* Which chain of conventional ops a kernel computes.
|
||||
*
|
||||
* This is a declaration, not a rewriter. spec.md §2.3 rules out a fusion rewriter, and the
|
||||
* declare phase keeps nothing one could work on: `Program` holds no operand edges, and the Builder
|
||||
* collapses each buffer's use-set to a `first_def`/`last_use` pair with reads and writes merged.
|
||||
* "Op A's output is op B's only input" is not recoverable from that, which is also why
|
||||
* `--debug-graph` prints no edge it cannot prove. Fusion stays a selection: the architecture asks
|
||||
* for the fused op and emits the sequence when nothing serves it (rad_op_resolved in
|
||||
* rad_builder.h is the idiom for a banded or optional fusion).
|
||||
*
|
||||
* The declaration makes the equivalence machine-readable, which gives:
|
||||
* - an oracle: a fused kernel with no libref counterpart is checked against its chain run on the
|
||||
* same plugin's unfused rows, and the answer should be byte-identical;
|
||||
* - an advisory in --debug-graph: these declared ops form a chain some kernel can run in one
|
||||
* launch, and why it did not fire;
|
||||
* - the per-library fusion-claim count in rad-kbench's report.
|
||||
*
|
||||
* It is a hook rather than a table because a step's geometry is not always derivable from the
|
||||
* fused op's: `qk_norm_rope_gate` replaces an `rmsnorm` at M = T * n_head, a product that is not
|
||||
* in its parameter list.
|
||||
*
|
||||
* Operand wiring: every operand of every step is either an operand of the fused kernel or a
|
||||
* temporary passed between steps. A temporary needs no description here; the step op's own
|
||||
* `opd_shape` sizes and types it. Often none is needed: the fp8 folds still write their
|
||||
* intermediate when `out_bf16` is passed, so the fused and unfused forms leave the same buffers. */
|
||||
enum {
|
||||
RAD_FUSE_NONE = -1, /* this step does not pass that optional operand */
|
||||
};
|
||||
/* 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 (as with RadShapeFn). */
|
||||
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,
|
||||
* which may differ with the geometry (an `rmsnorm_quant_fp8` with a residual
|
||||
* replaces `rmsnorm_add`, without one `rmsnorm`).
|
||||
* RAD_E_UNSUPPORTED this geometry or variant has no unfused equivalent in the vocabulary.
|
||||
*
|
||||
* A chain must be exact. A kernel that is merely close to a sequence publishes no hook, because
|
||||
* callers substitute one for the other and compare the bytes. */
|
||||
/* `present` has bit i set when operand i of the fused op is passed. The chain can depend on an
|
||||
* operand, not only on a parameter: `rmsnorm_quant_fp8` replaces `add` -> `rmsnorm` ->
|
||||
* `quant_act_fp8` given a residual and `rmsnorm` -> `quant_act_fp8` without. Inferring presence
|
||||
* from the plugin's own RadShapeFn is right for a checker calling the kernel cold but wrong for a
|
||||
* caller holding a real issue, such as the graph dump. `RAD_FUSE_NONE` cannot express it, since
|
||||
* the operands that vary are the step's required ones.
|
||||
*
|
||||
* RAD_FUSE_PRESENT_ALL means the caller does not know: answer for every operand your RadShapeFn
|
||||
* says exists. */
|
||||
#define RAD_FUSE_PRESENT_ALL ((uint64_t)~0ull)
|
||||
#define RAD_FUSE_HAS(mask, i) (((mask) >> (i)) & 1ull)
|
||||
|
||||
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 (the common case): the core appends no
|
||||
* choices and the kernel reads no tuned key. See RadTunable. */
|
||||
const RadTunable* tunables; int n_tunables;
|
||||
RadTuneValidFn tune_valid;
|
||||
|
||||
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 tools
|
||||
* that need a buffer for it skip it by name. libref supplies it for the whole conventional
|
||||
* vocabulary, so an op in docs/OPS.md is describable even when the kernel under test is not. */
|
||||
RadShapeFn opd_shape;
|
||||
/* The inverse of `relayout`, for a tool holding the stored bytes rather than the planes. Null
|
||||
* means the stored form cannot be read back, so a dense oracle has nothing to compare
|
||||
* against: a named skip, not a failure. */
|
||||
RadUnrelayoutFn unrelayout;
|
||||
/* The chain of conventional ops this kernel computes in one launch, or null if it is not a
|
||||
* fusion. Non-null also counts in rad-kbench's fusion-claim column.
|
||||
*
|
||||
* Keep this field last. Kernel tables are positional aggregate initialisers
|
||||
* (`{..., nullptr, nullptr, r4d_rad_embed_lookup, nullptr, ...}`), so a field inserted
|
||||
* anywhere else shifts every later initialiser, and since `nullptr` converts to any function
|
||||
* pointer type, part of that shift would still compile. Append new fields after this one. */
|
||||
RadFuseFn replaces;
|
||||
} RadKernelInfo;
|
||||
|
||||
/* ================================================================== kernel plugin exports */
|
||||
/* Every kernel plugin exports the whole set. The first plugin in hierarchy order to declare an op
|
||||
* fixes its schema; a later plugin declaring the same op name with a different schema is refused
|
||||
* at load with both plugins named. Arguments are positional, so disagreeing schemas would make
|
||||
* the same call mean different things depending on which plugin won selection, silently
|
||||
* (spec §2.3). */
|
||||
int rad_kernel_schema_count(void);
|
||||
const RadOpSchema* rad_kernel_schema_at(int i);
|
||||
int rad_kernel_count(void);
|
||||
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 exist so a plugin can
|
||||
* declare them with the right signature. The loader resolves those exact names, so a plugin that
|
||||
* spells them differently is silently never initialised.
|
||||
*
|
||||
* `rad_plugin_open` returning RAD_E_UNSUPPORTED declines this machine: the plugin is unloaded and
|
||||
* the rest of the installation carries on, so one installation can ship libraries for several
|
||||
* cards. Any other negative status refuses the plugin as an error. A kernel library need not
|
||||
* decline a card its device code was not built for: the loader reads that from the code objects
|
||||
* and leaves those device kernels out itself. */
|
||||
typedef int (*RadPluginOpenFn) (void);
|
||||
typedef void (*RadPluginCloseFn)(void);
|
||||
|
||||
/* Optional promise about kernel `i` of rad_kernel_at: nonzero means every launch reads and writes
|
||||
* only its operands and the scratch it was handed (no allocation it keeps, no counter kept between
|
||||
* launches), so two launches may run at once on one device when their operands and scratch do not
|
||||
* overlap. The engine then lets such a launch start before independent earlier launches on its
|
||||
* queue finish. Without the symbol, or with 0, every launch is ordered behind everything before
|
||||
* it, which is always correct. Symbol name: `rad_kernel_concurrent`. */
|
||||
typedef int (*RadKernelConcurrentFn)(int i);
|
||||
|
||||
/* Optional promise about kernel `i` of rad_kernel_at: nonzero means it is a collective. Its
|
||||
* launches exchange data with the other ranks' cards, so the interconnect carries their bytes
|
||||
* while they run and the step waits on it. The engine keeps its own bulk traffic on those links
|
||||
* (weights streamed to the card during compute) out of the way for that time. Without the symbol,
|
||||
* or with 0, only the conventional `all_reduce` op is treated as a collective. Symbol name:
|
||||
* `rad_kernel_collective`.
|
||||
*
|
||||
* 2 promises more: each launch ends the link hold itself as soon as the last byte the other ranks
|
||||
* send this card for it has landed, so a kernel that reduces after the exchange frees the link for
|
||||
* the rest of its run. The engine then passes each launch it holds the link for the parameter
|
||||
* `link_gate`, the address of a 64-bit word the kernel reaches at system scope; a launch without
|
||||
* it holds nothing. The kernel reads the word on the device as it starts (not on the host in the
|
||||
* launch call, where the hold is not yet in effect) and, once those bytes have landed, decrements
|
||||
* it with a system-scope atomic if it was odd; an even word it leaves alone. A launch that
|
||||
* decremented returns RAD_LINK_ENDED. Any other success returns RAD_OK and the engine ends the
|
||||
* hold behind the launch, so a path that ignores the word is always safe. */
|
||||
typedef int (*RadKernelCollectiveFn)(int i);
|
||||
#define RAD_LINK_ENDED 1
|
||||
|
||||
/* Optional: nonzero declares this kernel library a reference implementation, written to be
|
||||
* plainly correct rather than fast. For any library that says so, whatever its name:
|
||||
* - the loader ranks it below every unnamed kernel library, because a reference matches every
|
||||
* op it declares and would otherwise win over the library serving the card (naming it in
|
||||
* --kernels still places it where named, and a --kernels list that omits it leaves it out);
|
||||
* - the engine refuses to serve a model with an op only a reference library implements, unless
|
||||
* given --debug-accept-reference-kernels;
|
||||
* - rad-kbench checks every other library against it.
|
||||
* Without the symbol, or with 0, it is an ordinary library. Symbol name: `rad_plugin_reference`. */
|
||||
typedef int (*RadPluginReferenceFn)(void);
|
||||
|
||||
#ifdef __cplusplus
|
||||
} /* extern "C" */
|
||||
#endif
|
||||
#endif /* RAD_ABI_H */
|
||||
@@ -0,0 +1,912 @@
|
||||
/* rad_builder.h -- the declare phase. An architecture plugin states everything it will do before
|
||||
* doing any of it: every weight, every buffer, every op, in order. See spec.md §3.1.
|
||||
*
|
||||
* After declare, the whole model is known statically (every op, the kernel serving it, the weights
|
||||
* it touches, and the order), and the rest of the engine relies on that.
|
||||
*/
|
||||
#ifndef RAD_BUILDER_H
|
||||
#define RAD_BUILDER_H
|
||||
|
||||
#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;
|
||||
/* Always 1. Rotary scaling is a type with parameters (linear, YaRN, llama3, longrope) carried
|
||||
* in the free-form keys below (rope_parameters.* / rope_scaling.*, with text_config.* and
|
||||
* draft.* forms); arch/common/rad_arch.h's yarn_from reads them and refuses unknown schemes by
|
||||
* name. A bare factor here would read every scheme as a linear position divide. */
|
||||
float rope_scale;
|
||||
|
||||
/* Free-form key/value from the container header, for anything the struct above does not
|
||||
* 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 (the zero-initialised default) is the exact all-reduce. Nonzero
|
||||
* accepts a lossy wire: at two ranks libr4d serves a Walsh-Hadamard-rotated 6-bit payload (6
|
||||
* bits an element plus a bf16 scale per group of 64, so a prefill chunk's message shrinks
|
||||
* 2.4x), at three and four ranks a tiered int8 two-shot. The plugin inverts it into
|
||||
* `all_reduce`'s `exact` parameter.
|
||||
* The polarity makes a context that forgets the field exact, not lossy (spec §9). */
|
||||
int tp_wire_lossy;
|
||||
|
||||
/* The all-reduce message size, in bytes, from which the lossy wire is used. Below it the
|
||||
* plugin must use the exact kernel even when `tp_wire_lossy` is set: compression pays only
|
||||
* once the transfer is bandwidth-bound, and a decode step's few residual rows cost more to
|
||||
* rotate/pack/unpack than they save. 0 means the plugin's default, 128 KiB. */
|
||||
int64_t tp_wire_min_bytes;
|
||||
|
||||
|
||||
/* The KV cache dtype, a deployment choice rather than a property of the checkpoint: fp8
|
||||
* weights may want a bf16 cache and vice versa.
|
||||
*
|
||||
* RAD_DT_INVALID (the zero-initialised default) means the plugin's default, bf16 for every
|
||||
* architecture in this tree. RAD_F8E4M3 is the only other implemented value: the fp8kv
|
||||
* attention family is band-gated on it, and the store side writes E4M3 with per-(sequence,
|
||||
* head) descales.
|
||||
*
|
||||
* An ABI field rather than an environment variable because it changes what the model
|
||||
* computes, so it must have one visible answer: --kv-cache-dtype. */
|
||||
int kv_dtype; /* RAD_DT_INVALID = the plugin's default (bf16); or RAD_F8E4M3 */
|
||||
int is_draft; /* this builder scope is a drafter (spec §10) */
|
||||
const char* scope; /* "", "draft", "vision", "audio" -- prefixes declared names */
|
||||
|
||||
/* Nonzero: a declare that only sizes the activations, at a `max_tok` smaller than the
|
||||
* deployment's. The core runs one per level of the activation arena it lends out; the result
|
||||
* gives every buffer's size when no step carries more than `max_tok` tokens, and the arena
|
||||
* above that is lent to the expert slab while steps are that small.
|
||||
*
|
||||
* Invariant: the plugin must not touch its own state while this is set. Its step function
|
||||
* reads state the real declare wrote at the real `max_tok`; overwriting it would run every
|
||||
* later step against the smaller configuration. Declare into scratch storage instead: nothing
|
||||
* a sizing declare produces is issued, and its op handles are the real declare's.
|
||||
*
|
||||
* Only asked of a plugin that set RadArchProbe::shape_probe_ok. Trailing and zero-defaulted,
|
||||
* so a plugin built against the older struct is unchanged. */
|
||||
int shape_probe;
|
||||
|
||||
/* The most patches one encoder pass may carry; 0 means the deployment serves no media, the
|
||||
* plugin declares no encoder, and a tower the container carries stays off the card. It is the
|
||||
* encoder's `max_tok` (its activations are sized against it) and bounds the largest single
|
||||
* image accepted, since one image is one attention segment and is never split across passes. */
|
||||
int64_t max_enc_patches;
|
||||
|
||||
/* The most logits rows one step may name, when that exceeds the plugin's own rule of one per
|
||||
* sequence (1 + max_spec at a speculative step); 0 is the rule. The engine's KL mode sets it to
|
||||
* a step's tokens plus a row per sequence, since it reads a full-vocabulary row at every prompt
|
||||
* position; the logits buffer and the lm_head's row range are sized from it. The engine checks
|
||||
* the declared logits buffer and refuses the mode when it is shorter, so a plugin that ignores
|
||||
* the field is refused rather than overrun.
|
||||
*
|
||||
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
|
||||
int64_t max_out_rows;
|
||||
|
||||
/* The most frames one audio encoder pass may carry; 0 means no audio and no audio encoder.
|
||||
* It is the audio encoder's `max_tok`, as max_enc_patches is a vision tower's, and bounds the
|
||||
* longest clip, since one clip is one segment. The engine takes it from
|
||||
* RadArchProbe::audio_frames.
|
||||
*
|
||||
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
|
||||
int64_t max_audio_frames;
|
||||
|
||||
/* The most tokens a step of more than one sequence may carry, when that is less than
|
||||
* max_tok; 0 means max_tok. Under --prefill-span a prefill alone in its step may take max_tok
|
||||
* and every other step is planned at a shared budget, so a step wider than this is one
|
||||
* sequence. A plugin may size a buffer holding a row per query of every sequence in a step at
|
||||
* this, and serve a wider step a window at a time.
|
||||
*
|
||||
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
|
||||
int64_t max_mixed_tok;
|
||||
} RadBuildCtx;
|
||||
|
||||
/* ================================================================== weights */
|
||||
/* Access class, declared per weight because only the architecture plugin knows it. It tells the
|
||||
* placement planner whether prefetch can be exact (spec §5.2). */
|
||||
enum {
|
||||
RAD_ACCESS_PER_TOKEN = 0, /* read every forward pass -- dense weights */
|
||||
RAD_ACCESS_PER_REQUEST = 1, /* read once per request -- an encoder tower, with an image */
|
||||
RAD_ACCESS_CONDITIONAL = 2, /* read only if selected -- routed experts */
|
||||
RAD_ACCESS_RARE = 3, /* may not be read at all in a given deployment */
|
||||
RAD_ACCESS_VOCAB = 4 /* lm_head and the embedding table: read every token, very
|
||||
* large, and one is a gather rather than a GEMM. Neither
|
||||
* PER_TOKEN's prefetch nor CONDITIONAL's prediction fits it
|
||||
* (spec §5.2). */
|
||||
};
|
||||
|
||||
/* How a weight is split across tensor-parallel ranks. The plugin says; the core does not infer. */
|
||||
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.2). Layer grouping makes layer offload a contiguous
|
||||
* run rather than a scatter. */
|
||||
typedef struct RadWeightGroup {
|
||||
int32_t layer; /* -1 for a model-level weight */
|
||||
int32_t expert; /* -1 for a non-expert weight */
|
||||
int32_t slot; /* free index within the group, e.g. gate=0 up=1 down=2 */
|
||||
} RadWeightGroup;
|
||||
|
||||
/* Note: these are C compound literals, which C++ accepts only as a GNU extension. A C++ plugin
|
||||
* should use the equivalent grp_layer()/grp_expert()/grp_model() inline functions in
|
||||
* `<arch/rad_arch.h>`, as the in-tree plugins do. */
|
||||
#define rad_group_layer(l) ((RadWeightGroup){ (int32_t)(l), -1, 0 })
|
||||
#define rad_group_expert(l, e) ((RadWeightGroup){ (int32_t)(l), (int32_t)(e), 0 })
|
||||
#define rad_group_model() ((RadWeightGroup){ -1, -1, 0 })
|
||||
|
||||
/* The most projections one stored tensor may stack along dim 0. The bf16 delta net needs five
|
||||
* (q, k, v, a, b); eight leaves room without making the decl big. */
|
||||
enum { RAD_MAX_ROW_PARTS = 8 };
|
||||
|
||||
typedef struct RadWeightDecl {
|
||||
uint32_t dtype; /* what the kernel reads; the stored layout comes from the kernel */
|
||||
uint32_t rank;
|
||||
int64_t shape[RAD_MAX_RANK]; /* this rank's extent of what `planes` select (below) */
|
||||
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 concatenates
|
||||
* several projections ([gate|up], the delta net's [q|k|v]). Rows of this rank, in stored
|
||||
* order, summing to shape[0]; 0 parts means dim 0 is one projection.
|
||||
*
|
||||
* A tensor-parallel rank owns a slice of each stacked projection, not a contiguous slice of
|
||||
* the stack: rows [rank*D, (rank+1)*D) of a fused gate_up would give rank 0 the whole gate and
|
||||
* rank 1 the whole up, and the model would produce fluent wrong text (spec §9). The parts
|
||||
* cannot be inferred from the container, which holds only the fused result, and a checkpoint
|
||||
* tensor may already be a fusion the name map does not mention (in_proj_qkv is three head
|
||||
* groups in one [10240, 5120]). Only the plugin knows them. */
|
||||
int n_row_parts;
|
||||
int64_t row_parts[RAD_MAX_ROW_PARTS];
|
||||
|
||||
/* Which stored weight this is a view of, and which of its planes. spec.md §4.3.
|
||||
*
|
||||
* A container entry or checkpoint tensor is a logical weight: the planes of its encoding
|
||||
* (rad_encoding.h). A block-fp8 linear's codes and scale plane are one weight, not two. A
|
||||
* kernel takes them as whatever operands its schema has: gemm_nt_q takes codes and scales as
|
||||
* two, the fp8 lm_head one operand holding both. So a declared weight names its `source` (null
|
||||
* for the logical weight of its own name) and the `planes` it takes, by role, comma-separated:
|
||||
* "codes", "scale", "codes,scale". Null takes every plane, which for a plain weight is one.
|
||||
*
|
||||
* One declared weight is one stored buffer. Its dtype and shape describe what is selected: a
|
||||
* single plane's own dtype and extents, or for several, the codes' dtype and the logical
|
||||
* extents. A dtype other than the plane's is legal only as an exact widening (a bf16 norm read
|
||||
* as f32), which the loader performs; anything lossy is the quantiser's job, done before the
|
||||
* container is written. */
|
||||
const char* source;
|
||||
const char* planes;
|
||||
} RadWeightDecl;
|
||||
|
||||
rad_weight rad_decl_weight(RadBuilder* b, const char* name, const RadWeightDecl* d);
|
||||
|
||||
/* A stored weight's encoding, its logical extents in `shape` (RAD_MAX_RANK entries, may be null)
|
||||
* and its rank in `rank` (may be null). RAD_OK, or RAD_E_NOTFOUND when the model has no such
|
||||
* weight.
|
||||
*
|
||||
* The answer comes from whatever the model is loaded from (a container entry, a checkpoint tensor,
|
||||
* or in rad-convert the recipe that will quantise it), so a plugin chooses its ops the same way at
|
||||
* convert and at load: an fp8 GEMM for a block-fp8 weight, the rotated expert kernels for
|
||||
* `i4*bf16[1x128]/fwht128`. Ask after the weight's name map entry (rad_decl_name_map), which is how
|
||||
* a checkpoint is searched for it. A builder with no model behind it (a test, a synthetic tool)
|
||||
* answers RAD_E_NOTFOUND, and a weight declared there is read as plain in its declared dtype. */
|
||||
int rad_weight_encoding(RadBuilder* b, const char* source, RadEncoding* out, int64_t* shape,
|
||||
uint32_t* rank);
|
||||
|
||||
/* ================================================================== buffers */
|
||||
/* Activations are declared too, so the buffer plan can analyse them. Liveness is computed over the
|
||||
* declared op list, so scratch and intermediates come from one arena sized once instead of an
|
||||
* allocator called per step (spec §3.1). */
|
||||
enum {
|
||||
RAD_BUF_TRANSIENT = 0, /* liveness-analysed, may share storage with another transient */
|
||||
RAD_BUF_PERSIST = 1, /* survives across steps: a KV-adjacent scratch, a routing histogram */
|
||||
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 */
|
||||
/* The KV group a derivation is about, or 0 for the only one of its kind.
|
||||
*
|
||||
* `conv_state_index` computes a read cursor inside a rolling window, so it needs that group's
|
||||
* slot per sequence and window depth, and a model may declare several (Qwen4-Exp's PLE layer
|
||||
* has two conv states of different depths and dtypes beside the gated delta net's). 0 with
|
||||
* more than one group of the kind a derivation reads is refused: the wrong window depth gives
|
||||
* a plausible cursor and a convolution that reads history it never wrote.
|
||||
*
|
||||
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
|
||||
rad_kvgroup kv;
|
||||
} 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, pool and slot mapping in the
|
||||
* step batch. Linear-attention state is a KV group too: not paged the same way, but allocated,
|
||||
* mapped and freed by the same manager, so there is one record of what a sequence owns
|
||||
* (spec §7.2). */
|
||||
enum {
|
||||
RAD_KV_FULL = 0, /* paged, per-token, growing -- full attention */
|
||||
RAD_KV_WINDOW = 1, /* paged, per-token, bounded by the window */
|
||||
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 from the resolved attention kernel's constraints at
|
||||
* declare, so the core needs no edit when a kernel changes (spec §7.2). Read it back with
|
||||
* rad_kv_block_size() after declaring the attention op that consumes this group. */
|
||||
} RadKVGroupDecl;
|
||||
|
||||
/* `rad_kvgroup` is in rad_types.h with the other handles -- RadBufDecl above carries one. */
|
||||
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 weight operands. The core resolves each against the kernel
|
||||
* hierarchy, per band, per domain. This phase always completes, and every op that failed to
|
||||
* resolve is reported together at the end. */
|
||||
rad_op rad_decl_op(RadBuilder* b, const char* op,
|
||||
const RadParam* params, int n_params,
|
||||
const rad_weight* weights, int n_weights);
|
||||
|
||||
/* 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. rad_decl_op names only weights, which placement moves; the buffer
|
||||
* planner needs liveness, i.e. which ops read and write which buffers. A transient with no
|
||||
* declared use is assumed live for the whole program, which is sound (a plugin may issue any
|
||||
* handle in any order) but wasteful; --debug-graph prints how many buffers fell into that case.
|
||||
* Separate calls rather than four more parameters on every rad_decl_op. */
|
||||
int rad_op_reads (RadBuilder* b, rad_op h, const rad_buf* bufs, int n);
|
||||
int rad_op_writes(RadBuilder* b, rad_op h, const rad_buf* bufs, int n);
|
||||
|
||||
/* A buffer the architecture touches from the second lane, the one case where the op range a
|
||||
* buffer's declarations imply does not bound when its bytes are in use.
|
||||
*
|
||||
* The planner packs transients from one linear order (spec §3.1): two whose declared lives do not
|
||||
* overlap share arena bytes. `rad_lane` breaks that: lane 1's ops sit at op indices inside lane
|
||||
* 0's, so a shared-arm scratch live over ops 41..42 can overlay a routed-arm scratch live over ops
|
||||
* 37..38, and on two streams those runs overlap in time, corrupting data silently.
|
||||
*
|
||||
* A buffer named here is live for the whole program, like a buffer with no declared use. It is
|
||||
* per-buffer rather than a mode because unsharing every buffer costs ~220 MiB on a large model,
|
||||
* against a few MiB for one block's lane-1 transients. Call it at declare for every buffer the
|
||||
* second lane reads or writes; the lane-0 buffers they could share with are covered, since
|
||||
* sharing needs both sides.
|
||||
*
|
||||
* A no-op for a PERSIST or DERIVED buffer, which is live everywhere already. */
|
||||
int rad_buf_concurrent(RadBuilder* b, rad_buf buf);
|
||||
|
||||
/* An uneven shard: this rank's slice of a RAD_SHARD_ROW or RAD_SHARD_COL weight's split dimension
|
||||
* is [lo, hi) rather than an even 1/tp. Rows of each stacked row part for ROW, columns for COL, in
|
||||
* the container's unsharded units. The declared extent must already be `hi - lo` (per row part,
|
||||
* for ROW).
|
||||
*
|
||||
* For a width that does not divide into equal whole blocks across ranks: a 640-column projection
|
||||
* with 128-column scale blocks is five blocks, split three and two. The stacked parts of a ROW
|
||||
* weight must be equal in the container, since only the rank's own part sizes are declared.
|
||||
* Refused for a container converted for more than one rank (its entries are already even shares)
|
||||
* and for a stored layout whose row runs or column groups the span would cut. */
|
||||
int rad_weight_shard_span(RadBuilder* b, rad_weight w, int64_t lo, int64_t hi);
|
||||
|
||||
/* A stacked weight's span, one [lo, hi) per row part, with each part's whole extent in the
|
||||
* container, for parts of unequal width that rad_weight_shard_span's single span cannot express
|
||||
* (the delta net's [q|k|v|z] is 2048, 2048, 6144, 6144 rows on Flash-Next). `n` is the declared
|
||||
* part count; container part g is `total[g]` rows, of which this rank takes [lo[g], hi[g]) and
|
||||
* declared `hi[g] - lo[g]`; the totals must sum to the entry's rows. An uneven share of the heads
|
||||
* (6 of 16 K heads, with three ranks taking 6, 5 and 5) is declared this way, without padding.
|
||||
* Additive export. */
|
||||
int rad_weight_shard_span_parts(RadBuilder* b, rad_weight w, const int64_t* lo, const int64_t* hi,
|
||||
const int64_t* total, int n);
|
||||
|
||||
/* This rank keeps no cache for the group. The group is still declared as on every other rank (the
|
||||
* scheduler indexes groups by position and one block table serves every rank, so it must exist
|
||||
* with the same block size and layers), but no pool is carved for it. For a rank the geometry
|
||||
* gives no attention heads (rad_arch.h Geom::attn_zero), whose attention is a `fill` of zeros.
|
||||
* After this, no op on this rank may name the group as a RAD_KV operand; the engine refuses one
|
||||
* at issue. Additive export. */
|
||||
int rad_kv_group_zero(RadBuilder* b, rad_kvgroup g);
|
||||
|
||||
#define RAD_BUFS(...) ((const rad_buf[]){ __VA_ARGS__ }), \
|
||||
(int)(sizeof((const rad_buf[]){ __VA_ARGS__ }) / sizeof(rad_buf))
|
||||
|
||||
/* Did the last rad_decl_op resolve? A plugin asks for the fused op first and emits the unfused
|
||||
* sequence when it does not, which makes fusion a selection rather than a compiler pass
|
||||
* (spec §2.3). An unresolved handle is RAD_NULL_HANDLE and becomes an error only if issued. */
|
||||
int rad_op_resolved(RadBuilder* b, rad_op h);
|
||||
|
||||
/* Does any loaded kernel library declare op `op`? Declaring an op outside the vocabulary is an
|
||||
* error, since that is what a misspelt name looks like; an op that is declared but resolves to no
|
||||
* kernel is not (rad_op_resolved). A plugin asks this first for a fused op only an optional
|
||||
* library defines, and emits the chain when the answer is 0. Additive export. */
|
||||
int rad_op_declared(RadBuilder* b, const char* op);
|
||||
|
||||
/* ================================================================== checkpoint name map */
|
||||
/* The plugin owns the map from checkpoint tensor names to declared weight names, including
|
||||
* convert-time fusions (q/k/v into one qkv, gate and up into gate_up). It is the only component
|
||||
* that knows both sides, and rad-convert reads the map from it (spec §2.4). */
|
||||
enum { RAD_MAP_COPY = 0, RAD_MAP_CONCAT = 1 };
|
||||
|
||||
typedef struct RadNameMap {
|
||||
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; this carries the expert index so rad-convert need not parse it
|
||||
* out of the declared name. */
|
||||
int src_index[8];
|
||||
} RadNameMap;
|
||||
|
||||
/* RAD_MAP_COPY with n_src > 1: the first source present in the container wins. This expresses a
|
||||
* tied lm_head (output.weight if present, else token_embd.weight), so one plugin covers family
|
||||
* members that differ only in tying. RAD_MAP_CONCAT with n_src > 1 concatenates all sources along
|
||||
* concat_dim and requires every one. */
|
||||
|
||||
int rad_decl_name_map(RadBuilder* b, const RadNameMap* m);
|
||||
|
||||
|
||||
/* ================================================================== the step's output */
|
||||
/* Which buffer holds this step's logits. The core samples from it (the sampler chain is core logic
|
||||
* whose ops resolve through the same hierarchy as the plugin's, spec §13), and only the plugin
|
||||
* knows which buffer it is. A name match would be wrong: a drafter or encoder tower declares into
|
||||
* a scope (RadBuildCtx::scope, spec §10, §11), so "the buffer called logits" can be two buffers in
|
||||
* one Program.
|
||||
*
|
||||
* Its extent along dim 0 bounds RadBatch::n_out: one row per sampled position, not per token of
|
||||
* the step. Declaring it [max_tok, n_vocab] is legal but, at a 248K vocabulary, 8 GiB.
|
||||
*
|
||||
* A Program with no logits buffer cannot serve, and the engine says so at startup. An
|
||||
* embedding-only or encoder-only plugin declares none. */
|
||||
int rad_declare_logits(RadBuilder* b, rad_buf logits);
|
||||
|
||||
/* Which buffer holds this step's pooled vectors, what an embedding model returns instead of
|
||||
* logits. Row s is sequence s's whole input pooled into one vector, with whatever pooling the
|
||||
* model was trained with (a mean, the last token, a CLS row). The core reads rows [0, n_seq) back
|
||||
* after the step and hands each to its request. It does not normalise them; that is the API's
|
||||
* choice, not the model's.
|
||||
*
|
||||
* Declaring it makes the Program an embedding program:
|
||||
* - every sequence in a step is a whole input. The scheduler never splits one across steps,
|
||||
* since a bidirectional encoder cannot be fed half its input, and refuses an input longer
|
||||
* than one step rather than truncating it;
|
||||
* - there is no sampler, drafter or prefix cache, and nothing is generated: a request ends at
|
||||
* the step that carried it.
|
||||
*
|
||||
* f32, device, [>= max_seqs, dim]: `dim` is the vector width the core reads. A Program declares
|
||||
* this or logits, never both. */
|
||||
int rad_declare_pooled(RadBuilder* b, rad_buf pooled);
|
||||
|
||||
|
||||
/* ================================================================== the drafter */
|
||||
/* The plugin's draft head. The core drives the extra passes, and only the plugin knows what it
|
||||
* is, so it is declared rather than detected from weight names (`mtp.fc.weight`) with the core
|
||||
* re-reading the drafter's configuration keys the plugin already read.
|
||||
*
|
||||
* The kind is a drive shape, not a model. SERIAL runs `depth` dependent passes, each embedding the
|
||||
* last one's proposal, so tokens arrive one at a time and a pass that declines ends the chain
|
||||
* (MTP, EAGLE, Medusa-serial). BLOCK runs a context pass, then one pass that fills every drafted
|
||||
* position at once (DFlash2 and other block-diffusion drafters).
|
||||
*
|
||||
* `proposal` is the buffer a pass writes its token ids into; 0 means the sampler's token buffer,
|
||||
* which suits a head whose logits go through the ordinary sampler chain.
|
||||
*
|
||||
* Declaring no drafter is the normal case; the scheduler's prompt-lookup drafter still runs. */
|
||||
typedef enum {
|
||||
RAD_DRAFT_NONE = 0,
|
||||
RAD_DRAFT_SERIAL = 1, /* `depth` dependent passes, one proposal each */
|
||||
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 block position embeds; a block drafter
|
||||
* without one cannot run. `window` is the drafter's own sliding window over its own cache, 0
|
||||
* for unbounded. The core stages the block pass against it, so it must match the window the
|
||||
* plugin gated its attention with. */
|
||||
int32_t mask_token;
|
||||
int64_t window;
|
||||
|
||||
/* BLOCK only: how many rows the query pass runs over, per sequence. 0 means `depth + 1`.
|
||||
*
|
||||
* The core stages the block as an anchor (the token the sampler just chose) followed by
|
||||
* `block - 1` copies of `mask_token`, and the head runs over the last `depth` rows. That covers
|
||||
* both training conventions:
|
||||
*
|
||||
* block = depth + 1 the anchor row predicts nothing; each mask row predicts the token at
|
||||
* its own position. The head sees rows 1..depth. DFlash2.
|
||||
* block = depth every row, the anchor included, predicts the token at the next
|
||||
* position (the ordinary next-token relation). The head sees rows
|
||||
* 0..depth-1. DSpark, whose reference takes `hidden[:, -block_size:, :]`.
|
||||
*
|
||||
* A wrong value is not visible in the output: both run, every draft is verified so the text
|
||||
* stays correct, but the proposals shift by one position and acceptance drops to about chance.
|
||||
* Hence it is declared by the plugin, which knows how the checkpoint was trained. */
|
||||
int64_t block;
|
||||
} RadDrafterDecl;
|
||||
|
||||
int rad_declare_drafter(RadBuilder* b, const RadDrafterDecl* d);
|
||||
|
||||
/* A serial head with no cache of its own: each of its attention layers reads one trunk layer's K
|
||||
* and V and writes none. Gemma 4's assistant head, whose layers have only a query projection,
|
||||
* reads the last sliding and last global trunk layer. Called once, after rad_declare_drafter.
|
||||
* Additive export; RAD_ABI_VERSION does not move.
|
||||
*
|
||||
* Effect on the serial driver, all following from the head writing nothing:
|
||||
*
|
||||
* No history pass, since there is no K and V of its own to fill. The pass carries round 1
|
||||
* alone: one row per drafting sequence, at the committed position, with the token the trunk
|
||||
* chose after it and the trunk's hidden state there (out_ids). A sequence that does not draft
|
||||
* gets no row, and a step with nothing to draft no pass.
|
||||
*
|
||||
* Every round runs at that same position over the same context. The trunk's cache past the
|
||||
* committed position holds K and V of drafts the last verify rejected, or nothing, so every
|
||||
* round's `seqused` ends at the committed position; the head's proposals travel forward in its
|
||||
* hidden state and next input token instead.
|
||||
*
|
||||
* `pos_offset` is the rotary position of those rows relative to the committed position: 0 is the
|
||||
* position of the trunk hidden state the head continues from, 1 that of the token it embeds. It
|
||||
* moves nothing else (the context ends at the committed position either way), and which one a
|
||||
* checkpoint was trained with is the plugin's to know. */
|
||||
int rad_drafter_shared_kv(RadBuilder* b, int pos_offset);
|
||||
|
||||
/* ================================================================== the encoder */
|
||||
/* A media encoder the plugin runs on an encoder pass (RadBatch::enc). The core drives the pass and
|
||||
* reads its result, so the plugin declares it. A plugin that declares none serves text only, and
|
||||
* the server refuses a media part by name.
|
||||
*
|
||||
* This is the shape of the interface, not the model. The core stages patches of `patch_dim`
|
||||
* elements and reads back one `n_embd`-wide row per `merge` of them; the tower itself is the
|
||||
* plugin's business. How an image or video becomes patches is the processor's (core/mm), which
|
||||
* reads its geometry from the container; the core refuses a program whose encoder disagrees with
|
||||
* the processor about `patch_dim` or `merge`. */
|
||||
/* A program declares at most two: one serving images and video, one serving audio. An audio
|
||||
* encoder's "patch" is one feature frame (a mel row), its `merge` is frames per output row, and
|
||||
* its `max_patches` is RadBuildCtx::max_audio_frames. RadBatch::enc names which one a pass runs. */
|
||||
enum {
|
||||
RAD_MM_IMAGE = 1u << 0,
|
||||
RAD_MM_VIDEO = 1u << 1,
|
||||
RAD_MM_AUDIO = 1u << 2,
|
||||
};
|
||||
|
||||
typedef struct RadEncoderDecl {
|
||||
const char* name; /* "vision" -- for messages */
|
||||
uint32_t modalities; /* RAD_MM_* this encoder serves: IMAGE|VIDEO, or AUDIO alone */
|
||||
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 (max_audio_frames) */
|
||||
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);
|
||||
|
||||
/* ================================================================== the image generator */
|
||||
/* A program that makes images: a conditioning network reads a prompt (and pictures), a denoiser
|
||||
* turns a noise latent into an image latent over a number of steps, and a decoder turns the
|
||||
* latent into pixels. The core drives the passes, so the plugin declares them.
|
||||
*
|
||||
* Declaring one makes the program a generator, driven by passes rather than token steps
|
||||
* (RadBatch::gen):
|
||||
*
|
||||
* RAD_GEN_PASS_COND one conditioning sequence (the prompt and any reference pictures)
|
||||
* encoded into the generator's KV group. Once per request, twice with
|
||||
* guidance (the negative prompt is its own sequence).
|
||||
* RAD_GEN_PASS_DENOISE one step of every image the pass carries: each image's latent rows,
|
||||
* read from and written back to the plugin's state at the image's lane,
|
||||
* against its conditioning's KV.
|
||||
* RAD_GEN_PASS_DECODE one image's latent to pixels, in `image_out`, which the core reads back.
|
||||
*
|
||||
* A program declares exactly one of this, logits or pooled vectors.
|
||||
*
|
||||
* The fields are the model's contract with a client: the prompt it was trained on, the sizes it
|
||||
* makes, its sampler's schedule. The core turns a request into passes from them without naming
|
||||
* any model. */
|
||||
enum { RAD_GEN_PASS_COND = 1, RAD_GEN_PASS_DENOISE = 2, RAD_GEN_PASS_DECODE = 3 };
|
||||
|
||||
/* How the generator's sequence is laid out; the core builds it from the conditioning prompt.
|
||||
*
|
||||
* JOINT_GRID the prompt's rows after `drop_prefix`, each media slot standing for `slot_rows`
|
||||
* rows that a reference picture's latent tokens take in raster order, then the
|
||||
* image being made. Rotary positions are three components: a text row counts up
|
||||
* in all three; a picture of h x w tokens holds the count in the first, and its row
|
||||
* and column, centred on zero (-(n - n/2) .. n/2 - 1), in the other two, after which
|
||||
* the count moves on by max(h, w). Text rows attend causally, a picture's rows to
|
||||
* each other both ways, every row to every row before it. */
|
||||
enum { RAD_GEN_LAYOUT_JOINT_GRID = 1 };
|
||||
|
||||
typedef struct RadGeneratorDecl {
|
||||
const char* name; /* "qwen-image" -- for messages */
|
||||
int32_t layout; /* RAD_GEN_LAYOUT_* */
|
||||
|
||||
/* The conditioning prompt, as text the core tokenises. `{prompt}` is replaced by the user's
|
||||
* prompt; in `tmpl_edit`, `{images}` by one `tmpl_image` per reference picture, joined by
|
||||
* `tmpl_image_sep`. In `tmpl_image`, `{n}` is the picture's 1-based number and `{image}` marks
|
||||
* where the picture's own tokens go (the media processor's run for it, markers included). */
|
||||
const char* tmpl_text;
|
||||
const char* tmpl_edit;
|
||||
const char* tmpl_image;
|
||||
const char* tmpl_image_sep;
|
||||
/* The tokens of this text at the start of the prompt are encoded but not handed to the
|
||||
* generator; the conditioning starts after them (e.g. a fixed system turn). */
|
||||
const char* drop_prefix;
|
||||
/* Prompt for a transparent image, in the words the model was trained on; `{prompt}` is the
|
||||
* user's description. Empty when the model makes no alpha. */
|
||||
const char* tmpl_transparent;
|
||||
|
||||
/* Geometry. One latent token covers `latent_scale` x `latent_scale` pixels and holds
|
||||
* `latent_channels` values; a side is a multiple of `size_multiple` pixels; an image has
|
||||
* `pixel_channels` channels (4: RGBA). A media slot of the conditioning prompt (one encoder
|
||||
* output row) stands for `slot_rows` rows of the generator's sequence. */
|
||||
int64_t latent_channels;
|
||||
int64_t latent_scale;
|
||||
int64_t size_multiple;
|
||||
int64_t pixel_channels;
|
||||
int64_t slot_rows;
|
||||
/* The largest image, in latent tokens; the plugin sizes its per-image buffers for it. */
|
||||
int64_t max_tokens;
|
||||
/* Reference pictures: at most `max_refs` a request, each resized to `ref_area` pixels. */
|
||||
int64_t max_refs;
|
||||
int64_t ref_area;
|
||||
/* The size a request that names none is made at. */
|
||||
int64_t default_width, default_height;
|
||||
|
||||
/* The sampler: flow matching, Euler steps from sigma 1 towards 0.
|
||||
* A fixed schedule: `n_sigmas` values, the terminal 0 implied; a request may not change the
|
||||
* step count. Otherwise `default_steps` sigmas from 1 to 1/steps, shifted:
|
||||
* dyn_shift 0 sigma' = shift * s / (1 + (shift - 1) * s)
|
||||
* dyn_shift 1 mu linear in the image's token count, 256 -> base_shift .. max_seq ->
|
||||
* max_shift; shift_exp 1: exp(mu) / (exp(mu) + (1/s - 1)), 0: mu / (mu + ...)
|
||||
* then, with shift_terminal > 0, stretched so the last sigma is shift_terminal. */
|
||||
int64_t default_steps;
|
||||
int32_t n_sigmas;
|
||||
const double* sigmas;
|
||||
double shift;
|
||||
int32_t dyn_shift;
|
||||
int32_t shift_exp;
|
||||
double base_shift, max_shift;
|
||||
int64_t base_seq, max_seq;
|
||||
double shift_terminal;
|
||||
/* Guidance a request gets when it names none; 1 is off. */
|
||||
double default_cfg;
|
||||
|
||||
/* `max_lanes` images may be in flight at once, each in a lane of the plugin's own state.
|
||||
* `image_out` is [max_tokens * latent_scale^2, pixel_channels] u8 on the device: row-major
|
||||
* pixels of the image a decode pass made. */
|
||||
int64_t max_lanes;
|
||||
rad_buf image_out;
|
||||
} RadGeneratorDecl;
|
||||
|
||||
int rad_declare_generator(RadBuilder* b, const RadGeneratorDecl* 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: 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 branching on a quant
|
||||
* descriptor inside one plugin obscures what actually runs. So `qwen35_bf16` and `qwen35_fp8` both
|
||||
* answer "qwen35" to rad_arch_id and are told apart here, by RadModelMeta::quant.
|
||||
*
|
||||
* The match is exact, with no fallback. Unquantised containers and plugins both say ""; the
|
||||
* symbol is optional and a plugin without it reads as "". A fallback to a dense plugin would fail
|
||||
* later at the name map with a worse message than "no plugin claims qwen35 at fp8_e4m3; qwen35 is
|
||||
* served at: (unquantised)". */
|
||||
const char* rad_arch_quant(void);
|
||||
|
||||
/* What the plugin can say before it declares anything. Optional: a plugin that does not export
|
||||
* it answers zero to everything, each field's default.
|
||||
*
|
||||
* The main case is the draft depth, a model property that is an input to declaration:
|
||||
* `RadBuildCtx::max_spec` sizes buffers, bands kernels and sets the scheduler's window, so it is
|
||||
* fixed before rad_arch_declare runs, yet only the plugin reads the drafter's configuration. 0
|
||||
* means the container carries no drafter.
|
||||
*
|
||||
* --num-speculative-tokens overrides the answer, and the plugin sees the result in
|
||||
* RadBuildCtx::max_spec; a plugin whose checkpoint cannot serve that depth refuses in declare. */
|
||||
typedef struct RadArchProbe {
|
||||
int draft_depth;
|
||||
|
||||
/* Nonzero when `draft_depth` is the only depth the drafter serves. A serial head's depth is a
|
||||
* throughput operating point (each extra pass costs one pass and acceptance decays, but it
|
||||
* still runs). A block drafter's depth is the block length its checkpoint was trained at (its
|
||||
* convolution masks the position within the block), so any other depth is refused.
|
||||
*
|
||||
* `--num-speculative-tokens auto` takes `draft_depth` either way. rad-convert does not: a
|
||||
* container carries everything the model can serve, so it widens to `draft_depth` only when
|
||||
* this says the drafter has no choice; otherwise a deployment wanting a deeper serial draft
|
||||
* would have to convert again. */
|
||||
int draft_depth_fixed;
|
||||
|
||||
/* The plugin honours RadBuildCtx::shape_probe: a sizing declare leaves the state its step
|
||||
* function reads untouched. Zero means the core does not ask, and the activation arena is not
|
||||
* lent. */
|
||||
int shape_probe_ok;
|
||||
|
||||
/* The encoder's merge, input patches per output row (RadEncoderDecl::merge), when the plugin
|
||||
* declares an encoder. A pass carries whole output rows, so the core rounds the pass size it
|
||||
* picks itself (`--mm-max-patches auto`) down to a multiple of this; an operator-named size is
|
||||
* kept, and the plugin refuses one that does not divide. 0 is no opinion. */
|
||||
int64_t enc_merge;
|
||||
|
||||
/* The longest clip the audio encoder takes, in feature frames (a whole number of its merge);
|
||||
* the engine sizes the audio pass with it (RadBuildCtx::max_audio_frames). 0 is no audio. */
|
||||
int64_t audio_frames;
|
||||
|
||||
/* Nonzero for an image generator (rad_declare_generator): the rows its largest pass carries.
|
||||
* The engine sizes the step for it before declare (a denoise pass carries all of an image's
|
||||
* latent rows at once, twice with guidance) and turns off what a generator does not use. 0 is
|
||||
* a program that generates text or embeds. */
|
||||
int64_t gen_rows;
|
||||
/* The most patches the generator's conditioning pass encodes: every reference picture a
|
||||
* request may carry, at the model's resize target. This is the encoder's pass size
|
||||
* (max_enc_patches). */
|
||||
int64_t gen_patches;
|
||||
} RadArchProbe;
|
||||
|
||||
int rad_arch_probe(const RadModelMeta* meta, RadArchProbe* out);
|
||||
|
||||
/* How this model spells a turn, as data. Optional: without it the engine derives the format by
|
||||
* analysing the chat template.
|
||||
*
|
||||
* One streaming parser driven by this description splits a reply into reasoning, content and tool
|
||||
* calls, and the lazy grammar that constrains a call and its trigger words are generated from it,
|
||||
* so a model whose format the template analysis misses or gets wrong is supported by stating it
|
||||
* here. It describes the tagged family:
|
||||
*
|
||||
* [reasoning_open] reasoning [reasoning_close] content
|
||||
* [call_open] name_prefix NAME name_suffix
|
||||
* arg_prefix ARG arg_name_suffix arg_value_prefix VALUE arg_value_suffix ...
|
||||
* call_end [call_close]
|
||||
*
|
||||
* Qwen3.8, for example, is "<think>\n" / "\n</think>\n\n", calls "<tool_call>\n" / "</tool_call>",
|
||||
* "<function=" / ">\n" / "</function>\n", arguments "<parameter=" / ">\n" / "" / "</parameter>\n".
|
||||
* Whitespace at the ends of a tag is optional when matching. Every string is NUL-terminated
|
||||
* UTF-8; NULL reads as "". The engine copies what it needs while loading, so static storage in
|
||||
* the plugin is enough.
|
||||
*
|
||||
* The other family is a call written as a name and one object holding its arguments
|
||||
* (args_form = RAD_CHAT_ARGS_OBJECT):
|
||||
*
|
||||
* [call_open] name_prefix NAME name_suffix { key: value, ... } [call_end] [call_close]
|
||||
*
|
||||
* The object is JSON, or a dialect of it: strings between object_string_open and
|
||||
* object_string_close, their text verbatim, and keys written bare (object_bare_keys). Gemma 4 is
|
||||
* "<|tool_call>" / "<tool_call|>", "call:" / "" / "", strings "<|\"|>" / "<|\"|>", bare keys --
|
||||
* `<|tool_call>call:get_weather{city:<|"|>Paris<|"|>}<tool_call|>` -- and the reply's JSON
|
||||
* arguments are that object respelled as JSON. The arg_* fields describe tagged arguments only
|
||||
* and are empty in this family.
|
||||
*
|
||||
* The struct only grows at its end. `struct_size` is sizeof(RadChatFormat) as the plugin was
|
||||
* compiled; the engine reads only the fields that size covers and treats the rest as zero, so a
|
||||
* plugin built against an older header keeps loading, and a new field must make zero mean "as
|
||||
* before". So this export does not move RAD_ABI_VERSION. A field reordered, retyped or removed is
|
||||
* a layout change and bumps RAD_ABI_VERSION like any other. */
|
||||
enum {
|
||||
RAD_CHAT_VALUE_RAW = 0, /* the text between the delimiters, verbatim */
|
||||
RAD_CHAT_VALUE_CDATA = 1, /* verbatim, unless wrapped in <![CDATA[ ... ]]>, which is removed */
|
||||
RAD_CHAT_VALUE_JSON = 2 /* a JSON value; text that does not parse as JSON is taken raw */
|
||||
};
|
||||
|
||||
enum {
|
||||
/* The generation prompt shows whether the reply starts inside a reasoning block: whatever
|
||||
* follows the first `reasoning_open` in it is the start of the reply's own text. */
|
||||
RAD_CHAT_THINK_FROM_PROMPT = 0,
|
||||
RAD_CHAT_THINK_ALWAYS = 1, /* the reply is inside a reasoning block from its first byte */
|
||||
RAD_CHAT_THINK_NEVER = 2 /* the model opens its own block, if any */
|
||||
};
|
||||
|
||||
enum {
|
||||
RAD_CHAT_ARGS_TAGGED = 0, /* each argument in its own tags: arg_prefix .. arg_value_suffix */
|
||||
RAD_CHAT_ARGS_OBJECT = 1 /* one object after the name, in JSON or the object_* dialect */
|
||||
};
|
||||
|
||||
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 these yet, so a format that sets one is refused at startup by name; they are fields so
|
||||
* supporting them later does not change the struct. */
|
||||
const char* section_open;
|
||||
const char* section_close;
|
||||
const char* call_separator;
|
||||
|
||||
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 -- at
|
||||
* its start only where the tag before it does not end with that newline itself. */
|
||||
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;
|
||||
|
||||
/* RAD_CHAT_ARGS_*: how a call's arguments are written. Zero is the tagged family above. With
|
||||
* RAD_CHAT_ARGS_OBJECT, name_suffix may be empty -- the name then ends where the object
|
||||
* begins -- and so may call_end, when the object's own closing brace ends the call. */
|
||||
uint32_t args_form;
|
||||
/* RAD_CHAT_ARGS_OBJECT: a string delimiter of the object's dialect besides JSON's `"`. What
|
||||
* stands between the two is the string, verbatim -- the dialect has no escapes. NULL: the
|
||||
* object writes JSON strings only. */
|
||||
const char* object_string_open;
|
||||
const char* object_string_close;
|
||||
/* RAD_CHAT_ARGS_OBJECT: non-zero when the dialect writes a key bare, `key:value`. */
|
||||
uint32_t object_bare_keys;
|
||||
|
||||
/* Non-zero: a reasoning block may open again later in the reply (after its answer, between
|
||||
* calls) and is read as reasoning there too, and a reasoning_close with no block open is not
|
||||
* part of the answer. Zero: only a block the reply starts with is reasoning. */
|
||||
uint32_t reasoning_anywhere;
|
||||
} RadChatFormat;
|
||||
|
||||
/* Return the format, or NULL for "derive it from the chat template". Called once at startup. */
|
||||
const RadChatFormat* rad_arch_chat_format(const RadModelMeta* meta);
|
||||
|
||||
/* How a speech model's prompt carries audio, as data. Optional: a plugin that does not export it
|
||||
* is a model the speech routes do not serve.
|
||||
*
|
||||
* It states the tokens that open and close a clip, the turn a transcription is asked in, how a
|
||||
* language is named and forced, and where the transcript starts in the reply, so the core's
|
||||
* routes know nothing of any one model. Qwen3-ASR, for example:
|
||||
*
|
||||
* audio_open "<|audio_start|>" audio_close "<|audio_end|>"
|
||||
* transcribe_prompt "<|im_start|>system\n{context}<|im_end|>\n<|im_start|>user\n{audio}"
|
||||
* "<|im_end|>\n<|im_start|>assistant\n{language}"
|
||||
* language_prompt "language {language}<asr_text>"
|
||||
* transcript_open "<asr_text>" language_lead "language "
|
||||
* languages { "en", "English", "zh", "Chinese", ... }
|
||||
*
|
||||
* Every string is NUL-terminated UTF-8 and NULL reads as "". The engine copies what it needs while
|
||||
* loading, so static storage in the plugin is enough.
|
||||
*
|
||||
* The struct only grows at its end, as RadChatFormat does: `struct_size` is sizeof(RadAudioFormat)
|
||||
* as the plugin was compiled, the engine reads only the fields that size covers, and a field added
|
||||
* later reads as zero for an older plugin. So this export does not move RAD_ABI_VERSION. */
|
||||
typedef struct RadAudioFormat {
|
||||
uint32_t struct_size;
|
||||
|
||||
/* The literal tokens around a clip's placeholder run, as the vocabulary spells them, for a
|
||||
* model whose config names no id for them. NULL: the config's own (boa/eoa_token_id). */
|
||||
const char* audio_open;
|
||||
const char* audio_close;
|
||||
|
||||
/* The transcription prompt (POST /v1/audio/transcriptions), with three slots: {context} is
|
||||
* the request's `prompt` text, {audio} the clip, and {language} `language_prompt` with the
|
||||
* request's language named in it, or "" when the request names none and the model is to say
|
||||
* which it heard. Each slot appears once. NULL: this model does not transcribe. */
|
||||
const char* transcribe_prompt;
|
||||
const char* language_prompt;
|
||||
|
||||
/* A reply whose language was not forced names it first: `language_lead` and the language's
|
||||
* name, then `transcript_open`, then the transcript. "" for a model whose reply is the
|
||||
* transcript alone. */
|
||||
const char* transcript_open;
|
||||
const char* language_lead;
|
||||
|
||||
/* The languages the model names, as n_languages (ISO 639-1 code, the model's own name) pairs:
|
||||
* a request's `language` matches either spelling, and the name is what {language} takes. */
|
||||
const char* const* languages;
|
||||
uint32_t n_languages;
|
||||
} RadAudioFormat;
|
||||
|
||||
/* Return the format, or NULL when this model serves no speech route. Called once at startup. */
|
||||
const RadAudioFormat* rad_arch_audio_format(const RadModelMeta* meta);
|
||||
|
||||
int rad_arch_declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx);
|
||||
/* Forward declaration; the signature is in rad_runtime.h. */
|
||||
struct RadCtx;
|
||||
struct RadBatch;
|
||||
void rad_arch_step(struct RadCtx* c, const struct RadBatch* batch);
|
||||
|
||||
#ifdef __cplusplus
|
||||
} /* extern "C" */
|
||||
#endif
|
||||
#endif /* RAD_BUILDER_H */
|
||||
@@ -0,0 +1,77 @@
|
||||
/* rad_device.h -- the device layer. Deliberately thin: everything above it is written once, and
|
||||
* every backend implements the small set of calls below.
|
||||
*
|
||||
* The host backend is a full backend. It lets the core, scheduler, planner, tokeniser, server and
|
||||
* libref be built and tested without an accelerator, and RAD_DOMAIN_HOST kernels run on it when the
|
||||
* planner puts a layer on the CPU (spec §5.1).
|
||||
*/
|
||||
#ifndef RAD_DEVICE_H
|
||||
#define RAD_DEVICE_H
|
||||
|
||||
#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 };
|
||||
|
||||
/* Everything the engine knows about a device. Nothing above this layer names a vendor, product or
|
||||
* instruction set: the scheduler, planner and budgets learn the machine from these fields at run
|
||||
* time. Hardware knowledge belongs in kernel libraries, which declare the devices they serve.
|
||||
*
|
||||
* Every field carries what the backend reports, in the backend's own vocabulary. */
|
||||
typedef struct RadDeviceProps {
|
||||
char name[128]; /* the product name, for logs and for the tuning cache's key */
|
||||
char arch[32]; /* the backend's name for the architecture, with any feature
|
||||
* 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 */
|
||||
@@ -0,0 +1,457 @@
|
||||
/* rad_encoding.h -- what a stored weight's numbers are, independent of how any kernel wants them
|
||||
* arranged. spec.md §4.1.
|
||||
*
|
||||
* An encoding is the code type, the codebook the codes index (if any), the grouping of the scales,
|
||||
* zero points and minimums over the weight, and the transform applied before quantisation. It is a
|
||||
* property of the model: choosing one is lossy and can be expensive (GPTQ needs a calibration
|
||||
* run), and changing one means quantising again. A layout (fragment order, a scale carried in each
|
||||
* row's tail, a nibble order that suits one unpack) is a property of a kernel, lossless and cheap,
|
||||
* applied when the model loads (rad_abi.h). A container holds encodings only, so a kernel library
|
||||
* can change any layout without a reconvert.
|
||||
*
|
||||
* An encoding is data rather than an enum value, so a quantiser plugin can invent one without the
|
||||
* core knowing it. The core can size, slice and place any encoding from this struct alone, and
|
||||
* decodes every encoding of the one scheme it defines, "affine". That scheme covers the common
|
||||
* formats: per-channel and grouped integers of any width, block FP8, MXFP4/6/8, NVFP4, llama.cpp's
|
||||
* legacy, K- and I-quants, AWQ's column scales, GPTQ's act-order permutation, Hadamard and Givens
|
||||
* rotations.
|
||||
*
|
||||
* ===================================================================== PLANES
|
||||
*
|
||||
* An encoding is up to RAD_ENC_MAX_PLANES planes, each a dense row-major array of one core dtype.
|
||||
* 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) from bit 0 of the row's first byte, so two 4-bit codes
|
||||
* share a byte with element 0 in bits 0-3, and a 3-bit code may straddle a byte. Every row starts
|
||||
* on a byte. A kernel that wants its nibbles permuted for its own unpack does so in its relayout.
|
||||
*
|
||||
* ===================================================================== THE AFFINE SCHEME
|
||||
*
|
||||
* The planes are found by role, and only "codes" is required. A weight element decodes as
|
||||
*
|
||||
* q = code codes is TILED; its block is [1 x 1] -- one code a value -- or
|
||||
* [1 x V] with a "grid", one code a V-vector
|
||||
* q = grid[code][k] grid TABLE [entries x V]: a vector codebook (the IQ2/IQ3/IQ1
|
||||
* lattices); value k of the code's V-vector
|
||||
* q = table[code] table TABLE [1 x entries]: a scalar codebook (IQ4_NL)
|
||||
* q = -q if the sign bit is set signs TILED u1 [1 x 1], one bit a value
|
||||
* q = q - zero zero TILED; an integer or real offset in the code's domain
|
||||
* v = q * scale * scale.1 * ... scale, scale.1, ... TILED: every scale level, multiplied
|
||||
* v = v - min * min.1 * ... min, min.1, ... TILED: a minimum in the value's domain
|
||||
* w = v . T^-1 the transform, per row, over the columns (below)
|
||||
*
|
||||
* so NVFP4 is fp4 codes, an e4m3 scale per [1 x 16] and an f32 scale.1 per tensor; Q4_K is u4
|
||||
* codes, a u6 scale and u6 min per [1 x 32] each times an f16 per [1 x 256]; IQ2_XXS is u8 codes
|
||||
* per [1 x 8] into a 256 x 8 grid with a sign bit a value and two scale levels. Any other scheme
|
||||
* is a quantiser's own, and that quantiser decodes it (rad_quant.h).
|
||||
*
|
||||
* ===================================================================== TRANSFORMS
|
||||
*
|
||||
* `transform` names what was done to each row before it was quantised: the stored row is v = w . T,
|
||||
* so a kernel computes <w, x> = <v, x . T^-T> and transforms its activation, never the weight.
|
||||
*
|
||||
* "" none.
|
||||
* "fwhtN" T = H_N / N block-diagonally over groups of N columns, H_N the unnormalised
|
||||
* Sylvester Hadamard (entries +-1, H H = N I). Decoding applies H_N once (w = H v);
|
||||
* the activation is rotated by the unnormalised H_N with nothing folded at runtime:
|
||||
* the 1/N lives in the stored scale.
|
||||
* "perm" T is a column permutation: TABLE "t.perm" i32 [1 x cols], v[j] = w[perm[j]] --
|
||||
* GPTQ's act-order, which quantises the columns in a different order than stored.
|
||||
* "givens" T = D . G_1 . ... . G_S: D = diag(t.scale) when TABLE "t.scale" f32 [1 x cols]
|
||||
* is present, and G_s a stage of disjoint Givens rotations -- TABLE "t.pairs" i32
|
||||
* [S x cols] lists stage s's pairs as (pairs[s][2p], pairs[s][2p+1]), TABLE "t.angle"
|
||||
* f32 [S x cols/2] their angles, and a row vector's pair (a, b) at angle t becomes
|
||||
* (a cos t + b sin t, b cos t - a sin t). ParoQuant's scaled pairwise rotation.
|
||||
* A weight whose row parts were rotated independently (a fused gate_up, a fused
|
||||
* q|k|v: each projection has its own rotation) carries P parts: TABLE "t.part" i32
|
||||
* [1 x P] holds the end row (exclusive) of each part, and the other tables stack the
|
||||
* parts in order -- t.pairs and t.angle S rows a part (P*S rows), t.scale one row a
|
||||
* part (P rows). Without "t.part" the weight is one part. The stages of a part are
|
||||
* applied in table order, and a part's pairs address columns of the whole row.
|
||||
* TABLE "t.dense" f16 [P * cols/128 x 128*128], where a weight carries it, is the same
|
||||
* rotation composed: row p * (cols/128) + g holds part p's stages over the 128 columns
|
||||
* of group g as one matrix, element j * 128 + i the output j for the unit input e_i,
|
||||
* composed exactly (f64) and rounded to f16. It is stored because a kernel that
|
||||
* applies the rotation as a matrix must not compute one at load (rad_abi.h).
|
||||
*
|
||||
* Pure C, header-only, like the rest of abi/.
|
||||
*/
|
||||
#ifndef RAD_ENCODING_H
|
||||
#define RAD_ENCODING_H
|
||||
|
||||
#include "rad_types.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
enum { RAD_ENC_MAX_PLANES = 8, RAD_ENC_STR = 24 };
|
||||
|
||||
enum { RAD_PLANE_TILED = 0, RAD_PLANE_TABLE = 1 };
|
||||
|
||||
typedef struct RadEncPlane {
|
||||
char role[RAD_ENC_STR]; /* "codes", "scale", "scale.1", "zero", "min", "grid", "t.perm" */
|
||||
uint32_t dtype; /* a core dtype -- never a plugin-private one */
|
||||
uint32_t kind; /* RAD_PLANE_TILED | RAD_PLANE_TABLE */
|
||||
int64_t block[2]; /* TILED: logical rows x cols one element covers; 0 = whole */
|
||||
int64_t extent[2]; /* TABLE: the plane's own rows x cols */
|
||||
} RadEncPlane;
|
||||
|
||||
typedef struct RadEncoding {
|
||||
char scheme[RAD_ENC_STR]; /* "plain" | "affine" | a quantiser's own */
|
||||
char transform[RAD_ENC_STR]; /* "" | "fwhtN" | "perm" | "givens" */
|
||||
int32_t n_planes;
|
||||
int32_t reserved;
|
||||
RadEncPlane plane[RAD_ENC_MAX_PLANES];
|
||||
} RadEncoding;
|
||||
|
||||
/* ================================================================== building one */
|
||||
|
||||
static inline void rad_enc_copy_str(char* dst, const char* src) {
|
||||
size_t n = src ? strlen(src) : 0;
|
||||
if (n >= RAD_ENC_STR) n = RAD_ENC_STR - 1;
|
||||
memset(dst, 0, RAD_ENC_STR);
|
||||
if (n) memcpy(dst, src, n);
|
||||
}
|
||||
|
||||
static inline void rad_enc_clear(RadEncoding* e) { memset(e, 0, sizeof *e); }
|
||||
|
||||
/* Append a TILED plane. Returns its index, or -1 when the encoding is full. */
|
||||
static inline int rad_enc_add_plane(RadEncoding* e, const char* role, uint32_t dtype,
|
||||
int64_t block_rows, int64_t block_cols) {
|
||||
RadEncPlane* p;
|
||||
if (e->n_planes >= RAD_ENC_MAX_PLANES) return -1;
|
||||
p = &e->plane[e->n_planes];
|
||||
memset(p, 0, sizeof *p);
|
||||
rad_enc_copy_str(p->role, role);
|
||||
p->dtype = dtype;
|
||||
p->kind = RAD_PLANE_TILED;
|
||||
p->block[0] = block_rows;
|
||||
p->block[1] = block_cols;
|
||||
return e->n_planes++;
|
||||
}
|
||||
|
||||
/* Append a TABLE plane of its own [rows x cols]. */
|
||||
static inline int rad_enc_add_table(RadEncoding* e, const char* role, uint32_t dtype,
|
||||
int64_t rows, int64_t cols) {
|
||||
const int i = rad_enc_add_plane(e, role, dtype, 0, 0);
|
||||
if (i < 0) return i;
|
||||
e->plane[i].kind = RAD_PLANE_TABLE;
|
||||
e->plane[i].extent[0] = rows;
|
||||
e->plane[i].extent[1] = cols;
|
||||
return i;
|
||||
}
|
||||
|
||||
/* A weight stored as it is: one plane of `dtype`, one element a value. */
|
||||
static inline RadEncoding rad_enc_plain(uint32_t dtype) {
|
||||
RadEncoding e;
|
||||
rad_enc_clear(&e);
|
||||
rad_enc_copy_str(e.scheme, "plain");
|
||||
rad_enc_add_plane(&e, "codes", dtype, 1, 1);
|
||||
return e;
|
||||
}
|
||||
|
||||
/* value = code * scale, one scale per [block_rows x block_cols]. Further planes go on with
|
||||
* rad_enc_add_plane / rad_enc_add_table, and a transform with
|
||||
* rad_enc_copy_str(e.transform, ...). */
|
||||
static inline RadEncoding rad_enc_affine(uint32_t codes, uint32_t scale, int64_t block_rows,
|
||||
int64_t block_cols) {
|
||||
RadEncoding e;
|
||||
rad_enc_clear(&e);
|
||||
rad_enc_copy_str(e.scheme, "affine");
|
||||
rad_enc_add_plane(&e, "codes", codes, 1, 1);
|
||||
rad_enc_add_plane(&e, "scale", scale, block_rows, block_cols);
|
||||
return e;
|
||||
}
|
||||
|
||||
/* ================================================================== reading one */
|
||||
|
||||
static inline int rad_enc_is(const RadEncoding* e, const char* scheme) {
|
||||
return e && strncmp(e->scheme, scheme, RAD_ENC_STR) == 0;
|
||||
}
|
||||
|
||||
/* The index of the plane with this role, or -1. */
|
||||
static inline int rad_enc_find(const RadEncoding* e, const char* role) {
|
||||
int i;
|
||||
if (!e || !role) return -1;
|
||||
for (i = 0; i < e->n_planes; ++i)
|
||||
if (strncmp(e->plane[i].role, role, RAD_ENC_STR) == 0) return i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* The plane with this role, or null. */
|
||||
static inline const RadEncPlane* rad_enc_plane(const RadEncoding* e, const char* role) {
|
||||
const int i = rad_enc_find(e, role);
|
||||
return i < 0 ? 0 : &e->plane[i];
|
||||
}
|
||||
|
||||
/* The index of level `level` of a multiplied chain -- "scale", "scale.1", "scale.2" -- or -1. */
|
||||
static inline int rad_enc_find_level(const RadEncoding* e, const char* base, int level) {
|
||||
char r[RAD_ENC_STR];
|
||||
if (level == 0) return rad_enc_find(e, base);
|
||||
snprintf(r, sizeof r, "%s.%d", base, level);
|
||||
return rad_enc_find(e, r);
|
||||
}
|
||||
|
||||
/* Does `role` belong to the chain `base` ("scale" -> scale, scale.1, ...)? */
|
||||
static inline int rad_enc_role_in_chain(const char* role, const char* base) {
|
||||
const size_t n = strlen(base);
|
||||
int lv = 0;
|
||||
if (strncmp(role, base, n) != 0) return 0;
|
||||
if (role[n] == 0) return 1;
|
||||
return role[n] == '.' && sscanf(role + n + 1, "%d", &lv) == 1 && lv > 0;
|
||||
}
|
||||
|
||||
/* The order N of an "fwhtN" transform, 0 when the transform is not one, -1 when it is malformed. */
|
||||
static inline int64_t rad_enc_fwht(const RadEncoding* e) {
|
||||
long long n = 0;
|
||||
if (!e || strncmp(e->transform, "fwht", 4) != 0) return 0;
|
||||
if (sscanf(e->transform + 4, "%lld", &n) != 1 || n < 2 || (n & (n - 1)) != 0) return -1;
|
||||
return (int64_t)n;
|
||||
}
|
||||
|
||||
/* The number of independently rotated row parts of a "givens" weight: the width of its "t.part"
|
||||
* table, or 1 without one. 0 when the table is malformed. */
|
||||
static inline int64_t rad_enc_givens_parts(const RadEncoding* e) {
|
||||
const int i = rad_enc_find(e, "t.part");
|
||||
if (i < 0) return 1;
|
||||
return e->plane[i].kind == RAD_PLANE_TABLE && e->plane[i].extent[0] == 1 &&
|
||||
e->plane[i].extent[1] >= 1 ? e->plane[i].extent[1] : 0;
|
||||
}
|
||||
|
||||
/* Byte-for-byte equality. Valid because the strings are always zero-padded, so memcmp sees only
|
||||
* meaningful bytes. */
|
||||
static inline int rad_enc_equal(const RadEncoding* a, const RadEncoding* b) {
|
||||
return a && b && memcmp(a, b, sizeof *a) == 0;
|
||||
}
|
||||
|
||||
/* ================================================================== 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")) {
|
||||
const int ip = rad_enc_find(e, "t.pairs"), ia = rad_enc_find(e, "t.angle");
|
||||
const int is = rad_enc_find(e, "t.scale");
|
||||
const int64_t np = rad_enc_givens_parts(e);
|
||||
if (ip <= 0 || ia <= 0 || np < 1) return 0;
|
||||
if (e->plane[ip].kind != RAD_PLANE_TABLE || e->plane[ia].kind != RAD_PLANE_TABLE) return 0;
|
||||
if (e->plane[ip].extent[0] % np || e->plane[ia].extent[0] != e->plane[ip].extent[0]) return 0;
|
||||
if (e->plane[ia].extent[1] * 2 != e->plane[ip].extent[1]) return 0;
|
||||
if (is > 0 && (e->plane[is].kind != RAD_PLANE_TABLE || e->plane[is].extent[0] != np ||
|
||||
e->plane[is].extent[1] != e->plane[ip].extent[1])) return 0;
|
||||
{
|
||||
const int id = rad_enc_find(e, "t.dense");
|
||||
if (id > 0 && (e->plane[id].kind != RAD_PLANE_TABLE || e->plane[id].dtype != RAD_F16 ||
|
||||
e->plane[ip].extent[1] % 128 ||
|
||||
e->plane[id].extent[0] != np * (e->plane[ip].extent[1] / 128) ||
|
||||
e->plane[id].extent[1] != 128 * 128)) return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* ================================================================== the canonical spelling
|
||||
*
|
||||
* What a person, a log line and rad-info read. Kernels read the struct.
|
||||
*
|
||||
* plain <dtype> bf16
|
||||
* affine, codes and scales <codes>*<scale>[RxC]*<scale.1>[RxC] fp4_e2m1*fp8_e4m3[1x16]*f32[*x*]
|
||||
* with an integer zero ...-<zero>[RxC] u2*f16[1x128]-u8[1x128]
|
||||
* anything else <scheme>:<role>=<dtype><shape>,... affine:codes=u4[1x1],...
|
||||
* and a transform .../<transform> i4*bf16[1x128]/fwht128
|
||||
*
|
||||
* A block extent of 0 -- the whole extent -- is written `*`, and a TABLE plane's shape is written
|
||||
* `{RxC}`. Returns the length written, like snprintf; the output is always terminated. */
|
||||
static inline int rad_enc_shape_str(const RadEncPlane* p, char* buf, size_t n) {
|
||||
char r[24], c[24];
|
||||
if (p->kind == RAD_PLANE_TABLE)
|
||||
return snprintf(buf, n, "{%lldx%lld}", (long long)p->extent[0], (long long)p->extent[1]);
|
||||
if (p->block[0] > 0) snprintf(r, sizeof r, "%lld", (long long)p->block[0]);
|
||||
else snprintf(r, sizeof r, "*");
|
||||
if (p->block[1] > 0) snprintf(c, sizeof c, "%lld", (long long)p->block[1]);
|
||||
else snprintf(c, sizeof c, "*");
|
||||
return snprintf(buf, n, "[%sx%s]", r, c);
|
||||
}
|
||||
|
||||
/* Codes, a scale chain and at most an integer zero: the shape that has a short spelling. */
|
||||
static inline int rad_enc_is_simple_affine(const RadEncoding* e) {
|
||||
int i, lv;
|
||||
if (!rad_enc_is(e, "affine") || e->plane[0].block[1] != 1) return 0;
|
||||
for (i = 1; i < e->n_planes; ++i) {
|
||||
const char* r = e->plane[i].role;
|
||||
if (!rad_enc_role_in_chain(r, "scale") && strncmp(r, "zero", RAD_ENC_STR) != 0 &&
|
||||
strncmp(r, "t.", 2) != 0) return 0;
|
||||
}
|
||||
/* and the scales in level order, so the spelling is read the way it is multiplied */
|
||||
for (i = 1, lv = 0; i < e->n_planes; ++i) {
|
||||
if (!rad_enc_role_in_chain(e->plane[i].role, "scale")) continue;
|
||||
if (rad_enc_find_level(e, "scale", lv++) != i) return 0;
|
||||
}
|
||||
return lv > 0;
|
||||
}
|
||||
|
||||
static inline int rad_enc_format(const RadEncoding* e, char* buf, size_t n) {
|
||||
char shp[64];
|
||||
size_t at = 0;
|
||||
int i;
|
||||
#define RAD_ENC_PUT(...) \
|
||||
do { \
|
||||
int w_ = snprintf(buf + (at < n ? at : n), at < n ? n - at : 0, __VA_ARGS__); \
|
||||
if (w_ > 0) at += (size_t)w_; \
|
||||
} while (0)
|
||||
if (!buf || n == 0) return 0;
|
||||
buf[0] = 0;
|
||||
if (!e || e->n_planes < 1) {
|
||||
RAD_ENC_PUT("(none)");
|
||||
} else if (rad_enc_is(e, "plain") && e->n_planes == 1) {
|
||||
RAD_ENC_PUT("%s", rad_dtype_name(e->plane[0].dtype));
|
||||
} else if (rad_enc_is_simple_affine(e)) {
|
||||
RAD_ENC_PUT("%s", rad_dtype_name(e->plane[0].dtype));
|
||||
for (i = 1; i < e->n_planes; ++i) {
|
||||
if (!rad_enc_role_in_chain(e->plane[i].role, "scale")) continue;
|
||||
rad_enc_shape_str(&e->plane[i], shp, sizeof shp);
|
||||
RAD_ENC_PUT("*%s%s", rad_dtype_name(e->plane[i].dtype), shp);
|
||||
}
|
||||
i = rad_enc_find(e, "zero");
|
||||
if (i > 0) {
|
||||
rad_enc_shape_str(&e->plane[i], shp, sizeof shp);
|
||||
RAD_ENC_PUT("-%s%s", rad_dtype_name(e->plane[i].dtype), shp);
|
||||
}
|
||||
} else {
|
||||
RAD_ENC_PUT("%s:", e->scheme);
|
||||
for (i = 0; i < e->n_planes; ++i) {
|
||||
rad_enc_shape_str(&e->plane[i], shp, sizeof shp);
|
||||
RAD_ENC_PUT("%s%s=%s%s", i ? "," : "", e->plane[i].role,
|
||||
rad_dtype_name(e->plane[i].dtype), shp);
|
||||
}
|
||||
}
|
||||
if (e && e->transform[0]) RAD_ENC_PUT("/%s", e->transform);
|
||||
#undef RAD_ENC_PUT
|
||||
return (int)at;
|
||||
}
|
||||
|
||||
#ifdef __cplusplus
|
||||
} /* extern "C" */
|
||||
#endif
|
||||
|
||||
#endif /* RAD_ENCODING_H */
|
||||
@@ -0,0 +1,169 @@
|
||||
/* 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 format version. A file in any other is refused with an instruction to convert
|
||||
* again, so there is a single reader with a single set of invariants. */
|
||||
#ifndef RAD_FORMAT_H
|
||||
#define RAD_FORMAT_H
|
||||
|
||||
#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): a
|
||||
* calibration set routes differently from decoding, so this gives only a small residency hit-rate
|
||||
* gain over starting cold. */
|
||||
typedef struct RadFileProfile {
|
||||
int32_t layer;
|
||||
int32_t expert;
|
||||
float share; /* fraction of tokens routed here in the calibration set */
|
||||
float reserved;
|
||||
} RadFileProfile;
|
||||
|
||||
/* ------------------------------------------------------------------ vocab */
|
||||
/* rad-convert interprets tokenizer.json and bakes the result here, rather than hashing the file
|
||||
* against a hardcoded enum as llama.cpp does (spec §12). */
|
||||
enum { RAD_TOK_BPE = 1, RAD_TOK_UNIGRAM = 2, RAD_TOK_WORDPIECE = 3, RAD_TOK_RWKV = 4 };
|
||||
|
||||
/* Normaliser / pre-tokeniser / decoder steps, in declared order. */
|
||||
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 flags; /* RAD_VOCAB_*; zero in a file written before the field existed */
|
||||
uint64_t reserved[3];
|
||||
} RadVocabHeader;
|
||||
|
||||
/* BPE: a pre-token that is already a vocabulary entry is emitted whole instead of merged
|
||||
* (tokenizers' `ignore_merges`). LFM2's vocabulary sets it. */
|
||||
enum { RAD_VOCAB_IGNORE_MERGES = 1u << 0 };
|
||||
|
||||
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 */
|
||||
@@ -0,0 +1,49 @@
|
||||
#ifndef RAD_PHILOX_H
|
||||
#define RAD_PHILOX_H
|
||||
|
||||
/* Counter-based Gaussian noise, the single definition every kernel library uses, so an image's
|
||||
* starting latent depends only on its seed: not on the batch it shares a pass with, the rank
|
||||
* count, or the order its rows are visited in.
|
||||
*
|
||||
* Element e of a seed's stream is Philox4x32-10 at counter (e / 4, 0) keyed by the 64-bit seed,
|
||||
* its four words made uniform in (0, 1) as ((w >> 8) + 0.5) * 2^-24 and paired by Box-Muller --
|
||||
* words 0 and 1 give elements 4g and 4g+1 (r cos t, r sin t), words 2 and 3 give 4g+2 and 4g+3.
|
||||
* f32 throughout. A library's libm may differ from another's in the last place of log, cos and
|
||||
* sin, so two libraries agree to a tolerance and each agrees with itself exactly. */
|
||||
#include <stdint.h>
|
||||
#include <math.h>
|
||||
|
||||
#if defined(__HIPCC__)
|
||||
#define RAD_PHILOX_HD __host__ __device__ __forceinline__
|
||||
#else
|
||||
#define RAD_PHILOX_HD static inline
|
||||
#endif
|
||||
|
||||
RAD_PHILOX_HD void rad_philox4x32_10(uint32_t c[4], uint32_t k0, uint32_t k1) {
|
||||
const uint32_t M0 = 0xD2511F53u, M1 = 0xCD9E8D57u, W0 = 0x9E3779B9u, W1 = 0xBB67AE85u;
|
||||
for (int r = 0; r < 10; ++r) {
|
||||
const uint64_t p0 = (uint64_t)M0 * c[0], p1 = (uint64_t)M1 * c[2];
|
||||
const uint32_t hi0 = (uint32_t)(p0 >> 32), lo0 = (uint32_t)p0;
|
||||
const uint32_t hi1 = (uint32_t)(p1 >> 32), lo1 = (uint32_t)p1;
|
||||
const uint32_t n0 = hi1 ^ c[1] ^ k0, n2 = hi0 ^ c[3] ^ k1;
|
||||
c[0] = n0; c[1] = lo1; c[2] = n2; c[3] = lo0;
|
||||
k0 += W0;
|
||||
k1 += W1;
|
||||
}
|
||||
}
|
||||
|
||||
/* Element `e` of the standard-normal stream of `seed`. */
|
||||
RAD_PHILOX_HD float rad_philox_normal(uint64_t seed, uint64_t e) {
|
||||
const uint64_t g = e >> 2;
|
||||
uint32_t c[4] = { (uint32_t)g, (uint32_t)(g >> 32), 0u, 0u };
|
||||
rad_philox4x32_10(c, (uint32_t)seed, (uint32_t)(seed >> 32));
|
||||
const int j = (int)(e & 3u);
|
||||
const uint32_t wa = c[(j >> 1) * 2], wb = c[(j >> 1) * 2 + 1];
|
||||
const float ua = ((float)(wa >> 8) + 0.5f) * (1.0f / 16777216.0f);
|
||||
const float ub = ((float)(wb >> 8) + 0.5f) * (1.0f / 16777216.0f);
|
||||
const float r = sqrtf(-2.0f * logf(ua));
|
||||
const float t = 6.28318530717958647692f * ub;
|
||||
return (j & 1) ? r * sinf(t) : r * cosf(t);
|
||||
}
|
||||
|
||||
#endif /* RAD_PHILOX_H */
|
||||
@@ -0,0 +1,197 @@
|
||||
/* rad_planes.h -- the joined form of a weight operand that takes several planes, for kernels that
|
||||
* read the planes as the container stores them. spec.md §4.3.
|
||||
*
|
||||
* A weight can be declared over several planes of one stored tensor (RadWeightDecl::planes:
|
||||
* "scale,zero", "codes,table", or every plane of an fp8 lm head), and it reaches a kernel as one
|
||||
* operand, so something has to say where each plane lies. A kernel that wants the planes
|
||||
* rearranged for its own reads says so in its layout hook (rad_abi.h, RadLayoutFn). One that reads
|
||||
* them unchanged uses this form instead:
|
||||
*
|
||||
* [header][entry 0][entry 1]... padded to RAD_PLANES_ALIGN
|
||||
* plane 0 dense rows, padded to RAD_PLANES_ALIGN
|
||||
* plane 1 ...
|
||||
*
|
||||
* The header and the entries describe each selected plane (its role, dtype, block, this rank's
|
||||
* extents and where its bytes start), so a launch finds its planes from the operand alone, without
|
||||
* the encoding. Each plane is the canonical bytes (rad_encoding.h), unchanged: the conversion is a
|
||||
* copy and its inverse is one too.
|
||||
*
|
||||
* A library implements its layout, relayout and unrelayout hooks with the three functions below
|
||||
* and reads at launch with rad_planes_find. Every library that uses this form stores the same bytes
|
||||
* under the same tag, so two such libraries serving different bands of one op read one stored
|
||||
* weight. A selection of one plane is not joined: rad_planes_layout declines it, and the weight is
|
||||
* stored as it is.
|
||||
*
|
||||
* Pure C, header-only, like the rest of abi/.
|
||||
*/
|
||||
#ifndef RAD_PLANES_H
|
||||
#define RAD_PLANES_H
|
||||
|
||||
#include "rad_abi.h"
|
||||
#include "rad_encoding.h"
|
||||
|
||||
#include <string.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define RAD_PLANES_TAG "rad.planes"
|
||||
#define RAD_PLANES_MAGIC 0x534e4c50u /* "PLNS" */
|
||||
enum { RAD_PLANES_ALIGN = 64 };
|
||||
|
||||
/* One selected plane. `offset` counts from the start of the joined bytes. */
|
||||
typedef struct RadPlanesEntry {
|
||||
char role[RAD_ENC_STR];
|
||||
uint32_t dtype;
|
||||
uint32_t kind; /* RAD_PLANE_TILED | RAD_PLANE_TABLE */
|
||||
int64_t block[2]; /* the encoding's block (TILED) or extent (TABLE) */
|
||||
int64_t rows, cols; /* this rank's extents of the plane, in its own elements */
|
||||
int64_t row_bytes; /* rad_dtype_bytes(dtype, cols): every row starts on a byte */
|
||||
int64_t offset;
|
||||
} RadPlanesEntry;
|
||||
|
||||
typedef struct RadPlanesHeader {
|
||||
uint32_t magic;
|
||||
int32_t n_planes;
|
||||
char transform[RAD_ENC_STR]; /* the encoding's, for a kernel that checks it */
|
||||
int64_t bytes; /* the whole joined form, padding included */
|
||||
} RadPlanesHeader;
|
||||
|
||||
static inline int64_t rad_planes_round(int64_t n) {
|
||||
return (n + RAD_PLANES_ALIGN - 1) / RAD_PLANES_ALIGN * RAD_PLANES_ALIGN;
|
||||
}
|
||||
|
||||
/* The joined form's entries for the planes a layout hook was handed, and its total size; -1 when
|
||||
* the planes cannot be joined (no planes, more than RAD_ENC_MAX_PLANES, an index outside the
|
||||
* encoding, or a plane with no byte size). */
|
||||
static inline int64_t rad_planes_plan(const RadEncoding* enc, const int* sel,
|
||||
const RadTensor* planes, int n_planes, RadPlanesEntry* e) {
|
||||
int64_t off;
|
||||
int i;
|
||||
if (!enc || !sel || !planes || n_planes < 1 || n_planes > RAD_ENC_MAX_PLANES) return -1;
|
||||
off = rad_planes_round((int64_t)sizeof(RadPlanesHeader) +
|
||||
(int64_t)n_planes * (int64_t)sizeof(RadPlanesEntry));
|
||||
for (i = 0; i < n_planes; ++i) {
|
||||
const RadEncPlane* p;
|
||||
if (sel[i] < 0 || sel[i] >= enc->n_planes) return -1;
|
||||
p = &enc->plane[sel[i]];
|
||||
memset(&e[i], 0, sizeof e[i]);
|
||||
memcpy(e[i].role, p->role, RAD_ENC_STR);
|
||||
e[i].dtype = planes[i].dtype;
|
||||
e[i].kind = p->kind;
|
||||
e[i].block[0] = p->kind == RAD_PLANE_TABLE ? p->extent[0] : p->block[0];
|
||||
e[i].block[1] = p->kind == RAD_PLANE_TABLE ? p->extent[1] : p->block[1];
|
||||
e[i].rows = planes[i].rank >= 2 ? planes[i].shape[0] : 1;
|
||||
e[i].cols = planes[i].rank >= 2 ? planes[i].shape[1]
|
||||
: (planes[i].rank == 1 ? planes[i].shape[0] : 0);
|
||||
e[i].row_bytes = rad_dtype_bytes(e[i].dtype, e[i].cols);
|
||||
if (e[i].rows < 0 || e[i].row_bytes <= 0) return -1;
|
||||
e[i].offset = off;
|
||||
off = rad_planes_round(off + e[i].rows * e[i].row_bytes);
|
||||
}
|
||||
return off;
|
||||
}
|
||||
|
||||
/* RadLayoutFn's answer for the joined form. RAD_E_UNSUPPORTED for a single plane, which is stored
|
||||
* as it is. The stored dtype is the first plane's, so a launch that dispatches on the operand's
|
||||
* dtype still sees the codes' (or the scale's) type; the stored shape is the byte count. */
|
||||
static inline int rad_planes_layout(const RadEncoding* enc, const int* sel, const RadTensor* planes,
|
||||
int n_planes, RadLayout* out) {
|
||||
RadPlanesEntry e[RAD_ENC_MAX_PLANES];
|
||||
int64_t bytes;
|
||||
if (n_planes == 1) return RAD_E_UNSUPPORTED;
|
||||
bytes = rad_planes_plan(enc, sel, planes, n_planes, e);
|
||||
if (bytes < 0 || !out) return RAD_E_SHAPE;
|
||||
memset(out, 0, sizeof *out);
|
||||
out->tag = RAD_PLANES_TAG;
|
||||
out->dtype = planes[0].dtype;
|
||||
out->rank = 1;
|
||||
out->shape[0] = bytes;
|
||||
out->align = RAD_PLANES_ALIGN;
|
||||
out->bytes = bytes;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* RadRelayoutFn: the header, the entries and each plane's rows, copied. The planes are dense, as
|
||||
* the loader hands them. */
|
||||
static inline int rad_planes_relayout(const RadEncoding* enc, const int* sel,
|
||||
const RadTensor* planes, int n_planes, void* dst,
|
||||
int64_t dst_bytes) {
|
||||
RadPlanesEntry e[RAD_ENC_MAX_PLANES];
|
||||
RadPlanesHeader h;
|
||||
uint8_t* d = (uint8_t*)dst;
|
||||
int i;
|
||||
const int64_t bytes = rad_planes_plan(enc, sel, planes, n_planes, e);
|
||||
if (bytes < 0 || !dst || dst_bytes < bytes) return RAD_E_SHAPE;
|
||||
memset(d, 0, (size_t)bytes);
|
||||
memset(&h, 0, sizeof h);
|
||||
h.magic = RAD_PLANES_MAGIC;
|
||||
h.n_planes = n_planes;
|
||||
memcpy(h.transform, enc->transform, RAD_ENC_STR);
|
||||
h.bytes = bytes;
|
||||
memcpy(d, &h, sizeof h);
|
||||
memcpy(d + sizeof h, e, (size_t)n_planes * sizeof e[0]);
|
||||
for (i = 0; i < n_planes; ++i) {
|
||||
if (!planes[i].data && e[i].rows * e[i].row_bytes > 0) return RAD_E_INVAL;
|
||||
if (e[i].rows * e[i].row_bytes > 0)
|
||||
memcpy(d + e[i].offset, planes[i].data, (size_t)(e[i].rows * e[i].row_bytes));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* RadUnrelayoutFn: the planes back out of the joined form, into the buffers `planes` carry. */
|
||||
static inline int rad_planes_unrelayout(const RadEncoding* enc, const int* sel, const void* src,
|
||||
int64_t src_bytes, const RadTensor* planes, int n_planes) {
|
||||
RadPlanesEntry e[RAD_ENC_MAX_PLANES];
|
||||
const uint8_t* s = (const uint8_t*)src;
|
||||
int i;
|
||||
const int64_t bytes = rad_planes_plan(enc, sel, planes, n_planes, e);
|
||||
if (bytes < 0 || !src || src_bytes < bytes) return RAD_E_SHAPE;
|
||||
for (i = 0; i < n_planes; ++i) {
|
||||
if (!planes[i].data && e[i].rows * e[i].row_bytes > 0) return RAD_E_INVAL;
|
||||
if (e[i].rows * e[i].row_bytes > 0)
|
||||
memcpy(planes[i].data, s + e[i].offset, (size_t)(e[i].rows * e[i].row_bytes));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ================================================================== reading one at launch */
|
||||
|
||||
/* The joined form's header, or null when `base` does not hold one. */
|
||||
static inline const RadPlanesHeader* rad_planes_header(const void* base) {
|
||||
const RadPlanesHeader* h = (const RadPlanesHeader*)base;
|
||||
if (!h || h->magic != RAD_PLANES_MAGIC || h->n_planes < 1 ||
|
||||
h->n_planes > RAD_ENC_MAX_PLANES)
|
||||
return 0;
|
||||
return h;
|
||||
}
|
||||
|
||||
/* Entry `i`, or null. */
|
||||
static inline const RadPlanesEntry* rad_planes_entry(const void* base, int i) {
|
||||
const RadPlanesHeader* h = rad_planes_header(base);
|
||||
if (!h || i < 0 || i >= h->n_planes) return 0;
|
||||
return (const RadPlanesEntry*)((const uint8_t*)base + sizeof(RadPlanesHeader)) + i;
|
||||
}
|
||||
|
||||
/* The plane with this role: its bytes, and its entry through `out` when given; null when the
|
||||
* joined form has no such plane. */
|
||||
static inline const void* rad_planes_find(const void* base, const char* role,
|
||||
const RadPlanesEntry** out) {
|
||||
const RadPlanesHeader* h = rad_planes_header(base);
|
||||
int i;
|
||||
if (!h || !role) return 0;
|
||||
for (i = 0; i < h->n_planes; ++i) {
|
||||
const RadPlanesEntry* e = rad_planes_entry(base, i);
|
||||
if (strncmp(e->role, role, RAD_ENC_STR) == 0) {
|
||||
if (out) *out = e;
|
||||
return (const uint8_t*)base + e->offset;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
#ifdef __cplusplus
|
||||
} /* extern "C" */
|
||||
#endif
|
||||
#endif /* RAD_PLANES_H */
|
||||
@@ -0,0 +1,541 @@
|
||||
/* rad_plugin.h -- everything a kernel or architecture plugin needs and cannot link.
|
||||
*
|
||||
* ===================================================================== WHY THIS FILE EXISTS
|
||||
*
|
||||
* A plugin exports the symbols in rad_abi.h and links nothing of radiance's, so it has only the
|
||||
* raw structs. This header supplies the helpers every plugin would otherwise rewrite: an
|
||||
* optional-operand fetch, parameters with defaults, row pitch, and f32<->bf16/f16/fp8
|
||||
* conversions.
|
||||
*
|
||||
* Two of them are contracts, not conveniences. The narrowing conversions define what a result is:
|
||||
* libref's contract is f32 accumulation, IEEE round-to-nearest-even, no FMA and no reassociation,
|
||||
* and a plugin whose bf16 rounding truncates cannot be checked against the reference. And an
|
||||
* absent optional operand is a null RadTensor.data, not a short operand count; getting that wrong
|
||||
* silently shifts every later operand by one.
|
||||
*
|
||||
* ===================================================================== WHAT IS AND IS NOT HERE
|
||||
*
|
||||
* Here: pure, total, header-only functions over the ABI's own types. Nothing allocates, holds
|
||||
* state or calls back into the core, and nothing may start to.
|
||||
*
|
||||
* Not here: anything that needs the core. Device allocations, streams and builder handles come
|
||||
* from rad_device.h / rad_builder.h / rad_runtime.h, which the host exports; the loader's ABI
|
||||
* check covers them.
|
||||
*
|
||||
* This header is optional. A plugin that includes only rad_abi.h is complete; this is
|
||||
* convenience plus one shared definition of the rounding.
|
||||
*
|
||||
* Pure C, like the rest of abi/. See spec.md 2.
|
||||
*/
|
||||
#ifndef RAD_PLUGIN_H
|
||||
#define RAD_PLUGIN_H
|
||||
|
||||
#include "rad_abi.h"
|
||||
|
||||
#include <string.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* ================================================================== parameters
|
||||
*
|
||||
* Two families: `launch` and `scratch` get a RadArgs; `layout`, `relayout`, `unrelayout` and
|
||||
* `opd_shape` get a bare (const RadParam*, int) pair with no tensors. */
|
||||
|
||||
static inline const RadParam* rad_param_find(const RadParam* p, int n_p, const char* key) {
|
||||
if (!p || !key) return 0;
|
||||
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 not an int.
|
||||
*
|
||||
* A range is deliberately not accepted: by the time a kernel runs, the ranged axis has been
|
||||
* resolved to a value, so a range reaching a launch is a selection bug that returning its low
|
||||
* bound would hide. */
|
||||
static inline long long rad_param_geti(const RadParam* p, int n_p, const char* key,
|
||||
long long dflt) {
|
||||
const RadParam* f = rad_param_find(p, n_p, key);
|
||||
return (f && f->kind == RAD_P_INT) ? f->ival : dflt;
|
||||
}
|
||||
|
||||
/* The same read for a shape hook, the one place a range is legitimate; it reads as its high
|
||||
* bound. `opd_shape` sizes buffers before selection has collapsed anything, so over a banded op it
|
||||
* describes the whole band, and the high end covers the low. */
|
||||
static inline long long rad_param_getdim(const RadParam* p, int n_p, const char* key,
|
||||
long long dflt) {
|
||||
const RadParam* f = rad_param_find(p, n_p, key);
|
||||
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. */
|
||||
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: an optional operand a call does not pass is a RadTensor whose `data`
|
||||
* is null, not a shorter `n_t`. Operands are positional, so treating absence as a shorter array
|
||||
* would read operand i+1 for operand i and produce wrong numbers without a fault.
|
||||
*
|
||||
* There is always one entry per schema operand. This returns null both past the end and for a
|
||||
* null `data`; a caller that sees the former has a schema disagreement, not an absent operand. */
|
||||
static inline const RadTensor* rad_arg_in(const RadArgs* a, int i) {
|
||||
if (!a || !a->t || i < 0 || i >= a->n_t) return 0;
|
||||
return a->t[i].data ? &a->t[i] : 0;
|
||||
}
|
||||
|
||||
|
||||
/* There is deliberately no rad_arg_out. RadArgs::t is a `const RadTensor*`: the descriptors are
|
||||
* const, and a kernel writes an output through the non-const `void* data` inside one, so outputs
|
||||
* are fetched with rad_arg_in too. */
|
||||
|
||||
/* Are the first `n` operands all present? For a launch whose required operands are a prefix. */
|
||||
static inline int rad_args_have(const RadArgs* a, int n) {
|
||||
for (int i = 0; i < n; ++i) if (!rad_arg_in(a, i)) return 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* ================================================================== tensor shape helpers */
|
||||
|
||||
/* [rows..., K] flattened to (M, K): every leading axis is a row count and only the last is
|
||||
* structural, as a row-owning kernel (one workgroup per row) wants. Returns 0 on a rank-0
|
||||
* tensor. */
|
||||
static inline int64_t rad_tensor_rows(const RadTensor* t) {
|
||||
if (!t || t->rank == 0) return 0;
|
||||
int64_t m = 1;
|
||||
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: the stride of the second-to-last axis (the last
|
||||
* extent when contiguous). Strides are in elements, not bytes (rad_types.h). */
|
||||
static inline int64_t rad_tensor_row_pitch(const RadTensor* t) {
|
||||
if (!t || t->rank == 0) return 0;
|
||||
if (t->rank == 1) return t->shape[0];
|
||||
return t->stride[t->rank - 2];
|
||||
}
|
||||
|
||||
/* Is `p` aligned to `bytes`? The ABI does not promise alignment and a constraint row cannot
|
||||
* express it, so a kernel issuing wide loads checks it in the entry point (rad_types.h). */
|
||||
static inline int rad_ptr_aligned(const void* p, int64_t bytes) {
|
||||
return bytes > 0 && ((uintptr_t)p % (uintptr_t)bytes) == 0;
|
||||
}
|
||||
|
||||
/* ================================================================== narrowing conversions
|
||||
*
|
||||
* These define what a result is, so they are stated once here.
|
||||
*
|
||||
* libref's contract, which every kernel is checked against, is f32 accumulation, IEEE
|
||||
* round-to-nearest-ties-to-even, no fused multiply-add and no reassociation; `-ffp-contract=off`
|
||||
* is a correctness flag in this project. A plugin whose bf16 narrowing truncates is off by up to
|
||||
* one ulp on every element and cannot be checked against the reference.
|
||||
*
|
||||
* Every conversion is exact when widening and RTNE when narrowing, and keeps subnormals rather
|
||||
* than flushing them: the hardware decodes subnormals, and flushing loses the smallest block of
|
||||
* every quantised weight. */
|
||||
|
||||
static inline float rad_bf16_to_f32(uint16_t h) {
|
||||
uint32_t u = (uint32_t)h << 16;
|
||||
float f;
|
||||
memcpy(&f, &u, 4);
|
||||
return f;
|
||||
}
|
||||
|
||||
/* `(u >> 16) & 1` is the tie-break: it adds one more than the halfway point when the surviving
|
||||
* bit is odd, so ties go to even. Overflow carries into 0x7f80, the bf16 infinity. A NaN is forced
|
||||
* quiet so it cannot round into an infinity. */
|
||||
static inline uint16_t rad_f32_to_bf16(float f) {
|
||||
uint32_t u;
|
||||
memcpy(&u, &f, 4);
|
||||
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 a hardware
|
||||
* convert whose rounding mode a caller could have changed. */
|
||||
static inline uint16_t rad_f32_to_f16(float f) {
|
||||
uint32_t u;
|
||||
memcpy(&u, &f, 4);
|
||||
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. The
|
||||
* KV-cache and block-scaled weight format, so the attention oracle and every fp8 GEMM depend on
|
||||
* its rounding. */
|
||||
static inline float rad_fp8e4m3_to_f32(uint8_t b) {
|
||||
uint32_t s = (uint32_t)(b >> 7) << 31;
|
||||
uint32_t e = (uint32_t)(b >> 3) & 0xfu;
|
||||
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: a NaN for one large activation would spread through
|
||||
* the whole row. Every fp8 cast in this project clamps for that reason. */
|
||||
static inline uint8_t rad_f32_to_fp8e4m3(float f) {
|
||||
uint32_t u;
|
||||
memcpy(&u, &f, 4);
|
||||
{
|
||||
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 below half of it (exponent -11 and
|
||||
* below) rounds to zero. Exponent -10 is [2^-10, 2^-9): its tie point 2^-10 rounds to the
|
||||
* even zero and the rest up to 2^-9, which the subnormal branch does with a 24-bit
|
||||
* shift. */
|
||||
if (e < -10) return s;
|
||||
if (e < -6) { /* subnormal fp8 */
|
||||
int sh = -6 - e + 20;
|
||||
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.
|
||||
*
|
||||
* Narrowing rounds to f16 and then drops the low byte. Every e5m2 tie point is an f16 value, so
|
||||
* the f16 step can move `f` onto a tie but never across one; when it lands on a tie, `f`'s side
|
||||
* of it decides, and only an exact tie goes to even. That makes the result one RTNE of `f`. */
|
||||
static inline float rad_fp8e5m2_to_f32(uint8_t b) {
|
||||
return rad_f16_to_f32((uint16_t)((uint16_t)b << 8));
|
||||
}
|
||||
|
||||
static inline uint8_t rad_f32_to_fp8e5m2(float f) {
|
||||
uint16_t h = rad_f32_to_f16(f);
|
||||
uint16_t lo = (uint16_t)(h & 0xffu);
|
||||
uint16_t q = (uint16_t)(h >> 8);
|
||||
/* A NaN keeps its top payload bits and stays quiet; rounding its low byte could carry it out
|
||||
* of the exponent into a zero of the other sign. */
|
||||
if ((h & 0x7fffu) > 0x7c00u) return (uint8_t)(q | 0x02u);
|
||||
if (lo == 0x80u && (h & 0x7c00u) != 0x7c00u) {
|
||||
/* Magnitudes of non-negative floats order as their bit patterns. */
|
||||
float t = rad_f16_to_f32(h);
|
||||
uint32_t uf, ut;
|
||||
memcpy(&uf, &f, 4);
|
||||
memcpy(&ut, &t, 4);
|
||||
uf &= 0x7fffffffu;
|
||||
ut &= 0x7fffffffu;
|
||||
if (uf != ut) return (uint8_t)(uf > ut ? q + 1u : q);
|
||||
}
|
||||
if (lo > 0x80u || (lo == 0x80u && (q & 1u))) ++q;
|
||||
return (uint8_t)q;
|
||||
}
|
||||
|
||||
/* OCP FP4 e2m1: 1-2-1, bias 1, no infinity or NaN; all sixteen codes are numbers, max 6. */
|
||||
static inline float rad_fp4e2m1_to_f32(uint8_t nib) {
|
||||
static const float mag[8] = { 0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f };
|
||||
return (nib & 8u) ? -mag[nib & 7u] : mag[nib & 7u];
|
||||
}
|
||||
|
||||
/* OCP FP6, both forms. No infinity or NaN; e2m3 has bias 1 and max 7.5, e3m2 bias 3 and max 28. */
|
||||
static inline float rad_fp6_to_f32(uint8_t c, int ebits) {
|
||||
const int mbits = 5 - ebits, bias = ebits == 2 ? 1 : 3;
|
||||
const int e = (c >> mbits) & ((1 << ebits) - 1), m = c & ((1 << mbits) - 1);
|
||||
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 the one place the dtype enum and the conversions above
|
||||
* meet. Returns 0 for a dtype it cannot read, which a caller must treat as a refusal, not a value.
|
||||
*
|
||||
* For sub-byte dtypes `i` counts elements from `base`, which is valid only within one row: rows
|
||||
* start on a byte (rad_encoding.h), so a caller crossing rows steps `base` by a row's bytes. */
|
||||
static inline float rad_load_f32(const void* base, uint32_t dtype, int64_t i) {
|
||||
const uint8_t* b8 = (const uint8_t*)base;
|
||||
int sgn = 0;
|
||||
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 chosen bit pattern, masked to
|
||||
* the dtype's width), leaving neighbours in the same byte alone. A signed code is passed as its
|
||||
* value (-8..7 for i4) and stored two's complement. The quantisers' counterpart to rad_load_f32;
|
||||
* nothing rounds here. Returns 0 for a dtype wider than 16 bits. */
|
||||
static inline int rad_store_code(void* base, uint32_t dtype, int64_t i, int code) {
|
||||
const int bits = rad_dtype_bits(dtype);
|
||||
if (bits < 1 || bits > 16) return 0;
|
||||
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;
|
||||
}
|
||||
|
||||
/* `v` rounded to the nearest integer, ties to even, and clamped to [lo, hi]; NaN is 0. Exact and
|
||||
* independent of the rounding mode: a float of magnitude 2^23 or more is already an integer, and
|
||||
* below that its fraction is exact in a double. */
|
||||
static inline double rad_round_even_sat(float v, double lo, double hi) {
|
||||
double d = (double)v, r;
|
||||
if (v != v) return 0.0;
|
||||
if (d >= 8388608.0 || d <= -8388608.0) {
|
||||
r = d;
|
||||
} else {
|
||||
const long long t = (long long)d; /* toward zero */
|
||||
const double f = d - (double)t;
|
||||
long long n = t;
|
||||
if (f > 0.5 || (f == 0.5 && (t & 1))) ++n;
|
||||
else if (f < -0.5 || (f == -0.5 && (t & 1))) --n;
|
||||
r = (double)n;
|
||||
}
|
||||
return r < lo ? lo : (r > hi ? hi : r);
|
||||
}
|
||||
|
||||
/* Store `v` as element `i` of a byte-aligned plane. A float dtype rounds as the narrowings above
|
||||
* do; an integer dtype rounds to nearest, ties to even, and saturates to its range, NaN storing 0.
|
||||
* Sub-byte dtypes are stored with rad_store_code; any other dtype is left unwritten. */
|
||||
static inline void rad_store_f32(void* base, uint32_t dtype, int64_t i, float v) {
|
||||
switch (dtype) {
|
||||
case RAD_F32: ((float*)base)[i] = v; break;
|
||||
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)rad_round_even_sat(v, -128.0, 127.0); break;
|
||||
case RAD_U8: ((uint8_t*)base)[i] = (uint8_t)rad_round_even_sat(v, 0.0, 255.0); break;
|
||||
case RAD_U16:
|
||||
((uint16_t*)base)[i] = (uint16_t)rad_round_even_sat(v, 0.0, 65535.0);
|
||||
break;
|
||||
case RAD_I16:
|
||||
((int16_t*)base)[i] = (int16_t)rad_round_even_sat(v, -32768.0, 32767.0);
|
||||
break;
|
||||
case RAD_I32:
|
||||
((int32_t*)base)[i] = (int32_t)rad_round_even_sat(v, -2147483648.0, 2147483647.0);
|
||||
break;
|
||||
case RAD_U32:
|
||||
((uint32_t*)base)[i] = (uint32_t)rad_round_even_sat(v, 0.0, 4294967295.0);
|
||||
break;
|
||||
case RAD_I64: {
|
||||
/* 2^63 is the first float past the range, so it is compared, not clamped to. */
|
||||
const double r = rad_round_even_sat(v, -9223372036854775808.0, 9223372036854775808.0);
|
||||
((int64_t*)base)[i] = r >= 9223372036854775808.0 ? INT64_MAX : (int64_t)r;
|
||||
break;
|
||||
}
|
||||
case RAD_BOOL: ((uint8_t*)base)[i] = v != 0.0f ? 1u : 0u; break;
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef __cplusplus
|
||||
} /* extern "C" */
|
||||
#endif
|
||||
|
||||
#endif /* RAD_PLUGIN_H */
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
/* 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 the only place a weight's numbers are chosen: a kernel only
|
||||
* rearranges the planes it is given (rad_abi.h, RadRelayoutFn).
|
||||
*
|
||||
* rad-convert drives quantisers through a recipe: ordered rules from a logical weight name to a
|
||||
* 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, then
|
||||
* hands the weight over in row blocks (`row_block`, `quantize`), so a 51 GB table streams.
|
||||
*
|
||||
* Input: the weight's logical name, shape and movement group, and the column importances when the
|
||||
* converter has an imatrix. Other calibration data (a GPTQ Hessian, AutoRound's activations) is an
|
||||
* option the quantiser reads itself (`calib=DIR`); its format is the quantiser's business.
|
||||
*
|
||||
* Output: the canonical planes only, so every kernel library that accepts the encoding and the
|
||||
* core's own decoder can read it. That is how rad-convert measures the error without knowing the
|
||||
* method.
|
||||
*
|
||||
* Pure C, like the rest of abi/.
|
||||
*/
|
||||
#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. Also -1 when `encoding` is asked at declare, before the
|
||||
* group exists, so an encoding may depend on the name and shape but not on these; rad-convert
|
||||
* refuses a quantiser whose answer changes once it is told. */
|
||||
int32_t layer, expert;
|
||||
/* The imatrix's column importances for this weight (the second moment of its input, one per
|
||||
* column), or null when the converter has none. Per expert where the imatrix has that form. */
|
||||
const float* importance;
|
||||
} RadQuantWeight;
|
||||
|
||||
/* 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 a recipe error reported with the weight's name. */
|
||||
typedef int (*RadQuantEncodingFn)(const RadParam* o, int n_o, const RadQuantWeight* w,
|
||||
RadEncoding* out);
|
||||
|
||||
/* The rows one `quantize` call may take: every call but the last gets a multiple of this, starting
|
||||
* on a multiple of it. 0 means the whole weight in one call, needed for any cross-row decision (a
|
||||
* derived per-tensor scale, a learned rotation, a shared Hessian). Must be a multiple of every
|
||||
* TILED plane's block rows. */
|
||||
typedef int64_t (*RadQuantRowBlockFn)(const RadParam* o, int n_o, const RadQuantWeight* w);
|
||||
|
||||
/* Quantise logical rows [row0, row0 + rows) of `w`, given as f32 [rows, cols] in `src`, into the
|
||||
* planes. `planes[i]` points at the element row of plane i that covers logical row `row0` (row
|
||||
* row0 / br for a TILED plane of block rows br; the plane's start for a whole-extent or TABLE
|
||||
* plane), and the call writes exactly the rows its block covers.
|
||||
* The buffers arrive zeroed. `src` may be modified. */
|
||||
typedef int (*RadQuantizeFn)(const RadParam* o, int n_o, const RadQuantWeight* w,
|
||||
float* src, int64_t row0, int64_t rows, void* const* planes);
|
||||
|
||||
/* 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.
|
||||
*
|
||||
* The oracle, rad-kbench and rad-convert's error measurement all read a quantiser's own scheme
|
||||
* through it. The core asks every loaded quantiser that has one, in load order, and takes the
|
||||
* first answer that is not RAD_E_UNSUPPORTED, so a decoder must return RAD_E_UNSUPPORTED for an
|
||||
* encoding it did not write. `w` names the weight where the caller knows it; a decoder must need
|
||||
* nothing beyond the encoding, `rows` and `cols`, because the oracle knows no more. */
|
||||
typedef int (*RadQuantDecodeFn)(const RadEncoding* e, const RadQuantWeight* w,
|
||||
const void* const* planes, int64_t row0, int64_t rows,
|
||||
float* out);
|
||||
|
||||
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 (kind
|
||||
* RAD_PLUGIN_QUANT). Two plugins naming the same quantiser are refused at load, both named, since
|
||||
* a recipe naming it would otherwise give different numbers depending on load order. */
|
||||
int rad_quant_count(void);
|
||||
const RadQuantizerInfo* rad_quant_at(int i);
|
||||
|
||||
#ifdef __cplusplus
|
||||
} /* extern "C" */
|
||||
#endif
|
||||
|
||||
#endif /* RAD_QUANT_H */
|
||||
@@ -0,0 +1,480 @@
|
||||
/* rad_runtime.h -- the run phase. Ordinary C++ with one rule: it may only issue handles obtained
|
||||
* during declare. There is no capture discipline: the device backend records a pass's dispatch
|
||||
* packets at the queue as they are issued and replays them (core/device/aql.cpp,
|
||||
* core/runtime/ctx.h), so the step function needs no graph-safe form. See spec.md §3.2.
|
||||
*/
|
||||
#ifndef RAD_RUNTIME_H
|
||||
#define RAD_RUNTIME_H
|
||||
|
||||
#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 KV group; rebuilding it per group
|
||||
* and per layer would make a large share of a decode step host work with the device idle (spec §8).
|
||||
*
|
||||
* Every pointer is device memory unless the field name says _h. The host mirrors give the
|
||||
* scheduler and the run phase the bounds without a device read. */
|
||||
enum { RAD_PHASE_PREFILL = 0, RAD_PHASE_DECODE = 1, RAD_PHASE_MIXED = 2 };
|
||||
|
||||
typedef struct RadKVGroupBatch {
|
||||
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 */
|
||||
/* State slots per sequence: 1 unless the group's kernel asked for scratch beside the state.
|
||||
* A linear kernel serving speculation cannot commit the state until acceptance is known, so it
|
||||
* keeps the committed state in column 0 and replay scratch in the later columns. The engine
|
||||
* zeroes all of them at admission and otherwise does not look inside. Zero means 1. */
|
||||
int64_t state_index_pitch;
|
||||
int64_t block_size;
|
||||
int64_t max_blocks;
|
||||
} 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 */
|
||||
|
||||
/* The tokens the sampler wants logits for: indices into this step's tokens, [n_out].
|
||||
*
|
||||
* A prefill chunk computes hidden states for every token, but the sampler wants only each
|
||||
* sequence's last. The plugin issues gather_rows over these and runs the lm_head only on the
|
||||
* result (docs/OPS.md, "Vocabulary edges"); over all n_tok rows at max_tok 8192 and a 248K
|
||||
* vocab the logits buffer would be 8 GiB instead of 63 MiB.
|
||||
*
|
||||
* n_out is 0 for a chunk that finishes no sequence (the middle of a long prefill): no logits
|
||||
* are produced and the lm_head is not run. */
|
||||
int64_t n_out;
|
||||
const int32_t* out_ids; /* [n_out] device */
|
||||
|
||||
const int32_t* q_lens; /* [n_seq] device: query length this step */
|
||||
const int32_t* ctx_lens; /* [n_seq] device: context length before this step */
|
||||
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 that runs the trunk; non-zero runs only the draft
|
||||
* head, and the sign gives the kind:
|
||||
*
|
||||
* r < 0 a history pass: one row per token, gathered from the trunk step's rows
|
||||
* (out_ids). The head attends to its own K and V, which nothing else writes (a
|
||||
* prefill fills only the trunk's layers); this fills them for the positions the
|
||||
* step just committed. When `n_draft_out` is non-zero the pass is also draft round
|
||||
* 1 and ends in the lm_head over the rows `draft_out_ids` names.
|
||||
* r > 1 draft round r, one-based. One row per sequence, reading the head's output from
|
||||
* the round before and ending in the lm_head; it samples the r-th draft. There is
|
||||
* no pass with r == 1: the history pass carries that round.
|
||||
*
|
||||
* Zero is the ordinary step so that a zeroed RadBatch runs the model, the same reason
|
||||
* `num_accepted` is one-based (docs/OPS.md).
|
||||
*
|
||||
* On any draft pass `token_ids` is already shifted (the head at index i reads the token at
|
||||
* i + 1) by the batch builder, so no kernel or plugin applies the shift. Every other field
|
||||
* keeps its usual meaning. */
|
||||
int32_t draft_pass;
|
||||
|
||||
/* Linear-state checkpointing (spec §7.3): tokens at which the scheduler wants a checkpoint
|
||||
* 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 prefill chunks; the scheduler
|
||||
* orders every step that way. A block that treats the two differently issues over each as a
|
||||
* contiguous sub-range of the per-sequence arrays (`cu_seqlens + n_seq_decode`,
|
||||
* `state_index + n_seq_decode * pitch`, ...) with the token operands left at their base. This
|
||||
* works because cu_seqlens holds absolute row offsets, so a kernel reading cu[n] and cu[n+1]
|
||||
* finds the right rows in either sub-array.
|
||||
*
|
||||
* Without the split a mixed step is prefill-shaped for every sequence, so its decode rows
|
||||
* cannot verify a draft and produce one token instead of several; under interactive load many
|
||||
* steps are mixed.
|
||||
*
|
||||
* n_seq_decode == n_seq on a pure decode step and 0 on a pure prefill, so a block that does
|
||||
* not care can ignore these fields, and one that does needs no phase test. */
|
||||
int64_t n_seq_decode;
|
||||
/* The decode rows are tokens [0, n_tok_decode) and the prefill chunks the rest. A per-token
|
||||
* op cannot derive this, since each decode row is 1 + its own draft count. */
|
||||
int64_t n_tok_decode;
|
||||
/* The longest query in each half. max_q_len over a mixed step is the prefill chunk's, and
|
||||
* banding the decode half with it would give eight rows a thousand-row GEMM's band.
|
||||
*
|
||||
* Only the decode value is currently read (by the GDN blocks). The prefill value is for a
|
||||
* block whose prefill path bands on a per-sequence query length; the GDN prefill ops band on
|
||||
* the step's total tokens, taken from their operands. */
|
||||
int32_t max_q_len_decode;
|
||||
int32_t max_q_len_prefill;
|
||||
|
||||
/* Draft round 1, carried by the history pass: [n_draft_out] device, indices into this pass's
|
||||
* rows, one per drafting sequence, in the order the later rounds' rows take.
|
||||
*
|
||||
* Round 1 continues from the last committed position with the token the trunk chose after it.
|
||||
* The history pass already has a row with exactly those inputs: it covers every position the
|
||||
* verify step could have committed and repeats the last committed one past it
|
||||
* (core/sched/advance.h, ADV_HIST). So each drafting sequence's last history row is its
|
||||
* round-1 row, saving a separate pass; the pass ends in the lm_head over those rows, and the
|
||||
* head's wide state there is what round 2 continues from.
|
||||
*
|
||||
* 0 on a history pass that drafts nothing, and on every other pass. */
|
||||
int64_t n_draft_out;
|
||||
const int32_t* draft_out_ids;
|
||||
|
||||
/* The prompt after this step: `n_ahead` more tokens of the last sequence, stored in
|
||||
* `token_ids` right after its n_tok (the next prefill chunk); 0 on every other step (decode,
|
||||
* draft pass, a prefill's last chunk).
|
||||
*
|
||||
* Nothing is computed on them. They let an op that fetches per-token data from a slow tier
|
||||
* start the next step's reads during this one: the PLE gather reads its rows from the
|
||||
* container file, tens of thousands of random reads per chunk (docs/OPS.md, ngram_ids'
|
||||
* `ahead_ids` and embed_lookup_q's `ahead`). */
|
||||
int64_t n_ahead;
|
||||
|
||||
/* ================================================ multimodal (spec §11) */
|
||||
|
||||
/* The rotary position of every token, which differs from `positions`. `positions` is a
|
||||
* token's index in its sequence (the KV slot, the QSA block and other bookkeeping count in
|
||||
* it). Qwen-VL style M-RoPE gives each token three components (temporal, height, width): a
|
||||
* text token has all three equal, an image token has the image's start in the first and its
|
||||
* row and column offsets in the others, and text after an image continues from the image's
|
||||
* largest component, so from the first image on the rotary position runs behind the index.
|
||||
*
|
||||
* [3, n_tok] device, component-major: plane c is rope_pos + c * n_tok. Plane 0 alone is a
|
||||
* valid one-component position for every token whose components agree, i.e. every token when
|
||||
* `rope_mixed` is 0, so a kernel reading one position per token can use plane 0 then.
|
||||
*
|
||||
* Null when the program declares no encoder; `positions` is then the rotary position. */
|
||||
const int32_t* rope_pos;
|
||||
/* Host-side: non-zero when some token on this pass has differing components (an image or
|
||||
* video span is present); a block with a one-component fast path must take the
|
||||
* multi-component path. */
|
||||
int32_t rope_mixed;
|
||||
|
||||
/* Rows that take an encoder's output in place of a token embedding: row i of `mm_embd`
|
||||
* replaces the embedding of this pass's token `mm_rows[i]`. The placeholder ids a media span
|
||||
* holds in `token_ids` are still real ids (a hashed n-gram embedding reads them).
|
||||
*
|
||||
* Rank 0 holds the rows and every other rank zeros, matching a vocabulary-sharded embedding
|
||||
* lookup where non-owning ranks contribute zero to the following reduction. So a plugin
|
||||
* overwrites its lookup output with these rows before that reduction, whether it is an
|
||||
* all-reduce or folded into the first layer's norm.
|
||||
*
|
||||
* On a pass that shifts its tokens (a draft history pass) the rows are shifted with them. 0
|
||||
* rows on every pass without media. */
|
||||
int64_t n_mm_rows;
|
||||
const int32_t* mm_rows; /* [n_mm_rows] device: index into this pass's tokens */
|
||||
const void* mm_embd; /* [n_mm_rows, n_embd] bf16 device */
|
||||
|
||||
/* The encoder pass. Non-zero `enc` runs a declared encoder (rad_declare_encoder) and nothing
|
||||
* else: no token rows, no KV, no logits. Its value is that encoder's `modalities`
|
||||
* (RAD_MM_AUDIO, or the image/video mask), selecting between two declared encoders. Input is a
|
||||
* list of patches already resized, normalised and cut by the processor; output is the
|
||||
* encoder's declared `out` buffer, one row per `merge` patches, read back after the pass.
|
||||
*
|
||||
* An audio pass's patches are feature frames with 1-D coordinates: plane 0 the frame's index
|
||||
* in its clip, plane 1 whether it takes part in the convolution (1) or is staging the encoder
|
||||
* reads as zero (0), plane 2 the clip's real frames and plane 3 its staged ones. The zero
|
||||
* frames pad a clip staged whole to whole output rows, or, for a clip staged a second at a
|
||||
* time (Qwen3-ASR), align each second to whole rows.
|
||||
*
|
||||
* Patches are grouped into segments (one per image, one per temporal group of a video), and
|
||||
* attention runs within a segment. `enc_coord` gives each patch's place in its segment, which
|
||||
* is all a learned position table or a 2-D rotary embedding needs. */
|
||||
int32_t enc;
|
||||
int64_t enc_n_patch;
|
||||
const void* enc_pixels; /* [enc_n_patch, patch_dim] bf16 device */
|
||||
/* [4, enc_n_patch] device, component-major like rope_pos: row, column, the segment's height
|
||||
* 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 */
|
||||
|
||||
/* ================================================ image generation */
|
||||
|
||||
/* A generator pass (rad_declare_generator): RAD_GEN_PASS_*, with `gen_b` its payload. 0 on
|
||||
* every step of a program that declared no generator. */
|
||||
int32_t gen;
|
||||
const struct RadGenBatch* gen_b;
|
||||
} RadBatch;
|
||||
|
||||
/* What a generator pass carries beside the step batch's own fields, which keep their meanings:
|
||||
*
|
||||
* COND one sequence. `token_ids`, `positions` and `rope_pos` are its conditioning prompt, the
|
||||
* encoder's input (`enc_*`) is the prompt's reference pictures and `mm_rows` the prompt
|
||||
* rows the encoder's output rows replace, as on any media step. What is here lays out
|
||||
* the generator's sequence over those rows and writes it into the KV group.
|
||||
* DENOISE one entry per (image, conditioning): `cu_seqlens` bounds each entry's latent rows,
|
||||
* and the KV group's `block_table` and `seqused` name its conditioning's sequence.
|
||||
* DECODE one image.
|
||||
*
|
||||
* Every pointer is device memory unless the name ends in _h. */
|
||||
typedef struct RadGenBatch {
|
||||
/* ---- COND */
|
||||
int64_t rows; /* the generator's rows for this sequence */
|
||||
/* Where each row comes from: >= 0 the prompt row of that index (the conditioning network's
|
||||
* output there), < 0 the reference latent row -(1 + src). [rows] */
|
||||
const int32_t* src;
|
||||
/* Rotary positions, three components a row. On a COND pass they are laid out segment by
|
||||
* segment: segment s's [3, length] component-major block starts at element 3 * seg_h[s], so a
|
||||
* segment's positions are one dense operand. On a DENOISE pass, [3, n_tok] component-major,
|
||||
* the latent rows'. */
|
||||
const int32_t* rope;
|
||||
/* The sequence in segments: rows [seg_h[s], seg_h[s+1]), each a picture (`seg_bidi_h` 1, its
|
||||
* rows attend to each other both ways) or a run of text (0, causal). A segment is never split
|
||||
* and attends to every segment before it. `seg` is the same offsets on the device; `seg_cu`
|
||||
* is [n_seg, 2], segment s's own cu_seqlens {0, length}, and `seg_start` [n_seg] its first
|
||||
* row -- the keys before it, which is its `seqused` when it is run on its own. */
|
||||
int64_t n_seg;
|
||||
const int32_t* seg;
|
||||
const int32_t* seg_h;
|
||||
const int32_t* seg_bidi_h;
|
||||
const int32_t* seg_cu;
|
||||
const int32_t* seg_start;
|
||||
/* [rows] the KV slot each row is stored at. */
|
||||
const int32_t* slot_mapping;
|
||||
/* Pixels for the decoder's encoder: `n_px` blocks of `px` [*, pixel_channels] bf16 in
|
||||
* [-1, 1], block b at pixel px_h[3b], px_h[3b+1] high and px_h[3b+2] wide. These are the
|
||||
* reference pictures in prompt order and, with `inpaint`, a last block holding the picture
|
||||
* being repainted at the output size, whose latents go to the lanes below. */
|
||||
int64_t n_px;
|
||||
const void* px;
|
||||
const int32_t* px_h;
|
||||
/* [n_px, 2] each block's own cu_seqlens over its latent tokens: {0, (h / scale) (w / scale)}. */
|
||||
const int32_t* px_cu;
|
||||
int32_t inpaint;
|
||||
/* [image tokens] f32: 1 where the image is repainted, 0 where the picture is kept. */
|
||||
const float* inp_mask;
|
||||
/* The lanes this conditioning's images run in, which take the repainted picture's latents. */
|
||||
int64_t n_lane;
|
||||
const int32_t* lane_h;
|
||||
|
||||
/* ---- DENOISE, one value per entry ([n_seq]); on a COND pass `sigma` is one 0, the time
|
||||
* the conditioning is modulated at */
|
||||
const float* sigma; /* where the entry's latent is */
|
||||
const float* sigma_next; /* where this step takes it */
|
||||
const float* cfg; /* guidance: v = neg + cfg * (pos - neg); 1 without a pair */
|
||||
/* The entry holding this image's negative conditioning, or -1 for none; -2 marks an entry
|
||||
* that is one, whose rows serve another entry's step and which does not move its lane. */
|
||||
const int32_t* pair;
|
||||
const int32_t* lane; /* the plugin's lane the image's latent lives in */
|
||||
const int32_t* lane_dh; /* ... the same, host */
|
||||
/* RAD_GEN_F_*. */
|
||||
const int32_t* flags;
|
||||
/* [n_seq, 2] the image's noise seed, low word first. */
|
||||
const uint32_t* seed;
|
||||
|
||||
/* ---- DECODE */
|
||||
int32_t dec_lane;
|
||||
int32_t dec_height, dec_width; /* pixels */
|
||||
int32_t dec_preview; /* the lane's preview latent, not its state */
|
||||
} RadGenBatch;
|
||||
|
||||
/* An entry's flags on a DENOISE pass. */
|
||||
enum {
|
||||
RAD_GEN_F_FIRST = 1, /* the image's first step: its latent is the noise its seed draws */
|
||||
RAD_GEN_F_INPAINT = 2, /* repaint: after the step, the kept region goes back to the picture,
|
||||
* noised to sigma_next with the image's own noise */
|
||||
RAD_GEN_F_PREVIEW = 4 /* write the step's estimate of the clean latent to the lane's preview */
|
||||
};
|
||||
|
||||
/* ================================================================== 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 block table but not the pool
|
||||
* base, which belongs to the block manager. handle is the rad_kvgroup and offset is the layer,
|
||||
* since a group's pool holds one cache per bound layer. */
|
||||
/* RAD_OPK_WTAB names a run of consecutively declared weights. A routed MoE layer has no single
|
||||
* base to stride from: its experts are separate movement units (spec §4.2), and after placement
|
||||
* one may be in VRAM, the next streamed over the link and a third on disk. The core resolves each
|
||||
* handle like any weight (residency table, mover event, use note) and hands the kernel a device
|
||||
* array of pointers, one per expert, in declaration order. See RAD_WTAB below for the RadTensor
|
||||
* shape rule. */
|
||||
enum { RAD_OPK_BUF = 0, RAD_OPK_WEIGHT = 1, RAD_OPK_RAW = 2, RAD_OPK_NONE = 3, RAD_OPK_KV = 4,
|
||||
RAD_OPK_WTAB = 5 };
|
||||
|
||||
typedef struct RadOperand {
|
||||
uint8_t kind;
|
||||
uint32_t dtype; /* RAD_OPK_RAW only: what the pointer points at (buffers and weights
|
||||
* carry their dtype in the declaration). RAD_DT_INVALID means the
|
||||
* kernel knows it from the schema position, which a specialised
|
||||
* kernel does and libref does not. */
|
||||
uint32_t handle; /* rad_buf or rad_weight */
|
||||
void* raw; /* RAD_OPK_RAW: a pointer the core did not allocate (a batch field) */
|
||||
int64_t offset; /* element offset into the buffer or weight */
|
||||
int64_t rows; /* 0 = the declared extent; >0 = only this many rows of dim 0 */
|
||||
int64_t cols; /* 0 = the declared extent; >0 = a column slice of that width, with the
|
||||
* declared width kept as the stride. Lets q, k and v be views of one
|
||||
* fused qkv buffer instead of three buffers and a copy. */
|
||||
} RadOperand;
|
||||
|
||||
#define RAD_B(h) ((RadOperand){ RAD_OPK_BUF, RAD_DT_INVALID, (h), 0, 0, 0, 0 })
|
||||
#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, as a declaration loop
|
||||
* over experts produces (rad_decl_weight hands out consecutive indices).
|
||||
*
|
||||
* The kernel receives `RadTensor::data` as a device array of `n` `void*`, entry e pointing at
|
||||
* expert e's first byte. `shape[0]` is n and `stride[0]` is 0; the zero leading stride marks an
|
||||
* axis that must be indexed through the table, not by arithmetic. `dtype` and `shape[1..]` /
|
||||
* `stride[1..]` are one entry's; every weight in the run must agree on them, or the core refuses
|
||||
* the issue by name.
|
||||
*
|
||||
* The table is rebuilt only when a pointer changes, so a resident model pays one comparison per
|
||||
* expert per issue and no copy. */
|
||||
#define RAD_WTAB(h, n) ((RadOperand){ RAD_OPK_WTAB, RAD_DT_INVALID, (h), 0, 0, (n), 0 })
|
||||
#define RAD_KV(g, layer) ((RadOperand){ RAD_OPK_KV, RAD_DT_INVALID, (g), 0, (layer), 0, 0 })
|
||||
#define RAD_P(ptr) ((RadOperand){ RAD_OPK_RAW, RAD_DT_INVALID, 0, (void*)(ptr), 0, 0, 0 })
|
||||
#define RAD_P_T(ptr, dt) ((RadOperand){ RAD_OPK_RAW, (dt), 0, (void*)(ptr), 0, 0, 0 })
|
||||
/* A raw pointer to a dense 2-D array, [rows, cols], packed. On a raw operand `cols` is the second
|
||||
* extent, not a column slice (there is no declared width to slice). This is how a two-dimensional
|
||||
* batch field such as the block table, [n_seq, max_blocks], keeps its width. */
|
||||
#define RAD_P_T2(ptr, dt, r, c) \
|
||||
((RadOperand){ RAD_OPK_RAW, (dt), 0, (void*)(ptr), 0, (r), (c) })
|
||||
#define RAD_NONE ((RadOperand){ RAD_OPK_NONE, RAD_DT_INVALID, 0, 0, 0, 0, 0 })
|
||||
|
||||
#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 for the current execution site.
|
||||
*
|
||||
* `n` is the value of the op's ranged parameter (at most one per op, so this is a single integer
|
||||
* on the hot path). RAD_N_BATCH means the batch's token count, which almost every op wants. An op
|
||||
* with no ranged parameter ignores it.
|
||||
*
|
||||
* Ops take handles, not pointers, so a weight's location is not fixed at declare; placement
|
||||
* depends on this (spec §3.2). */
|
||||
#define RAD_N_BATCH ((int64_t)-1)
|
||||
|
||||
int rad_issue(RadCtx* c, rad_op op, const RadOperand* opd, int n_opd, int64_t n);
|
||||
|
||||
/* The second lane, for overlapping a collective (or an arm no shard divides) with compute.
|
||||
* `rad_lane` selects the stream later issues launch on (0 or 1); `rad_lane_join(c, from, to)`
|
||||
* orders `to` behind everything already issued on `from` without blocking the host. The runtime
|
||||
* joins lane 1 into lane 0 at the end of every step, so a missing join costs speed, not
|
||||
* correctness.
|
||||
*
|
||||
* Three rules (reasons at Ctx::lane1_ in core): every collective must use the same lane, since
|
||||
* the all-reduce numbers its scratch slots per launch and the ranks must agree; a kernel with a
|
||||
* device-wide arrival counter must key it on the stream (libr4d's split-K GEMM does), or it may
|
||||
* not run here; and every buffer the second lane touches must be named to rad_buf_concurrent,
|
||||
* because the planner packs transients from one linear order. */
|
||||
int rad_lane(RadCtx* c, int lane);
|
||||
int rad_lane_join(RadCtx* c, int from, int to);
|
||||
|
||||
/* 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 this is how it
|
||||
* refuses a batch shape it does not serve; the engine stops with `what` in the message. Returns
|
||||
* the status it set, so a helper can `return rad_step_fail(...)`. */
|
||||
int rad_step_fail(RadCtx* c, const char* what);
|
||||
|
||||
/* ================================================================== run-phase queries */
|
||||
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). These are device-side buffers the plugin
|
||||
* issues its expert ops against, not host-visible expert ids. */
|
||||
typedef struct RadRouting {
|
||||
const int32_t* expert_ids; /* [n_tok, top_k] device */
|
||||
const float* expert_w; /* [n_tok, top_k] device */
|
||||
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);
|
||||
|
||||
/* A core-owned device row of at least `n_expert` int32 where a layer's expert counts can be
|
||||
* written in place; the core copies it to the host once at the end of the pass. A router that
|
||||
* writes here and reports this pointer as `expert_count` hands the counts over for free; any other
|
||||
* pointer costs one copy dispatch per routed layer on the compute stream. Null when the core keeps
|
||||
* no histogram for `layer` or its row is narrower than `n_expert`; the router then writes its own
|
||||
* buffer and reports that. */
|
||||
int32_t* rad_route_counts(RadCtx* c, int layer, int64_t n_expert);
|
||||
|
||||
/* Next-layer expert prefetch, at decode. At its router input a routed layer names the next routed
|
||||
* layer; the core applies that layer's router to this layer's input rows, picks the experts it is
|
||||
* likeliest to route that sit in the pinned host pool, and copies them to the card while the rest
|
||||
* of this layer runs. Just before the next layer's routed GEMMs it points their weight-table
|
||||
* entries at the copies that have landed, where the entries still name the pool slots copied from.
|
||||
* Results are unchanged: a copy holds its slot's bytes. Active only when placement keeps experts
|
||||
* in a pinned pool and the device backend can spare a DMA engine; a pass of more than 16 rows
|
||||
* makes no prediction. The three calls are no-ops otherwise.
|
||||
*
|
||||
* `parts` names, for each of the next layer's experts, the weights its unit is made of (at most four,
|
||||
* e.g. the gate-up matrix and its scales and the down matrix and its scales), as the routed GEMMs
|
||||
* read them through weight tables; 0 where an expert has fewer or none. An expert is prefetched only
|
||||
* where each of its weights is in exactly one table and all of them sit in one pool slot. The arrays
|
||||
* must outlive the context; the core reads the routing counts only to rank and count, never to choose
|
||||
* an expert's bytes. `layer` is the next layer's index as rad_route_report and
|
||||
* rad_expert_prefetch_step name it; `router` is its router, [n_expert, n_embd] bf16. */
|
||||
typedef struct RadPrefetchNext {
|
||||
int layer;
|
||||
rad_weight router;
|
||||
int64_t n_expert, top_k;
|
||||
int64_t n_parts;
|
||||
const rad_weight* parts; /* [n_expert * n_parts] */
|
||||
const int32_t* count_at; /* [n_expert]: where the expert's count is in the layer's routing
|
||||
counts (rad_route_counts), -1 for nowhere; null when at its index */
|
||||
} RadPrefetchNext;
|
||||
|
||||
/* At this layer's router input: `h` rows [r0, r0 + rows) of n_embd bf16, read in place on another
|
||||
* stream -- the block must not overwrite them before this layer's routed GEMMs. */
|
||||
int rad_expert_prefetch(RadCtx* c, const RadPrefetchNext* next, rad_buf h, int64_t r0, int64_t rows,
|
||||
int64_t n_embd);
|
||||
/* After this layer's routed down GEMM: the copies cross the link from here, overlapping the next
|
||||
* layer's attention rather than this layer's own streamed experts. */
|
||||
int rad_expert_prefetch_mark(RadCtx* c);
|
||||
/* Ahead of `layer`'s routed GEMMs, on every routed layer of every pass. */
|
||||
int rad_expert_prefetch_step(RadCtx* c, int layer);
|
||||
|
||||
/* A weight's pointer, for the rare plugin-private kernel invoked outside the op vocabulary. Waits
|
||||
* on the mover. The weight may move afterwards, so the pointer is valid only within one issue. */
|
||||
void* rad_weight_ptr(RadCtx* c, rad_weight w);
|
||||
void* rad_buf_ptr(RadCtx* c, rad_buf b);
|
||||
|
||||
#ifdef __cplusplus
|
||||
} /* extern "C" */
|
||||
#endif
|
||||
#endif /* RAD_RUNTIME_H */
|
||||
@@ -0,0 +1,129 @@
|
||||
/* rad_sample.h -- the per-sequence sampling row.
|
||||
*
|
||||
* Every sampler op takes `params` as an operand: an array of the struct below, one row per sampled
|
||||
* position, uploaded once per step. Its layout is therefore a wire format between the core and
|
||||
* every kernel plugin, stated here because a plugin cannot include a core header.
|
||||
*
|
||||
* ============================== WHY NOT PARAMETERS ==============================
|
||||
*
|
||||
* `rep`, `freq`, `pres`, `k` and `p` read like op parameters, and docs/OPS.md names them that way,
|
||||
* but parameters are geometry: the selector matches constraints against them and they are frozen
|
||||
* at declare (spec §2.2). Two requests in one batch with different top_p would need two
|
||||
* resolutions of the same op. So the values are data and travel as an operand. `seed` and
|
||||
* `offset`, which docs/OPS.md gives `sample_pick` as two more operands, are row fields for the
|
||||
* same reason.
|
||||
*
|
||||
* core/sample/sampler.h carries the full schema table this implies; libref implements it.
|
||||
*/
|
||||
#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 with one integer test instead of reading
|
||||
* five floats to find they are the identity.
|
||||
*
|
||||
* RAD_SP_GREEDY owns the row's token. `sample_argmax` writes it, and every later candidate stage
|
||||
* (`sample_topk`, the narrowing stages, `sample_merge_topk`, `sample_pick`) treats the row as
|
||||
* having no candidates and leaves `token` alone. A batch mixing greedy and sampled rows issues
|
||||
* both paths over every row, so a stage that ignored the flag would overwrite the argmax with a
|
||||
* draw. A greedy row that must go through the candidate chain (a split vocabulary, where the
|
||||
* argmax column is not a token id) is staged at top_k = 1 without this flag. */
|
||||
enum {
|
||||
RAD_SP_GREEDY = 1 << 0, /* argmax path; the candidate chain is not run for this sequence */
|
||||
RAD_SP_PENALTY = 1 << 1, /* any of rep / freq / pres is non-identity */
|
||||
RAD_SP_MASK = 1 << 2, /* a grammar is constraining this sequence this step */
|
||||
RAD_SP_XTC = 1 << 3,
|
||||
RAD_SP_DRY = 1 << 4,
|
||||
RAD_SP_LOGPROBS = 1 << 5 /* `sample_logprobs` summarises this row's raw logits */
|
||||
};
|
||||
|
||||
/* 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.
|
||||
*
|
||||
* 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 the last n tokens (llama.cpp's
|
||||
* meaning for `repeat_last_n` and `dry_penalty_last_n`).
|
||||
*
|
||||
* `dry_rep_limit` is the longest repeat DRY may count for the row, fixed by the most recent
|
||||
* sequence breaker in the DRY window (llama.cpp's `rep_limit`), or 0 when no breaker occurs there
|
||||
* 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 here, not left to a library, because a host reference, a device
|
||||
* kernel and a rerun must produce the same stream (spec §13). splitmix64 over
|
||||
* (seed * golden ratio + pos), taking 24 bits as a float in [0, 1): exactly f32's mantissa, so no
|
||||
* double is needed anywhere.
|
||||
*
|
||||
* Independent draws at one position use independent streams: the request's seed XORed with a key,
|
||||
* `rad_sample_uniform01(seed ^ key, pos)`. The pick uses the seed itself. XTC's firing coin has its
|
||||
* own key so the pick is not correlated with it; speculative acceptance and its residual draw have
|
||||
* theirs. Every implementation of a stage takes its key from here. */
|
||||
#define RAD_SAMPLE_KEY_PICK 0x0ull
|
||||
#define RAD_SAMPLE_KEY_XTC 0x58544311ull
|
||||
#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 */
|
||||
+336
@@ -0,0 +1,336 @@
|
||||
/* rad_types.h -- the primitive vocabulary shared by the core, the plugins and the tools.
|
||||
*
|
||||
* Pure C. Everything here crosses an .so boundary, so nothing in this file may be a C++ type,
|
||||
* have a non-trivial layout, or depend on a compiler flag. See spec.md §2.
|
||||
*/
|
||||
#ifndef RAD_TYPES_H
|
||||
#define RAD_TYPES_H
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
#include <string.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* ------------------------------------------------------------------ status */
|
||||
/* Zero is success. Negative is failure, and the value names its class so a caller can report it.
|
||||
* A kernel returning negative at issue is a selection bug, not a runtime condition (spec.md §17). */
|
||||
enum {
|
||||
RAD_OK = 0,
|
||||
RAD_E_SHAPE = -1, /* geometry this instantiation does not serve */
|
||||
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
|
||||
*
|
||||
* Every free function in this header is a `static inline` definition, not a declaration. A plugin
|
||||
* links these headers and nothing of the engine's, so a function defined in the core would
|
||||
* resolve at dlopen only if the host happened to export it (ENABLE_EXPORTS/-rdynamic); otherwise
|
||||
* RTLD_NOW fails the plugin.
|
||||
*
|
||||
* The helpers are therefore part of the ABI by value: a plugin carries the dtype table it was
|
||||
* built against, and RAD_ABI_VERSION enforces the match (the loader refuses a mismatch by name,
|
||||
* with both versions printed).
|
||||
*
|
||||
* Everything here is pure, small and total: nothing allocates or holds state, and nothing may
|
||||
* start to. */
|
||||
static inline const char* rad_strerror(int status) {
|
||||
switch (status) {
|
||||
case RAD_OK: return "ok";
|
||||
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): libref computes on tensors, rad-kbench compares them
|
||||
* elementwise, the buffer planner sizes buffers from shapes, and rad-convert writes bytes.
|
||||
*
|
||||
* The enum is open at the top: values >= RAD_DT_PLUGIN_BASE are kernel-plugin private, sized by
|
||||
* the plugin's own layout hook and never interpreted by the core. A format invented for one kernel
|
||||
* lives there (spec §19.6). */
|
||||
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. Element counts are logical elements; byte sizes
|
||||
* come from rad_dtype_bits(). They pack along a row, lowest bits first (element 2j of a 4-bit
|
||||
* row in bits 0-3 of byte j), and a row starts on a byte (rad_encoding.h). What a code means
|
||||
* is its encoding's business; these give only its width and signedness. */
|
||||
RAD_I4 = 16, /* two's complement, -8..7 */
|
||||
RAD_I2 = 17, /* two's complement, -2..1 */
|
||||
RAD_FP4E2M1 = 18, /* OCP FP4: 1-2-1, no inf or nan, max 6 */
|
||||
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, in the header for the reason given above rad_strerror.
|
||||
*
|
||||
* Sub-byte formats carry their packed width here. A shared scale is never folded into a code's
|
||||
* width (it is a plane of its own, rad_encoding.h), so every width below is exact. */
|
||||
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 those found in checkpoints (safetensors)
|
||||
* and kernel dtype strings. */
|
||||
static inline uint32_t rad_dtype_parse(const char* name) {
|
||||
if (!name) return RAD_DT_INVALID;
|
||||
for (int i = 0; i < RAD_DT_TABLE_N; ++i)
|
||||
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, since a byte stride would be fractional for sub-byte
|
||||
* dtypes. */
|
||||
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 non-unit axes are dense are both contiguous. A shape-1 axis
|
||||
* may carry any stride and still describe the same bytes, so its stride is not checked. */
|
||||
static inline int rad_tensor_is_contiguous(const RadTensor* t) {
|
||||
if (!t || t->rank == 0) return 1;
|
||||
int64_t acc = 1;
|
||||
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 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. A double rather
|
||||
* than a "%.9g" string, which would be exact for an IEEE single but
|
||||
* unreadable in a graph dump. Constraints never match on a float:
|
||||
* a tolerance is not a predicate. */
|
||||
} RadParam;
|
||||
|
||||
/* Builders. RAD_PARAMS below wraps these into a positional list. */
|
||||
#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 the
|
||||
* entry point still rejects what it cannot run (spec §2.1). */
|
||||
enum { RAD_C_EQ = 0, RAD_C_LE = 1, RAD_C_GE = 2, RAD_C_DIV = 3, RAD_C_IN = 4 };
|
||||
|
||||
typedef struct RadConstraint {
|
||||
const char* key;
|
||||
int op;
|
||||
long long ival; /* EQ / LE / GE / DIV */
|
||||
const char* sval; /* IN: space-separated set of admissible strings */
|
||||
} RadConstraint;
|
||||
|
||||
/* A constraint on the machine rather than the geometry. A key starting "device." is matched
|
||||
* against what the engine measured about the ranks' devices at launch, not against op parameters,
|
||||
* so architecture plugins and schemas need not carry machine capabilities. Such a key is in no
|
||||
* geometry, so it changes no tuning key and no selection fold. Where nothing measured it (a tool
|
||||
* selecting without an engine) it is absent, and a constraint on an absent key does not hold.
|
||||
*
|
||||
* device.p2p 1 when every rank's device can read and write every other rank's memory
|
||||
* directly; 0 when some pair cannot. One rank has no peer to reach, and is 1. */
|
||||
#define RAD_DEVICE_FACT_PREFIX "device."
|
||||
#define RAD_FACT_P2P "device.p2p"
|
||||
|
||||
#define RAD_C(k, o, v) { (k), (o), (long long)(v), 0 }
|
||||
#define RAD_CEQ(k, v) { (k), RAD_C_EQ, (long long)(v), 0 }
|
||||
#define RAD_CLE(k, v) { (k), RAD_C_LE, (long long)(v), 0 }
|
||||
#define RAD_CGE(k, v) { (k), RAD_C_GE, (long long)(v), 0 }
|
||||
#define RAD_CDIV(k, v) { (k), RAD_C_DIV, (long long)(v), 0 }
|
||||
#define RAD_CIN(k, s) { (k), RAD_C_IN, 0, (s) }
|
||||
|
||||
/* ------------------------------------------------------------------ handles */
|
||||
/* Opaque, dense, small. A handle is an index into a core-owned table; zero is never a valid
|
||||
* handle, so a zeroed struct is an unset one and a failed decl_* is falsy. */
|
||||
typedef uint32_t rad_weight;
|
||||
typedef uint32_t rad_buf;
|
||||
typedef uint32_t rad_op;
|
||||
/* A KV group handle. Here with the other handles because RadBufDecl in rad_builder.h carries
|
||||
* one. */
|
||||
typedef uint32_t rad_kvgroup;
|
||||
|
||||
#define RAD_NULL_HANDLE 0u
|
||||
|
||||
/* ------------------------------------------------------------------ streams */
|
||||
/* Opaque: the core never dereferences one. On a card it is the engine's own queue, not a
|
||||
* hipStream_t. A kernel plugin may use it only with hipLaunchKernel (and so <<<>>>),
|
||||
* hipMemcpyAsync, hipMemcpy2DAsync and hipMemsetAsync, which the engine implements itself, and
|
||||
* must pass it to nothing else in HIP (docs/PLUGIN.md, "What a launch may do"). Under the host
|
||||
* backend the host kernels ignore it. */
|
||||
typedef void* RadStream;
|
||||
|
||||
#ifdef __cplusplus
|
||||
} /* extern "C" */
|
||||
#endif
|
||||
#endif /* RAD_TYPES_H */
|
||||
@@ -0,0 +1,92 @@
|
||||
#ifndef RAD_YARN_H
|
||||
#define RAD_YARN_H
|
||||
|
||||
/* Static YaRN coefficients. The architecture resolves the correction bounds from the original
|
||||
* training length, never the deployment or table length. Kernels share the resolved coefficients
|
||||
* so direct and table-backed RoPE cannot disagree.
|
||||
*
|
||||
* C++ gets RadYarn with a member frequency() (callable from HIP device code) and default member
|
||||
* values; C gets the same four-float struct and rad_yarn_frequency(). The two definitions must
|
||||
* compute the same frequencies; tests/abi_layout_test.cpp compares them. */
|
||||
#include "rad_plugin.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
#include <cmath>
|
||||
|
||||
#if defined(__HIPCC__)
|
||||
#define RAD_YARN_HD __host__ __device__
|
||||
#else
|
||||
#define RAD_YARN_HD
|
||||
#endif
|
||||
|
||||
struct RadYarn {
|
||||
float factor = 0.0f; /* zero: YaRN off, frequency() returns `inv` unchanged */
|
||||
float low = 0.0f;
|
||||
float high = 0.0f;
|
||||
float magnitude = 1.0f;
|
||||
|
||||
RAD_YARN_HD float frequency(float inv, int i) const {
|
||||
if (factor == 0.0f) return inv;
|
||||
const float width = high == low ? 0.001f : high - low;
|
||||
const float ramp = fminf(1.0f, fmaxf(0.0f, ((float)i - low) / width));
|
||||
/* Keep the blend order used by the reference YaRN implementation. */
|
||||
const float mask = 1.0f - ramp;
|
||||
return (inv / factor) * (1.0f - mask) + inv * mask;
|
||||
}
|
||||
};
|
||||
|
||||
inline RadYarn rad_yarn_args(const RadArgs* a) {
|
||||
const float factor = (float)rad_args_getf_or(a, "yarn_factor", 0.0);
|
||||
/* Disabled YaRN ignores every auxiliary coefficient on every backend. */
|
||||
if (factor == 0.0f) return {};
|
||||
return { factor,
|
||||
(float)rad_args_getf_or(a, "yarn_low", 0.0),
|
||||
(float)rad_args_getf_or(a, "yarn_high", 0.0),
|
||||
(float)rad_args_getf_or(a, "yarn_magnitude", 1.0) };
|
||||
}
|
||||
|
||||
inline bool rad_yarn_valid(const RadYarn& y) {
|
||||
return std::isfinite(y.factor) && (y.factor == 0.0f ||
|
||||
(y.factor >= 1.0f && std::isfinite(y.low) && std::isfinite(y.high) &&
|
||||
y.high >= y.low && std::isfinite(y.magnitude) && y.magnitude > 0.0f));
|
||||
}
|
||||
|
||||
#undef RAD_YARN_HD
|
||||
|
||||
#else /* C */
|
||||
#include <math.h>
|
||||
|
||||
typedef struct RadYarn {
|
||||
float factor; /* zero: YaRN off, rad_yarn_frequency() returns `inv` unchanged */
|
||||
float low;
|
||||
float high;
|
||||
float magnitude; /* 1 when off */
|
||||
} RadYarn;
|
||||
|
||||
static inline float rad_yarn_frequency(const RadYarn* y, float inv, int i) {
|
||||
float width, ramp, mask;
|
||||
if (y->factor == 0.0f) return inv;
|
||||
width = y->high == y->low ? 0.001f : y->high - y->low;
|
||||
ramp = fminf(1.0f, fmaxf(0.0f, ((float)i - y->low) / width));
|
||||
mask = 1.0f - ramp;
|
||||
return (inv / y->factor) * (1.0f - mask) + inv * mask;
|
||||
}
|
||||
|
||||
static inline RadYarn rad_yarn_args(const RadArgs* a) {
|
||||
RadYarn y = { 0.0f, 0.0f, 0.0f, 1.0f };
|
||||
y.factor = (float)rad_args_getf_or(a, "yarn_factor", 0.0);
|
||||
if (y.factor == 0.0f) return y;
|
||||
y.low = (float)rad_args_getf_or(a, "yarn_low", 0.0);
|
||||
y.high = (float)rad_args_getf_or(a, "yarn_high", 0.0);
|
||||
y.magnitude = (float)rad_args_getf_or(a, "yarn_magnitude", 1.0);
|
||||
return y;
|
||||
}
|
||||
|
||||
static inline int rad_yarn_valid(const RadYarn* y) {
|
||||
return isfinite(y->factor) && (y->factor == 0.0f ||
|
||||
(y->factor >= 1.0f && isfinite(y->low) && isfinite(y->high) && y->high >= y->low &&
|
||||
isfinite(y->magnitude) && y->magnitude > 0.0f));
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,54 @@
|
||||
# Architecture plugins: one directory and one .so each, linking only rad_abi, never the core.
|
||||
#
|
||||
# qwen35 covers the Qwen3.5, Qwen3.6 and Qwen3.8 dense models, which all report that id; qwen35moe
|
||||
# is the same graph with a routed FFN (docs/ARCHITECTURES.md). There is one plugin per
|
||||
# (architecture, quantisation) pair, which is the selection key (spec §2.4): qwen35_bf16 and
|
||||
# qwen35_fp8 both claim "qwen35" and are told apart by the container's quantisation descriptor
|
||||
# (rad_arch_quant in abi/rad_builder.h).
|
||||
#
|
||||
# Plugins are discovered, not listed, so the build is exactly what is in the tree. The glob is
|
||||
# sorted because file(GLOB) returns directory order, and the link order sets the plugin load order,
|
||||
# which decides which architecture wins a tie.
|
||||
file(GLOB RAD_ARCH_DIRS CONFIGURE_DEPENDS LIST_DIRECTORIES true ${CMAKE_CURRENT_SOURCE_DIR}/*)
|
||||
list(SORT RAD_ARCH_DIRS)
|
||||
|
||||
# In-tree plugins use the installed include spelling. arch/common/ installs as
|
||||
# <include>/radiance/arch/, so plugins write `#include <arch/rad_arch.h>`; in this tree that
|
||||
# resolves through a build-tree directory whose arch/ links to common/.
|
||||
set(RAD_ARCH_INCLUDE_ROOT ${CMAKE_BINARY_DIR}/rad_include)
|
||||
file(MAKE_DIRECTORY ${RAD_ARCH_INCLUDE_ROOT})
|
||||
if(NOT EXISTS ${RAD_ARCH_INCLUDE_ROOT}/arch)
|
||||
file(CREATE_LINK ${CMAKE_CURRENT_SOURCE_DIR}/common ${RAD_ARCH_INCLUDE_ROOT}/arch SYMBOLIC)
|
||||
endif()
|
||||
target_include_directories(rad_abi INTERFACE $<BUILD_INTERFACE:${RAD_ARCH_INCLUDE_ROOT}>)
|
||||
|
||||
foreach(d ${RAD_ARCH_DIRS})
|
||||
if(NOT IS_DIRECTORY ${d})
|
||||
continue()
|
||||
endif()
|
||||
get_filename_component(a ${d} NAME)
|
||||
# common/ is the shared header library, not a plugin.
|
||||
if(a STREQUAL "common")
|
||||
continue()
|
||||
endif()
|
||||
if(EXISTS ${d}/CMakeLists.txt)
|
||||
# Each plugin's own build rules, the same ones it uses out of tree.
|
||||
add_subdirectory(${a})
|
||||
else()
|
||||
# Reported at configure time rather than skipped silently: either a plugin is missing its build
|
||||
# file or the directory does not belong here.
|
||||
message(STATUS
|
||||
"arch: '${a}' has no CMakeLists.txt -- not an architecture plugin, skipped")
|
||||
endif()
|
||||
endforeach()
|
||||
|
||||
# arch/common/ ships: abi/rad_builder.h directs C++ plugin authors to the grp_*() helpers in
|
||||
# arch/common/rad_arch.h instead of the rad_group_*() compound-literal macros (a GNU extension in
|
||||
# C++).
|
||||
#
|
||||
# Installed flat into arch/. These headers include each other by bare basename, which resolves
|
||||
# relative to the including file in both trees, and rad_arch.h's "rad_builder.h" resolves against
|
||||
# the include root that radiance::abi provides.
|
||||
install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/common/
|
||||
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/radiance/arch
|
||||
FILES_MATCHING PATTERN "*.h")
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,210 @@
|
||||
/* rad_block_attn.h -- one grouped-query attention block with per-head q/k RMS norms, bf16
|
||||
* operands, paged KV: Qwen3's attention.
|
||||
*
|
||||
* rmsnorm -> q gemm, k gemm, v gemm -> q norm, k norm (per head) -> rope (NeoX)
|
||||
* -> kv_store -> paged attention -> o gemm -> [all_reduce] -> residual
|
||||
*
|
||||
* rad_block_attn_gated.h without the output gate, and more than a flag apart: Qwen3's q_proj is
|
||||
* [n_head * head_dim, n_embd] (queries only, no interleaved gate), the rotary covers every head
|
||||
* dimension as plain NeoX over the token's position, and the norms are plain RMS norms,
|
||||
* `x_hat * w` (Qwen3RMSNorm), not Gemma's `1 + w`. Qwen3-1.7B is Qwen3-ASR's decoder
|
||||
* (arch/qwen3asr_bf16).
|
||||
*
|
||||
* q, k and v are three projections into three contiguous buffers: paged attention reads `q`
|
||||
* contiguous (libr4d's fill_paged refuses a pitched query), so a fused [q|k|v] row would need a
|
||||
* copy before attention. Each per-head norm is an ordinary `rmsnorm` with M = tokens x heads and
|
||||
* n = head_dim, and the rotary is `rope` over q and over k, which every kernel library serves.
|
||||
*
|
||||
* Positions are RadBatch::positions, one component a token. A media span in the prompt (an audio
|
||||
* clip's placeholders) counts up like text, as the reference's position ids do; this block never
|
||||
* reads the M-RoPE planes.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_ATTN_H
|
||||
#define RAD_BLOCK_ATTN_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct AttnBF16 {
|
||||
/* The activation buffers, declared once by the plugin and shared by every layer: layers that
|
||||
* share a geometry share the buffer (spec §8). */
|
||||
struct Wire {
|
||||
rad_buf x = 0; /* [max_tok, n_embd] the residual stream */
|
||||
rad_buf h = 0; /* [max_tok, n_embd] normed input, then the o output */
|
||||
rad_buf q = 0; /* [max_tok, q_dim] projected, normed, rotated */
|
||||
rad_buf k = 0; /* [max_tok, kv_dim] */
|
||||
rad_buf v = 0; /* [max_tok, kv_dim] */
|
||||
rad_buf attn = 0; /* [max_tok, q_dim] attention output */
|
||||
};
|
||||
|
||||
/* The checkpoint-side names for one layer; the plugin owns the spelling (spec §2.4). */
|
||||
struct Src {
|
||||
const char* norm = nullptr; /* input_layernorm.weight */
|
||||
const char* q = nullptr;
|
||||
const char* k = nullptr;
|
||||
const char* v = nullptr;
|
||||
const char* q_norm = nullptr;
|
||||
const char* k_norm = nullptr;
|
||||
const char* o = nullptr;
|
||||
};
|
||||
|
||||
Geom g{};
|
||||
Wire w{};
|
||||
int layer = 0;
|
||||
rad_kvgroup kv = 0;
|
||||
|
||||
rad_weight w_norm = 0, w_q = 0, w_k = 0, w_v = 0, w_q_norm = 0, w_k_norm = 0, w_o = 0;
|
||||
rad_op op_norm = 0, op_q = 0, op_k = 0, op_v = 0, op_q_norm = 0, op_k_norm = 0;
|
||||
rad_op op_rope_q = 0, op_rope_k = 0, op_kv_store = 0, op_attn = 0, op_o = 0, op_ar = 0;
|
||||
rad_op op_add = 0;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup group,
|
||||
const Wire& wire, const Src& src);
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
};
|
||||
|
||||
inline int AttnBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup group,
|
||||
const Wire& wire, const Src& src) {
|
||||
g = geom; w = wire; layer = l; kv = group;
|
||||
const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim();
|
||||
|
||||
/* KV-head replication is not plumbed here, for the reason rad_block_attn_gated.h gives: the
|
||||
* plain row-shard of k and v would hand a rank part of one KV head. Refused by name. */
|
||||
if (g.world > g.n_head_kv_all) {
|
||||
fprintf(stderr, "radiance: %s declares no KV row span and cannot serve world_size = %d "
|
||||
"with n_head_kv = %lld\n", __func__, g.world, (long long)g.n_head_kv_all);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
/* ---- weights. [out, in], so nothing is transposed at load. q, k and v row-shard by head;
|
||||
* o column-shards, so each rank holds a partial sum of the residual update. */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l), src.norm));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q.weight", l), src.q));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k.weight", l), src.k));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_v.weight", l), src.v));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_norm.weight", l), src.q_norm));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k_norm.weight", l), src.k_norm));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_output.weight", l), src.o));
|
||||
|
||||
w_norm = decl_w(b, nm.f("blk.%d.attn_norm.weight", l), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
w_q = decl_w(b, nm.f("blk.%d.attn_q.weight", l), RAD_BF16, {q_dim, g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
|
||||
w_k = decl_w(b, nm.f("blk.%d.attn_k.weight", l), RAD_BF16, {kv_dim, g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
|
||||
w_v = decl_w(b, nm.f("blk.%d.attn_v.weight", l), RAD_BF16, {kv_dim, g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
|
||||
/* One gain shared by every head, replicated across ranks though the heads are not. */
|
||||
w_q_norm = decl_w(b, nm.f("blk.%d.attn_q_norm.weight", l), RAD_F32, {g.head_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
w_k_norm = decl_w(b, nm.f("blk.%d.attn_k_norm.weight", l), RAD_F32, {g.head_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
w_o = decl_w(b, nm.f("blk.%d.attn_output.weight", l), RAD_BF16, {g.n_embd, q_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, grp_layer(l));
|
||||
|
||||
auto gemm = [&](int64_t N, int64_t K, rad_weight wt) {
|
||||
return RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(wt));
|
||||
};
|
||||
auto head_norm = [&](int64_t heads, rad_weight wt) {
|
||||
return RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * heads), RAD_INT("n", g.head_dim),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(wt));
|
||||
};
|
||||
|
||||
op_norm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_norm)),
|
||||
{w.x}, {w.h});
|
||||
op_q = rw(b, gemm(q_dim, g.n_embd, w_q), {w.h}, {w.q});
|
||||
op_k = rw(b, gemm(kv_dim, g.n_embd, w_k), {w.h}, {w.k});
|
||||
op_v = rw(b, gemm(kv_dim, g.n_embd, w_v), {w.h}, {w.v});
|
||||
/* Each norm runs in place: a row's scale is computed before the row is written. */
|
||||
op_q_norm = rw(b, head_norm(g.n_head, w_q_norm), {w.q}, {w.q});
|
||||
op_k_norm = rw(b, head_norm(g.n_head_kv, w_k_norm), {w.k}, {w.k});
|
||||
/* Two rope calls because q and k are two buffers: a `rope` that names only q heads is a fused
|
||||
* row with an empty k and v. The full head dim rotates. */
|
||||
op_rope_q = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, 0, g.head_dim, "neox"),
|
||||
{w.q}, {w.q});
|
||||
op_rope_k = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head_kv, 0, g.head_dim, "neox"),
|
||||
{w.k}, {w.k});
|
||||
|
||||
/* attn_paged before kv_store: block_size is RAD_DERIVED, read off the resolved attention
|
||||
* kernel and back into kv_store with rad_kv_block_size() (rad_block_attn_gated.h says why). */
|
||||
op_attn = rw(b, RAD_OP(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", 0), RAD_INT("n_head", g.n_head),
|
||||
RAD_INT("block_size", RAD_KV_BLOCK),
|
||||
RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
|
||||
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.q}, {w.attn});
|
||||
op_kv_store = rw(b, RAD_OP(b, "kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head_kv", g.n_head_kv),
|
||||
RAD_INT("block_size", rad_kv_block_size(b, kv)),
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.k, w.v}, {});
|
||||
|
||||
op_o = rw(b, gemm(g.n_embd, q_dim, w_o), {w.attn}, {w.h});
|
||||
if (g.world > 1)
|
||||
op_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h}, {w.h});
|
||||
op_add = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.x, w.h}, {w.x});
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
inline void AttnBF16::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
|
||||
const int32_t* table = kvb ? kvb->block_table : nullptr;
|
||||
const int32_t* used = kvb ? kvb->seqused : nullptr;
|
||||
const int64_t T = batch->n_tok;
|
||||
const RadOperand pos = praw(batch->positions, RAD_I32, T);
|
||||
|
||||
RAD_ISSUE(c, op_norm, brows(w.x, T), RAD_W(w_norm), brows(w.h, T));
|
||||
RAD_ISSUE(c, op_q, brows(w.h, T), RAD_W(w_q), brows(w.q, T));
|
||||
RAD_ISSUE(c, op_k, brows(w.h, T), RAD_W(w_k), brows(w.k, T));
|
||||
RAD_ISSUE(c, op_v, brows(w.h, T), RAD_W(w_v), brows(w.v, T));
|
||||
RAD_ISSUE_N(c, op_q_norm, T * g.n_head, brows(w.q, T), RAD_W(w_q_norm), brows(w.q, T));
|
||||
RAD_ISSUE_N(c, op_k_norm, T * g.n_head_kv, brows(w.k, T), RAD_W(w_k_norm), brows(w.k, T));
|
||||
RAD_ISSUE(c, op_rope_q, brows(w.q, T), pos);
|
||||
RAD_ISSUE(c, op_rope_k, brows(w.k, T), pos);
|
||||
RAD_ISSUE(c, op_kv_store,
|
||||
brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer));
|
||||
/* The actual query length selects the band; cu_seqlens carries a ragged step. */
|
||||
RAD_ISSUE_N(c, op_attn, batch->max_q_len,
|
||||
brows(w.q, T), kv_cache(kv, layer),
|
||||
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
|
||||
praw(used, RAD_I32, batch->n_seq),
|
||||
RAD_NONE, RAD_NONE,
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
|
||||
brows(w.attn, T));
|
||||
RAD_ISSUE(c, op_o, brows(w.attn, T), RAD_W(w_o), brows(w.h, T));
|
||||
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
|
||||
RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h, T), brows(w.x, T));
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_ATTN_H */
|
||||
@@ -0,0 +1,209 @@
|
||||
/* rad_block_attn_fp8.h -- plain GQA attention with block-scaled FP8 projections.
|
||||
*
|
||||
* rmsnorm -> quant_act_fp8 -> fused q|k|v gemm_nt_q -> rope -> kv_store -> attn_paged
|
||||
* -> quant_act_fp8 -> o gemm_nt_q -> [all_reduce] -> residual add
|
||||
*
|
||||
* rad_block_attn_gated_fp8.h without its two family-specific features:
|
||||
*
|
||||
* - No per-head q/k norm. Qwen3.5 norms each head before rotating; LLaMA and MiniCPM5 rotate
|
||||
* the GEMM output directly.
|
||||
* - No output gate. The attention output goes straight into the out-projection.
|
||||
*
|
||||
* That allows a fused q|k|v, which the gated block cannot have (its query projection is [q|gate]
|
||||
* interleaved per head). The three weights concatenate along dim 0 into one
|
||||
* [q_dim + 2*kv_dim, n_embd], and `rope` takes that row as is: q heads, then k heads, v untouched
|
||||
* (docs/OPS.md). One GEMM, one rope and one quantise.
|
||||
*
|
||||
* `row_parts` is required: a tensor-parallel rank owns a slice of each of the three projections,
|
||||
* not a contiguous slice of the stack. LinearFP8 checks that each part is a whole number of
|
||||
* 128-row scale blocks.
|
||||
*
|
||||
* The fused front op, the KV dtype and the fold flags are documented in rad_fp8.h and
|
||||
* rad_block_attn_gated_fp8.h.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_ATTN_FP8_H
|
||||
#define RAD_BLOCK_ATTN_FP8_H
|
||||
|
||||
#include "rad_fp8.h"
|
||||
|
||||
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 */
|
||||
};
|
||||
|
||||
/* Checkpoint tensor names; the declaration is the same whether they hold block fp8 or a dense
|
||||
* tensor the recipe quantises. */
|
||||
struct Src {
|
||||
const char* norm = nullptr;
|
||||
const char* q = nullptr;
|
||||
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, HF's rotate_half), as LLaMA derivatives ship. Stated
|
||||
* explicitly: GPT-J's adjacent pairs would pass every per-op check too. */
|
||||
const char* mode = "neox";
|
||||
|
||||
rad_weight w_norm = 0;
|
||||
LinearFP8 qkv{}, o{};
|
||||
NormQuantFP8 nq_h{};
|
||||
QuantFP8 q_attn{};
|
||||
rad_op op_rope = 0, op_qlift = 0, op_attn = 0, op_kv_store = 0;
|
||||
rad_op op_ar = 0, op_add = 0;
|
||||
bool ar_out = false;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup group,
|
||||
int64_t rotary_dim, const Wire& wire, const Src& src,
|
||||
bool fold = false, bool add_out = true,
|
||||
int ar_in = kArNone, bool ar_out_ = false);
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
};
|
||||
|
||||
inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup group,
|
||||
int64_t rotary_dim, const Wire& wire, const Src& src,
|
||||
bool fold, bool add_out, int ar_in, bool ar_out_) {
|
||||
g = geom; w = wire; layer = l;
|
||||
ar_out = ar_out_; kv = group; n_rot = rotary_dim;
|
||||
|
||||
const int64_t q_dim = g.q_dim();
|
||||
const int64_t kv_dim = g.kv_dim();
|
||||
|
||||
if (n_rot <= 0 || n_rot > g.head_dim || (n_rot & 1)) {
|
||||
fprintf(stderr, "radiance: rotary_dim %lld is not an even width inside head_dim %lld\n",
|
||||
(long long)n_rot, (long long)g.head_dim);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* No KV-head replication: the fused [q|k|v] uses the plain even row shard, so above the KV head
|
||||
* count a rank would read the wrong rows. rad_block_attn_gated_fp8.h is the block that uses
|
||||
* geom_from's `kv_off`. */
|
||||
if (g.world > g.n_head_kv_all) {
|
||||
fprintf(stderr, "radiance: %s declares no KV row span and cannot serve world_size = %d "
|
||||
"with n_head_kv = %lld.\n", __func__, g.world,
|
||||
(long long)g.n_head_kv_all);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l), src.norm));
|
||||
w_norm = decl_w(b, nm.f("blk.%d.attn_norm.weight", l), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
|
||||
/* Norm and quantise in one op (rad_fp8.h: NormQuantFP8). */
|
||||
RAD_ARCH_TRY(nq_h.declare(b, g, w_norm, fold ? w.h.x : w.x, w.h, g.n_embd,
|
||||
fold ? w.x : 0, 0, ar_in));
|
||||
RAD_ARCH_TRY(qkv.declare(b, nm, g, nm.f("blk.%d.attn_qkv", l), q_dim + 2 * kv_dim, g.n_embd,
|
||||
RAD_SHARD_ROW, grp_layer(l), { src.q, src.k, src.v }, w.h, w.qkv,
|
||||
0, { q_dim, kv_dim, kv_dim }));
|
||||
|
||||
op_rope = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, g.n_head_kv, n_rot, mode),
|
||||
{w.qkv}, {w.qkv});
|
||||
|
||||
/* Copies the query out of the fused row: libr4d's paged attention reads `q` as a dense
|
||||
* [total_q, n_head, head_dim] block with no pitch argument (r4d_attn_args.h, fill_paged), so a
|
||||
* column slice with pitch q_dim + 2*kv_dim is refused at issue. One copy per layer is cheaper
|
||||
* at decode than splitting the projection (one more GEMM and one more rope). Remove it if the
|
||||
* kernels gain a q pitch. `cast` with from == to is this tree's row copy. */
|
||||
op_qlift = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", q_dim),
|
||||
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.qkv}, {w.q});
|
||||
|
||||
/* Declared before kv_store, which reads back the resolved `block_size` (rad_block_attn_gated.h
|
||||
* explains declare vs issue order). */
|
||||
op_attn = rw(b, RAD_OP(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
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; a plain `quant_act_fp8`, as there is no gate pass to
|
||||
* fold it into. */
|
||||
RAD_ARCH_TRY(q_attn.declare(b, g, w.attn, q_dim));
|
||||
RAD_ARCH_TRY(o.declare(b, nm, g, nm.f("blk.%d.attn_output", l), g.n_embd, q_dim,
|
||||
RAD_SHARD_COL, grp_layer(l), { src.o }, w.attn, w.h.x));
|
||||
|
||||
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: rotates n_head query heads, then n_head_kv key heads, and
|
||||
* leaves the value heads alone. */
|
||||
RAD_ISSUE(c, op_rope, brows(w.qkv, T), rope_posmc(g, batch, T));
|
||||
|
||||
/* k and v are column slices of the fused row, at q_dim and q_dim + kv_dim. */
|
||||
RAD_ISSUE(c, op_kv_store,
|
||||
bcol(w.qkv, q_dim, kv_dim, T), bcol(w.qkv, q_dim + kv_dim, kv_dim, T),
|
||||
praw(slot, RAD_I32, T), kv_cache(kv, layer));
|
||||
|
||||
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 */
|
||||
@@ -0,0 +1,313 @@
|
||||
/* rad_block_attn_gated.h -- gated grouped-query attention, bf16 operands, paged KV.
|
||||
*
|
||||
* rmsnorm -> q|gate gemm, k gemm, v gemm -> qk-norm + rope -> kv_store -> paged attention
|
||||
* -> attn * sigmoid(gate) -> o gemm -> [all_reduce] -> residual
|
||||
*
|
||||
* Qwen3.5's attention, which differs from Qwen3's in three ways:
|
||||
*
|
||||
* * `q_proj` emits the query and a per-head output gate interleaved at a pitch of 2*head_dim:
|
||||
* head h's query at h*2*head_dim, its gate at h*2*head_dim + head_dim. Both are strided views
|
||||
* of one buffer. libr4d's `qk_norm_rope_gate` takes the stride from the `qg` operand's row
|
||||
* pitch (there is no `qg_pitch` parameter; pQkNormRopeGate in libr4d/r4d_rows.cpp), so the
|
||||
* interleaved layout is declared as is.
|
||||
* * The gate multiplies the attention output, `out = attn * sigmoid(gate)`. The config's `output_gate_type: "swish"` refers to the
|
||||
* GDN block's gate; this one is sigmoid, as in llama.cpp (src/models/qwen35.cpp,
|
||||
* build_layer_attn).
|
||||
* * RoPE is partial (`partial_rotary_factor` 0.25 rotates the first 64 of 256 head dims) and is
|
||||
* M-RoPE; see `mode` in declare().
|
||||
*
|
||||
* k and v are separate projections (two GEMMs, two movement units) so every consumer gets a
|
||||
* contiguous operand. With a fused [k|v] row the per-head k norm would be a column slice whose
|
||||
* last dimension is kv_dim, not head_dim, and a kernel reading extents from its operands (libref
|
||||
* does) would normalise across the k/v seam. libr4d's kernel takes a `k_pitch` for the fused
|
||||
* form, so a quantised sibling can fuse without changing this block's shape.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_ATTN_GATED_H
|
||||
#define RAD_BLOCK_ATTN_GATED_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct AttnGatedBF16 {
|
||||
/* Activation buffers, declared once by the plugin and shared by every layer of this kind
|
||||
* (spec §3.1); liveness over the declared read/write sets makes the sharing safe. */
|
||||
struct Wire {
|
||||
rad_buf x = 0; /* [max_tok, n_embd] the residual stream */
|
||||
rad_buf h = 0; /* [max_tok, n_embd] normed input, then the o output */
|
||||
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] sigmoid of the de-interleaved gate */
|
||||
rad_buf attn = 0; /* [max_tok, q_dim] attention output, then gated in place */
|
||||
};
|
||||
|
||||
/* Checkpoint-side names for one layer, supplied by the plugin, which owns the map (spec §2.4):
|
||||
* `model.language_model.layers.N.*` from safetensors, `blk.N.*` from GGUF. */
|
||||
struct Src {
|
||||
const char* norm = nullptr; /* input_layernorm.weight */
|
||||
const char* qg = nullptr; /* self_attn.q_proj.weight -- query AND gate */
|
||||
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_q_norm = 0, op_k_norm = 0, op_rope_q = 0, op_rope_k = 0;
|
||||
rad_op op_attn = 0, op_kv_store = 0, op_sigmoid = 0, op_gate = 0;
|
||||
rad_op op_o = 0, op_ar = 0, op_add = 0;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup group,
|
||||
int64_t rotary_dim, const Wire& wire, const Src& src);
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
};
|
||||
|
||||
inline int AttnGatedBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
rad_kvgroup group, int64_t rotary_dim, const Wire& wire,
|
||||
const Src& src) {
|
||||
g = geom; w = wire; layer = l; kv = group; n_rot = rotary_dim;
|
||||
|
||||
const int64_t q_dim = g.q_dim();
|
||||
const int64_t kv_dim = g.kv_dim();
|
||||
const int64_t qg_dim = 2 * q_dim; /* query and gate, one per head, interleaved */
|
||||
|
||||
if (n_rot <= 0 || n_rot > g.head_dim || (n_rot & 1)) {
|
||||
fprintf(stderr, "radiance: rotary_dim %lld is not an even width inside head_dim %lld\n",
|
||||
(long long)n_rot, (long long)g.head_dim);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* KV-head replication is not supported here. Above the KV head count geom_from gives each rank
|
||||
* one KV head and a `kv_off` row span, but this block declares k and v with the plain even
|
||||
* row shard, which would hand a rank part of one head and compute wrong values. The span is
|
||||
* passed in rad_block_attn_gated_fp8.h. */
|
||||
if (g.world > g.n_head_kv_all) {
|
||||
fprintf(stderr, "radiance: %s declares no KV row span and cannot serve world_size = %d "
|
||||
"with n_head_kv = %lld; the KV-head replication in geom_from needs the "
|
||||
"span passed to its k/v weights.\n", __func__, g.world,
|
||||
(long long)g.n_head_kv_all);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
/* ---- weights. Shapes are [out, in]: gemm_nt multiplies A[M,K] by B[N,K] transposed, the
|
||||
* layout checkpoints already use.
|
||||
*
|
||||
* The q|gate projection row-shards by head because each head's query and gate are adjacent:
|
||||
* rows [h*2*head_dim, (h+1)*2*head_dim) are one head's pair, so a rank's heads form a
|
||||
* contiguous row range. */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l), src.norm));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_qg.weight", l), src.qg));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k.weight", l), src.k));
|
||||
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 replicated across ranks. */
|
||||
w_q_norm = decl_w(b, nm.f("blk.%d.attn_q_norm.weight", l), RAD_F32, {g.head_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
w_k_norm = decl_w(b, nm.f("blk.%d.attn_k_norm.weight", l), RAD_F32, {g.head_dim},
|
||||
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 run order except attn_paged (see there). Each states its read and write sets,
|
||||
* from which the buffer planner computes liveness. */
|
||||
op_norm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), RAD_STR("dtype", g.dtype)),
|
||||
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});
|
||||
|
||||
/* The fused qk_norm_rope_gate is not declared: libr4d's version (libr4d/r4d_rows.cpp,
|
||||
* pQkNormRopeGate) takes a precomputed cos/sin table operand, and this block has no PERSIST
|
||||
* [max_ctx, rot] table to give it. The unfused sequence below runs everywhere, including
|
||||
* without libr4d.
|
||||
*
|
||||
* `mode` is "mrope" (mrope_section [11,11,10], interleaved). Each rotary dimension has its own
|
||||
* frequency and the section only chooses which position component feeds it, so with equal
|
||||
* components (text) mrope is bit-identical to neox.
|
||||
*
|
||||
* Per-head RMS norm is a rmsnorm with M = tokens x heads, n = head_dim. The q norm reads the
|
||||
* strided view of the interleaved projection and writes the contiguous q buffer, so it
|
||||
* de-interleaves in the same pass. The k norm runs in place, which is safe because a row's
|
||||
* scale is computed before the row is written. */
|
||||
op_q_norm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head),
|
||||
RAD_INT("n", g.head_dim),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_q_norm)),
|
||||
{w.qg}, {w.q});
|
||||
op_k_norm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head_kv),
|
||||
RAD_INT("n", g.head_dim),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_k_norm)),
|
||||
{w.k}, {w.k});
|
||||
/* Two rope calls because q and k are separate buffers. `rope` describes a fused [q|k|v] row by
|
||||
* n_head and n_head_kv; n_head_kv 0 makes it a q-only (or k-only) row. */
|
||||
op_rope_q = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, 0, n_rot, mode),
|
||||
{w.q}, {w.q});
|
||||
op_rope_k = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head_kv, 0, n_rot, mode),
|
||||
{w.k}, {w.k});
|
||||
|
||||
/* attn_paged is declared before kv_store although it runs after it. `block_size` is
|
||||
* RAD_DERIVED, a property of the resolved attention kernel (spec §7.2): the selector writes the
|
||||
* winner's value into the resolved geometry and kv_store reads it with rad_kv_block_size().
|
||||
* The ops touch disjoint buffers, so the order mismatch does not affect buffer planning.
|
||||
*
|
||||
* The ranged parameter is q_len, not M: 1 at decode, up to n_spec+1 at a verify, thousands in
|
||||
* a prefill chunk, with a libr4d kernel per band. `scale` defaults to 1/sqrt(head_dim). */
|
||||
op_attn = rw(b, RAD_OP(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", 0),
|
||||
/* Bounds for the kernel's scratch hook: libr4d sizes a split-KV
|
||||
* partial buffer of num_seqs * q_len * q_heads * splits rows. */
|
||||
RAD_INT("n_head", g.n_head), RAD_INT("block_size", RAD_KV_BLOCK), RAD_INT("max_seqs", g.max_seqs),
|
||||
RAD_INT("max_ctx", g.max_ctx),
|
||||
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.q}, {w.attn});
|
||||
|
||||
/* kv_store writes the group's pool, which is not a declared buffer, so its write set is
|
||||
* empty. */
|
||||
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, as two ops: the op vocabulary has no gated multiply with a bf16 output
|
||||
* (`gated_had_quant_i8` is the same arithmetic with an int8 epilogue). The sigmoid reads the
|
||||
* strided gate view of the interleaved projection into the contiguous gate buffer. */
|
||||
op_sigmoid = rw(b, RAD_OP(b, "sigmoid",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head),
|
||||
RAD_INT("n", g.head_dim), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.qg}, {w.gate});
|
||||
|
||||
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 column-sharded output projection leaves a partial sum on each rank. The plugin emits the
|
||||
* collective itself, so --debug-graph shows it here (spec §9). `exact` is always stated, so a
|
||||
* deployment that has not accepted a lossy wire gets the exact kernel. `hops` (one-shot vs
|
||||
* two-shot) is left to the kernel library, by message size. */
|
||||
if (g.world > 1)
|
||||
op_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
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 {
|
||||
/* Issue statuses are ignored: rad_issue records a failure and the core aborts the step and
|
||||
* fails its requests, naming the kernel and geometry (spec §17). */
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
|
||||
const int32_t* table = kvb ? kvb->block_table : nullptr;
|
||||
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));
|
||||
|
||||
/* The q view of the interleaved projection: head_dim columns of every 2*head_dim. */
|
||||
RAD_ISSUE_N(c, op_q_norm, T * g.n_head,
|
||||
bcol(w.qg, 0, g.head_dim, T), RAD_W(w_q_norm), brows(w.q, T));
|
||||
RAD_ISSUE_N(c, op_k_norm, T * g.n_head_kv,
|
||||
brows(w.k, T), RAD_W(w_k_norm), brows(w.k, T));
|
||||
RAD_ISSUE(c, op_rope_q, brows(w.q, T), rope_posmc(g, batch, T));
|
||||
RAD_ISSUE(c, op_rope_k, brows(w.k, T), rope_posmc(g, batch, T));
|
||||
|
||||
RAD_ISSUE(c, op_kv_store,
|
||||
brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer));
|
||||
|
||||
/* The longest query length, not the token count, selects the attention band: a verify step and
|
||||
* a prefill chunk can have the same token count at very different q_len. */
|
||||
RAD_ISSUE_N(c, op_attn, batch->max_q_len,
|
||||
brows(w.q, T), kv_cache(kv, layer),
|
||||
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
|
||||
praw(used, RAD_I32, batch->n_seq),
|
||||
RAD_NONE, RAD_NONE,
|
||||
/* cu_seqlens: the batch may be ragged (a prefill chunk beside decode rows). */
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
|
||||
brows(w.attn, T));
|
||||
|
||||
/* out = attn * sigmoid(gate), the gate read out of the interleaved projection. */
|
||||
RAD_ISSUE_N(c, op_sigmoid, T * g.n_head,
|
||||
bcol(w.qg, g.head_dim, g.head_dim, T), brows(w.gate, T));
|
||||
RAD_ISSUE(c, op_gate, brows(w.attn, T), brows(w.gate, T), brows(w.attn, T));
|
||||
|
||||
RAD_ISSUE(c, op_o, brows(w.attn, T), RAD_W(w_o), brows(w.h, T));
|
||||
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 */
|
||||
@@ -0,0 +1,630 @@
|
||||
/* rad_block_attn_gated_fp8.h -- gated GQA attention with block-scaled FP8 projections.
|
||||
*
|
||||
* The architecture (interleaved q|gate projection, partial M-RoPE, separate k and v, sigmoid
|
||||
* gate) is documented in rad_block_attn_gated.h. What differs here:
|
||||
*
|
||||
* - q|gate, k, v and o are LinearFP8: an E4M3 weight with a bf16 [N/128][K/128] scale plane,
|
||||
* through `gemm_nt_q` at dtype fp8a8.
|
||||
* - One input quantise feeds the three input projections (they all read the post-norm hidden
|
||||
* state); the gate pass quantises the out-projection's input.
|
||||
* - Per-head norms, rope, kv_store and attn_paged stay bf16.
|
||||
* - The KV cache dtype is `g.kv_dtype`, not `g.dtype`: it is a deployment choice that selects
|
||||
* libr4d's fp8kv attention family. The attention op and kv_store both take it, so they agree.
|
||||
* - Optional fused prologue, QSA sparse attention and an attention-zero mode (see declare).
|
||||
*
|
||||
* The q|gate projection is [2*n_head*head_dim, n_embd] = [12288, 5120] at 27B, scale plane
|
||||
* [96, 40]. Row-sharding by head keeps whole 128-row scale blocks only because 2*head_dim = 512 is
|
||||
* a multiple of 128; LinearFP8 checks this.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_ATTN_GATED_FP8_H
|
||||
#define RAD_BLOCK_ATTN_GATED_FP8_H
|
||||
|
||||
#include "rad_fp8.h"
|
||||
|
||||
#include <cstring>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct AttnGatedFP8 {
|
||||
struct Wire {
|
||||
rad_buf x = 0; /* [max_tok, n_embd] the residual stream */
|
||||
ActFP8 h{}; /* [max_tok, n_embd] normed input, then the o output */
|
||||
rad_buf qg = 0; /* [max_tok, n_head, 2*head_dim] query and gate, interleaved */
|
||||
rad_buf k = 0; /* [max_tok, kv_dim] */
|
||||
rad_buf v = 0; /* [max_tok, kv_dim] */
|
||||
rad_buf q = 0; /* [max_tok, q_dim] de-interleaved, normed, rotated */
|
||||
/* [rope_table_rows, rot] f32 cos/sin table, shared by every layer, filled once a step. Zero
|
||||
* if the plugin builds none; the fused prologue is then not requested. */
|
||||
rad_buf cos_sin = 0;
|
||||
ActFP8 attn{}; /* [max_tok, q_dim] attention output, then gated in place */
|
||||
/* [max_tok, q_dim] de-interleaved sigmoid gate, used only with bf16 linears
|
||||
* (Geom::w_bf16), where the gate is `sigmoid` then `mul`; the fused gate quantiser always
|
||||
* writes codes. */
|
||||
rad_buf gate = 0;
|
||||
};
|
||||
|
||||
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 (16). Qwen4-Exp's QSA selects 4-token blocks,
|
||||
* and a page of 4 turns the selected set into a paged block table, so no new attention kernel
|
||||
* is needed (docs/QSA.md). The attention kernel's rows must carry a matching
|
||||
* C_EQ("block_size", ...) or nothing resolves. */
|
||||
int64_t kv_block = 0;
|
||||
/* The QSA selection, when this layer has an indexer (produced by arch/common/rad_qsa.h; see
|
||||
* docs/QSA.md). On a sparse step the attention is issued with these in place of each row's
|
||||
* block table and context length: same op, same kernel, different list. `sel` is `topk + 1`
|
||||
* wide and the kernel takes its block-table pitch from the operand. */
|
||||
rad_buf qsa_sel = 0;
|
||||
rad_buf qsa_sequ = 0;
|
||||
/* Context length up to which dense attention gives the same result, `budget + ratio - 1`.
|
||||
* Below it every complete block is selected, the paths agree to the bit, and dense is cheaper
|
||||
* at prefill (it reads each key once per query tile, sparse reads a table per query). Zero
|
||||
* means always sparse. */
|
||||
int64_t qsa_exact_to = 0;
|
||||
/* `sel`'s row pitch is `topk + 1`; the extra slot is the partial page
|
||||
* (r4d_qsa_select_bf16.hip). */
|
||||
int64_t qsa_topk = 0;
|
||||
/* Query rows per sparse attention launch, a scratch budget. The decode kernel's split-KV
|
||||
* partials are sized at declare from `max_seqs` and `q_len`, so issuing more rows than
|
||||
* `max_seqs` means declaring a larger value, which grows the scratch arena (the maximum over
|
||||
* ops) by `rows * q_len_band * n_head * (head_dim + 2) * 4` bytes: about 32 MiB at 256 rows on
|
||||
* this model, 63 MiB at 512, 253 MiB at 2048. With max_seqs alone, `--max-num-seqs 4` would
|
||||
* split a 2048-token prefill chunk into 512 launches per layer; 256 makes it 8, past which
|
||||
* launch cost no longer matters. */
|
||||
static constexpr int64_t kQsaRows = 256;
|
||||
int64_t qsa_rows() const { return g.max_seqs > kQsaRows ? g.max_seqs : kQsaRows; }
|
||||
/* The gated form takes the whole step in one launch: its band is q_len 1, so partials are only
|
||||
* `rows * n_head * (2 * head_dim + 8)` bytes (12.8 MiB for 2048 rows on this model). One
|
||||
* 2048-row launch is about 2.16 ms per layer versus 3.0 ms for eight 256-row launches, each
|
||||
* with its own tail. */
|
||||
int64_t qsa_gq_rows() const { return g.max_tok > qsa_rows() ? g.max_tok : qsa_rows(); }
|
||||
/* The rotation's pairing. Halves (NeoX, HF's rotate_half over the partial rotary width) and
|
||||
* adjacent pairs (GPT-J) are both self-consistent and pass every per-op check, so it must be
|
||||
* stated. "mrope" over one position component per token is NeoX (rad_block_attn_gated.h).
|
||||
*
|
||||
* The q|gate order is fixed as well: q is the first half of each head's pair, the gate the
|
||||
* second (as vLLM chunks q_gate). The unfused q norm reads column 0 of each head, the gate
|
||||
* quantiser column head_dim, and the fused prologue splits the same way. A swap would pass
|
||||
* silently, since q_norm and the sigmoid accept either half. */
|
||||
const char* mode = "mrope";
|
||||
|
||||
rad_weight w_norm = 0, w_q_norm = 0, w_k_norm = 0;
|
||||
/* 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; /* the same with kv_store folded in */
|
||||
int64_t fused_rows = 0; /* widest T the fused ops take */
|
||||
rad_op op_q_norm = 0, op_k_norm = 0, op_rope_q = 0, op_rope_k = 0;
|
||||
rad_op op_attn = 0, op_kv_store = 0, op_gq = 0;
|
||||
rad_op op_attn_gq = 0; /* attn_paged + gate_quant_fp8 */
|
||||
/* The output gate as `sigmoid` then `mul`: the bf16-linear form (Geom::w_bf16), and with fp8
|
||||
* linears the chain gate_quant_fp8 fuses, where it is not served. `gate` is the sigmoid's
|
||||
* output (the wire's with bf16 linears, the block's own otherwise) and `q_gate` the chain's
|
||||
* quantiser (no op with bf16 linears). */
|
||||
rad_op op_sig = 0, op_mul = 0;
|
||||
rad_buf gate = 0;
|
||||
QuantFP8 q_gate{};
|
||||
rad_op op_ar = 0, op_add = 0;
|
||||
rad_op op_fill = 0; /* the attention-zero rank: see declare */
|
||||
/* The next block absorbs this block's closing all-reduce, so this one must not issue it.
|
||||
* Counterpart of `ar_in` (this block's norm absorbs the predecessor's); separate because a
|
||||
* block is declared without knowing what follows. Both sides ask ar_fused_ok(g, T), so they
|
||||
* agree on whether the collective was issued. */
|
||||
bool ar_out = false;
|
||||
/* Which wires that consumer takes (ArOut, rad_fp8.h): the norm's by default, or a gated
|
||||
* residual's own (HyperConn::ar_take). Set before declare; both sides then ask
|
||||
* ar_taken(g, T, ar_out, ar_out_take). */
|
||||
int ar_out_take = kArOutNorm;
|
||||
|
||||
/* `fold`: the previous block left its delta in `w.h.x` for this norm to add. `add_out`: the
|
||||
* next block will not add, so this one issues the trailing add. See rad_fp8.h. */
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup group,
|
||||
int64_t rotary_dim, const Wire& wire, const Src& src,
|
||||
bool fold = false, bool add_out = true,
|
||||
int ar_in = kArNone, bool ar_out_ = false);
|
||||
/* Stores the pass's K and V exactly as step() does, with no query, attention or output. Used
|
||||
* by passes that only leave layer state behind, such as the MTP head's history pass over a
|
||||
* prompt chunk with no drafting row. */
|
||||
void store_kv(RadCtx* c, const RadBatch* batch) const;
|
||||
|
||||
/* The block's tail, declared last by every rank: the all-reduce and the trailing add. */
|
||||
int declare_out(RadBuilder* b, bool add_out);
|
||||
/* `own_ar` false: the caller issues the all-reduce itself (GdnFP8::step says when). */
|
||||
void step(RadCtx* c, const RadBatch* batch, bool own_ar = true,
|
||||
ArPieces* pieces = nullptr) const;
|
||||
bool issues_ar(int64_t T) const { return op_ar && !ar_taken(g, T, ar_out, ar_out_take); }
|
||||
void issue_ar(RadCtx* c, int64_t r0, int64_t rows) const {
|
||||
RAD_ISSUE_N(c, op_ar_ov ? op_ar_ov : op_ar, rows * g.n_embd,
|
||||
brow_slice(w.h.x, r0, rows, g.n_embd), RAD_NONE);
|
||||
}
|
||||
/* Set before declare: the `overlap` issue_ar's collective is declared at, 0 for none. */
|
||||
int ar_overlap = 0;
|
||||
rad_op op_ar_ov = 0;
|
||||
};
|
||||
|
||||
inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
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;
|
||||
|
||||
/* Row spans, in the container's unsharded rows, used where the even shard is the wrong cut.
|
||||
*
|
||||
* Above the KV head count geom_from replicates KV heads (rad_arch.h): with 2 KV heads at
|
||||
* head_dim 256 and 4 ranks, the k/v entry is 512 rows and ranks 0-1 take [0, 256), ranks 2-3
|
||||
* [256, 512), where the even shard would hand rank 2 half a head. The scale plane takes the
|
||||
* same span in 128-blocks; kv_off is a multiple of head_dim, so it never cuts a block. At
|
||||
* world <= n_head_kv_all the span stays 0/0 and the even shard applies.
|
||||
*
|
||||
* Under a smaller attention world (Geom::attn_world) q|gate and the output also take this
|
||||
* rank's heads [attn_rank * n_head, +n_head) as a span. An attention-zero rank declares none
|
||||
* of them (see the `fill` below). */
|
||||
const bool a_spanned = g.attn_world != g.world;
|
||||
const bool kv_spanned = g.world > g.n_head_kv_all || a_spanned;
|
||||
const int64_t kv_span_lo = kv_spanned ? g.kv_off : 0;
|
||||
const int64_t kv_span_hi = kv_spanned ? g.kv_off + kv_dim : 0;
|
||||
const int64_t qg_span_lo = a_spanned ? g.attn_rank * qg_dim : 0;
|
||||
const int64_t qg_span_hi = a_spanned ? (g.attn_rank + 1) * qg_dim : 0;
|
||||
const int64_t o_span_lo = a_spanned ? g.attn_rank * q_dim : 0;
|
||||
const int64_t o_span_hi = a_spanned ? (g.attn_rank + 1) * q_dim : 0;
|
||||
|
||||
if (n_rot <= 0 || n_rot > g.head_dim || (n_rot & 1)) {
|
||||
fprintf(stderr, "radiance: rotary_dim %lld is not an even width inside head_dim %lld\n",
|
||||
(long long)n_rot, (long long)g.head_dim);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* `src.norm == nullptr`: the architecture prepares the input. A pre-norm block owns its norm
|
||||
* (rad_fp8.h's NormQuantFP8: add the previous delta, normalise, quantise). In a gated-residual
|
||||
* model, rad_block_hc.h's `hc_read` produces the block input from a 4x wider stream, so this
|
||||
* block takes `wire.h` as already normed and quantised and declares no norm weight.
|
||||
*
|
||||
* `ar_in` is refused in that mode: the fused all-reduce lives inside the norm, so it would be
|
||||
* silently dropped. The caller emits a standalone collective instead (`add_out`/`ar_out`). */
|
||||
ext_in = (src.norm == nullptr);
|
||||
if (ext_in) {
|
||||
if (!w.h.x || (!g.w_bf16 && (!w.h.q || !w.h.s)) || ar_in != kArNone) return RAD_E_INVAL;
|
||||
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+quantise op feeds all three input projections (rad_fp8.h: NormQuantFP8). */
|
||||
if (!ext_in)
|
||||
RAD_ARCH_TRY(nq_h.declare(b, g, w_norm, fold ? w.h.x : w.x, w.h, g.n_embd,
|
||||
fold ? w.x : 0, 0, ar_in));
|
||||
|
||||
/* An attention-zero rank holds no heads, so its output projection contributes zero to the
|
||||
* reduce. Its output wire is zeroed by one `fill` instead of running projections on zero
|
||||
* weights (and it keeps no KV pool, rad_kv_group_zero). The all-reduce and residual add run as
|
||||
* usual, and the norm above stays because a pre-norm block's `fold` and `ar_in` live in it. */
|
||||
if (g.attn_zero) {
|
||||
op_fill = rw(b, RAD_OP(b, "fill",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, {w.h.x});
|
||||
return declare_out(b, add_out);
|
||||
}
|
||||
RAD_ARCH_TRY(qg.declare(b, nm, g, nm.f("blk.%d.attn_qg", l), qg_dim, g.n_embd,
|
||||
RAD_SHARD_ROW, grp_layer(l), { src.qg }, w.h, w.qg,
|
||||
0, {}, qg_span_lo, qg_span_hi));
|
||||
RAD_ARCH_TRY(kp.declare(b, nm, g, nm.f("blk.%d.attn_k", l), kv_dim, g.n_embd,
|
||||
RAD_SHARD_ROW, grp_layer(l), { src.k }, w.h, w.k,
|
||||
0, {}, kv_span_lo, kv_span_hi));
|
||||
RAD_ARCH_TRY(vp.declare(b, nm, g, nm.f("blk.%d.attn_v", l), kv_dim, g.n_embd,
|
||||
RAD_SHARD_ROW, grp_layer(l), { src.v }, w.h, w.v,
|
||||
0, {}, kv_span_lo, kv_span_hi));
|
||||
|
||||
/* The fused prologue (qk norms + rope + q|gate split) is a probe; the four unfused ops below
|
||||
* are declared either way and run when it does not resolve. Its schema takes a precomputed
|
||||
* cos/sin table instead of `theta`: `rope_table` fills `w.cos_sin` once a step for every
|
||||
* layer, and without a table the fusion is not requested.
|
||||
*
|
||||
* The kernel rotates NeoX pairs and has no `mode`. M-RoPE qualifies because the table is
|
||||
* filled at one component per token, which is exact when the components agree; step() takes
|
||||
* the fused path only then.
|
||||
*
|
||||
* No `gate_out` is passed: `gate_quant_fp8` reads the gate in place in the interleaved
|
||||
* projection.
|
||||
*
|
||||
* Bit-identical to the unfused ops, asserted in r4d_selftest: the kernel rounds the norm output
|
||||
* to bf16 before rotating and reproduces `r4d_rmsnorm_bf16`'s sum-of-squares order element by
|
||||
* element. A ULP-level difference would shift the engine's transcript within a few dozen
|
||||
* steps. */
|
||||
const bool rope_neox = !std::strcmp(mode, "neox") || !std::strcmp(mode, "mrope") || g.rope_mc;
|
||||
fused_rows = qk_fuse_rows(g);
|
||||
if (w.cos_sin && rope_neox && fused_rows > 0 && rad_op_declared(b, "qk_norm_rope_gate"))
|
||||
op_fused = rw(b, RAD_OP(b, "qk_norm_rope_gate",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, fused_rows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head),
|
||||
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, which reads back the resolved `block_size`
|
||||
* (rad_block_attn_gated.h). */
|
||||
op_attn = RAD_OP(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", 0),
|
||||
RAD_INT("n_head", g.n_head),
|
||||
RAD_INT("block_size", kv_block > 0 ? kv_block : (int64_t)RAD_KV_BLOCK),
|
||||
/* The sparse path issues one row per query, so the split-KV
|
||||
* scratch is sized for the widest launch (kQsaRows). */
|
||||
RAD_INT("max_seqs", (qsa_sel && qsa_sequ) ? qsa_rows()
|
||||
: g.max_seqs),
|
||||
RAD_INT("max_ctx", g.max_ctx),
|
||||
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS);
|
||||
/* The QSA selection buffers must be declared as reads of this op. Otherwise their last use is
|
||||
* `qsa_select`, the arena may overlay another buffer, and the attention reads garbage page
|
||||
* ids: an aperture violation outside the cache. rad_op_reads rather than rw() because the list
|
||||
* depends on whether the layer has an indexer. */
|
||||
if (op_attn) {
|
||||
const rad_buf rd[3] = { w.q, qsa_sel, qsa_sequ };
|
||||
rad_op_reads(b, op_attn, rd, (qsa_sel && qsa_sequ) ? 3 : 1);
|
||||
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 fused prologue with the cache store folded in: a k head's block already holds its
|
||||
* token's rotated k, so it also writes k and v into the cache, byte-identical to kv_store.
|
||||
* Declared here because the cache block size is read back from the attention op above.
|
||||
* Resolves for E4M3 and bf16 caches. */
|
||||
if (op_fused && rad_op_declared(b, "qk_norm_rope_gate_kv_store"))
|
||||
op_fused_kv = rw(b, RAD_OP(b, "qk_norm_rope_gate_kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, fused_rows),
|
||||
RAD_INT("head_dim", g.head_dim), RAD_INT("n_head", g.n_head),
|
||||
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});
|
||||
|
||||
/* Output gate, multiply and quantiser in one pass (`gate_quant_fp8`); at decode the dispatch
|
||||
* gaps between three small ops are comparable to the work. Each row is a (token, head) pair:
|
||||
* the gate is a fixed stride inside [q|gate], the attention output is contiguous, and the
|
||||
* [T * n_head, head_dim / 128] scale plane is byte-identical to the [T, q_dim / 128] the out
|
||||
* projection reads.
|
||||
*
|
||||
* The bf16 product is still written to `w.attn.x` and the codes are taken over it
|
||||
* (r4d_fused_quant_fp8.hip says why). The codes operand's dtype picks the quantiser, int8 when
|
||||
* the out projection is fed int8 (ActFP8::q8_fed). Serves prefill and decode: there is no
|
||||
* cross-row reduction.
|
||||
*
|
||||
* With bf16 linears (Geom::w_bf16) the gate is the plain `sigmoid` + `mul` pair instead.
|
||||
*
|
||||
* Where no loaded library declares gate_quant_fp8, or it does not resolve, the fp8 block runs
|
||||
* the chain it fuses: the gate into a buffer of its own, the multiply, then the activation
|
||||
* quantiser, which write what the fused op writes. A head of whole 128-column blocks makes
|
||||
* the quantiser's [T, q_dim / 128] scale plane the fused op's [T * n_head, head_dim / 128]. */
|
||||
auto gate_pair = [&](rad_buf out) {
|
||||
gate = out;
|
||||
op_sig = rw(b, RAD_OP(b, "sigmoid",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head),
|
||||
RAD_INT("n", g.head_dim), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.qg}, {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, gate}, {w.attn.x});
|
||||
return op_sig && op_mul ? RAD_OK : RAD_E_INVAL;
|
||||
};
|
||||
if (g.w_bf16) {
|
||||
RAD_ARCH_TRY(gate_pair(w.gate));
|
||||
} else {
|
||||
if (rad_op_declared(b, "gate_quant_fp8"))
|
||||
op_gq = rw(b, RAD_OP(b, "gate_quant_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head),
|
||||
RAD_INT("n", g.head_dim), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", g.dtype), RAD_STR("act", "sigmoid")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.qg, w.attn.x}, {w.attn.cq(), w.attn.cs(), w.attn.x});
|
||||
if (!op_gq && g.head_dim % RAD_FP8_BLOCK == 0) {
|
||||
RAD_ARCH_TRY(gate_pair(decl_b(b, nm.f("blk.%d.attn_gate", l), g.act_dtype,
|
||||
{g.max_tok, q_dim})));
|
||||
RAD_ARCH_TRY(q_gate.declare(b, g, w.attn, q_dim));
|
||||
if (!q_gate.op) return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
|
||||
/* On the sparse path the gate is applied inside the attention's split-KV merge: each launch
|
||||
* row is one (token, head) at q_len 1, and the merge already holds the head_dim values the gate
|
||||
* and quantiser read, so one op merges, gates, rounds and quantises (byte-identical to the
|
||||
* pair). Declared only with a selection: the dense path also uses the prefill kernel, which
|
||||
* has no merge. */
|
||||
if (op_attn && qsa_sel && qsa_sequ && !g.w_bf16 &&
|
||||
rad_op_declared(b, "attn_paged_gate_quant")) {
|
||||
op_attn_gq = RAD_OP(b, "attn_paged_gate_quant",
|
||||
RAD_PARAMS(RAD_INT("q_len", 1), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
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,
|
||||
0, {}, o_span_lo, o_span_hi));
|
||||
return declare_out(b, add_out);
|
||||
}
|
||||
|
||||
inline int AttnGatedFP8::declare_out(RadBuilder* b, bool add_out) {
|
||||
if (g.world > 1)
|
||||
op_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
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});
|
||||
/* The same collective for a caller that runs it beside other work (issue_ar, a pipelined
|
||||
* prefill): at `overlap` 1 it gets the rows that hold fewer CUs while waiting on the link. */
|
||||
if (g.world > 1 && ar_overlap > 0)
|
||||
op_ar_ov = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes),
|
||||
RAD_INT("overlap", ar_overlap)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h.x}, {w.h.x});
|
||||
|
||||
/* Only when the next block's norm will not add (rad_fp8.h: NormQuantFP8). */
|
||||
if (add_out)
|
||||
op_add = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.x, w.h.x}, {w.x});
|
||||
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
inline void AttnGatedFP8::store_kv(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
if (!ext_in) nq_h.step(c, T);
|
||||
if (op_fill) return; /* the attention-zero rank holds no heads to store */
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
|
||||
kp.step(c, w.h, w.k, T);
|
||||
vp.step(c, w.h, w.v, 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_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));
|
||||
}
|
||||
|
||||
inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
ArPieces* pieces) const {
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
|
||||
const int32_t* table = kvb ? kvb->block_table : nullptr;
|
||||
const int32_t* used = kvb ? kvb->seqused : nullptr;
|
||||
|
||||
const int64_t T = batch->n_tok;
|
||||
|
||||
if (!ext_in) nq_h.step(c, T);
|
||||
if (op_fill) {
|
||||
/* Attention-zero rank: zero output, then the reduce and the residual. */
|
||||
RAD_ISSUE_N(c, op_fill, T, brows(w.h.x, T));
|
||||
if (own_ar && op_ar && !ar_taken(g, T, ar_out, ar_out_take))
|
||||
RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h.x, T), RAD_NONE);
|
||||
if (op_add) RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h.x, T), brows(w.x, T));
|
||||
return;
|
||||
}
|
||||
qg.step(c, w.h, w.qg, T);
|
||||
kp.step(c, w.h, w.k, T);
|
||||
vp.step(c, w.h, w.v, T);
|
||||
|
||||
/* Fused or unfused prologue. The fused kernel takes the whole [q|gate] projection and splits it
|
||||
* itself, and rotates k in place like the unfused ops. It reads one rotary component per
|
||||
* token, so a pass with media tokens (differing components) takes the unfused path with the
|
||||
* full [3, T] positions. */
|
||||
const bool fuse_ok = T <= fused_rows && !rope_mixed(batch);
|
||||
const bool fused_kv = op_fused_kv && fuse_ok;
|
||||
if (fused_kv) {
|
||||
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));
|
||||
|
||||
/* Sparse attention issues one row per query. `attn_paged` indexes its block table and length
|
||||
* by row, and a row need not be a sequence, so T queries issued as T rows of q_len 1, each with
|
||||
* its own selection and `seqused`, is per-query sparse attention; at decode T is the sequence
|
||||
* count.
|
||||
*
|
||||
* Below `qsa_exact_to` the dense path gives the same result more cheaply (see the field);
|
||||
* `max_ctx_len` is a host-side bound the batch already carries.
|
||||
*
|
||||
* Launches are chunked because the split-KV scratch is sized at declare from `max_seqs` and
|
||||
* `q_len` (rows = max_seqs * q_len_max * heads); more rows are refused as RAD_E_SCRATCH at
|
||||
* issue. Rows of q_len 1 up to the declared max_seqs always fit. */
|
||||
const int64_t reach = (int64_t)batch->max_ctx_len + batch->max_q_len;
|
||||
const bool sparse = qsa_sel && qsa_sequ &&
|
||||
(T == batch->n_seq || qsa_exact_to <= 0 || reach > qsa_exact_to);
|
||||
const bool gated = sparse && op_attn_gq;
|
||||
/* A piece at a time where the caller takes the all-reduce that way (ArPieces). On the gated
|
||||
* sparse path every query row is its own (q_len 1) and the gate rides in the merge, so the
|
||||
* attention and out projection can finish a piece's rows and hand off its reduction while the
|
||||
* next piece's attention runs. Each piece is launched as a step of the piece's width would
|
||||
* launch it. */
|
||||
if (gated && !own_ar && pieces && pieces->cuts(T) && !op_add) {
|
||||
const int64_t chunk = qsa_gq_rows();
|
||||
const int64_t qw = g.q_dim(), hd = g.head_dim;
|
||||
for (int64_t p0 = 0; p0 < T; p0 += pieces->rows) {
|
||||
const int64_t pn = T - p0 < pieces->rows ? T - p0 : pieces->rows;
|
||||
for (int64_t off = p0; off < p0 + pn; off += chunk) {
|
||||
const int64_t rows = (p0 + pn - off) < chunk ? (p0 + pn - off) : chunk;
|
||||
RAD_ISSUE_N(c, op_attn_gq, 1,
|
||||
brow_slice(w.q, off, rows, qw),
|
||||
kv_cache(kv, layer),
|
||||
brow_slice(qsa_sel, off, rows, qsa_topk + 1),
|
||||
brow_slice(qsa_sequ, off, rows, 1),
|
||||
RAD_NONE, RAD_NONE, RAD_NONE,
|
||||
brow_slice(w.attn.x, off, rows, qw),
|
||||
bcol_at(w.qg, off, g.n_head * 2 * hd, hd, hd, rows),
|
||||
brow_slice(w.attn.cq(), off, rows, qw),
|
||||
brow_slice(w.attn.cs(), off, rows, fp8_blocks(qw)));
|
||||
}
|
||||
o.step(c, w.attn, w.h.x, T, p0, pn);
|
||||
if (p0 + pn < T) pieces->hand(p0, pn);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (gated) {
|
||||
const int64_t chunk = qsa_gq_rows();
|
||||
const int64_t qw = g.q_dim(), hd = g.head_dim;
|
||||
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 (a prefill chunk beside decode rows). */
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
|
||||
brows(w.attn.x, T));
|
||||
}
|
||||
|
||||
if (gated) {
|
||||
/* the sparse attention gated and quantised in its merge */
|
||||
} else if (op_sig) {
|
||||
/* The gate is the strided second half of each head's [q|gate] pair. */
|
||||
RAD_ISSUE_N(c, op_sig, T * g.n_head,
|
||||
bcol(w.qg, g.head_dim, g.head_dim, T), brows(gate, T));
|
||||
RAD_ISSUE(c, op_mul, brows(w.attn.x, T), brows(gate, T), brows(w.attn.x, T));
|
||||
q_gate.step(c, T);
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_gq, T * g.n_head,
|
||||
bcol(w.qg, g.head_dim, g.head_dim, T), brows(w.attn.x, T),
|
||||
brows(w.attn.cq(), T), brows(w.attn.cs(), T), brows(w.attn.x, T));
|
||||
}
|
||||
|
||||
o.step(c, w.attn, w.h.x, T);
|
||||
if (own_ar && op_ar && !ar_taken(g, T, ar_out, ar_out_take))
|
||||
RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h.x, T), RAD_NONE);
|
||||
if (op_add) RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h.x, T), brows(w.x, T));
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_ATTN_GATED_FP8_H */
|
||||
@@ -0,0 +1,864 @@
|
||||
/* rad_block_dflash2.h -- the DFlash2 block-diffusion drafter, bf16.
|
||||
*
|
||||
* A small transformer that proposes a whole block of tokens in one forward pass. Compared with
|
||||
* the MTP head (rad_block_mtp_fp8.h):
|
||||
*
|
||||
* MTP depth d costs d chained forwards; round i+1 embeds round i's token.
|
||||
* DFlash2 depth d costs one forward over d+1 positions: the anchor token plus d mask
|
||||
* tokens are denoised together.
|
||||
*
|
||||
* So depth is nearly free here, and there is no `draft_pass`. Published acceptance is 4.10-5.46
|
||||
* versus MTP's 3.74-5.02 at 7 drafts.
|
||||
*
|
||||
* Since positions are proposed together, position l+1 does not know what position l chose. The
|
||||
* candidate selector (`dflash_select`) restores that dependence: each position keeps the draft
|
||||
* head's top K, a low-rank bilinear form scores edges between consecutive positions, and a greedy
|
||||
* walk picks one path.
|
||||
*
|
||||
* ============================== THE TWO PASSES ==============================
|
||||
*
|
||||
* Context pass, one row per committed token. The drafter does not run its layers over the
|
||||
* context; it turns the target's hidden states at five intermediate layers into its own K and V:
|
||||
*
|
||||
* c = fc(concat of the trunk's residual stream at layers 5, 19, 33, 47, 61) [n_taps*n_embd]
|
||||
* c = hidden_norm(c)
|
||||
* for each draft layer: k|v = kv_proj(c); k = k_norm(k) then rope; kv_store(k, v)
|
||||
*
|
||||
* The taps and the `dflash_src` buffer they land in are the trunk's (qwen35_fp8.cpp).
|
||||
*
|
||||
* Query pass, one row per draft position, `block` = 1 + n_spec rows per 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)
|
||||
*
|
||||
* then, over the mask rows of each block (offsets 1..block-1; the anchor at offset 0 is already
|
||||
* chosen and only conditions the rest), each predicting the token at its own position:
|
||||
*
|
||||
* cand, unary = top_k(draft_head(x)) the candidates and their logits
|
||||
* hp = hidden_projection(x) the selector's query, rank 256
|
||||
* tokens = dflash_select(cand, unary, hp, anchor, predecessor, successor)
|
||||
*
|
||||
* ============================== WHAT IS SHARED WITH THE TARGET ==============================
|
||||
*
|
||||
* The embedding table and lm_head. The checkpoint (81 tensors) ships neither, and
|
||||
* `mask_token_id` is an ordinary id in the target's vocabulary (248070 here), so there is no
|
||||
* separate mask embedding.
|
||||
*
|
||||
* The head reads the 2-bit copy of the lm_head, as the MTP head does (rad_block_mtp_fp8.h,
|
||||
* op_dlogits): the target verifies every draft with its own head, so a coarser draft costs only
|
||||
* acceptance, never an emitted token. Candidates are rescored against the target's head when it
|
||||
* is fp8 or int8 (op_drerank), so coarseness affects only which candidates are proposed.
|
||||
*
|
||||
* ============================== PLAIN NORMS ==============================
|
||||
*
|
||||
* The norms use `w`, not the trunk's `1 + w`: vLLM uses plain RMSNorm here, and the gains are all
|
||||
* positive and centred near one (hidden_norm 0.11..1.24, input_layernorm 0.05..1.70, k_norm
|
||||
* 0.32..2.53, final norm 2.45..5.25). So this geometry's `wadd` and `wadd_qk` are zero.
|
||||
*
|
||||
* ============================== SHARDING ==============================
|
||||
*
|
||||
* q/kv and gate_up shard by row, o and down by column with an all-reduce: ten collectives per
|
||||
* draft pass, each 5120 * block * 2 bytes (80 KiB at block 8), below the lossy wire's floor.
|
||||
*
|
||||
* Replicated:
|
||||
*
|
||||
* fc [n_embd, n_taps*n_embd], 262 MiB. Column-sharding would halve it but add an
|
||||
* all-reduce to the prefill path.
|
||||
* conv weights projection and base kernel, 26 MiB a layer. The convolution spans the whole
|
||||
* replicated hidden row, so every rank needs every coefficient.
|
||||
* codebooks [n_vocab, 256], 127 MiB each, gathered by global token id. Only 128 rows are
|
||||
* read per pass; the cost is residency.
|
||||
*
|
||||
* Cost: the context pass is the expensive half (`fc` plus five KV projections read 3.4 GB over a
|
||||
* 2048-token prefill chunk). The attention window is 2048 tokens, so context rows further back
|
||||
* are never read and the scheduler need not compute them.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_DFLASH2_H
|
||||
#define RAD_BLOCK_DFLASH2_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
#include "rad_fp8.h"
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
/* brow_slice() for a weight. The conv base kernel is one [2, taps, n_embd] tensor holding the
|
||||
* prepare and finish tap sets; the op takes one side at a time. */
|
||||
inline RadOperand wrow_slice(rad_weight h, int64_t first, int64_t n, int64_t pitch) {
|
||||
RadOperand o = RAD_W(h);
|
||||
o.offset = first * pitch;
|
||||
o.rows = n;
|
||||
return o;
|
||||
}
|
||||
|
||||
struct Dflash2 {
|
||||
enum { MAX_LAYERS = 8 };
|
||||
|
||||
/* The drafter config beyond its geometry, read by the plugin from `draft.*` metadata keys. */
|
||||
struct Config {
|
||||
int64_t n_taps = 0; /* how many trunk layers `fc` concatenates */
|
||||
int64_t block = 0; /* query rows a sequence: the anchor plus n_spec mask tokens */
|
||||
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 (prepare's set, then finish's);
|
||||
* `dflash_conv` reads a slice of it at the full row pitch. */
|
||||
int64_t coef_dim(int64_t n_embd) const { return 2 * taps * ng(n_embd); }
|
||||
};
|
||||
|
||||
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 separate buffers because of the per-head k norm: `rmsnorm` takes one row
|
||||
* pitch, and K heads inside a fused [K|V] row are head_dim apart within a token but
|
||||
* 2*kv_dim apart between tokens. libr4d refuses such an operand (libr4d/r4d_model.cpp,
|
||||
* rows_pitch). Same reason as in rad_block_attn_gated.h. */
|
||||
rad_buf ck = 0; /* [max_tok, kv_dim] ONE layer's K, reused across layers */
|
||||
rad_buf cv = 0; /* [max_tok, kv_dim] ONE layer's V, reused across layers */
|
||||
/* the query pass */
|
||||
rad_buf x = 0; /* [qrows, n_embd] the drafter's residual stream */
|
||||
rad_buf h = 0; /* [qrows, n_embd] normed input, o/down output, and the final norm */
|
||||
rad_buf h2 = 0; /* [qrows, n_embd] the convolution's output; must not alias x */
|
||||
rad_buf coef = 0; /* [qrows, coef_dim] */
|
||||
rad_buf q = 0; /* [qrows, q_dim] */
|
||||
rad_buf k = 0; /* [qrows, kv_dim] separate from v, see `ck` */
|
||||
rad_buf v = 0; /* [qrows, kv_dim] */
|
||||
rad_buf attn = 0; /* [qrows, q_dim] */
|
||||
rad_buf gate_up = 0;/* [qrows, 2 * n_ff] */
|
||||
rad_buf ffn = 0; /* [qrows, n_ff] */
|
||||
/* FP8 codes and scales of the activations the linears read, written by `quant_act_fp8`
|
||||
* and read only by the `gemm_nt_q` linears. One pair per activation, not per linear: q, k
|
||||
* and v all read h2. h2 is still quantised twice a layer, because the convolution
|
||||
* rewrites it between the attention and feed-forward halves. */
|
||||
rad_buf srcq = 0, srcs = 0; /* [max_tok, n_taps*n_embd] e4m3 | [.., /128] f32 */
|
||||
rad_buf cq = 0, cs = 0; /* [max_tok, n_embd] */
|
||||
rad_buf h2q = 0, h2s = 0; /* [qrows, n_embd] */
|
||||
rad_buf atq = 0, ats = 0; /* [qrows, q_dim] */
|
||||
rad_buf ffq = 0, ffs = 0; /* [qrows, n_ff] */
|
||||
/* the head and the selector, one row per draft position (block - 1 per sequence) */
|
||||
rad_buf sel_h = 0; /* [srows, n_embd] the gathered final hidden states */
|
||||
rad_buf hp = 0; /* [srows, sel_rank] hidden_projection of them */
|
||||
rad_buf dq = 0; /* [srows, n_embd] i8 the 2-bit head's quantised activation */
|
||||
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 */
|
||||
/* Vocab-parallel pairs, declared only when head_sharded(g): (int32 id, f32 value) pairs
|
||||
* stored as f32, this rank's top-R and the all-gathered world_size * R. */
|
||||
rad_buf dpair = 0; /* [srows, sel_topk, 2] f32 */
|
||||
rad_buf dgath = 0; /* [srows, world * sel_topk, 2] f32 */
|
||||
rad_buf tokens = 0; /* [max_seqs, steps] i32 the draft; the engine reads it by name */
|
||||
};
|
||||
|
||||
/* Whether the 2-bit draft head is vocab-sharded (rad_arch.h: vocab_head_sharded), so whoever
|
||||
* declares the buffers can ask the block. Sharding halves the draft path's widest read (341 MiB
|
||||
* of codes and scales at 248320 rows) for one all_gather of R pairs a row. */
|
||||
static bool head_sharded(const Geom& g) { return vocab_head_sharded(g); }
|
||||
/* Rows of the draft head on this rank, and so the width of `dlog`. */
|
||||
static int64_t head_rows(const Geom& g) { return vocab_head_rows(g); }
|
||||
|
||||
Geom g{}; /* the drafter's geometry, not the trunk's */
|
||||
Config cfg{};
|
||||
Wire w{};
|
||||
int first_layer = 0; /* absolute, for the KV group's layer_slot lookup */
|
||||
int64_t qrows = 0, crows = 0, srows = 0;
|
||||
int64_t gated_rows = 0; /* the band op_gug was declared over; 0 when there is no fold */
|
||||
rad_kvgroup kv = 0;
|
||||
|
||||
/* model-scope weights.
|
||||
*
|
||||
* The linears are block fp8 or OCP-MXFP4 (rad_fp8.h: DenseFP8, per the recipe) although the
|
||||
* checkpoint is bf16: the drafter is read whole every decode step. On Qwen3.8-27B at depth 7,
|
||||
* MXFP4 accepts ~1% fewer tokens per step than fp8 and saves ~1.5 ms of a ~34 ms step.
|
||||
* Quantisation can only change acceptance, since every draft is verified. */
|
||||
DenseFP8 w_fc{};
|
||||
rad_weight w_hnorm = 0, w_norm = 0;
|
||||
rad_weight w_selp = 0, w_pred = 0, w_succ = 0;
|
||||
rad_weight w_tok = 0; /* the target's embedding table */
|
||||
rad_weight w_dh = 0, w_dhs = 0; /* the 2-bit copy of the target's lm_head */
|
||||
|
||||
/* per-layer weights */
|
||||
rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {};
|
||||
/* K and V are separate weights: a block-scaled operand's layout follows the op's N, so a fused
|
||||
* [2*kv_dim, n_embd] weight issued one half at a time would hand the layout hook a
|
||||
* [2*kv_dim/128][K/128] plane for a [kv_dim, K] op, which it refuses. */
|
||||
DenseFP8 w_q[MAX_LAYERS]{}, w_k[MAX_LAYERS]{}, w_v[MAX_LAYERS]{}, w_o[MAX_LAYERS]{};
|
||||
rad_weight w_qn[MAX_LAYERS] = {}, w_kn[MAX_LAYERS] = {};
|
||||
DenseFP8 w_gu[MAX_LAYERS]{}, w_dn[MAX_LAYERS]{};
|
||||
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] = {};
|
||||
|
||||
/* Activation quantisers, one per activation that feeds a linear. Weightless, so one declaration
|
||||
* serves every layer; ops with weights are per layer because a weight's prefetch interval
|
||||
* comes from the op that declares it. */
|
||||
rad_op op_qsrc = 0, op_qc = 0; /* context pass */
|
||||
rad_op op_qh2 = 0, op_qat = 0, op_qff = 0; /* query pass */
|
||||
|
||||
/* query-pass ops. Weightless ones are declared once and issued per layer; their read and write
|
||||
* sets are the same every layer. */
|
||||
rad_op op_embed = 0, op_embed_ar = 0;
|
||||
rad_op op_anorm[MAX_LAYERS] = {}, op_fnorm[MAX_LAYERS] = {};
|
||||
rad_op op_acoef[MAX_LAYERS] = {}, op_fcoef[MAX_LAYERS] = {};
|
||||
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_drerank = 0; /* the candidates rescored against the target's head */
|
||||
/* The target's lm_head, set by the plugin before declare when logit_rerank can read it (fp8 or
|
||||
* int8 rows); 0 keeps the coarse head's scores. */
|
||||
rad_weight w_lm = 0;
|
||||
/* Candidates the coarse head proposes for the rerank (logit_rerank's and row_topk's ceiling).
|
||||
* Rescoring is exact, so a wider set can only find more of the exact top sel_topk. */
|
||||
static constexpr int64_t kRerankR = 32;
|
||||
int64_t top_w = 0; /* the coarse top-K's width: kRerankR or sel_topk */
|
||||
rad_op op_hp = 0, op_sel = 0;
|
||||
|
||||
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 per committed token; `batch` carries those rows and the draft KV
|
||||
* group's slot mapping. */
|
||||
void context(RadCtx* c, const RadBatch* batch) const;
|
||||
/* The query pass and the selector, `block` rows per 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, declared as the MTP head's is (rad_block_mtp_fp8.h):
|
||||
* `dflash.draft_head.weight` is the target's lm_head under its own name, quantised by the
|
||||
* recipe to u2 codes with an f16 scale and u8 zero per group of 128. One checkpoint tensor,
|
||||
* two views: codes, and the scale|zero planes the GEMM's relayout interleaves.
|
||||
*
|
||||
* When sharded, each rank's `row_topk` reports global ids, an all_gather moves R pairs a row,
|
||||
* and `row_topk_merge` reduces them to exactly the unsharded global top-R, ties included
|
||||
* (docs/OPS.md). This runs before the selector, so every rank holds the same candidates for
|
||||
* the replicated codebooks. The all_gather is `world * R` pairs a row (2 KiB at R = 16). */
|
||||
enum { DF_W2_GROUP = 128 };
|
||||
const bool dh_shard = head_sharded(g);
|
||||
const int dh_split = dh_shard ? RAD_SHARD_ROW : RAD_SHARD_NONE;
|
||||
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) }));
|
||||
/* q, k and v are separate weights. The context pass needs only k and v, so a fused qkv
|
||||
* would compute and discard q for every context token. k and v: see w_q's declaration. */
|
||||
RAD_ARCH_TRY(w_k[i].declare(b, nm, nm.f("dflash.blk.%d.attn_k", i), kvd, g.n_embd,
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(first_layer + i),
|
||||
{ nm.ckpt("%s.layers.%d.self_attn.k_proj.weight", ck, i) }));
|
||||
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 and windowed: the block is denoised as a whole, so each query row sees its whole
|
||||
* block plus the context (`causal` comes from the config's `is_causal: false`). The window is
|
||||
* the checkpoint's `sliding_window`.
|
||||
*
|
||||
* Declared before both kv_stores, which read the resolved `block_size` back with
|
||||
* rad_kv_block_size(); before this declaration it returns zero. */
|
||||
op_attn = rw(b, RAD_OP(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, cfg.block), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", cfg.causal),
|
||||
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 is `fp8a8` (or `mxfp4a8` for a 4-bit recipe; DenseFP8 reads which from the
|
||||
* container and declares the GEMM), reading an E4M3 activation pair from a `quant_act_fp8`.
|
||||
* There is no `fp8a16` band: that kernel is M <= 1, and neither pass runs at one row.
|
||||
*
|
||||
* Nothing is row-sliced: the fp8a8 pair covers every M, and libr4d's bf16 GEMM row (used by
|
||||
* the conv coefficient projections and the selector's hidden projection, K = n_embd) is
|
||||
* C_LE("M", 65536). */
|
||||
op_qsrc = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", cfg.n_taps * g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.src}, {w.srcq, w.srcs});
|
||||
op_cfc = w_fc.gemm(b, crows, g.n_embd, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.c});
|
||||
/* In place, like the per-head q/k norms below: a row's scale is computed before the row is
|
||||
* written. */
|
||||
op_cnorm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_hnorm)),
|
||||
{w.c}, {w.c});
|
||||
/* One quantise for all layers: every layer's k and v read the same `c`. */
|
||||
op_qc = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.c}, {w.cq, w.cs});
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
/* One op per weight: an op's declared weight list gives each weight its prefetch interval
|
||||
* and residency class. */
|
||||
op_ck[i] = w_k[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.ck});
|
||||
op_cv[i] = w_v[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.cv});
|
||||
op_cknorm[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
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});
|
||||
}
|
||||
/* A whole-head NeoX rope over a q-only or k-only tensor of `heads` heads: `rope` rotates the
|
||||
* first n_head + n_head_kv heads, so n_head_kv is 0. Weightless, so one op serves every layer. */
|
||||
auto rope = [&](int64_t rows, int64_t heads, rad_buf x) {
|
||||
return rw(b, decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", heads), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
RAD_STR("mode", "neox")),
|
||||
RAD_NOWEIGHTS),
|
||||
{x}, {x});
|
||||
};
|
||||
op_crope = rope(crows, g.n_head_kv, w.ck);
|
||||
op_cstore = rw(b, RAD_OP(b, "kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head_kv", g.n_head_kv),
|
||||
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 the lookup is partial and needs an exact
|
||||
* all-reduce. */
|
||||
if (g.world > 1)
|
||||
op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
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 quantisers, issued per layer: h2 twice (the convolution rewrites it between
|
||||
* the halves), attn and ffn once each. */
|
||||
op_qh2 = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
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] = w_q[i].gemm(b, qrows, qd, g.n_embd, {w.h2q, w.h2s}, {w.q});
|
||||
op_kp[i] = w_k[i].gemm(b, qrows, kvd, g.n_embd, {w.h2q, w.h2s}, {w.k});
|
||||
op_vp[i] = w_v[i].gemm(b, qrows, kvd, g.n_embd, {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] = w_o[i].gemm(b, qrows, g.n_embd, qd, {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] = w_gu[i].gemm(b, qrows, 2 * g.n_ff, g.n_embd, {w.h2q, w.h2s}, {w.gate_up});
|
||||
/* The fold saves two launches and the bf16 round trip of the [T, n_ff] product; it is an
|
||||
* fp8a8 tile, so an MXFP4 gate_up takes the pair. */
|
||||
if (!w_gu[i].mx)
|
||||
op_gug[i] = decl_gated_fold(b, qrows, 2 * g.n_ff, g.n_embd, w_gu[i].w, w_gu[i].s,
|
||||
{w.h2q, w.h2s}, {w.ffq, w.ffs}, &gated_rows);
|
||||
op_dn[i] = w_dn[i].gemm(b, qrows, g.n_embd, g.n_ff, {w.ffq, w.ffs}, {w.h});
|
||||
}
|
||||
|
||||
/* The convolutions. `block_size` is the query block: the shifted tap is masked at each block's
|
||||
* first row so one sequence's block does not convolve with the previous one's.
|
||||
*
|
||||
* One op per (layer, convolution) because the base kernel is a weight (see op_ck). Each op is
|
||||
* issued twice, prepare and finish, against the two halves of its [2, taps, n_embd] tensor. */
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
op_aconv[i] = rw(b, RAD_OP(b, "dflash_conv",
|
||||
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});
|
||||
}
|
||||
/* The attention output is written and read inside every layer, between the two halves of the
|
||||
* attention convolution, but its two ops (op_attn, op_qat) are declared once ahead of the
|
||||
* layers. Planned from those alone, its range would end before the coefficients' begins and
|
||||
* the plan could lay one over the other. Read by the last convolution as well, it is live
|
||||
* wherever the coefficients are. */
|
||||
if (rad_op_reads(b, op_fconv[g.n_layer - 1], &w.attn, 1) < 0) return RAD_E_INVAL;
|
||||
op_qrope = rope(qrows, g.n_head, w.q);
|
||||
op_krope = rope(qrows, g.n_head_kv, w.k);
|
||||
op_store = rw(b, RAD_OP(b, "kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head_kv", g.n_head_kv),
|
||||
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 head runs over the mask rows, offsets 1..block-1 of each block: `steps` rows per
|
||||
* sequence, each predicting the token at its own position. The anchor row predicts nothing.
|
||||
* An off-by-one here only shows as collapsed acceptance; the output stays correct.
|
||||
*
|
||||
* The gather makes those rows contiguous, numbered s * steps + l as `dflash_select` reads
|
||||
* them. */
|
||||
op_gather = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
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, reports global ids and also writes the pair
|
||||
* plane the gather moves. Replicated, `vocab_off` is omitted: an optional parameter present
|
||||
* with value 0 is a different declaration from an absent one. */
|
||||
const bool rerank = w_lm && (dh_shard || g.world <= 1); /* see op_drerank below */
|
||||
if (!rerank) top_w = cfg.sel_topk;
|
||||
op_dtopk = dh_shard
|
||||
? rw(b, RAD_OP(b, "row_topk",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)),
|
||||
RAD_INT("R", top_w), 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", top_w), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.dlog}, {w.cand, w.unary});
|
||||
/* Exact rescoring when the target's head can be read row by row: the coarse head proposes its
|
||||
* top kRerankR, `logit_rerank` scores them against the target's head and re-sorts, and the
|
||||
* selector reads the best sel_topk, giving the candidates and unary logits the drafter was
|
||||
* trained against. On Qwen3.8-27B the 2-bit head's top-1 matches the exact head on 76% of
|
||||
* draft rows, the rescored one on all; this matches the 4-bit head's speed at half its bytes.
|
||||
*
|
||||
* Sharded, each rank rescores only ids it owns and the merge below ranks exact values. A
|
||||
* replicated head above one rank proposes ids other ranks own, so it keeps its own scores. */
|
||||
if (rerank) {
|
||||
op_drerank = RAD_OP(b, "logit_rerank",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("R", top_w),
|
||||
RAD_INT("n_vocab", head_rows(g)), 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;
|
||||
rad_buf rd[2] = { w.sel_h, w.cand };
|
||||
rad_buf wr[3] = { w.cand, w.unary, 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 position's pairs from every rank are adjacent, as
|
||||
* `row_topk_merge` reads them. */
|
||||
op_dgather = rw(b, RAD_OP(b, "all_gather",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_INT("numel", srows * top_w * 2),
|
||||
RAD_STR("dtype", "f32"),
|
||||
RAD_INT("row", top_w * 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", top_w),
|
||||
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`: the operand is the step's token_ids, `block` per sequence with
|
||||
* the anchor first. */
|
||||
op_sel = rw(b, RAD_OP(b, "dflash_select",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("steps", cfg.steps()),
|
||||
RAD_INT("top_k", cfg.sel_topk), RAD_INT("rank", cfg.sel_rank),
|
||||
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;
|
||||
|
||||
/* As wide as the prefill chunk, one launch per op (the fp8a8 pair covers every M). */
|
||||
RAD_ISSUE_N(c, op_qsrc, T, brows(w.src, T), brows(w.srcq, T), brows(w.srcs, T));
|
||||
RAD_ISSUE_N(c, op_cfc, T, brows(w.srcq, T), brows(w.srcs, T), RAD_W(w_fc.w), RAD_W(w_fc.s),
|
||||
brows(w.c, T), RAD_NONE, w_fc.bref());
|
||||
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, w_k[i].bref());
|
||||
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, w_v[i].bref());
|
||||
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, w_q[i].bref());
|
||||
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, w_k[i].bref());
|
||||
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, w_v[i].bref());
|
||||
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, w_o[i].bref());
|
||||
/* Reduce before the closing convolution. It is linear with coefficients from the
|
||||
* replicated norm, so either order gives the same result; reducing first keeps x's
|
||||
* update agreed across ranks. */
|
||||
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_aconv[i], T, brows(w.h, T), bcol(w.coef, half, half, T),
|
||||
wrow_slice(w_acb[i], 1, 1, cfg.taps * g.n_embd), brows(w.h2, T));
|
||||
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, w_gu[i].bref());
|
||||
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, w_dn[i].bref());
|
||||
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 predicting rows, `steps` per sequence, named by the scheduler through out_ids. */
|
||||
const int64_t S = batch->n_out;
|
||||
if (S <= 0) return;
|
||||
RAD_ISSUE_N(c, op_gather, S, RAD_B(w.h), praw(batch->out_ids, RAD_I32, S), brows(w.sel_h, S));
|
||||
|
||||
/* `dsum` is group-major, [n_embd/group][ceil(M/16)*16], so it has no row slice; pass it
|
||||
* whole. */
|
||||
RAD_ISSUE_N(c, op_dquant, S, brows(w.sel_h, S), brows(w.dq, S), brows(w.ds, S), RAD_B(w.dsum));
|
||||
/* The trailing operand is mxfp4's optional reference, absent here. Operands are positional,
|
||||
* so an absent optional one is RAD_NONE, not a shorter list. */
|
||||
RAD_ISSUE_N(c, op_dlogits, S, brows(w.dq, S), brows(w.ds, S), RAD_W(w_dh), RAD_W(w_dhs),
|
||||
brows(w.dlog, S), RAD_B(w.dsum), RAD_NONE);
|
||||
/* RAD_NONE fills the unused `pairs` slot. Sharded, this rank's top-R are only candidates and
|
||||
* the merge overwrites `cand`/`unary`. */
|
||||
if (op_dmerge) {
|
||||
RAD_ISSUE_N(c, op_dtopk, S, brows(w.dlog, S), brows(w.cand, S), brows(w.unary, S),
|
||||
brows(w.dpair, S));
|
||||
if (op_drerank)
|
||||
RAD_ISSUE_N(c, op_drerank, S, brows(w.sel_h, S), RAD_W(w_lm), brows(w.cand, 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);
|
||||
if (op_drerank)
|
||||
RAD_ISSUE_N(c, op_drerank, S, brows(w.sel_h, S), RAD_W(w_lm), brows(w.cand, 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, bcol(w.cand, 0, cfg.sel_topk, S),
|
||||
bcol(w.unary, 0, cfg.sel_topk, 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 */
|
||||
@@ -0,0 +1,817 @@
|
||||
/* rad_block_dspark.h -- the DSpark block-diffusion drafter, fp8 weights over a bf16 checkpoint.
|
||||
*
|
||||
* ============================== WHAT 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) versus MTP's 3.74-5.02.
|
||||
*
|
||||
* Not rad_block_dflash2.h despite the name: DSpark subclasses SpecForge's `DFlashDraftModel`,
|
||||
* which is plain Qwen3 attention (the checkpoint has q/k/v/o, q_norm/k_norm, gate/up/down and no
|
||||
* conv or selection tensors), while `Dflash2` is the conv-based drafter. This block reuses
|
||||
* Dflash2's structure (Config / Wire / declare / context / step) and its selector.
|
||||
*
|
||||
* ============================== THE FORWARD PASS ==============================
|
||||
*
|
||||
* The published repo has no reference code (`auto_map: dspark.DSparkDraftModel`);
|
||||
* `RadixArk/Qwen3.8-27B-DSpark` ships `dspark.py` and `dflash.py`, which this implements:
|
||||
*
|
||||
* target_hidden = hidden_norm(fc(concat of the trunk's residual stream after layers
|
||||
* 1, 10, 20, 30, 39)) [n_taps * n_embd] -> [n_embd]
|
||||
* h = target.embed_tokens([anchor, MASK, MASK, ...]) `block` noise rows
|
||||
* per layer (x5):
|
||||
* h_n = input_layernorm(h)
|
||||
* q = q_norm(q_proj(h_n)) q from the noise rows only
|
||||
* 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`; `target_hidden` is computed once and each layer projects it with its
|
||||
* own k_proj and v_proj. The drafter uses the target's embedding table and lm_head, so the
|
||||
* vocabularies must agree.
|
||||
*
|
||||
* ============================== DUAL-SOURCE K/V AS A PAGED CACHE ==============================
|
||||
*
|
||||
* The reference appends context and noise rows to its cache, attends over both, then
|
||||
* `crop(start)`s the noise. Here that is a paged KV group: context written per committed token,
|
||||
* noise rows written past `seqused`, where the next context pass overwrites them. Two passes, as
|
||||
* in Dflash2:
|
||||
*
|
||||
* Context pass, one row per committed token: the five k/v projections over the projected trunk
|
||||
* taps, stored. The drafter's layers never run over the context.
|
||||
*
|
||||
* Query pass, `block` rows per sequence, through the five layers, attending to the context and
|
||||
* to each other.
|
||||
*
|
||||
* `k_norm` is per head over head_dim, so norming the two halves separately is bit-identical to
|
||||
* norming the concatenation. `attn_paged` with `causal = 0` serves the non-causal block. The
|
||||
* shape (16 heads, 2 KV heads, head_dim 128, GQA 8) matches the target, so the trunk's attention
|
||||
* and norm/rope rows serve it.
|
||||
*
|
||||
* ============================== ROW ALIGNMENT ==============================
|
||||
*
|
||||
* `block` is both the number of noise rows and the number of drafts (seven in, seven out, verify
|
||||
* width eight). Row j of [anchor, MASK x (block-1)] predicts position start + j + 1, the anchor
|
||||
* row included, so `steps() == block` here and `block - 1` in Dflash2, whose anchor row predicts
|
||||
* nothing. Getting this wrong only shifts proposals by one and drops acceptance to chance. The
|
||||
* core stages the block against `RadDrafterDecl::block` and runs the head over the last `depth`
|
||||
* rows, which covers both conventions (rad_builder.h).
|
||||
*
|
||||
* ============================== THE MARKOV HEAD USES Dflash2'S SELECTOR ==============================
|
||||
*
|
||||
* DSpark adds a rank-256 learned bigram bias to the draft logits:
|
||||
*
|
||||
* logits[l] += markov_w2 @ markov_w1[prev(l)] prev(0) = the anchor,
|
||||
* prev(l) = the token chosen at l - 1
|
||||
*
|
||||
* This is serial in l. Literally it is seven [rank, n_vocab] GEMMs with an argmax between each,
|
||||
* reading 66 MiB of `markov_w2` seven times a step. `dflash_select` scores
|
||||
*
|
||||
* unary[l][c] + sum_r pred[prev][r] * hp[l][r] * succ[cand[l][c]][r]
|
||||
*
|
||||
* over the base head's top K, reading the predecessor after the previous step's argmax inside one
|
||||
* workgroup. With `hp` absent (treated as ones) it is the bigram `<pred[prev], succ[cand]>`;
|
||||
* passing `markov_w1` as `pred` and `markov_w2` as `succ` makes the walk the greedily decoded
|
||||
* Markov head. The gather is K * rank * 2 bytes a position (8 KiB at K = 16).
|
||||
*
|
||||
* Only the candidate set is approximated: the bias re-ranks the base head's top K, where the
|
||||
* reference could promote any of 130560 tokens. Since every draft is verified, this costs only
|
||||
* acceptance.
|
||||
*
|
||||
* The confidence head (`AcceptRatePredictor`) is not implemented: it only lets a serving loop
|
||||
* shorten the block adaptively, and this engine's depth is fixed at declare (1, 3 or 7). It does
|
||||
* not change what the drafter proposes.
|
||||
*
|
||||
* ============================== PLAIN NORMS ==============================
|
||||
*
|
||||
* `w`, not `1 + w`: the reference uses `Qwen3RMSNorm` (`model_type: qwen3`), so this geometry's
|
||||
* `wadd` and `wadd_qk` are zero. That matches the MiniCPM5 target but is the drafter's own
|
||||
* setting.
|
||||
*
|
||||
* ============================== PRECISION ==============================
|
||||
*
|
||||
* E4M3 + a bf16 [N/128][K/128] plane fc, q/k/v/o, gate_up, down -- every linear
|
||||
* bf16, no plane every norm, and both Markov codebooks
|
||||
*
|
||||
* The checkpoint is dense bf16; the linears are rad_fp8.h's DenseFP8 over weights the recipe
|
||||
* quantises, because the drafter is read whole every decode step (324M parameters: 648 MB at
|
||||
* bf16, 324 MB at fp8). This can only change acceptance.
|
||||
*
|
||||
* The codebooks are bf16 and replicated: they are gathered by global token id from a merged
|
||||
* candidate set. 66.8 MiB each; only K rows are read per position, so the cost is residency.
|
||||
*
|
||||
* ============================== NOT DONE ==============================
|
||||
*
|
||||
* The q/k norms and ropes are four launches per layer where `qk_norm_rope` would be one. That
|
||||
* op takes a fused [q|k] row; the query pass would need a [q_dim + kv_dim] buffer, a column-
|
||||
* slice store and a contiguous q copy, as in rad_block_attn_fp8.h. Worth twenty launches a step.
|
||||
*
|
||||
* The all-reduce is not folded into the following norm (kArNone), so a TP2 query pass issues
|
||||
* ten collectives. At 28 KiB per message for one sequence (under the lossy floor), a fold
|
||||
* would save launches, not bytes.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_DSPARK_H
|
||||
#define RAD_BLOCK_DSPARK_H
|
||||
|
||||
#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, fixed by the w2a8 row. */
|
||||
enum { DS_W2_GROUP = 128 };
|
||||
|
||||
/* The drafter config beyond its geometry, read by the plugin from `draft.*` metadata keys. */
|
||||
struct Config {
|
||||
int64_t n_taps = 0; /* how many trunk layers `fc` concatenates */
|
||||
int64_t block = 0; /* noise rows per sequence, and drafts (one per row) */
|
||||
int64_t rank = 0; /* markov_rank: the codebooks' width */
|
||||
int64_t top_k = 0; /* candidates the Markov walk re-ranks */
|
||||
int64_t window = 0; /* sliding attention width, 0 for none */
|
||||
int causal = 0;
|
||||
/* Every row predicts, so `block`, not `block - 1` (see ROW ALIGNMENT). */
|
||||
int64_t steps() const { return block; }
|
||||
};
|
||||
|
||||
struct Wire {
|
||||
/* ---- the context pass, one row per committed token */
|
||||
rad_buf src = 0; /* [max_tok, n_taps * n_embd] the trunk's taps, read only */
|
||||
rad_buf c = 0; /* [max_tok, n_embd] fc's output, then normed in place */
|
||||
/* K and V are separate buffers because of the per-head k norm: `rmsnorm` takes one row
|
||||
* pitch, and K heads inside a fused [K|V] row are head_dim apart within a token but
|
||||
* 2*kv_dim apart between tokens. libr4d refuses such an operand (libr4d/r4d_model.cpp,
|
||||
* rows_pitch). */
|
||||
rad_buf ck = 0; /* [max_tok, kv_dim] one layer's K, reused across layers */
|
||||
rad_buf cv = 0; /* [max_tok, kv_dim] one layer's V, reused across layers */
|
||||
rad_buf srcq = 0, srcs = 0; /* fp8 codes and scales: e4m3 | f32 [.., /128] */
|
||||
rad_buf cq = 0, cs = 0;
|
||||
|
||||
/* ---- the query pass, `block` rows per sequence */
|
||||
rad_buf x = 0; /* [qrows, n_embd] the drafter's residual stream */
|
||||
/* Normed input and the block's delta share one activation, as in the trunk
|
||||
* (rad_block_attn_fp8.h): o_proj and down_proj write `h.x`, and the next norm folds it
|
||||
* into the stream before norming, writing `h` again. */
|
||||
ActFP8 h{}; /* [qrows, n_embd] */
|
||||
rad_buf q = 0; /* [qrows, q_dim] */
|
||||
rad_buf k = 0; /* [qrows, kv_dim] separate from v, see `ck` */
|
||||
rad_buf v = 0; /* [qrows, kv_dim] */
|
||||
ActFP8 attn{}; /* [qrows, q_dim] */
|
||||
rad_buf gate_up = 0; /* [qrows, 2 * n_ff] */
|
||||
ActFP8 ffn{}; /* [qrows, n_ff] */
|
||||
|
||||
/* ---- the head and the Markov walk, one row per draft position */
|
||||
rad_buf sel_h = 0; /* [srows, n_embd] the gathered final hidden states */
|
||||
rad_buf dq = 0; /* [srows, n_embd] i8 the 2-bit head's quantised activation */
|
||||
rad_buf ds = 0; /* [srows, 1] f32 one scale a row */
|
||||
rad_buf dsum = 0; /* [n_embd/128, pad] f32 GROUP-major, quant_act_i8's asum plane */
|
||||
rad_buf dlog = 0; /* [srows, head_rows(g)] bf16 the coarse logits */
|
||||
rad_buf cand = 0; /* [srows, top_k] i32 candidate token ids, global */
|
||||
rad_buf unary = 0; /* [srows, top_k] f32 and their logits */
|
||||
/* Vocab-parallel pairs, declared only when the head is sharded: (int32 id, f32 value)
|
||||
* pairs stored as f32, this rank's top-R and the all-gathered world * R. */
|
||||
rad_buf dpair = 0; /* [srows, top_k, 2] f32 */
|
||||
rad_buf dgath = 0; /* [srows, world * top_k, 2] f32 */
|
||||
rad_buf tokens = 0;/* [max_seqs, steps] i32 the draft; the engine reads it by name */
|
||||
};
|
||||
|
||||
/* rad_arch.h's vocab-head rule, asked through the block by whoever sizes `dlog` and the pair
|
||||
* planes. */
|
||||
static bool head_sharded(const Geom& g) { return vocab_head_sharded(g); }
|
||||
static int64_t head_rows(const Geom& g) { return vocab_head_rows(g); }
|
||||
|
||||
Geom g{}; /* the drafter's geometry, not the trunk's */
|
||||
Config cfg{};
|
||||
Wire w{};
|
||||
int first_layer = 0; /* absolute, for the KV group's layer_slot lookup */
|
||||
int64_t qrows = 0, crows = 0, srows = 0;
|
||||
int64_t gated_rows = 0; /* the band op_gug was declared over; 0 when there is no fold */
|
||||
rad_kvgroup kv = 0;
|
||||
|
||||
/* ---- model-scope weights */
|
||||
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 separate: the context pass needs only k and v, and a
|
||||
* block-scaled weight's layout follows its op's N, so k and v cannot be one weight issued a
|
||||
* half at a time. */
|
||||
rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {};
|
||||
DenseFP8 w_q[MAX_LAYERS]{}, w_k[MAX_LAYERS]{}, w_v[MAX_LAYERS]{}, w_o[MAX_LAYERS]{};
|
||||
rad_weight w_qn[MAX_LAYERS] = {}, w_kn[MAX_LAYERS] = {};
|
||||
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. Weightless ones are declared once and issued per layer; ops with weights
|
||||
* are per layer because a weight's prefetch interval and residency class come from the op
|
||||
* that declares it. */
|
||||
rad_op op_embed = 0, op_embed_ar = 0;
|
||||
/* The fused norm / residual add / quantise, declared directly rather than via rad_fp8.h's
|
||||
* NormQuantFP8: this block uses none of its fused-collective forms, and an array of the wrapper
|
||||
* (which nests a Geom) makes g++ 16.1 ICE in build_vec_init when the plugin assigns
|
||||
* `m = Model{}`. */
|
||||
rad_op op_anorm[MAX_LAYERS] = {}, op_fnorm[MAX_LAYERS] = {}, op_outnorm = 0;
|
||||
rad_op op_qat = 0;
|
||||
rad_op op_qp[MAX_LAYERS] = {}, op_kp[MAX_LAYERS] = {}, op_vp[MAX_LAYERS] = {};
|
||||
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 per committed token; `batch` carries those rows and the draft KV
|
||||
* group's slot mapping. */
|
||||
void context(RadCtx* c, const RadBatch* batch) const;
|
||||
/* The query pass, the head and the Markov walk, `block` rows per 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 srows equals the block's rows; kept separate from qrows because
|
||||
* Dflash2's convention makes them differ. */
|
||||
srows = g.max_seqs * cfg.steps();
|
||||
if (qrows <= 0 || srows <= 0) return RAD_E_INVAL;
|
||||
|
||||
/* ---------------------------------------------------------------- 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 Markov codebooks, bf16, replicated over the whole vocabulary. `markov_w1` (nn.Embedding)
|
||||
* and `markov_w2` (nn.Linear) both store [vocab, rank], so `w2 @ w1[prev]` is
|
||||
* `<w1[prev], w2[cand]>` and they map to the selector's `pred` and `succ`. RAD_ACCESS_VOCAB:
|
||||
* reads gather K rows per position. */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.markov_w1"),
|
||||
nm.ckpt("%s.markov_head.markov_w1.weight", ck)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.markov_w2"),
|
||||
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 (as in rad_block_mtp_fp8.h):
|
||||
* `dspark.draft_head.weight` is that tensor under its own name, quantised by the recipe to u2
|
||||
* codes with an f16 scale and u8 zero per group of 128. One checkpoint tensor, two views.
|
||||
*
|
||||
* The alternative source covers a tied head (small LLaMA derivatives ship no `lm_head.weight`
|
||||
* and reuse the embedding); it must match how the trunk declares its own head. */
|
||||
const bool dh_shard = head_sharded(g);
|
||||
const int dh_split = dh_shard ? RAD_SHARD_ROW : RAD_SHARD_NONE;
|
||||
const char* dhn = nm.f("dspark.draft_head.weight");
|
||||
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: each query row sees its whole block plus the context (`causal` comes from the
|
||||
* config's `is_causal: false`).
|
||||
*
|
||||
* Declared before both kv_stores, which read the resolved `block_size` back with
|
||||
* rad_kv_block_size(); before this declaration it returns zero. */
|
||||
op_attn = rw(b, RAD_OP(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, cfg.block), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", cfg.causal),
|
||||
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 is `fp8a8`, fed by a `quant_act_fp8`. There is no `fp8a16` band: that kernel is
|
||||
* M <= 1, and neither pass runs at one row. */
|
||||
op_qsrc = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", cfg.n_taps * g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
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, like the per-head q/k norms below: a row's scale is computed before the row is
|
||||
* written. */
|
||||
op_cnorm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_hnorm)),
|
||||
{w.c}, {w.c});
|
||||
/* One quantise for all layers: every layer's k and v read the same `c`. */
|
||||
op_qc = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.c}, {w.cq, w.cs});
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
/* One op per weight: an op's declared weight list gives each weight its prefetch interval
|
||||
* and residency class. */
|
||||
op_ck[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("N", kvd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
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, so a K-only tensor is
|
||||
* n_head = n_head_kv, n_head_kv = 0. Weightless, so one op serves every layer.
|
||||
*
|
||||
* Each context row is rotated by its own absolute position, as in the reference's single
|
||||
* concatenated rope (k gets the full position range, q the last q_len). */
|
||||
op_crope = rw(b, decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
|
||||
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 the lookup is partial. The all-reduce is exact:
|
||||
* each row comes from one rank and the others add zero, so a lossy wire would only lose
|
||||
* precision. */
|
||||
if (g.world > 1)
|
||||
op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
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});
|
||||
|
||||
/* Norm, residual add and quantise are one op, `rmsnorm_quant_fp8` (what rad_fp8.h's
|
||||
* NormQuantFP8 wraps). Layer 0 has no delta to fold, each later norm folds the previous
|
||||
* block's delta, and op_outnorm folds the last into the final norm, so there is no `add` op.
|
||||
* The final norm's fp8 output is unused (the head runs its own i8 quantiser), a few KiB of
|
||||
* waste that saves a launch: libr4d has no plain `rmsnorm_add` row.
|
||||
*
|
||||
* The op computes residual_out = x + residual, y = rmsnorm(residual_out) * w. A folded site
|
||||
* passes the previous block's output as `x` and the stream as `residual`; layer 0 passes the
|
||||
* stream as `x` and no residual. `residual` is INOUT, so it is in both the read and write sets;
|
||||
* otherwise the planner could reorder a reader in front of it. */
|
||||
auto decl_norm = [&](rad_weight gain, bool fold) -> rad_op {
|
||||
rad_op h = RAD_OP(b, "rmsnorm_quant_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd)),
|
||||
RAD_WEIGHTS(gain));
|
||||
if (!h) return 0;
|
||||
rad_buf rd[2] = { fold ? w.h.x : w.x, w.x };
|
||||
rad_buf wr[4] = { w.h.q, w.h.s, w.h.x, w.x };
|
||||
rad_op_reads (b, h, rd, fold ? 2 : 1);
|
||||
rad_op_writes(b, h, wr, fold ? 4 : 3);
|
||||
return h;
|
||||
};
|
||||
op_qat = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", qd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.attn.x}, {w.attn.q, w.attn.s});
|
||||
if (!op_qat) return RAD_E_INVAL;
|
||||
|
||||
/* Invariant: the norms are declared where step() issues them. Declaration order is the buffer
|
||||
* planner's liveness (a transient lives over the op indices that touch it, and disjoint spans
|
||||
* may share bytes; core/build/rad_bufplan.cpp). The norms are the only ops touching the stream
|
||||
* `x` after the embedding, so their positions define its lifetime: each layer's two norms sit
|
||||
* in the loop, the final one after every op the layers issue, including the shared handles
|
||||
* below. Declared up front, the stream's lifetime would end before the layers and the planner
|
||||
* could overlay a feed-forward temporary on it. */
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
op_anorm[i] = decl_norm(w_anorm[i], i != 0);
|
||||
if (!op_anorm[i]) return RAD_E_INVAL;
|
||||
op_qp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", qd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_q[i].w, w_q[i].s)),
|
||||
{w.h.q, w.h.s}, {w.q});
|
||||
op_kp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", kvd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_k[i].w, w_k[i].s)),
|
||||
{w.h.q, w.h.s}, {w.k});
|
||||
op_vp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", kvd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_v[i].w, w_v[i].s)),
|
||||
{w.h.q, w.h.s}, {w.v});
|
||||
op_qn[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head), RAD_INT("n", g.head_dim),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_qn[i])),
|
||||
{w.q}, {w.q});
|
||||
op_kn[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head_kv),
|
||||
RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps),
|
||||
RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_kn[i])),
|
||||
{w.k}, {w.k});
|
||||
op_op[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", qd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_o[i].w, w_o[i].s)),
|
||||
{w.attn.q, w.attn.s}, {w.h.x});
|
||||
op_fnorm[i] = decl_norm(w_fnorm[i], true);
|
||||
if (!op_fnorm[i]) return RAD_E_INVAL;
|
||||
op_gu[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", 2 * g.n_ff),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_gu[i].w, w_gu[i].s)),
|
||||
{w.h.q, w.h.s}, {w.gate_up});
|
||||
op_gug[i] = decl_gated_fold(b, qrows, 2 * g.n_ff, g.n_embd, w_gu[i].w, w_gu[i].s,
|
||||
{w.h.q, w.h.s}, {w.ffn.q, w.ffn.s}, &gated_rows);
|
||||
op_dn[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", g.n_ff), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
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, decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
RAD_STR("mode", "neox")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.q}, {w.q});
|
||||
op_krope = rw(b, decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
RAD_STR("mode", "neox")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.k}, {w.k});
|
||||
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, issued after both the out and the down projection (same shape, same buffer).
|
||||
* Exact or lossy per the deployment, as for the trunk. */
|
||||
if (g.world > 1)
|
||||
op_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, qrows * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h.x}, {w.h.x});
|
||||
op_outnorm = decl_norm(w_norm, true);
|
||||
if (!op_outnorm) return RAD_E_INVAL;
|
||||
|
||||
/* ---------------------------------------------------------------- the head and the walk
|
||||
*
|
||||
* Every row predicts, so the head runs over all `steps` rows, anchor included (see ROW
|
||||
* ALIGNMENT). The gather numbers rows s * steps + l as the walk reads them; for this
|
||||
* convention it is the identity, but `out_ids` is the contract, so it is issued anyway. */
|
||||
op_gather = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
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, reports global ids and also writes the pair
|
||||
* plane the gather moves. Replicated, `vocab_off` is omitted: an optional parameter present
|
||||
* with value 0 is a different declaration from an absent one. */
|
||||
op_dtopk = dh_shard
|
||||
? rw(b, RAD_OP(b, "row_topk",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)),
|
||||
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 are adjacent for
|
||||
* `row_topk_merge`, which reduces them to exactly the unsharded global top-R, ties
|
||||
* included; the replicated codebooks are then indexed by global id. */
|
||||
op_dgather = rw(b, RAD_OP(b, "all_gather",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_INT("numel", srows * cfg.top_k * 2),
|
||||
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 `hp` absent is the bigram
|
||||
* `unary + <markov_w1[prev], markov_w2[cand]>`, decoded greedily (see the file header). The
|
||||
* absent `hp` is passed as RAD_NONE at the issue site.
|
||||
*
|
||||
* `anchor_stride` is `block`: the operand is the step's token_ids, `block` per sequence with
|
||||
* the anchor first. */
|
||||
op_sel = rw(b, RAD_OP(b, "dflash_select",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("steps", cfg.steps()),
|
||||
RAD_INT("top_k", cfg.top_k), RAD_INT("rank", cfg.rank),
|
||||
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. Folded, `x` is the previous block's delta in `h.x` and the stream is the
|
||||
* residual; unfolded (layer 0), `x` is the stream and the residual is RAD_NONE. */
|
||||
auto issue_norm = [&](rad_op op, bool fold, rad_weight gain, int64_t rows) {
|
||||
RAD_ISSUE_N(c, op, rows, brows(fold ? w.h.x : w.x, rows),
|
||||
fold ? brows(w.x, rows) : RAD_NONE, RAD_W(gain),
|
||||
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 feed-forward delta into the stream and
|
||||
* quantises; at layer 0 it norms the embedding. */
|
||||
issue_norm(op_anorm[i], i != 0, w_anorm[i], T);
|
||||
RAD_ISSUE_N(c, op_qp[i], T, brows(w.h.q, T), brows(w.h.s, T),
|
||||
RAD_W(w_q[i].w), RAD_W(w_q[i].s), brows(w.q, T), RAD_NONE, RAD_NONE);
|
||||
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));
|
||||
/* Noise rows go into the cache past `seqused`; the next context pass overwrites them,
|
||||
* which is the reference's `crop(start)`. */
|
||||
RAD_ISSUE_N(c, op_store, T, brows(w.k, T), brows(w.v, T),
|
||||
praw(slot, RAD_I32, T), kv_cache(kv, first_layer + i));
|
||||
RAD_ISSUE_N(c, op_attn, batch->max_q_len,
|
||||
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. */
|
||||
issue_norm(op_outnorm, true, w_norm, T);
|
||||
|
||||
/* The predicting rows (all of them), named by the scheduler through out_ids. */
|
||||
const int64_t S = batch->n_out;
|
||||
if (S <= 0) return;
|
||||
RAD_ISSUE_N(c, op_gather, S, RAD_B(w.h.x), praw(batch->out_ids, RAD_I32, S),
|
||||
brows(w.sel_h, S));
|
||||
|
||||
/* `dsum` is group-major, [n_embd/group][ceil(M/16)*16], so it has no row slice; pass it
|
||||
* whole. */
|
||||
RAD_ISSUE_N(c, op_dquant, S, brows(w.sel_h, S), brows(w.dq, S), brows(w.ds, S),
|
||||
RAD_B(w.dsum));
|
||||
/* The trailing operand is mxfp4's optional reference, absent here. Operands are positional,
|
||||
* so an absent optional one is RAD_NONE, not a shorter list. */
|
||||
RAD_ISSUE_N(c, op_dlogits, S, brows(w.dq, S), brows(w.ds, S), RAD_W(w_dh), RAD_W(w_dhs),
|
||||
brows(w.dlog, S), RAD_B(w.dsum), RAD_NONE);
|
||||
if (op_dmerge) {
|
||||
/* Sharded, this rank's top-R are only candidates; the merge overwrites `cand`/`unary`. */
|
||||
RAD_ISSUE_N(c, op_dtopk, S, brows(w.dlog, S), brows(w.cand, S), brows(w.unary, S),
|
||||
brows(w.dpair, S));
|
||||
RAD_ISSUE(c, op_dgather, brows(w.dpair, S), brows(w.dgath, S));
|
||||
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 */
|
||||
@@ -0,0 +1,359 @@
|
||||
/* rad_block_gdn.h -- one gated-delta-net (linear attention) block, bf16 operands.
|
||||
*
|
||||
* Hybrid models are the normal case (spec §7.2): Qwen3.5-27B has 48 GDN layers to 16
|
||||
* full-attention ones. This block composes with AttnGatedBF16 and MlpBF16 in one plugin.
|
||||
*
|
||||
* rmsnorm -> in gemm ([q|k|v|a|b]) -> z gemm
|
||||
* prefill: gdn_conv_prep -> gdn_kkt_solve -> gdn_chunk_scan -> gdn_gated_rmsnorm
|
||||
* decode: gdn_conv_update -> gdn_recurrent_update (which folds the gated norm)
|
||||
* -> out gemm -> [all_reduce] -> residual add
|
||||
*
|
||||
* The two paths branch on phase, which spec §10 allows: both sequences are declared, resolved
|
||||
* and in the graph dump. The chunked path amortises over a prefill chunk, the recurrent path is
|
||||
* O(1) per token, and no single kernel suits both.
|
||||
*
|
||||
* Both paths take `num_accepted`: the recurrent state and conv window have already absorbed
|
||||
* rejected draft tokens, and rollback is a change of read offset, not a recompute (spec §10,
|
||||
* OPS.md).
|
||||
*
|
||||
* ============================== TWO CONVENTIONS ==============================
|
||||
*
|
||||
* `A_log` is a log. The decay is
|
||||
*
|
||||
* g = -exp(A_log) . softplus(a + dt_bias)
|
||||
*
|
||||
* and the kernels (libr4d and libref) take the exponent themselves. Safetensors stores
|
||||
* `linear_attn.A_log` in that form, so the weight is declared `ssm_a_log` and copied through.
|
||||
* llama.cpp's GGUF conversion writes `ssm_a = -exp(A_log)` instead, so a container built from a
|
||||
* GGUF must undo it; otherwise the decay is -exp(-exp(A_log)), near -1 for every head. The name
|
||||
* makes the convention visible in the weight manifest.
|
||||
*
|
||||
* q and k are L2-normalised, not RMS-normalised (no division by the width, no gain), inside
|
||||
* gdn_conv_prep (prefill) and gdn_recurrent_update (decode), which already hold the head in
|
||||
* registers. There is no separate l2_norm op.
|
||||
*
|
||||
* ============================== THE FUSED IN-PROJECTION ==============================
|
||||
*
|
||||
* gdn_conv_prep's `x` is the whole row [q | k | v | a | b]: conv_dim convolved channels, then
|
||||
* one decay input and one beta input per value head. So in_proj_qkv, in_proj_a and in_proj_b are
|
||||
* one declared weight and one GEMM.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_GDN_H
|
||||
#define RAD_BLOCK_GDN_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
|
||||
#include <cmath>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct GdnBF16 {
|
||||
struct Config {
|
||||
int64_t n_head_k = 0; /* per rank -- q and k share these */
|
||||
int64_t head_k = 0; /* the recurrent state's key width */
|
||||
int64_t n_head_v = 0; /* per rank; a multiple of n_head_k, 3x it on this model */
|
||||
int64_t head_v = 0;
|
||||
int64_t conv_width = 4;
|
||||
int64_t chunk = 64; /* the chunked-scan interval, and the checkpoint interval */
|
||||
|
||||
int64_t k_dim() const { return n_head_k * head_k; }
|
||||
int64_t v_dim() const { return n_head_v * head_v; }
|
||||
int64_t conv_dim() const { return 2 * k_dim() + v_dim(); }
|
||||
int64_t in_dim() const { return conv_dim() + 2 * n_head_v; } /* ... + a + b */
|
||||
};
|
||||
|
||||
struct Wire {
|
||||
rad_buf x = 0; /* [max_tok, n_embd] the residual stream */
|
||||
rad_buf h = 0; /* [max_tok, n_embd] normed input, then the out projection */
|
||||
rad_buf in = 0; /* [max_tok, in_dim] [q|k|v|a|b], pre-convolution */
|
||||
rad_buf z = 0; /* [max_tok, v_dim] the output gate */
|
||||
rad_buf q = 0; /* [max_tok, n_head_k, head_k] post-convolution, l2-normed */
|
||||
rad_buf k = 0; /* [max_tok, n_head_k, head_k] */
|
||||
rad_buf v = 0; /* [max_tok, n_head_v, head_v] */
|
||||
rad_buf gdec = 0; /* [max_tok, n_head_v] the resolved decay, per-chunk cumsum */
|
||||
rad_buf beta = 0; /* [max_tok, n_head_v] */
|
||||
rad_buf kkt = 0; /* [max_tok, n_head_v, chunk] the within-chunk inverse */
|
||||
rad_buf o = 0; /* [max_tok, n_head_v, head_v] */
|
||||
};
|
||||
|
||||
/* Checkpoint-side names for one layer; the plugin owns the spelling (spec §2.4). */
|
||||
struct Src {
|
||||
const char* norm = nullptr; /* input_layernorm.weight */
|
||||
const char* in_qkv = nullptr; /* linear_attn.in_proj_qkv.weight */
|
||||
const char* in_a = nullptr; /* linear_attn.in_proj_a.weight */
|
||||
const char* in_b = nullptr; /* linear_attn.in_proj_b.weight */
|
||||
const char* in_z = nullptr; /* linear_attn.in_proj_z.weight */
|
||||
const char* conv1d = nullptr; /* linear_attn.conv1d.weight */
|
||||
const char* a_log = nullptr; /* linear_attn.A_log, a log (see the header) */
|
||||
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 to 48 value heads on Qwen3.5-27B);
|
||||
* the kernels take H and Hg separately and need H to be a multiple of Hg. */
|
||||
if (cfg.n_head_v % cfg.n_head_k != 0) {
|
||||
fprintf(stderr, "radiance: %lld value heads is not a multiple of %lld key heads\n",
|
||||
(long long)cfg.n_head_v, (long long)cfg.n_head_k);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* The query scale is required. `gdn_chunk_scan` and `gdn_recurrent_update` multiply the output
|
||||
* by `scale` (o = scale * e^g Q S^T + ...), which defaults to 1; FLA's chunk_gated_delta_rule,
|
||||
* vLLM and llama.cpp use head_k^-0.5.
|
||||
*
|
||||
* The following gated RMS norm does not cancel it: the scan output is around 1e-6, so
|
||||
* mean(o^2) ~ 1e-12 is dominated by eps = 1e-6 and the norm reduces to a fixed division by
|
||||
* sqrt(eps). Without the scale every delta-net layer's contribution is sqrt(head_k) too
|
||||
* large. */
|
||||
const double q_scale = 1.0 / std::sqrt((double)cfg.head_k);
|
||||
|
||||
const int64_t v_dim = cfg.v_dim();
|
||||
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));
|
||||
/* q, k, v, a and b in one row, as gdn_conv_prep reads it. A row-sharded CONCAT shards each
|
||||
* source before concatenating, and `in_proj_qkv` is itself three head groups, so the row split
|
||||
* below has five parts. Maps are declared before the weights, since weight encodings are looked
|
||||
* up through the map. */
|
||||
RAD_ARCH_TRY(map_concat(b, nm.f("blk.%d.ssm_in.weight", l),
|
||||
{ src.in_qkv, src.in_a, src.in_b }, 0));
|
||||
RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ssm_z.weight", l), src.in_z));
|
||||
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 shards with its channels. The checkpoint ships [conv_dim, 1, 4];
|
||||
* the depthwise group extent is squeezed at convert. Qwen3.5's conv1d has bias=False, so the
|
||||
* bias operand is passed absent. */
|
||||
w_conv = decl_w(b, nm.f("blk.%d.ssm_conv1d.weight", l), RAD_BF16,
|
||||
{conv_dim, cfg.conv_width},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l), 0,
|
||||
{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, so replicated. */
|
||||
w_out_norm = decl_w(b, nm.f("blk.%d.ssm_norm.weight", l), RAD_F32, {cfg.head_v},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
w_out = decl_w(b, nm.f("blk.%d.ssm_out.weight", l), RAD_BF16, {g.n_embd, v_dim},
|
||||
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 (prefill). `chunk` is RAD_DERIVED on gdn_kkt_solve and gdn_chunk_scan
|
||||
* (the tile length belongs to the kernel), but gdn_conv_prep takes it explicitly because its
|
||||
* gate cumsum must be cut at the scan's tile boundary. Known gap: nothing checks that the
|
||||
* supplied and derived values agree; a mismatch applies the decay over the wrong span. */
|
||||
op_conv_prep = rw(b, RAD_OP(b, "gdn_conv_prep",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_k", cfg.head_k),
|
||||
RAD_INT("head_v", cfg.head_v), RAD_INT("chunk", cfg.chunk),
|
||||
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 has up to n_spec+1 query rows per sequence. `n_head_v` is stated explicitly: with 48
|
||||
* value heads to 16 key heads, inferring it from a flattened view gives a plausible wrong
|
||||
* answer. */
|
||||
op_conv_update = rw(b, RAD_OP(b, "gdn_conv_update",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok),
|
||||
RAD_INT("head_k", cfg.head_k),
|
||||
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});
|
||||
/* `state_form` states what the state cache holds, which the operands do not show. libr4d's
|
||||
* recurrent update has two contracts: per_candidate writes one full state per candidate token
|
||||
* (1 + n_spec slots); anchor keeps one committed state per sequence and replays the accepted
|
||||
* prefix from a scratch slot (two slots at any depth). `o` is the same, `state` differs. It
|
||||
* matches KVGroupPlan::state_copies (2 when speculating, else 1), and lets a reference decline
|
||||
* the form it lacks and the kernel refuse a pool sized for the other. */
|
||||
op_recur = rw(b, RAD_OP(b, "gdn_recurrent_update",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_k", cfg.head_k),
|
||||
RAD_INT("head_v", cfg.head_v),
|
||||
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;
|
||||
/* Slots per state_index row: the state, plus scratch when a kernel serving speculation asks
|
||||
* for it (RadKVGroupBatch). Passed through unread. */
|
||||
const int64_t st_w = st && st->state_index_pitch > 0 ? st->state_index_pitch : 1;
|
||||
const int32_t* cv_idx = cv ? cv->state_index : nullptr;
|
||||
|
||||
const int64_t T = batch->n_tok;
|
||||
const int64_t S = batch->n_seq;
|
||||
const int64_t 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));
|
||||
|
||||
/* Each path runs over its own run of sequences (details in rad_block_gdn_fp8.h's step()). The
|
||||
* step is sorted decode-first and every kernel derives grid and rows from cu_seqlens, which
|
||||
* holds absolute offsets: the prefill half gets `cu + D` with token operands at their base,
|
||||
* the decode half has both narrowed to DT. The gated norm is per token, so it takes a row
|
||||
* slice. */
|
||||
int64_t D = 0, DT = 0;
|
||||
batch_split(batch, &D, &DT);
|
||||
/* The decode half's band. In a mixed step max_q_len is the prefill chunk's; in a pure decode
|
||||
* step it is already right, so a batch leaving max_q_len_decode zero still works there. */
|
||||
const int32_t qd = batch->phase == RAD_PHASE_MIXED ? batch->max_q_len_decode : batch->max_q_len;
|
||||
const int64_t P = S - D;
|
||||
const int64_t PT = T - DT;
|
||||
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, so it takes z and the gain. */
|
||||
RAD_ISSUE_N(c, op_recur, qd,
|
||||
brows(w.q, DT), brows(w.k, DT), brows(w.v, DT),
|
||||
bcol(w.in, conv_dim, H, DT), bcol(w.in, conv_dim + H, H, DT),
|
||||
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, unused: the bf16 out projection reads
|
||||
* `o` directly. Operands are positional and the runtime checks the schema's
|
||||
* count of sixteen (core/runtime/issue.cpp), so pass two RAD_NONE. */
|
||||
RAD_NONE, RAD_NONE);
|
||||
}
|
||||
|
||||
if (P > 0) {
|
||||
/* Sixteen operands, inputs before outputs (docs/OPS.md). `a` and `b_gate` are optional in
|
||||
* the schema (libref falls back to the fused `x` tail), but libr4d's conv_prep requires
|
||||
* them and `cache_idx`; omitting them would silently fall back to the reference kernel.
|
||||
*
|
||||
* `has_init` is ctx_lens: zero exactly when a sequence starts fresh (new, or preempted and
|
||||
* replaying, with a recycled conv slot), so the first chunk does not convolve against the
|
||||
* slot's stale window. */
|
||||
RAD_ISSUE(c, op_conv_prep,
|
||||
brows(w.in, T), RAD_W(w_conv), RAD_NONE, RAD_W(w_a_log), RAD_W(w_dt_bias),
|
||||
kv_cache(kv_conv, layer), praw(batch->cu_seqlens + D, RAD_I32, P + 1),
|
||||
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 over the prefill rows only; the recurrent kernel already
|
||||
* gated the decode rows. */
|
||||
RAD_ISSUE_N(c, op_gnorm, PT,
|
||||
brow_slice(w.o, DT, PT, v_dim), brow_slice(w.z, DT, PT, v_dim),
|
||||
RAD_W(w_out_norm), brow_slice(w.o, DT, PT, v_dim));
|
||||
}
|
||||
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 */
|
||||
@@ -0,0 +1,541 @@
|
||||
/* rad_block_gdn_fp8.h -- the gated-delta-net block with block-scaled FP8 projections.
|
||||
*
|
||||
* The architecture (A_log convention, in-kernel L2 norm of q and k, the two declared paths,
|
||||
* `num_accepted`) is documented in rad_block_gdn.h and does not change with the weight format.
|
||||
*
|
||||
* ============================== a AND b SPLIT OUT; z FUSED ==============================
|
||||
*
|
||||
* rad_block_gdn.h fuses in_proj_qkv, in_proj_a and in_proj_b into one weight. Here the
|
||||
* checkpoint prevents it:
|
||||
*
|
||||
* in_proj_qkv.weight F8_E4M3 [10240, 5120] with weight_scale_inv [80, 40]
|
||||
* in_proj_z.weight F8_E4M3 [ 6144, 5120] with weight_scale_inv [48, 40]
|
||||
* in_proj_a.weight BF16 [48, 5120] -- no scale plane
|
||||
* in_proj_b.weight BF16 [48, 5120] -- no scale plane
|
||||
*
|
||||
* a and b have one row per value head (48, not a whole 128-row block), so the quantiser left them
|
||||
* bf16 and they cannot be concatenated with E4M3 tensors. They become a separate small bf16
|
||||
* `gemm_nt` ([96, 5120], 0.5% of the layer's projection bytes). gdn_conv_prep and
|
||||
* gdn_recurrent_update take a and b as separate operands in both blocks (column views of the
|
||||
* fused row there, of their own buffer here); libref sizes its `x` read as
|
||||
* `conv_dim + (a present ? 0 : 2*H)` for this case.
|
||||
*
|
||||
* The output gate is fused instead, into `ssm_inz`: in_proj_z is E4M3 with whole scale blocks and
|
||||
* reads the same normed activation, so [q|k|v|z] is one weight and one launch. `w.in.x` is then
|
||||
* conv_dim + v_dim wide, and the convolution input and the gate are column views of it; the
|
||||
* consuming kernels all take a row pitch.
|
||||
*
|
||||
* ============================== THE OUT-PROJECTION'S INPUT IS RANK 3 ==============================
|
||||
*
|
||||
* `o` is [tokens, value heads, head width] because libr4d's chunk-scan and recurrent kernels need
|
||||
* rank 3. The quantiser reads dim 0 as rows and the rest as the row (as r4d_row_pitch does and
|
||||
* the GEMM's K requires); one row per head would put scales on a grid the GEMM does not read.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_GDN_FP8_H
|
||||
#define RAD_BLOCK_GDN_FP8_H
|
||||
|
||||
#include "rad_fp8.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct GdnFP8 {
|
||||
/* The bf16 block's geometry plus the gate activation, uneven head splits, and `ab_dim`
|
||||
* (2 * n_head_v), the width of the separate a|b projection. */
|
||||
struct Config {
|
||||
int64_t n_head_k = 0;
|
||||
int64_t head_k = 0;
|
||||
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, a per-checkpoint property: `RMSNormGated` defaults to
|
||||
* silu (every Qwen3.5/3.6 release), while Qwen4-Exp sets `output_gate_type: "sigmoid"`.
|
||||
* libr4d's r4d_gdn_gated_rmsnorm (`gn_act`) and `gdn_recurrent_update` implement both.
|
||||
* "silu" or "sigmoid"; anything else is refused. */
|
||||
const char* act = "silu";
|
||||
/* Uneven head split (rad_weight_shard_span_parts). n_head_k / n_head_v are this rank's;
|
||||
* k_first / v_first are its first heads within the container's n_head_k_all /
|
||||
* n_head_v_all. k_first < 0 means the plain even row shard. Three ranks over 16 K heads
|
||||
* take 6, 5 and 5 (18, 15, 15 of 48 V heads), with no padding. */
|
||||
int64_t k_first = -1, v_first = -1;
|
||||
int64_t n_head_k_all = 0, n_head_v_all = 0;
|
||||
bool uneven() const { return k_first >= 0; }
|
||||
|
||||
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 */
|
||||
/* [q|k|v] and the output gate from one GEMM (ssm_inz): the convolution reads the left
|
||||
* `conv_dim` columns and the gate is the right `v_dim`, both as `bcol` views. */
|
||||
ActFP8 in{}; /* [max_tok, conv_dim+v_dim] [q|k|v] then the output gate */
|
||||
rad_buf ab = 0; /* [max_tok, 2*n_head_v] the decay and beta inputs, bf16 */
|
||||
rad_buf q = 0; /* [max_tok, n_head_k, head_k] post-convolution, l2-normed */
|
||||
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 in one launch, with the
|
||||
* convolution in the recurrent update's prologue. The pair is declared either way; cr_rows is
|
||||
* the widest decode window the fold serves. */
|
||||
rad_op op_cr = 0;
|
||||
int64_t cr_rows = 0;
|
||||
rad_op op_ar = 0, op_add = 0;
|
||||
/* The next block absorbs this block's closing all-reduce (see rad_block_attn_gated_fp8.h). */
|
||||
bool ar_out = false;
|
||||
/* Which wires that consumer takes (ArOut, rad_fp8.h); set before declare. */
|
||||
int ar_out_take = kArOutNorm;
|
||||
|
||||
/* `fold`: the previous block left its delta in `w.h.x` for this norm to add. `add_out`: the
|
||||
* next block will not add, so this one issues the trailing add. See rad_fp8.h. */
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int l,
|
||||
rad_kvgroup state, rad_kvgroup conv, const Wire& wire, const Src& s,
|
||||
bool fold = false, bool add_out = true,
|
||||
int ar_in = kArNone, bool ar_out_ = false);
|
||||
/* `own_ar` false: the caller issues this step's all-reduce itself, a row slice at a time
|
||||
* (issue_ar), to overlap it with other work (a pipelined prefill). Only on a block without a
|
||||
* trailing add, which would read the delta before the reduction. */
|
||||
void step(RadCtx* c, const RadBatch* batch, bool own_ar = true,
|
||||
ArPieces* pieces = nullptr) const;
|
||||
/* Whether a step of T rows issues the all-reduce itself, asked by a caller before taking it
|
||||
* over; and that all-reduce over rows [r0, r0 + rows) of the output. */
|
||||
bool issues_ar(int64_t T) const { return op_ar && !ar_taken(g, T, ar_out, ar_out_take); }
|
||||
void issue_ar(RadCtx* c, int64_t r0, int64_t rows) const {
|
||||
RAD_ISSUE_N(c, op_ar_ov ? op_ar_ov : op_ar, rows * g.n_embd,
|
||||
brow_slice(w.h.x, r0, rows, g.n_embd), RAD_NONE);
|
||||
}
|
||||
/* Set before declare: the `overlap` issue_ar's collective is declared at, 0 for none. */
|
||||
int ar_overlap = 0;
|
||||
rad_op op_ar_ov = 0;
|
||||
};
|
||||
|
||||
inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int l,
|
||||
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 is required; rad_block_gdn.h explains why the gated norm does not cancel
|
||||
* it. */
|
||||
const double q_scale = 1.0 / std::sqrt((double)cfg.head_k);
|
||||
|
||||
if (!cfg.act || (std::strcmp(cfg.act, "silu") != 0 && std::strcmp(cfg.act, "sigmoid") != 0)) {
|
||||
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();
|
||||
|
||||
/* `s.norm == nullptr`: the architecture prepares the input (a gated-residual model's
|
||||
* rad_block_hc.h `hc_read`), so `wire.h` is already normed and quantised and no norm weight is
|
||||
* declared. `ar_in` is then refused, since the fused all-reduce lives inside the norm. See
|
||||
* rad_block_attn_gated_fp8.h. */
|
||||
ext_in = (s.norm == nullptr);
|
||||
if (ext_in) {
|
||||
if (!w.h.x || (!g.w_bf16 && (!w.h.q || !w.h.s)) || ar_in != kArNone) return RAD_E_INVAL;
|
||||
} 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));
|
||||
}
|
||||
/* Maps before weights: weight encodings are looked up through the map. */
|
||||
RAD_ARCH_TRY(map_concat(b, nm.f("blk.%d.ssm_ab.weight", l), { s.in_a, s.in_b }, 0));
|
||||
RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ssm_conv1d.weight", l), s.conv1d));
|
||||
RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ssm_a_log", l), s.a_log));
|
||||
RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ssm_dt.bias", l), s.dt_bias));
|
||||
RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ssm_norm.weight", l), s.out_norm));
|
||||
/* The decay and beta projections, bf16 as in the checkpoint. Row-sharded with their value
|
||||
* heads: the two-part split gives rank r rows [r*n_head_v, (r+1)*n_head_v) of each of a and
|
||||
* b, which a contiguous slice of the concatenation would not. */
|
||||
w_ab = decl_w(b, nm.f("blk.%d.ssm_ab.weight", l), RAD_BF16, {ab_dim, g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l), 0,
|
||||
{cfg.n_head_v, cfg.n_head_v});
|
||||
/* The depthwise convolution shards with its channels, [q|k|v] (three parts). */
|
||||
w_conv = decl_w(b, nm.f("blk.%d.ssm_conv1d.weight", l), RAD_BF16,
|
||||
{conv_dim, cfg.conv_width},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l), 0,
|
||||
{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));
|
||||
|
||||
/* Norm and quantise in one op (rad_fp8.h: NormQuantFP8); the qkv|z and a|b projections read
|
||||
* it. */
|
||||
if (!ext_in)
|
||||
RAD_ARCH_TRY(nq_h.declare(b, g, w_norm, fold ? w.h.x : w.x, w.h, g.n_embd,
|
||||
fold ? w.x : 0, 0, ar_in));
|
||||
/* Two checkpoint tensors (in_proj_qkv = [q|k|v], in_proj_z = the gate), four projections, one
|
||||
* GEMM. At decode two calls at 5120 and 3072 rows cost more than one at 8192, since each pays
|
||||
* its own ramp and tail. Bit-identical: row arithmetic is unchanged and both extents are past
|
||||
* the split-K threshold.
|
||||
*
|
||||
* The four row parts are required so rank r owns its slice of each of q, k, v and z; one
|
||||
* contiguous cut would give rank 0 all of q and k. */
|
||||
RAD_ARCH_TRY(in.declare(b, nm, g, nm.f("blk.%d.ssm_inz", l), conv_dim + v_dim, g.n_embd,
|
||||
RAD_SHARD_ROW, grp_layer(l), { s.in_qkv, s.in_z }, w.h, w.in.x, 0,
|
||||
{ cfg.k_dim(), cfg.k_dim(), cfg.v_dim(), cfg.v_dim() }, 0, 0,
|
||||
/* a rotated weight was rotated per checkpoint tensor: q|k|v, then z */
|
||||
{ 2 * cfg.k_dim() + cfg.v_dim(), cfg.v_dim() }));
|
||||
if (cfg.uneven()) {
|
||||
/* This rank's heads of each part, in container rows: q and k by K head, v and z by V head.
|
||||
* The scale plane of a row shard has the same rows (its blocks run along K). */
|
||||
const int64_t kl = cfg.k_first * cfg.head_k, vl = cfg.v_first * cfg.head_v;
|
||||
const int64_t ka = cfg.n_head_k_all * cfg.head_k, va = cfg.n_head_v_all * cfg.head_v;
|
||||
const int64_t lo[4] = { kl, kl, vl, vl };
|
||||
const int64_t hi[4] = { kl + cfg.k_dim(), kl + cfg.k_dim(), vl + cfg.v_dim(), vl + cfg.v_dim() };
|
||||
const int64_t tot[4] = { ka, ka, va, va };
|
||||
RAD_ARCH_TRY(in.span_parts(b, lo, hi, tot, 4));
|
||||
const int64_t clo[3] = { kl, kl, vl }, chi[3] = { kl + cfg.k_dim(), kl + cfg.k_dim(), vl + cfg.v_dim() };
|
||||
const int64_t ctot[3] = { ka, ka, va };
|
||||
RAD_ARCH_TRY(rad_weight_shard_span_parts(b, w_conv, clo, chi, ctot, 3));
|
||||
const int64_t alo[2] = { cfg.v_first, cfg.v_first };
|
||||
const int64_t ahi[2] = { cfg.v_first + cfg.n_head_v, cfg.v_first + cfg.n_head_v };
|
||||
const int64_t atot[2] = { cfg.n_head_v_all, cfg.n_head_v_all };
|
||||
RAD_ARCH_TRY(rad_weight_shard_span_parts(b, w_ab, alo, ahi, atot, 2));
|
||||
RAD_ARCH_TRY(rad_weight_shard_span(b, w_a_log, cfg.v_first, cfg.v_first + cfg.n_head_v));
|
||||
RAD_ARCH_TRY(rad_weight_shard_span(b, w_dt_bias, cfg.v_first, cfg.v_first + cfg.n_head_v));
|
||||
}
|
||||
/* One launch over all rows: libr4d's bf16 kernel for this 96-column shape is general in M
|
||||
* (MT row tiles per block, grid.y covers the rest). A kernel capped at M = 64 would cap every
|
||||
* op in the step, and so the prefill chunk, at 64 tokens (see brow_slice in rad_arch.h).
|
||||
*
|
||||
* At decode the cost is launch count: `gemm_nt` is the most-dispatched decode kernel, nearly
|
||||
* all fixed cost, across three small per-layer projections of the same activation (the MoE
|
||||
* router, the shared expert's gate on rank 0 only, and this a|b). Merging them would need
|
||||
* contiguous weights (a re-convert) or a grouped gemm_nt over a weight-pointer table, as
|
||||
* moe_gemm_q does. */
|
||||
op_ab = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", ab_dim),
|
||||
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_ab)), {w.h.x}, {w.ab});
|
||||
|
||||
/* ---- the chunked path. As in the bf16 block, except `a` and `b_gate` are views of `ab`. */
|
||||
op_conv_prep = rw(b, RAD_OP(b, "gdn_conv_prep",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_k", cfg.head_k),
|
||||
RAD_INT("head_v", cfg.head_v), RAD_INT("chunk", cfg.chunk),
|
||||
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});
|
||||
/* `state_form`: anchor when speculating, else per_candidate (rad_block_gdn.h explains). */
|
||||
op_recur = rw(b, RAD_OP(b, "gdn_recurrent_update",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_k", cfg.head_k),
|
||||
RAD_INT("head_v", cfg.head_v),
|
||||
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 (int8 when ActFP8::q8_fed; the codes
|
||||
* dtype picks the quantiser). A bf16 out-projection reads only `o.x` and these stay absent. */
|
||||
if (op_recur && w.o.cq()) {
|
||||
const rad_buf oq[2] = { w.o.cq(), w.o.cs() };
|
||||
RAD_ARCH_TRY(rad_op_writes(b, op_recur, oq, 2));
|
||||
}
|
||||
/* The conv + recurrent fold. Its window is a register preload, so the band stops at eight
|
||||
* tokens per sequence. Optional (no RAD_ARCH_TRY): without it the pair runs. */
|
||||
{
|
||||
const int64_t hi = g.max_tok < 8 ? g.max_tok : 8;
|
||||
op_cr = rw(b, RAD_OP(b, "gdn_conv_recurrent_update",
|
||||
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, 0, {},
|
||||
cfg.uneven() ? cfg.v_first * cfg.head_v : 0,
|
||||
cfg.uneven() ? cfg.v_first * cfg.head_v + v_dim : 0));
|
||||
|
||||
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});
|
||||
/* The same collective for a caller that runs it beside other work (issue_ar, a pipelined
|
||||
* prefill): at `overlap` 1 it gets the rows that hold fewer CUs while waiting on the link. */
|
||||
if (g.world > 1 && ar_overlap > 0)
|
||||
op_ar_ov = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes),
|
||||
RAD_INT("overlap", ar_overlap)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h.x}, {w.h.x});
|
||||
/* Only when the next block's norm will not add (rad_fp8.h: NormQuantFP8). */
|
||||
if (add_out)
|
||||
op_add = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
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, bool own_ar,
|
||||
ArPieces* pieces) const {
|
||||
const RadKVGroupBatch* st = kv_batch(batch, kv_state);
|
||||
const RadKVGroupBatch* cv = kv_batch(batch, kv_conv);
|
||||
const int32_t* st_idx = st ? st->state_index : nullptr;
|
||||
/* Slots per state_index row: the state, plus scratch when a kernel serving speculation asks
|
||||
* for it (RadKVGroupBatch). Passed through unread. */
|
||||
const int64_t st_w = st && st->state_index_pitch > 0 ? st->state_index_pitch : 1;
|
||||
const int32_t* cv_idx = cv ? cv->state_index : nullptr;
|
||||
|
||||
const int64_t T = batch->n_tok;
|
||||
const int64_t S = batch->n_seq;
|
||||
const int64_t H = cfg.n_head_v;
|
||||
/* The two parts of `w.in.x`: the convolution's [q|k|v], then the output gate. */
|
||||
const int64_t conv_dim = cfg.conv_dim();
|
||||
const int64_t v_dim = cfg.v_dim();
|
||||
|
||||
/* One prefill sequence in two pieces (ArPieces::cu): the whole block a piece at a time, each
|
||||
* piece the chunk a span of 1 makes (the projection over its rows; the convolution, solve and
|
||||
* scan over its bounds, with the state handed on through the cache; the gated norm, quantiser
|
||||
* and out projection), so the first piece's reduction runs beside all of the second piece's
|
||||
* work. The second piece reads the history the first left in the convolution slot: a spanned
|
||||
* step is past the prompt's first interval, so its context length is never zero. */
|
||||
if (!own_ar && pieces && pieces->cu && pieces->cuts(T) && T <= 2 * pieces->rows && ext_in &&
|
||||
!op_add && S == 1 && batch->phase == RAD_PHASE_PREFILL) {
|
||||
const int64_t in_w = conv_dim + v_dim;
|
||||
for (int64_t p = 0; p < 2; ++p) {
|
||||
const int64_t r0 = p * pieces->rows;
|
||||
const int64_t n = p == 0 ? pieces->rows : T - pieces->rows;
|
||||
const int32_t* cu = pieces->cu + p;
|
||||
in.step(c, w.h, w.in.x, T, r0, n);
|
||||
RAD_ISSUE_N(c, op_ab, n, brow_slice(w.h.x, r0, n, g.n_embd), RAD_W(w_ab),
|
||||
brow_slice(w.ab, r0, n, 2 * H));
|
||||
RAD_ISSUE_N(c, op_conv_prep, n,
|
||||
bcol(w.in.x, 0, conv_dim, T), RAD_W(w_conv), RAD_NONE, RAD_W(w_a_log),
|
||||
RAD_W(w_dt_bias), kv_cache(kv_conv, layer), praw(cu, RAD_I32, 2),
|
||||
bcol(w.ab, 0, H, T), bcol(w.ab, H, H, T),
|
||||
praw(cv_idx, RAD_I32, 1), praw(batch->ctx_lens, RAD_I32, 1),
|
||||
brows(w.q, T), brows(w.k, T), brows(w.v, T),
|
||||
brows(w.gdec, T), brows(w.beta, T));
|
||||
RAD_ISSUE_N(c, op_kkt, n,
|
||||
brows(w.k, T), brows(w.beta, T), brows(w.gdec, T),
|
||||
praw(cu, RAD_I32, 2), brows(w.kkt, T));
|
||||
RAD_ISSUE_N(c, op_scan, n,
|
||||
brows(w.q, T), brows(w.k, T), brows(w.v, T), brows(w.kkt, T),
|
||||
brows(w.gdec, T), brows(w.beta, T),
|
||||
kv_cache(kv_state, layer), praw(cu, RAD_I32, 2),
|
||||
brows(w.o.x, T), kv_cache(kv_state, layer),
|
||||
praw2(st_idx, RAD_I32, 1, st_w));
|
||||
RAD_ISSUE_N(c, op_gnorm, n,
|
||||
brow_slice(w.o.x, r0, n, v_dim),
|
||||
bcol_at(w.in.x, r0, in_w, conv_dim, v_dim, n),
|
||||
RAD_W(w_out_norm), brow_slice(w.o.x, r0, n, v_dim));
|
||||
q_o.step(c, T, r0, n);
|
||||
out.step(c, w.o, w.h.x, T, r0, n);
|
||||
if (p == 0) pieces->hand(r0, n);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!ext_in) nq_h.step(c, T);
|
||||
in.step(c, w.h, w.in.x, T);
|
||||
RAD_ISSUE_N(c, op_ab, T, brows(w.h.x, T), RAD_W(w_ab), brows(w.ab, T));
|
||||
|
||||
/* Each path runs over its own run of sequences. The step is sorted decode-first: decode rows
|
||||
* are sequences [0, D) with tokens [0, DT), prefill chunks are [D, S) with the rest. A pure
|
||||
* step issues one path.
|
||||
*
|
||||
* Per-sequence arrays are offset, token operands are not. Every kernel here derives its grid
|
||||
* and rows from cu_seqlens (N = len(cu) - 1, a sequence's first row is the absolute cu[n]), so
|
||||
* the prefill half gets `cu + D` with q, k, v at their base; offsetting those too would count
|
||||
* the displacement twice. The decode half is the prefix: cu ends at DT and its token operands
|
||||
* are cut to DT rows. The gated norm and the standalone quantiser take no cu and are per
|
||||
* token, so they take row slices at DT.
|
||||
*
|
||||
* This keeps decode-only sequences in a mixed step off the chunked path, which commits state
|
||||
* directly and has no num_accepted, so drafts verified there could not be rolled back. */
|
||||
int64_t D = 0, DT = 0;
|
||||
batch_split(batch, &D, &DT);
|
||||
/* The decode half's band. In a mixed step max_q_len is the prefill chunk's; in a pure decode
|
||||
* step it is already right, so a batch leaving max_q_len_decode zero still works there. */
|
||||
const int32_t qd = batch->phase == RAD_PHASE_MIXED ? batch->max_q_len_decode : batch->max_q_len;
|
||||
const int64_t P = S - D;
|
||||
const int64_t PT = T - DT;
|
||||
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);
|
||||
}
|
||||
|
||||
/* The output a piece at a time where the caller takes the all-reduce that way (ArPieces): the
|
||||
* gated norm, quantiser and out projection are per row, so a pure prefill step can finish them
|
||||
* a piece at a time and hand off each piece's reduction behind it. */
|
||||
const bool cut = !own_ar && pieces && pieces->cuts(T) && D == 0 && P > 0 && !op_add;
|
||||
if (P > 0) {
|
||||
RAD_ISSUE(c, op_conv_prep,
|
||||
bcol(w.in.x, 0, conv_dim, T), RAD_W(w_conv), RAD_NONE, RAD_W(w_a_log), RAD_W(w_dt_bias),
|
||||
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));
|
||||
if (cut) {
|
||||
for (int64_t r0 = 0; r0 < T; r0 += pieces->rows) {
|
||||
const int64_t n = T - r0 < pieces->rows ? T - r0 : pieces->rows;
|
||||
RAD_ISSUE_N(c, op_gnorm, n,
|
||||
brow_slice(w.o.x, r0, n, v_dim),
|
||||
bcol_at(w.in.x, r0, in_w, conv_dim, v_dim, n),
|
||||
RAD_W(w_out_norm), brow_slice(w.o.x, r0, n, v_dim));
|
||||
q_o.step(c, T, r0, n);
|
||||
out.step(c, w.o, w.h.x, T, r0, n);
|
||||
if (r0 + n < T) pieces->hand(r0, n);
|
||||
}
|
||||
return;
|
||||
}
|
||||
/* Per token, so a row slice over the prefill rows only; the recurrent kernel already
|
||||
* gated the decode rows. */
|
||||
RAD_ISSUE_N(c, op_gnorm, PT,
|
||||
brow_slice(w.o.x, DT, PT, v_dim),
|
||||
bcol_at(w.in.x, DT, in_w, conv_dim, v_dim, PT),
|
||||
RAD_W(w_out_norm), brow_slice(w.o.x, DT, PT, v_dim));
|
||||
/* Only the prefill rows are quantised here; the decode kernel quantises in its epilogue.
|
||||
* The chunked scan cannot: its workgroup is a chunk, not a row, so it cannot reduce a
|
||||
* row group's amax. */
|
||||
q_o.step(c, T, DT, PT);
|
||||
}
|
||||
|
||||
out.step(c, w.o, w.h.x, T);
|
||||
if (own_ar && op_ar && !ar_taken(g, T, ar_out, ar_out_take))
|
||||
RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h.x, T), RAD_NONE);
|
||||
if (op_add) RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h.x, T), brows(w.x, T));
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_GDN_FP8_H */
|
||||
@@ -0,0 +1,334 @@
|
||||
/* rad_block_gemma4_vision.h -- Gemma 4's vision tower (transformers' Gemma4VisionModel), served by
|
||||
* gemma4_bf16 (the 31B's tower: 27 layers of width 1152) and embgemma2 (16 layers of width 768).
|
||||
*
|
||||
* a patch is 16 x 16 x 3, staged by the core's Gemma 4 processor as 2 * (u / 255) - 1 in bf16,
|
||||
* (y, x, channel); patch embedding a [width, 768] linear plus a learned row for the patch's
|
||||
* column and one for its row (a [2, npos, width] table), the two summed first
|
||||
* layers: sandwich norms (gain w, not 1 + w), q/k RMS-normed with a gain and v without one, a
|
||||
* 2-D rotary over two neox blocks of a head -- x (the column) over the first, y over the second,
|
||||
* each block at theta^(-j / (hd / 4)) (rope_type "default"; EmbeddingGemma 2 spells the same
|
||||
* rotary "axial") -- bidirectional attention within an image at scale 1, a gated gelu-tanh MLP
|
||||
* pooling: the mean of each pool x pool window times sqrt(width) (the processor lays a window's
|
||||
* patches out consecutively, raster order of windows, as the reference's position pooling)
|
||||
* standardisation (vision_config.standardize), when set: (z - std_bias) * std_scale per channel.
|
||||
* The reference does it in f32 because a few channels carry ~5e4 with a bias that cancels them;
|
||||
* here z is the pooler's bf16 row, so those channels keep bf16's spacing at that magnitude
|
||||
* (about 1e-2 after the scale). The bias row is made on the card: fill(-1) times std_bias, added
|
||||
* to z, then times std_scale.
|
||||
* the multimodal embedder: an RMS norm with no gain and a width -> n_embd linear. Its rows
|
||||
* replace the image's placeholder embeddings (which the text model scales by sqrt(n_embd); the
|
||||
* image rows are not scaled).
|
||||
*
|
||||
* One encoder pass carries RadBuildCtx::max_enc_patches patches over any number of segments (an
|
||||
* image, or one frame of a video). Every rank runs the whole tower (engine_mm.cpp), so its weights
|
||||
* are replicated (RAD_SHARD_NONE) and each rank writes the rows into its own copy of the embedding
|
||||
* stream. */
|
||||
#ifndef RAD_BLOCK_GEMMA4_VISION_H
|
||||
#define RAD_BLOCK_GEMMA4_VISION_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct Gemma4Vision {
|
||||
struct Layer {
|
||||
rad_weight in_norm = 0, qkv = 0, q_norm = 0, k_norm = 0, o = 0, post_attn = 0;
|
||||
rad_weight pre_ff = 0, gate_up = 0, down = 0, post_ff = 0;
|
||||
rad_op op_in = 0, op_qkv = 0, op_qk = 0, op_attn = 0, op_o = 0, op_pa = 0, op_add1 = 0;
|
||||
rad_op op_pf = 0, op_gu = 0, op_act = 0, op_down = 0, op_pff = 0, op_add2 = 0;
|
||||
};
|
||||
bool on = false, standardize = false;
|
||||
int64_t P = 0, R = 0, width = 0, heads = 0, hd = 0, ff = 0, patch_dim = 0, pool = 0;
|
||||
int64_t npos = 0, n_embd = 0;
|
||||
rad_weight w_in = 0, w_px = 0, w_py = 0, w_proj = 0, w_sbias = 0, w_sscale = 0;
|
||||
rad_op op_patch = 0, op_px = 0, op_py = 0, op_padd = 0, op_add = 0, op_pool = 0, op_norm = 0;
|
||||
rad_op op_out = 0, op_sfill = 0, op_sbias = 0, op_sadd = 0, op_sscale = 0;
|
||||
rad_buf b_x = 0, b_h = 0, b_o = 0, b_qkv = 0, b_att = 0, b_gu = 0, b_ff = 0, b_px = 0,
|
||||
b_py = 0, b_pool = 0, b_sb = 0, b_pn = 0, b_out = 0;
|
||||
std::vector<Layer> L;
|
||||
|
||||
static bool present(const RadModelMeta* m) {
|
||||
const char* t = rad_meta_gets(m, "vision_config.model_type", "");
|
||||
return t && !std::strcmp(t, "gemma4_vision");
|
||||
}
|
||||
|
||||
/* `pre` is the checkpoint prefix of the tower and its embedder ("model." for Gemma 4's
|
||||
* conditional-generation checkpoints, "" for EmbeddingGemma 2); `who` names the plugin in
|
||||
* refusals. The tower's layers take weight groups from `first_group`. */
|
||||
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
|
||||
int64_t model_embd, int first_group, const char* pre, const char* who) {
|
||||
on = false;
|
||||
if (!present(m) || ctx->max_enc_patches <= 0) return RAD_OK;
|
||||
width = rad_meta_geti(m, "vision_config.hidden_size", 0);
|
||||
heads = rad_meta_geti(m, "vision_config.num_attention_heads", 0);
|
||||
hd = rad_meta_geti(m, "vision_config.head_dim", 0);
|
||||
ff = rad_meta_geti(m, "vision_config.intermediate_size", 0);
|
||||
pool = rad_meta_geti(m, "vision_config.pooling_kernel_size", 0);
|
||||
npos = rad_meta_geti(m, "vision_config.position_embedding_size", 0);
|
||||
const int64_t depth = rad_meta_geti(m, "vision_config.num_hidden_layers", 0);
|
||||
const int64_t patch = rad_meta_geti(m, "vision_config.patch_size", 0);
|
||||
const int64_t kvh = rad_meta_geti(m, "vision_config.num_key_value_heads", heads);
|
||||
const double eps = rad_meta_getf(m, "vision_config.rms_norm_eps", 1e-6);
|
||||
const double theta = rad_meta_getf(m, "vision_config.rope_parameters.rope_theta", 0.0);
|
||||
const char* rt = rad_meta_gets(m, "vision_config.rope_parameters.rope_type", "");
|
||||
const char* act = rad_meta_gets(m, "vision_config.hidden_activation", "");
|
||||
standardize = rad_meta_geti(m, "vision_config.standardize", 0) != 0;
|
||||
if (width <= 0 || heads <= 0 || hd <= 0 || ff <= 0 || pool <= 0 || npos <= 0 ||
|
||||
depth <= 0 || patch <= 0 || !(theta > 0) || heads * hd != width || kvh != heads ||
|
||||
hd % 4) {
|
||||
fprintf(stderr, "radiance: %s: the container's vision_config is incomplete or not the "
|
||||
"shape this tower serves (hidden %lld, heads %lld x %lld, kv %lld, ff "
|
||||
"%lld, pooling %lld, layers %lld)\n", who, (long long)width,
|
||||
(long long)heads, (long long)hd, (long long)kvh, (long long)ff,
|
||||
(long long)pool, (long long)depth);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* Clipped linears (their bounds are buffers the vision checkpoint states as infinite) and
|
||||
* any rotary or activation other than the 2-D one and gelu-tanh are refused by name. */
|
||||
if (rad_meta_geti(m, "vision_config.use_clipped_linears", 0) ||
|
||||
(std::strcmp(rt, "default") && std::strcmp(rt, "axial")) ||
|
||||
std::strcmp(act, "gelu_pytorch_tanh")) {
|
||||
fprintf(stderr, "radiance: %s: this vision tower uses clipped linears, a '%s' rotary or "
|
||||
"a '%s' activation, which it does not serve\n", who, rt, act);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
n_embd = model_embd;
|
||||
patch_dim = 3 * patch * patch;
|
||||
const int64_t kk = pool * pool;
|
||||
P = ctx->max_enc_patches;
|
||||
if (P % kk) P -= P % kk;
|
||||
R = P / kk;
|
||||
const int A = RAD_ACCESS_PER_REQUEST, N = RAD_SHARD_NONE;
|
||||
char V[64];
|
||||
std::snprintf(V, sizeof V, "%svision_tower", pre);
|
||||
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("v.patch.weight"), nm.ckpt("%s.patch_embedder.input_proj.weight", V)));
|
||||
RAD_ARCH_TRY(map_slice(b, nm.f("v.pos_x.weight"),
|
||||
nm.ckpt("%s.patch_embedder.position_embedding_table", V), 0));
|
||||
RAD_ARCH_TRY(map_slice(b, nm.f("v.pos_y.weight"),
|
||||
nm.ckpt("%s.patch_embedder.position_embedding_table", V), 1));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("v.embed.weight"), nm.ckpt("%sembed_vision.embedding_projection.weight", pre)));
|
||||
w_in = decl_w(b, nm.f("v.patch.weight"), RAD_BF16, {width, patch_dim}, A, N, grp_model());
|
||||
w_px = decl_w(b, nm.f("v.pos_x.weight"), RAD_BF16, {npos, width}, A, N, grp_model());
|
||||
w_py = decl_w(b, nm.f("v.pos_y.weight"), RAD_BF16, {npos, width}, A, N, grp_model());
|
||||
w_proj = decl_w(b, nm.f("v.embed.weight"), RAD_BF16, {n_embd, width}, A, N, grp_model());
|
||||
if (standardize) {
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("v.std_bias"), nm.ckpt("%s.std_bias", V)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("v.std_scale"), nm.ckpt("%s.std_scale", V)));
|
||||
w_sbias = decl_w(b, nm.f("v.std_bias"), RAD_BF16, {width}, A, N, grp_model());
|
||||
w_sscale = decl_w(b, nm.f("v.std_scale"), RAD_BF16, {width}, A, N, grp_model());
|
||||
}
|
||||
L.assign((size_t)depth, Layer{});
|
||||
for (int64_t i = 0; i < depth; ++i) {
|
||||
Layer& l = L[(size_t)i];
|
||||
const long long li = (long long)i;
|
||||
const RadWeightGroup g = grp_layer(first_group + (int)i);
|
||||
auto src = [&](const char* s) { return nm.ckpt("%s.encoder.layers.%lld.%s", V, li, s); };
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.in_norm", li), src("input_layernorm.weight")));
|
||||
RAD_ARCH_TRY(map_concat(b, nm.f("v.blk.%lld.qkv", li),
|
||||
{src("self_attn.q_proj.linear.weight"),
|
||||
src("self_attn.k_proj.linear.weight"),
|
||||
src("self_attn.v_proj.linear.weight")}));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.q_norm", li), src("self_attn.q_norm.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.k_norm", li), src("self_attn.k_norm.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.o", li), src("self_attn.o_proj.linear.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.post_attn", li), src("post_attention_layernorm.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.pre_ff", li), src("pre_feedforward_layernorm.weight")));
|
||||
RAD_ARCH_TRY(map_concat(b, nm.f("v.blk.%lld.gate_up", li),
|
||||
{src("mlp.gate_proj.linear.weight"),
|
||||
src("mlp.up_proj.linear.weight")}));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.down", li), src("mlp.down_proj.linear.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.post_ff", li), src("post_feedforward_layernorm.weight")));
|
||||
l.in_norm = decl_w(b, nm.f("v.blk.%lld.in_norm", li), RAD_BF16, {width}, A, N, g);
|
||||
l.qkv = decl_w(b, nm.f("v.blk.%lld.qkv", li), RAD_BF16, {3 * width, width}, A, N, g);
|
||||
l.q_norm = decl_w(b, nm.f("v.blk.%lld.q_norm", li), RAD_BF16, {hd}, A, N, g);
|
||||
l.k_norm = decl_w(b, nm.f("v.blk.%lld.k_norm", li), RAD_BF16, {hd}, A, N, g);
|
||||
l.o = decl_w(b, nm.f("v.blk.%lld.o", li), RAD_BF16, {width, width}, A, N, g);
|
||||
l.post_attn = decl_w(b, nm.f("v.blk.%lld.post_attn", li), RAD_BF16, {width}, A, N, g);
|
||||
l.pre_ff = decl_w(b, nm.f("v.blk.%lld.pre_ff", li), RAD_BF16, {width}, A, N, g);
|
||||
l.gate_up = decl_w(b, nm.f("v.blk.%lld.gate_up", li), RAD_BF16, {2 * ff, width}, A, N, g);
|
||||
l.down = decl_w(b, nm.f("v.blk.%lld.down", li), RAD_BF16, {width, ff}, A, N, g);
|
||||
l.post_ff = decl_w(b, nm.f("v.blk.%lld.post_ff", li), RAD_BF16, {width}, A, N, g);
|
||||
}
|
||||
|
||||
b_x = decl_b(b, nm.f("v.x"), RAD_BF16, {P, width});
|
||||
b_h = decl_b(b, nm.f("v.h"), RAD_BF16, {P, width});
|
||||
b_o = decl_b(b, nm.f("v.o"), RAD_BF16, {P, width});
|
||||
b_qkv = decl_b(b, nm.f("v.qkv"), RAD_BF16, {P, 3 * width});
|
||||
b_att = decl_b(b, nm.f("v.att"), RAD_BF16, {P, width});
|
||||
b_gu = decl_b(b, nm.f("v.gu"), RAD_BF16, {P, 2 * ff});
|
||||
b_ff = decl_b(b, nm.f("v.ff"), RAD_BF16, {P, ff});
|
||||
b_px = decl_b(b, nm.f("v.px"), RAD_BF16, {P, width});
|
||||
b_py = decl_b(b, nm.f("v.py"), RAD_BF16, {P, width});
|
||||
b_pool = decl_b(b, nm.f("v.pool"), RAD_BF16, {R, width});
|
||||
b_sb = decl_b(b, nm.f("v.sb"), RAD_BF16, {R, width});
|
||||
b_pn = decl_b(b, nm.f("v.pn"), RAD_BF16, {R, width});
|
||||
b_out = decl_b(b, nm.f("v.out"), RAD_BF16, {R, n_embd});
|
||||
|
||||
auto rms = [&](int64_t rows, rad_weight w) {
|
||||
if (!w)
|
||||
return RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width),
|
||||
RAD_F64("eps", eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
return RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width),
|
||||
RAD_F64("eps", eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w));
|
||||
};
|
||||
auto gemm = [&](int64_t rows, int64_t Nn, int64_t K, rad_weight w) {
|
||||
return RAD_OP(b, "gemm_nt", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", Nn),
|
||||
RAD_INT("K", K), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w));
|
||||
};
|
||||
auto add = [&](int64_t rows) {
|
||||
return RAD_OP(b, "add", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
auto lookup = [&](rad_weight w) {
|
||||
return RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n_embd", width),
|
||||
RAD_INT("n_vocab", npos), RAD_STR("dtype", "bf16"),
|
||||
RAD_INT("vocab_offset", 0), RAD_F64("mult", 1.0)),
|
||||
RAD_WEIGHTS(w));
|
||||
};
|
||||
auto gain = [&](rad_weight w) {
|
||||
return RAD_OP(b, "mul_weight", RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", width),
|
||||
RAD_STR("dtype", "bf16"), RAD_INT("scalar", 0)),
|
||||
RAD_WEIGHTS(w));
|
||||
};
|
||||
op_patch = rw(b, gemm(P, width, patch_dim, w_in), {}, {b_x});
|
||||
op_px = rw(b, lookup(w_px), {}, {b_px});
|
||||
op_py = rw(b, lookup(w_py), {}, {b_py});
|
||||
op_padd = rw(b, add(P), {b_px, b_py}, {b_px});
|
||||
op_add = rw(b, add(P), {b_x, b_px}, {b_x});
|
||||
/* Two neox blocks of hd / 4 pairs, x (staged plane 1, the column) then y (plane 0). */
|
||||
char sec[48];
|
||||
std::snprintf(sec, sizeof sec, "%lld %lld", (long long)(hd / 4), (long long)(hd / 4));
|
||||
for (Layer& l : L) {
|
||||
l.op_in = rw(b, rms(P, l.in_norm), {b_x}, {b_h});
|
||||
l.op_qkv = rw(b, gemm(P, 3 * width, width, l.qkv), {b_h}, {b_qkv});
|
||||
l.op_qk = rw(b, RAD_OP(b, "qk_norm_rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", hd),
|
||||
RAD_INT("n_head", heads), RAD_INT("n_head_kv", heads),
|
||||
RAD_F64("theta", theta), RAD_F64("eps", eps),
|
||||
RAD_STR("mode", "blocks"), RAD_INT("v_norm", 1),
|
||||
RAD_STR("sections", sec), RAD_STR("comps", "1 0")),
|
||||
RAD_WEIGHTS(l.q_norm, l.k_norm)),
|
||||
{b_qkv}, {b_qkv});
|
||||
l.op_attn = rw(b, RAD_OP(b, "attn_dense",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", hd),
|
||||
RAD_INT("gqa", 1), RAD_INT("causal", 0),
|
||||
RAD_STR("dtype", "bf16"), RAD_F64("scale", 1.0),
|
||||
RAD_INT("max_seqlen", P), RAD_INT("window", 0)),
|
||||
RAD_NOWEIGHTS),
|
||||
{b_qkv}, {b_att});
|
||||
l.op_o = rw(b, gemm(P, width, width, l.o), {b_att}, {b_o});
|
||||
l.op_pa = rw(b, rms(P, l.post_attn), {b_o}, {b_o});
|
||||
l.op_add1 = rw(b, add(P), {b_x, b_o}, {b_x});
|
||||
l.op_pf = rw(b, rms(P, l.pre_ff), {b_x}, {b_h});
|
||||
l.op_gu = rw(b, gemm(P, 2 * ff, width, l.gate_up), {b_h}, {b_gu});
|
||||
l.op_act = rw(b, RAD_OP(b, "act_mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", ff),
|
||||
RAD_STR("act", "gelu_tanh"), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{b_gu}, {b_ff});
|
||||
l.op_down = rw(b, gemm(P, width, ff, l.down), {b_ff}, {b_o});
|
||||
l.op_pff = rw(b, rms(P, l.post_ff), {b_o}, {b_o});
|
||||
l.op_add2 = rw(b, add(P), {b_x, b_o}, {b_x});
|
||||
}
|
||||
op_pool = rw(b, RAD_OP(b, "pool_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
|
||||
RAD_INT("k", kk), RAD_F64("mult", std::sqrt((double)width)),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{b_x}, {b_pool});
|
||||
if (standardize) {
|
||||
op_sfill = rw(b, RAD_OP(b, "fill",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", width),
|
||||
RAD_STR("dtype", "bf16"), RAD_F64("value", -1.0)),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, {b_sb});
|
||||
op_sbias = rw(b, gain(w_sbias), {b_sb}, {b_sb});
|
||||
op_sadd = rw(b, add(R), {b_pool, b_sb}, {b_pool});
|
||||
op_sscale = rw(b, gain(w_sscale), {b_pool}, {b_pool});
|
||||
}
|
||||
op_norm = rw(b, rms(R, 0), {b_pool}, {b_pn});
|
||||
op_out = rw(b, gemm(R, n_embd, width, w_proj), {b_pn}, {b_out});
|
||||
|
||||
RadEncoderDecl e{};
|
||||
e.name = "vision";
|
||||
e.modalities = RAD_MM_IMAGE | RAD_MM_VIDEO;
|
||||
e.patch_dim = patch_dim;
|
||||
e.merge = kk;
|
||||
e.max_patches = P;
|
||||
e.n_embd = n_embd;
|
||||
e.out = b_out;
|
||||
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
|
||||
rad_note(b, "vision tower: %lld layers of %lld (%lld heads x %lld), ff %lld, patch %lld, "
|
||||
"pooled %lldx%lld%s; %lld patches a pass -> %lld rows of %lld",
|
||||
(long long)depth, (long long)width, (long long)heads, (long long)hd, (long long)ff,
|
||||
(long long)patch, (long long)pool, (long long)pool,
|
||||
standardize ? ", standardised" : "", (long long)P, (long long)R,
|
||||
(long long)n_embd);
|
||||
on = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t Pn = batch->enc_n_patch, S = batch->enc_n_seg, kk = pool * pool;
|
||||
if (!on || Pn <= 0 || Pn > P || Pn % kk || S <= 0) {
|
||||
rad_step_fail(c, "an encoder pass this program's vision tower cannot serve: no tower, "
|
||||
"more patches than it was declared for, or not whole pooling windows");
|
||||
return;
|
||||
}
|
||||
const int64_t Rn = Pn / kk;
|
||||
const int32_t* crd = batch->enc_coord;
|
||||
const RadOperand pix = praw2(batch->enc_pixels, RAD_BF16, Pn, patch_dim);
|
||||
const RadOperand rc = praw2(crd, RAD_I32, 2, Pn);
|
||||
const RadOperand cu = praw(batch->enc_cu, RAD_I32, S + 1);
|
||||
|
||||
RAD_ISSUE_N(c, op_patch, Pn, pix, RAD_W(w_in), brows(b_x, Pn));
|
||||
RAD_ISSUE_N(c, op_px, Pn, praw(crd + Pn, RAD_I32, Pn), RAD_W(w_px), brows(b_px, Pn));
|
||||
RAD_ISSUE_N(c, op_py, Pn, praw(crd, RAD_I32, Pn), RAD_W(w_py), brows(b_py, Pn));
|
||||
RAD_ISSUE_N(c, op_padd, Pn, brows(b_px, Pn), brows(b_py, Pn), brows(b_px, Pn));
|
||||
RAD_ISSUE_N(c, op_add, Pn, brows(b_x, Pn), brows(b_px, Pn), brows(b_x, Pn));
|
||||
for (const Layer& l : L) {
|
||||
RAD_ISSUE_N(c, l.op_in, Pn, brows(b_x, Pn), RAD_W(l.in_norm), brows(b_h, Pn));
|
||||
RAD_ISSUE_N(c, l.op_qkv, Pn, brows(b_h, Pn), RAD_W(l.qkv), brows(b_qkv, Pn));
|
||||
RAD_ISSUE_N(c, l.op_qk, Pn, brows(b_qkv, Pn), rc, RAD_W(l.q_norm), RAD_W(l.k_norm));
|
||||
RAD_ISSUE_N(c, l.op_attn, Pn, bcol(b_qkv, 0, width, Pn), bcol(b_qkv, width, width, Pn),
|
||||
bcol(b_qkv, 2 * width, width, Pn), cu, brows(b_att, Pn));
|
||||
RAD_ISSUE_N(c, l.op_o, Pn, brows(b_att, Pn), RAD_W(l.o), brows(b_o, Pn));
|
||||
RAD_ISSUE_N(c, l.op_pa, Pn, brows(b_o, Pn), RAD_W(l.post_attn), brows(b_o, Pn));
|
||||
RAD_ISSUE_N(c, l.op_add1, Pn, brows(b_x, Pn), brows(b_o, Pn), brows(b_x, Pn));
|
||||
RAD_ISSUE_N(c, l.op_pf, Pn, brows(b_x, Pn), RAD_W(l.pre_ff), brows(b_h, Pn));
|
||||
RAD_ISSUE_N(c, l.op_gu, Pn, brows(b_h, Pn), RAD_W(l.gate_up), brows(b_gu, Pn));
|
||||
RAD_ISSUE_N(c, l.op_act, Pn, bcol(b_gu, 0, ff, Pn), bcol(b_gu, ff, ff, Pn),
|
||||
brows(b_ff, Pn));
|
||||
RAD_ISSUE_N(c, l.op_down, Pn, brows(b_ff, Pn), RAD_W(l.down), brows(b_o, Pn));
|
||||
RAD_ISSUE_N(c, l.op_pff, Pn, brows(b_o, Pn), RAD_W(l.post_ff), brows(b_o, Pn));
|
||||
RAD_ISSUE_N(c, l.op_add2, Pn, brows(b_x, Pn), brows(b_o, Pn), brows(b_x, Pn));
|
||||
}
|
||||
RAD_ISSUE_N(c, op_pool, Pn, brows(b_x, Pn), brows(b_pool, Rn));
|
||||
if (standardize) {
|
||||
RAD_ISSUE_N(c, op_sfill, Rn, brows(b_sb, Rn));
|
||||
RAD_ISSUE_N(c, op_sbias, Rn, brows(b_sb, Rn), RAD_W(w_sbias), brows(b_sb, Rn));
|
||||
RAD_ISSUE_N(c, op_sadd, Rn, brows(b_pool, Rn), brows(b_sb, Rn), brows(b_pool, Rn));
|
||||
RAD_ISSUE_N(c, op_sscale, Rn, brows(b_pool, Rn), RAD_W(w_sscale), brows(b_pool, Rn));
|
||||
}
|
||||
RAD_ISSUE_N(c, op_norm, Rn, brows(b_pool, Rn), RAD_NONE, brows(b_pn, Rn));
|
||||
RAD_ISSUE_N(c, op_out, Rn, brows(b_pn, Rn), RAD_W(w_proj), brows(b_out, Rn));
|
||||
}
|
||||
};
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_GEMMA4_VISION_H */
|
||||
@@ -0,0 +1,396 @@
|
||||
/* rad_block_hc.h -- the gated residual (hyper-connection) Qwen4-Exp uses instead of a pre-norm
|
||||
* and a residual add.
|
||||
*
|
||||
* ============================== THE RESIDUAL STREAM IS `hc` TIMES AS WIDE ==============================
|
||||
*
|
||||
* hidden_size 2560 at hc_count 4 gives a 10240-wide stream, entered as four identical copies of
|
||||
* the embedding, carried through all 48 layers, and collapsed at the end by a connection with no
|
||||
* write half. Each of the 96 blocks (attention or delta net, then feed-forward) reads a 2560 mix
|
||||
* of the four streams and writes its output back into all four; both halves are data-dependent:
|
||||
*
|
||||
* read N = grouped_rmsnorm(h) one rsqrt per 2560 stream, one 10240 gain, `1 + w`
|
||||
* g = sigmoid(mix_up @ silu(mix_down @ N / hc))
|
||||
* 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 state the same and name what a second implementation
|
||||
* must match: the mix is a mean, each gate argument has its own `/ hc`, and the write adds into
|
||||
* the unnormed stream.
|
||||
*
|
||||
* One struct declares both halves because they share weights and buffers and must pair: each
|
||||
* write consumes the `inj` of its own read.
|
||||
*
|
||||
* Cost: the arithmetic is small (2 x 10240 x 320 + 4 x 10240 = 6.6M MACs per token, about one
|
||||
* expert pair); the cost is launches, 96 connections per step. So the read emits the fp8 form of
|
||||
* `x` itself instead of a following `quant_act_fp8`, and the write could later be folded into the
|
||||
* producing block's epilogue.
|
||||
*
|
||||
* Nothing is sharded: the residual stream is replicated (spec §9), and so are these weights
|
||||
* (6.7 MB per connection at bf16, 1.3 GB over the model). Sharding the low-rank gate would add an
|
||||
* all-reduce between `mix_down` and `mix_up`, 96 more small collectives per step.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_HC_H
|
||||
#define RAD_BLOCK_HC_H
|
||||
|
||||
#include "rad_fp8.h"
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
/* Initialises the wide stream with hc identical copies of the embedding, one launch per step.
|
||||
* Separate from the embedding lookup, whose output width is n_embd. The copies diverge at the
|
||||
* first write, which uses a different gain per stream. */
|
||||
struct HcEnter {
|
||||
Geom g{};
|
||||
int64_t hc = 0;
|
||||
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 the connection has a write half. The final mixer does not: it collapses the
|
||||
* stream into the hidden state the lm_head reads. */
|
||||
int inject = 1;
|
||||
/* Whether the read also emits the block input's fp8 codes. Not for the final mixer, whose
|
||||
* consumer (the lm_head) reads bf16. */
|
||||
int quant = 1;
|
||||
/* Whether the write also performs the all-reduce of the block's output; the block then
|
||||
* skips its own on every step takes_ar() accepts. The block's partial sum is the write's
|
||||
* input buffer, so this saves a launch. */
|
||||
int reduce = 0;
|
||||
/* Whether the read also emits Hadamard-rotated fp8 codes of the block input, for a
|
||||
* consumer whose weight carries the rotation (MoeFP8's rotated expert plane). Produced in
|
||||
* the plain codes' finisher, so requires `quant`; the consumer declares no quantiser. */
|
||||
int rotate = 0;
|
||||
/* Whether the plain codes are int8 (q8/s8) rather than E4M3 (q/s), for int8 trunk linears
|
||||
* (LinearFP8::i8). The rotated codes stay E4M3, the routed experts' operand. */
|
||||
int codes_i8 = 0;
|
||||
/* The most rows one read is declared for, 0 for max_tok; a wider step reads in pieces
|
||||
* (read_pieces). The read's scratch is sized for its band (some 22 KiB a row at
|
||||
* Flash-Next's shape, on every lane with a scratch region), so a model that reads a wider
|
||||
* step in pieces anyway declares the band no wider than a piece. */
|
||||
int64_t read_rows = 0;
|
||||
};
|
||||
|
||||
struct Wire {
|
||||
rad_buf h = 0; /* [max_tok, hc * n_embd] the wide stream, updated in place */
|
||||
ActFP8 x{}; /* [max_tok, n_embd] the block input; q/s unused if !quant */
|
||||
rad_buf inj = 0; /* [max_tok, hc] the per-branch write gains */
|
||||
rad_buf rq = 0; /* [max_tok, n_embd] the rotated codes, when `rotate` */
|
||||
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 mixing matrices are E4M3 rows with a per-group scale rather than bf16 (OPS.md's
|
||||
* `mix`), read from their encoding at declare. */
|
||||
bool mix_e4m3 = false;
|
||||
rad_op op_read = 0, op_write = 0;
|
||||
/* The write with the all-reduce folded in; 0 when not requested or not served.
|
||||
* `op_ar_write6` is the same on the rotated 6-bit wire, declared only when a lossy payload is
|
||||
* accepted and issued on the steps ar_wire_is_exact rejects (every trunk all-reduce at a
|
||||
* prefill chunk); its payload is 2.6x smaller. */
|
||||
rad_op op_ar_write = 0;
|
||||
rad_op op_ar_write6 = 0;
|
||||
/* The same with the MoE gather folded in front: the block leaves its routed experts' rows
|
||||
* unsummed, and the reduction's message is their sum. Declared by declare_gather() after the
|
||||
* block, whose buffers it reads; `gather_rows` is its bound, 0 when not declared or not
|
||||
* served (see gather_taken). */
|
||||
struct GatherSrc {
|
||||
rad_buf ye = 0, ew = 0, sorted = 0, sh = 0, sg = 0; /* sh and sg: the shared arm, or 0 */
|
||||
int64_t top_k = 0;
|
||||
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 for this step's wire, or 0 when that wire has no fused form (then the
|
||||
* block's own collective runs before the plain write). At four ranks there is no rotated
|
||||
* form, so steps ar_exact_write_takes declines get 0. */
|
||||
rad_op ar_write(int64_t T) const {
|
||||
return ar_exact_write_takes(g, T) ? op_ar_write : op_ar_write6;
|
||||
}
|
||||
/* Whether this step's write reduces the block's output. The block asks the same of the same T
|
||||
* (ar_taken with ar_take()) before skipping its own collective. */
|
||||
bool takes_ar(int64_t T) const { return ar_write(T) != 0; }
|
||||
/* Which wires this write takes, for the block. The rotated form exists only beside the exact
|
||||
* one, so together they take every message. */
|
||||
int ar_take() const { return op_ar_write6 ? kArOutBoth : kArOutExact; }
|
||||
bool takes_gather(int64_t T) const {
|
||||
return takes_ar(T) && gather_taken(g, T, gather_rows, gather_rows6);
|
||||
}
|
||||
|
||||
/* `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;
|
||||
/* The read over rows [0, T), in pieces of Config::read_rows where it is set; one read
|
||||
* otherwise. The read's down product splits K by how many row tiles it is handed
|
||||
* (hc_down_kchunk in libr4d), so one read over twice the rows sums in a different order than
|
||||
* two reads over half of them; reading a wide step in pieces computes what the narrower steps
|
||||
* did. */
|
||||
void read_pieces(RadCtx* c_, int64_t T) const {
|
||||
const int64_t piece = c.read_rows;
|
||||
if (piece <= 0 || T <= piece) { read(c_, T, 0, T); return; }
|
||||
for (int64_t r0 = 0; r0 < T; r0 += piece) read(c_, T, r0, T - r0 < piece ? T - r0 : piece);
|
||||
}
|
||||
};
|
||||
|
||||
inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const char* name,
|
||||
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;
|
||||
/* The inject weight and the `inj` buffer must both be present or both absent. */
|
||||
if (c.inject && (!src.inject_w || !w.inj)) {
|
||||
fprintf(stderr, "radiance: %s: inject is on but %s is missing\n", name,
|
||||
src.inject_w ? "the inj buffer" : "block_inject_weight");
|
||||
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();
|
||||
|
||||
/* Maps first: weight encodings are looked up through them. */
|
||||
const char* nn = nm.f("%s_norm.weight", name);
|
||||
const char* dn = nm.f("%s_down.weight", name);
|
||||
const char* un = nm.f("%s_up.weight", name);
|
||||
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 bf16 or E4M3 rows with a per-group scale (lowrank 320 is 2.5 scale
|
||||
* blocks, so 128x128 tiles do not fit). Each is declared over all its planes at the codes'
|
||||
* dtype; both must share one format for the read kernel. */
|
||||
const uint32_t mdt = weight_codes_dtype(b, dn, RAD_BF16);
|
||||
if (weight_codes_dtype(b, un, RAD_BF16) != mdt || (mdt != RAD_BF16 && mdt != RAD_F8E4M3)) {
|
||||
fprintf(stderr, "radiance: %s: the mixing matrices are %s and %s; a connection reads both "
|
||||
"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 norm gain in this tree. */
|
||||
w_norm = decl_w(b, nn, RAD_F32, {HN}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
w_down = decl_w(b, dn, mdt, {c.lowrank, HN}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp_model());
|
||||
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 as 0 when off, not omitted: kernel rows constrain them, and
|
||||
* an absent key fails every constraint.
|
||||
*
|
||||
* RAD_WEIGHTS expands to two arguments, so the weight list is built as an array. A missing
|
||||
* inject weight shortens the list; a zero weight handle would be a declaration failure. */
|
||||
const rad_weight wts[4] = { w_norm, w_down, w_up, w_inj };
|
||||
const int n_wts = c.inject ? 4 : 3;
|
||||
|
||||
/* Outputs are x, inj?, codes?, scales?, rotated pair?. The write set is positional with
|
||||
* optional outputs at the tail, so an absent one shortens the list. */
|
||||
rad_buf wr[6] = { w.x.x, 0, 0, 0, 0, 0 };
|
||||
int n_wr = 1;
|
||||
if (c.inject) wr[n_wr++] = w.inj;
|
||||
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, c.read_rows > 0 && c.read_rows < g.max_tok
|
||||
? c.read_rows : g.max_tok),
|
||||
RAD_INT("n", g.n_embd),
|
||||
RAD_INT("hc", c.hc), RAD_INT("lowrank", c.lowrank),
|
||||
RAD_F64("eps", g.eps), RAD_STR("dtype", g.dtype),
|
||||
RAD_F64("wadd", g.wadd), RAD_INT("inject", c.inject ? 1 : 0),
|
||||
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;
|
||||
/* An unresolved handle is 0, not an error: without the fused kernel the pair runs and
|
||||
* takes_ar() always answers no. At four ranks only the exact form exists, declared over the
|
||||
* decode and verify rows. `wire` 0 is stated, not omitted, because rows constrain it. */
|
||||
const int64_t ar_rows = ar_exact_write_rows(g);
|
||||
if (c.reduce && ar_rows >= 1)
|
||||
op_ar_write = rw(b, RAD_OP(b, "ar_hc_write",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, ar_rows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("hc", c.hc), RAD_INT("world_size", g.world),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("wire", 0)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.x.x, w.inj, w.h}, {w.x.x, w.h});
|
||||
/* The rotated form at two ranks only: there is no four-rank form on that wire
|
||||
* (docs/OPS.md), and an unresolvable op would be reported at startup as an unservable
|
||||
* band. */
|
||||
if (op_ar_write && !g.wire_exact && g.world == 2)
|
||||
op_ar_write6 = rw(b, RAD_OP(b, "ar_hc_write",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("hc", c.hc), RAD_INT("world_size", g.world),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("wire", 6)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.x.x, w.inj, w.h}, {w.x.x, w.h});
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
inline int HyperConn::declare_gather(RadBuilder* b, const GatherSrc& src) {
|
||||
if (!op_ar_write || src.top_k <= 0 || !src.ye || !src.ew || !src.sorted) return RAD_OK;
|
||||
/* Two or four ranks. At four only the exact form exists (op_ar_write6 is 0). Other widths keep
|
||||
* the block's own gather and both bounds stay 0. */
|
||||
if (g.world != 2 && g.world != 4) return RAD_OK;
|
||||
const bool shared = src.sh && src.sg;
|
||||
gsrc = src;
|
||||
/* Up to one pass's rows, capped at the write's own bound (ar_exact_write_rows): prefill chunks
|
||||
* at two ranks, decode and verify steps at four. The kernel reads its slots from an LDS table
|
||||
* at decode and from an inverse table at a chunk. */
|
||||
int64_t rows = src.rows;
|
||||
const int64_t ar_rows = ar_exact_write_rows(g);
|
||||
if (rows > ar_rows) rows = ar_rows;
|
||||
if (rows < 1) return RAD_OK;
|
||||
const rad_buf rd[8] = { src.ye, src.ew, src.sorted, w.x.x, w.inj, w.h, src.sh, src.sg };
|
||||
const rad_buf wr[2] = { w.x.x, w.h };
|
||||
/* One op per wire, the rotated form only beside the rotated write. An unresolved handle is 0:
|
||||
* the block keeps its gather and that wire's bound stays 0. */
|
||||
op_ar_gather_write = RAD_OP(b, "ar_gather_hc_write",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("hc", c.hc), RAD_INT("top_k", src.top_k),
|
||||
RAD_INT("world_size", g.world),
|
||||
RAD_STR("dtype", g.dtype),
|
||||
RAD_STR("act", shared ? "sigmoid" : "none"),
|
||||
RAD_INT("wire", 0)),
|
||||
RAD_NOWEIGHTS);
|
||||
if (op_ar_gather_write) {
|
||||
RAD_ARCH_TRY(rad_op_reads (b, op_ar_gather_write, rd, shared ? 8 : 6));
|
||||
RAD_ARCH_TRY(rad_op_writes(b, op_ar_gather_write, wr, 2));
|
||||
gather_rows = rows;
|
||||
}
|
||||
if (op_ar_write6) {
|
||||
op_ar_gather_write6 = RAD_OP(b, "ar_gather_hc_write",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("hc", c.hc), RAD_INT("top_k", src.top_k),
|
||||
RAD_INT("world_size", g.world),
|
||||
RAD_STR("dtype", g.dtype),
|
||||
RAD_STR("act", shared ? "sigmoid" : "none"),
|
||||
RAD_INT("wire", 6)),
|
||||
RAD_NOWEIGHTS);
|
||||
if (op_ar_gather_write6) {
|
||||
RAD_ARCH_TRY(rad_op_reads (b, op_ar_gather_write6, rd, shared ? 8 : 6));
|
||||
RAD_ARCH_TRY(rad_op_writes(b, op_ar_gather_write6, wr, 2));
|
||||
gather_rows6 = rows;
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
inline void HyperConn::read(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const {
|
||||
(void)T;
|
||||
const int64_t HN = hn();
|
||||
RAD_ISSUE_N(c_, op_read, rows,
|
||||
brow_slice(w.h, r0, rows, HN), RAD_W(w_norm), RAD_W(w_down), RAD_W(w_up),
|
||||
c.inject ? RAD_W(w_inj) : RAD_NONE,
|
||||
brow_slice(w.x.x, r0, rows, g.n_embd),
|
||||
c.inject ? brow_slice(w.inj, r0, rows, c.hc) : RAD_NONE,
|
||||
c.quant ? brow_slice(c.codes_i8 ? w.x.q8 : w.x.q, r0, rows, g.n_embd) : RAD_NONE,
|
||||
c.quant ? brow_slice(c.codes_i8 ? w.x.s8 : w.x.s, r0, rows,
|
||||
fp8_blocks(g.n_embd)) : RAD_NONE,
|
||||
c.rotate ? brow_slice(w.rq, r0, rows, g.n_embd) : RAD_NONE,
|
||||
c.rotate ? brow_slice(w.rs, r0, rows, fp8_blocks(g.n_embd)) : RAD_NONE);
|
||||
}
|
||||
|
||||
/* The block's output `y` is read from `w.x.x`, the buffer the read wrote the block's input to:
|
||||
* every block leaves its delta in the activation its norm produced, and the input is dead by
|
||||
* then. */
|
||||
inline void HyperConn::write(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const {
|
||||
if (!op_write) return;
|
||||
if (takes_gather(T)) {
|
||||
const int64_t k = gsrc.top_k;
|
||||
const bool shared = gsrc.sh && gsrc.sg;
|
||||
const rad_op op = ar_exact_write_takes(g, T) ? op_ar_gather_write : op_ar_gather_write6;
|
||||
RAD_ISSUE_N(c_, op, rows,
|
||||
brows(gsrc.ye, rows * k), brow_slice(gsrc.ew, r0, rows, k),
|
||||
brows(gsrc.sorted, rows * k),
|
||||
shared ? brow_slice(gsrc.sh, r0, rows, g.n_embd) : RAD_NONE,
|
||||
shared ? brow_slice(gsrc.sg, r0, rows, 1) : RAD_NONE,
|
||||
brow_slice(w.x.x, r0, rows, g.n_embd),
|
||||
brow_slice(w.inj, r0, rows, c.hc),
|
||||
brow_slice(w.h, r0, rows, hn()));
|
||||
return;
|
||||
}
|
||||
RAD_ISSUE_N(c_, takes_ar(T) ? ar_write(T) : op_write, rows,
|
||||
brow_slice(w.x.x, r0, rows, g.n_embd),
|
||||
brow_slice(w.inj, r0, rows, c.hc),
|
||||
brow_slice(w.h, r0, rows, hn()));
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_HC_H */
|
||||
@@ -0,0 +1,121 @@
|
||||
/* 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 fused into one weight at convert time (spec §2.4): the map concatenates the
|
||||
* checkpoint's gate and up along dim 0 and silu_mul splits [M, 2n] back into gate * up. One GEMM
|
||||
* launch and one movement unit instead of two.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_MLP_H
|
||||
#define RAD_BLOCK_MLP_H
|
||||
|
||||
#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 supplies them because only it knows both
|
||||
* sides of the map (spec §2.4); spellings differ per checkpoint (`...layers.N.mlp.*`,
|
||||
* `blk.N.ffn_*`). */
|
||||
struct Src {
|
||||
const char* norm = nullptr; /* post_attention_layernorm.weight */
|
||||
const char* gate = nullptr;
|
||||
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 leaves a partial sum on every rank. The plugin emits the
|
||||
* reduction so the graph dump shows it (spec §9). */
|
||||
if (g.world > 1)
|
||||
op_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
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 {
|
||||
/* Operands carry the step's row count, not the buffer's: kernels read extents from the
|
||||
* operands because a ranged parameter is collapsed to a band before issue (rad_arch.h). */
|
||||
const int64_t T = batch->n_tok;
|
||||
RAD_ISSUE(c, op_norm, brows(w.x, T), RAD_W(w_norm), brows(w.h, T));
|
||||
RAD_ISSUE(c, op_gate_up, brows(w.h, T), RAD_W(w_gate_up), brows(w.gate_up, T));
|
||||
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 */
|
||||
@@ -0,0 +1,169 @@
|
||||
/* 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
|
||||
*
|
||||
* rad_block_mlp.h documents the architecture. Differences:
|
||||
*
|
||||
* - Both projections are LinearFP8 (rad_fp8.h): an E4M3 weight with a bf16 [N/128][K/128]
|
||||
* scale plane, through `gemm_nt_q` at dtype fp8a8.
|
||||
* - Each takes an E4M3 activation quantised every step (the checkpoint's `activation_scheme`
|
||||
* is `dynamic`, so no activation scale is stored).
|
||||
* - Activations between ops stay bf16, so `Geom::dtype` stays "bf16" and every other op
|
||||
* resolves as in the bf16 block.
|
||||
*
|
||||
* The gate/up fusion survives the format because each part is a whole number of 128-row blocks:
|
||||
* two [17408, 5120] sources with [136, 40] scale planes concatenate to [34816, 5120] and
|
||||
* [272, 40]. Parts not on a 128-row boundary would misalign every scale after the seam.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_MLP_FP8_H
|
||||
#define RAD_BLOCK_MLP_FP8_H
|
||||
|
||||
#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] */
|
||||
};
|
||||
|
||||
/* Checkpoint names. `gate`, `up` and `down` name the `.weight` tensors; the checkpoint reader
|
||||
* pairs each with its scale plane. */
|
||||
struct Src {
|
||||
const char* norm = nullptr;
|
||||
const char* gate = nullptr;
|
||||
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;
|
||||
/* gate_up with the gate and quantiser in its epilogue, so the [M, 2*n_ff] bf16 product is
|
||||
* never written (unfused, the extra launch and second pass are a sizeable decode cost).
|
||||
* Declared beside the pair, not instead of it: the fold is the narrow tile's epilogue and
|
||||
* serves M <= 64, so prefill chunks take the pair. Byte-identical, as r4d_selftest and
|
||||
* ref_test check. */
|
||||
rad_op op_gated = 0;
|
||||
int64_t gated_rows = 0;
|
||||
/* The next block absorbs this block's closing all-reduce, so this one must not issue it.
|
||||
* Counterpart of `ar_in`; both sides ask ar_fused_ok(g, T), so they agree. */
|
||||
bool ar_out = false;
|
||||
|
||||
/* `fold`: a predecessor's delta is still in `w.h.x` and this norm does its residual add
|
||||
* (false for the first block of a chain). `add_out`: issue the trailing add here. See
|
||||
* rad_fp8.h. */
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
|
||||
const Src& src, bool fold = false, bool add_out = true,
|
||||
int ar_in = kArNone, bool ar_out_ = false);
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
/* The block over the first `T` rows of its buffers (see MoeFP8::step_rows). */
|
||||
void step_rows(RadCtx* c, int64_t T) const { slice(c, T, 0, T); }
|
||||
/* One row slice of the whole block; `rows <= 0` means the rest of the step. */
|
||||
void slice(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const;
|
||||
};
|
||||
|
||||
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));
|
||||
|
||||
/* Norm, quantise and residual add in one op (rad_fp8.h: NormQuantFP8). Folded, it adds the
|
||||
* previous block's delta from `h` into the stream; unfolded it reads the stream directly. */
|
||||
RAD_ARCH_TRY(nq_h.declare(b, g, w_norm, fold ? w.h.x : w.x, w.h, g.n_embd, fold ? w.x : 0,
|
||||
0, ar_in));
|
||||
RAD_ARCH_TRY(gate_up.declare(b, nm, g, nm.f("blk.%d.ffn_gate_up", l),
|
||||
2 * g.n_ff, g.n_embd, RAD_SHARD_ROW, grp_layer(l),
|
||||
{ src.gate, src.up }, w.h, w.gate_up, 0, { g.n_ff, g.n_ff }));
|
||||
|
||||
/* The bf16 silu product is written only if the down projection reads the bf16 plane
|
||||
* (LinearFP8::reads_x); a block-fp8 down_proj reads only codes and scales. */
|
||||
const char* down_base = nm.f("blk.%d.ffn_down", l);
|
||||
RAD_ARCH_TRY(down.probe(b, nm, g, down_base, { src.down }));
|
||||
RAD_ARCH_TRY(gq_ffn.declare(b, g, w.gate_up, w.ffn, g.n_ff, "silu", 0, down.reads_x));
|
||||
|
||||
/* The fold (decl_gated_fold), an fp8a8 tile, so bf16, MXFP4 and rotated 5-bit gate_up weights
|
||||
* take the pair. */
|
||||
if (!gate_up.bf16 && !gate_up.mx && !gate_up.paro5)
|
||||
op_gated = decl_gated_fold(b, g.max_tok, gate_up.N, gate_up.K, gate_up.w, gate_up.ws,
|
||||
{ w.h.q, w.h.s },
|
||||
gq_ffn.want_x
|
||||
? std::initializer_list<rad_buf>{ w.ffn.q, w.ffn.s, w.ffn.x }
|
||||
: std::initializer_list<rad_buf>{ w.ffn.q, w.ffn.s },
|
||||
&gated_rows);
|
||||
RAD_ARCH_TRY(down.declare(b, nm, g, down_base,
|
||||
g.n_embd, g.n_ff, RAD_SHARD_COL, grp_layer(l),
|
||||
{ src.down }, w.ffn, w.h.x));
|
||||
|
||||
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 when the next block's norm will not add (rad_fp8.h: NormQuantFP8). */
|
||||
if (add_out)
|
||||
op_add = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.x, w.h.x}, {w.x});
|
||||
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* One row slice of the block; r0 = 0, rows = T is the whole step (`brow_slice` at offset 0 is
|
||||
* `brows`). Every op is per row: the norm and quantiser group along K within a row, the GEMMs
|
||||
* accumulate each output row independently, and the fused all-reduce reduces within a row
|
||||
* (r4d_ar.cpp). So results do not depend on the cut, provided it obeys the band rule in
|
||||
* core/runtime/ctx.h. */
|
||||
inline void MlpFP8::slice(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const {
|
||||
if (rows <= 0) rows = T - r0;
|
||||
nq_h.step(c, T, r0, rows);
|
||||
if (op_gated && rows <= gated_rows) {
|
||||
RAD_ISSUE_N(c, op_gated, rows, brow_slice(w.h.q, r0, rows, g.n_embd),
|
||||
brow_slice(w.h.s, r0, rows, g.n_embd / RAD_FP8_BLOCK), RAD_W(gate_up.w),
|
||||
RAD_W(gate_up.ws), brow_slice(w.ffn.q, r0, rows, g.n_ff),
|
||||
brow_slice(w.ffn.s, r0, rows, g.n_ff / RAD_FP8_BLOCK),
|
||||
gq_ffn.want_x ? brow_slice(w.ffn.x, r0, rows, g.n_ff) : RAD_NONE);
|
||||
} else {
|
||||
gate_up.step(c, w.h, w.gate_up, T, r0, rows);
|
||||
gq_ffn.step(c, w.gate_up, T, r0, rows);
|
||||
}
|
||||
down.step(c, w.ffn, w.h.x, T, r0, rows);
|
||||
if (op_ar && !(ar_out && ar_fused_ok(g, rows)))
|
||||
RAD_ISSUE_N(c, op_ar, rows * g.n_embd, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_NONE);
|
||||
if (op_add)
|
||||
RAD_ISSUE_N(c, op_add, rows, brow_slice(w.x, r0, rows, g.n_embd),
|
||||
brow_slice(w.h.x, r0, rows, g.n_embd),
|
||||
brow_slice(w.x, r0, rows, g.n_embd));
|
||||
}
|
||||
|
||||
inline void MlpFP8::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
slice(c, T, 0, T);
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_MLP_FP8_H */
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,428 @@
|
||||
/* 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 under an `mtp.` prefix that predicts
|
||||
* token i+2 from the trunk's hidden state at i and the embedding of token i+1. It is the
|
||||
* speculative-decoding drafter; the embedding table and lm_head are the trunk's
|
||||
* (`mtp_use_dedicated_embeddings: false`, no `mtp.lm_head`).
|
||||
*
|
||||
* 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
|
||||
*
|
||||
* This is DeepSeek-V3's MTP layout: the head runs over the trunk's position indices and the shift
|
||||
* is only in which token is embedded. An off-by-one shows only as collapsed acceptance.
|
||||
*
|
||||
* The forward:
|
||||
*
|
||||
* 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'
|
||||
*
|
||||
* h' is both the logits input and the next round's `h`, as in the reference (a Qwen3-Next MTP
|
||||
* forward returns one tensor; an EAGLE head returns a (normed, unnormed) pair).
|
||||
*
|
||||
* ============================== THE TWO KINDS OF PASS ==============================
|
||||
*
|
||||
* By the sign of RadBatch::draft_pass:
|
||||
*
|
||||
* < 0 History pass, one row per token, gathering the trunk's hidden states. The head's
|
||||
* attention reads its own K and V for every earlier position, which the trunk's prefill
|
||||
* does not write; without this pass the head attends to stale pool contents and proposes
|
||||
* noise. The scheduler runs it over the positions the last step added, verified ones
|
||||
* included.
|
||||
*
|
||||
* It is also draft round 1 for every drafting sequence: its last history row is the
|
||||
* committed position plus the token the trunk chose after it, so the pass ends in the
|
||||
* lm_head over those rows (RadBatch::draft_out_ids) and leaves the head's output there
|
||||
* for round 2.
|
||||
*
|
||||
* > 1 Draft round, one row per sequence, reading the previous round's output from the same
|
||||
* buffer and ending in the lm_head. There is no separate round-1 pass.
|
||||
*
|
||||
* ============================== PRECISION ==============================
|
||||
*
|
||||
* As stored in mtp.safetensors:
|
||||
*
|
||||
* F8_E4M3 + scale layers.0.self_attn.{q,k,v,o}_proj, layers.0.mlp.{gate,up,down}_proj
|
||||
* BF16, no scale fc, norm, pre_fc_norm_embedding, pre_fc_norm_hidden, and every norm inside
|
||||
* the layer
|
||||
*
|
||||
* `fc` ([5120, 10240], bf16) is a plain `gemm_nt` issued once over the whole chunk: libr4d's bf16
|
||||
* row is C_LE("M", 65536) and K = 10240 is a multiple of 16. The history pass has one row per
|
||||
* token of a prefill chunk, so slicing at 64 would cost dozens of launches.
|
||||
*
|
||||
* ============================== THE CONCAT ORDER ==============================
|
||||
*
|
||||
* `fc` reads the normed embedding and the normed hidden state concatenated. The order is not in
|
||||
* the checkpoint (both are one [5120, 10240] matrix); this follows DeepSeek-V3's MTP:
|
||||
* `enorm(embedding)` then `hnorm(hidden)`. Per-op checks cannot tell the orders apart; the draft
|
||||
* acceptance rate does (the wrong order accepts almost nothing).
|
||||
*
|
||||
* ============================== THE NORM GAINS ==============================
|
||||
*
|
||||
* GemmaRMSNorm's `1 + w` (Geom::wadd) applies: pre_fc_norm_hidden is -0.06 .. -0.24 and
|
||||
* pre_fc_norm_embedding -0.27 .. -0.61, negative gains that only `1 + w` explains. `mtp.norm`
|
||||
* (0.59 .. 1.31) is ambiguous, so it takes the trunk output norm's `final_wadd`.
|
||||
*
|
||||
* ============================== THE KV CACHE ==============================
|
||||
*
|
||||
* The head's attention is bound to the trunk's full-attention group as one more layer, at
|
||||
* absolute index n_main:
|
||||
*
|
||||
* - It shares the trunk's slot mapping and block table, writing K and V at the slot of the
|
||||
* trunk's token for that position. A rejected draft's entry is overwritten by the next step's
|
||||
* correct token at the same address, and each round writes its position before attending to
|
||||
* it, so no rollback is needed (as in vLLM's EAGLE/MTP proposer).
|
||||
* - A second group would need its own page geometry, free list and eviction for a cache one
|
||||
* seventeenth the size.
|
||||
*
|
||||
* The group's page grows from 16 layers to 17 (6% more attention KV), only when speculation is
|
||||
* declared.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_MTP_FP8_H
|
||||
#define RAD_BLOCK_MTP_FP8_H
|
||||
|
||||
#include "rad_block_attn_gated_fp8.h"
|
||||
#include "rad_block_mlp_fp8.h"
|
||||
#include "rad_block_vit.h"
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
/* Declares the name map of the 2-bit draft head `head` (the checkpoint lm_head `lm` under its own
|
||||
* name, quantised by a recipe to u2 codes with an f16 scale and u8 zero per group of 128) and
|
||||
* returns whether the model holds it at two bits. If not (no such recipe), draft rounds read the
|
||||
* bf16 head.
|
||||
*
|
||||
* Called once by the plugin, before it declares the head's buffers; the block infers the answer
|
||||
* from whether those buffers exist. */
|
||||
inline bool mtp_draft_head_q2(RadBuilder* b, const char* head, const char* lm) {
|
||||
if (!head || !lm) return false;
|
||||
if (map_copy(b, head, lm) < 0) return false;
|
||||
RadEncoding e{};
|
||||
return weight_enc(b, head, &e) && e.n_planes > 0 && e.plane[0].dtype == RAD_U2;
|
||||
}
|
||||
|
||||
/* Templated on the feed-forward, since the head mirrors a trunk layer, which is dense or routed
|
||||
* by model (Qwen3.6-35B-A3B's `mtp.layers.0` has `mlp.experts.*`, `mlp.gate` and a shared expert).
|
||||
* `Ffn` is MlpFP8 or MoeFP8; both have the same declare() signature over their own Wire and Src
|
||||
* (MoeFP8's Config travels inside its Src for this reason). */
|
||||
template <class Ffn>
|
||||
struct MtpBlockFP8 {
|
||||
struct Wire {
|
||||
/* [max_tok, n_embd] the trunk's final hidden states for the step just run (the plugin's
|
||||
* `h`). A pass names the rows it wants through out_ids. */
|
||||
rad_buf src = 0;
|
||||
/* [max_tok, n_embd] in: the hidden state this pass predicts from; out: the head's own,
|
||||
* the next round's input. Sized for a prefill chunk (history passes are one row per
|
||||
* token). */
|
||||
rad_buf hout = 0;
|
||||
rad_buf e = 0; /* [max_tok, n_embd] the input token's embedding */
|
||||
rad_buf c = 0; /* [max_tok, 2 * n_embd] the two normed halves, fc's input */
|
||||
rad_buf x = 0; /* [max_tok, n_embd] the head's own residual stream */
|
||||
rad_buf logits = 0; /* [max_logit_rows, n_vocab] the trunk's, shared */
|
||||
/* The 2-bit draft head's working set (see op_dlogits), sized at max_logit_rows: only
|
||||
* drafting rows reach it. */
|
||||
rad_buf dq = 0; /* [max_logit_rows, n_embd] int8 codes */
|
||||
rad_buf ds = 0; /* [max_logit_rows, 1] f32, one scale a row */
|
||||
rad_buf dsum = 0; /* [n_embd/group, mpad] f32, group-major (quant_act_i8's asum) */
|
||||
rad_buf 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 reuses the trunk's working set, which is dead by the time the head runs (a
|
||||
* second set would be 150 MiB). */
|
||||
AttnGatedFP8::Wire attn{};
|
||||
typename Ffn::Wire mlp{};
|
||||
};
|
||||
|
||||
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. The trunk maps it as `output.weight`; the draft head is a
|
||||
* second logical weight over the same tensor, quantised to 2 bits (mtp_draft_head_q2). */
|
||||
const char* lm = nullptr;
|
||||
AttnGatedFP8::Src attn{};
|
||||
typename Ffn::Src mlp{};
|
||||
};
|
||||
|
||||
Geom g{};
|
||||
Wire w{};
|
||||
int layer = 0; /* absolute, for the KV group's layer_slot lookup */
|
||||
int64_t rows = 0; /* the widest pass: one row per token of a prefill chunk */
|
||||
int64_t off_e = 0, off_h = 0; /* the two halves' column offsets inside `c` */
|
||||
rad_weight w_tok = 0, w_lm = 0, w_fc = 0, w_norm = 0, w_pre_h = 0, w_pre_e = 0;
|
||||
rad_weight w_dh = 0, w_dhs = 0; /* the 2-bit lm_head and its (scale, zero) plane */
|
||||
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;
|
||||
/* Media rows over the head's embedding: the history pass embeds the prompt too (one position
|
||||
* on), and an image token's embedding comes from the encoder. Set `media` before declare when
|
||||
* the program has an encoder. */
|
||||
bool media = false;
|
||||
MediaRows mrows{};
|
||||
rad_op op_norm = 0, op_dsel = 0, op_dback = 0, op_logits = 0;
|
||||
rad_op op_dquant = 0, op_dlogits = 0, op_dtopk = 0;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup kv,
|
||||
int64_t rotary_dim, rad_weight tok_embd, rad_weight lm_head, float out_wadd,
|
||||
const Wire& wire, const Src& src);
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
};
|
||||
|
||||
template <class Ffn>
|
||||
inline int MtpBlockFP8<Ffn>::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
rad_kvgroup kv, int64_t rotary_dim, rad_weight tok_embd,
|
||||
rad_weight lm_head, float out_wadd, const Wire& wire,
|
||||
const Src& src) {
|
||||
g = geom; w = wire; layer = l; w_tok = tok_embd; w_lm = lm_head;
|
||||
rows = g.max_tok;
|
||||
if (rows <= 0 || !w_tok || !w_lm) return RAD_E_INVAL;
|
||||
|
||||
/* The normed embedding first, then the normed hidden state (see the header). */
|
||||
off_e = 0;
|
||||
off_h = g.n_embd;
|
||||
|
||||
/* The head's own weights, all replicated: three norms over the replicated stream, and `fc`,
|
||||
* which column-sharded would save 52 MiB per rank at the cost of an all-reduce per round. */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("mtp.pre_fc_norm_hidden.weight"), src.pre_norm_hidden));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("mtp.pre_fc_norm_embedding.weight"), src.pre_norm_embedding));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("mtp.norm.weight"), src.norm));
|
||||
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));
|
||||
|
||||
/* Separate gather_rows and embed_lookup ops over the trunk's buffers and weights, because
|
||||
* they write different buffers and liveness comes from each op's read/write sets. */
|
||||
op_gather = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
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 the lookup is partial and needs an exact
|
||||
* all-reduce. */
|
||||
if (g.world > 1)
|
||||
op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
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));
|
||||
|
||||
/* Moves round 1's rows of a history pass (RadBatch::draft_out_ids, one per drafting sequence)
|
||||
* to the front of `x` before the feed-forward, which then runs on those rows only. Goes through
|
||||
* `hout` (dead between fc's read and the norm's write), since an in-place gather could
|
||||
* overwrite a row not yet read. */
|
||||
op_dsel = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.x}, {w.hout});
|
||||
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.hout}, {w.x});
|
||||
if (!op_dsel || !op_dback) return RAD_E_INVAL;
|
||||
|
||||
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});
|
||||
|
||||
/* The trunk's lm_head over the head's hidden state, banded at the logits buffer's extent: it
|
||||
* runs over one row per drafting sequence. */
|
||||
op_logits = rw(b, RAD_OP(b, "logits_gemm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
RAD_INT("n_vocab", g.n_vocab),
|
||||
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 at the memory roofline for the bf16 lm_head's 2.54 GB, and a speculative
|
||||
* step runs the projection once to verify plus once per draft round. Drafts are verified by the
|
||||
* exact head, so a coarser draft head costs only acceptance, never an emitted token.
|
||||
*
|
||||
* The draft rounds read a 2-bit copy: 318 MB of codes and 40 MB of (scale, zero) dwords, an
|
||||
* eighth of the traffic. libr4d's `gemm_w2a8_nt` takes codes and the scale/zero planes as two
|
||||
* operands, laid out as `r4d.w2a8.frag.g128` at load (libr4d/r4d_layout.cpp). The grid is
|
||||
* asymmetric (four levels are too few for a symmetric one), so the activation side uses
|
||||
* `quant_act_i8`'s three-output form, whose per-group row sums subtract the stored zero.
|
||||
*
|
||||
* The draft head bypasses the sampler, which reads f32 logits: `row_topk` at R=1 takes the
|
||||
* argmax on the GEMM's bf16 output and the engine reads the id from `didx`. The trunk's logits
|
||||
* plane is untouched.
|
||||
*/
|
||||
enum { MTP_W2_GROUP = 128 }; /* libr4d's R4D_GEMM_W2A8_GROUP, and the layout's g128 tag */
|
||||
/* The plugin declares the working set only when mtp_draft_head_q2 found a 2-bit head (and
|
||||
* declared its name map). */
|
||||
q2 = src.lm && w.dq && w.ds && w.dsum && w.dlog && w.didx && w.dval;
|
||||
if (q2) {
|
||||
/* Replicated over the whole vocabulary. Without the sampler's cross-rank merge, a sharded
|
||||
* plane would let each rank propose only its own vocabulary slice. Replication costs 341
|
||||
* MiB per card at 2 bits and keeps the draft path single-rank. (The stored bytes are also
|
||||
* tile-major, 16 output rows per packed block, so a shard would have to be whole tiles.) */
|
||||
const char* dhn = nm.f("mtp.draft_head.weight");
|
||||
w_dh = decl_view(b, dhn, nullptr, "codes", RAD_U2, {g.n_vocab_all, g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
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});
|
||||
}
|
||||
|
||||
/* Keep `hout` live through the head's last op: it is the next round's input, and if only the
|
||||
* lm_head's first op read it, the planner could give its bytes to later ops (silently lowering
|
||||
* acceptance). */
|
||||
{
|
||||
const rad_op last = q2 ? op_dtopk : op_logits;
|
||||
if (rad_op_reads(b, last, &w.hout, 1) < 0) return RAD_E_INVAL;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* One pass of the head over the scheduler's batch for it: n_tok rows, `token_ids` already shifted
|
||||
* one position on (batch.cpp, token_at), `positions` the head's indices, and the KV group batch
|
||||
* carrying each row's slot, so the attention layer needs no special case. */
|
||||
template <class Ffn>
|
||||
inline void MtpBlockFP8<Ffn>::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
const int r = batch->draft_pass;
|
||||
|
||||
/* The history pass gathers; later rounds read the previous pass's output from the same
|
||||
* buffer. */
|
||||
if (r == 1) {
|
||||
rad_step_fail(c, "the MTP head was handed a draft-round-1 pass: that round is carried by "
|
||||
"the history pass (RadBatch::draft_out_ids) and has no pass of its own");
|
||||
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));
|
||||
|
||||
/* A history pass with no drafting rows (every prefill chunk but a prompt's last) only needs
|
||||
* K and V. `n_draft_out` is the same on every rank, so skipped collectives match. */
|
||||
if (r < 0 && batch->n_draft_out <= 0) {
|
||||
attn.store_kv(c, batch);
|
||||
return;
|
||||
}
|
||||
attn.step(c, batch);
|
||||
|
||||
/* A history pass with drafting rows continues on those rows alone (round 1): they are moved
|
||||
* to the front of `x` and the rest of the head runs over them. */
|
||||
int64_t L = T; /* the rows the stream goes on with */
|
||||
if (r < 0) {
|
||||
L = batch->n_draft_out;
|
||||
RAD_ISSUE_N(c, op_dsel, L, RAD_B(w.x), praw(batch->draft_out_ids, RAD_I32, L),
|
||||
brows(w.hout, L));
|
||||
RAD_ISSUE_N(c, op_dback, L, brows(w.hout, L), brows(w.x, L));
|
||||
}
|
||||
|
||||
mlp.step_rows(c, L);
|
||||
|
||||
RAD_ISSUE(c, op_norm, brows(w.x, L), RAD_W(w_norm), brows(w.hout, L));
|
||||
if (q2) {
|
||||
/* `dsum` is group-major [n_embd/group][ceil(L/16)*16], so it has no row slice; pass it
|
||||
* whole. */
|
||||
RAD_ISSUE_N(c, op_dquant, L, brows(w.hout, L), brows(w.dq, L), brows(w.ds, L),
|
||||
RAD_B(w.dsum));
|
||||
/* The trailing `b_ref` is mxfp4's and absent; operands are positional, so pass RAD_NONE
|
||||
* (rad_fp8.h). */
|
||||
RAD_ISSUE_N(c, op_dlogits, L, brows(w.dq, L), brows(w.ds, L), RAD_W(w_dh), RAD_W(w_dhs),
|
||||
brows(w.dlog, L), RAD_B(w.dsum), RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_dtopk, L, brows(w.dlog, L), brows(w.didx, L), brows(w.dval, L),
|
||||
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 (SwiGLU feed-forward). The routed one is MtpBlockFP8<MoeFP8>, named by the
|
||||
* plugin that needs it; this header does not include rad_block_moe_fp8.h. */
|
||||
using MtpFP8 = MtpBlockFP8<MlpFP8>;
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_MTP_FP8_H */
|
||||
@@ -0,0 +1,535 @@
|
||||
/* rad_block_mtp_hc.h -- the multi-token-prediction head of a model whose residual stream is `hc`
|
||||
* times the model width.
|
||||
*
|
||||
* ============================== DIFFERENCES FROM rad_block_mtp_fp8.h ==============================
|
||||
*
|
||||
* That file serves Qwen3.5 / Qwen3-Next / Qwen3.6, whose head is a pre-norm layer reading the
|
||||
* trunk's [n_embd] hidden state. Qwen4-Exp's head has the same indexing and passes but lives in
|
||||
* the wide stream:
|
||||
*
|
||||
* 10240-wide input `mtp.pre_fc_norm_hidden.weight` is [hc * n_embd]: the head
|
||||
* continues from the trunk's wide stream before the output mixer,
|
||||
* not `last_hidden_state`.
|
||||
* two fc matrices `mtp.fc_hidden` and `mtp.fc_embedding`, both [n_embd, n_embd], so
|
||||
* no concatenation: the hidden matrix is applied to each
|
||||
* sub-stream and the embedding product broadcast into all of them
|
||||
* (docs/OPS.md's `mtp_enter` row).
|
||||
* gated residuals, no norms `mtp.layers.0.attn_hyper_connection` and `.mlp_hyper_connection`,
|
||||
* as in a trunk layer; no `input_layernorm` or
|
||||
* `post_attention_layernorm`.
|
||||
* its own mixer `mtp.hyper_connection_mixer`, a connection with no write half
|
||||
* that collapses the wide stream for the lm_head (the model's 98th
|
||||
* connection, shaped like the trunk's final one).
|
||||
*
|
||||
* ============================== THE INDEXING ==============================
|
||||
*
|
||||
* 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 layout: the head runs over the trunk's position indices and the shift is only in
|
||||
* which token is embedded. An off-by-one shows only as collapsed acceptance.
|
||||
*
|
||||
* ============================== THE TWO KINDS OF PASS ==============================
|
||||
*
|
||||
* By the sign of `RadBatch::draft_pass` (details in rad_block_mtp_fp8.h):
|
||||
*
|
||||
* < 0 History pass, one row per token, continuing from the trunk's wide stream. It writes the
|
||||
* head's own K and V, which nothing else writes. It is also draft round 1 for drafting
|
||||
* sequences: it ends in the lm_head over their rows (RadBatch::draft_out_ids) and hands
|
||||
* their wide state on as the carry.
|
||||
* > 1 Draft round, one row per sequence, continuing from the head's own stream.
|
||||
*
|
||||
* ============================== THE CARRY ==============================
|
||||
*
|
||||
* `hin` is what a round continues from and `hw` the head's own stream. They cannot share a buffer:
|
||||
* `mtp_enter` reads the whole wide row for every output channel, so in-place writes would clobber
|
||||
* unread input. (The pre-norm head's carry is written by a different op, `mtp.norm`; here the
|
||||
* round ends with the mlp connection's in-place write.) A `cast` copies `hw` to `hin` between
|
||||
* rounds (a 20 KB row at decode), skipped on the last round. A drafting history pass instead
|
||||
* gathers its round-1 rows and copies them back to the front of `hw`, where the mixer reads them.
|
||||
*
|
||||
* ============================== THE KV CACHE ==============================
|
||||
*
|
||||
* The head's attention is bound to the trunk's full-attention group as one more layer, at
|
||||
* absolute index n_layer, sharing its slot mapping and block table; a rejected draft's entry is
|
||||
* overwritten by the next step's token at the same address (see rad_block_mtp_fp8.h). The group's
|
||||
* page grows from 12 layers to 13 (8% more attention KV), only when speculation is declared.
|
||||
*
|
||||
* ============================== BUFFERS ==============================
|
||||
*
|
||||
* The layer reuses the trunk's working buffers (`attn_qg`, the expert planes, the narrow block
|
||||
* input), which are dead once the trunk step is committed; a second set would be 150 MiB. Only
|
||||
* the wide stream, the carry, the embedding and the logits path are its own.
|
||||
*
|
||||
* Invariant: declare this block after the trunk's last op. Declaration order is the buffer
|
||||
* planner's liveness (core/build/rad_bufplan.cpp); declared mid-trunk, the head would share bytes
|
||||
* with live trunk buffers (symptom: correct output, zero acceptance).
|
||||
*/
|
||||
#ifndef RAD_BLOCK_MTP_HC_H
|
||||
#define RAD_BLOCK_MTP_HC_H
|
||||
|
||||
#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"
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
/* Candidates the coarse 2-bit head proposes for exact rescoring (`logit_rerank` against the
|
||||
* full-precision head) before column 0 is read. The 2-bit head's top-1 differs from the exact one
|
||||
* often enough to cost acceptance; 8 is the reference implementation's value, which recovered
|
||||
* 99.63% agreement with the exact argmax, at R rows of the weight per draft row (40 KB against
|
||||
* 318 MB).
|
||||
*
|
||||
* Both 4 and 16 give lower acceptance than 8: acceptance is agreement with the trunk, while the
|
||||
* rescore maximises the head's own preference, so beyond some width the coarse ranking is a useful
|
||||
* restriction. */
|
||||
static constexpr int64_t kDraftTopR = 8;
|
||||
|
||||
struct MtpHcBlock {
|
||||
struct Wire {
|
||||
/* [max_tok, hc * n_embd] the trunk's wide stream for the step just run; a pass names the
|
||||
* rows it wants through out_ids. */
|
||||
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, sized at max_logit_rows (only drafting rows reach
|
||||
* it). */
|
||||
rad_buf dq = 0, ds = 0, dsum = 0, dlog = 0, didx = 0, dval = 0;
|
||||
/* Vocab-parallel pairs, declared only when the head is sharded: (int32 id, f32 value)
|
||||
* pairs stored as f32, this rank's top-R and the all-gathered world * R. */
|
||||
rad_buf dpair = 0, dgath = 0;
|
||||
AttnGatedFP8::Wire attn{};
|
||||
MoeFP8::Wire mlp{};
|
||||
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 runs; decides whether the carry is needed */
|
||||
int64_t ngroup = 0; /* the pre-fc norm's groups: hc, one rsqrt per sub-stream */
|
||||
bool q2 = false;
|
||||
/* The 2-bit draft head's name. The plugin passes it to mtp_draft_head_q2 (which declares the
|
||||
* map) and declares the head's buffers if that returns true. */
|
||||
static const char* head_name(Names& nm) { return nm.f("mtp.draft_head.weight"); }
|
||||
|
||||
rad_weight w_tok = 0, w_lm = 0, w_fc_h = 0, w_fc_e = 0, w_pre_h = 0, w_pre_e = 0;
|
||||
rad_weight w_dh = 0, w_dhs = 0;
|
||||
|
||||
HyperConn hc_attn{}, hc_mlp{}, mixer{};
|
||||
AttnGatedFP8 attn{};
|
||||
QsaIndexer qsa{};
|
||||
/* The indexer's window bounds for a pass wider than its score plane (QsaIndexer::step), set by
|
||||
* the caller before step(); null where no pass is. */
|
||||
const int32_t* qsa_win_cu = nullptr;
|
||||
MoeFP8 mlp{};
|
||||
|
||||
rad_op op_gather = 0, op_embed = 0, op_embed_ar = 0, op_enter = 0, op_carry = 0;
|
||||
|
||||
/* Media rows over the head's embedding (see MtpBlockFP8::media). Set 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 vocab-head rule, asked through the block by whoever sizes `dlog` and the pair
|
||||
* planes. */
|
||||
static bool head_sharded(const Geom& g) { return vocab_head_sharded(g); }
|
||||
static int64_t head_rows(const Geom& g) { return vocab_head_rows(g); }
|
||||
|
||||
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 per sub-stream, like every gated
|
||||
* residual here. A flat norm fits the same [hc*n] gain and passes per-op checks; only the
|
||||
* acceptance rate tells them apart (docs/OPS.md's `mtp_enter` row). */
|
||||
ngroup = hc.hc;
|
||||
if (rows <= 0 || !w_tok || !w_lm || hc.hc <= 1) return RAD_E_INVAL;
|
||||
if (!w.src || !w.hin || !w.hw || !w.e || !w.hout) return RAD_E_INVAL;
|
||||
const int64_t HN = hc.hc * g.n_embd;
|
||||
|
||||
/* ---- the entry's four weights, all replicated: two gains over the replicated stream, and two
|
||||
* fc matrices whose column shard would save 13 MB per rank at an all-reduce per round. */
|
||||
const char* nph = nm.f("mtp.pre_fc_norm_hidden.weight");
|
||||
const char* npe = nm.f("mtp.pre_fc_norm_embedding.weight");
|
||||
const char* nfh = nm.f("mtp.fc_hidden.weight");
|
||||
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 entry matrices are bf16 or E4M3 rows with a per-group scale (OPS.md's `fc` on
|
||||
* mtp_enter), declared over all planes at the codes' dtype; both must match. */
|
||||
const uint32_t fdt = weight_codes_dtype(b, nfh, RAD_BF16);
|
||||
if (weight_codes_dtype(b, nfe, RAD_BF16) != fdt || (fdt != RAD_BF16 && fdt != RAD_F8E4M3)) {
|
||||
fprintf(stderr, "radiance: the MTP head's fc_hidden is %s and fc_embedding %s; the entry "
|
||||
"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;
|
||||
|
||||
/* Separate gather_rows and embed_lookup ops over the trunk's buffers and weights, because
|
||||
* they write different buffers and liveness comes from each op's read/write sets. */
|
||||
op_gather = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", HN),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
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 the lookup is partial and needs an exact
|
||||
* all-reduce. */
|
||||
if (g.world > 1)
|
||||
op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
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, as a trunk full-attention layer at index n_layer: gated residual, gated
|
||||
* attention with its indexer, gated residual, routed feed-forward. Declared in step()'s issue
|
||||
* order. */
|
||||
RAD_ARCH_TRY(hc_attn.declare(b, nm, g, nm.f("mtp.attn_hc"), hc, HyperConn::Wire{w.hw, w.x, w.inj},
|
||||
src.hc_attn));
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, kv));
|
||||
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));
|
||||
/* ---- round 1's rows of a history pass (RadBatch::draft_out_ids), moved before the
|
||||
* feed-forward, which then runs on them only: gathered into `hin` and copied back to the
|
||||
* front of `hw` (an in-place gather could overwrite unread rows). */
|
||||
op_dsel = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", HN),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
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 connection's read also writes the rotated expert input, as on the trunk. */
|
||||
HyperConn::Config mcfg = hc;
|
||||
HyperConn::Wire mwire{w.hw, w.x, w.inj};
|
||||
if (src.mlp.cfg.expert_rot) { mcfg.rotate = 1; mwire.rq = w.mlp.hr.q; mwire.rs = w.mlp.hr.s; }
|
||||
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 following write takes the MoE 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 run in place). */
|
||||
op_carry = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", HN),
|
||||
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.hw}, {w.hin});
|
||||
|
||||
/* ---- the head's mixer: a connection with no write half that collapses the wide stream for
|
||||
* the lm_head, which reads bf16, so no fp8 codes. */
|
||||
{
|
||||
HyperConn::Config mc = hc;
|
||||
mc.inject = 0;
|
||||
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 extent (one
|
||||
* row per drafting sequence). */
|
||||
op_logits = rw(b, RAD_OP(b, "logits_gemm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
RAD_INT("n_vocab", g.n_vocab),
|
||||
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 (rationale in rad_block_mtp_fp8.h): fewer bytes per draft round,
|
||||
* at the cost of acceptance only. */
|
||||
enum { MTP_W2_GROUP = 128 };
|
||||
/* R is kDraftTopR. It must also be at least 2: `ar_gather_2rank` needs rows of whole 16-byte
|
||||
* words and a pair is 8 bytes. The engine reads column 0 through `proposal_pitch`. */
|
||||
q2 = w.dq && w.ds && w.dsum && w.dlog && w.didx && w.dval;
|
||||
if (q2) {
|
||||
/* Vocab-parallel when possible (159 MB a round instead of 318). Bypassing the sampler, it
|
||||
* uses the same three ops as rad_block_dspark.h: a top-R reporting global ids, an
|
||||
* all_gather of (id, value) pairs, and a merge giving exactly the unsharded top-R. */
|
||||
const bool dh_shard = head_sharded(g) && w.dpair && w.dgath;
|
||||
const int dh_split = dh_shard ? RAD_SHARD_ROW : RAD_SHARD_NONE;
|
||||
const int64_t hrows = dh_shard ? g.n_vocab : g.n_vocab_all;
|
||||
/* Its own stored weight made from the trunk's lm_head by the recipe (`u2*f16+u8[1x128]`),
|
||||
* name map declared by mtp_draft_head_q2. The GEMM takes codes as one operand and the
|
||||
* scale/zero planes as the other. */
|
||||
const char* dhn = head_name(nm);
|
||||
w_dh = decl_view(b, dhn, nullptr, "codes", RAD_U2, {hrows, g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, dh_split, grp_layer(l));
|
||||
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, reports global ids and also writes the
|
||||
* pair plane the gather moves. Replicated, `vocab_off` is omitted: an optional parameter
|
||||
* present with value 0 is a different declaration from an absent one. */
|
||||
op_dtopk = dh_shard
|
||||
? rw(b, RAD_OP(b, "row_topk",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("N", hrows),
|
||||
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});
|
||||
/* ---- Exact rescoring of the coarse candidates against `w_lm`, the trunk's lm_head
|
||||
* (already resident; the fallback `op_logits` reads it). It reads R rows per draft row in
|
||||
* the trunk's stored layout, which libr4d's rerank shares with its fp8 logits GEMM.
|
||||
*
|
||||
* No extra collective: sharded, every candidate is one this rank owns, and the existing
|
||||
* gather and merge then rank exact values. It overwrites `didx`/`dval`/`dpair` in place.
|
||||
*
|
||||
* Skipped for a replicated draft head above one rank: the vocabulary did not shard cleanly
|
||||
* (vocab_head_sharded) while the trunk's lm_head stays row-sharded, so candidates include
|
||||
* ids this rank cannot score.
|
||||
*
|
||||
* `vocab_off` is always passed: this op has one form, and at world 1 it is 0. */
|
||||
const bool rerank = dh_shard || g.world <= 1;
|
||||
if (rerank) {
|
||||
op_drerank = RAD_OP(b, "logit_rerank",
|
||||
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 rather than rw(): the write set is conditional (see rad_fp8.h:
|
||||
* NormQuantFP8). */
|
||||
rad_buf rd[2] = { w.hout, w.didx };
|
||||
rad_buf wr[3] = { w.didx, w.dval, w.dpair };
|
||||
rad_op_reads (b, op_drerank, rd, 2);
|
||||
rad_op_writes(b, op_drerank, wr, dh_shard ? 3 : 2);
|
||||
}
|
||||
if (dh_shard) {
|
||||
/* Row-interleaved, so one draft row's pairs from every rank are adjacent for
|
||||
* `row_topk_merge`. */
|
||||
op_dgather = rw(b, RAD_OP(b, "all_gather",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_INT("numel", g.max_logit_rows * kDraftTopR * 2),
|
||||
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;
|
||||
}
|
||||
/* Keep the carry `hin` live through the head's last op: it is written before the mixer and
|
||||
* lm_head run, and the planner could otherwise give its bytes to them (silently lowering
|
||||
* acceptance). */
|
||||
{
|
||||
rad_op last = op_logits;
|
||||
if (q2) last = op_dmerge ? op_dmerge : op_drerank ? op_drerank : op_dtopk;
|
||||
if (rad_op_reads(b, last, &w.hin, 1) < 0) return RAD_E_INVAL;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* One pass of the head over the scheduler's batch for it: n_tok rows, `token_ids` already shifted
|
||||
* one position on (sched/batch.cpp, token_at), `positions` the head's indices, and the KV group
|
||||
* batch carrying each row's slot, so the attention layer needs no special case. */
|
||||
inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
const int r = batch->draft_pass;
|
||||
|
||||
/* The history pass continues from the trunk's wide stream; later rounds from the head's,
|
||||
* which the carry left in the same buffer. */
|
||||
if (r == 1) {
|
||||
rad_step_fail(c, "the MTP head was handed a draft-round-1 pass: that round is carried by "
|
||||
"the history pass (RadBatch::draft_out_ids) and has no pass of its own");
|
||||
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_pieces(c, T);
|
||||
|
||||
/* A history pass with no drafting rows (every prefill chunk but a prompt's last) only stores
|
||||
* the head's state: K and V, and the indexer's block keys and tail. `n_draft_out` is the same
|
||||
* on every rank, so skipped collectives match. */
|
||||
if (r < 0 && batch->n_draft_out <= 0) {
|
||||
qsa.store(c, attn.w.h, batch);
|
||||
attn.store_kv(c, batch);
|
||||
return;
|
||||
}
|
||||
|
||||
/* The indexer runs first because the attention reads its selection; `w.h` is already final,
|
||||
* written by the connection above. */
|
||||
qsa.step(c, attn.w.h, batch, qsa_win_cu);
|
||||
attn.step(c, batch);
|
||||
|
||||
hc_attn.write(c, T, 0, T);
|
||||
|
||||
/* A history pass with drafting rows continues on those rows alone (round 1): they are moved
|
||||
* to the front of `hw` and the rest of the head runs over them. */
|
||||
int64_t L = T; /* the rows the stream goes on with */
|
||||
if (r < 0) {
|
||||
L = batch->n_draft_out;
|
||||
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));
|
||||
}
|
||||
|
||||
hc_mlp.read_pieces(c, L);
|
||||
mlp.step_rows(c, L);
|
||||
hc_mlp.write(c, L, 0, L);
|
||||
|
||||
/* The carry, only if a later round reads it: a history pass is round 1, followed by round 2
|
||||
* when depth > 1; the last round is followed by a trunk step. */
|
||||
if (r < 0 ? depth > 1 : r < depth)
|
||||
RAD_ISSUE_N(c, op_carry, L, brows(w.hw, L), brows(w.hin, L));
|
||||
|
||||
mixer.read(c, L, 0, L);
|
||||
if (q2) {
|
||||
/* `dsum` is group-major [n_embd/group][ceil(L/16)*16], so it has no row slice; pass it
|
||||
* whole. */
|
||||
RAD_ISSUE_N(c, op_dquant, L, brows(w.hout, L), brows(w.dq, L), brows(w.ds, L),
|
||||
RAD_B(w.dsum));
|
||||
/* The trailing `b_ref` is mxfp4's and absent; operands are positional, so pass RAD_NONE
|
||||
* (rad_fp8.h). */
|
||||
RAD_ISSUE_N(c, op_dlogits, L, brows(w.dq, L), brows(w.ds, L), RAD_W(w_dh), RAD_W(w_dhs),
|
||||
brows(w.dlog, L), RAD_B(w.dsum), RAD_NONE);
|
||||
if (op_dmerge) {
|
||||
RAD_ISSUE_N(c, op_dtopk, L, brows(w.dlog, L), brows(w.didx, L), brows(w.dval, L),
|
||||
brows(w.dpair, L));
|
||||
/* In place over all three, so the gather and merge carry exact values. */
|
||||
if (op_drerank)
|
||||
RAD_ISSUE_N(c, op_drerank, L, brows(w.hout, L), RAD_W(w_lm), brows(w.didx, L),
|
||||
brows(w.didx, L), brows(w.dval, L), brows(w.dpair, L));
|
||||
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 */
|
||||
@@ -0,0 +1,481 @@
|
||||
/* rad_block_ple.h -- Qwen4-Exp's Per-Layer Embedding, declared and issued.
|
||||
*
|
||||
* ============================== WHAT IT IS ==============================
|
||||
*
|
||||
* One layer has a second embedding table addressed by a hash of the last three tokens.
|
||||
* Qwen3.8-Flash-Next's is 320,001,536 rows of 160 (51 of the checkpoint's 125 billion
|
||||
* parameters), read sixteen rows per token and mixed into the residual stream by a dot product
|
||||
* against the stream:
|
||||
*
|
||||
* ids = ngram_ids(tokens) [T, 16] a hash of the last 3 ids, per head
|
||||
* e = embed_lookup_q(ids, table, scale) [T, 2560] 16 x 160, flattened
|
||||
* 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
|
||||
*
|
||||
* This runs before the attention hyper-connection reads the stream, so `h` is the wide, un-normed
|
||||
* residual.
|
||||
*
|
||||
* ============================== THE TABLE ==============================
|
||||
*
|
||||
* The 51.2 GB table cannot be staged onto a card, so `embed_lookup_q` reads it where
|
||||
* --ngram-placement put it: a host gather over the container's mmap or a locked RAM copy
|
||||
* (libavx/avx_ngram.cpp), a device kernel reading a pinned copy over the link, or a card's own
|
||||
* copy. The result reaches the card through the host arena, 5 KB per token at decode. Hence:
|
||||
*
|
||||
* The table is a weight operand: the planner places an op on the host only when all its weight
|
||||
* operands are Site::Host, judged from the table's placement.
|
||||
*
|
||||
* `ids` and `e` are host-domain buffers, written and read by the host gather; a device gather
|
||||
* accesses them over the link. Everything downstream of `e` is device work.
|
||||
*
|
||||
* It is 128 checkpoint tensors, mapped in pieces by map_concat_shards(); the order is the
|
||||
* concatenation, and a permuted table silently looks up wrong rows.
|
||||
*
|
||||
* ============================== THE TWO ROLLING WINDOWS ==============================
|
||||
*
|
||||
* The n-gram hash needs the two committed ids before the step, and the convolution nine timesteps
|
||||
* of its input. Both are RAD_KV_CONV windows read at `num_accepted - 1`. The token window's cold
|
||||
* value is EOS, the convolution's zero (zero is a real token id); `has_init` marks cold slots.
|
||||
*
|
||||
* What a step leaves in the window depends on the step, signalled by whether `num_accepted` is
|
||||
* passed (libref/ref_ple.cpp). A decode row may have drafts rejected, so its window uses
|
||||
* gdn_conv_update's shifted layout, where the next read offset selects the history ending at the
|
||||
* last kept token. A prefill chunk commits everything and leaves its tail at offset zero, read by
|
||||
* the next step's `num_accepted` of 1. One layout cannot serve both, so step() issues both ops
|
||||
* once per half of the batch, as rad_block_gdn_fp8.h does.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_PLE_H
|
||||
#define RAD_BLOCK_PLE_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
#include "rad_fp8.h"
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct PleLayer {
|
||||
struct Config {
|
||||
int64_t hc = 0; /* hyper-connection streams */
|
||||
int64_t embed_dim = 0; /* ple_embed_dim: heads * head_dim */
|
||||
int64_t heads = 0; /* (ngram - 1) * heads_per_ngram */
|
||||
int64_t ngram = 0;
|
||||
int64_t eos = -1;
|
||||
int64_t rows = 0; /* the table's row count, padded */
|
||||
int64_t shards = 0; /* how many checkpoint tensors it is stored as */
|
||||
int64_t conv_width = 0;
|
||||
int64_t dilation = 0; /* == ngram, in this model */
|
||||
int64_t head_dim() const { return heads > 0 ? embed_dim / heads : 0; }
|
||||
int64_t hist() const { return (conv_width - 1) * dilation; }
|
||||
};
|
||||
|
||||
struct Wire {
|
||||
rad_buf h = 0; /* [max_tok, hc * n_embd] the wide stream, read and added into */
|
||||
};
|
||||
|
||||
struct Src {
|
||||
/* The table's shards are named `<prefix><i><suffix>`; everything else is one tensor. */
|
||||
const char* shard_prefix = nullptr;
|
||||
const char* shard_suffix = nullptr;
|
||||
const char* mult = nullptr;
|
||||
const char* vocab_sizes = nullptr;
|
||||
const char* offsets = nullptr;
|
||||
const char* key_proj = nullptr;
|
||||
const char* value_proj = nullptr;
|
||||
const char* norm_key = nullptr;
|
||||
const char* norm_query = nullptr;
|
||||
const char* norm_conv = nullptr;
|
||||
const char* conv1d = nullptr;
|
||||
};
|
||||
|
||||
Geom g{};
|
||||
Config c{};
|
||||
Wire w{};
|
||||
int layer_ = 0;
|
||||
|
||||
rad_weight w_table = 0, w_scale = 0, w_mult = 0, w_vsz = 0, w_off = 0;
|
||||
/* The table is plain bf16 as shipped (no scale weight) rather than E4M3. */
|
||||
bool table_bf16 = false;
|
||||
rad_weight w_key = 0, w_value = 0, w_nk = 0, w_nq = 0, w_nc = 0, w_conv = 0;
|
||||
|
||||
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 ids()). */
|
||||
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 heads (the reference's constructor checks). */
|
||||
if (c.heads % (c.ngram - 1) || c.embed_dim % c.heads) {
|
||||
fprintf(stderr, "radiance: ple: %lld heads over %lld n-gram orders, %lld embed dims -- "
|
||||
"neither divides\n", (long long)c.heads, (long long)(c.ngram - 1),
|
||||
(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;
|
||||
/* ============================== REPLICATED UNDER TP ==============================
|
||||
*
|
||||
* The whole layer is replicated and has no collective. The table is addressed by a token hash
|
||||
* every rank computes identically, so a vocabulary shard is useless; and it is Tier::Mapped,
|
||||
* so all ranks gather through one shared row cache over the same file.
|
||||
*
|
||||
* The rest is 63 MiB per rank (key_proj 50, value_proj 12.5, three norm gains, a conv weight).
|
||||
* Column-sharding the projections would shard `gv` and `gvn` across the hyper-connection
|
||||
* streams and need an all-gather per step to save 31 MiB per card. Every rank adds the same
|
||||
* `out` into an identical copy of the stream, so the result stays bit-identical across ranks.
|
||||
*
|
||||
* The duplicated gather is `heads` rows per token: 16 at decode, 32768 at a 2048-token chunk,
|
||||
* about 70 ms per rank through the mapping (7.6% of a prefill step). That cost is page-table
|
||||
* population, not I/O: a prefill's distinct rows land about one per 4 KiB page (of 25), so the
|
||||
* mapping pays a fault per row. At decode half of each step's rows are new and the page cache
|
||||
* makes the waiting thread start each read. So the kernel keeps its own row cache and reads
|
||||
* misses straight from the file (libavx/avx_ngram.cpp). Ranks share that cache: each claims
|
||||
* and reads the misses it reaches first and waits only for rows another rank has claimed, so
|
||||
* each miss is read once without a cross-rank barrier.
|
||||
*/
|
||||
|
||||
const int64_t HN = hn();
|
||||
const int64_t HD = c.head_dim();
|
||||
|
||||
/* ---- the table, its scale, and the three hash constants -------------------------------- */
|
||||
/* E4M3 with one scale for all 320 million rows (Qwen3.8-Flash-Next-FP8's choice; E4M3 has its
|
||||
* own exponent, a row's dynamic range is 2.3x, and the scale sits on a three-octave plateau).
|
||||
* One stored weight, `fp8_e4m3*bf16[*x*]`: codes plus a one-element scale plane, made by the
|
||||
* recipe (data/recipes/qwen4exp-w4.recipe); the gather takes them as two operands. The name map
|
||||
* joins the shards along rows and is declared first, since the encoding is looked up through
|
||||
* it. RAD_ACCESS_VOCAB: it is a vocabulary table, just not the token one. */
|
||||
const char* tn = nm.f("blk.%d.ple_ngram.weight", layer);
|
||||
RAD_ARCH_TRY(map_concat_shards(b, tn, src.shard_prefix, src.shard_suffix, (int)c.shards, 0));
|
||||
/* Or the checkpoint's own bf16 table (102 GB) when the container holds it as shipped: the same
|
||||
* op with no scale (an absent scale means 1), still a host gather over the mapping. */
|
||||
RadEncoding te{};
|
||||
table_bf16 = weight_enc(b, tn, &te) && rad_enc_is(&te, "plain") && te.n_planes == 1 &&
|
||||
te.plane[0].dtype == RAD_BF16;
|
||||
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: the multipliers are ~2.4e13 (a token id times one fills 63 bits), so narrowing them
|
||||
* would change every id. */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_mult", layer), src.mult));
|
||||
w_mult = decl_w(b, nm.f("blk.%d.ple_mult", layer), RAD_I64, {c.ngram},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
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: the FP8 checkpoint's `modules_to_not_convert` names both projections. */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_key.weight", layer), src.key_proj));
|
||||
w_key = decl_w(b, nm.f("blk.%d.ple_key.weight", layer), RAD_BF16, {HN, c.embed_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
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 a per-sequence rolling window of width-1 + num_spec entries. The token
|
||||
* window's `conv_width` is ngram, so its window is ngram - 1 + n_spec.
|
||||
*
|
||||
* The channel count is n_head_kv * head_dim, not `state_dim` (RAD_KV_LINEAR's per-head
|
||||
* geometry, ignored by the CONV kind). Set via state_dim, both groups would size to zero and
|
||||
* the KV manager would refuse the model; rad-kbench would not catch it, since it synthesises
|
||||
* the state operand from the op's shape function. */
|
||||
{
|
||||
RadKVGroupDecl td{};
|
||||
td.kind = RAD_KV_CONV;
|
||||
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 (window =
|
||||
* conv_width - 1 + n_spec) is that plus one; the raw conv_width would size an undilated
|
||||
* window and the deepest tap would read unwritten data. */
|
||||
cd.conv_width = c.hist() + 1;
|
||||
cd.n_head_kv = 1;
|
||||
cd.head_dim = HN; /* [n_states, hc*n_embd, hist + n_spec] */
|
||||
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 ---------------------------------------------------------------------------- */
|
||||
/* The two buffers the gather touches are host domain. `ids` is written by ngram_ids and read by
|
||||
* the gather; `e` is written by the gather and copied onto the card (`ple_emb_dev`). The host
|
||||
* arena is mapped, so the device reads it over the link (core/runtime/ctx.cpp), 5 KB per token
|
||||
* at decode. A device gather (--ngram-placement ram or vram, with libr4d) reads `ids` and
|
||||
* writes `e` over the link too; the domain is fixed here, before placement decides who gathers.
|
||||
*
|
||||
* `ids` is PERSIST: it is written at the top of the step and read at this layer, but liveness
|
||||
* follows declared order, where the two ops are adjacent, so a transient could be overwritten
|
||||
* in between. */
|
||||
{
|
||||
/* Twice the step's rows: the step's ids, then those of the prompt that follows
|
||||
* (RadBatch::n_ahead), which the gather's reader prefetches while the step runs. */
|
||||
RadBufDecl d{};
|
||||
d.dtype = RAD_I32; d.rank = 2; d.shape[0] = 2 * g.max_tok; d.shape[1] = c.heads;
|
||||
d.kind = RAD_BUF_PERSIST; d.domain = RAD_DOMAIN_HOST;
|
||||
b_ids = rad_decl_buffer(b, nm.f("ple_ids"), &d);
|
||||
|
||||
/* [max_tok, embed_dim], not [max_tok * heads, head_dim]: one shape must serve the gather
|
||||
* (`heads` rows per token) and the projections (one `embed_dim` row per token). The gather
|
||||
* derives its row count as numel / width (r4d_rows_pitch), so [T, 2560] read at 160 is
|
||||
* T*16 rows. The GEMM takes M and K from the operand's shape (gemm_ops), so the tall shape
|
||||
* would give it M = T*16, K = 160 and the step would be refused. */
|
||||
RadBufDecl e{};
|
||||
e.dtype = g.act_dtype; e.rank = 2;
|
||||
e.shape[0] = g.max_tok; e.shape[1] = c.embed_dim;
|
||||
e.kind = RAD_BUF_TRANSIENT; e.domain = RAD_DOMAIN_HOST;
|
||||
b_emb = rad_decl_buffer(b, nm.f("ple_emb"), &e);
|
||||
}
|
||||
/* The device copy the projections read. A tiled GEMM reads each A row band once per column
|
||||
* block (80 times for the key projection), so reading `e` from the host arena repeats link
|
||||
* traffic: at a 2048-token chunk the projections take about 3.0 and 0.9 ms from the host arena
|
||||
* versus 1.4 and 0.3 ms from VRAM. The copy is 10.5 MB per chunk, 5 KB per token at decode. */
|
||||
b_embd = decl_b(b, nm.f("ple_emb_dev"), g.act_dtype, {g.max_tok, c.embed_dim});
|
||||
b_k = decl_b(b, nm.f("ple_k"), g.act_dtype, {g.max_tok, HN});
|
||||
b_v = decl_b(b, nm.f("ple_v"), g.act_dtype, {g.max_tok, g.n_embd});
|
||||
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;
|
||||
|
||||
/* State slots come from RadKVGroupBatch::state_index, filled per group by the step batch, as in
|
||||
* rad_block_gdn_fp8.h; the core's `conv_state_index` is not used.
|
||||
*
|
||||
* ---- the ops, in the order step() issues them ------------------------------------------- */
|
||||
layer_ = layer;
|
||||
|
||||
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: the gather fetches one table row per head per token, and the band resolves
|
||||
* on that count. */
|
||||
{
|
||||
const rad_weight wt[2] = { w_table, w_scale }; /* a bf16 table has no scale plane */
|
||||
op_gather = rw(b, RAD_OP(b, "embed_lookup_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * c.heads), RAD_INT("n_embd", HD),
|
||||
RAD_INT("n_vocab", c.rows), RAD_STR("dtype", g.dtype)),
|
||||
wt, table_bf16 ? 1 : 2),
|
||||
{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, un-normed; the op applies all three norms because the third is
|
||||
* over bytes it writes. */
|
||||
op_gate = rw(b, RAD_OP(b, "ple_gate",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("hc", c.hc), RAD_F64("eps", g.eps),
|
||||
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});
|
||||
|
||||
/* The add into the stream: `hidden_states + ple(...)`, where ple_conv's residual operand
|
||||
* already produced `gv + silu(conv)`. */
|
||||
op_add = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", HN),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
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;
|
||||
}
|
||||
|
||||
/* Slots come from the group batch, and `has_init` is `ctx_lens` (nonzero means a history), as in
|
||||
* rad_block_gdn_fp8.h.
|
||||
*
|
||||
* The two windowed ops are issued once per half of the step (batch_split: decode sequences
|
||||
* [0, D) with tokens [0, DT) first, then prefill). The decode half passes `num_accepted`, so the
|
||||
* op leaves its window readable after a partial rejection; the prefill half passes none and leaves
|
||||
* each chunk's tail at offset zero. The prefill half gets per-sequence arrays at `+ D` with token
|
||||
* operands at their base (kernels use the absolute offsets in `cu`); the decode half narrows to DT
|
||||
* rows.
|
||||
*
|
||||
* ids() runs first in the step, before every layer: it reads only the token ids and its own
|
||||
* window. The host gather that consumes it then waits for one small kernel, and the layers issued
|
||||
* in between keep the device busy during the gather. */
|
||||
inline void PleLayer::ids(RadCtx* c_, const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
const int64_t S = batch->n_seq;
|
||||
|
||||
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 following the last prefill chunk is hashed in the same launch into the rows
|
||||
* after the step's (`tok` reaches A tokens past the step); the window left behind is the
|
||||
* step's alone. */
|
||||
const int64_t A = P > 0 ? ahead_rows(batch) : 0;
|
||||
if (P > 0)
|
||||
RAD_ISSUE_N(c_, op_ids, T,
|
||||
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 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;
|
||||
|
||||
/* Operands are T rows (the gather derives its per-head rows from numel); the op's M band is
|
||||
* T * heads. The trailing operand is the following prompt's ids, which the gather's reader
|
||||
* prefetches for the next step. */
|
||||
const int64_t A = P > 0 ? ahead_rows(batch) : 0;
|
||||
RAD_ISSUE_N(c_, op_gather, T * c.heads,
|
||||
brows(b_ids, T), RAD_W(w_table), table_bf16 ? RAD_NONE : RAD_W(w_scale),
|
||||
brows(b_emb, T),
|
||||
A > 0 ? brow_slice(b_ids, T, A, c.heads) : RAD_NONE);
|
||||
|
||||
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 rows of `n`, not the element count, matching the declared band 1..max_tok. */
|
||||
RAD_ISSUE_N(c_, op_add, T, brows(w.h, T), brows(b_out, T), brows(w.h, T));
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_PLE_H */
|
||||
@@ -0,0 +1,402 @@
|
||||
/* 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. Qwen3-VL's deepstack taps (the residual stream after
|
||||
* named blocks, each through its own merger whose norm is taken after the 2x2 view, over
|
||||
* merge^2 * width, added to the language model's hidden state after its first layers) are declared
|
||||
* only for a plugin that passes `deepstack`; otherwise a tower with taps is refused. Every linear
|
||||
* is `gemm_nt_bias` with activation and residual in the epilogue, rounded where the reference's
|
||||
* separate tensors are.
|
||||
*
|
||||
* Every rank runs the whole tower with replicated weights: every rank embeds every token, and
|
||||
* sharding would cost a collective per layer for once-per-picture compute. Weights are
|
||||
* RAD_ACCESS_PER_REQUEST, so placement may keep them off the card when VRAM is short.
|
||||
*
|
||||
* Activations are sized by the pass (RadBuildCtx::max_enc_patches rows), except in a sizing
|
||||
* declare (shape_probe), which uses the probe's step to keep the tower out of the smaller arena
|
||||
* levels; an encoder pass always runs at the full plan (Engine::arena_step).
|
||||
*/
|
||||
#ifndef RAD_BLOCK_VIT_H
|
||||
#define RAD_BLOCK_VIT_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct VisionTower {
|
||||
/* Geometry, from the container's vision_config. */
|
||||
int64_t depth = 0, width = 0, heads = 0, ff = 0, patch = 0, temporal = 0, chans = 0;
|
||||
int64_t merge = 0, side = 0, n_embd = 0, head_dim = 0, patch_dim = 0, P = 0;
|
||||
float eps = 1e-6f, theta = 10000.0f;
|
||||
bool on = false;
|
||||
|
||||
struct Layer {
|
||||
rad_weight n1w = 0, n1b = 0, n2w = 0, n2b = 0;
|
||||
rad_weight qkv_w = 0, qkv_b = 0, out_w = 0, out_b = 0;
|
||||
rad_weight up_w = 0, up_b = 0, down_w = 0, down_b = 0;
|
||||
rad_op ln1 = 0, qkv = 0, rope = 0, attn = 0, proj = 0, ln2 = 0, up = 0, down = 0;
|
||||
};
|
||||
std::vector<Layer> L;
|
||||
rad_weight w_patch = 0, b_patch = 0, w_pos = 0;
|
||||
rad_weight mn_w = 0, mn_b = 0, m1_w = 0, m1_b = 0, m2_w = 0, m2_b = 0;
|
||||
rad_op op_patch = 0, op_pos = 0, op_mln = 0, op_m1 = 0, op_m2 = 0;
|
||||
rad_buf b_x = 0, b_h = 0, b_qkv = 0, b_att = 0, b_ff = 0, b_mh = 0, b_mf = 0, b_out = 0;
|
||||
char sec[48] = {};
|
||||
|
||||
/* Deepstack: tap t is the residual stream after block `ds_layer[t]`, merged into `b_ds[t]`
|
||||
* ([P / merge^2, n_embd], one row per merged token, in `b_out`'s order). */
|
||||
enum { MAX_DS = 4 };
|
||||
int n_ds = 0;
|
||||
int ds_layer[MAX_DS] = {};
|
||||
rad_weight ds_nw[MAX_DS] = {}, ds_nb[MAX_DS] = {}, ds_1w[MAX_DS] = {}, ds_1b[MAX_DS] = {};
|
||||
rad_weight ds_2w[MAX_DS] = {}, ds_2b[MAX_DS] = {};
|
||||
rad_op ds_ln[MAX_DS] = {}, ds_1[MAX_DS] = {}, ds_2[MAX_DS] = {};
|
||||
rad_buf b_ds[MAX_DS] = {};
|
||||
|
||||
/* Whether the container carries a vision tower. */
|
||||
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, bool deepstack = false);
|
||||
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, bool deepstack) {
|
||||
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's rows replace token embeddings, so they must be the model's width. */
|
||||
if (n_embd != model_embd) {
|
||||
fprintf(stderr, "radiance: the vision tower emits %lld-wide rows and the model embeds "
|
||||
"%lld-wide tokens\n", (long long)n_embd, (long long)model_embd);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* Deepstack feeds tower layers into the language model's early layers; a plugin that does not
|
||||
* consume it is refused the tower. */
|
||||
const char* ds = rad_meta_gets(m, "vision_config.deepstack_visual_indexes", "");
|
||||
n_ds = 0;
|
||||
for (const char* q = ds; q && *q;) {
|
||||
if (*q < '0' || *q > '9') { ++q; continue; }
|
||||
char* e = nullptr;
|
||||
const long v = std::strtol(q, &e, 10);
|
||||
q = e;
|
||||
if (!deepstack) {
|
||||
fprintf(stderr, "radiance: this vision tower has deepstack taps (%s), which this plugin "
|
||||
"does not serve\n", ds);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (n_ds >= MAX_DS || v < 0 || v >= depth) {
|
||||
fprintf(stderr, "radiance: deepstack taps '%s' do not fit a %lld-block tower\n", ds,
|
||||
(long long)depth);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
ds_layer[n_ds++] = (int)v;
|
||||
}
|
||||
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, even in a sizing declare. It
|
||||
* selects the kernel, and the engine runs the real declare's kernel at every level; only the
|
||||
* ranged row counts may follow the probe's step. */
|
||||
const int64_t max_seg = P;
|
||||
if (ctx->shape_probe) {
|
||||
/* A sizing declare: rows follow the probe's step (rounded to whole merged rows), keeping
|
||||
* the activations out of the levels a decode step runs at. */
|
||||
const int64_t r = std::min<int64_t>(P, ctx->max_tok);
|
||||
P = std::max<int64_t>(mm, r / mm * mm);
|
||||
}
|
||||
if (P % mm) return RAD_E_SHAPE;
|
||||
const int64_t R = P / mm;
|
||||
const int ACC = RAD_ACCESS_PER_REQUEST;
|
||||
|
||||
/* ---- weights, replicated. Model-level groups for the stem and merger; one group per block
|
||||
* from `first_group` on (past every language layer), so a tower block is its own movement
|
||||
* unit. */
|
||||
auto bw = [&](const char* dn, const char* src, uint32_t dt, std::initializer_list<int64_t> shp,
|
||||
RadWeightGroup g) -> rad_weight {
|
||||
/* map first: the weight's encoding is looked up through it */
|
||||
if (map_copy(b, dn, src) < 0) return 0;
|
||||
return decl_w(b, dn, dt, shp, ACC, RAD_SHARD_NONE, g);
|
||||
};
|
||||
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;
|
||||
for (int t = 0; t < n_ds; ++t) {
|
||||
const char* pre = "model.visual.deepstack_merger_list";
|
||||
ds_nw[t] = bw(nm.f("v.ds.%d.norm.weight", t), nm.ckpt("%s.%d.norm.weight", pre, t), RAD_BF16, { mm * width }, grp_model());
|
||||
ds_nb[t] = bw(nm.f("v.ds.%d.norm.bias", t), nm.ckpt("%s.%d.norm.bias", pre, t), RAD_BF16, { mm * width }, grp_model());
|
||||
ds_1w[t] = bw(nm.f("v.ds.%d.fc1.weight", t), nm.ckpt("%s.%d.linear_fc1.weight", pre, t), RAD_BF16, { mm * width, mm * width }, grp_model());
|
||||
ds_1b[t] = bw(nm.f("v.ds.%d.fc1.bias", t), nm.ckpt("%s.%d.linear_fc1.bias", pre, t), RAD_BF16, { mm * width }, grp_model());
|
||||
ds_2w[t] = bw(nm.f("v.ds.%d.fc2.weight", t), nm.ckpt("%s.%d.linear_fc2.weight", pre, t), RAD_BF16, { n_embd, mm * width }, grp_model());
|
||||
ds_2b[t] = bw(nm.f("v.ds.%d.fc2.bias", t), nm.ckpt("%s.%d.linear_fc2.bias", pre, t), RAD_BF16, { n_embd }, grp_model());
|
||||
if (!ds_nw[t] || !ds_nb[t] || !ds_1w[t] || !ds_1b[t] || !ds_2w[t] || !ds_2b[t])
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* ---- activations. `mh`, the merger's input, is declared at the merged width: the norm writes
|
||||
* P rows of `width` and the first merger layer reads the same bytes as P/mm rows of
|
||||
* mm * width (the reference's view(), no copy). */
|
||||
b_x = decl_b(b, nm.f("v.x"), RAD_BF16, { P, width });
|
||||
b_h = decl_b(b, nm.f("v.h"), RAD_BF16, { P, width });
|
||||
b_qkv = decl_b(b, nm.f("v.qkv"), RAD_BF16, { P, 3 * width });
|
||||
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 });
|
||||
/* A deepstack merger normalises after the view, over R rows of merge^2 * width. Its ops are
|
||||
* declared after the tower and issued between blocks; their working planes are consumed before
|
||||
* the next block. Each tap's output must survive until the language model reads it, so it is
|
||||
* PERSIST. */
|
||||
for (int t = 0; t < n_ds; ++t) {
|
||||
b_ds[t] = decl_b(b, nm.f("v.ds.%d.out", t), RAD_BF16, { R, n_embd }, RAD_BUF_PERSIST);
|
||||
if (!b_ds[t]) return RAD_E_INVAL;
|
||||
ds_ln[t] = rw(b, RAD_OP(b, "layernorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", mm * width),
|
||||
RAD_F64("eps", eps), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(ds_nw[t], ds_nb[t])),
|
||||
{ b_x }, { b_mh });
|
||||
ds_1[t] = rw(b, gemm(R, mm * width, mm * width, "gelu", ds_1w[t], ds_1b[t]), { b_mh }, { b_mf });
|
||||
ds_2[t] = rw(b, gemm(R, n_embd, mm * width, "none", ds_2w[t], ds_2b[t]), { b_mf }, { b_ds[t] });
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
/* Patches, coordinates (planes 0-1 a dense [2, P] of (row, column); all four a dense [4, P])
|
||||
* and segment boundaries, staged by the core. */
|
||||
const RadOperand pix = praw2(batch->enc_pixels, RAD_BF16, Pn, patch_dim);
|
||||
const RadOperand rc = praw2(batch->enc_coord, RAD_I32, 2, Pn);
|
||||
const RadOperand crd = praw2(batch->enc_coord, RAD_I32, 4, Pn);
|
||||
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 (size_t li = 0; li < L.size(); ++li) {
|
||||
const Layer& l = L[li];
|
||||
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));
|
||||
for (int t = 0; t < n_ds; ++t) {
|
||||
if (ds_layer[t] != (int)li) continue;
|
||||
RAD_ISSUE_N(c, ds_ln[t], Rn, brows(b_x, Pn), RAD_W(ds_nw[t]), RAD_W(ds_nb[t]),
|
||||
brows(b_mh, Rn));
|
||||
RAD_ISSUE_N(c, ds_1[t], Rn, brows(b_mh, Rn), RAD_W(ds_1w[t]), RAD_W(ds_1b[t]), RAD_NONE,
|
||||
brows(b_mf, Rn));
|
||||
RAD_ISSUE_N(c, ds_2[t], Rn, brows(b_mf, Rn), RAD_W(ds_2w[t]), RAD_W(ds_2b[t]), RAD_NONE,
|
||||
brows(b_ds[t], Rn));
|
||||
}
|
||||
}
|
||||
/* The merger norm writes P rows of `width`; the next layer reads them as P/mm merged rows. */
|
||||
RAD_ISSUE_N(c, op_mln, Pn, brows(b_x, Pn), RAD_W(mn_w), RAD_W(mn_b), brows(b_mh, Rn));
|
||||
RAD_ISSUE_N(c, op_m1, Rn, brows(b_mh, Rn), RAD_W(m1_w), RAD_W(m1_b), RAD_NONE,
|
||||
brows(b_mf, Rn));
|
||||
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
|
||||
*
|
||||
* Scatters encoder rows over the token embeddings they replace (RadBatch::mm_rows): one
|
||||
* `scatter_rows` of `n_embd` bf16 rows into the embedding buffer.
|
||||
*
|
||||
* Issue it before the embedding's reduction. The lookup is vocab-sharded, so each rank holds a
|
||||
* partial sum; the core gives rank 0 the encoder rows and other ranks zeros, so the following
|
||||
* reduction (an all_reduce, or the first layer's fused norm) counts each row once. */
|
||||
struct MediaRows {
|
||||
rad_op op = 0;
|
||||
int64_t n_embd = 0;
|
||||
|
||||
int declare(RadBuilder* b, int64_t max_tok, int64_t width, rad_buf embd) {
|
||||
n_embd = width;
|
||||
op = rw(b, RAD_OP(b, "scatter_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, max_tok), RAD_INT("n", width),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ embd }, { embd });
|
||||
return op ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* `embd` narrowed to this pass's tokens; nothing is issued on a pass with no media rows. */
|
||||
void step(RadCtx* c, const RadBatch* batch, rad_buf embd, int64_t T) const {
|
||||
if (!op || batch->n_mm_rows <= 0) return;
|
||||
RAD_ISSUE_N(c, op, batch->n_mm_rows,
|
||||
praw2(batch->mm_embd, RAD_BF16, batch->n_mm_rows, n_embd),
|
||||
praw(batch->mm_rows, RAD_I32, batch->n_mm_rows), brows(embd, T));
|
||||
}
|
||||
};
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_VIT_H */
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,61 @@
|
||||
/* rad_gemma4_chat.h -- Gemma 4's reply format (reasoning and tool calls) as data.
|
||||
*
|
||||
* Template analysis finds nothing in Gemma 4's chat template (llama.cpp uses a hand-written
|
||||
* handler), so without this the model would get no reasoning split and refuse tool requests.
|
||||
* This restates the model's tokenizer_config.json `response_template` in the engine's terms:
|
||||
*
|
||||
* thinking <|channel>thought\n ... <channel|>
|
||||
* tool calls <|tool_call>call:NAME{key:<|"|>text<|"|>,n:3,flag:true}<tool_call|>, repeated
|
||||
* the object unquoted keys, strings between <|"|> and <|"|> with their text verbatim, every
|
||||
* other value as JSON writes it
|
||||
* the turn ends at <turn|>; after its calls the model writes <|tool_response> and stops
|
||||
* (generation_config.json names it beside <eos> and <turn|>)
|
||||
*
|
||||
* The model also emits an extra thought channel after the answer and a lone <channel|>.
|
||||
* `reasoning_anywhere` reads the first as reasoning and drops the second.
|
||||
*
|
||||
* Shared because two plugins serve Gemma 4 (arch/gemma4 with bf16 and fp8 experts, arch/gemma4_bf16
|
||||
* for the CT-INT4 dense release) and the format belongs to the model; the reply-format tests read
|
||||
* this same declaration. */
|
||||
#pragma once
|
||||
#include "rad_builder.h"
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
inline const RadChatFormat* gemma4_chat_format() {
|
||||
static const char* const kBreaks[] = { "<|tool_call>" };
|
||||
static const char* const kTriggers[] = { "<|tool_call>" };
|
||||
static const RadChatFormat f = [] {
|
||||
RadChatFormat c{};
|
||||
c.struct_size = (uint32_t)sizeof(RadChatFormat);
|
||||
c.name = "plugin:gemma4";
|
||||
c.reasoning_open = "<|channel>thought\n";
|
||||
c.reasoning_close = "<channel|>";
|
||||
/* A call that starts inside an unclosed thought ends it there. */
|
||||
c.reasoning_breaks = kBreaks;
|
||||
c.n_reasoning_breaks = 1;
|
||||
/* Thinking off: the template closes an empty channel in the generation prompt. On: the
|
||||
* model opens its own, or the prompt has opened it after a tool response. */
|
||||
c.reasoning_in_prompt = RAD_CHAT_THINK_FROM_PROMPT;
|
||||
c.reasoning_anywhere = 1;
|
||||
|
||||
c.call_open = "<|tool_call>";
|
||||
c.call_close = "<tool_call|>";
|
||||
c.name_prefix = "call:";
|
||||
c.name_suffix = ""; /* the name ends at the object's `{` */
|
||||
c.call_end = ""; /* and the object's `}` ends the call */
|
||||
c.args_form = RAD_CHAT_ARGS_OBJECT;
|
||||
c.object_string_open = "<|\"|>";
|
||||
c.object_string_close = "<|\"|>";
|
||||
c.object_bare_keys = 1;
|
||||
|
||||
c.triggers = kTriggers;
|
||||
c.n_triggers = 1;
|
||||
return c;
|
||||
}();
|
||||
return &f;
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,435 @@
|
||||
/* rad_qsa.h -- Qwen4-Exp's QSA indexer: decides which blocks of key history a full-attention
|
||||
* layer's attention reads.
|
||||
*
|
||||
* docs/QSA.md has the design; this is the declaration side. The kernels are libr4d's
|
||||
* `qsa_block_key`, `qsa_score` and `qsa_select`; the sparse attention is the ordinary `attn_paged`
|
||||
* issued with the selection in place of the sequence's block table (both plain operands, so core/
|
||||
* knows nothing of QSA).
|
||||
*
|
||||
* Contents: the projection and query path, the block-key path with its two states, and the score
|
||||
* and selection. Below `budget + ratio - 1` tokens of context every visible block is selected, so
|
||||
* the sparse path must reproduce the dense path's text byte for byte; that is the test for any
|
||||
* change here.
|
||||
*/
|
||||
#ifndef RAD_QSA_H
|
||||
#define RAD_QSA_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
#include "rad_fp8.h"
|
||||
|
||||
#include <atomic>
|
||||
|
||||
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, shared by the indexer */
|
||||
const char* mode = "neox";
|
||||
/* Checkpoint names. Absent means this layer has no indexer and declare() is a no-op. */
|
||||
const char* qk_proj = nullptr;
|
||||
const char* q_norm = nullptr;
|
||||
const char* k_norm = nullptr;
|
||||
/* Derived; set by the caller because they size buffers it declares. */
|
||||
int64_t topk = 0; /* budget / ratio -- blocks the selection keeps */
|
||||
int64_t max_blocks = 0; /* max_ctx / ratio -- the widest block table */
|
||||
int64_t max_work = 0; /* ceil(max_tok / ratio) + max_seqs */
|
||||
/* The tail's ring length, `ratio + max_spec`. A ring of `ratio` indexed by `pos % ratio`
|
||||
* fails under speculation: the next step restarts at the first rejected position, so
|
||||
* overwritten slots are needed again (at ratio 4, depth 3, positions 9..12 write slots
|
||||
* 1,2,3,0 and 12 overwrites the slot of 8; accepting one then rebuilds block 2 from token
|
||||
* 12, corrupting that block key permanently). A step can still owe positions
|
||||
* [p0 - ratio + 1, p0 + n_spec], so `ratio + max_spec` slots keep every owed position. */
|
||||
int64_t ring = 0; /* ratio + max_spec */
|
||||
/* The attention group, whose page ids the selection outputs. The block-key group is
|
||||
* declared on first use (see declare()). */
|
||||
rad_kvgroup kv_attn = 0;
|
||||
/* The tail's group: one RAD_KV_LINEAR state per sequence per layer, `ring` rows of
|
||||
* `head_dim` (a KV group because it is per-sequence state; see Wire). */
|
||||
rad_kvgroup kv_tail = 0;
|
||||
/* Whether anything reads the selection. False on the dense path; the stateful block-key
|
||||
* half still runs so the sparse path can later read the history, but score and select (the
|
||||
* indexer's largest ops) are skipped. Declared either way, so the graph and buffer plan do
|
||||
* not depend on it. */
|
||||
bool emit_sel = true;
|
||||
/* The rows the score plane was declared with, 0 for max_tok. Fewer only where a step
|
||||
* wider than them is one sequence (RadBuildCtx::max_mixed_tok); such a step scores and
|
||||
* selects in windows of this many rows (step()). */
|
||||
int64_t plane_rows = 0;
|
||||
};
|
||||
|
||||
/* `qk` is the whole projection (`heads` query heads, then one raw key head); `q` is the query
|
||||
* heads normed and rotated, contiguous.
|
||||
*
|
||||
* The raw key is not normed or rotated here: it is pooled over `ratio` tokens first, and the
|
||||
* pooled result is normed and rotated at the block's first token's position (`qsa_block_key`),
|
||||
* unlike the q path. */
|
||||
struct Wire {
|
||||
rad_buf qk = 0; /* [max_tok, (heads + 1) * head_dim] */
|
||||
rad_buf q = 0; /* [max_tok, heads * head_dim] */
|
||||
/* These buffers are within-step scratch shared by every layer. The tail is not here: it
|
||||
* carries an unfinished block's raw index keys across steps, per layer (each layer has its
|
||||
* own `index_qk_proj`, the MTP head included) and per sequence (batch rows are step-local
|
||||
* and shift between steps). A KV group has a stable per-sequence slot, zeroed on hand-out
|
||||
* and checkpointed with the linear state by the prefix cache, so the tail is
|
||||
* `Config::kv_tail` (RAD_KV_LINEAR), bound to this layer in declare(). */
|
||||
rad_buf stage = 0; /* [max_work * ratio, head_dim] */
|
||||
rad_buf page = 0; /* [max_work] i32 */
|
||||
rad_buf bpos = 0; /* [max_work] i32, or [max_work, 3] under M-RoPE */
|
||||
rad_buf nc = 0; /* [max_seqs] i32 */
|
||||
/* The selection, one row per query, not per sequence (the same at decode; at prefill each
|
||||
* query of a chunk selects from the shared history, docs/QSA.md, "Per-query selection"). `sel` and
|
||||
* `seqused` replace the sequence's block table and length for the sparse attention.
|
||||
*
|
||||
* `score` is the largest: max_tok * max_ctx/ratio floats, 134 MB at a 2048-token chunk
|
||||
* and 64K context, one buffer for the whole model. A step of one sequence is tiled on the
|
||||
* query axis when it is wider than the plane (Config::plane_rows): a window of it is a
|
||||
* sequence of its own rows. A step of several is not: that would need a per-token
|
||||
* sequence id operand (from qsa_work), since `cu` is absolute over the batch. */
|
||||
rad_buf score = 0; /* [max_tok, max_blocks] f32 */
|
||||
rad_buf sel = 0; /* [max_tok, topk + 1] i32 */
|
||||
rad_buf nsel = 0; /* [max_tok] i32 */
|
||||
rad_buf sequ = 0; /* [max_tok] i32 */
|
||||
/* The model's cos/sin plane, [rope_table_rows, rot], or 0 if it builds none. Filled once a
|
||||
* step by `rope_table` for the attention block; the indexer rotates at the same `rot`,
|
||||
* `theta` and `scale`. Without it the unfused per-head norms run. */
|
||||
rad_buf cos_sin = 0;
|
||||
};
|
||||
|
||||
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;
|
||||
/* Most rows `op_qprep` may be issued over (0 when not declared): `qk_fuse_rows`, a correctness
|
||||
* bound, since the cos/sin table is filled only for steps at or under it. */
|
||||
int64_t qprep_rows = 0;
|
||||
rad_op op_work = 0, op_bkey = 0, op_tail = 0, op_score = 0, op_select = 0;
|
||||
|
||||
bool on() const { return op_rope != 0; }
|
||||
|
||||
/* `bk` is the block-key KV group, created on first use and shared by all QSA layers (hence
|
||||
* in/out). It must be declared immediately before `qsa_block_key`: `Builder::find_kv_consumer`
|
||||
* binds a group to the first later-declared op with a `block_size`. */
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Config& cfg,
|
||||
const Wire& wire, const ActFP8& in, rad_kvgroup* bk);
|
||||
/* `win_cu`, device: {0, plane_rows}, the one sequence of a window of a step wider than the
|
||||
* score plane (Config::plane_rows); null where no step is. */
|
||||
void step(RadCtx* c, const ActFP8& in, const RadBatch* batch,
|
||||
const int32_t* win_cu = nullptr) const;
|
||||
/* Stores the pass's block keys and tail exactly as step() does, with no query, score or
|
||||
* selection (see AttnGatedFP8::store_kv). */
|
||||
void store(RadCtx* c, const ActFP8& in, const RadBatch* batch) const;
|
||||
bool store_keys(RadCtx* c, const RadBatch* batch) const;
|
||||
};
|
||||
|
||||
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 layer's rotary width must fit inside the index head (as the checkpoint's validator also
|
||||
* requires). */
|
||||
if (c.rot < 0 || c.rot > c.head_dim || (c.rot & 1)) return RAD_E_SHAPE;
|
||||
|
||||
const int64_t nw = (c.heads + 1) * c.head_dim; /* the projection width */
|
||||
|
||||
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;
|
||||
|
||||
/* Unfused, one norm op is issued once per head: in `qk` (`heads + 1` heads wide) the query
|
||||
* heads are 128 apart within a token and 640 apart across tokens, which no rank-2 view can
|
||||
* express, but a one-head column slice can. It writes a contiguous `q` that the rope takes
|
||||
* whole. For 128-wide rows these launches are nearly all overhead.
|
||||
*
|
||||
* `op_qprep` fuses them (five launches to one) using `qk_norm_rope_gate`'s k side: it reads
|
||||
* [tokens, heads, head_dim] at the operand's row pitch, writes heads contiguously, and rounds
|
||||
* the norm to bf16 before rotating. With no gate, `n_head` 0 selects that half and passes no
|
||||
* q operands. It needs the model's cos/sin table (same `rot`, `theta`, `scale` as the
|
||||
* attention block) and is used only up to `qk_fuse_rows`, a correctness bound: the table is
|
||||
* filled only for steps that small, so a larger step would rotate by stale angles. The bound
|
||||
* comes from the same function as the attention block's. */
|
||||
const bool qprep_neox = !std::strcmp(c.mode, "neox") || !std::strcmp(c.mode, "mrope") ||
|
||||
g.rope_mc;
|
||||
qprep_rows = qk_fuse_rows(g);
|
||||
if (w.cos_sin && qprep_neox && qprep_rows > 0 && (c.head_dim % 32) == 0 &&
|
||||
rad_op_declared(b, "qk_norm_rope_gate"))
|
||||
op_qprep = rw(b, RAD_OP(b, "qk_norm_rope_gate",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qprep_rows),
|
||||
RAD_INT("head_dim", c.head_dim), RAD_INT("n_head", 0),
|
||||
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 caller's group holds one state per sequence per bound layer. */
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, c.kv_tail));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.qsa_k_norm.weight", l), c.k_norm));
|
||||
w_kn = decl_w(b, nm.f("blk.%d.qsa_k_norm.weight", l), RAD_F32, { c.head_dim },
|
||||
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 block-key group, declared immediately before its consumer (see the declaration). One KV
|
||||
* head, `block_size` = ratio and `head_dim` = n / (2 * ratio) make a page hold exactly one
|
||||
* block key of `n` values, one page per `ratio` tokens. */
|
||||
if (*bk == 0) {
|
||||
if ((c.head_dim % (2 * c.ratio)) != 0) return RAD_E_SHAPE;
|
||||
RadKVGroupDecl d{};
|
||||
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 given the step's rotary planes. */
|
||||
{
|
||||
const RadParam ps[] = { RAD_RANGE("M", 1, c.max_work), RAD_INT("n", c.head_dim),
|
||||
RAD_INT("ratio", c.ratio), RAD_INT("rotary_dim", c.rot),
|
||||
RAD_INT("block_size", c.ratio),
|
||||
RAD_F64("eps", g.eps), RAD_F64("theta", g.theta),
|
||||
RAD_F64("scale", g.rope_scale), RAD_F64("wadd", g.wadd_qk),
|
||||
RAD_STR("dtype", g.dtype), RAD_STR("mode", g.rope_mode),
|
||||
RAD_STR("sections", g.rope_sections) };
|
||||
const int n_ps = (int)(sizeof ps / sizeof ps[0]) - (g.rope_mc ? 0 : 2);
|
||||
op_bkey = rw(b, decl_rotary(b, g, "qsa_block_key", ps, n_ps, &w_kn, 1),
|
||||
{w.stage, w.page, w.bpos}, {});
|
||||
}
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, kv_bk));
|
||||
|
||||
op_tail = rw(b, RAD_OP(b, "qsa_tail_store",
|
||||
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 for both, up to a whole prefill chunk: the selection is per query. */
|
||||
op_score = rw(b, RAD_OP(b, "qsa_score",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", c.head_dim),
|
||||
RAD_INT("heads", c.heads), RAD_INT("blocks", c.max_blocks),
|
||||
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;
|
||||
}
|
||||
|
||||
/* Stores the block keys of the blocks the pass completes and the tail of raw keys after them,
|
||||
* from the projection's raw-key head. False when the step has no batch for the indexer's
|
||||
* groups. */
|
||||
inline bool QsaIndexer::store_keys(RadCtx* c_, const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok, S = batch->n_seq;
|
||||
const int64_t nw = (c.heads + 1) * c.head_dim;
|
||||
const int64_t koff = c.heads * c.head_dim; /* the raw-key head, after the query heads */
|
||||
const RadKVGroupBatch* bkb = kv_batch(batch, kv_bk);
|
||||
const RadKVGroupBatch* tlb = kv_batch(batch, c.kv_tail);
|
||||
if (!bkb || !tlb) return false;
|
||||
/* Column 0 of the state row is the committed slot; the row is wider when speculating (linear
|
||||
* groups get a second copy), so use the batch's pitch. */
|
||||
const int64_t tw = tlb->state_index_pitch > 0 ? tlb->state_index_pitch : 1;
|
||||
|
||||
/* Invariant: the work list runs before the tail store. The gather reads a completing block's
|
||||
* raw keys, up to `ratio - 1` of which are in the tail from earlier steps and are about to be
|
||||
* overwritten. The ring also spaces overwrites by `ring` positions, but the order still decides
|
||||
* what a straddling block reads. */
|
||||
const int64_t work = (T + c.ratio - 1) / c.ratio + S;
|
||||
/* Block positions: one component per block, or three under M-RoPE with planes. Under M-RoPE
|
||||
* `bpos` is [max_work, 3]; this step passes [work, 3], or only column 0 when the pass has no
|
||||
* planes (qsa_work then writes component 0 and the block key reads the one-component form). */
|
||||
const bool mc = g.rope_mc && batch->rope_pos;
|
||||
RadOperand bpos = g.rope_mc ? RAD_B_COL(w.bpos, 0, mc ? 3 : 1) : brows(w.bpos, work);
|
||||
if (g.rope_mc) bpos.rows = work;
|
||||
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));
|
||||
return true;
|
||||
}
|
||||
|
||||
inline void QsaIndexer::store(RadCtx* c_, const ActFP8& in, const RadBatch* batch) const {
|
||||
if (!on()) return;
|
||||
proj.step(c_, in, w.qk, batch->n_tok);
|
||||
(void)store_keys(c_, batch);
|
||||
}
|
||||
|
||||
inline void QsaIndexer::step(RadCtx* c_, const ActFP8& in, const RadBatch* batch,
|
||||
const int32_t* win_cu) const {
|
||||
if (!on()) return;
|
||||
const int64_t T = batch->n_tok, S = batch->n_seq;
|
||||
const int64_t qw = c.heads * c.head_dim;
|
||||
const int64_t nw = (c.heads + 1) * c.head_dim;
|
||||
|
||||
proj.step(c_, in, w.qk, T);
|
||||
/* One fused launch or `heads` + 1 unfused. The fused form takes the whole projection at its
|
||||
* row pitch and writes the query heads contiguous and rotated. `n_head` 0 is the k-only form:
|
||||
* no q_gate, q_w or q_out, and `gate_out` absent. `T <= qprep_rows` is a correctness bound
|
||||
* (see declare()). */
|
||||
if (op_qprep && T <= qprep_rows && !rope_mixed(batch)) {
|
||||
RAD_ISSUE_N(c_, op_qprep, T,
|
||||
RAD_NONE, brows(w.qk, T), RAD_B(w.cos_sin), rope_pos1(batch, T),
|
||||
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));
|
||||
}
|
||||
|
||||
/* The keys first: the selection below reads the blocks they complete. */
|
||||
const RadKVGroupBatch* bkb = kv_batch(batch, kv_bk);
|
||||
const RadKVGroupBatch* atb = kv_batch(batch, c.kv_attn);
|
||||
if (!atb || !store_keys(c_, batch)) return;
|
||||
|
||||
/* Score and select per query: both ops take `cu`, the block table stays per sequence, and `m`
|
||||
* is a query row, so each query of a prefill chunk selects from the shared history, as the
|
||||
* checkpoint does. */
|
||||
if (!c.emit_sel) return;
|
||||
|
||||
/* Narrow the score columns to the live history. Both kernels size their grid from the
|
||||
* operand's width (the live count is device data), so the full `max_ctx` width would make a
|
||||
* 2000-token prompt walk 50000 block slots; the pitch stays declared, only the column count
|
||||
* moves.
|
||||
*
|
||||
* This must be an upper bound: an underestimate silently drops blocks. A query has at most
|
||||
* (position + 1) / ratio complete blocks; positions are bounded by the host context bound plus
|
||||
* the step's tokens plus the draft window; the +1 keeps `n < nb` so the partial page `bt[n]`
|
||||
* is readable. */
|
||||
const int64_t reach = (int64_t)batch->max_ctx_len + batch->n_tok + batch->n_spec + c.ratio;
|
||||
int64_t live = reach / c.ratio + 1;
|
||||
if (live > c.max_blocks) live = c.max_blocks;
|
||||
if (live < 1) live = 1;
|
||||
|
||||
/* A step wider than the score plane is one sequence (Config::plane_rows), scored and selected
|
||||
* in windows of the plane's rows from the front, the last one ending at the step's end and
|
||||
* overlapping the one before. A window is handed as a sequence of its own rows (`win_cu` =
|
||||
* {0, rows}). Every operand a query row reads is its own (query, position, selection) and the
|
||||
* block table and complete-block count are the step's, so each row is scored and selected as
|
||||
* in one pass over the step, and a row two windows share is written twice with the same
|
||||
* bytes. */
|
||||
const int64_t PR = c.plane_rows > 0 ? c.plane_rows : T;
|
||||
if (T > PR) {
|
||||
if (S != 1 || !win_cu) {
|
||||
rad_step_fail(c_, "qsa: a step wider than the score plane must be one sequence with "
|
||||
"its window bounds (RadBuildCtx::max_mixed_tok)");
|
||||
return;
|
||||
}
|
||||
for (int64_t w0 = 0;;) {
|
||||
RAD_ISSUE_N(c_, op_score, PR,
|
||||
brow_slice(w.q, w0, PR, qw), kv_cache(kv_bk, layer),
|
||||
praw2(bkb->block_table, RAD_I32, S, bkb->block_table_pitch),
|
||||
praw(win_cu, RAD_I32, 2), brows(w.nc, S),
|
||||
bcol_at(w.score, 0, c.max_blocks, 0, live, PR));
|
||||
RAD_ISSUE_N(c_, op_select, PR,
|
||||
bcol_at(w.score, 0, c.max_blocks, 0, live, PR),
|
||||
praw2(atb->block_table, RAD_I32, S, atb->block_table_pitch),
|
||||
brows(w.nc, S), praw(batch->positions + w0, RAD_I32, PR),
|
||||
praw(win_cu, RAD_I32, 2),
|
||||
brow_slice(w.sel, w0, PR, c.topk + 1), brow_slice(w.nsel, w0, PR, 1),
|
||||
brow_slice(w.sequ, w0, PR, 1));
|
||||
if (w0 + PR >= T) break;
|
||||
w0 = w0 + PR + PR <= T ? w0 + PR : T - PR;
|
||||
}
|
||||
return;
|
||||
}
|
||||
RAD_ISSUE_N(c_, op_score, T,
|
||||
brows(w.q, T), kv_cache(kv_bk, layer),
|
||||
praw2(bkb->block_table, RAD_I32, S, bkb->block_table_pitch),
|
||||
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: prints the first few selections (nc, nsel, sequ, leading sel and score
|
||||
* entries) to tell a divergence from intended dropping (`nc` above `topk`). Synchronises the
|
||||
* stream; off unless set. */
|
||||
static const bool dbg = std::getenv("RADIANCE_DEBUG_QSA") != nullptr;
|
||||
if (dbg) {
|
||||
static std::atomic<int> seen{0};
|
||||
if (seen.fetch_add(1) < 6) {
|
||||
rad_stream_sync(rad_stream(c_));
|
||||
std::vector<int32_t> hnc(1), hns(1), hsu(1), hsel(8);
|
||||
std::vector<float> hsc(8);
|
||||
rad_memcpy_async(hnc.data(), rad_buf_ptr(c_, w.nc), 4, rad_stream(c_));
|
||||
rad_memcpy_async(hns.data(), rad_buf_ptr(c_, w.nsel), 4, rad_stream(c_));
|
||||
rad_memcpy_async(hsu.data(), rad_buf_ptr(c_, w.sequ), 4, rad_stream(c_));
|
||||
rad_memcpy_async(hsel.data(), rad_buf_ptr(c_, w.sel), 32, rad_stream(c_));
|
||||
rad_memcpy_async(hsc.data(), rad_buf_ptr(c_, w.score), 32, rad_stream(c_));
|
||||
rad_stream_sync(rad_stream(c_));
|
||||
std::fprintf(stderr, "D qsa L%d nc=%d nsel=%d sequ=%d sel[%d %d %d %d] "
|
||||
"score[%.4g %.4g %.4g %.4g]\n", layer,
|
||||
hnc[0], hns[0], hsu[0], hsel[0], hsel[1], hsel[2], hsel[3],
|
||||
hsc[0], hsc[1], hsc[2], hsc[3]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_QSA_H */
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/embgemma2 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(embgemma2 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(embgemma2 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/embgemma2.cpp)
|
||||
@@ -0,0 +1,913 @@
|
||||
/* embgemma2 -- EmbeddingGemma 2, a bidirectional Gemma encoder that pools a whole input into one
|
||||
* vector. bf16 weights and bf16 activations.
|
||||
*
|
||||
* An embedding model: it declares a pooled output (rad_declare_pooled) and no logits, so the
|
||||
* engine runs it with no sampler and no KV cache, carries every input whole in one step, and
|
||||
* returns each sequence's pooled row. Attention is bidirectional on every layer, so nothing is
|
||||
* paged: a token attends to later tokens, and there is nothing to carry between steps.
|
||||
*
|
||||
* ============================== THE SHAPE ==============================
|
||||
*
|
||||
* 24 layers, hidden 512, ffn 2048, vocab 262144, embedding scale sqrt(512) rounded to bf16
|
||||
* layer_types: five `sliding_attention` then one `full_attention`, four times over
|
||||
* sliding: 4 heads / 2 kv heads / head_dim 256, rope theta 1e4, |i - j| <= 512
|
||||
* full: 4 heads / 1 kv head / head_dim 512, rope theta 1e6, the whole input
|
||||
* attention scale 1.0 (the q/k norms carry the temperature); q, k and v are RMS-normed per head,
|
||||
* v with no gain
|
||||
* Gemma's sandwich norms: a norm before and after attention and the feed-forward, all plain
|
||||
* RMSNorm gains (x_hat * w, not 1 + w)
|
||||
* a gated gelu-tanh feed-forward
|
||||
* per-layer embeddings, projection-only: the token embedding projected to 24 x 512, normed, and
|
||||
* each layer's slice gating that layer's residual through a 512 -> 512 -> 512 bottleneck
|
||||
* a learned scalar per layer, multiplying the residual stream at the layer's end
|
||||
* final norm, then the mean over every token of the input, then 512 -> 768
|
||||
*
|
||||
* The reference is transformers' modeling_embedding_gemma2 (model_type embedding_gemma2, which
|
||||
* rad-convert spells `embeddinggemma2`). Its mean pooling and normalisation are
|
||||
* sentence-transformers' modules on top; normalisation is the server's (it truncates to
|
||||
* `dimensions` first), so the pooled row here is the unnormalised mean.
|
||||
*
|
||||
* Everything the checkpoint carries is declared: the text model, the vision tower
|
||||
* (rad_block_gemma4_vision.h) and the audio encoder.
|
||||
*/
|
||||
#include <arch/rad_arch.h>
|
||||
#include <arch/rad_block_gemma4_vision.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
namespace embgemma2 {
|
||||
|
||||
using namespace rad::arch;
|
||||
|
||||
/* What a layer's attention is: the two kinds differ in head width, KV head count, rotary base and
|
||||
* window, and nothing else. */
|
||||
struct Kind {
|
||||
int64_t head_dim = 0;
|
||||
int64_t n_head = 0;
|
||||
int64_t n_head_kv = 0;
|
||||
double theta = 0.0;
|
||||
int64_t window = 0; /* attn_dense's `window`: |i - j| < window, 0 the whole input */
|
||||
int64_t qkv() const { return (n_head + 2 * n_head_kv) * head_dim; }
|
||||
int64_t q() const { return n_head * head_dim; }
|
||||
};
|
||||
|
||||
struct Layer {
|
||||
int full = 0;
|
||||
rad_weight w_in_norm = 0, w_qkv = 0, w_q_norm = 0, w_k_norm = 0, w_o = 0, w_post_attn = 0;
|
||||
rad_weight w_pre_ff = 0, w_gate_up = 0, w_down = 0, w_post_ff = 0;
|
||||
rad_weight w_ple_gate = 0, w_ple_proj = 0, w_post_ple = 0, w_scalar = 0;
|
||||
rad_op op_in_norm = 0, op_qkv = 0, op_qk = 0, op_attn = 0, op_o = 0, op_post_attn = 0;
|
||||
rad_op op_add_attn = 0, op_pre_ff = 0, op_gate_up = 0, op_act = 0, op_down = 0;
|
||||
rad_op op_post_ff = 0, op_add_ff = 0, op_ple_gate = 0, op_ple_act = 0, op_ple_proj = 0;
|
||||
rad_op op_post_ple = 0, op_add_ple = 0, op_scale = 0;
|
||||
};
|
||||
|
||||
/* ============================== THE AUDIO ENCODER (Gemma 4's USM conformer) ==============================
|
||||
*
|
||||
* a frame is 128 log-mel bins (the processor's), four frames an output row
|
||||
* subsampling: two 3x3 stride-2 convolutions over (time, frequency) -- 1 -> 128 -> 32 channels,
|
||||
* each input masked to the clip's real frames first, each followed by a channel LayerNorm (no
|
||||
* bias) and a ReLU -- then 32 x 32 features a row through a 1024 linear
|
||||
* 12 conformer blocks: a feed-forward at half weight, local attention (11 frames back, a
|
||||
* relative-position term, a softplus per-dimension query scale, a softcap of 50), a gated
|
||||
* depthwise causal convolution, a second half-weight feed-forward, a norm; their linears are
|
||||
* clipped: input and output clamped to bounds the checkpoint stores
|
||||
* 1024 -> 1536 with a bias, then the multimodal embedder: an RMS norm with no gain, 1536 -> 512.
|
||||
*
|
||||
* The blocks' clamps at +-1e10 ("gradient clipping") are omitted: they are ten orders of magnitude
|
||||
* beyond the activations' range and change nothing. One clip is one segment; a pass carries up to
|
||||
* RadBuildCtx::max_audio_frames frames. */
|
||||
struct Audio {
|
||||
/* A clipped linear: the weight and its four bounds. */
|
||||
struct Clip {
|
||||
rad_weight w = 0, in_lo = 0, in_hi = 0, out_lo = 0, out_hi = 0;
|
||||
rad_op op_in = 0, op_mm = 0, op_out = 0;
|
||||
};
|
||||
struct FF {
|
||||
rad_weight pre = 0, post = 0;
|
||||
Clip l1, l2;
|
||||
rad_op op_pre = 0, op_act = 0, op_post = 0, op_add = 0;
|
||||
};
|
||||
struct Layer {
|
||||
FF ff1, ff2;
|
||||
rad_weight n_pre_attn = 0, n_post_attn = 0, n_out = 0, w_rel = 0, pds = 0;
|
||||
Clip q, k, v, post;
|
||||
rad_weight lc_pre = 0, lc_dw = 0, lc_norm = 0;
|
||||
Clip lc_start, lc_end;
|
||||
rad_op op_npa = 0, op_rel = 0, op_attn = 0, op_npo = 0, op_add_attn = 0;
|
||||
rad_op op_lc_pre = 0, op_glu = 0, op_dw = 0, op_lc_norm = 0, op_lc_act = 0, op_lc_add = 0;
|
||||
rad_op op_out = 0;
|
||||
};
|
||||
bool on = false;
|
||||
int64_t P = 0, R = 0, H = 0, heads = 0, hd = 0, ffw = 0, n_embd = 0, out_dims = 0;
|
||||
int64_t c0 = 0, c1 = 0, nmel = 0, merge = 4, left = 0, chunk = 0, n_rel = 0;
|
||||
double eps = 1e-6, softcap = 0;
|
||||
rad_weight w_c0 = 0, w_c1 = 0, w_n0 = 0, w_n1 = 0, w_in = 0, w_out = 0, b_outw = 0, w_emb = 0;
|
||||
rad_op op_c0 = 0, op_n0 = 0, op_r0 = 0, op_c1 = 0, op_n1 = 0, op_r1 = 0, op_in = 0;
|
||||
rad_op op_relpos = 0, op_outp = 0, op_en = 0, op_emb = 0;
|
||||
rad_buf b_s0 = 0, b_s1 = 0, b_x = 0, b_h = 0, b_hc = 0, b_f = 0, b_q = 0, b_k = 0, b_v = 0;
|
||||
rad_buf b_att = 0, b_o = 0, b_g = 0, b_u = 0, b_relpos = 0, b_relk = 0, b_o2 = 0, b_on = 0;
|
||||
rad_buf b_out = 0;
|
||||
std::vector<Layer> L;
|
||||
|
||||
static bool present(const RadModelMeta* m) {
|
||||
const char* t = rad_meta_gets(m, "audio_config.model_type", "");
|
||||
return t && !std::strcmp(t, "gemma4_audio");
|
||||
}
|
||||
/* The longest clip in frames: 30 s at the extractor's 10 ms hop, rounded up to whole rows. */
|
||||
static int64_t frames_for(const RadModelMeta* m) {
|
||||
const int64_t rate = rad_meta_geti(m, "preprocessor.sampling_rate", 16000);
|
||||
const int64_t fl = rad_meta_geti(m, "preprocessor.frame_length", 320);
|
||||
const int64_t hop = rad_meta_geti(m, "preprocessor.hop_length", 160);
|
||||
if (rate <= 0 || hop <= 0) return 0;
|
||||
const int64_t n = 30 * rate;
|
||||
const int64_t real = (n + fl / 2 - fl - 1) / hop + 1;
|
||||
return (real + 3) / 4 * 4;
|
||||
}
|
||||
|
||||
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
|
||||
int64_t model_embd, int first_group) {
|
||||
on = false;
|
||||
if (!present(m) || ctx->max_audio_frames <= 0) return RAD_OK;
|
||||
const char* A = "audio_config";
|
||||
auto gi = [&](const char* k, int64_t d) {
|
||||
char key[96];
|
||||
std::snprintf(key, sizeof key, "%s.%s", A, k);
|
||||
return rad_meta_geti(m, key, d);
|
||||
};
|
||||
auto gf = [&](const char* k, double d) {
|
||||
char key[96];
|
||||
std::snprintf(key, sizeof key, "%s.%s", A, k);
|
||||
return rad_meta_getf(m, key, d);
|
||||
};
|
||||
H = gi("hidden_size", 0);
|
||||
heads = gi("num_attention_heads", 0);
|
||||
out_dims = gi("output_proj_dims", 0);
|
||||
chunk = gi("attention_chunk_size", 0);
|
||||
/* transformers masks a key unless 0 <= q - k < attention_context_left - 1, so the
|
||||
* furthest key back is context_left - 2 frames: 11 for this checkpoint, the query and
|
||||
* eleven before it. */
|
||||
left = gi("attention_context_left", 0) - 2;
|
||||
softcap = gf("attention_logit_cap", 0.0);
|
||||
eps = gf("rms_norm_eps", 1e-6);
|
||||
const int64_t depth = gi("num_hidden_layers", 0);
|
||||
const int64_t kconv = gi("conv_kernel_size", 0);
|
||||
const int64_t right = gi("attention_context_right", 0);
|
||||
const double resw = gf("residual_weight", 0.0);
|
||||
const char* act = rad_meta_gets(m, "audio_config.hidden_act", "");
|
||||
const char* chs = rad_meta_gets(m, "audio_config.subsampling_conv_channels", "");
|
||||
nmel = rad_meta_geti(m, "preprocessor.feature_size", 0);
|
||||
if (std::sscanf(chs ? chs : "", "%lld %lld", (long long*)&c0, (long long*)&c1) != 2)
|
||||
c0 = c1 = 0;
|
||||
hd = heads > 0 ? H / heads : 0;
|
||||
ffw = 4 * H;
|
||||
n_rel = left + 1;
|
||||
if (H <= 0 || heads <= 0 || hd * heads != H || out_dims <= 0 || depth <= 0 || kconv <= 0 ||
|
||||
chunk <= 0 || left < 0 || right != 0 || !(softcap > 0) || resw != 0.5 ||
|
||||
std::strcmp(act ? act : "", "silu") || c0 <= 0 || c1 <= 0 || nmel != 128 ||
|
||||
(nmel / 4) * c1 != H) {
|
||||
fprintf(stderr, "radiance: embgemma2: the container's audio_config is not the "
|
||||
"conformer this plugin serves (hidden %lld, heads %lld, output %lld, "
|
||||
"layers %lld, conv %lld, left %lld right %lld, residual %g, act %s, "
|
||||
"subsampling %lld/%lld over %lld bins)\n", (long long)H,
|
||||
(long long)heads, (long long)out_dims, (long long)depth, (long long)kconv,
|
||||
(long long)left, (long long)right, resw, act ? act : "", (long long)c0,
|
||||
(long long)c1, (long long)nmel);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
n_embd = model_embd;
|
||||
P = ctx->max_audio_frames;
|
||||
if (P % merge) return RAD_E_SHAPE;
|
||||
R = P / merge;
|
||||
const int AC = RAD_ACCESS_PER_REQUEST, N = RAD_SHARD_NONE;
|
||||
const char* T = "audio_tower";
|
||||
|
||||
/* ---- weights */
|
||||
auto w = [&](const char* dn, const char* src, std::initializer_list<int64_t> shp,
|
||||
RadWeightGroup g) -> rad_weight {
|
||||
if (map_copy(b, dn, src) < 0) return 0;
|
||||
return decl_w(b, dn, RAD_BF16, shp, AC, N, g);
|
||||
};
|
||||
auto clip = [&](Clip& c, const char* dn, const char* src, int64_t out, int64_t in,
|
||||
RadWeightGroup g) {
|
||||
char d1[160], s1[200];
|
||||
std::snprintf(d1, sizeof d1, "%s.w", dn); std::snprintf(s1, sizeof s1, "%s.linear.weight", src);
|
||||
c.w = w(nm.f("%s", d1), nm.ckpt("%s", s1), {out, in}, g);
|
||||
const char* bn[4] = { "input_min", "input_max", "output_min", "output_max" };
|
||||
rad_weight* dst[4] = { &c.in_lo, &c.in_hi, &c.out_lo, &c.out_hi };
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
std::snprintf(d1, sizeof d1, "%s.%s", dn, bn[i]);
|
||||
std::snprintf(s1, sizeof s1, "%s.%s", src, bn[i]);
|
||||
*dst[i] = w(nm.f("%s", d1), nm.ckpt("%s", s1), {1}, g);
|
||||
}
|
||||
};
|
||||
w_c0 = w(nm.f("a.sscp.c0"), nm.ckpt("%s.subsample_conv_projection.layer0.conv.weight", T), {c0, 1, 3, 3}, grp_model());
|
||||
w_n0 = w(nm.f("a.sscp.n0"), nm.ckpt("%s.subsample_conv_projection.layer0.norm.weight", T), {c0}, grp_model());
|
||||
w_c1 = w(nm.f("a.sscp.c1"), nm.ckpt("%s.subsample_conv_projection.layer1.conv.weight", T), {c1, c0, 3, 3}, grp_model());
|
||||
w_n1 = w(nm.f("a.sscp.n1"), nm.ckpt("%s.subsample_conv_projection.layer1.norm.weight", T), {c1}, grp_model());
|
||||
w_in = w(nm.f("a.sscp.proj"), nm.ckpt("%s.subsample_conv_projection.input_proj_linear.weight", T), {H, H}, grp_model());
|
||||
w_out = w(nm.f("a.out.w"), nm.ckpt("%s.output_proj.weight", T), {out_dims, H}, grp_model());
|
||||
b_outw = w(nm.f("a.out.b"), nm.ckpt("%s.output_proj.bias", T), {out_dims}, grp_model());
|
||||
w_emb = w(nm.f("a.embed"), nm.ckpt("embed_audio.embedding_projection.weight"), {n_embd, out_dims}, grp_model());
|
||||
L.assign((size_t)depth, Layer{});
|
||||
for (int64_t i = 0; i < depth; ++i) {
|
||||
Layer& l = L[(size_t)i];
|
||||
const long long li = (long long)i;
|
||||
const RadWeightGroup g = grp_layer(first_group + (int)i);
|
||||
char d[96], s[160];
|
||||
auto D = [&](const char* x) { std::snprintf(d, sizeof d, "a.blk.%lld.%s", li, x); return nm.f("%s", d); };
|
||||
auto S = [&](const char* x) { std::snprintf(s, sizeof s, "%s.layers.%lld.%s", T, li, x); return nm.ckpt("%s", s); };
|
||||
for (int f = 0; f < 2; ++f) {
|
||||
FF& ff = f ? l.ff2 : l.ff1;
|
||||
const char* fn = f ? "feed_forward2" : "feed_forward1";
|
||||
char px[64]; std::snprintf(px, sizeof px, "%s.pre_layer_norm.weight", fn);
|
||||
ff.pre = w(D(px), S(px), {H}, g);
|
||||
std::snprintf(px, sizeof px, "%s.post_layer_norm.weight", fn);
|
||||
ff.post = w(D(px), S(px), {H}, g);
|
||||
char dn[96], sn[160];
|
||||
std::snprintf(dn, sizeof dn, "a.blk.%lld.%s.l1", li, fn);
|
||||
std::snprintf(sn, sizeof sn, "%s.layers.%lld.%s.ffw_layer_1", T, li, fn);
|
||||
clip(ff.l1, dn, sn, ffw, H, g);
|
||||
std::snprintf(dn, sizeof dn, "a.blk.%lld.%s.l2", li, fn);
|
||||
std::snprintf(sn, sizeof sn, "%s.layers.%lld.%s.ffw_layer_2", T, li, fn);
|
||||
clip(ff.l2, dn, sn, H, ffw, g);
|
||||
}
|
||||
l.n_pre_attn = w(D("norm_pre_attn"), S("norm_pre_attn.weight"), {H}, g);
|
||||
l.n_post_attn = w(D("norm_post_attn"), S("norm_post_attn.weight"), {H}, g);
|
||||
l.n_out = w(D("norm_out"), S("norm_out.weight"), {H}, g);
|
||||
l.w_rel = w(D("rel_k"), S("self_attn.relative_k_proj.weight"), {H, H}, g);
|
||||
l.pds = w(D("per_dim_scale"), S("self_attn.per_dim_scale"), {hd}, g);
|
||||
const char* qn[4] = { "q_proj", "k_proj", "v_proj", "post" };
|
||||
Clip* qc[4] = { &l.q, &l.k, &l.v, &l.post };
|
||||
for (int j = 0; j < 4; ++j) {
|
||||
char dn[96], sn[160];
|
||||
std::snprintf(dn, sizeof dn, "a.blk.%lld.attn.%s", li, qn[j]);
|
||||
std::snprintf(sn, sizeof sn, "%s.layers.%lld.self_attn.%s", T, li, qn[j]);
|
||||
clip(*qc[j], dn, sn, H, H, g);
|
||||
}
|
||||
l.lc_pre = w(D("lconv.pre"), S("lconv1d.pre_layer_norm.weight"), {H}, g);
|
||||
l.lc_dw = w(D("lconv.dw"), S("lconv1d.depthwise_conv1d.weight"), {H, 1, kconv}, g);
|
||||
l.lc_norm = w(D("lconv.norm"), S("lconv1d.conv_norm.weight"), {H}, g);
|
||||
{
|
||||
char dn[96], sn[160];
|
||||
std::snprintf(dn, sizeof dn, "a.blk.%lld.lconv.start", li);
|
||||
std::snprintf(sn, sizeof sn, "%s.layers.%lld.lconv1d.linear_start", T, li);
|
||||
clip(l.lc_start, dn, sn, 2 * H, H, g);
|
||||
std::snprintf(dn, sizeof dn, "a.blk.%lld.lconv.end", li);
|
||||
std::snprintf(sn, sizeof sn, "%s.layers.%lld.lconv1d.linear_end", T, li);
|
||||
clip(l.lc_end, dn, sn, H, H, g);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- activations: the subsampler's planes at their own widths, the blocks' at R rows */
|
||||
b_s0 = decl_b(b, nm.f("a.s0"), RAD_BF16, {P / 2, (nmel / 2) * c0});
|
||||
b_s1 = decl_b(b, nm.f("a.s1"), RAD_BF16, {R, (nmel / 4) * c1});
|
||||
b_x = decl_b(b, nm.f("a.x"), RAD_BF16, {R, H});
|
||||
b_h = decl_b(b, nm.f("a.h"), RAD_BF16, {R, H});
|
||||
b_hc = decl_b(b, nm.f("a.hc"), RAD_BF16, {R, H});
|
||||
b_f = decl_b(b, nm.f("a.f"), RAD_BF16, {R, ffw});
|
||||
b_q = decl_b(b, nm.f("a.q"), RAD_BF16, {R, H});
|
||||
b_k = decl_b(b, nm.f("a.k"), RAD_BF16, {R, H});
|
||||
b_v = decl_b(b, nm.f("a.v"), RAD_BF16, {R, H});
|
||||
b_att = decl_b(b, nm.f("a.att"), RAD_BF16, {R, H});
|
||||
b_o = decl_b(b, nm.f("a.o"), RAD_BF16, {R, H});
|
||||
b_g = decl_b(b, nm.f("a.g"), RAD_BF16, {R, 2 * H});
|
||||
b_u = decl_b(b, nm.f("a.u"), RAD_BF16, {R, H});
|
||||
b_relpos = decl_b(b, nm.f("a.relpos"), RAD_BF16, {n_rel, H});
|
||||
b_relk = decl_b(b, nm.f("a.relk"), RAD_BF16, {n_rel, H});
|
||||
b_o2 = decl_b(b, nm.f("a.o2"), RAD_BF16, {R, out_dims});
|
||||
b_on = decl_b(b, nm.f("a.on"), RAD_BF16, {R, out_dims});
|
||||
b_out = decl_b(b, nm.f("a.out"), RAD_BF16, {R, n_embd});
|
||||
|
||||
auto gemm = [&](int64_t rows, int64_t Nn, int64_t K, rad_weight wt) {
|
||||
return RAD_OP(b, "gemm_nt", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", Nn),
|
||||
RAD_INT("K", K), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(wt));
|
||||
};
|
||||
auto rms = [&](int64_t rows, int64_t n, rad_weight wt, double mult) {
|
||||
if (!wt)
|
||||
return RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_F64("eps", eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
return RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_F64("eps", eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", "bf16"), RAD_F64("mult", mult)),
|
||||
RAD_WEIGHTS(wt));
|
||||
};
|
||||
auto clamp = [&](int64_t rows, int64_t n, rad_weight lo, rad_weight hi) {
|
||||
return RAD_OP(b, "clamp", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(lo, hi));
|
||||
};
|
||||
auto unary = [&](const char* op, int64_t rows, int64_t n) {
|
||||
return RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
auto add = [&](int64_t rows, int64_t n) { return unary("add", rows, n); };
|
||||
auto lnorm = [&](int64_t rows, int64_t n, rad_weight g) {
|
||||
return RAD_OP(b, "layernorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_F64("eps", eps), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(g));
|
||||
};
|
||||
auto conv = [&](int64_t rows, int64_t width, int64_t ci, int64_t co, int64_t cu_div,
|
||||
int64_t vstride, rad_weight wt) {
|
||||
return RAD_OP(b, "conv2d", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("width", width),
|
||||
RAD_INT("cin", ci), RAD_INT("cout", co),
|
||||
RAD_INT("kh", 3), RAD_INT("kw", 3),
|
||||
RAD_INT("stride", 2), RAD_INT("pad", 1),
|
||||
RAD_INT("cu_div", cu_div),
|
||||
RAD_INT("valid_stride", vstride),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(wt));
|
||||
};
|
||||
/* A clipped linear over rows of `in` into `out`: the input clamp writes a copy (the input
|
||||
* feeds several projections, each with its own bounds), the output clamp is in place. The
|
||||
* copy is a whole [R, n_in] buffer, since a GEMM's input must be contiguous. */
|
||||
auto clipped = [&](Clip& c, int64_t n_out, int64_t n_in, rad_buf in, rad_buf tmp,
|
||||
rad_buf out) {
|
||||
c.op_in = rw(b, clamp(R, n_in, c.in_lo, c.in_hi), {in}, {tmp});
|
||||
c.op_mm = rw(b, gemm(R, n_out, n_in, c.w), {tmp}, {out});
|
||||
c.op_out = rw(b, clamp(R, n_out, c.out_lo, c.out_hi), {out}, {out});
|
||||
};
|
||||
|
||||
op_c0 = rw(b, conv(P, nmel, 1, c0, 1, 1, w_c0), {}, {b_s0});
|
||||
op_n0 = rw(b, lnorm(P / 2 * (nmel / 2), c0, w_n0), {b_s0}, {b_s0});
|
||||
op_r0 = rw(b, unary("relu", P / 2 * (nmel / 2), c0), {b_s0}, {b_s0});
|
||||
op_c1 = rw(b, conv(P / 2, nmel / 2, c0, c1, 2, 2, w_c1), {b_s0}, {b_s1});
|
||||
op_n1 = rw(b, lnorm(R * (nmel / 4), c1, w_n1), {b_s1}, {b_s1});
|
||||
op_r1 = rw(b, unary("relu", R * (nmel / 4), c1), {b_s1}, {b_s1});
|
||||
op_in = rw(b, gemm(R, H, H, w_in), {b_s1}, {b_x});
|
||||
op_relpos = rw(b, RAD_OP(b, "rel_sinusoid",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, n_rel), RAD_INT("n", H),
|
||||
RAD_F64("max_timescale", 10000.0),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, {b_relpos});
|
||||
for (Layer& l : L) {
|
||||
auto ffw_block = [&](FF& ff) {
|
||||
ff.op_pre = rw(b, rms(R, H, ff.pre, 1.0), {b_x}, {b_h});
|
||||
clipped(ff.l1, ffw, H, b_h, b_hc, b_f);
|
||||
ff.op_act = rw(b, unary("silu", R, ffw), {b_f}, {b_f});
|
||||
/* the activation's only reader is this linear, so its clamp is in place */
|
||||
clipped(ff.l2, H, ffw, b_f, b_f, b_o);
|
||||
ff.op_post = rw(b, rms(R, H, ff.post, 0.5), {b_o}, {b_o});
|
||||
ff.op_add = rw(b, add(R, H), {b_x, b_o}, {b_x});
|
||||
};
|
||||
ffw_block(l.ff1);
|
||||
l.op_npa = rw(b, rms(R, H, l.n_pre_attn, 1.0), {b_x}, {b_h});
|
||||
clipped(l.q, H, H, b_h, b_hc, b_q);
|
||||
clipped(l.k, H, H, b_h, b_hc, b_k);
|
||||
clipped(l.v, H, H, b_h, b_hc, b_v);
|
||||
l.op_rel = rw(b, gemm(n_rel, H, H, l.w_rel), {b_relpos}, {b_relk});
|
||||
l.op_attn = rw(b, RAD_OP(b, "attn_local_rel",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("head_dim", hd),
|
||||
RAD_INT("n_head", heads), RAD_INT("left", left),
|
||||
RAD_INT("right", 0), RAD_F64("softcap", softcap),
|
||||
RAD_INT("cu_div", merge), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(l.pds)),
|
||||
{b_q, b_k, b_v, b_relk}, {b_att});
|
||||
clipped(l.post, H, H, b_att, b_hc, b_o);
|
||||
l.op_npo = rw(b, rms(R, H, l.n_post_attn, 1.0), {b_o}, {b_o});
|
||||
l.op_add_attn = rw(b, add(R, H), {b_x, b_o}, {b_x});
|
||||
l.op_lc_pre = rw(b, rms(R, H, l.lc_pre, 1.0), {b_x}, {b_h});
|
||||
clipped(l.lc_start, 2 * H, H, b_h, b_hc, b_g);
|
||||
/* GLU: the first half times the sigmoid of the second. */
|
||||
l.op_glu = rw(b, RAD_OP(b, "act_mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", H),
|
||||
RAD_STR("act", "sigmoid"), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{b_g}, {b_u});
|
||||
l.op_dw = rw(b, RAD_OP(b, "conv1d_dw",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", H),
|
||||
RAD_INT("k", kconv), RAD_INT("cu_div", merge),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(l.lc_dw)),
|
||||
{b_u}, {b_o});
|
||||
l.op_lc_norm = rw(b, rms(R, H, l.lc_norm, 1.0), {b_o}, {b_o});
|
||||
l.op_lc_act = rw(b, unary("silu", R, H), {b_o}, {b_o});
|
||||
clipped(l.lc_end, H, H, b_o, b_hc, b_u);
|
||||
l.op_lc_add = rw(b, add(R, H), {b_x, b_u}, {b_x});
|
||||
ffw_block(l.ff2);
|
||||
l.op_out = rw(b, rms(R, H, l.n_out, 1.0), {b_x}, {b_x});
|
||||
}
|
||||
op_outp = rw(b, RAD_OP(b, "gemm_nt_bias",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("N", out_dims),
|
||||
RAD_INT("K", H), RAD_STR("dtype", "bf16"),
|
||||
RAD_STR("act", "none")),
|
||||
RAD_WEIGHTS(w_out, b_outw)),
|
||||
{b_x}, {b_o2});
|
||||
op_en = rw(b, rms(R, out_dims, 0, 1.0), {b_o2}, {b_on});
|
||||
op_emb = rw(b, gemm(R, n_embd, out_dims, w_emb), {b_on}, {b_out});
|
||||
|
||||
RadEncoderDecl e{};
|
||||
e.name = "audio";
|
||||
e.modalities = RAD_MM_AUDIO;
|
||||
e.patch_dim = nmel;
|
||||
e.merge = merge;
|
||||
e.max_patches = P;
|
||||
e.n_embd = n_embd;
|
||||
e.out = b_out;
|
||||
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
|
||||
rad_note(b, "audio encoder: %lld conformer blocks of %lld (%lld heads x %lld), "
|
||||
"subsampling %lld/%lld channels, local attention %lld back; %lld frames a "
|
||||
"pass -> %lld rows of %lld", (long long)depth, (long long)H, (long long)heads,
|
||||
(long long)hd, (long long)c0, (long long)c1, (long long)left, (long long)P,
|
||||
(long long)R, (long long)n_embd);
|
||||
on = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t Pn = batch->enc_n_patch, S = batch->enc_n_seg;
|
||||
if (!on || Pn <= 0 || Pn > P || Pn % merge || S <= 0) {
|
||||
rad_step_fail(c, "an audio pass this program's audio encoder cannot serve: none "
|
||||
"declared, more frames than it was declared for, or not whole rows");
|
||||
return;
|
||||
}
|
||||
const int64_t Rn = Pn / merge;
|
||||
const int32_t* crd = batch->enc_coord;
|
||||
const RadOperand frames = praw2(batch->enc_pixels, RAD_BF16, Pn, nmel);
|
||||
const RadOperand valid = praw(crd + Pn, RAD_I32, Pn);
|
||||
const RadOperand cu = praw(batch->enc_cu, RAD_I32, S + 1);
|
||||
auto clipped = [&](const Clip& cl, rad_buf in, int64_t n_in, rad_buf tmp, rad_buf out,
|
||||
int64_t n_out) {
|
||||
RAD_ISSUE_N(c, cl.op_in, Rn, bcol(in, 0, n_in, Rn), RAD_W(cl.in_lo), RAD_W(cl.in_hi),
|
||||
bcol(tmp, 0, n_in, Rn));
|
||||
RAD_ISSUE_N(c, cl.op_mm, Rn, bcol(tmp, 0, n_in, Rn), RAD_W(cl.w), bcol(out, 0, n_out, Rn));
|
||||
RAD_ISSUE_N(c, cl.op_out, Rn, bcol(out, 0, n_out, Rn), RAD_W(cl.out_lo), RAD_W(cl.out_hi),
|
||||
bcol(out, 0, n_out, Rn));
|
||||
};
|
||||
|
||||
RAD_ISSUE_N(c, op_c0, Pn, frames, RAD_W(w_c0), cu, valid, brows(b_s0, Pn / 2));
|
||||
RAD_ISSUE_N(c, op_n0, Pn / 2 * (nmel / 2), brows(b_s0, Pn / 2), RAD_W(w_n0), RAD_NONE,
|
||||
brows(b_s0, Pn / 2));
|
||||
RAD_ISSUE_N(c, op_r0, Pn / 2 * (nmel / 2), brows(b_s0, Pn / 2), brows(b_s0, Pn / 2));
|
||||
RAD_ISSUE_N(c, op_c1, Pn / 2, brows(b_s0, Pn / 2), RAD_W(w_c1), cu, valid, brows(b_s1, Rn));
|
||||
RAD_ISSUE_N(c, op_n1, Rn * (nmel / 4), brows(b_s1, Rn), RAD_W(w_n1), RAD_NONE,
|
||||
brows(b_s1, Rn));
|
||||
RAD_ISSUE_N(c, op_r1, Rn * (nmel / 4), brows(b_s1, Rn), brows(b_s1, Rn));
|
||||
RAD_ISSUE_N(c, op_in, Rn, brows(b_s1, Rn), RAD_W(w_in), brows(b_x, Rn));
|
||||
RAD_ISSUE_N(c, op_relpos, n_rel, brows(b_relpos, n_rel));
|
||||
for (const Layer& l : L) {
|
||||
auto ffw_block = [&](const FF& ff) {
|
||||
RAD_ISSUE_N(c, ff.op_pre, Rn, brows(b_x, Rn), RAD_W(ff.pre), brows(b_h, Rn));
|
||||
clipped(ff.l1, b_h, H, b_hc, b_f, ffw);
|
||||
RAD_ISSUE_N(c, ff.op_act, Rn, brows(b_f, Rn), brows(b_f, Rn));
|
||||
clipped(ff.l2, b_f, ffw, b_f, b_o, H);
|
||||
RAD_ISSUE_N(c, ff.op_post, Rn, brows(b_o, Rn), RAD_W(ff.post), brows(b_o, Rn));
|
||||
RAD_ISSUE_N(c, ff.op_add, Rn, brows(b_x, Rn), brows(b_o, Rn), brows(b_x, Rn));
|
||||
};
|
||||
ffw_block(l.ff1);
|
||||
RAD_ISSUE_N(c, l.op_npa, Rn, brows(b_x, Rn), RAD_W(l.n_pre_attn), brows(b_h, Rn));
|
||||
clipped(l.q, b_h, H, b_hc, b_q, H);
|
||||
clipped(l.k, b_h, H, b_hc, b_k, H);
|
||||
clipped(l.v, b_h, H, b_hc, b_v, H);
|
||||
RAD_ISSUE_N(c, l.op_rel, n_rel, brows(b_relpos, n_rel), RAD_W(l.w_rel),
|
||||
brows(b_relk, n_rel));
|
||||
RAD_ISSUE_N(c, l.op_attn, Rn, brows(b_q, Rn), brows(b_k, Rn), brows(b_v, Rn),
|
||||
brows(b_relk, n_rel), RAD_W(l.pds), cu, brows(b_att, Rn));
|
||||
clipped(l.post, b_att, H, b_hc, b_o, H);
|
||||
RAD_ISSUE_N(c, l.op_npo, Rn, brows(b_o, Rn), RAD_W(l.n_post_attn), brows(b_o, Rn));
|
||||
RAD_ISSUE_N(c, l.op_add_attn, Rn, brows(b_x, Rn), brows(b_o, Rn), brows(b_x, Rn));
|
||||
RAD_ISSUE_N(c, l.op_lc_pre, Rn, brows(b_x, Rn), RAD_W(l.lc_pre), brows(b_h, Rn));
|
||||
clipped(l.lc_start, b_h, H, b_hc, b_g, 2 * H);
|
||||
RAD_ISSUE_N(c, l.op_glu, Rn, bcol(b_g, H, H, Rn), bcol(b_g, 0, H, Rn), brows(b_u, Rn));
|
||||
RAD_ISSUE_N(c, l.op_dw, Rn, brows(b_u, Rn), RAD_W(l.lc_dw), cu, brows(b_o, Rn));
|
||||
RAD_ISSUE_N(c, l.op_lc_norm, Rn, brows(b_o, Rn), RAD_W(l.lc_norm), brows(b_o, Rn));
|
||||
RAD_ISSUE_N(c, l.op_lc_act, Rn, brows(b_o, Rn), brows(b_o, Rn));
|
||||
clipped(l.lc_end, b_o, H, b_hc, b_u, H);
|
||||
RAD_ISSUE_N(c, l.op_lc_add, Rn, brows(b_x, Rn), brows(b_u, Rn), brows(b_x, Rn));
|
||||
ffw_block(l.ff2);
|
||||
RAD_ISSUE_N(c, l.op_out, Rn, brows(b_x, Rn), RAD_W(l.n_out), brows(b_x, Rn));
|
||||
}
|
||||
RAD_ISSUE_N(c, op_outp, Rn, brows(b_x, Rn), RAD_W(w_out), RAD_W(b_outw), RAD_NONE,
|
||||
brows(b_o2, Rn));
|
||||
RAD_ISSUE_N(c, op_en, Rn, brows(b_o2, Rn), RAD_NONE, brows(b_on, Rn));
|
||||
RAD_ISSUE_N(c, op_emb, Rn, brows(b_on, Rn), RAD_W(w_emb), brows(b_out, Rn));
|
||||
}
|
||||
};
|
||||
|
||||
struct Model {
|
||||
Names nm{""};
|
||||
Geom g{};
|
||||
Kind ks{}, kf{}; /* sliding, full */
|
||||
int64_t n_ple = 0; /* hidden_size_per_layer_input */
|
||||
int64_t n_out = 0; /* embedding_dim */
|
||||
|
||||
rad_buf b_x = 0, b_h = 0, b_o = 0, b_qkv_s = 0, b_qkv_f = 0, b_att_s = 0, b_att_f = 0;
|
||||
rad_buf b_gu = 0, b_ff = 0, b_p = 0, b_ple = 0, b_mean = 0, b_proj = 0, b_pooled = 0;
|
||||
|
||||
rad_weight w_tok = 0, w_ple_proj = 0, w_ple_norm = 0, w_norm = 0, w_out = 0;
|
||||
rad_op op_embed = 0, op_ple = 0, op_ple_norm = 0, op_norm = 0, op_mean = 0, op_out = 0;
|
||||
rad_op op_cast = 0;
|
||||
rad_op op_mm = 0; /* the media rows over their placeholders' embeddings */
|
||||
|
||||
std::vector<Layer> layers;
|
||||
Gemma4Vision vis;
|
||||
Audio aud;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
|
||||
/* The layer schedule, read rather than derived: layer_types states which layers attend to the
|
||||
* whole input, and an assumed pattern would silently be wrong for a sibling checkpoint that
|
||||
* differs. */
|
||||
static int read_schedule(const RadModelMeta* meta, int64_t n_layer, std::vector<int>* full) {
|
||||
const char* s = rad_meta_gets(meta, "layer_types", nullptr);
|
||||
if (!s || !*s) {
|
||||
fprintf(stderr, "radiance: embgemma2: the container has no layer_types; it says which "
|
||||
"layers are sliding and which see the whole input, and is not guessed\n");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
full->clear();
|
||||
for (const char* p = s; *p; ) {
|
||||
while (*p == ' ') ++p;
|
||||
if (!*p) break;
|
||||
const char* t = p;
|
||||
while (*p && *p != ' ') ++p;
|
||||
const size_t len = (size_t)(p - t);
|
||||
if (len == 14 && !std::strncmp(t, "full_attention", 14)) full->push_back(1);
|
||||
else if (len == 17 && !std::strncmp(t, "sliding_attention", 17)) full->push_back(0);
|
||||
else {
|
||||
fprintf(stderr, "radiance: embgemma2: layer_types names '%.*s'; this plugin knows "
|
||||
"full_attention and sliding_attention\n", (int)len, t);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
}
|
||||
if ((int64_t)full->size() != n_layer) {
|
||||
fprintf(stderr, "radiance: embgemma2: layer_types names %zu layers and the model has "
|
||||
"%lld\n", full->size(), (long long)n_layer);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
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;
|
||||
/* A 270M encoder fits easily on one card; tensor parallelism would only add an all-reduce per
|
||||
* layer, so it is not offered. */
|
||||
if (ctx->world_size > 1) {
|
||||
fprintf(stderr, "radiance: embgemma2 runs on one card (--tp 1); the text model is 270M "
|
||||
"parameters\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
Model& m = g_model[ctx->rank];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
|
||||
Geom& g = m.g;
|
||||
Names& nm = m.nm;
|
||||
const int64_t T = g.max_tok, E = g.n_embd;
|
||||
|
||||
std::vector<int> full;
|
||||
RAD_ARCH_TRY(read_schedule(meta, g.n_layer, &full));
|
||||
|
||||
/* The two attention kinds. The sliding one is the config's top-level geometry; the full one
|
||||
* overrides head width and KV heads per layer (per_layer_config), and every full layer must
|
||||
* state the same override (checked below). */
|
||||
m.ks.head_dim = g.head_dim;
|
||||
m.ks.n_head = g.n_head;
|
||||
m.ks.n_head_kv = g.n_head_kv;
|
||||
m.ks.theta = rad_meta_getf(meta, "rope_parameters.sliding_attention.rope_theta", 0.0);
|
||||
/* The reference's window is a radius (|i - j| <= sliding_window) and attn_dense's is a strict
|
||||
* bound, so one more. */
|
||||
const int64_t radius = meta_int2(meta, "", "sliding_window", 0);
|
||||
m.ks.window = radius + 1;
|
||||
m.kf.n_head = g.n_head;
|
||||
m.kf.theta = rad_meta_getf(meta, "rope_parameters.full_attention.rope_theta", 0.0);
|
||||
m.kf.window = 0;
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
if (!full[(size_t)l]) continue;
|
||||
char k1[96], k2[96];
|
||||
std::snprintf(k1, sizeof k1, "per_layer_config.%02lld.head_dim", (long long)l);
|
||||
std::snprintf(k2, sizeof k2, "per_layer_config.%02lld.num_key_value_heads", (long long)l);
|
||||
const int64_t hd = meta_int2(meta, "", k1, 0), kv = meta_int2(meta, "", k2, 0);
|
||||
if (!m.kf.head_dim) { m.kf.head_dim = hd; m.kf.n_head_kv = kv; }
|
||||
if (hd <= 0 || kv <= 0 || hd != m.kf.head_dim || kv != m.kf.n_head_kv) {
|
||||
fprintf(stderr, "radiance: embgemma2: full-attention layer %lld states head_dim %lld "
|
||||
"and %lld KV heads; this plugin serves one full geometry\n",
|
||||
(long long)l, (long long)hd, (long long)kv);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
m.n_ple = meta_int2(meta, "", "hidden_size_per_layer_input", 0);
|
||||
m.n_out = meta_int2(meta, "", "embedding_dim", 0);
|
||||
if (!(m.ks.theta > 0) || !(m.kf.theta > 0) || radius <= 0 || m.kf.head_dim <= 0 ||
|
||||
m.n_ple <= 0 || m.n_out <= 0 || m.ks.n_head % m.ks.n_head_kv || m.kf.n_head % m.kf.n_head_kv) {
|
||||
fprintf(stderr, "radiance: embgemma2: the container does not describe the model (rope "
|
||||
"thetas %g / %g, sliding_window %lld, full head_dim %lld, "
|
||||
"hidden_size_per_layer_input %lld, embedding_dim %lld)\n",
|
||||
m.ks.theta, m.kf.theta, (long long)radius, (long long)m.kf.head_dim,
|
||||
(long long)m.n_ple, (long long)m.n_out);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const int64_t P = m.n_ple * g.n_layer;
|
||||
/* One input is at most one step (Request::embed), so the longest attention segment is the
|
||||
* step's token budget. */
|
||||
const int64_t max_seg = T;
|
||||
|
||||
/* ---- activations. ple holds every layer's per-layer input for the whole step, read as one
|
||||
* column slice per layer. */
|
||||
m.b_x = decl_b(b, nm.f("x"), RAD_BF16, {T, E});
|
||||
m.b_h = decl_b(b, nm.f("h"), RAD_BF16, {T, E});
|
||||
m.b_o = decl_b(b, nm.f("o"), RAD_BF16, {T, E});
|
||||
m.b_qkv_s = decl_b(b, nm.f("qkv_s"), RAD_BF16, {T, m.ks.qkv()});
|
||||
m.b_qkv_f = decl_b(b, nm.f("qkv_f"), RAD_BF16, {T, m.kf.qkv()});
|
||||
m.b_att_s = decl_b(b, nm.f("att_s"), RAD_BF16, {T, m.ks.q()});
|
||||
m.b_att_f = decl_b(b, nm.f("att_f"), RAD_BF16, {T, m.kf.q()});
|
||||
m.b_gu = decl_b(b, nm.f("gate_up"), RAD_BF16, {T, 2 * g.n_ff});
|
||||
m.b_ff = decl_b(b, nm.f("ffn"), RAD_BF16, {T, g.n_ff});
|
||||
m.b_p = decl_b(b, nm.f("ple_p"), RAD_BF16, {T, m.n_ple});
|
||||
m.b_ple = decl_b(b, nm.f("ple"), RAD_BF16, {T, P});
|
||||
m.b_mean = decl_b(b, nm.f("mean"), RAD_BF16, {g.max_seqs, E});
|
||||
m.b_proj = decl_b(b, nm.f("proj"), RAD_BF16, {g.max_seqs, m.n_out});
|
||||
m.b_pooled= decl_b(b, nm.f("pooled"), RAD_F32, {g.max_seqs, m.n_out}, RAD_BUF_PERSIST);
|
||||
RAD_ARCH_TRY(rad_declare_pooled(b, m.b_pooled));
|
||||
|
||||
/* ---- the model-level weights, all at the checkpoint's bf16, norm gains included: the
|
||||
* reference widens a gain to f32 at use, which is exact, and a wider stored copy could not be
|
||||
* read in place on the host backend. */
|
||||
const char* L = "language_model";
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("%s.embed_tokens.weight", L)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("ple_proj.weight"),
|
||||
nm.ckpt("%s.ple.per_layer_model_projection.weight", L)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("ple_norm.weight"),
|
||||
nm.ckpt("%s.ple.per_layer_projection_norm.weight", L)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("%s.norm.weight", L)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("embd_proj.weight"),
|
||||
nm.ckpt("%s.embedding_projection.weight", L)));
|
||||
m.w_tok = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, {g.n_vocab, E},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
m.w_ple_proj = decl_w(b, nm.f("ple_proj.weight"), RAD_BF16, {P, E},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
m.w_ple_norm = decl_w(b, nm.f("ple_norm.weight"), RAD_BF16, {m.n_ple},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
m.w_norm = decl_w(b, nm.f("output_norm.weight"), RAD_BF16, {E},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
m.w_out = decl_w(b, nm.f("embd_proj.weight"), RAD_BF16, {m.n_out, E},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
|
||||
auto rmsnorm = [&](int64_t rows, int64_t n, double eps, rad_weight w) {
|
||||
return RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", eps),
|
||||
RAD_F64("wadd", 0.0), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w));
|
||||
};
|
||||
auto gemm = [&](int64_t rows, int64_t N, int64_t K, rad_weight w) {
|
||||
return RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w));
|
||||
};
|
||||
auto elem = [&](const char* op, int64_t n, rad_weight w) {
|
||||
if (w)
|
||||
return RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", n),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w));
|
||||
return RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", n),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
auto act_mul = [&](int64_t n) {
|
||||
return RAD_OP(b, "act_mul", RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", n),
|
||||
RAD_STR("act", "gelu_tanh"),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
|
||||
/* The embedding, scaled by sqrt(hidden) rounded as the reference rounds it (a bf16 buffer):
|
||||
* sqrt(512) = 22.6274 multiplies as 22.625. */
|
||||
const double escale = rad_bf16_to_f32(rad_f32_to_bf16((float)std::sqrt((double)E)));
|
||||
m.op_embed = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_embd", E),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype),
|
||||
RAD_INT("vocab_offset", 0), RAD_F64("mult", escale)),
|
||||
RAD_WEIGHTS(m.w_tok)),
|
||||
{}, {m.b_x});
|
||||
/* The per-layer inputs: the embedding projected to n_layer x n_ple and RMS-normed per layer.
|
||||
* The reference scales the projection by hidden^-0.5 before the norm; the RMS norm of s*x with
|
||||
* eps equals the norm of x with eps / s^2, which is what is declared, avoiding the bf16
|
||||
* rounding of s*x. */
|
||||
/* A media part's rows overwrite its placeholders' embeddings before anything reads them, so an
|
||||
* image token's per-layer inputs come from its image row (declared only with a tower). */
|
||||
if ((Gemma4Vision::present(meta) && ctx->max_enc_patches > 0) ||
|
||||
(Audio::present(meta) && ctx->max_audio_frames > 0))
|
||||
m.op_mm = rw(b, RAD_OP(b, "scatter_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_x}, {m.b_x});
|
||||
m.op_ple = rw(b, gemm(T, P, E, m.w_ple_proj), {m.b_x}, {m.b_ple});
|
||||
m.op_ple_norm = rw(b, rmsnorm(T * g.n_layer, m.n_ple, (double)g.eps * (double)E, m.w_ple_norm),
|
||||
{m.b_ple}, {m.b_ple});
|
||||
|
||||
m.layers.resize((size_t)g.n_layer);
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
Layer& y = m.layers[(size_t)l];
|
||||
y.full = full[(size_t)l];
|
||||
const Kind& k = y.full ? m.kf : m.ks;
|
||||
const rad_buf qkv = y.full ? m.b_qkv_f : m.b_qkv_s;
|
||||
const rad_buf att = y.full ? m.b_att_f : m.b_att_s;
|
||||
const long long ll = (long long)l;
|
||||
const RadWeightGroup gl = grp_layer((int)l);
|
||||
auto src = [&](const char* s) { return nm.ckpt("%s.layers.%lld.%s", L, ll, s); };
|
||||
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.in_norm", ll), src("input_layernorm.weight")));
|
||||
RAD_ARCH_TRY(map_concat(b, nm.f("blk.%lld.qkv", ll),
|
||||
{src("self_attn.q_proj.weight"), src("self_attn.k_proj.weight"),
|
||||
src("self_attn.v_proj.weight")}));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.q_norm", ll), src("self_attn.q_norm.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.k_norm", ll), src("self_attn.k_norm.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.o", ll), src("self_attn.o_proj.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.post_attn", ll),
|
||||
src("post_attention_layernorm.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.pre_ff", ll),
|
||||
src("pre_feedforward_layernorm.weight")));
|
||||
RAD_ARCH_TRY(map_concat(b, nm.f("blk.%lld.gate_up", ll),
|
||||
{src("mlp.gate_proj.weight"), src("mlp.up_proj.weight")}));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.down", ll), src("mlp.down_proj.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.post_ff", ll),
|
||||
src("post_feedforward_layernorm.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ple_gate", ll),
|
||||
src("ple_block.per_layer_input_gate.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ple_proj", ll),
|
||||
src("ple_block.per_layer_projection.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.post_ple", ll),
|
||||
src("ple_block.post_per_layer_input_norm.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.scalar", ll), src("layer_scalar")));
|
||||
|
||||
const int A = RAD_ACCESS_PER_TOKEN, N = RAD_SHARD_NONE;
|
||||
y.w_in_norm = decl_w(b, nm.f("blk.%lld.in_norm", ll), RAD_BF16, {E}, A, N, gl);
|
||||
y.w_qkv = decl_w(b, nm.f("blk.%lld.qkv", ll), RAD_BF16, {k.qkv(), E}, A, N, gl);
|
||||
y.w_q_norm = decl_w(b, nm.f("blk.%lld.q_norm", ll), RAD_BF16, {k.head_dim}, A, N, gl);
|
||||
y.w_k_norm = decl_w(b, nm.f("blk.%lld.k_norm", ll), RAD_BF16, {k.head_dim}, A, N, gl);
|
||||
y.w_o = decl_w(b, nm.f("blk.%lld.o", ll), RAD_BF16, {E, k.q()}, A, N, gl);
|
||||
y.w_post_attn = decl_w(b, nm.f("blk.%lld.post_attn", ll), RAD_BF16, {E}, A, N, gl);
|
||||
y.w_pre_ff = decl_w(b, nm.f("blk.%lld.pre_ff", ll), RAD_BF16, {E}, A, N, gl);
|
||||
y.w_gate_up = decl_w(b, nm.f("blk.%lld.gate_up", ll), RAD_BF16, {2 * g.n_ff, E}, A, N, gl);
|
||||
y.w_down = decl_w(b, nm.f("blk.%lld.down", ll), RAD_BF16, {E, g.n_ff}, A, N, gl);
|
||||
y.w_post_ff = decl_w(b, nm.f("blk.%lld.post_ff", ll), RAD_BF16, {E}, A, N, gl);
|
||||
y.w_ple_gate = decl_w(b, nm.f("blk.%lld.ple_gate", ll), RAD_BF16, {m.n_ple, E}, A, N, gl);
|
||||
y.w_ple_proj = decl_w(b, nm.f("blk.%lld.ple_proj", ll), RAD_BF16, {E, m.n_ple}, A, N, gl);
|
||||
y.w_post_ple = decl_w(b, nm.f("blk.%lld.post_ple", ll), RAD_BF16, {E}, A, N, gl);
|
||||
/* bf16 and one element: the reference multiplies the bf16 residual by it in bf16. */
|
||||
y.w_scalar = decl_w(b, nm.f("blk.%lld.scalar", ll), RAD_BF16, {1}, A, N, gl);
|
||||
|
||||
y.op_in_norm = rw(b, rmsnorm(T, E, g.eps, y.w_in_norm), {m.b_x}, {m.b_h});
|
||||
y.op_qkv = rw(b, gemm(T, k.qkv(), E, y.w_qkv), {m.b_h}, {qkv});
|
||||
y.op_qk = rw(b, RAD_OP(b, "qk_norm_rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", k.head_dim),
|
||||
RAD_INT("n_head", k.n_head),
|
||||
RAD_INT("n_head_kv", k.n_head_kv),
|
||||
RAD_F64("theta", k.theta), RAD_F64("eps", g.eps),
|
||||
RAD_STR("mode", "neox"), RAD_INT("v_norm", 1)),
|
||||
RAD_WEIGHTS(y.w_q_norm, y.w_k_norm)),
|
||||
{qkv}, {qkv});
|
||||
y.op_attn = rw(b, RAD_OP(b, "attn_dense",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", k.head_dim),
|
||||
RAD_INT("gqa", k.n_head / k.n_head_kv),
|
||||
RAD_INT("causal", 0), RAD_STR("dtype", "bf16"),
|
||||
RAD_F64("scale", 1.0),
|
||||
RAD_INT("max_seqlen", max_seg),
|
||||
RAD_INT("window", k.window)),
|
||||
RAD_NOWEIGHTS),
|
||||
{qkv}, {att});
|
||||
y.op_o = rw(b, gemm(T, E, k.q(), y.w_o), {att}, {m.b_o});
|
||||
y.op_post_attn= rw(b, rmsnorm(T, E, g.eps, y.w_post_attn), {m.b_o}, {m.b_o});
|
||||
y.op_add_attn = rw(b, elem("add", E, 0), {m.b_x, m.b_o}, {m.b_x});
|
||||
y.op_pre_ff = rw(b, rmsnorm(T, E, g.eps, y.w_pre_ff), {m.b_x}, {m.b_h});
|
||||
y.op_gate_up = rw(b, gemm(T, 2 * g.n_ff, E, y.w_gate_up), {m.b_h}, {m.b_gu});
|
||||
y.op_act = rw(b, act_mul(g.n_ff), {m.b_gu}, {m.b_ff});
|
||||
y.op_down = rw(b, gemm(T, E, g.n_ff, y.w_down), {m.b_ff}, {m.b_o});
|
||||
y.op_post_ff = rw(b, rmsnorm(T, E, g.eps, y.w_post_ff), {m.b_o}, {m.b_o});
|
||||
y.op_add_ff = rw(b, elem("add", E, 0), {m.b_x, m.b_o}, {m.b_x});
|
||||
y.op_ple_gate = rw(b, gemm(T, m.n_ple, E, y.w_ple_gate), {m.b_x}, {m.b_p});
|
||||
y.op_ple_act = rw(b, act_mul(m.n_ple), {m.b_p, m.b_ple}, {m.b_p});
|
||||
y.op_ple_proj = rw(b, gemm(T, E, m.n_ple, y.w_ple_proj), {m.b_p}, {m.b_o});
|
||||
y.op_post_ple = rw(b, rmsnorm(T, E, g.eps, y.w_post_ple), {m.b_o}, {m.b_o});
|
||||
y.op_add_ple = rw(b, elem("add", E, 0), {m.b_x, m.b_o}, {m.b_x});
|
||||
y.op_scale = rw(b, RAD_OP(b, "mul_weight",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E),
|
||||
RAD_STR("dtype", "bf16"), RAD_INT("scalar", 1)),
|
||||
RAD_WEIGHTS(y.w_scalar)),
|
||||
{m.b_x}, {m.b_x});
|
||||
}
|
||||
|
||||
m.op_norm = rw(b, rmsnorm(T, E, g.eps, m.w_norm), {m.b_x}, {m.b_h});
|
||||
m.op_mean = rw(b, RAD_OP(b, "seg_mean",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_h}, {m.b_mean});
|
||||
m.op_out = rw(b, gemm(g.max_seqs, m.n_out, E, m.w_out), {m.b_mean}, {m.b_proj});
|
||||
m.op_cast = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("n", m.n_out),
|
||||
RAD_STR("from", "bf16"), RAD_STR("to", "f32")),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_proj}, {m.b_pooled});
|
||||
|
||||
RAD_ARCH_TRY(m.vis.declare(b, meta, ctx, nm, E, (int)g.n_layer, "", "embgemma2"));
|
||||
RAD_ARCH_TRY(m.aud.declare(b, meta, ctx, nm, E,
|
||||
(int)g.n_layer + (int)m.vis.L.size()));
|
||||
|
||||
int n_full = 0;
|
||||
for (int f : full) n_full += f;
|
||||
rad_note(b, "embedding model: %lld layers (%d whole-input, %lld sliding |i-j|<=%lld), hidden "
|
||||
"%lld, ffn %lld; sliding %lldx%lld (kv %lld) theta %g, full %lldx%lld (kv %lld) "
|
||||
"theta %g; per-layer inputs %lld; mean-pooled to %lld",
|
||||
(long long)g.n_layer, n_full, (long long)(g.n_layer - n_full), (long long)radius,
|
||||
(long long)E, (long long)g.n_ff, (long long)m.ks.n_head, (long long)m.ks.head_dim,
|
||||
(long long)m.ks.n_head_kv, m.ks.theta, (long long)m.kf.n_head,
|
||||
(long long)m.kf.head_dim, (long long)m.kf.n_head_kv, m.kf.theta,
|
||||
(long long)m.n_ple, (long long)m.n_out);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Before declare: the vision tower's pooling window, so a pass size the core picks is a whole
|
||||
* number of windows. */
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
if (Gemma4Vision::present(meta)) {
|
||||
const int64_t k = rad_meta_geti(meta, "vision_config.pooling_kernel_size", 0);
|
||||
if (k > 0) out->enc_merge = k * k;
|
||||
}
|
||||
if (Audio::present(meta)) out->audio_frames = Audio::frames_for(meta);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Geom& g = m.g;
|
||||
const int64_t T = batch->n_tok, S = batch->n_seq, E = g.n_embd;
|
||||
if (batch->enc) {
|
||||
if (batch->enc == RAD_MM_AUDIO) m.aud.step(c, batch);
|
||||
else m.vis.step(c, batch);
|
||||
return;
|
||||
}
|
||||
if (T <= 0 || S <= 0) return;
|
||||
const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, S + 1);
|
||||
const RadOperand pos = praw(batch->positions, RAD_I32, T);
|
||||
|
||||
RAD_ISSUE(c, m.op_embed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.b_x, T));
|
||||
if (m.op_mm && batch->n_mm_rows > 0)
|
||||
RAD_ISSUE_N(c, m.op_mm, batch->n_mm_rows,
|
||||
praw2(batch->mm_embd, RAD_BF16, batch->n_mm_rows, E),
|
||||
praw(batch->mm_rows, RAD_I32, batch->n_mm_rows), brows(m.b_x, T));
|
||||
RAD_ISSUE(c, m.op_ple, brows(m.b_x, T), RAD_W(m.w_ple_proj), brows(m.b_ple, T));
|
||||
/* [T, n_layer * n_ple] read as [T * n_layer, n_ple]: one norm row per (token, layer). */
|
||||
RAD_ISSUE_N(c, m.op_ple_norm, T * g.n_layer, brows(m.b_ple, T), RAD_W(m.w_ple_norm),
|
||||
brows(m.b_ple, T));
|
||||
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const Layer& y = m.layers[(size_t)l];
|
||||
const Kind& k = y.full ? m.kf : m.ks;
|
||||
const rad_buf qkv = y.full ? m.b_qkv_f : m.b_qkv_s;
|
||||
const rad_buf att = y.full ? m.b_att_f : m.b_att_s;
|
||||
const int64_t q = k.q(), kv = k.n_head_kv * k.head_dim;
|
||||
|
||||
RAD_ISSUE(c, y.op_in_norm, brows(m.b_x, T), RAD_W(y.w_in_norm), brows(m.b_h, T));
|
||||
RAD_ISSUE(c, y.op_qkv, brows(m.b_h, T), RAD_W(y.w_qkv), brows(qkv, T));
|
||||
RAD_ISSUE(c, y.op_qk, brows(qkv, T), pos, RAD_W(y.w_q_norm), RAD_W(y.w_k_norm));
|
||||
RAD_ISSUE(c, y.op_attn, bcol(qkv, 0, q, T), bcol(qkv, q, kv, T), bcol(qkv, q + kv, kv, T),
|
||||
cu, brows(att, T));
|
||||
RAD_ISSUE(c, y.op_o, brows(att, T), RAD_W(y.w_o), brows(m.b_o, T));
|
||||
RAD_ISSUE(c, y.op_post_attn, brows(m.b_o, T), RAD_W(y.w_post_attn), brows(m.b_o, T));
|
||||
RAD_ISSUE(c, y.op_add_attn, brows(m.b_x, T), brows(m.b_o, T), brows(m.b_x, T));
|
||||
RAD_ISSUE(c, y.op_pre_ff, brows(m.b_x, T), RAD_W(y.w_pre_ff), brows(m.b_h, T));
|
||||
RAD_ISSUE(c, y.op_gate_up, brows(m.b_h, T), RAD_W(y.w_gate_up), brows(m.b_gu, T));
|
||||
RAD_ISSUE(c, y.op_act, bcol(m.b_gu, 0, g.n_ff, T), bcol(m.b_gu, g.n_ff, g.n_ff, T),
|
||||
brows(m.b_ff, T));
|
||||
RAD_ISSUE(c, y.op_down, brows(m.b_ff, T), RAD_W(y.w_down), brows(m.b_o, T));
|
||||
RAD_ISSUE(c, y.op_post_ff, brows(m.b_o, T), RAD_W(y.w_post_ff), brows(m.b_o, T));
|
||||
RAD_ISSUE(c, y.op_add_ff, brows(m.b_x, T), brows(m.b_o, T), brows(m.b_x, T));
|
||||
RAD_ISSUE(c, y.op_ple_gate, brows(m.b_x, T), RAD_W(y.w_ple_gate), brows(m.b_p, T));
|
||||
RAD_ISSUE(c, y.op_ple_act, brows(m.b_p, T), bcol(m.b_ple, l * m.n_ple, m.n_ple, T),
|
||||
brows(m.b_p, T));
|
||||
RAD_ISSUE(c, y.op_ple_proj, brows(m.b_p, T), RAD_W(y.w_ple_proj), brows(m.b_o, T));
|
||||
RAD_ISSUE(c, y.op_post_ple, brows(m.b_o, T), RAD_W(y.w_post_ple), brows(m.b_o, T));
|
||||
RAD_ISSUE(c, y.op_add_ple, brows(m.b_x, T), brows(m.b_o, T), brows(m.b_x, T));
|
||||
RAD_ISSUE(c, y.op_scale, brows(m.b_x, T), RAD_W(y.w_scalar), brows(m.b_x, T));
|
||||
}
|
||||
|
||||
RAD_ISSUE(c, m.op_norm, brows(m.b_x, T), RAD_W(m.w_norm), brows(m.b_h, T));
|
||||
RAD_ISSUE(c, m.op_mean, brows(m.b_h, T), cu, brows(m.b_mean, S));
|
||||
RAD_ISSUE_N(c, m.op_out, S, brows(m.b_mean, S), RAD_W(m.w_out), brows(m.b_proj, S));
|
||||
RAD_ISSUE_N(c, m.op_cast, S, brows(m.b_proj, S), brows(m.b_pooled, S));
|
||||
(void)E;
|
||||
}
|
||||
|
||||
} /* namespace embgemma2 */
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PLUGIN(embgemma2, "embeddinggemma2", "", "0.1.0",
|
||||
"EmbeddingGemma 2: a bidirectional Gemma encoder with per-layer embeddings, "
|
||||
"mean-pooled to one vector an input; bf16")
|
||||
RAD_ARCH_PROBE(embgemma2)
|
||||
#endif
|
||||
@@ -0,0 +1,14 @@
|
||||
# gemma4 -- architecture plugin for Gemma 4's text model (Gemma4ForConditionalGeneration /
|
||||
# Gemma4ForCausalLM: the 26B-A4B MoE and the dense sizes without per-layer embeddings), with a
|
||||
# z-lab DFlash drafter merged at convert time.
|
||||
#
|
||||
# Built in radiance's tree (arch/ discovers it) or standalone against an installed radiance:
|
||||
# cmake -S arch/gemma4 -B build-gemma4 -DCMAKE_PREFIX_PATH=/opt/radiance && cmake --build build-gemma4
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(gemma4 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(gemma4 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/gemma4.cpp)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,682 @@
|
||||
/* gemma4_dflash.h -- the DFlash (v1) block-diffusion drafter, as z-lab trains it for Gemma 4.
|
||||
*
|
||||
* ============================== WHAT IT IS ==============================
|
||||
*
|
||||
* rad_block_dflash2.h without DFlash2's additions (the per-layer dynamic convolutions around
|
||||
* attention and the feed-forward, and the candidate selector). The original DFlash is a small
|
||||
* Qwen3-shaped transformer that denoises one anchor token plus `block - 1` mask tokens in one
|
||||
* forward and takes every position's argmax from the target's lm_head.
|
||||
*
|
||||
* context pass, one row a committed token:
|
||||
* c = hidden_norm(fc(concat of the trunk's residual stream at target_layer_ids)))
|
||||
* for each layer: k = k_norm(k_proj(c)) then rope; v = v_proj(c); kv_store(k, v)
|
||||
*
|
||||
* query pass, `block` rows a sequence:
|
||||
* x = embed(anchor, mask, ...) * sqrt(hidden) <- Gemma's embedding scale, see below
|
||||
* for each layer:
|
||||
* h = input_layernorm(x)
|
||||
* q, k, v = q_proj(h), k_proj(h), v_proj(h); q_norm, k_norm; rope; kv_store
|
||||
* x += o_proj(attention(q, cache)) sliding layers causal over a 2048 window,
|
||||
* the full layer non-causal over everything
|
||||
* x += down(silu(gate(h')) * up(h')), h' = post_attention_layernorm(x)
|
||||
* x = norm(x)
|
||||
* over the mask rows: logits = lm_head(x) [the target's]; draft = argmax
|
||||
*
|
||||
* ============================== THE THREE GEMMA-SPECIFIC FACTS ==============================
|
||||
*
|
||||
* From vLLM PR #41703. Getting any of them wrong costs only acceptance, since every draft is
|
||||
* verified against the trunk.
|
||||
*
|
||||
* The embedding is scaled. Gemma multiplies its token embedding by sqrt(hidden_size), stored as
|
||||
* bf16 (53.0 at 2816), and the drafter was trained through the target's embedding module, which
|
||||
* applies it. `embed_lookup`'s `mult` carries it.
|
||||
*
|
||||
* The sliding layers are causal and the full layer is not. The checkpoint's `layer_types` names
|
||||
* four sliding layers and one full one, and the PR's test pins `causal True` on the sliding
|
||||
* layers and `False` on the full one, so this block declares two attention ops and issues the one
|
||||
* each layer's type names.
|
||||
*
|
||||
* The logits are soft-capped, which is deliberately ignored: the draft is an argmax, and
|
||||
* cap * tanh(x / cap) is strictly increasing.
|
||||
*
|
||||
* ============================== THE HEAD ==============================
|
||||
*
|
||||
* The target's own head, read in bf16 by an ordinary `gemm_nt` over the gathered mask rows. Gemma
|
||||
* ties it to the embedding, so it is the weight the trunk's `embed_lookup` and `logits_gemm` read
|
||||
* and costs no extra bytes. It is vocab-sharded with the trunk: the top-1 runs over this rank's
|
||||
* slice and the ranks' candidates merge exactly (`row_topk` at R = 2 -> `all_gather` ->
|
||||
* `pair_argmax`; R = 2 because the gather moves 16-byte rows, see kTopR).
|
||||
*
|
||||
* The bf16 head (262144 x 2816 x 2 bytes) is the widest read on the draft path, about 566 us of a
|
||||
* 26B-A4B decode step at tp 4 on 4x R9700. So where the container holds a block-fp8 copy of the
|
||||
* table under its own name, `dflash.draft_head.weight` (one checkpoint tensor, two logical
|
||||
* weights, as in rad_block_dflash2.h), made by the recipe line
|
||||
*
|
||||
* dflash.draft_head.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
*
|
||||
* the head is `gemm_nt_q` over that copy at fp8a8, half the bytes, with the argmax over its
|
||||
* coarser logits. Drafts are still verified, so the copy can change proposals but never accepted
|
||||
* text. Without the copy, or in another encoding, the bf16 table is read. The copy costs half the
|
||||
* table's bytes again (176 MiB per rank at tp 4). There is no rerank against the bf16 table:
|
||||
* DFlash2's rerank needs the target's head in fp8 or int8, which a tied Gemma head is not.
|
||||
*
|
||||
* ============================== THE LINEARS ARE FP8 ==============================
|
||||
*
|
||||
* As in DFlash2, since the drafter is read whole on every decode step: the container must be
|
||||
* converted with a recipe that makes the six linears block fp8 (or MXFP4). declare() refuses a bf16
|
||||
* one by name rather than letting the loader fail on a view.
|
||||
*/
|
||||
#ifndef GEMMA4_DFLASH_H
|
||||
#define GEMMA4_DFLASH_H
|
||||
|
||||
#include <arch/rad_arch.h>
|
||||
#include <arch/rad_fp8.h>
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
namespace gemma4 {
|
||||
|
||||
using namespace rad::arch;
|
||||
|
||||
/* Block fp8 as libr4d's fp8a8 GEMMs read it: fp8_e4m3 codes, a bf16 scale per 128x128 block, no
|
||||
* transform (a recipe's `rtn codes=fp8_e4m3 block=128x128 scale=bf16`). */
|
||||
inline bool block_fp8_128(const RadEncoding& e) {
|
||||
const RadEncPlane* sc = rad_enc_plane(&e, "scale");
|
||||
return rad_enc_is(&e, "affine") && e.n_planes == 2 && !e.transform[0] &&
|
||||
e.plane[0].dtype == RAD_F8E4M3 && sc && sc->dtype == RAD_BF16 &&
|
||||
sc->block[0] == RAD_FP8_BLOCK && sc->block[1] == RAD_FP8_BLOCK;
|
||||
}
|
||||
|
||||
struct Dflash1 {
|
||||
enum { MAX_LAYERS = 8 };
|
||||
|
||||
struct Config {
|
||||
int64_t n_taps = 0; /* how many trunk layers `fc` concatenates */
|
||||
int64_t block = 0; /* query rows per sequence: the anchor plus block - 1 masks */
|
||||
int64_t window = 0; /* the sliding layers' window; 0 for none */
|
||||
int full[MAX_LAYERS] = {}; /* 1: a full-attention (non-causal, unwindowed) layer */
|
||||
double escale = 1.0; /* the target's embedding scale, rounded as the target holds it */
|
||||
int64_t steps() const { return block - 1; }
|
||||
};
|
||||
|
||||
struct Wire {
|
||||
/* the context pass */
|
||||
rad_buf src = 0, srcq = 0, srcs = 0; /* [max_tok, n_taps*n_embd] bf16 | e4m3 | f32 */
|
||||
rad_buf c = 0, cq = 0, cs = 0; /* [max_tok, n_embd] */
|
||||
rad_buf ck = 0, cv = 0; /* [max_tok, kv_dim] -- see rad_block_dflash2.h */
|
||||
/* the query pass */
|
||||
rad_buf x = 0, h = 0, hq = 0, hs = 0; /* [qrows, n_embd] */
|
||||
rad_buf q = 0, k = 0, v = 0; /* [qrows, q_dim | kv_dim | kv_dim] */
|
||||
rad_buf attn = 0, atq = 0, ats = 0; /* [qrows, q_dim] */
|
||||
rad_buf gate_up = 0; /* [qrows, 2 * n_ff] */
|
||||
rad_buf ffn = 0, ffq = 0, ffs = 0; /* [qrows, n_ff] */
|
||||
/* the head, one row per draft position */
|
||||
rad_buf sel_h = 0; /* [srows, n_embd] */
|
||||
rad_buf selq = 0, sels = 0; /* [srows, n_embd] e4m3 | f32, the fp8 head's */
|
||||
rad_buf dlog = 0; /* [srows, n_vocab on this rank] bf16 */
|
||||
rad_buf cand = 0, unary = 0; /* [srows, kTopR] i32 | f32 -- this rank's best */
|
||||
rad_buf dpair = 0, dgath = 0; /* [srows, kTopR, 2] | [srows, world * kTopR, 2] f32 */
|
||||
rad_buf tokens = 0; /* [srows, 1] i32: the draft, pitch `steps` */
|
||||
};
|
||||
|
||||
Geom g{}; /* the drafter's geometry */
|
||||
Config cfg{};
|
||||
Wire w{};
|
||||
int first_layer = 0;
|
||||
int64_t qrows = 0, crows = 0, srows = 0, gated_rows = 0;
|
||||
rad_kvgroup kv = 0;
|
||||
bool sharded = false;
|
||||
|
||||
DenseFP8 w_fc{};
|
||||
rad_weight w_hnorm = 0, w_norm = 0;
|
||||
rad_weight w_tok = 0; /* the target's table: embedding and head */
|
||||
DenseFP8 w_dh{}; /* its block-fp8 copy, the head where it is stored */
|
||||
bool fp8_head = false;
|
||||
rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {};
|
||||
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_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] = {};
|
||||
|
||||
rad_op op_embed = 0, op_embed_ar = 0, op_qh = 0, op_qat = 0, op_qff = 0;
|
||||
rad_op op_anorm[MAX_LAYERS] = {}, op_fnorm[MAX_LAYERS] = {};
|
||||
/* The residual add, norm and quantiser in one launch where `rmsnorm_quant_fp8` is served
|
||||
* (libr4d): op_anq[i] for the attention input (layer 0's without the add) and op_fnq[i] for
|
||||
* the feed-forward input. Zero where not served; the `add` / `rmsnorm` / `quant_act_fp8` chain
|
||||
* is issued instead. */
|
||||
rad_op op_anq[MAX_LAYERS] = {}, op_fnq[MAX_LAYERS] = {};
|
||||
rad_op op_qp[MAX_LAYERS] = {}, op_kp[MAX_LAYERS] = {}, op_vp[MAX_LAYERS] = {};
|
||||
rad_op op_op[MAX_LAYERS] = {}, op_qn[MAX_LAYERS] = {}, op_kn[MAX_LAYERS] = {};
|
||||
rad_op op_gu[MAX_LAYERS] = {}, op_gug[MAX_LAYERS] = {}, op_dn[MAX_LAYERS] = {};
|
||||
rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn_swa = 0, op_attn_full = 0;
|
||||
rad_op op_act = 0, op_ar = 0, op_add = 0, op_final = 0;
|
||||
rad_op op_gather = 0, op_qsel = 0, op_head = 0, op_topk = 0, op_dgather = 0, op_pick = 0;
|
||||
|
||||
/* Candidates each rank contributes under a sharded head. The draft needs one, but the gather
|
||||
* moves whole 16-byte words per row and an (int32 id, f32 value) pair is 8 bytes, so R = 1 is
|
||||
* refused at launch (as rad_block_mtp_hc.h states). Two pairs make one word; `pair_argmax`
|
||||
* reduces the world * 2 of them to the global top-1. */
|
||||
static constexpr int64_t kTopR = 2;
|
||||
|
||||
static bool head_sharded(const Geom& g) { return vocab_head_sharded(g); }
|
||||
|
||||
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, const Wire& wire,
|
||||
const char* tok_src);
|
||||
void context(RadCtx* c, const RadBatch* batch) const;
|
||||
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; }
|
||||
/* The six linears must be quantised by the recipe. DenseFP8 declares E4M3 (or MXFP4) views
|
||||
* whatever the container holds, and the loader's error for a bf16 weight read through an fp8
|
||||
* view would name the view, not the missing recipe. */
|
||||
static int need_quantised(RadBuilder* b, const char* wn) {
|
||||
RadEncoding e{};
|
||||
if (!weight_enc(b, wn, &e) || e.n_planes <= 0) return RAD_OK; /* nothing to ask yet */
|
||||
const uint32_t dt = e.plane[0].dtype;
|
||||
if (dt == RAD_F8E4M3 || dt == RAD_FP4E2M1) return RAD_OK;
|
||||
fprintf(stderr, "radiance: gemma4: the DFlash drafter's '%s' is stored %s. Its six linears "
|
||||
"are served block fp8 (or MXFP4): convert with a recipe that names them, "
|
||||
"e.g. `dflash.blk.*.attn_q.weight rtn codes=fp8_e4m3 block=128x128 "
|
||||
"scale=bf16` and the same for fc, attn_k/v/output, ffn_gate_up and "
|
||||
"ffn_down.\n", wn, rad_dtype_name(dt));
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------------------ declare */
|
||||
|
||||
inline int Dflash1::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 Wire& wire, const char* tok_src) {
|
||||
g = geom; cfg = c; w = wire; first_layer = base_layer; kv = group; w_tok = tok_embd;
|
||||
if (!ck || !w_tok || !tok_src) return RAD_E_INVAL;
|
||||
if (g.n_layer <= 0 || g.n_layer > MAX_LAYERS) {
|
||||
fprintf(stderr, "radiance: gemma4: the drafter 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) 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;
|
||||
srows = g.max_seqs * cfg.steps();
|
||||
if (qrows <= 0 || srows <= 0) return RAD_E_INVAL;
|
||||
sharded = head_sharded(g);
|
||||
|
||||
/* ---------------------------------------------------------------- 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(need_quantised(b, nm.f("dflash.fc.weight")));
|
||||
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)));
|
||||
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());
|
||||
|
||||
/* ---------------------------------------------------------------- per-layer weights */
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
const RadWeightGroup gl = grp_layer(first_layer + i);
|
||||
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)));
|
||||
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, gl);
|
||||
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, gl);
|
||||
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, gl);
|
||||
w_kn[i] = decl_w(b, nm.f("dflash.blk.%d.attn_k_norm.weight", i), RAD_F32, {g.head_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl);
|
||||
/* The declared names match rad_block_dflash2.h's, so one recipe quantises both
|
||||
* drafters. */
|
||||
RAD_ARCH_TRY(w_q[i].declare(b, nm, nm.f("dflash.blk.%d.attn_q", i), qd, g.n_embd,
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl,
|
||||
{ nm.ckpt("%s.layers.%d.self_attn.q_proj.weight", ck, i) }));
|
||||
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, gl,
|
||||
{ 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, gl,
|
||||
{ nm.ckpt("%s.layers.%d.self_attn.v_proj.weight", ck, 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, gl,
|
||||
{ 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, gl,
|
||||
{ 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, gl,
|
||||
{ nm.ckpt("%s.layers.%d.mlp.down_proj.weight", ck, i) }));
|
||||
for (const char* s : { "attn_q", "attn_k", "attn_v", "attn_output", "ffn_gate_up",
|
||||
"ffn_down" })
|
||||
RAD_ARCH_TRY(need_quantised(b, nm.f("dflash.blk.%d.%s.weight", i, s)));
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- attention: two kinds
|
||||
* Declared before either kv_store, which reads `block_size` back from the resolved kernel.
|
||||
* Both read the one KV group, so whichever resolves first answers for it. */
|
||||
auto attn = [&](int causal, int64_t window) {
|
||||
return rw(b, RAD_OP(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, cfg.block), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", causal),
|
||||
RAD_INT("window", 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});
|
||||
};
|
||||
bool any_full = false, any_swa = false;
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) (cfg.full[l] ? any_full : any_swa) = true;
|
||||
if (any_swa) op_attn_swa = attn(1, cfg.window);
|
||||
if (any_full) op_attn_full = attn(0, 0);
|
||||
|
||||
/* ---------------------------------------------------------------- the context pass */
|
||||
op_qsrc = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", cfg.n_taps * g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.src}, {w.srcq, w.srcs});
|
||||
op_cfc = w_fc.gemm(b, crows, g.n_embd, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.c});
|
||||
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", 0.0),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_hnorm)),
|
||||
{w.c}, {w.c});
|
||||
op_qc = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.c}, {w.cq, w.cs});
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
op_ck[i] = w_k[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.ck});
|
||||
op_cv[i] = w_v[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.cv});
|
||||
op_cknorm[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
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", 0.0), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_kn[i])),
|
||||
{w.ck}, {w.ck});
|
||||
}
|
||||
op_crope = rw(b, decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
RAD_STR("mode", "neox")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.ck}, {w.ck});
|
||||
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_F64("mult", cfg.escale)),
|
||||
RAD_WEIGHTS(w_tok)),
|
||||
{}, {w.x});
|
||||
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});
|
||||
op_qh = 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.h}, {w.hq, w.hs});
|
||||
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});
|
||||
|
||||
/* x's norm under `gain`, quantised into hq|hs, in one launch; with `add`, the
|
||||
* fused_add_rms_norm form (x += h first). It computes exactly the chain's result: the norm of
|
||||
* the bf16-rounded sum and the codes of the bf16-rounded norm (libr4d/r4d_rows.cpp). */
|
||||
auto norm_quant = [&](rad_weight gain, bool add) -> rad_op {
|
||||
const rad_op h = RAD_OP(b, "rmsnorm_quant_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", g.dtype), RAD_F64("wadd", 0.0)),
|
||||
RAD_WEIGHTS(gain));
|
||||
return add ? rw(b, h, {w.h, w.x}, {w.x, w.hq, w.hs}) : rw(b, h, {w.x}, {w.hq, w.hs});
|
||||
};
|
||||
|
||||
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", 0.0),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_anorm[i])),
|
||||
{w.x}, {w.h});
|
||||
op_anq[i] = norm_quant(w_anorm[i], l > 0);
|
||||
op_qp[i] = w_q[i].gemm(b, qrows, qd, g.n_embd, {w.hq, w.hs}, {w.q});
|
||||
op_kp[i] = w_k[i].gemm(b, qrows, kvd, g.n_embd, {w.hq, w.hs}, {w.k});
|
||||
op_vp[i] = w_v[i].gemm(b, qrows, kvd, g.n_embd, {w.hq, w.hs}, {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", 0.0),
|
||||
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", 0.0), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_kn[i])),
|
||||
{w.k}, {w.k});
|
||||
op_op[i] = w_o[i].gemm(b, qrows, g.n_embd, qd, {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", 0.0),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_fnorm[i])),
|
||||
{w.x}, {w.h});
|
||||
op_fnq[i] = norm_quant(w_fnorm[i], true);
|
||||
op_gu[i] = w_gu[i].gemm(b, qrows, 2 * g.n_ff, g.n_embd, {w.hq, w.hs}, {w.gate_up});
|
||||
/* The gate_up|silu|quant fold where it resolves, else the pair (rad_block_dflash2.h's
|
||||
* rule, band included). */
|
||||
{
|
||||
const int64_t hi = qrows < 64 ? qrows : 64;
|
||||
if (hi > 0 && !w_gu[i].mx) {
|
||||
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.hq, w.hs}, {w.ffq, w.ffs});
|
||||
if (op_gug[i]) gated_rows = hi;
|
||||
}
|
||||
}
|
||||
op_dn[i] = w_dn[i].gemm(b, qrows, g.n_embd, g.n_ff, {w.ffq, w.ffs}, {w.h});
|
||||
}
|
||||
op_qrope = rw(b, decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
RAD_STR("mode", "neox")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.q}, {w.q});
|
||||
op_krope = rw(b, decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
RAD_STR("mode", "neox")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.k}, {w.k});
|
||||
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.h}, {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", 0.0),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_norm)),
|
||||
{w.x}, {w.h});
|
||||
|
||||
/* ---------------------------------------------------------------- the head
|
||||
* The mask rows (offsets 1..block-1 of each block, named by out_ids) are gathered contiguous,
|
||||
* projected onto this rank's slice of the target's vocabulary, and the argmax taken. Sharded,
|
||||
* each rank reports its best kTopR as global ids with logits; these are all-gathered and
|
||||
* reduced to the global top-1 by `pair_argmax` (ties to the lower id), which is exact since the
|
||||
* global winner is its own shard's first. */
|
||||
op_gather = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h}, {w.sel_h});
|
||||
/* The fp8 copy, where the container holds one (see the file header). The name map comes first
|
||||
* since it is how the encoding is looked up; rad-convert writes only declared weights. The
|
||||
* copy is row-sharded like the table, so this rank's rows are the same vocabulary slice and
|
||||
* `vocab_off` holds. */
|
||||
const char* dhn = nm.f("dflash.draft_head.weight");
|
||||
RAD_ARCH_TRY(map_copy(b, dhn, tok_src));
|
||||
RadEncoding he{};
|
||||
fp8_head = weight_enc(b, dhn, &he) && block_fp8_128(he);
|
||||
if (fp8_head) {
|
||||
if (g.n_vocab % RAD_FP8_BLOCK || g.n_embd % RAD_FP8_BLOCK) {
|
||||
fprintf(stderr, "radiance: gemma4: the fp8 draft head is %lldx%lld a rank, which "
|
||||
"is not whole %d-row scale blocks\n",
|
||||
(long long)g.n_vocab, (long long)g.n_embd, RAD_FP8_BLOCK);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const int shard = g.world > 1 ? RAD_SHARD_ROW : RAD_SHARD_NONE;
|
||||
w_dh.w = decl_view(b, dhn, nullptr, "codes", RAD_F8E4M3, { g.n_vocab, g.n_embd },
|
||||
RAD_ACCESS_PER_TOKEN, shard, grp_model());
|
||||
w_dh.s = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale", RAD_BF16,
|
||||
{ fp8_blocks(g.n_vocab), fp8_blocks(g.n_embd) }, RAD_ACCESS_PER_TOKEN,
|
||||
shard, grp_model());
|
||||
if (!w_dh.w || !w_dh.s) return RAD_E_INVAL;
|
||||
w.selq = decl_b(b, nm.f("df_selq"), RAD_F8E4M3, {srows, g.n_embd});
|
||||
w.sels = decl_b(b, nm.f("df_sels"), RAD_F32, {srows, fp8_blocks(g.n_embd)});
|
||||
op_qsel = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.sel_h}, {w.selq, w.sels});
|
||||
op_head = w_dh.gemm(b, srows, g.n_vocab, g.n_embd, {w.selq, w.sels}, {w.dlog});
|
||||
} else {
|
||||
op_head = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab),
|
||||
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_tok)),
|
||||
{w.sel_h}, {w.dlog});
|
||||
}
|
||||
if (sharded) {
|
||||
op_topk = rw(b, RAD_OP(b, "row_topk",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab),
|
||||
RAD_INT("R", kTopR), RAD_INT("vocab_off", g.vocab_off),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.dlog}, {w.cand, w.unary, w.dpair});
|
||||
/* Row-interleaved, so one draft position's pairs from every rank land side by side. */
|
||||
op_dgather = rw(b, RAD_OP(b, "all_gather",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_INT("numel", srows * kTopR * 2), RAD_STR("dtype", "f32"),
|
||||
RAD_INT("row", kTopR * 2)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.dpair}, {w.dgath});
|
||||
op_pick = rw(b, RAD_OP(b, "pair_argmax",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.world * kTopR),
|
||||
RAD_STR("dtype", "f32")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.dgath}, {w.tokens});
|
||||
if (!op_pick) {
|
||||
fprintf(stderr, "radiance: gemma4: the sharded draft head needs `pair_argmax` on the "
|
||||
"device, and no loaded kernel library serves it there\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
} else {
|
||||
op_topk = rw(b, RAD_OP(b, "row_topk",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab),
|
||||
RAD_INT("R", 1), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.dlog}, {w.tokens, w.unary});
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------------ the context pass */
|
||||
|
||||
inline void Dflash1::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, w_fc.bref());
|
||||
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, w_k[i].bref());
|
||||
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, w_v[i].bref());
|
||||
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 Dflash1::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;
|
||||
|
||||
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;
|
||||
const rad_op op_attn = cfg.full[i] ? op_attn_full : op_attn_swa;
|
||||
|
||||
/* The attention input, with the last layer's residual add where one launch takes both. */
|
||||
if (op_anq[i]) {
|
||||
RAD_ISSUE_N(c, op_anq[i], T, l > 0 ? brows(w.h, T) : brows(w.x, T),
|
||||
l > 0 ? brows(w.x, T) : RAD_NONE, RAD_W(w_anorm[i]), brows(w.hq, T),
|
||||
brows(w.hs, T), RAD_NONE);
|
||||
} else {
|
||||
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_qh, T, brows(w.h, T), brows(w.hq, T), brows(w.hs, T));
|
||||
}
|
||||
RAD_ISSUE_N(c, op_qp[i], T, brows(w.hq, T), brows(w.hs, T),
|
||||
RAD_W(w_q[i].w), RAD_W(w_q[i].s), brows(w.q, T), RAD_NONE, w_q[i].bref());
|
||||
RAD_ISSUE_N(c, op_kp[i], T, brows(w.hq, T), brows(w.hs, T),
|
||||
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.k, T), RAD_NONE, w_k[i].bref());
|
||||
RAD_ISSUE_N(c, op_vp[i], T, brows(w.hq, T), brows(w.hs, T),
|
||||
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.v, T), RAD_NONE, w_v[i].bref());
|
||||
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, w_o[i].bref());
|
||||
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
|
||||
if (op_fnq[i]) {
|
||||
RAD_ISSUE_N(c, op_fnq[i], T, brows(w.h, T), brows(w.x, T), RAD_W(w_fnorm[i]),
|
||||
brows(w.hq, T), brows(w.hs, T), RAD_NONE);
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h, T), brows(w.x, T));
|
||||
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_qh, T, brows(w.h, T), brows(w.hq, T), brows(w.hs, T));
|
||||
}
|
||||
if (op_gug[i] && T <= gated_rows) {
|
||||
RAD_ISSUE_N(c, op_gug[i], T, brows(w.hq, T), brows(w.hs, 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.hq, T), brows(w.hs, T),
|
||||
RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.gate_up, T), RAD_NONE,
|
||||
w_gu[i].bref());
|
||||
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, w_dn[i].bref());
|
||||
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
|
||||
/* the residual add, unless the next layer's input norm takes it */
|
||||
if (l + 1 == g.n_layer || !op_anq[i + 1])
|
||||
RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h, T), brows(w.x, T));
|
||||
}
|
||||
RAD_ISSUE_N(c, op_final, T, brows(w.x, T), RAD_W(w_norm), brows(w.h, T));
|
||||
|
||||
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));
|
||||
if (fp8_head) {
|
||||
RAD_ISSUE_N(c, op_qsel, S, brows(w.sel_h, S), brows(w.selq, S), brows(w.sels, S));
|
||||
RAD_ISSUE_N(c, op_head, S, brows(w.selq, S), brows(w.sels, S), RAD_W(w_dh.w),
|
||||
RAD_W(w_dh.s), brows(w.dlog, S), RAD_NONE, w_dh.bref());
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_head, S, brows(w.sel_h, S), RAD_W(w_tok), brows(w.dlog, S));
|
||||
}
|
||||
if (sharded) {
|
||||
RAD_ISSUE_N(c, op_topk, 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_pick, S, brows(w.dgath, S), brows(w.tokens, S), RAD_NONE);
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_topk, S, brows(w.dlog, S), brows(w.tokens, S), brows(w.unary, S),
|
||||
RAD_NONE);
|
||||
}
|
||||
}
|
||||
|
||||
} /* namespace gemma4 */
|
||||
|
||||
#endif /* GEMMA4_DFLASH_H */
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/gemma4_bf16 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(gemma4_bf16 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(gemma4_bf16 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/gemma4_bf16.cpp)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/lfm2_bf16 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(lfm2_bf16 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(lfm2_bf16 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/lfm2_bf16.cpp)
|
||||
@@ -0,0 +1,488 @@
|
||||
/* lfm2_bf16 -- LiquidAI's LFM2 and LFM2-VL, bf16 weights and activations, one rank.
|
||||
*
|
||||
* ============================== THE SHAPE ==============================
|
||||
*
|
||||
* A hybrid of two layer kinds, in the order the checkpoint's `layer_types` lists them (read, not
|
||||
* derived: d1-3B's schedule is irregular, attention at 2, 5, 9, 13, ...):
|
||||
*
|
||||
* conv in_proj -> [B | C | x], y = out_proj(C * conv(B * x)), where conv is a
|
||||
* depthwise causal convolution of width `conv_L_cache` with no activation
|
||||
* full_attention GQA with per-head RMS norms on q and k, NeoX rotary over the whole head
|
||||
*
|
||||
* each followed by a SwiGLU feed-forward (w1 the gate, w3 the up, w2 the down). Every norm is a
|
||||
* plain RMSNorm (`x_hat * w`, not Gemma's `1 + w`), and the final one is `embedding_norm`. At
|
||||
* d1-3B: 30 layers (10 attention), hidden 2048, 32 heads over 8 at head_dim 64, ffn 10752,
|
||||
* vocabulary 128000 with the lm_head tied to the embedding, conv width 3.
|
||||
*
|
||||
* LFM2-VL nests the same text model under `model.language_model` and adds a SigLIP2 tower and a
|
||||
* projector (siglip2.h), declared when the container carries their weights and the deployment
|
||||
* asked for media; the projector's rows replace the image placeholders' embeddings, which rotate
|
||||
* at their token positions like any other token. A text-only LFM2 checkpoint keeps the text model
|
||||
* under `model`. Which one this is comes from the config (a VL checkpoint has a `text_config`),
|
||||
* not the model's name.
|
||||
*
|
||||
* ============================== WHAT IT DOES NOT SERVE ==============================
|
||||
*
|
||||
* Tensor parallelism (a 3B model needs one card). A drafter, MoE (LFM2-8B-A1B), conv bias, or a
|
||||
* checkpoint without the rotary: each is refused by name.
|
||||
*/
|
||||
#include <arch/rad_arch.h>
|
||||
#include <arch/rad_block_mlp.h>
|
||||
#include <arch/rad_block_vit.h>
|
||||
|
||||
#include "siglip2.h"
|
||||
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace lfm2_bf16 {
|
||||
|
||||
using namespace rad::arch;
|
||||
|
||||
struct Layer {
|
||||
bool attention = false;
|
||||
MlpBF16 mlp;
|
||||
rad_weight w_norm = 0, w_in = 0, w_out = 0;
|
||||
/* conv */
|
||||
rad_weight w_conv = 0;
|
||||
rad_op op_gate_in = 0, op_conv = 0, op_gate_out = 0;
|
||||
/* attention: w_in is q, these are k, v and the two head norms */
|
||||
rad_weight w_k = 0, w_v = 0, w_q_norm = 0, w_k_norm = 0;
|
||||
rad_op op_k = 0, op_v = 0, op_q_norm = 0, op_k_norm = 0, op_rope_q = 0, op_rope_k = 0;
|
||||
rad_op op_store = 0, op_attn = 0;
|
||||
/* both */
|
||||
rad_op op_norm = 0, op_in = 0, op_out = 0, op_add = 0;
|
||||
};
|
||||
|
||||
struct Model {
|
||||
Names nm{""};
|
||||
Geom g{};
|
||||
int64_t width = 0; /* conv_L_cache: the convolution's taps */
|
||||
rad_kvgroup kv_attn = 0, kv_conv = 0;
|
||||
|
||||
rad_buf b_x = 0, b_h = 0, b_bcx = 0, b_conv_in = 0, b_conv_out = 0;
|
||||
rad_buf b_q = 0, b_k = 0, b_v = 0, b_attn = 0, b_gate_up = 0, b_ffn = 0;
|
||||
rad_buf b_hout = 0, b_logits = 0;
|
||||
|
||||
rad_weight w_tok = 0, w_out_norm = 0, w_lm_head = 0;
|
||||
rad_op op_embed = 0, op_gather = 0, op_final_norm = 0, op_logits = 0;
|
||||
|
||||
std::vector<Layer> layers;
|
||||
|
||||
/* LFM2-VL's images: the tower and the scatter of its rows over the embeddings. */
|
||||
bool media = false;
|
||||
Siglip2 vit{};
|
||||
MediaRows mrows{};
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
|
||||
/* A text_config key first, then the top level: a VL checkpoint nests the text model's settings
|
||||
* and a text checkpoint does not. */
|
||||
static const char* text_key(const RadModelMeta* m, const char* key) {
|
||||
const std::string nested = std::string("text_config.") + key;
|
||||
const char* v = rad_meta_gets(m, nested.c_str(), nullptr);
|
||||
return v ? v : rad_meta_gets(m, key, nullptr);
|
||||
}
|
||||
static int64_t text_int(const RadModelMeta* m, const char* key, int64_t dflt) {
|
||||
const char* v = text_key(m, key);
|
||||
return v ? std::strtoll(v, nullptr, 10) : dflt;
|
||||
}
|
||||
static bool text_bool(const RadModelMeta* m, const char* key, bool dflt) {
|
||||
const char* v = text_key(m, key);
|
||||
if (!v) return dflt;
|
||||
return std::strcmp(v, "true") == 0 || std::strcmp(v, "1") == 0;
|
||||
}
|
||||
|
||||
/* `layer_types`, one word per layer, space-separated in the container. */
|
||||
static int read_schedule(const RadModelMeta* m, int64_t n_layer, std::vector<Layer>* out) {
|
||||
const char* s = text_key(m, "layer_types");
|
||||
if (!s || !*s) {
|
||||
fprintf(stderr, "radiance: lfm2: the container has no layer_types; this family's schedule "
|
||||
"is irregular and is not derived\n");
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
std::istringstream in(s);
|
||||
std::string kind;
|
||||
while (in >> kind) {
|
||||
if (kind != "conv" && kind != "full_attention") {
|
||||
fprintf(stderr, "radiance: lfm2: layer_types[%zu] is '%s'; this plugin knows 'conv' "
|
||||
"and 'full_attention'\n", out->size(), kind.c_str());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
Layer l;
|
||||
l.attention = kind == "full_attention";
|
||||
out->push_back(l);
|
||||
}
|
||||
if ((int64_t)out->size() != n_layer) {
|
||||
fprintf(stderr, "radiance: lfm2: layer_types names %zu layers and the model has %lld\n",
|
||||
out->size(), (long long)n_layer);
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
if (ctx->world_size > 1) {
|
||||
fprintf(stderr, "radiance: lfm2_bf16 serves one rank; run it with --tp 1\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (meta->n_expert > 0 || text_bool(meta, "conv_bias", false) ||
|
||||
!text_bool(meta, "block_use_swiglu", true) || !text_bool(meta, "use_pos_enc", true)) {
|
||||
fprintf(stderr, "radiance: lfm2_bf16 serves the dense SwiGLU model with rotary "
|
||||
"attention and bias-free convolutions; this checkpoint is not that\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
Model& m = g_model[ctx->rank];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
Names& nm = m.nm;
|
||||
|
||||
/* The FFN width as stated, unless the config asks for LFM2's sizing rule (1.2B and smaller
|
||||
* releases): two thirds of it, times the multiplier, rounded up to `multiple_of`. */
|
||||
RadModelMeta dims = *meta;
|
||||
if (text_bool(meta, "block_auto_adjust_ff_dim", false)) {
|
||||
int64_t ff = 2 * dims.n_ff / 3;
|
||||
if (const char* mult = text_key(meta, "block_ffn_dim_multiplier")) {
|
||||
const int64_t of = text_int(meta, "block_multiple_of", 256);
|
||||
const double f = std::strtod(mult, nullptr);
|
||||
if (!(f > 0.0) || of <= 0) return RAD_E_FORMAT;
|
||||
ff = (int64_t)(f * (double)ff);
|
||||
ff = of * ((ff + of - 1) / of);
|
||||
}
|
||||
dims.n_ff = ff;
|
||||
}
|
||||
RAD_ARCH_TRY(geom_from(m.g, &dims, ctx, "bf16", RAD_BF16));
|
||||
Geom& g = m.g;
|
||||
RAD_ARCH_TRY(yarn_from(g, meta, "", g.head_dim));
|
||||
RAD_ARCH_TRY(read_schedule(meta, g.n_layer, &m.layers));
|
||||
m.width = text_int(meta, "conv_L_cache", 0);
|
||||
if (m.width < 2 || m.width > 8) {
|
||||
fprintf(stderr, "radiance: lfm2: conv_L_cache %lld is outside the 2..8 the convolution "
|
||||
"kernels serve\n", (long long)m.width);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
const char* pre = rad_meta_gets(meta, "text_config.num_hidden_layers", nullptr)
|
||||
? "model.language_model" : "model";
|
||||
|
||||
/* ---- the two state groups: paged KV for the attention layers, and a rolling window of the
|
||||
* convolution's last width-1 inputs (plus the speculative slack the manager adds) for the
|
||||
* conv layers. The conv group's channels are n_head_kv * head_dim: one "head" of n_embd. */
|
||||
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_attn = rad_decl_kv_group(b, nm.f("kv_attn"), &fd);
|
||||
g.kv_dtype = rad_dtype_name(fd.dtype);
|
||||
|
||||
RadKVGroupDecl cd{};
|
||||
cd.kind = RAD_KV_CONV;
|
||||
cd.dtype = RAD_BF16;
|
||||
cd.n_head_kv = 1;
|
||||
cd.head_dim = g.n_embd;
|
||||
cd.conv_width = m.width;
|
||||
m.kv_conv = rad_decl_kv_group(b, nm.f("kv_conv"), &cd);
|
||||
if (!m.kv_attn || !m.kv_conv) return RAD_E_INVAL;
|
||||
|
||||
m.b_x = decl_b(b, nm.f("x"), RAD_BF16, {g.max_tok, g.n_embd});
|
||||
m.b_h = decl_b(b, nm.f("h"), RAD_BF16, {g.max_tok, g.n_embd});
|
||||
m.b_bcx = decl_b(b, nm.f("conv_bcx"), RAD_BF16, {g.max_tok, 3 * g.n_embd});
|
||||
m.b_conv_in = decl_b(b, nm.f("conv_in"), RAD_BF16, {g.max_tok, g.n_embd});
|
||||
m.b_conv_out = decl_b(b, nm.f("conv_out"), RAD_BF16, {g.max_tok, g.n_embd});
|
||||
m.b_q = decl_b(b, nm.f("attn_q"), RAD_BF16, {g.max_tok, g.q_dim()});
|
||||
m.b_k = decl_b(b, nm.f("attn_k"), RAD_BF16, {g.max_tok, g.kv_dim()});
|
||||
m.b_v = decl_b(b, nm.f("attn_v"), RAD_BF16, {g.max_tok, g.kv_dim()});
|
||||
m.b_attn = decl_b(b, nm.f("attn_out"), RAD_BF16, {g.max_tok, g.q_dim()});
|
||||
m.b_gate_up = decl_b(b, nm.f("gate_up"), RAD_BF16, {g.max_tok, 2 * g.n_ff});
|
||||
m.b_ffn = decl_b(b, nm.f("ffn"), RAD_BF16, {g.max_tok, g.n_ff});
|
||||
m.b_hout = decl_b(b, nm.f("h_out"), RAD_BF16, {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. The lm_head is tied but declared as its own weight: the
|
||||
* embedding may live in host memory (--embedding-placement) and the head on the card, and a
|
||||
* kernel may want a head layout the lookup does not read. */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("%s.embed_tokens.weight", pre)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("%s.embedding_norm.weight", pre)));
|
||||
RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"),
|
||||
nm.ckpt("%s.embed_tokens.weight", pre)));
|
||||
m.w_tok = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, {g.n_vocab, g.n_embd},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, 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"), RAD_BF16, {g.n_vocab, g.n_embd},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, 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_WEIGHTS(m.w_tok)),
|
||||
{}, {m.b_x});
|
||||
/* The encoder's rows overwrite the lookup; with one rank there is no reduction after it. */
|
||||
m.media = Siglip2::present(meta) && ctx->max_enc_patches > 0;
|
||||
if (m.media) RAD_ARCH_TRY(m.mrows.declare(b, g.max_tok, g.n_embd, m.b_x));
|
||||
|
||||
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;
|
||||
|
||||
auto gemm = [&](int64_t N, int64_t K, rad_weight w, rad_buf in, rad_buf out) {
|
||||
return rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w)),
|
||||
{in}, {out});
|
||||
};
|
||||
auto rmsnorm = [&](int64_t rows, int64_t n, rad_weight w, rad_buf in, rad_buf out) {
|
||||
return rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", g.eps),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w)),
|
||||
{in}, {out});
|
||||
};
|
||||
auto layer_w = [&](const char* name, int l, std::initializer_list<int64_t> shape,
|
||||
uint32_t dtype) {
|
||||
return decl_w(b, nm.f(name, l), dtype, shape, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp_layer(l));
|
||||
};
|
||||
|
||||
for (int l = 0; l < (int)m.layers.size(); ++l) {
|
||||
Layer& L = m.layers[(size_t)l];
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l),
|
||||
nm.ckpt("%s.layers.%d.operator_norm.weight", pre, l)));
|
||||
L.w_norm = layer_w("blk.%d.attn_norm.weight", l, {g.n_embd}, RAD_F32);
|
||||
L.op_norm = rmsnorm(g.max_tok, g.n_embd, L.w_norm, m.b_x, m.b_h);
|
||||
|
||||
if (L.attention) {
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, m.kv_attn));
|
||||
const char* a = "%s.layers.%d.self_attn.%s";
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q.weight", l), nm.ckpt(a, pre, l, "q_proj.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k.weight", l), nm.ckpt(a, pre, l, "k_proj.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_v.weight", l), nm.ckpt(a, pre, l, "v_proj.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_norm.weight", l),
|
||||
nm.ckpt(a, pre, l, "q_layernorm.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k_norm.weight", l),
|
||||
nm.ckpt(a, pre, l, "k_layernorm.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_output.weight", l),
|
||||
nm.ckpt(a, pre, l, "out_proj.weight")));
|
||||
L.w_in = layer_w("blk.%d.attn_q.weight", l, {g.q_dim(), g.n_embd}, RAD_BF16);
|
||||
L.w_k = layer_w("blk.%d.attn_k.weight", l, {g.kv_dim(), g.n_embd}, RAD_BF16);
|
||||
L.w_v = layer_w("blk.%d.attn_v.weight", l, {g.kv_dim(), g.n_embd}, RAD_BF16);
|
||||
L.w_q_norm = layer_w("blk.%d.attn_q_norm.weight", l, {g.head_dim}, RAD_F32);
|
||||
L.w_k_norm = layer_w("blk.%d.attn_k_norm.weight", l, {g.head_dim}, RAD_F32);
|
||||
L.w_out = layer_w("blk.%d.attn_output.weight", l, {g.n_embd, g.q_dim()}, RAD_BF16);
|
||||
|
||||
L.op_in = gemm(g.q_dim(), g.n_embd, L.w_in, m.b_h, m.b_q);
|
||||
L.op_k = gemm(g.kv_dim(), g.n_embd, L.w_k, m.b_h, m.b_k);
|
||||
L.op_v = gemm(g.kv_dim(), g.n_embd, L.w_v, m.b_h, m.b_v);
|
||||
/* The head norms run over rows of head_dim: a [T, heads * head_dim] buffer is
|
||||
* T * heads rows. */
|
||||
L.op_q_norm = rmsnorm(g.max_tok * g.n_head, g.head_dim, L.w_q_norm, m.b_q, m.b_q);
|
||||
L.op_k_norm = rmsnorm(g.max_tok * g.n_head_kv, g.head_dim, L.w_k_norm, m.b_k, m.b_k);
|
||||
L.op_rope_q = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, 0, g.head_dim,
|
||||
"neox"), {m.b_q}, {m.b_q});
|
||||
L.op_rope_k = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head_kv, 0, g.head_dim,
|
||||
"neox"), {m.b_k}, {m.b_k});
|
||||
/* attn_paged before kv_store: the cache's block size is read from the resolved
|
||||
* attention kernel. */
|
||||
L.op_attn = rw(b, RAD_OP(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok),
|
||||
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),
|
||||
{m.b_q}, {m.b_attn});
|
||||
L.op_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, m.kv_attn)),
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_k, m.b_v}, {});
|
||||
L.op_out = gemm(g.n_embd, g.q_dim(), L.w_out, m.b_attn, m.b_h);
|
||||
} else {
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, m.kv_conv));
|
||||
const char* c = "%s.layers.%d.conv.%s";
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.conv_in.weight", l), nm.ckpt(c, pre, l, "in_proj.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.conv.weight", l), nm.ckpt(c, pre, l, "conv.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.conv_out.weight", l), nm.ckpt(c, pre, l, "out_proj.weight")));
|
||||
L.w_in = layer_w("blk.%d.conv_in.weight", l, {3 * g.n_embd, g.n_embd}, RAD_BF16);
|
||||
/* The checkpoint ships [n_embd, 1, width]; the depthwise group axis is squeezed at
|
||||
* convert, as the gated delta net's conv1d is. */
|
||||
L.w_conv = layer_w("blk.%d.conv.weight", l, {g.n_embd, m.width}, RAD_BF16);
|
||||
L.w_out = layer_w("blk.%d.conv_out.weight", l, {g.n_embd, g.n_embd}, RAD_BF16);
|
||||
|
||||
/* in_proj's row is [B | C | x]: conv(B * x), then C * that. */
|
||||
L.op_in = gemm(3 * g.n_embd, g.n_embd, L.w_in, m.b_h, m.b_bcx);
|
||||
L.op_gate_in = rw(b, RAD_OP(b, "mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_bcx}, {m.b_conv_in});
|
||||
L.op_conv = rw(b, RAD_OP(b, "causal_conv1d",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("width", m.width), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(L.w_conv)),
|
||||
{m.b_conv_in}, {m.b_conv_out});
|
||||
L.op_gate_out = rw(b, RAD_OP(b, "mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_bcx, m.b_conv_out}, {m.b_conv_out});
|
||||
L.op_out = gemm(g.n_embd, g.n_embd, L.w_out, m.b_conv_out, m.b_h);
|
||||
}
|
||||
L.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),
|
||||
{m.b_x, m.b_h}, {m.b_x});
|
||||
|
||||
MlpBF16::Src ms{};
|
||||
ms.norm = nm.ckpt("%s.layers.%d.ffn_norm.weight", pre, l);
|
||||
ms.gate = nm.ckpt("%s.layers.%d.feed_forward.w1.weight", pre, l);
|
||||
ms.up = nm.ckpt("%s.layers.%d.feed_forward.w3.weight", pre, l);
|
||||
ms.down = nm.ckpt("%s.layers.%d.feed_forward.w2.weight", pre, l);
|
||||
RAD_ARCH_TRY(L.mlp.declare(b, nm, g, l, mw, ms));
|
||||
}
|
||||
|
||||
/* The final norm runs on the gathered rows only: it is per token, and those are the rows the
|
||||
* lm_head reads. */
|
||||
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_x}, {m.b_hout});
|
||||
m.op_final_norm = rmsnorm(g.max_logit_rows, g.n_embd, m.w_out_norm, m.b_hout, 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 vision tower, last, so its activations share the arena with every buffer above. */
|
||||
if (m.media) RAD_ARCH_TRY(m.vit.declare(b, meta, ctx, nm, g.n_embd, (int)g.n_layer + 64));
|
||||
|
||||
int64_t n_attn = 0;
|
||||
for (const Layer& L : m.layers) n_attn += L.attention ? 1 : 0;
|
||||
rad_note(b, "lfm2: %lld layers, %lld attention + %lld short convolution of width %lld; "
|
||||
"%lld heads over %lld at head_dim %lld, ffn %lld, vocab %lld",
|
||||
(long long)g.n_layer, (long long)n_attn, (long long)(g.n_layer - n_attn),
|
||||
(long long)m.width, (long long)g.n_head, (long long)g.n_head_kv,
|
||||
(long long)g.head_dim, (long long)g.n_ff, (long long)g.n_vocab);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The convolution is issued once per half of the step, like the PLE's and the gated delta net's:
|
||||
* the decode rows [0, D) with `num_accepted`, leaving the window in the layout a partly rejected
|
||||
* verify reads back from, and the prefill chunks [D, S) without it, each leaving its tail at
|
||||
* offset zero. `has_init` is `ctx_lens` (a sequence with earlier tokens has a history). The
|
||||
* prefill half's per-sequence arrays start at `+ D`; the token operands stay at their base, since
|
||||
* the kernel reads rows at the absolute offsets in `cu`. */
|
||||
static void conv_step(const Model& m, const Layer& L, RadCtx* c, const RadBatch* batch, int l) {
|
||||
const int64_t T = batch->n_tok, S = batch->n_seq;
|
||||
const RadKVGroupBatch* cv = kv_batch(batch, m.kv_conv);
|
||||
const int32_t* idx = cv ? cv->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, L.op_conv, DT,
|
||||
brows(m.b_conv_in, DT), RAD_W(L.w_conv), kv_cache(m.kv_conv, l),
|
||||
praw(batch->cu_seqlens, RAD_I32, D + 1), praw(idx, RAD_I32, D),
|
||||
praw(batch->ctx_lens, RAD_I32, D), praw(batch->num_accepted, RAD_I32, D),
|
||||
brows(m.b_conv_out, DT));
|
||||
if (P > 0)
|
||||
RAD_ISSUE_N(c, L.op_conv, T,
|
||||
brows(m.b_conv_in, T), RAD_W(L.w_conv), kv_cache(m.kv_conv, l),
|
||||
praw(batch->cu_seqlens + D, RAD_I32, P + 1),
|
||||
praw(idx ? idx + D : nullptr, RAD_I32, P),
|
||||
praw(batch->ctx_lens + D, RAD_I32, P), RAD_NONE,
|
||||
brows(m.b_conv_out, T));
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Geom& g = m.g;
|
||||
if (batch->draft_pass || batch->spec_parent ||
|
||||
(!m.media && (batch->enc || batch->n_mm_rows > 0))) {
|
||||
rad_step_fail(c, "lfm2_bf16: this step asks for an encoder, a draft pass or media rows, "
|
||||
"and the program declares none of them");
|
||||
return;
|
||||
}
|
||||
/* An encoder pass runs only the vision tower (RadBatch::enc). */
|
||||
if (batch->enc) {
|
||||
m.vit.step(c, batch);
|
||||
return;
|
||||
}
|
||||
const int64_t T = batch->n_tok, n = g.n_embd;
|
||||
RAD_ISSUE(c, m.op_embed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.b_x, T));
|
||||
m.mrows.step(c, batch, m.b_x, T);
|
||||
|
||||
for (int l = 0; l < (int)m.layers.size(); ++l) {
|
||||
const Layer& L = m.layers[(size_t)l];
|
||||
RAD_ISSUE(c, L.op_norm, brows(m.b_x, T), RAD_W(L.w_norm), brows(m.b_h, T));
|
||||
if (L.attention) {
|
||||
const RadKVGroupBatch* kv = kv_batch(batch, m.kv_attn);
|
||||
RAD_ISSUE(c, L.op_in, brows(m.b_h, T), RAD_W(L.w_in), brows(m.b_q, T));
|
||||
RAD_ISSUE(c, L.op_k, brows(m.b_h, T), RAD_W(L.w_k), brows(m.b_k, T));
|
||||
RAD_ISSUE(c, L.op_v, brows(m.b_h, T), RAD_W(L.w_v), brows(m.b_v, T));
|
||||
RAD_ISSUE_N(c, L.op_q_norm, T * g.n_head, brows(m.b_q, T), RAD_W(L.w_q_norm),
|
||||
brows(m.b_q, T));
|
||||
RAD_ISSUE_N(c, L.op_k_norm, T * g.n_head_kv, brows(m.b_k, T), RAD_W(L.w_k_norm),
|
||||
brows(m.b_k, T));
|
||||
RAD_ISSUE(c, L.op_rope_q, brows(m.b_q, T), rope_pos1(batch, T));
|
||||
RAD_ISSUE(c, L.op_rope_k, brows(m.b_k, T), rope_pos1(batch, T));
|
||||
RAD_ISSUE(c, L.op_store, brows(m.b_k, T), brows(m.b_v, T),
|
||||
praw(kv ? kv->slot_mapping : nullptr, RAD_I32, T), kv_cache(m.kv_attn, l));
|
||||
RAD_ISSUE_N(c, L.op_attn, batch->max_q_len,
|
||||
brows(m.b_q, T), kv_cache(m.kv_attn, l),
|
||||
praw2(kv ? kv->block_table : nullptr, RAD_I32, batch->n_seq,
|
||||
kv ? kv->block_table_pitch : 0),
|
||||
praw(kv ? kv->seqused : nullptr, RAD_I32, batch->n_seq),
|
||||
RAD_NONE, RAD_NONE,
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
|
||||
brows(m.b_attn, T));
|
||||
RAD_ISSUE(c, L.op_out, brows(m.b_attn, T), RAD_W(L.w_out), brows(m.b_h, T));
|
||||
} else {
|
||||
RAD_ISSUE(c, L.op_in, brows(m.b_h, T), RAD_W(L.w_in), brows(m.b_bcx, T));
|
||||
RAD_ISSUE(c, L.op_gate_in, bcol(m.b_bcx, 0, n, T), bcol(m.b_bcx, 2 * n, n, T),
|
||||
brows(m.b_conv_in, T));
|
||||
conv_step(m, L, c, batch, l);
|
||||
RAD_ISSUE(c, L.op_gate_out, bcol(m.b_bcx, n, n, T), brows(m.b_conv_out, T),
|
||||
brows(m.b_conv_out, T));
|
||||
RAD_ISSUE(c, L.op_out, brows(m.b_conv_out, T), RAD_W(L.w_out), brows(m.b_h, T));
|
||||
}
|
||||
RAD_ISSUE(c, L.op_add, brows(m.b_x, T), brows(m.b_h, T), brows(m.b_x, T));
|
||||
L.mlp.step(c, batch);
|
||||
}
|
||||
|
||||
/* The lm_head runs only on the rows the sampler asked for; a prefill chunk that finishes no
|
||||
* sequence skips it. */
|
||||
if (batch->n_out > 0) {
|
||||
RAD_ISSUE_N(c, m.op_gather, batch->n_out, brows(m.b_x, T),
|
||||
praw(batch->out_ids, RAD_I32, batch->n_out), brows(m.b_hout, batch->n_out));
|
||||
RAD_ISSUE_N(c, m.op_final_norm, batch->n_out, brows(m.b_hout, batch->n_out),
|
||||
RAD_W(m.w_out_norm), 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 lfm2_bf16 */
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PLUGIN(lfm2_bf16, "lfm2", "", "0.1.0",
|
||||
"LiquidAI LFM2 / LFM2-VL, bf16: short gated convolutions and GQA attention in the "
|
||||
"checkpoint's own schedule, one rank; LFM2-VL's SigLIP2 tower for images")
|
||||
#endif
|
||||
@@ -0,0 +1,325 @@
|
||||
/* siglip2.h -- LFM2-VL's image encoder: the SigLIP2 NaFlex tower and the projector after it.
|
||||
*
|
||||
* Per encoder pass (RadBatch::enc):
|
||||
*
|
||||
* x = patches @ Wp^T + bp the patch embedding, a linear layer over a patch
|
||||
* row (y, x, channel)
|
||||
* x += pos_table resampled to each segment's grid torch's antialiased half-pixel bilinear
|
||||
* (grid_embed_aa), rounded before the add
|
||||
* depth times:
|
||||
* x += out(attn(qkv(LN1(x)))) full attention within a segment (one tile or the
|
||||
* thumbnail), no rotary
|
||||
* x += fc2(gelu_tanh(fc1(LN2(x))))
|
||||
* y = post_LN(x)
|
||||
* out = l2(gelu(l1([LN](y viewed [P/merge^2, merge^2 * width])))) the projector
|
||||
*
|
||||
* i.e. transformers' Siglip2VisionModel (no pooling head) then Lfm2VlMultiModalProjector. The
|
||||
* projector's pixel unshuffle is a view: the processor stores each segment's patches in
|
||||
* merge-block order (core/mm/processor.cpp, image_lfm2), so a block's merge^2 patches are
|
||||
* consecutive rows, dy then dx, the order the unshuffle concatenates them. The tower is
|
||||
* order-independent: attention within a segment is permutation-equivariant, every other layer is
|
||||
* per patch, and the position table is resampled at each patch's own (row, column).
|
||||
*
|
||||
* q, k and v are one fused weight, concatenated at convert (map_concat), so a layer is one QKV
|
||||
* GEMM; the attention reads the three as column slices.
|
||||
*
|
||||
* Replicated, per-request weights and pass-sized activations, as in arch/common/rad_block_vit.h's
|
||||
* tower.
|
||||
*/
|
||||
#ifndef LFM2_SIGLIP2_H
|
||||
#define LFM2_SIGLIP2_H
|
||||
|
||||
#include <arch/rad_arch.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
namespace lfm2_bf16 {
|
||||
|
||||
using namespace rad::arch;
|
||||
|
||||
struct Siglip2 {
|
||||
int64_t depth = 0, width = 0, heads = 0, ff = 0, patch = 0, merge = 0, side = 0;
|
||||
int64_t head_dim = 0, patch_dim = 0, proj_hidden = 0, n_embd = 0, P = 0;
|
||||
float eps = 1e-6f;
|
||||
bool proj_norm = false, 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, attn = 0, proj = 0, ln2 = 0, up = 0, down = 0;
|
||||
};
|
||||
std::vector<Layer> L;
|
||||
rad_weight w_patch = 0, b_patch = 0, w_pos = 0, pn_w = 0, pn_b = 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_post = 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_mn = 0, b_mf = 0;
|
||||
rad_buf b_out = 0;
|
||||
|
||||
/* A tower to declare: the container is an LFM2-VL one, whose vision_config is SigLIP2's. */
|
||||
static bool present(const RadModelMeta* m) {
|
||||
return !std::strcmp(rad_meta_gets(m, "vision_config.model_type", ""), "siglip2_vision_model") &&
|
||||
rad_meta_geti(m, "vision_config.num_hidden_layers", 0) > 0;
|
||||
}
|
||||
|
||||
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 Siglip2::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.num_hidden_layers", 0);
|
||||
width = rad_meta_geti(m, "vision_config.hidden_size", 0);
|
||||
heads = rad_meta_geti(m, "vision_config.num_attention_heads", 0);
|
||||
ff = rad_meta_geti(m, "vision_config.intermediate_size", 0);
|
||||
patch = rad_meta_geti(m, "vision_config.patch_size", 0);
|
||||
eps = (float)rad_meta_getf(m, "vision_config.layer_norm_eps", 1e-6);
|
||||
const int64_t chans = rad_meta_geti(m, "vision_config.num_channels", 3);
|
||||
const int64_t npos = rad_meta_geti(m, "vision_config.num_patches", 0);
|
||||
merge = rad_meta_geti(m, "downsample_factor", 0);
|
||||
proj_hidden = rad_meta_geti(m, "projector_hidden_size", 0);
|
||||
n_embd = model_embd;
|
||||
side = (int64_t)std::llround(std::sqrt((double)npos));
|
||||
if (depth <= 0 || width <= 0 || heads <= 0 || ff <= 0 || patch <= 0 || merge <= 0 ||
|
||||
proj_hidden <= 0 || side <= 0 || side * side != npos || width % heads || chans != 3) {
|
||||
fprintf(stderr, "radiance: lfm2: the container's SigLIP2 vision_config is incomplete or "
|
||||
"inconsistent (layers %lld, hidden %lld, heads %lld, ff %lld, patch %lld, "
|
||||
"positions %lld, channels %lld; downsample_factor %lld, projector %lld)\n",
|
||||
(long long)depth, (long long)width, (long long)heads, (long long)ff,
|
||||
(long long)patch, (long long)npos, (long long)chans, (long long)merge,
|
||||
(long long)proj_hidden);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* The pooling head is SigLIP2's contrastive readout; LFM2-VL reads the patch rows, so a
|
||||
* checkpoint that ships a head is refused by name rather than loading unused weights. */
|
||||
if (rad_meta_geti(m, "vision_config.vision_use_head", 0) != 0 ||
|
||||
!std::strcmp(rad_meta_gets(m, "vision_config.vision_use_head", ""), "true")) {
|
||||
fprintf(stderr, "radiance: lfm2: this SigLIP2 tower has a pooling head, which LFM2-VL does "
|
||||
"not read and this plugin does not serve\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const char* act = rad_meta_gets(m, "vision_config.hidden_act", "gelu_pytorch_tanh");
|
||||
const char* pact = rad_meta_gets(m, "projector_hidden_act", "gelu");
|
||||
if (std::strcmp(act, "gelu_pytorch_tanh") || std::strcmp(pact, "gelu")) {
|
||||
fprintf(stderr, "radiance: lfm2: the tower's activation '%s' and the projector's '%s' are "
|
||||
"not gelu_pytorch_tanh and gelu, which is what this plugin serves\n",
|
||||
act, pact);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const char* pb = rad_meta_gets(m, "projector_bias", "true");
|
||||
if (std::strcmp(pb, "true") && std::strcmp(pb, "1")) {
|
||||
fprintf(stderr, "radiance: lfm2: a projector without biases is not served\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
proj_norm = !std::strcmp(rad_meta_gets(m, "projector_use_layernorm", "true"), "true") ||
|
||||
!std::strcmp(rad_meta_gets(m, "projector_use_layernorm", "true"), "1");
|
||||
head_dim = width / heads;
|
||||
patch_dim = chans * patch * patch;
|
||||
|
||||
const int64_t mm = merge * merge, mw = mm * width;
|
||||
P = ctx->max_enc_patches;
|
||||
/* The longest segment attention sees: a tile or the largest thumbnail, which the processor
|
||||
* keeps within max_num_patches. It selects the attention kernel's block height, so a sizing
|
||||
* declare uses the real value too. */
|
||||
const int64_t seg = rad_meta_geti(m, "processor.image_processor.max_num_patches",
|
||||
rad_meta_geti(m, "max_num_patches", P));
|
||||
const int64_t max_seg = std::min<int64_t>(P, seg);
|
||||
if (ctx->shape_probe) {
|
||||
const int64_t r = std::min<int64_t>(P, ctx->max_tok);
|
||||
P = std::max<int64_t>(mm, r / mm * mm);
|
||||
}
|
||||
if (P % mm) return RAD_E_SHAPE;
|
||||
const int64_t R = P / mm;
|
||||
const int ACC = RAD_ACCESS_PER_REQUEST;
|
||||
|
||||
auto bw = [&](const char* dn, const char* src, std::initializer_list<int64_t> shp,
|
||||
RadWeightGroup g) -> rad_weight {
|
||||
if (map_copy(b, dn, src) < 0) return 0;
|
||||
return decl_w(b, dn, RAD_BF16, shp, ACC, RAD_SHARD_NONE, g);
|
||||
};
|
||||
const char* tw = "model.vision_tower.vision_model.";
|
||||
w_patch = bw(nm.f("v.patch.weight"), nm.ckpt("%sembeddings.patch_embedding.weight", tw),
|
||||
{ width, patch_dim }, grp_model());
|
||||
b_patch = bw(nm.f("v.patch.bias"), nm.ckpt("%sembeddings.patch_embedding.bias", tw),
|
||||
{ width }, grp_model());
|
||||
w_pos = bw(nm.f("v.pos.weight"), nm.ckpt("%sembeddings.position_embedding.weight", tw),
|
||||
{ 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;
|
||||
const char* e = "%sencoder.layers.%d.%s";
|
||||
l.n1w = bw(nm.f("v.blk.%d.norm1.weight", li), nm.ckpt(e, tw, li, "layer_norm1.weight"), { width }, g);
|
||||
l.n1b = bw(nm.f("v.blk.%d.norm1.bias", li), nm.ckpt(e, tw, li, "layer_norm1.bias"), { width }, g);
|
||||
l.n2w = bw(nm.f("v.blk.%d.norm2.weight", li), nm.ckpt(e, tw, li, "layer_norm2.weight"), { width }, g);
|
||||
l.n2b = bw(nm.f("v.blk.%d.norm2.bias", li), nm.ckpt(e, tw, li, "layer_norm2.bias"), { width }, g);
|
||||
/* q, k, v fused at convert: one GEMM per layer. */
|
||||
const char* qw = nm.f("v.blk.%d.qkv.weight", li);
|
||||
const char* qb = nm.f("v.blk.%d.qkv.bias", li);
|
||||
if (map_concat(b, qw, { nm.ckpt(e, tw, li, "self_attn.q_proj.weight"),
|
||||
nm.ckpt(e, tw, li, "self_attn.k_proj.weight"),
|
||||
nm.ckpt(e, tw, li, "self_attn.v_proj.weight") }) < 0 ||
|
||||
map_concat(b, qb, { nm.ckpt(e, tw, li, "self_attn.q_proj.bias"),
|
||||
nm.ckpt(e, tw, li, "self_attn.k_proj.bias"),
|
||||
nm.ckpt(e, tw, li, "self_attn.v_proj.bias") }) < 0)
|
||||
return RAD_E_INVAL;
|
||||
l.qkv_w = decl_w(b, qw, RAD_BF16, { 3 * width, width }, ACC, RAD_SHARD_NONE, g);
|
||||
l.qkv_b = decl_w(b, qb, RAD_BF16, { 3 * width }, ACC, RAD_SHARD_NONE, g);
|
||||
l.out_w = bw(nm.f("v.blk.%d.proj.weight", li), nm.ckpt(e, tw, li, "self_attn.out_proj.weight"), { width, width }, g);
|
||||
l.out_b = bw(nm.f("v.blk.%d.proj.bias", li), nm.ckpt(e, tw, li, "self_attn.out_proj.bias"), { width }, g);
|
||||
l.up_w = bw(nm.f("v.blk.%d.fc1.weight", li), nm.ckpt(e, tw, li, "mlp.fc1.weight"), { ff, width }, g);
|
||||
l.up_b = bw(nm.f("v.blk.%d.fc1.bias", li), nm.ckpt(e, tw, li, "mlp.fc1.bias"), { ff }, g);
|
||||
l.down_w = bw(nm.f("v.blk.%d.fc2.weight", li), nm.ckpt(e, tw, li, "mlp.fc2.weight"), { width, ff }, g);
|
||||
l.down_b = bw(nm.f("v.blk.%d.fc2.bias", li), nm.ckpt(e, tw, li, "mlp.fc2.bias"), { width }, g);
|
||||
if (!l.n1w || !l.n1b || !l.n2w || !l.n2b || !l.qkv_w || !l.qkv_b || !l.out_w ||
|
||||
!l.out_b || !l.up_w || !l.up_b || !l.down_w || !l.down_b)
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
pn_w = bw(nm.f("v.post_norm.weight"), nm.ckpt("%spost_layernorm.weight", tw), { width }, grp_model());
|
||||
pn_b = bw(nm.f("v.post_norm.bias"), nm.ckpt("%spost_layernorm.bias", tw), { width }, grp_model());
|
||||
const char* pj = "model.multi_modal_projector.";
|
||||
if (proj_norm) {
|
||||
mn_w = bw(nm.f("v.proj.norm.weight"), nm.ckpt("%slayer_norm.weight", pj), { mw }, grp_model());
|
||||
mn_b = bw(nm.f("v.proj.norm.bias"), nm.ckpt("%slayer_norm.bias", pj), { mw }, grp_model());
|
||||
if (!mn_w || !mn_b) return RAD_E_INVAL;
|
||||
}
|
||||
m1_w = bw(nm.f("v.proj.fc1.weight"), nm.ckpt("%slinear_1.weight", pj), { proj_hidden, mw }, grp_model());
|
||||
m1_b = bw(nm.f("v.proj.fc1.bias"), nm.ckpt("%slinear_1.bias", pj), { proj_hidden }, grp_model());
|
||||
m2_w = bw(nm.f("v.proj.fc2.weight"), nm.ckpt("%slinear_2.weight", pj), { n_embd, proj_hidden }, grp_model());
|
||||
m2_b = bw(nm.f("v.proj.fc2.bias"), nm.ckpt("%slinear_2.bias", pj), { n_embd }, grp_model());
|
||||
if (!w_patch || !b_patch || !w_pos || !pn_w || !pn_b || !m1_w || !m1_b || !m2_w || !m2_b)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
/* ---- activations. `mh` is the post-norm's output declared at the merged width: the norm
|
||||
* writes P rows of `width` and the projector reads the same bytes as P/mm rows of
|
||||
* mm * width. */
|
||||
b_x = decl_b(b, nm.f("v.x"), RAD_BF16, { P, width });
|
||||
b_h = decl_b(b, nm.f("v.h"), RAD_BF16, { P, width });
|
||||
b_qkv = decl_b(b, nm.f("v.qkv"), RAD_BF16, { P, 3 * width });
|
||||
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, mw });
|
||||
if (proj_norm) b_mn = decl_b(b, nm.f("v.mn"), RAD_BF16, { R, mw });
|
||||
b_mf = decl_b(b, nm.f("v.mf"), RAD_BF16, { R, proj_hidden });
|
||||
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 || (proj_norm && !b_mn) || !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, int64_t n, rad_weight w, rad_weight bias) -> rad_op {
|
||||
return RAD_OP(b, "layernorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
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_aa",
|
||||
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, width, 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.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, width, l.n2w, l.n2b), { b_x }, { b_h });
|
||||
l.up = rw(b, gemm(P, ff, width, "gelu_tanh", 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_post = rw(b, lnorm(P, width, pn_w, pn_b), { b_x }, { b_mh });
|
||||
if (proj_norm) op_mln = rw(b, lnorm(R, mw, mn_w, mn_b), { b_mh }, { b_mn });
|
||||
op_m1 = rw(b, gemm(R, proj_hidden, mw, "gelu", m1_w, m1_b), { proj_norm ? b_mn : b_mh }, { b_mf });
|
||||
op_m2 = rw(b, gemm(R, n_embd, proj_hidden, "none", m2_w, m2_b), { b_mf }, { b_out });
|
||||
|
||||
if (!ctx->shape_probe) {
|
||||
RadEncoderDecl e{};
|
||||
e.name = "vision";
|
||||
e.modalities = RAD_MM_IMAGE;
|
||||
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, "SigLIP2 tower: %lld layers of %lld (%lld heads x %lld), ff %lld, patch %lld, "
|
||||
"%lld x %lld position table; projector %lld -> %lld -> %lld%s; %lld patches a "
|
||||
"pass -> %lld rows",
|
||||
(long long)depth, (long long)width, (long long)heads, (long long)head_dim,
|
||||
(long long)ff, (long long)patch, (long long)side, (long long)side,
|
||||
(long long)mw, (long long)proj_hidden, (long long)n_embd,
|
||||
proj_norm ? " behind a layer norm" : "", (long long)P, (long long)R);
|
||||
}
|
||||
on = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
inline void Siglip2::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 || batch->enc != RAD_MM_IMAGE || Pn <= 0 || Pn > P || Pn % mm || S <= 0) {
|
||||
rad_step_fail(c, "lfm2: an encoder pass this program's SigLIP2 tower cannot serve: no "
|
||||
"tower, not images, more patches than it was declared for, or not whole "
|
||||
"merged rows");
|
||||
return;
|
||||
}
|
||||
/* The patches, their coordinates (a dense [4, P] of row, column, segment height and width,
|
||||
* read by the position resample) and the segment boundaries. */
|
||||
const RadOperand pix = praw2(batch->enc_pixels, RAD_BF16, Pn, patch_dim);
|
||||
const RadOperand crd = praw2(batch->enc_coord, RAD_I32, 4, Pn);
|
||||
const RadOperand cu = praw(batch->enc_cu, RAD_I32, S + 1);
|
||||
|
||||
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.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 post-norm writes Pn rows of `width` into the merged-width buffer, which the projector
|
||||
* reads as Pn/mm rows: the pixel unshuffle. */
|
||||
RAD_ISSUE_N(c, op_post, Pn, brows(b_x, Pn), RAD_W(pn_w), RAD_W(pn_b), brows(b_mh, Rn));
|
||||
if (proj_norm)
|
||||
RAD_ISSUE_N(c, op_mln, Rn, brows(b_mh, Rn), RAD_W(mn_w), RAD_W(mn_b), brows(b_mn, Rn));
|
||||
RAD_ISSUE_N(c, op_m1, Rn, brows(proj_norm ? b_mn : 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));
|
||||
}
|
||||
|
||||
} /* namespace lfm2_bf16 */
|
||||
|
||||
#endif /* LFM2_SIGLIP2_H */
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/llama_dense_fp8 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see 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)
|
||||
@@ -0,0 +1,16 @@
|
||||
/* llama_dense_fp8 -- arch/llama_fp8 over a bf16 checkpoint quantised by rad-convert.
|
||||
*
|
||||
* For MiniCPM5-2B, which OpenBMB publishes only in bf16. The recipe
|
||||
* data/recipes/minicpm5-2b-dspark.recipe takes one amax per 128x128 block with scale = amax/448
|
||||
* rounded to bf16, so the container matches what a checkpoint shipped in fp8 would hold and every
|
||||
* kernel, layout and placement decision downstream is the same.
|
||||
*
|
||||
* A separate .so because the selection key is the (architecture, quantisation) pair (spec §2.4),
|
||||
* and a dense checkpoint's descriptor is empty. Everything else is arch/llama_fp8/llama_fp8.cpp;
|
||||
* `#if LLAMA_DENSE_SRC` there changes only the descriptor check and the graph dump text.
|
||||
*/
|
||||
#define LLAMA_DENSE_SRC 1
|
||||
#define LLAMA_NS llama_dense_fp8
|
||||
#define LLAMA_QUANT ""
|
||||
|
||||
#include "../llama_fp8/llama_fp8.cpp"
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/llama_fp8 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see 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)
|
||||
@@ -0,0 +1,610 @@
|
||||
/* llama_fp8 -- the plain LLaMA graph with block-scaled FP8 weights and FP8 activations.
|
||||
*
|
||||
* ============================== WHAT IT SERVES ==============================
|
||||
*
|
||||
* `model_type: llama` with `LlamaForCausalLM`, as MiniCPM5-2B reports: 42 layers, hidden 2048, 16
|
||||
* query heads over 2 KV heads at head_dim 128, SwiGLU at 6144, RMS norms, full rotary at theta
|
||||
* 5e6, an untied 130560-row head, and no biases. Every layer is full attention; unlike
|
||||
* arch/qwen35_fp8 there is no gated delta net, layer schedule, output gate or per-head q/k norm.
|
||||
*
|
||||
* ============================== TWO CHECKPOINT FORMATS, ONE GRAPH ==============================
|
||||
*
|
||||
* The selection key is the (architecture, quantisation) pair (spec §2.4) and one .so claims one
|
||||
* pair, so this source builds twice:
|
||||
*
|
||||
* llama_fp8 quant "fp8_e4m3" the checkpoint holds E4M3 codes and a `weight_scale_inv`
|
||||
* plane per linear, as the engine reads them.
|
||||
* llama_dense_fp8 quant "" the checkpoint is dense bf16, and a recipe quantises each
|
||||
* linear to those two planes at convert time
|
||||
* (data/recipes/minicpm5-2b-dspark.recipe: amax per 128x128
|
||||
* block, scale = amax/448 rounded to bf16).
|
||||
*
|
||||
* MiniCPM5-2B needs the second, since it is published only in bf16. Both builds declare the same
|
||||
* weights and ops, so nothing downstream can tell which one ran.
|
||||
*
|
||||
* ============================== WHAT IS AND IS NOT FP8 ==============================
|
||||
*
|
||||
* E4M3 + a bf16 [N/128][K/128] plane self_attn.{q,k,v,o}_proj, mlp.{gate,up,down}_proj
|
||||
* BF16, no plane every norm and the embedding
|
||||
*
|
||||
* The lm_head is declared at whatever the model holds: bf16 as llama checkpoints ship it, or block
|
||||
* fp8 where a recipe quantised it (the widest GEMM at half the bytes), and the logits kernel for
|
||||
* that encoding is selected. Both vocabulary edges are row-sharded with the vocabulary.
|
||||
*/
|
||||
#ifndef LLAMA_DENSE_SRC
|
||||
#define LLAMA_DENSE_SRC 0
|
||||
#endif
|
||||
#ifndef LLAMA_NS
|
||||
#define LLAMA_NS llama_fp8
|
||||
#endif
|
||||
#ifndef LLAMA_QUANT
|
||||
#define LLAMA_QUANT "fp8_e4m3"
|
||||
#endif
|
||||
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
#include <arch/rad_arch.h>
|
||||
#include <arch/rad_block_attn_fp8.h>
|
||||
#include <arch/rad_block_dspark.h>
|
||||
#include <arch/rad_block_mlp_fp8.h>
|
||||
|
||||
namespace LLAMA_NS {
|
||||
|
||||
using namespace rad::arch;
|
||||
|
||||
struct Layer {
|
||||
AttnFP8 attn;
|
||||
MlpFP8 mlp;
|
||||
};
|
||||
|
||||
struct Model {
|
||||
Names nm{""};
|
||||
Geom g{};
|
||||
int64_t n_rot = 0;
|
||||
int64_t n_main = 0;
|
||||
|
||||
rad_kvgroup kv_full = 0;
|
||||
|
||||
rad_buf b_x = 0, b_hout = 0, b_logits = 0;
|
||||
ActFP8 a_h{};
|
||||
rad_buf b_qkv = 0;
|
||||
rad_buf b_q = 0;
|
||||
ActFP8 a_attn{};
|
||||
rad_buf b_gate_up = 0;
|
||||
ActFP8 a_ffn{};
|
||||
|
||||
/* Auxiliary hidden-state taps, declared only when the container carries a drafter that wants
|
||||
* them. A DSpark or DFlash drafter reads the residual stream at several intermediate layers
|
||||
* and projects the concatenation down (`fc` is [n_embd, n_taps * n_embd]), so the input must
|
||||
* be one contiguous row. The trunk's one residual buffer is overwritten by every layer, so
|
||||
* each tap's rows are copied into its column slice as they pass. Same mechanism as
|
||||
* arch/qwen35_fp8. */
|
||||
enum { MAX_TAPS = 8 };
|
||||
int n_taps = 0;
|
||||
int tap_layer[MAX_TAPS] = {};
|
||||
rad_buf b_dfsrc = 0; /* [max_tok, n_taps * n_embd] */
|
||||
rad_op op_tap = 0;
|
||||
|
||||
/* The drafter, declared only when the container carries one and this serve speculates. Its
|
||||
* layers get absolute indices after the trunk's, so the KV group's layer_slot lookup finds
|
||||
* them and its weights land in layer groups of their own. */
|
||||
Dspark ds{};
|
||||
Dspark::Wire dsw{};
|
||||
rad_kvgroup kv_draft = 0;
|
||||
bool have_ds = false;
|
||||
|
||||
rad_weight w_tok = 0, w_out_norm = 0, w_lm_head = 0;
|
||||
rad_op op_embed = 0, op_embed_ar = 0, op_final_norm = 0, op_gather = 0, op_logits = 0;
|
||||
|
||||
std::vector<Layer> layers;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
|
||||
/* The quantisation descriptor is the selection key but is checked anyway: `--arch` can override
|
||||
* the architecture id at convert time, and a plugin handed the wrong checkpoint should say which
|
||||
* half disagrees rather than fail at a name map. */
|
||||
static int check_format(const RadModelMeta* meta) {
|
||||
const char* q = meta->quant ? meta->quant : "";
|
||||
#if LLAMA_DENSE_SRC
|
||||
if (*q) {
|
||||
fprintf(stderr, "radiance: llama_dense_fp8 serves an unquantised checkpoint and this one "
|
||||
"declares '%s'; llama_fp8 serves it\n", q);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
#else
|
||||
if (std::strncmp(q, "fp8", 3) != 0) {
|
||||
fprintf(stderr, "radiance: llama_fp8 serves a block-scaled fp8 checkpoint and this one "
|
||||
"declares '%s'; llama_dense_fp8 serves a dense bf16 one\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. Its Geom is the trunk's with the drafter's layer geometry from `draft.*`
|
||||
* substituted; the vocabulary, deployment bounds, rank and wire stay the trunk's.
|
||||
*
|
||||
* Nothing is defaulted quietly: a `draft.` config that does not describe a drafter this file
|
||||
* implements is refused by name, because a silently ignored scale factor or head type would only
|
||||
* lower acceptance (spec §17).
|
||||
*
|
||||
* The confidence head (`AcceptRatePredictor`) is deliberately ignored: it drives adaptive block
|
||||
* length, this engine's depth is fixed at declare, and it changes nothing the drafter proposes
|
||||
* (rad_block_dspark.h). */
|
||||
static int declare_dspark(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx,
|
||||
Model& m, int base_layer) {
|
||||
Names& nm = m.nm;
|
||||
Geom dg{};
|
||||
/* Plain RMS norm: the reference uses Qwen3RMSNorm (`model_type: qwen3`). It matches this
|
||||
* MiniCPM5 target, but it is the drafter's convention, set on the drafter's own Geom. */
|
||||
RAD_ARCH_TRY(drafter_geom(dg, m.g, meta, "DSpark"));
|
||||
|
||||
Dspark::Config dc{};
|
||||
dc.n_taps = m.n_taps;
|
||||
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, the head's only approximation, which
|
||||
* can cost acceptance but not correctness (rad_block_dspark.h). The selector bounds K at 32;
|
||||
* the default 16 is 8 KiB of codebook per position, and a checkpoint may ask for more. */
|
||||
dc.top_k = rad_meta_geti(meta, "draft.markov_top_k", 16);
|
||||
if (dc.top_k < 1 || dc.top_k > 32) {
|
||||
fprintf(stderr, "radiance: draft.markov_top_k is %lld; the Markov walk scores at most 32 "
|
||||
"candidates a position\n", (long long)dc.top_k);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
/* The block is both the number of noise rows and the number of drafts: every row, the anchor
|
||||
* included, predicts the token after it. So the depth is `block_size`, where a DFlash2
|
||||
* container's is `block_size - 1` (see RadDrafterDecl::block). A wrong value runs but accepts
|
||||
* nothing.
|
||||
*
|
||||
* A block-diffusion drafter is trained for one block length and has no partial block, so any
|
||||
* other depth is refused. The probe reports `draft_depth_fixed`, so the engine normally picks
|
||||
* this already. */
|
||||
const long long trained = rad_meta_geti(meta, "draft.block_size", 0);
|
||||
if (trained < 2) {
|
||||
fprintf(stderr, "radiance: this DSpark checkpoint declares no draft.block_size; the "
|
||||
"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 variants this implementation does not apply; each changes the proposals, so neither is
|
||||
* ignored quietly. */
|
||||
const char* mh = rad_meta_gets(meta, "draft.markov_head_type", "vanilla");
|
||||
if (dc.rank <= 0 || !mh || std::strcmp(mh, "vanilla") != 0) {
|
||||
fprintf(stderr, "radiance: this DSpark checkpoint has markov_rank %lld and "
|
||||
"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;
|
||||
}
|
||||
|
||||
/* DSpark's published config sets `sliding_window: null`, so this is normally a full cache. */
|
||||
RAD_ARCH_TRY(drafter_kv_group(b, nm, ctx, dg, dc.window, base_layer, &m.kv_draft));
|
||||
|
||||
/* Activations. The context pass has one row per committed token over a whole prefill chunk;
|
||||
* the query pass one row per draft position, `block` per sequence; the two are sized apart.
|
||||
* All are small: the drafter's cost is its weights. */
|
||||
const int64_t qd = dg.n_head * dg.head_dim;
|
||||
const int64_t kvd = dg.n_head_kv * dg.head_dim;
|
||||
int64_t qr = dg.max_seqs * dc.block;
|
||||
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});
|
||||
/* FP8 copies for the context pass. `srcq` is the largest (20 MiB at a 2048-token chunk, five
|
||||
* taps, hidden 2048) and halves the bytes of the context pass's dominant GEMM. */
|
||||
dw.srcq = decl_b(b, nm.f("ds_srcq"), RAD_F8E4M3, {dg.max_tok, dc.n_taps * dg.n_embd});
|
||||
dw.srcs = decl_b(b, nm.f("ds_srcs"), RAD_F32,
|
||||
{dg.max_tok, fp8_blocks(dc.n_taps * dg.n_embd)});
|
||||
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, 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; asking it keeps the buffer consistent with the op declared over it. */
|
||||
dw.dlog = decl_b(b, nm.f("ds_dlog"), dg.act_dtype, {sr, Dspark::head_rows(dg)});
|
||||
dw.cand = decl_b(b, nm.f("dspark_cand"), RAD_I32, {sr, dc.top_k});
|
||||
dw.unary = decl_b(b, nm.f("ds_unary"), RAD_F32, {sr, dc.top_k});
|
||||
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});
|
||||
}
|
||||
/* The proposal buffer (RadDrafterDecl::proposal): a block pass proposes through the
|
||||
* drafter's own walk, never through the sampler's token buffer. */
|
||||
dw.tokens = decl_b(b, nm.f("dspark_tokens"), RAD_I32, {dg.max_seqs, dc.steps()});
|
||||
|
||||
/* The same lm_head sources as the trunk's head (embedding as the tied alternative), so both
|
||||
* project onto one vocabulary. */
|
||||
RAD_ARCH_TRY(m.ds.declare(b, nm, dg, dc, base_layer, m.kv_draft, m.w_tok, "draft",
|
||||
nm.ckpt("lm_head.weight"), nm.ckpt("model.embed_tokens.weight"),
|
||||
dw));
|
||||
m.have_ds = true;
|
||||
|
||||
/* Block drafter: a context pass mirroring the trunk step, then one pass filling the whole
|
||||
* block. `block` is `depth`, not `depth + 1` (this drafter's training convention). `window`
|
||||
* must be the one this plugin gated its own attention with, since the scheduler stages the
|
||||
* block pass against it. */
|
||||
RadDrafterDecl drf{};
|
||||
drf.name = "dspark";
|
||||
drf.kind = RAD_DRAFT_BLOCK;
|
||||
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, which every "
|
||||
"unfilled block position embeds\n");
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
RAD_ARCH_TRY(rad_declare_drafter(b, &drf));
|
||||
|
||||
rad_note(b, "DSpark drafter: %lld layers at absolute %d..%d, %lld heads / %lld kv x %lld, "
|
||||
"ffn %lld, %s attention with a %lld-token window, %d trunk tap(s); one forward "
|
||||
"over %lld noise row(s), the anchor included, proposes %lld tokens",
|
||||
(long long)dg.n_layer, base_layer, base_layer + (int)dg.n_layer - 1,
|
||||
(long long)dg.n_head, (long long)dg.n_head_kv, (long long)dg.head_dim,
|
||||
(long long)dg.n_ff, dc.causal ? "causal" : "non-causal", (long long)dc.window,
|
||||
m.n_taps, (long long)dc.block, (long long)dc.steps());
|
||||
rad_note(b, "the rank-%lld Markov bigram head walks `unary + <markov_w1[prev], "
|
||||
"markov_w2[cand]>` over the draft head's top %lld, greedily; the confidence head "
|
||||
"(adaptive block length) is not applied",
|
||||
(long long)dc.rank, (long long)dc.top_k);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
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 `partial_rotary_factor` says otherwise (Phi-style
|
||||
* models set it). A config that states nothing means the full head. */
|
||||
{
|
||||
double prf = rad_meta_getf(meta, "partial_rotary_factor", 0.0);
|
||||
if (!(prf > 0.0)) prf = rad_meta_getf(meta, "rope_parameters.partial_rotary_factor", 0.0);
|
||||
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;
|
||||
}
|
||||
RAD_ARCH_TRY(yarn_from(g, meta, "", m.n_rot));
|
||||
|
||||
/* ---- 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, only when the container carries a drafter that reads them and the
|
||||
* deployment speculates: the buffer is one residual stream per tap, 40 MiB at a 2048-token
|
||||
* chunk with five taps and hidden 2048.
|
||||
*
|
||||
* Two key spellings: a SpecForge DFlash config nests the wiring under `dflash_config`, while
|
||||
* the published DSpark configs (openbmb/MiniCPM5-2B-DSpark and siblings) put it at the top
|
||||
* level. The flat key is read first. */
|
||||
if (ctx->max_spec > 0) {
|
||||
const char* da = rad_meta_gets(meta, "draft.architectures", "");
|
||||
if (da && (std::strstr(da, "DSpark") || std::strstr(da, "DFlash"))) {
|
||||
const char* ids = rad_meta_gets(meta, "draft.target_layer_ids", nullptr);
|
||||
if (!ids) ids = rad_meta_gets(meta, "draft.dflash_config.target_layer_ids", nullptr);
|
||||
m.n_taps = parse_layer_ids(ids, m.n_main, m.tap_layer, Model::MAX_TAPS);
|
||||
if (m.n_taps > 0) {
|
||||
m.b_dfsrc = decl_b(b, nm.f("draft_src"), g.act_dtype,
|
||||
{g.max_tok, (int64_t)m.n_taps * g.n_embd});
|
||||
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 the
|
||||
* alternative source: without `lm_head.weight` the embedding table serves as both, as in small
|
||||
* LLaMA derivatives. The head is declared at its codes' dtype (bf16, or E4M3 where a recipe
|
||||
* made it block fp8), queried after its name map entry. */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("model.embed_tokens.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("model.norm.weight")));
|
||||
RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"),
|
||||
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});
|
||||
/* Always exact: each token's embedding comes from one rank and the others contribute zero, so
|
||||
* a lossy wire would only add error. */
|
||||
if (g.world > 1)
|
||||
m.op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
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;
|
||||
|
||||
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];
|
||||
/* Residual fold and collective placement: rad_fp8.h, layer_fold. */
|
||||
const LayerFold f = layer_fold(g, l, m.n_main, m.tap_layer, m.n_taps, m.op_embed_ar != 0);
|
||||
|
||||
const char* pre = "model.layers";
|
||||
AttnFP8::Src as{};
|
||||
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,
|
||||
f.mix_fold, false, f.mix_ar_in, f.mix_ar_out));
|
||||
|
||||
MlpFP8::Src ms{};
|
||||
ms.norm = nm.ckpt("%s.%lld.post_attention_layernorm.weight", pre, (long long)l);
|
||||
ms.gate = nm.ckpt("%s.%lld.mlp.gate_proj.weight", pre, (long long)l);
|
||||
ms.up = nm.ckpt("%s.%lld.mlp.up_proj.weight", pre, (long long)l);
|
||||
ms.down = nm.ckpt("%s.%lld.mlp.down_proj.weight", pre, (long long)l);
|
||||
RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw, ms, true, f.mlp_add,
|
||||
f.mlp_ar_in, f.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", 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`. Do not move it.
|
||||
*
|
||||
* Declaration order is the buffer planner's liveness: a transient lives over [first_def,
|
||||
* last_use] in op indices, and buffers with disjoint ranges may share bytes
|
||||
* (core/build/rad_bufplan.cpp). The drafter's passes run after the whole trunk, so they must
|
||||
* be declared after it; declared earlier, the trunk's tail ops would look live after the
|
||||
* drafter, and trunk and drafter buffers live in one step would share bytes.
|
||||
*
|
||||
* The failure is silent: the trunk output stays correct (row 0 of a verify step is computed
|
||||
* before the clobber) but every draft is rejected. The op oracle cannot see it, since device
|
||||
* and host compute the same wrong answer from a clobbered input. It can also depend on world
|
||||
* size, because sharding changes buffer sizes and so the packer's offsets. */
|
||||
if (m.n_taps > 0)
|
||||
RAD_ARCH_TRY(declare_dspark(b, meta, ctx, m, (int)m.n_main));
|
||||
|
||||
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, "a dense bf16 checkpoint, every linear quantised by the recipe to E4M3 with a "
|
||||
"bf16 [N/%d,K/%d] scale plane (scale = block amax / 448, rounded to bf16)",
|
||||
RAD_FP8_BLOCK, RAD_FP8_BLOCK);
|
||||
#else
|
||||
rad_note(b, "weights are block-scaled fp8: E4M3 [N,K] with a bf16 [N/%d,K/%d] scale plane, "
|
||||
"one stored weight taken by gemm_nt_q as two operands",
|
||||
RAD_FP8_BLOCK, RAD_FP8_BLOCK);
|
||||
#endif
|
||||
rad_note(b, "bf16 in the checkpoint: every norm, the embedding and the lm_head, which is "
|
||||
"declared at what the container holds");
|
||||
if (m.n_taps > 0) {
|
||||
char ids[64] = {};
|
||||
int off = 0;
|
||||
for (int t = 0; t < m.n_taps && off < (int)sizeof(ids) - 8; ++t)
|
||||
off += snprintf(ids + off, sizeof(ids) - (size_t)off, t ? " %d" : "%d",
|
||||
m.tap_layer[t]);
|
||||
rad_note(b, "the drafter reads the residual stream after layer(s) %s into a [%lld, %lld] "
|
||||
"buffer; those layers keep their own residual add",
|
||||
ids, (long long)g.max_tok, (long long)((int64_t)m.n_taps * g.n_embd));
|
||||
}
|
||||
rad_note(b, "q, k and v are one fused [%lld, %lld] projection, rotated in place by `rope` "
|
||||
"(q heads, then k heads); no per-head q/k norm and no output gate",
|
||||
(long long)(q_dim + 2 * kv_dim), (long long)g.n_embd);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = g_model[rad_rank(c)];
|
||||
/* A drafter pass; the sign gives the kind. Positive is the query pass, proposing the whole
|
||||
* block at once; negative is the context pass, turning the tokens the trunk just committed
|
||||
* into the drafter's own K and V. Zero is a trunk step. */
|
||||
if (batch->draft_pass != 0) {
|
||||
if (!m.have_ds) {
|
||||
rad_step_fail(c, "the batch asks for a drafter pass and no drafter is declared: the "
|
||||
"container carries no `draft.` block, or declare ran at max_spec 0");
|
||||
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 its column slice. Runs on prefill and decode alike: the drafter
|
||||
* conditions on every committed token's residual stream. */
|
||||
for (int t = 0; t < m.n_taps; ++t) {
|
||||
if (m.tap_layer[t] != (int)li) continue;
|
||||
RAD_ISSUE(c, m.op_tap, brows(m.b_x, batch->n_tok),
|
||||
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 speculation depth this container supports: zero for a plain llama container (no MTP head
|
||||
* in this family), or the trained block length of a DSpark drafter added with `--draft-model`.
|
||||
*
|
||||
* `draft_depth` is `block_size`, not `block_size - 1` as in arch/qwen35_fp8: DSpark's anchor row
|
||||
* predicts too. `draft_depth_fixed` forbids any other depth, since the drafter was trained for
|
||||
* exactly one block length. */
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
out->draft_depth = 0;
|
||||
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. */
|
||||
#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
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/qwen35_bf16 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see 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)
|
||||
@@ -0,0 +1,478 @@
|
||||
/* qwen35_bf16 -- Qwen3.5 / 3.6 / 3.8 dense, bf16 weights and bf16 activations.
|
||||
*
|
||||
* Qwen3.5, 3.6 and 3.8 dense models report the architecture id `qwen35`; `qwen35moe` is the same
|
||||
* graph with a routed FFN. Dimensions come from metadata, so this file serves every size (0.8B to
|
||||
* 27B). docs/ARCHITECTURES.md has the geometry and its plausible-but-wrong traps.
|
||||
*
|
||||
* One plugin implements one architecture id for one quantisation scheme (spec §2.4); a quantised
|
||||
* variant is a separate plugin composing the same blocks against other ops (e.g.
|
||||
* rmsnorm_had_quant_i8, gemm_nt_q), so declare() below has no branch on quantisation.
|
||||
*
|
||||
* ============================== WHAT IT SERVES ==============================
|
||||
*
|
||||
* The unquantised release (quantisation descriptor ""), every projection a bf16 GEMM. The
|
||||
* block-scaled fp8 release is qwen35_fp8's. The lm_head is declared at whatever the model holds,
|
||||
* so a recipe-made block-fp8 head uses the fp8 logits kernel.
|
||||
*
|
||||
* ============================== THE SHAPE, AT 27B ==============================
|
||||
*
|
||||
* 64 layers, full_attention_interval 4 -> layers 3,7,...,63 are full attention (16 of them),
|
||||
* the other 48 are gated delta net
|
||||
* hidden 5120 ffn 17408 vocab 248320 (lm_head not tied)
|
||||
* 24 heads / 4 kv heads / head_dim 256 -> GQA 6; head_dim is read, not derived
|
||||
* (n_embd / n_head would be 213)
|
||||
* attn_output_gate -> q_proj is [n_embd, 2 * n_head * head_dim], query and gate interleaved
|
||||
* partial_rotary_factor 0.25 -> MROPE over the first 64 of 256 head dims, theta 1e7
|
||||
* linear: 16 key heads / 48 value heads of 128, conv width 4, fp32 recurrent state
|
||||
*
|
||||
* ============================== WHAT THIS PLUGIN DOES NOT DECLARE ==============================
|
||||
*
|
||||
* The MTP / NextN head (one extra decoder block plus fc, enorm, hnorm) is not declared here; it
|
||||
* is not needed for text generation. It sits beside the trunk under its own `mtp.` prefix, so
|
||||
* `nextn_predict_layers` is not subtracted from the layer count (see declare()); running it as a
|
||||
* trunk layer would be a different model.
|
||||
*
|
||||
* The vision tower (27 blocks, hidden 1152, 16 heads of 72, patch 16, out 5120) is declared
|
||||
* through arch/common/rad_block_vit.h, only when the container carries one and the deployment
|
||||
* asked for media.
|
||||
*/
|
||||
#include <arch/rad_arch.h>
|
||||
#include <arch/rad_block_attn_gated.h>
|
||||
#include <arch/rad_block_gdn.h>
|
||||
#include <arch/rad_block_mlp.h>
|
||||
#include <arch/rad_block_vit.h>
|
||||
|
||||
#include <vector>
|
||||
|
||||
namespace qwen35_bf16 {
|
||||
|
||||
using namespace rad::arch;
|
||||
|
||||
/* One trunk layer, of one of two kinds; both small structs are held rather than a union. `full`
|
||||
* is the only branch in step(), and it is fixed per layer by the model. */
|
||||
struct Layer {
|
||||
int full = 0;
|
||||
AttnGatedBF16 attn;
|
||||
GdnBF16 gdn;
|
||||
MlpBF16 mlp;
|
||||
};
|
||||
|
||||
struct Model {
|
||||
Names nm{""};
|
||||
Geom g{};
|
||||
GdnBF16::Config gcfg{};
|
||||
int64_t n_rot = 0;
|
||||
int64_t n_main = 0; /* trunk layers, excluding the MTP block */
|
||||
|
||||
rad_kvgroup kv_full = 0, kv_state = 0, kv_conv = 0;
|
||||
|
||||
/* the residual stream and the two vocabulary edges */
|
||||
rad_buf b_x = 0, b_h = 0, b_hout = 0, b_logits = 0;
|
||||
/* full attention */
|
||||
rad_buf b_qg = 0, b_k = 0, b_v = 0, b_q = 0, b_gate = 0, b_attn = 0;
|
||||
/* gated delta net */
|
||||
rad_buf b_in = 0, b_z = 0, b_gq = 0, b_gk = 0, b_gv = 0;
|
||||
rad_buf b_gdec = 0, b_beta = 0, b_kkt = 0, b_go = 0;
|
||||
/* feed-forward */
|
||||
rad_buf b_gate_up = 0, b_ffn = 0;
|
||||
|
||||
rad_weight w_tok = 0, w_out_norm = 0, w_lm_head = 0;
|
||||
rad_op op_embed = 0, op_embed_ar = 0, op_final_norm = 0, op_gather = 0, op_logits = 0;
|
||||
|
||||
/* ---- media (arch/common/rad_block_vit.h): the vision tower and the scatter of its rows,
|
||||
* declared only when the container carries a tower and the deployment asked for media. */
|
||||
bool media = false;
|
||||
VisionTower vit{};
|
||||
MediaRows mrows{};
|
||||
|
||||
std::vector<Layer> layers;
|
||||
};
|
||||
|
||||
/* Declare runs once per rank, in one process, on the rank's own thread (spec §1, §9), so the
|
||||
* model state is indexed by rank and read back in step() with rad_rank(). */
|
||||
static Model g_model[MAX_RANKS];
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
|
||||
Model& m = g_model[ctx->rank];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
|
||||
|
||||
/* A routed model is a different graph, served by the qwen35moe plugin. */
|
||||
if (meta->n_expert > 0) {
|
||||
fprintf(stderr, "radiance: qwen35_bf16 refuses a checkpoint with %lld experts; that is "
|
||||
"qwen35moe\n", (long long)meta->n_expert);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
Geom& g = m.g;
|
||||
Names& nm = m.nm;
|
||||
|
||||
/* ---- geometry RadModelMeta does not name, from the container's free-form header. Both
|
||||
* spellings are accepted: HuggingFace keys (from safetensors) and llama.cpp's (from GGUF). */
|
||||
bool have_interval = false;
|
||||
const int64_t interval = meta_int2(meta, "qwen35.full_attention_interval",
|
||||
"full_attention_interval", 4, &have_interval);
|
||||
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("qwen35", meta_text_gets(meta, "layer_types", nullptr),
|
||||
g.n_layer, interval, {"full_attention"}));
|
||||
/* Every declared layer is a trunk layer: `mtp_num_hidden_layers` is not part of
|
||||
* `num_hidden_layers` in this family (the MTP block ships separately under `mtp.`).
|
||||
* Subtracting it would drop full-attention layer 63 and silently run a trunk one layer short.
|
||||
* `nextn` is used only for the note below. */
|
||||
m.n_main = g.n_layer;
|
||||
|
||||
/* Qwen3.5's norms are GemmaRMSNorm, `x_hat * (1 + w)` (vLLM imports GemmaRMSNorm as
|
||||
* Qwen3_5RMSNorm). This covers input_layernorm, post_attention_layernorm, the final norm and
|
||||
* the q/k head norms, but not the delta net's ssm_norm, a plain RMSNormGated (gains ~0.88).
|
||||
* The checkpoint confirms it: layer norm weights of 0.07..0.29 and partly negative q/k norm
|
||||
* weights only make sense as `1 + w`. The final norm (0.68..0.96) is ambiguous and follows the
|
||||
* reference implementation. */
|
||||
g.wadd = 1.0f;
|
||||
g.wadd_qk = 1.0f;
|
||||
const float final_wadd = 1.0f;
|
||||
|
||||
/* The rotary width: partial_rotary_factor 0.25 over head_dim 256 is 64. A container that
|
||||
* omits it is refused rather than defaulted to a full rotation, which would give fluent wrong
|
||||
* text (spec §17). */
|
||||
m.n_rot = meta_int2(meta, "qwen35.rope.dimension_count", "rope_dimension_count", 0);
|
||||
if (m.n_rot <= 0) {
|
||||
/* Both spellings occur in this family: Qwen3.8-27B-FP8 states `partial_rotary_factor`
|
||||
* at the top level and inside `rope_parameters`, Qwen3.5-0.8B only inside
|
||||
* `rope_parameters` (rad-convert flattens nested config with a dot). */
|
||||
double prf = rad_meta_getf(meta, "partial_rotary_factor", 0.0);
|
||||
if (!(prf > 0.0)) prf = rad_meta_getf(meta, "rope_parameters.partial_rotary_factor", 0.0);
|
||||
if (prf > 0.0) m.n_rot = (int64_t)(g.head_dim * prf);
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
RAD_ARCH_TRY(yarn_from(g, meta, "", m.n_rot));
|
||||
|
||||
/* 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: libr4d's
|
||||
* gdn_chunk_scan_k128_v128_c64_bf16, and also the linear-state checkpoint interval
|
||||
* (spec §7.3). Note: gdn_conv_prep takes it while gdn_chunk_scan derives it from the kernel,
|
||||
* and nothing checks that the two agree. */
|
||||
gc.chunk = 64;
|
||||
|
||||
int s;
|
||||
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 (spec §7.2). Every layer is bound below to the group it owns state
|
||||
* in; a group with no bound layers is a declare error, since the bound layer count is how
|
||||
* many state instances a sequence holds.
|
||||
*
|
||||
* The full-attention group's block size is not declared: it comes from the resolved attention
|
||||
* kernel and is read back with rad_kv_block_size() inside the block. */
|
||||
RadKVGroupDecl fd{};
|
||||
fd.kind = RAD_KV_FULL;
|
||||
fd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16);
|
||||
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, as `mamba_ssm_dtype: float32` asks; an f16 state changes the
|
||||
* generated text (qwen35_fp8.cpp). It costs 48 x 128 x 128 x 4 = 3 MiB per layer, 144 MiB
|
||||
* across the 48 linear layers per sequence, the largest item in the memory plan. */
|
||||
RadKVGroupDecl sd{};
|
||||
sd.kind = RAD_KV_LINEAR;
|
||||
sd.dtype = RAD_F32;
|
||||
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 (the worst step) and shared by every layer of a
|
||||
* kind; liveness analysis over the declared read and write sets fits them in one arena
|
||||
* (spec §3.1). */
|
||||
m.b_x = decl_b(b, nm.f("x"), g.act_dtype, {g.max_tok, g.n_embd});
|
||||
m.b_h = decl_b(b, nm.f("h"), g.act_dtype, {g.max_tok, g.n_embd});
|
||||
|
||||
/* The query-and-gate projection is rank 3, [tokens, heads, 2*head_dim], so the per-head
|
||||
* interleaving is addressable: query and gate are the first and second head_dim columns of the
|
||||
* last dimension, i.e. ordinary column slices. Flattened, no operand could name them. */
|
||||
m.b_qg = decl_b(b, nm.f("attn_qg"), g.act_dtype, {g.max_tok, g.n_head, 2 * g.head_dim});
|
||||
m.b_k = decl_b(b, nm.f("attn_k"), g.act_dtype, {g.max_tok, kv_dim});
|
||||
m.b_v = decl_b(b, nm.f("attn_v"), g.act_dtype, {g.max_tok, kv_dim});
|
||||
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});
|
||||
/* Decay and beta are f32: the decay is a cumulative sum whose intra-chunk span reaches
|
||||
* hundreds of nats on real prefill inputs, and a bf16 running sum would lose the low bits that
|
||||
* every decay factor exponentiates. */
|
||||
m.b_gdec = decl_b(b, nm.f("gdn_g"), RAD_F32, {g.max_tok, gc.n_head_v});
|
||||
m.b_beta = decl_b(b, nm.f("gdn_beta"), RAD_F32, {g.max_tok, gc.n_head_v});
|
||||
/* bf16, not f32: gdn_kkt_solve writes this plane as bf16 and gdn_chunk_scan reads it as
|
||||
* bf16. */
|
||||
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 only: `max_logit_rows` is one row per sequence, or
|
||||
* per verified draft position. At 248320 vocab that is 63 MiB of logits instead of 8 GiB.
|
||||
* gather_rows selects the hidden states into the narrow `b_hout` (n_embd wide) before the
|
||||
* GEMM. */
|
||||
m.b_hout = decl_b(b, nm.f("h_out"), g.act_dtype, {g.max_logit_rows, g.n_embd});
|
||||
m.b_logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab});
|
||||
RAD_ARCH_TRY(rad_declare_logits(b, m.b_logits));
|
||||
|
||||
/* ---- vocabulary edges, both row-sharded. The lm_head is sharded because the sampler runs a
|
||||
* distributed top-k and full logits are never gathered (spec §9, §13); replicating the
|
||||
* embedding would cost 248320 x 5120 bf16 (2.43 GiB) per rank. `embed_lookup` takes a
|
||||
* `vocab_offset`: a rank gathers the ids in its slice and writes zero rows for the rest, and
|
||||
* the all_reduce below sums the ranks into x. */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"),
|
||||
nm.ckpt("model.language_model.embed_tokens.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"),
|
||||
nm.ckpt("model.language_model.norm.weight")));
|
||||
/* The 27B does not tie its lm_head (`tie_word_embeddings: false`); the second source serves
|
||||
* the small family members that do. The first source present wins. */
|
||||
RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"),
|
||||
nm.ckpt("model.language_model.embed_tokens.weight")));
|
||||
|
||||
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 (rad_arch.h). Declared at
|
||||
* its codes' dtype (bf16 as shipped, E4M3 where a recipe made it block fp8), which selects the
|
||||
* logits kernel. */
|
||||
m.w_lm_head = decl_w(b, nm.f("output.weight"),
|
||||
weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16),
|
||||
{g.n_vocab, g.n_embd}, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
|
||||
|
||||
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 overwrite the lookup before its reduction (see MediaRows). */
|
||||
m.media = VisionTower::present(meta) && ctx->max_enc_patches > 0;
|
||||
if (m.media) RAD_ARCH_TRY(m.mrows.declare(b, g.max_tok, g.n_embd, m.b_x));
|
||||
/* Always exact, not g.wire_exact: this sums disjoint rows (each token from one rank, zeros
|
||||
* from the others), so a lossy wire would only add error. */
|
||||
if (g.world > 1)
|
||||
m.op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
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. */
|
||||
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});
|
||||
|
||||
/* ---- notes for --debug-graph. */
|
||||
rad_note(b, "rank %d/%d: %lld trunk layers, %lld full attention + %lld gated delta net, "
|
||||
"n_head=%lld n_head_kv=%lld head_dim=%lld n_ff=%lld vocab=[%lld,%lld)",
|
||||
g.rank, g.world, (long long)m.n_main,
|
||||
(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 holds A_log itself: the kernels form -exp(A_log) * softplus(a + dt), "
|
||||
"so a GGUF's ssm_a = -exp(A_log) must be converted back");
|
||||
rad_note(b, "rope: %s over %lld of %lld head dims%s%s", g.rope_mode, (long long)m.n_rot,
|
||||
(long long)g.head_dim, g.rope_mc ? ", sections " : "", g.rope_sections);
|
||||
if (!have_interval)
|
||||
rad_note(b, "the container did not state full_attention_interval; assuming %lld, which "
|
||||
"makes layers 3,7,... full attention", (long long)interval);
|
||||
rad_note(b, "logits for at most %lld sampled rows a step (of %lld tokens): gather_rows "
|
||||
"selects RadBatch::out_ids before the lm_head", (long long)g.max_logit_rows,
|
||||
(long long)g.max_tok);
|
||||
if (nextn > 0)
|
||||
rad_note(b, "the %lld MTP/NextN layer(s) under `mtp.` are not declared: this plugin "
|
||||
"serves the trunk only", (long long)nextn);
|
||||
|
||||
/* The vision tower, last, so its activations share the arena with every buffer above. */
|
||||
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 only the vision tower (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 only on the rows the sampler asked for; a mid-prompt prefill chunk has
|
||||
* n_out zero and skips it. */
|
||||
if (batch->n_out > 0) {
|
||||
RAD_ISSUE_N(c, m.op_gather, batch->n_out,
|
||||
brows(m.b_h, batch->n_tok),
|
||||
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
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/qwen35_fp8 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(qwen35_fp8 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(qwen35_fp8 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/qwen35_fp8.cpp)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/qwen35moe_fp8 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see 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)
|
||||
@@ -0,0 +1,17 @@
|
||||
/* qwen35moe_fp8 -- Qwen3.5 / 3.6 MoE (35B-A3B), block-scaled FP8 weights and FP8 activations.
|
||||
*
|
||||
* This is arch/qwen35_fp8/qwen35_fp8.cpp with a routed feed-forward: three macros and an include.
|
||||
* Everything above the FFN (gated attention, gated delta net, layer schedule, rope, vocabulary
|
||||
* edges, MTP head) is identical between the dense and MoE configs. The places where a routed
|
||||
* feed-forward differs are behind `#if QWEN35_MOE` in that file.
|
||||
*
|
||||
* A second translation unit rather than a branch on `n_expert`, because the architecture id and
|
||||
* quantisation descriptor are the selection key (spec §2.4): a container converted from
|
||||
* `model_type: qwen3_5_moe` reports `qwen35moe`, the dense one `qwen35`, and one .so cannot claim
|
||||
* both ids.
|
||||
*/
|
||||
#define QWEN35_MOE 1
|
||||
#define QWEN35_NS qwen35moe_fp8
|
||||
#define QWEN35_ARCH_ID "qwen35moe"
|
||||
|
||||
#include "../qwen35_fp8/qwen35_fp8.cpp"
|
||||
@@ -0,0 +1,11 @@
|
||||
# A plugin like any other: built here inside radiance's tree, or on its own against an installed
|
||||
# radiance (`cmake -S arch/qwen3asr_bf16 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`) -- the
|
||||
# same rad_add_plugin either way (cmake/RadAddPlugin.cmake).
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(qwen3asr_bf16 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(qwen3asr_bf16 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/qwen3asr_bf16.cpp)
|
||||
@@ -0,0 +1,623 @@
|
||||
/* qwen3asr_bf16 -- Qwen3-ASR: a Whisper-style audio encoder over a dense Qwen3 decoder, bf16
|
||||
* weights and bf16 activations.
|
||||
*
|
||||
* A speech recogniser served as the generative model it is: the clip goes through the audio
|
||||
* encoder (RadEncoderDecl, RAD_MM_AUDIO), its rows replace the prompt's <|audio_pad|>
|
||||
* placeholders, and the decoder writes the transcript, after "language <Name><asr_text>" when the
|
||||
* request forces a language and after naming it when it does not. POST /v1/audio/transcriptions
|
||||
* builds the prompt from rad_arch_audio_format (below); /v1/chat/completions takes the clip as an
|
||||
* input_audio part. The reference is transformers' modeling_qwen3_asr (5.18) with its
|
||||
* Qwen3ASRFeatureExtractor, which core/mm reproduces (AudioFamily::Qwen3ASR).
|
||||
*
|
||||
* ============================== THE SHAPE, AT 1.7B ==============================
|
||||
*
|
||||
* audio encoder: log-mel [frames, 128], convolved one second (100 frames) at a time: three
|
||||
* Conv2d 3x3 / stride 2 / pad 1 over [mel, time] with 480 channels and exact gelu, 128 mel ->
|
||||
* 16 and 100 frames -> 13 rows; a row's 16 x 480 features through a 7680 -> 1024 linear (no
|
||||
* bias); sinusoidal positions 0..12 added to each second's rows; 24 pre-LayerNorm layers (eps
|
||||
* 1e-5), d_model 1024, 16 heads of 64, biased q/k/v/o and FFN linears, FFN 4096 with exact
|
||||
* gelu, attention bidirectional in blocks of 104 rows (n_window_infer 800 frames = 8 s) from
|
||||
* the clip's start; a final LayerNorm.
|
||||
* projector: 1024 -> 1024, gelu, 1024 -> 2048.
|
||||
* decoder: Qwen3-1.7B: 28 layers, hidden 2048, 16 heads over 8 KV heads of 128 (GQA 2), per-head
|
||||
* q/k RMS norms, NeoX rope over the whole head at theta 1e6, SwiGLU 6144, RMS eps 1e-6,
|
||||
* vocab 151936, the lm_head tied to the embedding.
|
||||
*
|
||||
* ============================== WHAT IS EASY TO GET WRONG ==============================
|
||||
*
|
||||
* Each second is convolved on its own. The core lays a clip out so one convolution over it does
|
||||
* that (core/mm/processor.h, AudioFamily::Qwen3ASR): a whole second is staged as 104 frames whose
|
||||
* last four read as zero (RadBatch::enc_coord plane 1), and the last, shorter second as 8 x the
|
||||
* rows the reference keeps of it. `conv2d`'s `valid` at strides 1, 2 and 4 keeps one second's
|
||||
* convolution out of the next's, and every row the tower writes is a row the reference keeps, so
|
||||
* nothing is compacted.
|
||||
*
|
||||
* The convolutions run over [mel, time], so PyTorch's kernel is [cout, cin, mel, time] with time
|
||||
* last, where `conv2d` convolves (time, width); `t_last` reads the checkpoint as it is. The 7680 ->
|
||||
* 1024 linear takes its input channel-major (c * 16 + f) where the convolution writes
|
||||
* frequency-major (f * 480 + c); as a 1 x 16 convolution over the frequency axis, the checkpoint's
|
||||
* [1024, 7680] is the kernel [1024, 480, 1, 16] in PyTorch's layout, and nothing is permuted.
|
||||
*
|
||||
* The 480-channel convolutions are GEMMs. Two of them and the 7680 -> 1024 linear are 95% of the
|
||||
* tower's arithmetic outside its transformer (68 GMAC for 30 s), and a direct convolution re-reads
|
||||
* the weights for every output. `conv2d_unfold` writes each output position's receptive field as
|
||||
* a row, its columns in the weight's own order, so `gemm_nt_bias` against the checkpoint's kernel
|
||||
* read as [cout, cin * 9] (a reshape, not a relayout) is the convolution, with the bias and the
|
||||
* gelu in its epilogue. The first convolution has one input channel and nine taps, too narrow a K
|
||||
* for a GEMM, so it stays a `conv2d`.
|
||||
*
|
||||
* Positions restart every 13 rows (`seg_sinusoid`, per clip), and attention runs in blocks of 104
|
||||
* rows from the clip's start, the last one short (`attn_dense`'s `block`). A clip is one encoder
|
||||
* segment, so the segment bounds (in frames, read at cu_div 8) are the clip's.
|
||||
*
|
||||
* The decoder's positions are the tokens' indices. The checkpoint's text_config is plain Qwen3
|
||||
* (no mrope_section), and the reference's position ids count the placeholders like text.
|
||||
*/
|
||||
#include <arch/rad_arch.h>
|
||||
#include <arch/rad_block_attn.h>
|
||||
#include <arch/rad_block_mlp.h>
|
||||
#include <arch/rad_block_vit.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
namespace qwen3asr_bf16 {
|
||||
|
||||
using namespace rad::arch;
|
||||
|
||||
/* The longest clip one encoder pass carries, in seconds: the reference extractor's own chunk
|
||||
* length (`chunk_length`), and the clip the transcription route cuts longer audio into. */
|
||||
constexpr int64_t kPassSeconds = 30;
|
||||
|
||||
/* Rows a chunk of `frames` keeps: three convolutions of kernel 3, stride 2, padding 1. */
|
||||
static int64_t post_cnn(int64_t frames) {
|
||||
for (int i = 0; i < 3; ++i) frames = frames > 0 ? (frames - 1) / 2 + 1 : 0;
|
||||
return frames;
|
||||
}
|
||||
|
||||
/* ============================== THE AUDIO ENCODER ============================== */
|
||||
struct AudioTower {
|
||||
struct Layer {
|
||||
rad_weight ln1w = 0, ln1b = 0, qkv_w = 0, qkv_b = 0, o_w = 0, o_b = 0;
|
||||
rad_weight ln2w = 0, ln2b = 0, fc1_w = 0, fc1_b = 0, fc2_w = 0, fc2_b = 0;
|
||||
rad_op op_ln1 = 0, op_qkv = 0, op_attn = 0, op_o = 0, op_ln2 = 0, op_fc1 = 0, op_fc2 = 0;
|
||||
};
|
||||
bool on = false;
|
||||
int64_t P = 0, R = 0, H = 0, heads = 0, hd = 0, ffn = 0, C = 0, nmel = 0, f3 = 0, w3 = 0;
|
||||
int64_t chunk_rows = 0, block = 0, n_embd = 0;
|
||||
static constexpr int64_t kMerge = 8; /* three stride-2 convolutions: 8 frames a row */
|
||||
rad_weight w_c1 = 0, b_c1 = 0, w_c2 = 0, b_c2 = 0, w_c3 = 0, b_c3 = 0, w_co = 0;
|
||||
rad_weight ln_w = 0, ln_b = 0, p1_w = 0, p1_b = 0, p2_w = 0, p2_b = 0;
|
||||
rad_op op_c1 = 0, op_u2 = 0, op_c2 = 0, op_u3 = 0, op_c3 = 0, op_uo = 0, op_co = 0;
|
||||
rad_op op_pos = 0, op_add_pos = 0;
|
||||
rad_op op_ln = 0, op_p1 = 0, op_p2 = 0;
|
||||
rad_buf b_s1 = 0, b_u = 0, b_s2 = 0, b_s3 = 0, b_uo = 0, b_x = 0, b_h = 0, b_pos = 0;
|
||||
rad_buf b_qkv = 0, b_att = 0;
|
||||
rad_buf b_f = 0, b_p1 = 0, b_out = 0;
|
||||
std::vector<Layer> L;
|
||||
|
||||
static bool present(const RadModelMeta* m) {
|
||||
const char* t = rad_meta_gets(m, "audio_config.model_type", "");
|
||||
return t && !std::strcmp(t, "qwen3_asr_encoder");
|
||||
}
|
||||
/* The frames a pass of kPassSeconds stages: whole seconds of merge x 13 rows each. */
|
||||
static int64_t frames_for(const RadModelMeta* m) {
|
||||
const int64_t nw = rad_meta_geti(m, "audio_config.n_window", 0);
|
||||
if (nw <= 0) return 0;
|
||||
return kPassSeconds * kMerge * post_cnn(2 * nw);
|
||||
}
|
||||
|
||||
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
|
||||
int64_t model_embd, int first_group) {
|
||||
on = false;
|
||||
if (!present(m) || ctx->max_audio_frames <= 0) return RAD_OK;
|
||||
auto gi = [&](const char* k, int64_t d) {
|
||||
char key[96];
|
||||
std::snprintf(key, sizeof key, "audio_config.%s", k);
|
||||
return rad_meta_geti(m, key, d);
|
||||
};
|
||||
H = gi("d_model", 0);
|
||||
heads = gi("encoder_attention_heads", 0);
|
||||
ffn = gi("encoder_ffn_dim", 0);
|
||||
C = gi("downsample_hidden_size", 0);
|
||||
nmel = gi("num_mel_bins", 0);
|
||||
const int64_t depth = gi("encoder_layers", 0);
|
||||
const int64_t nw = gi("n_window", 0);
|
||||
const int64_t nwi = gi("n_window_infer", 0);
|
||||
const int64_t out = gi("output_dim", 0);
|
||||
const int64_t kvh = gi("num_key_value_heads", heads);
|
||||
const char* act = rad_meta_gets(m, "audio_config.activation_function", "");
|
||||
hd = heads > 0 ? H / heads : 0;
|
||||
f3 = ((((nmel + 1) / 2) + 1) / 2 + 1) / 2;
|
||||
chunk_rows = post_cnn(2 * nw);
|
||||
block = nw > 0 && nwi % (2 * nw) == 0 ? chunk_rows * (nwi / (2 * nw)) : 0;
|
||||
/* What this tower does not carry is refused by name: a scaled embedding, grouped heads,
|
||||
* an activation other than exact gelu, a projector into some other width. */
|
||||
if (H <= 0 || heads <= 0 || hd * heads != H || ffn <= 0 || C <= 0 || nmel <= 0 ||
|
||||
depth <= 0 || nw <= 0 || block <= 0 || kvh != heads || out != model_embd ||
|
||||
std::strcmp(act ? act : "", "gelu") ||
|
||||
rad_meta_geti(m, "audio_config.scale_embedding", 0)) {
|
||||
fprintf(stderr, "radiance: qwen3asr: the container's audio_config is not the encoder "
|
||||
"this plugin serves (d_model %lld, heads %lld, ffn %lld, channels %lld, "
|
||||
"mel %lld, layers %lld, n_window %lld/%lld, output %lld for a %lld-wide "
|
||||
"decoder, act %s)\n", (long long)H, (long long)heads, (long long)ffn,
|
||||
(long long)C, (long long)nmel, (long long)depth, (long long)nw,
|
||||
(long long)nwi, (long long)out, (long long)model_embd, act ? act : "");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
n_embd = model_embd;
|
||||
P = ctx->max_audio_frames;
|
||||
if (P % kMerge) return RAD_E_SHAPE;
|
||||
R = P / kMerge;
|
||||
const int AC = RAD_ACCESS_PER_REQUEST, N = RAD_SHARD_NONE;
|
||||
const char* T = "model.audio_tower";
|
||||
|
||||
auto w = [&](const char* dn, const char* src, std::initializer_list<int64_t> shp,
|
||||
RadWeightGroup g) -> rad_weight {
|
||||
if (map_copy(b, dn, src) < 0) return 0;
|
||||
return decl_w(b, dn, RAD_BF16, shp, AC, N, g);
|
||||
};
|
||||
/* q, k and v into one projection, weights and biases alike: one GEMM a layer, and the
|
||||
* attention reads three column slices of its row. */
|
||||
auto wcat = [&](const char* dn, std::initializer_list<const char*> src,
|
||||
std::initializer_list<int64_t> shp, RadWeightGroup g) -> rad_weight {
|
||||
if (map_concat(b, dn, src, 0) < 0) return 0;
|
||||
return decl_w(b, dn, RAD_BF16, shp, AC, N, g);
|
||||
};
|
||||
w_c1 = w(nm.f("a.conv1.w"), nm.ckpt("%s.conv2d1.weight", T), {C, 1, 3, 3}, grp_model());
|
||||
b_c1 = w(nm.f("a.conv1.b"), nm.ckpt("%s.conv2d1.bias", T), {C}, grp_model());
|
||||
/* The two 480-channel kernels as the [cout, cin * 9] matrices their GEMMs read: the
|
||||
* checkpoint's [C, C, 3, 3], row-major, is that matrix. */
|
||||
w_c2 = w(nm.f("a.conv2.w"), nm.ckpt("%s.conv2d2.weight", T), {C, C * 9}, grp_model());
|
||||
b_c2 = w(nm.f("a.conv2.b"), nm.ckpt("%s.conv2d2.bias", T), {C}, grp_model());
|
||||
w_c3 = w(nm.f("a.conv3.w"), nm.ckpt("%s.conv2d3.weight", T), {C, C * 9}, grp_model());
|
||||
b_c3 = w(nm.f("a.conv3.b"), nm.ckpt("%s.conv2d3.bias", T), {C}, grp_model());
|
||||
w_co = w(nm.f("a.conv_out.w"), nm.ckpt("%s.conv_out.weight", T), {H, C * f3}, grp_model());
|
||||
ln_w = w(nm.f("a.ln_post.w"), nm.ckpt("%s.ln_post.weight", T), {H}, grp_model());
|
||||
ln_b = w(nm.f("a.ln_post.b"), nm.ckpt("%s.ln_post.bias", T), {H}, grp_model());
|
||||
p1_w = w(nm.f("a.proj1.w"), nm.ckpt("model.multi_modal_projector.linear_1.weight"), {H, H}, grp_model());
|
||||
p1_b = w(nm.f("a.proj1.b"), nm.ckpt("model.multi_modal_projector.linear_1.bias"), {H}, grp_model());
|
||||
p2_w = w(nm.f("a.proj2.w"), nm.ckpt("model.multi_modal_projector.linear_2.weight"), {n_embd, H}, grp_model());
|
||||
p2_b = w(nm.f("a.proj2.b"), nm.ckpt("model.multi_modal_projector.linear_2.bias"), {n_embd}, grp_model());
|
||||
if (!w_c1 || !b_c1 || !w_c2 || !b_c2 || !w_c3 || !b_c3 || !w_co || !ln_w || !ln_b ||
|
||||
!p1_w || !p1_b || !p2_w || !p2_b)
|
||||
return RAD_E_INVAL;
|
||||
L.assign((size_t)depth, Layer{});
|
||||
for (int64_t i = 0; i < depth; ++i) {
|
||||
Layer& l = L[(size_t)i];
|
||||
const RadWeightGroup g = grp_layer(first_group + (int)i);
|
||||
const int li = (int)i;
|
||||
const char* S = "model.audio_tower.layers";
|
||||
l.ln1w = w(nm.f("a.blk.%d.ln1.w", li), nm.ckpt("%s.%d.self_attn_layer_norm.weight", S, li), {H}, g);
|
||||
l.ln1b = w(nm.f("a.blk.%d.ln1.b", li), nm.ckpt("%s.%d.self_attn_layer_norm.bias", S, li), {H}, g);
|
||||
l.qkv_w = wcat(nm.f("a.blk.%d.qkv.w", li),
|
||||
{ nm.ckpt("%s.%d.self_attn.q_proj.weight", S, li),
|
||||
nm.ckpt("%s.%d.self_attn.k_proj.weight", S, li),
|
||||
nm.ckpt("%s.%d.self_attn.v_proj.weight", S, li) }, {3 * H, H}, g);
|
||||
l.qkv_b = wcat(nm.f("a.blk.%d.qkv.b", li),
|
||||
{ nm.ckpt("%s.%d.self_attn.q_proj.bias", S, li),
|
||||
nm.ckpt("%s.%d.self_attn.k_proj.bias", S, li),
|
||||
nm.ckpt("%s.%d.self_attn.v_proj.bias", S, li) }, {3 * H}, g);
|
||||
l.o_w = w(nm.f("a.blk.%d.o.w", li), nm.ckpt("%s.%d.self_attn.out_proj.weight", S, li), {H, H}, g);
|
||||
l.o_b = w(nm.f("a.blk.%d.o.b", li), nm.ckpt("%s.%d.self_attn.out_proj.bias", S, li), {H}, g);
|
||||
l.ln2w = w(nm.f("a.blk.%d.ln2.w", li), nm.ckpt("%s.%d.final_layer_norm.weight", S, li), {H}, g);
|
||||
l.ln2b = w(nm.f("a.blk.%d.ln2.b", li), nm.ckpt("%s.%d.final_layer_norm.bias", S, li), {H}, g);
|
||||
l.fc1_w = w(nm.f("a.blk.%d.fc1.w", li), nm.ckpt("%s.%d.fc1.weight", S, li), {ffn, H}, g);
|
||||
l.fc1_b = w(nm.f("a.blk.%d.fc1.b", li), nm.ckpt("%s.%d.fc1.bias", S, li), {ffn}, g);
|
||||
l.fc2_w = w(nm.f("a.blk.%d.fc2.w", li), nm.ckpt("%s.%d.fc2.weight", S, li), {H, ffn}, g);
|
||||
l.fc2_b = w(nm.f("a.blk.%d.fc2.b", li), nm.ckpt("%s.%d.fc2.bias", S, li), {H}, g);
|
||||
if (!l.ln1w || !l.ln1b || !l.qkv_w || !l.qkv_b || !l.o_w || !l.o_b || !l.ln2w ||
|
||||
!l.ln2b || !l.fc1_w || !l.fc1_b || !l.fc2_w || !l.fc2_b)
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* ---- activations: the convolutions' planes at their own widths, (time, mel, channel)
|
||||
* with the channel innermost; the rest at R rows. */
|
||||
/* The second and third convolutions' outputs are their GEMMs' [positions, C], which is the
|
||||
* same bytes as [time rows, width * C]: the next unfold reads them that way. */
|
||||
const int64_t w2 = (nmel + 1) / 2;
|
||||
w3 = (w2 + 1) / 2;
|
||||
b_s1 = decl_b(b, nm.f("a.s1"), RAD_BF16, {P / 2, w2 * C});
|
||||
b_u = decl_b(b, nm.f("a.unfold"), RAD_BF16, {P / 4 * w3, 9 * C});
|
||||
b_s2 = decl_b(b, nm.f("a.s2"), RAD_BF16, {P / 4 * w3, C});
|
||||
b_s3 = decl_b(b, nm.f("a.s3"), RAD_BF16, {R * f3, C});
|
||||
b_uo = decl_b(b, nm.f("a.unfold_out"), RAD_BF16, {R, f3 * C});
|
||||
b_x = decl_b(b, nm.f("a.x"), RAD_BF16, {R, H});
|
||||
b_h = decl_b(b, nm.f("a.h"), RAD_BF16, {R, H});
|
||||
b_pos = decl_b(b, nm.f("a.pos"), RAD_BF16, {R, H});
|
||||
b_qkv = decl_b(b, nm.f("a.qkv"), RAD_BF16, {R, 3 * H});
|
||||
b_att = decl_b(b, nm.f("a.att"), RAD_BF16, {R, H});
|
||||
b_f = decl_b(b, nm.f("a.f"), RAD_BF16, {R, ffn});
|
||||
b_p1 = decl_b(b, nm.f("a.p1"), RAD_BF16, {R, H});
|
||||
b_out = decl_b(b, nm.f("a.out"), RAD_BF16, {R, n_embd});
|
||||
|
||||
/* The first convolution has one input channel, so it is direct: nine taps are too narrow
|
||||
* a K for a GEMM. */
|
||||
auto conv1 = [&](rad_weight wt, rad_weight bias) {
|
||||
return RAD_OP(b, "conv2d",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("width", nmel),
|
||||
RAD_INT("cin", 1), RAD_INT("cout", C), RAD_INT("kh", 3),
|
||||
RAD_INT("kw", 3), RAD_INT("stride", 2), RAD_INT("pad", 1),
|
||||
RAD_INT("cu_div", 1), RAD_INT("valid_stride", 1),
|
||||
RAD_STR("dtype", "bf16"), RAD_INT("t_last", 1),
|
||||
RAD_STR("act", "gelu")),
|
||||
RAD_WEIGHTS(wt, bias));
|
||||
};
|
||||
auto gemm_m = [&](int64_t rows, int64_t Nn, int64_t K, const char* act_, rad_weight wt,
|
||||
rad_weight bias) {
|
||||
return RAD_OP(b, "gemm_nt_bias",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", Nn), RAD_INT("K", K),
|
||||
RAD_STR("dtype", "bf16"), RAD_STR("act", act_)),
|
||||
RAD_WEIGHTS(wt, bias));
|
||||
};
|
||||
auto gemm = [&](int64_t Nn, int64_t K, const char* act_, rad_weight wt, rad_weight bias) {
|
||||
return gemm_m(R, Nn, K, act_, wt, bias);
|
||||
};
|
||||
auto unfold = [&](int64_t rows, int64_t width, int64_t kh, int64_t kw, int64_t stride,
|
||||
int64_t pad, int64_t cu_div, int tlast) {
|
||||
return RAD_OP(b, "conv2d_unfold",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("width", width),
|
||||
RAD_INT("cin", C), RAD_INT("kh", kh), RAD_INT("kw", kw),
|
||||
RAD_INT("stride", stride), RAD_INT("pad", pad),
|
||||
RAD_INT("cu_div", cu_div), RAD_INT("valid_stride", cu_div),
|
||||
RAD_INT("t_last", tlast), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
auto lnorm = [&](rad_weight wt, rad_weight bias) {
|
||||
return RAD_OP(b, "layernorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", H), RAD_F64("eps", 1e-5),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(wt, bias));
|
||||
};
|
||||
|
||||
op_c1 = rw(b, conv1(w_c1, b_c1), {}, {b_s1});
|
||||
op_u2 = rw(b, unfold(P / 2, w2, 3, 3, 2, 1, 2, 1), {b_s1}, {b_u});
|
||||
op_c2 = rw(b, gemm_m(P / 4 * w3, C, 9 * C, "gelu", w_c2, b_c2), {b_u}, {b_s2});
|
||||
op_u3 = rw(b, unfold(P / 4, w3, 3, 3, 2, 1, 4, 1), {b_s2}, {b_u});
|
||||
op_c3 = rw(b, gemm_m(R * f3, C, 9 * C, "gelu", w_c3, b_c3), {b_u}, {b_s3});
|
||||
/* The 7680 -> 1024 linear as a 1 x f3 convolution over the frequency axis, unfolded: its
|
||||
* rows are (channel, frequency), the checkpoint's own [H, C * f3] column order. */
|
||||
op_uo = rw(b, unfold(R, f3, 1, f3, 1, 0, kMerge, 0), {b_s3}, {b_uo});
|
||||
op_co = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("N", H),
|
||||
RAD_INT("K", C * f3), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_co)),
|
||||
{b_uo}, {b_x});
|
||||
op_pos = rw(b, RAD_OP(b, "seg_sinusoid",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", H),
|
||||
RAD_INT("period", chunk_rows),
|
||||
RAD_F64("max_timescale", 10000.0),
|
||||
RAD_INT("cu_div", kMerge), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, {b_pos});
|
||||
op_add_pos = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", H),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{b_x, b_pos}, {b_x});
|
||||
for (Layer& l : L) {
|
||||
l.op_ln1 = rw(b, lnorm(l.ln1w, l.ln1b), {b_x}, {b_h});
|
||||
l.op_qkv = rw(b, gemm(3 * H, H, "none", l.qkv_w, l.qkv_b), {b_h}, {b_qkv});
|
||||
l.op_attn = rw(b, RAD_OP(b, "attn_dense",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("head_dim", hd),
|
||||
RAD_INT("gqa", 1), RAD_INT("causal", 0),
|
||||
RAD_STR("dtype", "bf16"),
|
||||
RAD_F64("scale", 1.0 / std::sqrt((double)hd)),
|
||||
RAD_INT("max_seqlen", R),
|
||||
RAD_INT("cu_div", kMerge),
|
||||
RAD_INT("block", block)),
|
||||
RAD_NOWEIGHTS),
|
||||
{b_qkv}, {b_att});
|
||||
/* The output projection and the second FFN linear add the residual in their epilogue,
|
||||
* rounded after the biased product as the reference's two tensors are. */
|
||||
l.op_o = rw(b, gemm(H, H, "none", l.o_w, l.o_b), {b_att, b_x}, {b_x});
|
||||
l.op_ln2 = rw(b, lnorm(l.ln2w, l.ln2b), {b_x}, {b_h});
|
||||
l.op_fc1 = rw(b, gemm(ffn, H, "gelu", l.fc1_w, l.fc1_b), {b_h}, {b_f});
|
||||
l.op_fc2 = rw(b, gemm(H, ffn, "none", l.fc2_w, l.fc2_b), {b_f, b_x}, {b_x});
|
||||
}
|
||||
op_ln = rw(b, lnorm(ln_w, ln_b), {b_x}, {b_h});
|
||||
op_p1 = rw(b, gemm(H, H, "gelu", p1_w, p1_b), {b_h}, {b_p1});
|
||||
op_p2 = rw(b, gemm(n_embd, H, "none", p2_w, p2_b), {b_p1}, {b_out});
|
||||
|
||||
if (!ctx->shape_probe) {
|
||||
RadEncoderDecl e{};
|
||||
e.name = "audio";
|
||||
e.modalities = RAD_MM_AUDIO;
|
||||
e.patch_dim = nmel;
|
||||
e.merge = kMerge;
|
||||
e.max_patches = P;
|
||||
e.n_embd = n_embd;
|
||||
e.out = b_out;
|
||||
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
|
||||
rad_note(b, "audio encoder: 3 convolutions of %lld channels over %lld mel bins, %lld "
|
||||
"layers of %lld (%lld heads x %lld), ffn %lld, attention in blocks of %lld "
|
||||
"rows; %lld frames a pass (%lld s) -> %lld rows of %lld",
|
||||
(long long)C, (long long)nmel, (long long)depth, (long long)H,
|
||||
(long long)heads, (long long)hd, (long long)ffn, (long long)block,
|
||||
(long long)P, (long long)kPassSeconds, (long long)R, (long long)n_embd);
|
||||
}
|
||||
on = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t Pn = batch->enc_n_patch, S = batch->enc_n_seg;
|
||||
if (!on || Pn <= 0 || Pn > P || Pn % kMerge || S <= 0) {
|
||||
rad_step_fail(c, "an audio pass this program's audio encoder cannot serve: none "
|
||||
"declared, more frames than it was declared for, or not whole rows");
|
||||
return;
|
||||
}
|
||||
const int64_t Rn = Pn / kMerge;
|
||||
const RadOperand frames = praw2(batch->enc_pixels, RAD_BF16, Pn, nmel);
|
||||
/* Plane 1: whether a frame takes part in the convolution (item.cpp). */
|
||||
const RadOperand valid = praw(batch->enc_coord + Pn, RAD_I32, Pn);
|
||||
const RadOperand cu = praw(batch->enc_cu, RAD_I32, S + 1);
|
||||
|
||||
RAD_ISSUE_N(c, op_c1, Pn, frames, RAD_W(w_c1), cu, valid, brows(b_s1, Pn / 2),
|
||||
RAD_W(b_c1));
|
||||
const int64_t n2 = Pn / 4 * w3, n3 = Rn * f3;
|
||||
RAD_ISSUE_N(c, op_u2, Pn / 2, brows(b_s1, Pn / 2), cu, valid, brows(b_u, n2));
|
||||
RAD_ISSUE_N(c, op_c2, n2, brows(b_u, n2), RAD_W(w_c2), RAD_W(b_c2), RAD_NONE,
|
||||
brows(b_s2, n2));
|
||||
RAD_ISSUE_N(c, op_u3, Pn / 4, brows(b_s2, n2), cu, valid, brows(b_u, n3));
|
||||
RAD_ISSUE_N(c, op_c3, n3, brows(b_u, n3), RAD_W(w_c3), RAD_W(b_c3), RAD_NONE,
|
||||
brows(b_s3, n3));
|
||||
RAD_ISSUE_N(c, op_uo, Rn, brows(b_s3, n3), cu, RAD_NONE, brows(b_uo, Rn));
|
||||
RAD_ISSUE_N(c, op_co, Rn, brows(b_uo, Rn), RAD_W(w_co), brows(b_x, Rn));
|
||||
RAD_ISSUE_N(c, op_pos, Rn, cu, brows(b_pos, Rn));
|
||||
RAD_ISSUE_N(c, op_add_pos, Rn, brows(b_x, Rn), brows(b_pos, Rn), brows(b_x, Rn));
|
||||
for (const Layer& l : L) {
|
||||
RAD_ISSUE_N(c, l.op_ln1, Rn, brows(b_x, Rn), RAD_W(l.ln1w), RAD_W(l.ln1b),
|
||||
brows(b_h, Rn));
|
||||
RAD_ISSUE_N(c, l.op_qkv, Rn, brows(b_h, Rn), RAD_W(l.qkv_w), RAD_W(l.qkv_b), RAD_NONE,
|
||||
brows(b_qkv, Rn));
|
||||
RAD_ISSUE_N(c, l.op_attn, Rn, bcol(b_qkv, 0, H, Rn), bcol(b_qkv, H, H, Rn),
|
||||
bcol(b_qkv, 2 * H, H, Rn), cu, brows(b_att, Rn));
|
||||
RAD_ISSUE_N(c, l.op_o, Rn, brows(b_att, Rn), RAD_W(l.o_w), RAD_W(l.o_b),
|
||||
brows(b_x, Rn), brows(b_x, Rn));
|
||||
RAD_ISSUE_N(c, l.op_ln2, Rn, brows(b_x, Rn), RAD_W(l.ln2w), RAD_W(l.ln2b),
|
||||
brows(b_h, Rn));
|
||||
RAD_ISSUE_N(c, l.op_fc1, Rn, brows(b_h, Rn), RAD_W(l.fc1_w), RAD_W(l.fc1_b), RAD_NONE,
|
||||
brows(b_f, Rn));
|
||||
RAD_ISSUE_N(c, l.op_fc2, Rn, brows(b_f, Rn), RAD_W(l.fc2_w), RAD_W(l.fc2_b),
|
||||
brows(b_x, Rn), brows(b_x, Rn));
|
||||
}
|
||||
RAD_ISSUE_N(c, op_ln, Rn, brows(b_x, Rn), RAD_W(ln_w), RAD_W(ln_b), brows(b_h, Rn));
|
||||
RAD_ISSUE_N(c, op_p1, Rn, brows(b_h, Rn), RAD_W(p1_w), RAD_W(p1_b), RAD_NONE,
|
||||
brows(b_p1, Rn));
|
||||
RAD_ISSUE_N(c, op_p2, Rn, brows(b_p1, Rn), RAD_W(p2_w), RAD_W(p2_b), RAD_NONE,
|
||||
brows(b_out, Rn));
|
||||
}
|
||||
};
|
||||
|
||||
/* ============================== THE DECODER ============================== */
|
||||
struct Layer {
|
||||
AttnBF16 attn;
|
||||
MlpBF16 mlp;
|
||||
};
|
||||
|
||||
struct Model {
|
||||
Names nm{""};
|
||||
Geom g{};
|
||||
rad_kvgroup kv = 0;
|
||||
rad_buf b_x = 0, b_h = 0, b_q = 0, b_k = 0, b_v = 0, b_attn = 0;
|
||||
rad_buf b_gate_up = 0, b_ffn = 0, b_hout = 0, b_logits = 0;
|
||||
rad_weight w_tok = 0, w_out_norm = 0, w_lm_head = 0;
|
||||
rad_op op_embed = 0, op_embed_ar = 0, op_final_norm = 0, op_gather = 0, op_logits = 0;
|
||||
bool media = false;
|
||||
MediaRows mrows{};
|
||||
AudioTower aud{};
|
||||
std::vector<Layer> layers;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
Model& m = g_model[ctx->rank];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
|
||||
Geom& g = m.g;
|
||||
Names& nm = m.nm;
|
||||
|
||||
/* Plain Qwen3: every layer full attention, no sliding window, plain RMS gains. */
|
||||
if (meta->n_expert > 0 || rad_meta_geti(meta, "text_config.use_sliding_window", 0)) {
|
||||
fprintf(stderr, "radiance: qwen3asr: the decoder has experts or a sliding window; this "
|
||||
"plugin serves the dense, full-attention Qwen3 decoder\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (!(g.theta > 0.0f)) g.theta = (float)rad_meta_getf(meta, "rope_parameters.rope_theta", 0.0);
|
||||
if (!(g.theta > 0.0f) || g.head_dim <= 0 || g.n_head % g.n_head_kv) {
|
||||
fprintf(stderr, "radiance: qwen3asr: the decoder's geometry is incomplete (theta %g, "
|
||||
"head_dim %lld, heads %lld over %lld)\n", (double)g.theta,
|
||||
(long long)g.head_dim, (long long)g.n_head, (long long)g.n_head_kv);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
g.wadd = 0.0f;
|
||||
g.wadd_qk = 0.0f;
|
||||
|
||||
RadKVGroupDecl fd{};
|
||||
fd.kind = RAD_KV_FULL;
|
||||
fd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16);
|
||||
fd.n_head_kv = g.n_head_kv;
|
||||
fd.head_dim = g.head_dim;
|
||||
m.kv = rad_decl_kv_group(b, nm.f("kv_attn"), &fd);
|
||||
g.kv_dtype = rad_dtype_name(fd.dtype);
|
||||
|
||||
m.b_x = decl_b(b, nm.f("x"), g.act_dtype, {g.max_tok, g.n_embd});
|
||||
m.b_h = decl_b(b, nm.f("h"), g.act_dtype, {g.max_tok, g.n_embd});
|
||||
m.b_q = decl_b(b, nm.f("attn_q"), g.act_dtype, {g.max_tok, g.q_dim()});
|
||||
m.b_k = decl_b(b, nm.f("attn_k"), g.act_dtype, {g.max_tok, g.kv_dim()});
|
||||
m.b_v = decl_b(b, nm.f("attn_v"), g.act_dtype, {g.max_tok, g.kv_dim()});
|
||||
m.b_attn = decl_b(b, nm.f("attn_out"), g.act_dtype, {g.max_tok, g.q_dim()});
|
||||
m.b_gate_up = decl_b(b, nm.f("gate_up"), g.act_dtype, {g.max_tok, 2 * g.n_ff});
|
||||
m.b_ffn = decl_b(b, nm.f("ffn"), g.act_dtype, {g.max_tok, g.n_ff});
|
||||
m.b_hout = decl_b(b, nm.f("h_out"), g.act_dtype, {g.max_logit_rows, g.n_embd});
|
||||
m.b_logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab});
|
||||
RAD_ARCH_TRY(rad_declare_logits(b, m.b_logits));
|
||||
|
||||
/* ---- the vocabulary edges, both row-sharded; the head is tied to the embedding
|
||||
* (tie_word_embeddings, and the checkpoint ships no lm_head.weight). */
|
||||
const char* pre = "model.language_model";
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("%s.embed_tokens.weight", pre)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("%s.norm.weight", pre)));
|
||||
RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"),
|
||||
nm.ckpt("%s.embed_tokens.weight", pre)));
|
||||
m.w_tok = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, {g.n_vocab, g.n_embd},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
|
||||
m.w_out_norm = decl_w(b, nm.f("output_norm.weight"), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
m.w_lm_head = decl_w(b, nm.f("output.weight"),
|
||||
weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16),
|
||||
{g.n_vocab, g.n_embd}, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
|
||||
|
||||
m.op_embed = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", g.n_embd),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype),
|
||||
RAD_INT("vocab_offset", g.vocab_off)),
|
||||
RAD_WEIGHTS(m.w_tok)),
|
||||
{}, {m.b_x});
|
||||
/* The encoder's rows, over the lookup and before its reduction (MediaRows says why). */
|
||||
m.media = AudioTower::present(meta) && ctx->max_audio_frames > 0;
|
||||
if (m.media) RAD_ARCH_TRY(m.mrows.declare(b, g.max_tok, g.n_embd, m.b_x));
|
||||
if (g.world > 1)
|
||||
m.op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_x}, {m.b_x});
|
||||
|
||||
AttnBF16::Wire aw{};
|
||||
aw.x = m.b_x; aw.h = m.b_h; aw.q = m.b_q; aw.k = m.b_k; aw.v = m.b_v; aw.attn = m.b_attn;
|
||||
MlpBF16::Wire mw{};
|
||||
mw.x = m.b_x; mw.h = m.b_h; mw.gate_up = m.b_gate_up; mw.ffn = m.b_ffn;
|
||||
m.layers.resize((size_t)g.n_layer);
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
Layer& lay = m.layers[(size_t)l];
|
||||
const char* lp = "model.language_model.layers";
|
||||
const long long li = (long long)l;
|
||||
AttnBF16::Src as{};
|
||||
as.norm = nm.ckpt("%s.%lld.input_layernorm.weight", lp, li);
|
||||
as.q = nm.ckpt("%s.%lld.self_attn.q_proj.weight", lp, li);
|
||||
as.k = nm.ckpt("%s.%lld.self_attn.k_proj.weight", lp, li);
|
||||
as.v = nm.ckpt("%s.%lld.self_attn.v_proj.weight", lp, li);
|
||||
as.q_norm = nm.ckpt("%s.%lld.self_attn.q_norm.weight", lp, li);
|
||||
as.k_norm = nm.ckpt("%s.%lld.self_attn.k_norm.weight", lp, li);
|
||||
as.o = nm.ckpt("%s.%lld.self_attn.o_proj.weight", lp, li);
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv));
|
||||
RAD_ARCH_TRY(lay.attn.declare(b, nm, g, (int)l, m.kv, aw, as));
|
||||
MlpBF16::Src ms{};
|
||||
ms.norm = nm.ckpt("%s.%lld.post_attention_layernorm.weight", lp, li);
|
||||
ms.gate = nm.ckpt("%s.%lld.mlp.gate_proj.weight", lp, li);
|
||||
ms.up = nm.ckpt("%s.%lld.mlp.up_proj.weight", lp, li);
|
||||
ms.down = nm.ckpt("%s.%lld.mlp.down_proj.weight", lp, li);
|
||||
RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw, ms));
|
||||
}
|
||||
|
||||
m.op_final_norm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(m.w_out_norm)),
|
||||
{m.b_x}, {m.b_h});
|
||||
m.op_gather = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
RAD_INT("n", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_h}, {m.b_hout});
|
||||
m.op_logits = rw(b, RAD_OP(b, "logits_gemm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
RAD_INT("n_vocab", g.n_vocab),
|
||||
RAD_INT("n_embd", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(m.w_lm_head)),
|
||||
{m.b_hout}, {m.b_logits});
|
||||
|
||||
rad_note(b, "rank %d/%d: %lld decoder layers, n_head=%lld n_head_kv=%lld head_dim=%lld "
|
||||
"n_ff=%lld theta=%g vocab=[%lld,%lld), lm_head tied",
|
||||
g.rank, g.world, (long long)g.n_layer, (long long)g.n_head, (long long)g.n_head_kv,
|
||||
(long long)g.head_dim, (long long)g.n_ff, (double)g.theta, (long long)g.vocab_off,
|
||||
(long long)(g.vocab_off + g.n_vocab));
|
||||
|
||||
/* The audio tower last, so its activations share the arena with every buffer above. */
|
||||
if (m.media) RAD_ARCH_TRY(m.aud.declare(b, meta, ctx, nm, g.n_embd, (int)g.n_layer + 64));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = g_model[rad_rank(c)];
|
||||
/* An encoder pass runs the audio tower and nothing else (RadBatch::enc). */
|
||||
if (batch->enc) {
|
||||
m.aud.step(c, batch);
|
||||
return;
|
||||
}
|
||||
const int64_t T = batch->n_tok;
|
||||
RAD_ISSUE(c, m.op_embed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.b_x, T));
|
||||
m.mrows.step(c, batch, m.b_x, T);
|
||||
if (m.op_embed_ar)
|
||||
RAD_ISSUE_N(c, m.op_embed_ar, T * m.g.n_embd, brows(m.b_x, T), RAD_NONE);
|
||||
for (const Layer& l : m.layers) {
|
||||
l.attn.step(c, batch);
|
||||
l.mlp.step(c, batch);
|
||||
}
|
||||
RAD_ISSUE(c, m.op_final_norm, brows(m.b_x, T), RAD_W(m.w_out_norm), brows(m.b_h, T));
|
||||
if (batch->n_out > 0) {
|
||||
RAD_ISSUE_N(c, m.op_gather, batch->n_out, brows(m.b_h, T),
|
||||
praw(batch->out_ids, RAD_I32, batch->n_out), brows(m.b_hout, batch->n_out));
|
||||
RAD_ISSUE_N(c, m.op_logits, batch->n_out, brows(m.b_hout, batch->n_out),
|
||||
RAD_W(m.w_lm_head), brows(m.b_logits, batch->n_out));
|
||||
}
|
||||
}
|
||||
|
||||
/* Before declare: the frames a pass carries, so the core sizes the audio encoder's pass. */
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
if (AudioTower::present(meta)) out->audio_frames = AudioTower::frames_for(meta);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Qwen3-ASR's audio format (RadAudioFormat): its clip markers; its transcription turn, which is
|
||||
* the reference processor's chat template with the request's prompt as the system text and the
|
||||
* clip as the user turn; and the forced-language prefix the model was trained with,
|
||||
* "language <Name><asr_text>". The language names are the reference processor's
|
||||
* LANGUAGE_CODE_TO_NAME. */
|
||||
static const char* const kLanguages[] = {
|
||||
"ar", "Arabic", "yue", "Cantonese", "zh", "Chinese", "cs", "Czech",
|
||||
"da", "Danish", "nl", "Dutch", "en", "English", "fil", "Filipino",
|
||||
"fi", "Finnish", "fr", "French", "de", "German", "el", "Greek",
|
||||
"hi", "Hindi", "hu", "Hungarian", "id", "Indonesian", "it", "Italian",
|
||||
"ja", "Japanese", "ko", "Korean", "mk", "Macedonian", "ms", "Malay",
|
||||
"fa", "Persian", "pl", "Polish", "pt", "Portuguese", "ro", "Romanian",
|
||||
"ru", "Russian", "es", "Spanish", "sv", "Swedish", "th", "Thai",
|
||||
"tr", "Turkish", "vi", "Vietnamese",
|
||||
};
|
||||
|
||||
static const RadAudioFormat* audio_format(const RadModelMeta* meta) {
|
||||
if (!AudioTower::present(meta)) return nullptr;
|
||||
static const RadAudioFormat f = {
|
||||
(uint32_t)sizeof(RadAudioFormat),
|
||||
"<|audio_start|>",
|
||||
"<|audio_end|>",
|
||||
"<|im_start|>system\n{context}<|im_end|>\n<|im_start|>user\n{audio}<|im_end|>\n"
|
||||
"<|im_start|>assistant\n{language}",
|
||||
"language {language}<asr_text>",
|
||||
"<asr_text>",
|
||||
"language ",
|
||||
kLanguages,
|
||||
(uint32_t)(sizeof(kLanguages) / sizeof(kLanguages[0]) / 2),
|
||||
};
|
||||
return &f;
|
||||
}
|
||||
|
||||
} /* namespace qwen3asr_bf16 */
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PLUGIN(qwen3asr_bf16, "qwen3asr", "", "0.1.0",
|
||||
"Qwen3-ASR: a Whisper-style audio encoder over a dense Qwen3 decoder; bf16 weights "
|
||||
"and activations")
|
||||
RAD_ARCH_PROBE(qwen3asr_bf16)
|
||||
RAD_ARCH_AUDIO_FORMAT(qwen3asr_bf16)
|
||||
#endif
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/qwen4exp_fp8 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(qwen4exp_fp8 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(qwen4exp_fp8 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/qwen4exp_fp8.cpp)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/qwenimage21 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(qwenimage21 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(qwenimage21 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/qwenimage21.cpp)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,56 @@
|
||||
#!/bin/sh
|
||||
# build.sh -- configure, build and run the fast tests.
|
||||
#
|
||||
# With no arguments the build configures itself: if hipcc is present and a card can be enumerated,
|
||||
# device kernels are compiled for that card's architecture, and otherwise the host backend is
|
||||
# built. The host backend is a real implementation, not a stub -- everything except device kernels
|
||||
# is exercised through it -- so a machine with no ROCm is a supported development configuration.
|
||||
#
|
||||
# Pass -DRAD_GPU_TARGETS=<arch>[;<arch>...] to cmake to compile for cards this machine does not
|
||||
# have. Which of them actually get kernels is decided by the kernel libraries present; each one
|
||||
# declares the architectures it serves.
|
||||
#
|
||||
# ./build.sh configure + build + the fast tests (ctest -L fast)
|
||||
# ./build.sh -c wipe the build directory first
|
||||
# ./build.sh --no-hip force the host backend even where hipcc exists
|
||||
# ./build.sh --asan AddressSanitizer + UBSan, host backend, in build-asan/
|
||||
# ./build.sh --tsan ThreadSanitizer, host backend, in build-tsan/
|
||||
# ./build.sh --debug CMAKE_BUILD_TYPE=Debug
|
||||
# ./build.sh -b DIR build in DIR instead of build/ (or build-asan/, build-tsan/)
|
||||
#
|
||||
# The other tiers (docs/GUIDE.md §1.3): ctest --test-dir build -LE 'gpu|oot' for everything that
|
||||
# runs without a card, plain ctest --test-dir build for everything.
|
||||
set -e
|
||||
|
||||
BUILD=
|
||||
CLEAN=0
|
||||
SAN=
|
||||
CMAKE_ARGS=""
|
||||
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
-c|--clean) CLEAN=1 ;;
|
||||
--no-hip) CMAKE_ARGS="$CMAKE_ARGS -DRAD_WITH_HIP=OFF" ;;
|
||||
--asan) SAN=asan ;;
|
||||
--tsan) SAN=tsan ;;
|
||||
--debug) CMAKE_ARGS="$CMAKE_ARGS -DCMAKE_BUILD_TYPE=Debug" ;;
|
||||
-b) shift; BUILD="$1" ;;
|
||||
*) echo "build.sh: unknown option $1" >&2; exit 2 ;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
|
||||
# A sanitised build gets a directory of its own, so it never reconfigures the normal tree. Host
|
||||
# code only: device kernels are not sanitised, and a sanitised engine is not one to serve from.
|
||||
case "$SAN" in
|
||||
asan) CMAKE_ARGS="$CMAKE_ARGS -DRAD_ASAN=ON -DRAD_TSAN=OFF -DRAD_WITH_HIP=OFF"
|
||||
BUILD=${BUILD:-build-asan} ;;
|
||||
tsan) CMAKE_ARGS="$CMAKE_ARGS -DRAD_TSAN=ON -DRAD_ASAN=OFF -DRAD_WITH_HIP=OFF"
|
||||
BUILD=${BUILD:-build-tsan} ;;
|
||||
*) BUILD=${BUILD:-build} ;;
|
||||
esac
|
||||
[ "$CLEAN" = 1 ] && rm -rf "$BUILD"
|
||||
|
||||
cmake -S . -B "$BUILD" -G Ninja $CMAKE_ARGS
|
||||
cmake --build "$BUILD" -j"$(nproc)"
|
||||
ctest --test-dir "$BUILD" -L '^fast$' -j8 --no-tests=error --output-on-failure
|
||||
@@ -0,0 +1,208 @@
|
||||
# rad_add_plugin / rad_hipify -- the single definition of how sources become a loadable radiance
|
||||
# plugin, shared by the in-tree and out-of-tree builds.
|
||||
#
|
||||
# The top-level CMakeLists.txt includes it while building the ABI target; the installed
|
||||
# radiance-config.cmake includes it after importing that target from radianceTargets.cmake. Keep
|
||||
# one copy: a drifted duplicate would emit plugins where the loader does not scan, with no build
|
||||
# error.
|
||||
#
|
||||
# What an includer must set first:
|
||||
# radiance::abi the ABI interface target -- an in-tree ALIAS, or the imported target
|
||||
# RAD_PLUGIN_OUT the build-tree $RADIANCE_HOME; a plugin lands in ${RAD_PLUGIN_OUT}/<kind>
|
||||
# RAD_HIP_FOUND whether device sources can be compiled at all
|
||||
# RAD_GPU_TARGETS the offload architectures this build targets. Any gfx name; a library that
|
||||
# serves only some of them narrows the list with rad_plugin_gpu_targets()
|
||||
# RAD_HIP_RUNTIME the amdhip64 library a device plugin links
|
||||
# The top-level file sets all five as it detects them. radiance-config.cmake sets them from what the
|
||||
# install recorded, so an out-of-tree plugin uses the engine's runtime; its GPU targets default to
|
||||
# the engine's and can be overridden with -DRAD_GPU_TARGETS.
|
||||
#
|
||||
# Optional:
|
||||
# RAD_PLUGIN_INSTALL_HOME the $RADIANCE_HOME `cmake --install` puts a plugin under. Unset in
|
||||
# the tree (plugins install beside the engine under the same prefix);
|
||||
# radiance-config.cmake sets it to the found installation's home.
|
||||
# RAD_HIP_VOPD_REPEATABLE ON when the HIP compiler's VOPD pairing is repeatable; unset is OFF,
|
||||
# which turns the pairing off on LLVM 24 (rad_hip_repeatable, below).
|
||||
|
||||
# For CMAKE_INSTALL_DATADIR. Included here because a consumer may not have; without it plugins
|
||||
# would install to <prefix>/radiance/<kind>, where the loader never looks.
|
||||
include(GNUInstallDirs)
|
||||
|
||||
# The tree's defaults for a plugin built standalone: C++20 and an optimised build type when none was
|
||||
# given. Every plugin directory, in tree or not, opens with:
|
||||
#
|
||||
# if(NOT COMMAND rad_add_plugin) # standalone, not inside radiance's tree
|
||||
# cmake_minimum_required(VERSION 3.21)
|
||||
# project(mylib LANGUAGES CXX) # CXX HIP for device code
|
||||
# find_package(radiance REQUIRED)
|
||||
# rad_plugin_defaults()
|
||||
# endif()
|
||||
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()
|
||||
|
||||
# CMake leaves two HIP rule variables empty. Without CMAKE_DEPFILE_FLAGS_HIP, Ninja records no
|
||||
# header as a dependency of a .hip object (`ninja -t deps` shows #deps 0), so editing a header
|
||||
# relinks a plugin around stale objects, which can leave engine and plugin disagreeing on a
|
||||
# signature. Without CMAKE_INCLUDE_SYSTEM_FLAG_HIP, SYSTEM include directories reach .hip sources as
|
||||
# `-I` and their warnings become ours. A macro, so the variables land in the caller's scope; values
|
||||
# already set are kept.
|
||||
macro(rad_hip_rule_fixes)
|
||||
if(NOT CMAKE_DEPFILE_FLAGS_HIP)
|
||||
set(CMAKE_DEPFILE_FLAGS_HIP "-MD -MT <DEP_TARGET> -MF <DEP_FILE>")
|
||||
endif()
|
||||
if(NOT CMAKE_INCLUDE_SYSTEM_FLAG_HIP)
|
||||
set(CMAKE_INCLUDE_SYSTEM_FLAG_HIP "-isystem ")
|
||||
endif()
|
||||
endmacro()
|
||||
|
||||
# Build a kernel, architecture or quantiser plugin. `kind` is the $RADIANCE_HOME directory the engine
|
||||
# scans for it; an installed plugin must use one of the three, or it would never be loaded. Test
|
||||
# plugins (never installed, see RAD_PLUGIN_INSTALL) use their own directories.
|
||||
function(rad_add_plugin name kind)
|
||||
cmake_parse_arguments(P "" "" "SOURCES;HIP_SOURCES;LIBS;INCLUDES;GPU_TARGETS" ${ARGN})
|
||||
if((NOT DEFINED RAD_PLUGIN_INSTALL OR RAD_PLUGIN_INSTALL) AND
|
||||
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)
|
||||
# Warn: a kernel library without its device sources still installs, with rows that have no
|
||||
# kernels behind them.
|
||||
message(WARNING
|
||||
"rad_add_plugin(${name}) was given HIP_SOURCES but this radiance has no device build "
|
||||
"(RAD_HIP_FOUND is OFF), so they are left out. A radiance configured without ROCm, or on a "
|
||||
"machine with no card and no -DRAD_GPU_TARGETS, has none.")
|
||||
endif()
|
||||
if(RAD_HIP_FOUND AND P_HIP_SOURCES)
|
||||
# The owning project must enable HIP itself; enable_language() is project scope and changes the
|
||||
# consumer's compiler set. Without it CMake fails with errors that do not name the cause, so
|
||||
# check here.
|
||||
get_property(_rad_langs GLOBAL PROPERTY ENABLED_LANGUAGES)
|
||||
if(NOT "HIP" IN_LIST _rad_langs)
|
||||
message(FATAL_ERROR
|
||||
"rad_add_plugin(${name}) was given HIP_SOURCES but the HIP language is not enabled in this "
|
||||
"project. Add `enable_language(HIP)` after project(); the project must enable it itself.")
|
||||
endif()
|
||||
set_source_files_properties(${P_HIP_SOURCES} PROPERTIES LANGUAGE HIP)
|
||||
# Each device source gets a compilation unit ID from the plugin name and its relative path.
|
||||
# clang's default hashes absolute paths and the command line, and the resulting
|
||||
# __hip_cuid_<hash> symbol has variable length, which shifts read-only data and every
|
||||
# PC-relative address into it. A location-independent ID keeps code objects identical wherever
|
||||
# the plugin is built, while still unique per source.
|
||||
foreach(src ${P_HIP_SOURCES})
|
||||
get_filename_component(_rad_abs "${src}" ABSOLUTE)
|
||||
file(RELATIVE_PATH _rad_rel "${CMAKE_CURRENT_SOURCE_DIR}" "${_rad_abs}")
|
||||
string(SHA256 _rad_cuid "${name}/${_rad_rel}")
|
||||
string(SUBSTRING "${_rad_cuid}" 0 16 _rad_cuid)
|
||||
set_property(SOURCE "${src}" APPEND PROPERTY COMPILE_OPTIONS "-cuid=${_rad_cuid}")
|
||||
endforeach()
|
||||
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. Create the kind directory at configure time: the
|
||||
# engine scans it at startup, and a missing one fails the scan rather than the lookup.
|
||||
file(MAKE_DIRECTORY ${RAD_PLUGIN_OUT}/${kind})
|
||||
set_target_properties(${name} PROPERTIES
|
||||
PREFIX "" OUTPUT_NAME "${name}"
|
||||
LIBRARY_OUTPUT_DIRECTORY ${RAD_PLUGIN_OUT}/${kind})
|
||||
if(RAD_HIP_FOUND AND P_HIP_SOURCES)
|
||||
rad_hipify(${name} ${P_GPU_TARGETS})
|
||||
endif()
|
||||
|
||||
# The install tree has the same shape, under RAD_DEFAULT_HOME (<prefix>/share/radiance).
|
||||
# RAD_PLUGIN_INSTALL=OFF opts out; its only in-tree user is core/plugin/testplugin (set in
|
||||
# core/CMakeLists.txt), whose plugins must never reach a real installation.
|
||||
if(NOT DEFINED RAD_PLUGIN_INSTALL)
|
||||
set(RAD_PLUGIN_INSTALL ON)
|
||||
endif()
|
||||
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()
|
||||
|
||||
# Repeatable device code on LLVM 24. ROCm 10.1's clang (AMD clang 24) is not deterministic: the
|
||||
# post-RA VOPD pairing pass (GCNVOPDUtils.cpp) caches each load's transitive load dependencies, a
|
||||
# fusion adds edges behind that cache, and which entries are cached follows the iteration order of
|
||||
# a pointer-keyed set. So two compiles can pair differently, giving different .text and speed.
|
||||
# LLVM 22 (ROCm 7.2) has no such cache and is repeatable.
|
||||
#
|
||||
# The docker image patches libLLVM to drop the cache after every fusion
|
||||
# (docker/llvm-vopd-pairing.patch) and sets RAD_HIP_VOPD_REPEATABLE=ON. Any other LLVM 24 gets VOPD
|
||||
# disabled, which costs 1.4 to 3.5% on the fp8 prefill tiles.
|
||||
function(rad_hip_repeatable tgt)
|
||||
if(CMAKE_HIP_COMPILER_ID STREQUAL "Clang" AND CMAKE_HIP_COMPILER_VERSION VERSION_GREATER_EQUAL 24
|
||||
AND NOT RAD_HIP_VOPD_REPEATABLE)
|
||||
target_compile_options(${tgt} PRIVATE $<$<COMPILE_LANGUAGE:HIP>:-mllvm=-amdgpu-enable-vopd=false>)
|
||||
endif()
|
||||
endfunction()
|
||||
|
||||
# Set a target's HIP architectures and device flags. -ffp-contract=off is mandatory for any
|
||||
# quantised cross-rank op: two ranks sum the dequantised products in opposite order, and an FMA on
|
||||
# either side makes them differ by ~1 ULP, breaking the replicated-state invariant.
|
||||
function(rad_hipify tgt)
|
||||
# Extra arguments narrow the architectures for this target; default is RAD_GPU_TARGETS.
|
||||
set(arches "${ARGN}")
|
||||
if(NOT arches)
|
||||
set(arches "${RAD_GPU_TARGETS}")
|
||||
endif()
|
||||
set_target_properties(${tgt} PROPERTIES HIP_ARCHITECTURES "${arches}")
|
||||
target_compile_options(${tgt} PRIVATE $<$<COMPILE_LANGUAGE:HIP>:-ffp-contract=off>)
|
||||
# Device optimisation level, set on the target because CMake's CMAKE_HIP_FLAGS_<CONFIG> is,
|
||||
# depending on version, empty (-O0 with asserts) or host-style '-O2 -g'. These come after the
|
||||
# toolchain flags, so they win. Non-Debug levels end in -g0 because a later -O does not undo -g,
|
||||
# and device debug info slows compiles, inhibits scheduling and changes code objects. NDEBUG is
|
||||
# required: a device assert is a hostcall, and the engine's queues have no hostcall buffer
|
||||
# (docs/PLUGIN.md). RAD_HIP_FLAGS_<CONFIG> overrides, as in the tree.
|
||||
foreach(cfg DEBUG RELEASE RELWITHDEBINFO MINSIZEREL)
|
||||
if(RAD_HIP_FLAGS_${cfg})
|
||||
set(lvl "${RAD_HIP_FLAGS_${cfg}}")
|
||||
elseif(cfg STREQUAL "DEBUG")
|
||||
set(lvl "-O0 -g")
|
||||
elseif(cfg STREQUAL "MINSIZEREL")
|
||||
set(lvl "-Os -DNDEBUG -g0")
|
||||
else()
|
||||
set(lvl "-O3 -DNDEBUG -g0")
|
||||
endif()
|
||||
separate_arguments(lvl)
|
||||
target_compile_options(${tgt} PRIVATE "$<$<AND:$<COMPILE_LANGUAGE:HIP>,$<CONFIG:${cfg}>>:${lvl}>")
|
||||
endforeach()
|
||||
# Uncompressed fat binary: the engine extracts the code object itself (core/device/aql_code.cpp)
|
||||
# and rejects a compressed one at first launch. This overrides any toolchain setting.
|
||||
target_compile_options(${tgt} PRIVATE $<$<COMPILE_LANGUAGE:HIP>:--no-offload-compress>)
|
||||
target_link_options(${tgt} PRIVATE $<$<LINK_LANGUAGE:HIP>:--no-offload-compress>)
|
||||
target_link_libraries(${tgt} PRIVATE ${RAD_HIP_RUNTIME})
|
||||
rad_hip_repeatable(${tgt})
|
||||
endfunction()
|
||||
|
||||
# Narrow RAD_GPU_TARGETS to the architectures one kernel library serves, given as regular
|
||||
# expressions ("^gfx12" for a generation, "^gfx1201$" for a chip). The result may be empty; the
|
||||
# plugin should then skip itself with a message rather than fail the configure.
|
||||
function(rad_plugin_gpu_targets out)
|
||||
set(keep "")
|
||||
foreach(t ${RAD_GPU_TARGETS})
|
||||
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()
|
||||
@@ -0,0 +1,85 @@
|
||||
# radiance-config.cmake -- what `find_package(radiance)` gets.
|
||||
#
|
||||
# Lets a plugin in another repository build against the installed ABI headers and install into
|
||||
# the $RADIANCE_HOME the engine's loader scans.
|
||||
#
|
||||
# What a consumer gets:
|
||||
# radiance::abi the header-only ABI target -- abi/ plus RAD_DEFAULT_HOME,
|
||||
# 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.
|
||||
|
||||
@PACKAGE_INIT@
|
||||
|
||||
# Read from abi/rad_abi.h at radiance's configure time, so the header stays the single source.
|
||||
set(RADIANCE_ABI_VERSION @RAD_ABI_VERSION@)
|
||||
|
||||
set_and_check(RADIANCE_INCLUDE_DIR "@PACKAGE_RAD_INCLUDE_RELDIR@")
|
||||
|
||||
# $RADIANCE_HOME as a CACHE PATH, so a consumer can override it. Relative to PACKAGE_PREFIX_DIR, so
|
||||
# a relocated prefix still resolves.
|
||||
set(RADIANCE_HOME "@PACKAGE_RAD_HOME_RELDIR@" CACHE PATH
|
||||
"\$RADIANCE_HOME of the radiance installation found by find_package(radiance)")
|
||||
set(RADIANCE_KERNELS_DIR "${RADIANCE_HOME}/kernels")
|
||||
set(RADIANCE_ARCHITECTURES_DIR "${RADIANCE_HOME}/architectures")
|
||||
set(RADIANCE_QUANTIZERS_DIR "${RADIANCE_HOME}/quantizers")
|
||||
# Where rad_add_plugin installs: the home of the engine this consumer built against. Override to
|
||||
# install elsewhere.
|
||||
set(RAD_PLUGIN_INSTALL_HOME "${RADIANCE_HOME}" CACHE PATH
|
||||
"the \$RADIANCE_HOME rad_add_plugin installs plugins under")
|
||||
|
||||
# The imported targets, including radiance::abi.
|
||||
include("${CMAKE_CURRENT_LIST_DIR}/radianceTargets.cmake")
|
||||
|
||||
# Device-build facts rad_add_plugin needs, recorded at radiance's configure time under the in-tree
|
||||
# names. The target list is carried over, not re-detected: a plugin built for the wrong gfx target
|
||||
# loads and launches, then computes garbage.
|
||||
set(RAD_HIP_FOUND @RAD_HIP_FOUND@)
|
||||
if(NOT DEFINED RAD_GPU_TARGETS)
|
||||
set(RAD_GPU_TARGETS "@RAD_GPU_TARGETS@")
|
||||
endif()
|
||||
# The HIP runtime and headers as radiance found them, or this machine's copies when the recorded
|
||||
# path does not exist (another machine, or a container with ROCm elsewhere).
|
||||
set(RAD_HIP_RUNTIME "@RAD_HIP_RUNTIME@")
|
||||
if(RAD_HIP_FOUND)
|
||||
if(NOT EXISTS "${RAD_HIP_RUNTIME}")
|
||||
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()
|
||||
endif()
|
||||
|
||||
# The consumer's build-tree $RADIANCE_HOME, so a plugin can be tested with
|
||||
# RADIANCE_HOME=<build dir>/radiance_home before install. A value already set is kept.
|
||||
if(NOT DEFINED RAD_PLUGIN_OUT)
|
||||
set(RAD_PLUGIN_OUT ${CMAKE_BINARY_DIR}/radiance_home)
|
||||
endif()
|
||||
|
||||
include("${CMAKE_CURRENT_LIST_DIR}/RadAddPlugin.cmake")
|
||||
if(RAD_HIP_FOUND)
|
||||
rad_hip_rule_fixes()
|
||||
endif()
|
||||
|
||||
check_required_components(radiance)
|
||||
@@ -0,0 +1,98 @@
|
||||
# One static library. The engine is monolithic on purpose (spec §head): substitution happens at the
|
||||
# plugin boundary, so .so seams inside it buy nothing.
|
||||
#
|
||||
# Sources are globbed per subdirectory with CONFIGURE_DEPENDS. Re-run cmake if a new file does not
|
||||
# appear.
|
||||
set(RAD_CORE_DIRS util device plugin build runtime mem sched place sample text server format mm diag gen)
|
||||
|
||||
set(RAD_CORE_SRC "")
|
||||
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, which belongs to the `radiance` executable. Every architecture plugin
|
||||
# host links the archive whole (tools/CMakeLists.txt), so a main() inside it would collide with each
|
||||
# tool's own.
|
||||
file(GLOB _top CONFIGURE_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp)
|
||||
list(REMOVE_ITEM _top ${CMAKE_CURRENT_SOURCE_DIR}/main.cpp)
|
||||
list(APPEND RAD_CORE_SRC ${_top})
|
||||
|
||||
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})
|
||||
# Run the ROCm the tree was built against. The HIP driver reports the runtime's directory as an
|
||||
# implicit link directory, so CMake writes no RPATH for it and the loader cache would pick the
|
||||
# system's libamdhip64.so.7. A linker flag instead of CMake's RPATH, because install rewrites the
|
||||
# latter and, next to ROCm 10 clang's entry, leaves an empty element (the current directory).
|
||||
get_filename_component(RAD_HIP_LIBDIR "${RAD_HIP_RUNTIME}" DIRECTORY)
|
||||
target_link_options(rad_core INTERFACE "LINKER:-rpath,${RAD_HIP_LIBDIR}")
|
||||
# AQL backend kernels: the copies and fills behind rad_memcpy_async and rad_memset_async.
|
||||
target_sources(rad_core PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/device/aql_blit.hip)
|
||||
set_source_files_properties(${CMAKE_CURRENT_SOURCE_DIR}/device/aql_blit.hip PROPERTIES LANGUAGE HIP)
|
||||
# Step bookkeeping on the card: acceptance and the next pass's positions (sched/advance.h).
|
||||
target_sources(rad_core PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/sched/advance.hip)
|
||||
set_source_files_properties(${CMAKE_CURRENT_SOURCE_DIR}/sched/advance.hip PROPERTIES LANGUAGE HIP)
|
||||
# Weight-table entries written in stream order, values passed as arguments (runtime/wtab.h).
|
||||
target_sources(rad_core PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/runtime/wtab.hip)
|
||||
set_source_files_properties(${CMAKE_CURRENT_SOURCE_DIR}/runtime/wtab.hip PROPERTIES LANGUAGE HIP)
|
||||
# Next-layer expert prefetch: prediction, plan and table patches (runtime/xprefetch.h).
|
||||
target_sources(rad_core PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/runtime/xprefetch.hip)
|
||||
set_source_files_properties(${CMAKE_CURRENT_SOURCE_DIR}/runtime/xprefetch.hip PROPERTIES LANGUAGE HIP)
|
||||
# Core kernels are built for every AMD GPU family, not only RAD_GPU_TARGETS: every copy and fill
|
||||
# runs them, so without a code object the engine cannot start on a card even when a third-party
|
||||
# kernel plugin supports it. The loader prefers the exact chip when both exist
|
||||
# (core/device/aql_code.cpp).
|
||||
set(RAD_CORE_GPU_TARGETS ${RAD_GPU_TARGETS}
|
||||
gfx9-generic gfx9-4-generic gfx10-1-generic gfx10-3-generic gfx11-generic gfx12-generic)
|
||||
list(REMOVE_DUPLICATES RAD_CORE_GPU_TARGETS)
|
||||
set_target_properties(rad_core PROPERTIES HIP_ARCHITECTURES "${RAD_CORE_GPU_TARGETS}")
|
||||
rad_hip_repeatable(rad_core)
|
||||
# Executables linking the core export the HIP entry points the backend defines, so a dlopen'ed
|
||||
# kernel plugin binds to them instead of real HIP (which does not own the queues). aql.cpp checks
|
||||
# this at startup and refuses to run without it.
|
||||
foreach(sym hipLaunchKernel hipMemcpy2DAsync hipMemcpyAsync hipMemsetAsync hipMemset hipStreamSynchronize
|
||||
hipEventRecord hipStreamWaitEvent hipGetLastError hipPeekAtLastError
|
||||
__hipRegisterFatBinary __hipRegisterFunction __hipUnregisterFatBinary)
|
||||
target_link_options(rad_core INTERFACE "LINKER:--export-dynamic-symbol=${sym}")
|
||||
endforeach()
|
||||
endif()
|
||||
|
||||
# The engine binary. core/main.cpp is owned by the engine component.
|
||||
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/main.cpp)
|
||||
add_executable(radiance main.cpp)
|
||||
target_link_libraries(radiance PRIVATE "$<LINK_LIBRARY:WHOLE_ARCHIVE,rad_core>")
|
||||
# ENABLE_EXPORTS: the architecture plugin binds the declare-phase C ABI back to this binary at
|
||||
# dlopen (tools/CMakeLists.txt).
|
||||
set_target_properties(radiance PROPERTIES
|
||||
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
|
||||
ENABLE_EXPORTS ON)
|
||||
# Installed beside the tools. RUNTIME rather than a bare DESTINATION, so the rule that carries
|
||||
# the executable also carries ENABLE_EXPORTS.
|
||||
install(TARGETS radiance RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
|
||||
endif()
|
||||
|
||||
# The plugin layer's test plugins (.so files, so they need their own CMakeLists).
|
||||
#
|
||||
# RAD_PLUGIN_INSTALL=OFF for this subtree only. rad_add_plugin normally installs what it builds,
|
||||
# but these plugins exist only for tests and must never be selectable from a real prefix.
|
||||
set(RAD_PLUGIN_INSTALL OFF)
|
||||
add_subdirectory(plugin)
|
||||
@@ -0,0 +1,215 @@
|
||||
/* 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, so the hot path never allocates.
|
||||
*
|
||||
* Two deliberate conservatisms (both in the spec): the arena is sized for max_tok, and liveness
|
||||
* covers the declared list, a superset of what any step issues. A plan correct for the worst step
|
||||
* is correct for every step.
|
||||
*
|
||||
* The packer is greedy interval colouring, largest first: each buffer takes the lowest aligned
|
||||
* offset that collides with no placed buffer whose lifetime overlaps. O(n^2) in the buffer count,
|
||||
* microseconds for a few hundred activations, and within a few percent of optimal on real shapes
|
||||
* (the one big activation goes first). Optimal packing is NP-hard and not worth a solver.
|
||||
*/
|
||||
#include "rad_build.h"
|
||||
#include "rad_internal.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <climits>
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* Every buffer starts at a 256-byte boundary: the container's sub-block alignment, and enough for
|
||||
* any RDNA4 vector load (dwordx4 is 16 B). A kernel needing more alignment for its scratch says so
|
||||
* through its scratch hook, which is sized separately. */
|
||||
static constexpr int64_t kBufAlign = (int64_t)RAD_ALIGN_SUB;
|
||||
|
||||
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 that fits `want` without colliding with anything already placed
|
||||
* (off >= 0) that is alive at the same time. */
|
||||
int64_t first_fit(const Item& want, const std::vector<Item>& placed) {
|
||||
std::vector<std::pair<int64_t, int64_t>> occ;
|
||||
occ.reserve(placed.size());
|
||||
for (const Item& p : placed)
|
||||
if (p.off >= 0 && overlaps(p, want)) occ.emplace_back(p.off, p.off + p.bytes);
|
||||
std::sort(occ.begin(), occ.end());
|
||||
|
||||
int64_t off = 0;
|
||||
for (auto& [s, e] : occ) {
|
||||
if (s >= off + want.bytes) break; /* the gap below this block is big enough */
|
||||
off = std::max(off, align_up(e, kBufAlign));
|
||||
}
|
||||
return off;
|
||||
}
|
||||
|
||||
/* Places every item, largest first, ties by lifetime start then index, so the plan is identical
|
||||
* on every rank and every run. Returns the packed extent. */
|
||||
int64_t pack(std::vector<Item>& items) {
|
||||
std::sort(items.begin(), items.end(), [](const Item& a, const Item& b) {
|
||||
if (a.bytes != b.bytes) return a.bytes > b.bytes;
|
||||
if (a.lo != b.lo) return a.lo < b.lo;
|
||||
return a.idx < b.idx;
|
||||
});
|
||||
int64_t end = 0;
|
||||
for (Item& it : items) {
|
||||
it.off = first_fit(it, items);
|
||||
end = std::max(end, it.off + it.bytes);
|
||||
}
|
||||
return end;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
int plan_buffers(Program& p, BufPlanReport* rep) {
|
||||
BufPlanReport r;
|
||||
int status = RAD_OK;
|
||||
|
||||
const int32_t last_op = (int32_t)p.ops.size() - 1;
|
||||
|
||||
std::vector<Item> transient, persist, host;
|
||||
for (size_t i = 1; i < p.buffers.size(); ++i) {
|
||||
BufferInfo& b = p.buffers[i];
|
||||
if (b.bytes <= 0) b.bytes = buffer_bytes(b.decl);
|
||||
if (b.bytes <= 0) {
|
||||
RAD_ERR("buffer plan: '%s' cannot be sized (dtype %u, rank %u)", b.name.c_str(),
|
||||
b.decl.dtype, b.decl.rank);
|
||||
status = RAD_E_INVAL;
|
||||
continue;
|
||||
}
|
||||
|
||||
Item it{ i, align_up(b.bytes, kBufAlign), b.first_def, b.last_use };
|
||||
if (it.lo < 0 || it.hi < it.lo) {
|
||||
/* No declared use: live for the whole program. */
|
||||
it.lo = 0;
|
||||
it.hi = last_op > 0 ? last_op : 0;
|
||||
if (b.decl.kind == RAD_BUF_TRANSIENT) ++r.n_unknown_live;
|
||||
}
|
||||
|
||||
/* Each domain is coloured separately, with offsets relative to its own arena. One shared
|
||||
* offset space would leave both arenas sparse and spend VRAM on host activations.
|
||||
* Program::arena_bytes is the device high-water mark, host_arena_bytes the host one. */
|
||||
if (b.decl.domain == RAD_DOMAIN_HOST) host.push_back(it);
|
||||
else if (b.decl.kind == RAD_BUF_TRANSIENT) transient.push_back(it);
|
||||
else persist.push_back(it);
|
||||
}
|
||||
|
||||
for (const Item& t : transient) r.sum_bytes += t.bytes;
|
||||
|
||||
/* peak_live: what a perfect packer would reach (see BufPlanReport). */
|
||||
for (int32_t t = 0; t <= std::max<int32_t>(last_op, 0); ++t) {
|
||||
int64_t live = 0;
|
||||
for (const Item& it : transient) if (it.lo <= t && t <= it.hi) live += it.bytes;
|
||||
r.peak_live = std::max(r.peak_live, live);
|
||||
}
|
||||
|
||||
/* PERSIST survives across steps and DERIVED is written by the core before any op runs, so
|
||||
* both are live for every op and share with nothing.
|
||||
*
|
||||
* They go at the bottom, transients above. A smaller step packs its transients smaller
|
||||
* (plan_level) and lends the unused top of the arena to the expert slab, so the fixed region
|
||||
* must sit where no level moves it: its contents outlive the step that wrote them. */
|
||||
int64_t off = 0;
|
||||
for (const Item& it : persist) {
|
||||
p.buffers[it.idx].arena_offset = off;
|
||||
off += it.bytes;
|
||||
off = align_up(off, kBufAlign);
|
||||
}
|
||||
const int64_t fixed = align_up(off, kBufAlign);
|
||||
r.persist_bytes = fixed;
|
||||
|
||||
const int64_t tr_end = pack(transient);
|
||||
for (const Item& it : transient) p.buffers[it.idx].arena_offset = fixed + it.off;
|
||||
r.transient_bytes = tr_end;
|
||||
|
||||
p.arena_fixed_bytes = fixed;
|
||||
p.arena_bytes = fixed + tr_end;
|
||||
|
||||
/* The host arena has its own base pointer; these offsets are relative to it. Same packer in
|
||||
* one pass: a host PERSIST is live for the whole program, so it shares with nothing. */
|
||||
const int64_t host_end = pack(host);
|
||||
for (const Item& it : host) p.buffers[it.idx].arena_offset = it.off;
|
||||
r.host_bytes = host_end;
|
||||
p.host_arena_bytes = host_end;
|
||||
|
||||
if (rep) *rep = r;
|
||||
return status;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ a smaller step's plan */
|
||||
|
||||
int plan_level(const Program& full, const Program& probe, int64_t rows, ArenaLevel* out,
|
||||
std::string* why) {
|
||||
auto refuse = [&](const std::string& w) {
|
||||
if (why) *why = w;
|
||||
return RAD_E_STATE;
|
||||
};
|
||||
if (probe.buffers.size() != full.buffers.size())
|
||||
return refuse(fmt("the sizing declare named %zu buffers and the real one %zu",
|
||||
probe.buffers.size() - 1, full.buffers.size() - 1));
|
||||
|
||||
ArenaLevel lv;
|
||||
lv.rows = rows;
|
||||
lv.offset.assign(full.buffers.size(), -1);
|
||||
lv.decl.assign(full.buffers.size(), RadBufDecl{});
|
||||
|
||||
std::vector<Item> transient;
|
||||
for (size_t i = 1; i < full.buffers.size(); ++i) {
|
||||
const BufferInfo& fb = full.buffers[i];
|
||||
const BufferInfo& pb = probe.buffers[i];
|
||||
const RadBufDecl& f = fb.decl;
|
||||
const RadBufDecl& q = pb.decl;
|
||||
if (fb.name != pb.name || f.kind != q.kind || f.domain != q.domain ||
|
||||
f.dtype != q.dtype || f.rank != q.rank)
|
||||
return refuse(fmt("buffer %zu is '%s' in the real declare and '%s' in the sizing one",
|
||||
i, fb.name.c_str(), pb.name.c_str()));
|
||||
/* Only the rows may shrink. Every other extent is a stride some kernel was resolved
|
||||
* against at the real size. */
|
||||
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 an earlier step's data, so it cannot move, and it keeps its full size: one sized
|
||||
* by the step (a per-token plane written outside the op order) is only smaller at a
|
||||
* smaller step, and the real extent covers it. */
|
||||
if (f.kind != RAD_BUF_TRANSIENT || f.domain == RAD_DOMAIN_HOST) {
|
||||
lv.decl[i] = f;
|
||||
lv.offset[i] = fb.arena_offset;
|
||||
continue;
|
||||
}
|
||||
/* The real declare's liveness: the op list is the same 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 = std::max<int32_t>((int32_t)full.ops.size() - 1, 0);
|
||||
}
|
||||
transient.push_back(it);
|
||||
}
|
||||
|
||||
const int64_t tr_end = pack(transient);
|
||||
for (const Item& it : transient) lv.offset[it.idx] = full.arena_fixed_bytes + it.off;
|
||||
lv.end = full.arena_fixed_bytes + tr_end;
|
||||
if (lv.end > full.arena_bytes)
|
||||
return refuse(fmt("packing the smaller buffers took %lld bytes, more than the full plan's "
|
||||
"%lld", (long long)lv.end, (long long)full.arena_bytes));
|
||||
*out = std::move(lv);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,243 @@
|
||||
/* rad_build.h -- the declare phase (spec §3.1): receives everything the architecture plugin will
|
||||
* ever do.
|
||||
*
|
||||
* Declare always completes. A missing kernel does not stop the walk: every op, band and domain
|
||||
* that resolved to nothing is collected with the constraint that refused it and reported at the
|
||||
* end, which shows whether a plugin or a model is missing.
|
||||
*
|
||||
* Nothing is decided twice. After declare the model is static (every op, its kernel, the
|
||||
* weights it touches, the order). The bucket table, weight manifest, buffer plan and KV block
|
||||
* sizes are built once here, so the step path indexes tables.
|
||||
*
|
||||
* The kernel hierarchy, op schemas, constraint matching and bucket boundaries belong to
|
||||
* core/plugin/. The Builder calls Registry::validate and Registry::build_bands rather than
|
||||
* reimplementing them, so selector and builder cannot drift apart.
|
||||
*
|
||||
* Lifetime: every KernelRow, Resolved and RadOpSchema in the Program points into a plugin's static
|
||||
* tables, which the Registry dlclose()s. Neither the Builder nor the Program may outlive the
|
||||
* Registry.
|
||||
*/
|
||||
#pragma once
|
||||
#include "plugin/registry.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <functional>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
/* The plugin's handle. rad_builder.h only forward-declares it; as a base of rad::Builder, the C
|
||||
* shims reach the Builder with a static_cast. */
|
||||
struct RadBuilder { };
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* Process-lifetime storage for declared names. RadNameMap and RadKernelInfo hold raw
|
||||
* `const char*` and the Program outlives the Builder, so the strings are interned: a few thousand,
|
||||
* deduplicated, never freed. Owning them in RadNameMap would be an ABI change. */
|
||||
const char* intern(std::string_view s);
|
||||
|
||||
/* Names for the enums the graph dump prints; `bld_` prefixed to keep them apart from the
|
||||
* planner's tier_name and site_name in rad_core.h. */
|
||||
const char* bld_domain_name(int domain);
|
||||
const char* bld_access_name(int access);
|
||||
const char* bld_buf_kind_name(int kind);
|
||||
const char* bld_kv_kind_name(int kind);
|
||||
|
||||
/* ------------------------------------------------------------------ the buffer plan */
|
||||
/* Packing results for the --debug-graph report. `sum_bytes` (no sharing) and `peak_live` (a
|
||||
* perfect packer) bracket the arena and show what the greedy pass left unused. */
|
||||
struct BufPlanReport {
|
||||
int64_t transient_bytes = 0; /* the packed, shared region */
|
||||
int64_t persist_bytes = 0; /* PERSIST + DERIVED: their own non-overlapping region */
|
||||
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 sound.
|
||||
*
|
||||
* Assigns BufferInfo::arena_offset for every buffer and sets Program::arena_bytes. Returns RAD_OK,
|
||||
* or RAD_E_INVAL if a buffer could not be sized (a plugin-private dtype the core cannot measure). */
|
||||
int plan_buffers(Program& p, BufPlanReport* rep = nullptr);
|
||||
|
||||
/* The arena layout for steps of at most `rows` tokens: the real plan's buffers, the fixed region
|
||||
* unchanged, and the transients repacked, so the arena past `end` is unused by such a step and
|
||||
* can be lent. `offset` and `decl` are indexed by buffer handle. */
|
||||
struct ArenaLevel {
|
||||
int64_t rows = 0;
|
||||
int64_t end = 0;
|
||||
std::vector<int64_t> offset;
|
||||
std::vector<RadBufDecl> decl;
|
||||
};
|
||||
/* Lay out `probe`'s buffers (a sizing declare at `rows`) over `full`'s. Refused, with the reason
|
||||
* in `why`, unless both declares describe the same buffers with only fewer rows; otherwise they
|
||||
* cannot share the real plan's fixed region and kernels. */
|
||||
int plan_level(const Program& full, const Program& probe, int64_t rows, ArenaLevel* out,
|
||||
std::string* why);
|
||||
|
||||
/* Bytes a declared buffer occupies. 0 means the core cannot size it: a plugin-private dtype, legal
|
||||
* for a weight (the kernel's layout hook sizes it) but not for an activation. */
|
||||
int64_t buffer_bytes(const RadBufDecl& d);
|
||||
|
||||
/* ------------------------------------------------------------------ the model behind a declare */
|
||||
/* What the model holds for a logical weight: its encoding and logical extents. rad_weight_encoding
|
||||
* answers with it and every declaration is checked against it (spec §2.4). The engine answers from
|
||||
* the container or checkpoint it loads, rad-convert from its recipe. `prog` is the declare so far,
|
||||
* whose name map is used to search a checkpoint. RAD_OK, or RAD_E_NOTFOUND for a weight the model
|
||||
* does not have. */
|
||||
struct WeightSource {
|
||||
RadEncoding enc{};
|
||||
uint32_t rank = 0;
|
||||
int64_t shape[RAD_MAX_RANK] = {0};
|
||||
};
|
||||
using WeightSourceFn = std::function<int(const std::string& name, const Program& prog,
|
||||
WeightSource* out)>;
|
||||
|
||||
/* ------------------------------------------------------------------ the builder */
|
||||
class Builder : public RadBuilder {
|
||||
public:
|
||||
/* The Registry must outlive the Builder and its Program (see the file header). */
|
||||
Builder(Registry& reg, const RadModelMeta& meta, const RadBuildCtx& ctx);
|
||||
|
||||
/* Where rad_weight_encoding's answers come from. Unset (tests, synthetic tools), every source
|
||||
* is RAD_E_NOTFOUND and a weight is read as plain in its declared dtype. */
|
||||
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 op_declared (const char* op) const;
|
||||
int decl_name_map(const RadNameMap* m);
|
||||
int declare_logits(rad_buf b);
|
||||
int declare_pooled(rad_buf b);
|
||||
int declare_drafter(const RadDrafterDecl* d);
|
||||
int drafter_shared_kv(int pos_offset);
|
||||
int declare_encoder(const RadEncoderDecl* d);
|
||||
int declare_generator(const RadGeneratorDecl* d);
|
||||
void note_v (const char* f, va_list ap);
|
||||
|
||||
/* An op's buffer operands (rad_op_reads/rad_op_writes in rad_builder.h), which give the
|
||||
* buffer planner activation liveness. A transient no op names is live for the whole
|
||||
* program; the --debug-graph buffer report counts those. */
|
||||
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);
|
||||
int weight_shard_span_parts(rad_weight w, const int64_t* lo, const int64_t* hi,
|
||||
const int64_t* total, int n);
|
||||
int kv_group_zero(rad_kvgroup g);
|
||||
|
||||
/* 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 errors here: an
|
||||
* unresolved op returns a null handle and the plugin should offer a fallback (spec §2.3); it
|
||||
* becomes an error only if the run phase issues it. */
|
||||
int finish();
|
||||
|
||||
/* A sizing declare (RadBuildCtx::shape_probe): each op takes the bands `ref` resolved at the
|
||||
* same position, and finish() initialises nothing. The plugin sees the real declare's answers
|
||||
* (which ops resolved, each group's block size), so it declares the same graph and nothing is
|
||||
* selected or set up twice. An op that differs from `ref`'s at that position is an error: a
|
||||
* different graph cannot be laid over the real buffers. */
|
||||
void set_reference(const Program* ref) { ref_ = ref; }
|
||||
|
||||
/* Off: finish() selects every kernel and initialises none, for callers that launch nothing.
|
||||
* rad-convert needs only the kernels' layouts; a kernel's init depends on the running process
|
||||
* (a ring, a peer's buffers), and libavx's n-gram gather refuses a process that cannot create
|
||||
* an io_uring ring, which must not stop a sandboxed conversion. */
|
||||
void set_instances(bool on) { instances_ = on; }
|
||||
|
||||
Program& program() { return prog_; }
|
||||
const Program& program() const { return prog_; }
|
||||
|
||||
/* Structural failures (a bad schema, two ranged parameters, a duplicate name), all of them,
|
||||
* like the miss list. */
|
||||
const std::vector<std::string>& errors() const { return errors_; }
|
||||
int status() const { return status_; }
|
||||
const BufPlanReport& buf_report() const { return bufrep_; }
|
||||
|
||||
private:
|
||||
/* Record a structural error and its class. Returns 0 so a decl_ function can
|
||||
* `return err(...)` and yield a null handle. */
|
||||
uint32_t err(int code, const char* f, ...) __attribute__((format(printf, 3, 4)));
|
||||
std::string scoped(const char* name) const;
|
||||
|
||||
void resolve_bands(OpInfo& oi);
|
||||
void record_tune_request(const Resolved& r);
|
||||
/* init() for every surviving instance, after the whole graph has resolved, so a failing init
|
||||
* cannot abort declare before the miss report is assembled. */
|
||||
void finish_instances();
|
||||
int32_t find_kv_consumer(rad_kvgroup g);
|
||||
void finish_layouts();
|
||||
void finish_kv_groups();
|
||||
void finish_weight_uses();
|
||||
void finish_buffer_liveness();
|
||||
|
||||
Registry& reg_;
|
||||
Program prog_;
|
||||
const Program* ref_ = nullptr;
|
||||
bool instances_ = true;
|
||||
|
||||
std::vector<std::string> errors_;
|
||||
int status_ = RAD_OK;
|
||||
bool finished_ = false;
|
||||
|
||||
std::string scope_;
|
||||
|
||||
/* Parallel to prog_.ops: the buffers each op declared it reads and writes. */
|
||||
struct OpBufUse { std::vector<rad_buf> reads, writes; };
|
||||
std::vector<OpBufUse> op_bufs_;
|
||||
|
||||
/* Buffers touched from the second lane (rad_buf_concurrent). Their declared op range does not
|
||||
* bound when their bytes are in use, so they are live for the whole program. */
|
||||
std::set<rad_buf> concurrent_bufs_;
|
||||
|
||||
/* Parallel to prog_.kv_groups: where in the op list the group was declared, and the op found
|
||||
* to consume it. Declaration order is the only link between an op and a group; see
|
||||
* find_kv_consumer(). */
|
||||
std::vector<int32_t> kv_decl_at_;
|
||||
std::vector<int32_t> kv_consumer_;
|
||||
|
||||
/* Declared name -> index of its first prog_.name_map entry, so a repeated declaration is
|
||||
* checked in constant time; a routed model declares tens of thousands of weights. */
|
||||
std::unordered_map<std::string, size_t> name_map_first_;
|
||||
|
||||
/* Declared weight name -> handle, for the same reason (Flash-Next declares about 100K weights
|
||||
* per rank). */
|
||||
std::unordered_map<std::string, rad_weight> weight_by_name_;
|
||||
|
||||
/* The model's answers, cached per source: a routed model declares each expert's codes and
|
||||
* scales as two weights over one source, and a checkpoint lookup walks the name map. */
|
||||
WeightSourceFn sources_;
|
||||
std::unordered_map<std::string, std::pair<int, WeightSource>> source_cache_;
|
||||
int lookup_source(const std::string& name, WeightSource* out);
|
||||
|
||||
BufPlanReport bufrep_;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ --debug-graph (spec §16) */
|
||||
/* The entire declared graph: every op in declared order with its bucket table (one line per band:
|
||||
* the resolving kernel, variant and plugin, the matched constraints, the weights touched and the
|
||||
* buffer written); then the weight manifest, buffer plan, KV groups, tuning requests and miss
|
||||
* report. The bucket-table block is exactly the format in spec §2.2. */
|
||||
std::string dump_graph_str(const Program& p, const std::vector<std::string>* errors = nullptr);
|
||||
|
||||
/* The same walk as JSON, for the server's Model view, grouped by (op, band table): an op declared
|
||||
* once per layer with one bucket table is one row with a count. */
|
||||
std::string dump_graph_json(const Program& p);
|
||||
void dump_graph (const Program& p, FILE* out,
|
||||
const std::vector<std::string>* errors = nullptr);
|
||||
|
||||
} /* namespace rad */
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,759 @@
|
||||
/* rad_graph.cpp -- `--debug-graph` (spec §16): the full record of what runs. Every op in declared
|
||||
* order with its bucket table (one line per band: the resolving kernel, variant and plugin), the
|
||||
* matched constraints, the weights it touches and the buffer it writes; then the weight manifest,
|
||||
* buffer plan, KV groups, tuning requests and miss report.
|
||||
*
|
||||
* The bucket-table block is exactly the format in spec §2.2:
|
||||
*
|
||||
* gemm_w4a8_nt N=8192 K=5120
|
||||
* M <= 16 -> gemm_w4a8_nt_m64 (libr4d, prio 20)
|
||||
* M <= 64 -> gemm_w4a8_nt_m64 (libr4d, prio 20)
|
||||
* M <= 8192 -> gemm_w4a8_prefill (libr4d, prio 10)
|
||||
*
|
||||
* Everything else goes on its own lines at a deeper indent, so the table stays greppable.
|
||||
*/
|
||||
#include "rad_build.h"
|
||||
|
||||
#include "startup.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <climits>
|
||||
#include <unordered_map>
|
||||
#include <cstring>
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* ordered_json keeps keys in insertion order rather than alphabetical. */
|
||||
using json = nlohmann::ordered_json;
|
||||
|
||||
namespace {
|
||||
|
||||
/* A constraint as the kernel wrote it. constraint_why() phrases it as a refusal
|
||||
* ("M <= 16, have 8192") for the miss column. */
|
||||
std::string constraint_str(const RadConstraint& c) {
|
||||
switch (c.op) {
|
||||
case RAD_C_EQ: return fmt("%s == %lld", c.key, c.ival);
|
||||
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)", plus the tuned point only for a kernel with declared axes, so rows that
|
||||
* were tuned stand out (spec §15). */
|
||||
std::string origin(const Resolved& r) {
|
||||
const RadKernelInfo* k = r.row->info;
|
||||
if (!k || k->n_tunables <= 0) return fmt("(%s, prio %d)", r.row->plugin.c_str(),
|
||||
k ? k->priority : 0);
|
||||
const char* vn = r.choice.empty() ? "?" : r.choice.c_str();
|
||||
/* Same spelling as render_band_table in core/plugin/. */
|
||||
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, through the arrow. Ranged and fixed forms share column positions
|
||||
* so they stack in one table. */
|
||||
std::string band_prefix(const OpInfo& o, const Band& b) {
|
||||
if (o.ranged_key.empty()) return " always -> ";
|
||||
if (b.hi == LLONG_MAX) return fmt(" %s <= any -> ", o.ranged_key.c_str());
|
||||
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 {
|
||||
/* Misses are reported per band, not per op (spec §2.2). */
|
||||
s += band_prefix(o, b) + fmt("%-24s", "(nothing)")
|
||||
+ "-- " + (b.miss[d].empty() ? "no kernel matched" : b.miss[d]) + "\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void dump_matched(std::string& s, const OpInfo& o, int d) {
|
||||
/* One line per distinct kernel, not per band. */
|
||||
std::vector<const RadKernelInfo*> seen;
|
||||
for (const Band& b : o.bands) {
|
||||
const Resolved& r = b.dom[d];
|
||||
if (!r || !r.row->info) continue;
|
||||
if (std::find(seen.begin(), seen.end(), r.row->info) != seen.end()) continue;
|
||||
seen.push_back(r.row->info);
|
||||
|
||||
std::string cs;
|
||||
for (int i = 0; i < r.row->info->n_constraints; ++i) {
|
||||
if (i) cs += ", ";
|
||||
cs += constraint_str(r.row->info->constraints[i]);
|
||||
}
|
||||
if (cs.empty()) cs = "(unconstrained -- serves any geometry)";
|
||||
s += fmt(" matched %s: %s\n", r.row->info->name, cs.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
/* Append a table row with trailing spaces trimmed; the tier and site columns are empty at declare
|
||||
* (the planner fills them). */
|
||||
void append_row(std::string& s, std::string row) {
|
||||
while (!row.empty() && row.back() == ' ') row.pop_back();
|
||||
s += row;
|
||||
s += '\n';
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
std::string dump_graph_str(const Program& p, const std::vector<std::string>* errors) {
|
||||
std::string s;
|
||||
|
||||
s += fmt("==== declared graph: %s [%s] rank %d/%d max_tok %lld max_seqs %lld%s\n\n",
|
||||
p.meta.name ? p.meta.name : "?", p.meta.arch_id ? p.meta.arch_id : "?",
|
||||
p.ctx.rank, p.ctx.world_size, (long long)p.ctx.max_tok, (long long)p.ctx.max_seqs,
|
||||
(p.ctx.scope && *p.ctx.scope) ? fmt(" scope '%s'", p.ctx.scope).c_str() : "");
|
||||
|
||||
/* ---------------------------------------------------------------- the ops */
|
||||
for (size_t i = 1; i < p.ops.size(); ++i) {
|
||||
const OpInfo& o = p.ops[i];
|
||||
|
||||
std::string params = o.base.str();
|
||||
s += o.op;
|
||||
if (!params.empty()) { s += " "; s += params; }
|
||||
s += "\n";
|
||||
|
||||
/* Device first and unlabelled, the §2.2 form. A host-only kernel set (a primary target,
|
||||
* not a fallback) gets a labelled host table instead of a device table of holes. */
|
||||
bool dev = domain_has_any(o, RAD_DOMAIN_DEVICE);
|
||||
bool hst = domain_has_any(o, RAD_DOMAIN_HOST);
|
||||
bool printed_device = dev || !hst;
|
||||
|
||||
if (printed_device) dump_bucket_table(s, o, RAD_DOMAIN_DEVICE);
|
||||
if (hst) {
|
||||
if (printed_device) s += " host domain:\n";
|
||||
dump_bucket_table(s, o, RAD_DOMAIN_HOST);
|
||||
}
|
||||
|
||||
if (printed_device) dump_matched(s, o, RAD_DOMAIN_DEVICE);
|
||||
if (hst) dump_matched(s, o, RAD_DOMAIN_HOST);
|
||||
|
||||
if (!o.weights.empty()) {
|
||||
std::vector<std::string> names;
|
||||
for (rad_weight h : o.weights)
|
||||
names.push_back(h < p.weights.size() ? p.weights[h].name : fmt("<bad handle %u>", h));
|
||||
s += fmt(" weights %s\n", join(names).c_str());
|
||||
}
|
||||
|
||||
/* Buffers this op writes, read off the plan: a transient whose live range begins here is
|
||||
* defined by this op. */
|
||||
std::vector<std::string> defs, ends;
|
||||
const int32_t nops = (int32_t)p.ops.size() - 1;
|
||||
for (size_t bi = 1; bi < p.buffers.size(); ++bi) {
|
||||
const BufferInfo& b = p.buffers[bi];
|
||||
if (b.decl.kind != RAD_BUF_TRANSIENT) continue;
|
||||
/* Whole-program liveness means no declared use; attributing it to the first and last
|
||||
* op would be wrong. The buffer plan section counts these. */
|
||||
if (b.first_def <= 0 && b.last_use >= nops) continue;
|
||||
if (b.first_def == (int32_t)i) defs.push_back(b.name);
|
||||
else if (b.last_use == (int32_t)i) ends.push_back(b.name);
|
||||
}
|
||||
if (!defs.empty()) s += fmt(" writes %s\n", join(defs).c_str());
|
||||
if (!ends.empty()) s += fmt(" last use %s\n", join(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 the storage form the resolved kernel asked for, which is why stored bytes may
|
||||
* differ from logical ones. tier and site stay blank: the planner fills them after
|
||||
* declare, and a default would read as a decision. */
|
||||
append_row(s, fmt(" %-40s %12s %6lld %-12s %6d %7d %6d %6d %-16s %-5s %-5s",
|
||||
w.name.c_str(), humanb(w.stored_bytes).c_str(), (long long)w.align,
|
||||
bld_access_name(w.decl.access), w.decl.group.layer, w.decl.group.expert,
|
||||
w.first_use_op, w.last_use_op,
|
||||
w.layout_tag.empty() ? "as declared" : w.layout_tag.c_str(), "", ""));
|
||||
}
|
||||
s += "\n";
|
||||
|
||||
/* ---------------------------------------------------------------- the buffer plan */
|
||||
int64_t sum = 0, peak = 0, unknown = 0, persist = 0;
|
||||
const int32_t last_op = (int32_t)p.ops.size() - 1;
|
||||
for (size_t i = 1; i < p.buffers.size(); ++i) {
|
||||
const BufferInfo& b = p.buffers[i];
|
||||
if (b.decl.domain == RAD_DOMAIN_HOST) continue;
|
||||
if (b.decl.kind == RAD_BUF_TRANSIENT) {
|
||||
sum += b.bytes;
|
||||
if (b.first_def <= 0 && b.last_use >= last_op) ++unknown;
|
||||
} else {
|
||||
persist += b.bytes;
|
||||
}
|
||||
}
|
||||
for (int32_t t = 1; t <= std::max<int32_t>(last_op, 1); ++t) {
|
||||
int64_t live = 0;
|
||||
for (size_t i = 1; i < p.buffers.size(); ++i) {
|
||||
const BufferInfo& b = p.buffers[i];
|
||||
if (b.decl.kind != RAD_BUF_TRANSIENT || b.decl.domain == RAD_DOMAIN_HOST) continue;
|
||||
if (b.first_def <= t && t <= b.last_use) live += b.bytes;
|
||||
}
|
||||
peak = std::max(peak, live);
|
||||
}
|
||||
|
||||
s += fmt("---- buffer plan: arena %s, scratch %s\n",
|
||||
humanb(p.arena_bytes).c_str(), humanb(p.scratch_bytes).c_str());
|
||||
s += fmt(" transient %12s packed from %s unshared (peak live %s, waste %s)\n",
|
||||
humanb(p.arena_bytes - persist).c_str(), humanb(sum).c_str(),
|
||||
humanb(peak).c_str(), humanb(p.arena_bytes - persist - peak).c_str());
|
||||
s += fmt(" persist %12s\n", humanb(persist).c_str());
|
||||
/* Two arenas, coloured separately (see plan_buffers). */
|
||||
if (p.host_arena_bytes)
|
||||
s += fmt(" host arena %12s (its own offset space and its own base pointer)\n",
|
||||
humanb(p.host_arena_bytes).c_str());
|
||||
if (unknown)
|
||||
s += fmt(" %lld transient buffer(s) had no declared use and are assumed live for the "
|
||||
"whole program -- that is the arena's waste, and it goes away when ops name "
|
||||
"their buffer operands\n", (long long)unknown);
|
||||
|
||||
std::vector<const BufferInfo*> big;
|
||||
for (size_t i = 1; i < p.buffers.size(); ++i) big.push_back(&p.buffers[i]);
|
||||
std::sort(big.begin(), big.end(),
|
||||
[](const BufferInfo* a, const BufferInfo* b) { return a->bytes > b->bytes; });
|
||||
for (size_t i = 0; i < big.size() && i < 5; ++i)
|
||||
s += fmt(" %-32s %12s %-9s live [%d,%d] @ %lld\n", big[i]->name.c_str(),
|
||||
humanb(big[i]->bytes).c_str(), bld_buf_kind_name(big[i]->decl.kind),
|
||||
big[i]->first_def, big[i]->last_use, (long long)big[i]->arena_offset);
|
||||
s += "\n";
|
||||
|
||||
/* ---------------------------------------------------------------- KV groups */
|
||||
if (p.kv_groups.size() > 1) {
|
||||
s += fmt("---- kv groups: %zu\n", p.kv_groups.size() - 1);
|
||||
for (size_t i = 1; i < p.kv_groups.size(); ++i) {
|
||||
const KVGroupInfo& g = p.kv_groups[i];
|
||||
s += fmt(" %-20s %-7s block %-5lld %12s/block %12s/state %zu layer(s)\n",
|
||||
g.name.c_str(), bld_kv_kind_name(g.decl.kind), (long long)g.block_size,
|
||||
humanb(g.bytes_per_block).c_str(), humanb(g.bytes_per_state).c_str(),
|
||||
g.layers.size());
|
||||
}
|
||||
s += "\n";
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- the drafter (spec §10) */
|
||||
if (p.drafter.kind != RAD_DRAFT_NONE) {
|
||||
const bool blk = p.drafter.kind == RAD_DRAFT_BLOCK;
|
||||
s += fmt("---- drafter: '%s', %s, %d token(s) a step\n",
|
||||
p.drafter_name.c_str(),
|
||||
blk ? "RAD_DRAFT_BLOCK -- a context pass, then one pass fills the whole block"
|
||||
: "RAD_DRAFT_SERIAL -- one dependent pass a token",
|
||||
p.drafter.depth);
|
||||
s += fmt(" proposal %s\n",
|
||||
p.drafter.proposal
|
||||
? fmt("%s [%lld a row]", p.buffers[p.drafter.proposal].name.c_str(),
|
||||
(long long)p.drafter.proposal_pitch).c_str()
|
||||
: "the sampler's token buffer (this head's logits go through the chain)");
|
||||
if (blk)
|
||||
s += fmt(" block %lld row(s) a sequence, the head over the last %d, mask token "
|
||||
"%d, drafter window %lld\n",
|
||||
(long long)p.drafter.block, p.drafter.depth,
|
||||
(int)p.drafter.mask_token, (long long)p.drafter.window);
|
||||
if (p.drafter_shared_kv)
|
||||
s += fmt(" cache none of its own: it reads the trunk's, owes no history, and "
|
||||
"every round runs at the committed position%s\n",
|
||||
p.drafter_pos_offset ? " (rotated one past it)" : "");
|
||||
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)
|
||||
*
|
||||
* Launches that stand in for several ops. A kernel with `replaces` declares, as data, the
|
||||
* conventional chain it computes; rad-check checks it against that chain. This section is
|
||||
* coverage, not advice: an op with no fusion is not a defect, and a fusion that did not fire
|
||||
* is usually banded on purpose. */
|
||||
{
|
||||
std::vector<std::string> lines;
|
||||
int n_fused = 0, n_ops_replaced = 0;
|
||||
for (size_t i = 1; i < p.ops.size(); ++i) {
|
||||
const OpInfo& o = p.ops[i];
|
||||
for (size_t b = 0; b < o.bands.size(); ++b) {
|
||||
for (int d = 0; d < RAD_N_DOMAINS; ++d) {
|
||||
const Resolved& r = o.bands[b].dom[d];
|
||||
if (!r || !r.row || !r.row->info || !r.row->info->replaces) continue;
|
||||
/* Walk the chain; the hook ends it by declining the step past the end. */
|
||||
std::string chain;
|
||||
int n_step = 0;
|
||||
for (int step = 0; step < RAD_MAX_FUSE_OPD; ++step) {
|
||||
RadFuseStep fs{};
|
||||
/* RAD_FUSE_PRESENT_ALL: the declared graph records ops and geometry, not
|
||||
* which optional operands a given issue passes (a per-step property). So
|
||||
* the row means "what this kernel stands in for", described for the operand
|
||||
* set the kernel publishes, not "what ran on the last token". */
|
||||
const int st = r.row->info->replaces(r.geom.params(), r.geom.n_params(),
|
||||
RAD_FUSE_PRESENT_ALL,
|
||||
step, &fs);
|
||||
if (st != RAD_OK) break;
|
||||
if (!fs.op) break;
|
||||
chain += (chain.empty() ? "" : " -> ");
|
||||
chain += fs.op;
|
||||
++n_step;
|
||||
}
|
||||
if (n_step < 2) continue; /* a one-op "chain" is not a fusion */
|
||||
++n_fused;
|
||||
n_ops_replaced += n_step;
|
||||
lines.push_back(fmt(" %-24s %-28s %s", o.op.c_str(), r.row->info->name,
|
||||
chain.c_str()));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (n_fused > 0) {
|
||||
std::sort(lines.begin(), lines.end());
|
||||
lines.erase(std::unique(lines.begin(), lines.end()), lines.end());
|
||||
s += fmt("---- fusions: %d resolved kernel(s) stand in for %d op(s)\n",
|
||||
n_fused, n_ops_replaced);
|
||||
s += " each row is a kernel and the conventional chain it declares it computes;\n"
|
||||
" rad-check runs that chain out of the same plugin and compares the bytes\n";
|
||||
for (const std::string& l : lines) s += l + "\n";
|
||||
s += "\n";
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- plugin notes */
|
||||
if (!p.notes.empty()) {
|
||||
s += "---- notes from the architecture plugin\n";
|
||||
for (const auto& n : p.notes) s += " " + n + "\n";
|
||||
s += "\n";
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- what did not resolve */
|
||||
if (!p.misses.empty()) {
|
||||
s += fmt("---- unresolved: %zu op/band/domain combination(s)\n", p.misses.size());
|
||||
s += " no DEVICE kernel is fatal for that band; no HOST kernel removes host-site\n"
|
||||
" placement for that op and nothing else (spec §2.1)\n";
|
||||
for (const auto& m : p.misses) s += " " + m.line() + "\n";
|
||||
s += "\n";
|
||||
}
|
||||
|
||||
if (errors && !errors->empty()) {
|
||||
s += fmt("---- declare errors: %zu\n", errors->size());
|
||||
for (const auto& e : *errors) s += " " + e + "\n";
|
||||
s += "\n";
|
||||
}
|
||||
|
||||
return s;
|
||||
}
|
||||
|
||||
void dump_graph(const Program& p, FILE* out, const std::vector<std::string>* errors) {
|
||||
std::string s = dump_graph_str(p, errors);
|
||||
fwrite(s.data(), 1, s.size(), out ? out : stderr);
|
||||
fflush(out ? out : stderr);
|
||||
}
|
||||
|
||||
/* ================================================================== the graph, as JSON
|
||||
*
|
||||
* dump_graph_str's content and more, for the server's Model view. It walks the same Program with
|
||||
* the same helpers (origin, constraint_str, the fuse hook), so the two views cannot disagree.
|
||||
*
|
||||
* The extra detail lives in the per-op panel: the schema doc and operands, declared geometry,
|
||||
* each band's winner and the candidates that lost with their reasons, the kernel's own
|
||||
* description, what it stands in for, the weights read (size, layout) and the buffers whose lives
|
||||
* begin and end at the op.
|
||||
*
|
||||
* Ops are grouped by (op name, every band's resolution), so a per-layer op is one entry with a
|
||||
* count. Per-occurrence facts (weights, buffers, op index) are the first declaration's, and the
|
||||
* page labels them so. */
|
||||
|
||||
/* A RadFuseStep's own geometry, which differs from the fused op's: `qk_norm_rope_gate` replaces
|
||||
* an rmsnorm at M = T * n_head, a product absent from the fused op's parameters. */
|
||||
static std::string params_str(const RadParam* p, int n) {
|
||||
std::string s;
|
||||
for (int i = 0; i < n; ++i) {
|
||||
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, which makes the claim
|
||||
* checkable and which a reader cannot derive. */
|
||||
static json fuse_steps(const Resolved& r) {
|
||||
json out = json::array();
|
||||
if (!r || !r.row || !r.row->info || !r.row->info->replaces) return out;
|
||||
for (int step = 0; step < RAD_MAX_FUSE_OPD; ++step) {
|
||||
RadFuseStep fs{};
|
||||
/* RAD_FUSE_PRESENT_ALL: see the same call in dump_graph_str. */
|
||||
if (r.row->info->replaces(r.geom.params(), r.geom.n_params(),
|
||||
RAD_FUSE_PRESENT_ALL, step, &fs) != RAD_OK) break;
|
||||
if (!fs.op) break;
|
||||
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;
|
||||
}
|
||||
|
||||
/* The optional ABI hooks a kernel supplies, which decide what the tools can do with it: without
|
||||
* `opd_shape` rad-check skips the row, without `unrelayout` a dense oracle has nothing to compare,
|
||||
* without `replaces` a fusion is unchecked. */
|
||||
static json kernel_hooks(const RadKernelInfo* k) {
|
||||
json h = json::array();
|
||||
if (k->init) h.push_back("init");
|
||||
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 author's own description. */
|
||||
if (k->family && *k->family) j["family"] = k->family;
|
||||
if (k->computes && *k->computes) j["computes"] = k->computes;
|
||||
if (k->shape && *k->shape) j["shape"] = k->shape;
|
||||
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 with its full range, not just the choice, so a reader can tell a tuned
|
||||
choice from a forced one (an axis with no alternatives at this shape). */
|
||||
json ax = json::array();
|
||||
int64_t space = 1;
|
||||
for (int i = 0; i < k->n_tunables; ++i) {
|
||||
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;
|
||||
}
|
||||
/* The kernel's declared constraints, which selection matched it on. With the band's
|
||||
* `considered` list and `priority`, they explain why it won. */
|
||||
json cons = json::array();
|
||||
for (int i = 0; i < k->n_constraints; ++i) cons.push_back(constraint_str(k->constraints[i]));
|
||||
j["constraints"] = std::move(cons);
|
||||
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;
|
||||
}
|
||||
|
||||
/* Every candidate for this band and what refused it (SelectionTrace::candidates; build_bands keeps
|
||||
* only the miss reason). Recomputed rather than stored on every Band, which would hold megabytes of
|
||||
* strings for the process lifetime; the cost is one pass over one op's rows per distinct band
|
||||
* table. `record = false` keeps the selection table's "asked" counts to the engine's own
|
||||
* queries. */
|
||||
static json considered_json(Registry& reg, const OpInfo& o, const Band& b, int dom) {
|
||||
Geometry q = o.base;
|
||||
if (!o.ranged_key.empty()) q.set_i(o.ranged_key, b.hi == INT64_MAX ? o.range_hi : b.hi);
|
||||
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;
|
||||
}
|
||||
|
||||
/* The op's schema. The operand list matters most: `RadArgs.t` is positional, so it is the only
|
||||
* way to read a fused kernel's `from` wiring. */
|
||||
static json schema_json(const RadOpSchema* s) {
|
||||
if (!s) return nullptr;
|
||||
json j;
|
||||
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;
|
||||
}
|
||||
|
||||
/* A weight one declaration of this op reads: its stored size, and the layout the winning kernel
|
||||
* demanded (why stored bytes may differ from logical ones). */
|
||||
static json weight_json(const WeightInfo& w) {
|
||||
json j;
|
||||
j["name"] = w.name;
|
||||
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: an override is a plugin ahead of the default in this list. */
|
||||
json plugs = json::array();
|
||||
for (const Plugin& pl : reg.plugins()) {
|
||||
json j;
|
||||
j["name"] = pl.name;
|
||||
j["order"] = pl.order;
|
||||
j["version"] = pl.version;
|
||||
j["kernels"] = pl.n_kernels;
|
||||
j["schemas"] = pl.n_schemas;
|
||||
if (!pl.description.empty()) j["description"] = pl.description;
|
||||
if (!pl.build_target.empty()) j["build_target"] = pl.build_target;
|
||||
if (!pl.arch_id.empty()) j["arch"] = pl.arch_id + (pl.arch_quant.empty()
|
||||
? std::string() : " " + pl.arch_quant);
|
||||
plugs.push_back(std::move(j));
|
||||
}
|
||||
root["plugins"] = std::move(plugs);
|
||||
|
||||
/* One entry per distinct (op, band table), with how many declarations collapsed into it. */
|
||||
std::vector<std::string> order; /* unique keys, first-seen order */
|
||||
std::vector<std::string> seq; /* every declared op, in order, by key */
|
||||
std::unordered_map<std::string, json> group;
|
||||
std::unordered_map<std::string, int64_t> tally;
|
||||
|
||||
const int32_t nops = (int32_t)p.ops.size() - 1;
|
||||
|
||||
for (size_t i = 1; i < p.ops.size(); ++i) {
|
||||
const OpInfo& o = p.ops[i];
|
||||
json bands = json::array();
|
||||
std::string key = o.op;
|
||||
for (const Band& b : o.bands) {
|
||||
json jb;
|
||||
jb["span"] = b.span;
|
||||
jb["hi"] = b.hi; /* the page picks the widest band as the node's headline */
|
||||
for (int d = 0; d < RAD_N_DOMAINS; ++d) {
|
||||
json rj = resolved_json(b.dom[d]);
|
||||
const char* dn = bld_domain_name(d);
|
||||
if (!rj.is_null()) jb[dn] = std::move(rj);
|
||||
else if (!b.miss[d].empty()) jb[std::string(dn) + "_miss"] = b.miss[d];
|
||||
}
|
||||
/* The grouping key is formed before the candidate lists are added: `considered`
|
||||
* depends only on op and band, so hashing it would add cost and nothing else. */
|
||||
key += "|" + jb.dump();
|
||||
for (int d = 0; d < RAD_N_DOMAINS; ++d)
|
||||
jb[std::string(bld_domain_name(d)) + "_considered"] =
|
||||
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);
|
||||
|
||||
/* Buffers whose lives begin or end at this op, read off the plan as in the text dump.
|
||||
* Whole-program buffers (no declared use) are skipped. */
|
||||
json writes = json::array(), frees = json::array();
|
||||
for (size_t bi = 1; bi < p.buffers.size(); ++bi) {
|
||||
const BufferInfo& bf = p.buffers[bi];
|
||||
if (bf.decl.kind != RAD_BUF_TRANSIENT) continue;
|
||||
if (bf.first_def <= 0 && bf.last_use >= nops) continue;
|
||||
if (bf.first_def != (int32_t)i && bf.last_use != (int32_t)i) continue;
|
||||
json jb;
|
||||
jb["name"] = bf.name;
|
||||
jb["bytes"] = bf.bytes;
|
||||
jb["domain"] = bld_domain_name(bf.decl.domain);
|
||||
jb["live"] = fmt("[%d, %d]", bf.first_def, bf.last_use);
|
||||
if (bf.first_def == (int32_t)i) writes.push_back(std::move(jb));
|
||||
else frees.push_back(std::move(jb));
|
||||
}
|
||||
j["writes"] = std::move(writes);
|
||||
j["frees"] = std::move(frees);
|
||||
j["bands"] = std::move(bands);
|
||||
group.emplace(key, std::move(j));
|
||||
order.push_back(key);
|
||||
tally[key] = 1;
|
||||
}
|
||||
|
||||
std::unordered_map<std::string, int> index_of;
|
||||
json ops = json::array();
|
||||
for (const std::string& key : order) {
|
||||
index_of[key] = (int)ops.size();
|
||||
json j = group[key];
|
||||
j["count"] = tally[key];
|
||||
ops.push_back(std::move(j));
|
||||
}
|
||||
|
||||
/* The declared order as indices into `ops`, which the grouping dropped and the diagram needs.
|
||||
* One small integer per declared op, far smaller than emitting every op in full. */
|
||||
json ord = json::array();
|
||||
std::vector<int> first_at((size_t)ops.size(), -1), last_at((size_t)ops.size(), -1);
|
||||
for (size_t k = 0; k < seq.size(); ++k) {
|
||||
const int gi = index_of[seq[k]];
|
||||
ord.push_back(gi);
|
||||
if (first_at[(size_t)gi] < 0) first_at[(size_t)gi] = (int)k;
|
||||
last_at[(size_t)gi] = (int)k;
|
||||
}
|
||||
/* First and last position of the group's declarations in the flow. */
|
||||
for (size_t k = 0; k < ops.size(); ++k) {
|
||||
ops[k]["first_at"] = first_at[k];
|
||||
ops[k]["last_at"] = last_at[k];
|
||||
}
|
||||
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 */
|
||||
@@ -0,0 +1,398 @@
|
||||
/* startup.cpp -- the tools' seam onto core/plugin and core/build, and the shared CLI plumbing.
|
||||
* The tools use the same Registry and Builder as the engine (see startup.h), so they resolve the
|
||||
* same program.
|
||||
*/
|
||||
#include "build/startup.h"
|
||||
#include "build/rad_build.h"
|
||||
#include "format/tunecache.h"
|
||||
#include "plugin/registry.h"
|
||||
|
||||
#include <sys/stat.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* One Registry for the life of the process: Resolved, Band and KernelRow point into plugin
|
||||
* static tables, and the Program outlives the call that built it.
|
||||
*
|
||||
* Never destroyed. A function-local static would be destroyed after the plugins' own static
|
||||
* destructors, and its close would call each instance's fini into destroyed plugin state (e.g.
|
||||
* libr4d's router erasing from its destroyed global map: a double free). A caller that needs the
|
||||
* finis closes the registry while plugins are alive, as Engine's shutdown does. */
|
||||
Registry& rad_tools_registry() {
|
||||
static Registry* r = new Registry();
|
||||
return *r;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the reference-kernel gate */
|
||||
|
||||
/* An op is "on the reference" when no band in any domain offers a non-reference kernel
|
||||
* (RadPluginReferenceFn). A reference library usually serves the host domain for every op, so
|
||||
* only an op with no other implementation is flagged: wherever it is placed, it runs naive code.
|
||||
* Counted once per declared instance; `out` lists distinct op names. */
|
||||
int rad_reference_ops(const Program& p, std::vector<std::string>* out) {
|
||||
int n = 0;
|
||||
for (size_t i = 1; i < p.ops.size(); ++i) {
|
||||
const OpInfo& oi = p.ops[i];
|
||||
bool real = false;
|
||||
for (const Band& b : oi.bands)
|
||||
for (int d = 0; d < RAD_N_DOMAINS && !real; ++d)
|
||||
if (b.dom[d] && b.dom[d].row && !b.dom[d].row->reference)
|
||||
real = true;
|
||||
if (real) continue;
|
||||
++n;
|
||||
/* Deduplicated by op name. */
|
||||
if (out && std::find(out->begin(), out->end(), oi.op) == out->end())
|
||||
out->push_back(oi.op);
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
int rad_gate_reference_kernels(const Program& p, bool allow, const char* what) {
|
||||
std::vector<std::string> ops;
|
||||
const int n = rad_reference_ops(p, &ops);
|
||||
if (n == 0) return RAD_OK;
|
||||
|
||||
const std::string list = join(ops);
|
||||
/* The reference libraries involved, by plugin name. */
|
||||
std::vector<std::string> refs;
|
||||
for (size_t i = 1; i < p.ops.size(); ++i)
|
||||
for (const Band& b : p.ops[i].bands)
|
||||
for (int d = 0; d < RAD_N_DOMAINS; ++d)
|
||||
if (b.dom[d] && b.dom[d].row && b.dom[d].row->reference &&
|
||||
std::find(refs.begin(), refs.end(), b.dom[d].row->plugin) == refs.end())
|
||||
refs.push_back(b.dom[d].row->plugin);
|
||||
const std::string libs = join(refs);
|
||||
|
||||
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), which runs "
|
||||
"orders of magnitude slower; %s refuses them (spec §17).\n"
|
||||
" %zu distinct op(s): %s\n"
|
||||
" Supply a kernel plugin that covers these ops, or pass "
|
||||
"--debug-accept-reference-kernels to accept the cost.",
|
||||
n, libs.c_str(), what, ops.size(), list.c_str());
|
||||
return RAD_E_NOKERNEL;
|
||||
}
|
||||
|
||||
std::vector<std::string> rad_home_dirs(const std::string& home) {
|
||||
std::vector<std::string> out;
|
||||
size_t i = 0;
|
||||
while (i <= home.size()) {
|
||||
size_t e = home.find(':', i);
|
||||
if (e == std::string::npos) e = home.size();
|
||||
if (e > i) out.push_back(home.substr(i, e - i));
|
||||
i = e + 1;
|
||||
}
|
||||
if (out.empty()) out.push_back(".");
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string rad_home_file(const std::string& home, const std::string& rel) {
|
||||
const std::vector<std::string> dirs = rad_home_dirs(home);
|
||||
for (const std::string& d : dirs) {
|
||||
struct stat st {};
|
||||
if (stat((d + "/" + rel).c_str(), &st) == 0) return d + "/" + rel;
|
||||
}
|
||||
return dirs.front() + "/" + rel;
|
||||
}
|
||||
|
||||
/* The homes on the path that have the directory `sub`. */
|
||||
static std::vector<std::string> home_subdirs(const std::string& home, const char* sub) {
|
||||
std::vector<std::string> out;
|
||||
for (const std::string& d : rad_home_dirs(home)) {
|
||||
struct stat st {};
|
||||
const std::string p = d + "/" + sub;
|
||||
if (stat(p.c_str(), &st) == 0 && S_ISDIR(st.st_mode)) out.push_back(p);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
int rad_tools_load_plugins(const std::string& home, const std::vector<std::string>& hierarchy,
|
||||
const std::string& arch_id, const std::string& quant,
|
||||
LoadedPlugins* out, bool imported) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
*out = LoadedPlugins{};
|
||||
|
||||
Registry& r = rad_tools_registry();
|
||||
|
||||
/* Kernels first, in hierarchy order, then architectures (unordered: no two may claim the same
|
||||
* id). A home need not have every directory, but kernels/ and architectures/ must each exist
|
||||
* somewhere on the path, or the scan reports the first home's as missing. */
|
||||
const std::string first = rad_home_dirs(home).front();
|
||||
std::vector<std::string> kdirs = home_subdirs(home, "kernels");
|
||||
if (kdirs.empty()) kdirs.push_back(first + "/kernels");
|
||||
int s = r.load_dirs(kdirs, hierarchy);
|
||||
if (s < 0) return s;
|
||||
|
||||
std::vector<std::string> adirs = home_subdirs(home, "architectures");
|
||||
if (adirs.empty()) adirs.push_back(first + "/architectures");
|
||||
s = r.load_dirs(adirs, {});
|
||||
if (s < 0) return s;
|
||||
|
||||
/* Quantisers: rad-convert drives them, and the oracle decodes through them for schemes the
|
||||
* core does not define. Optional. */
|
||||
const std::vector<std::string> qdirs = home_subdirs(home, "quantizers");
|
||||
if (!qdirs.empty()) {
|
||||
s = r.load_dirs(qdirs, {});
|
||||
if (s < 0) return s;
|
||||
}
|
||||
|
||||
RAD_TRY(r.check_complete());
|
||||
|
||||
/* The tuning cache, once the kernel set is known. A missing file leaves every shape on its
|
||||
* plugin's first variant. Logged when it has rows; --debug-graph shows the per-shape
|
||||
* source. */
|
||||
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 (arch_id, quant) pair (spec §2.4), matched exactly with no
|
||||
* fallback; a mismatched plugin would only fail later at the name map with a worse message. */
|
||||
for (const Plugin& p : r.plugins()) {
|
||||
if (p.kind == RAD_PLUGIN_KERNEL) {
|
||||
out->kernels.push_back({ p.name, p.version });
|
||||
} 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;
|
||||
}
|
||||
}
|
||||
|
||||
/* An imported quantisation is served by the family's quantised plugin (startup.h). */
|
||||
if (imported && !arch_id.empty() && out->arch_plugin.empty()) {
|
||||
std::vector<const Plugin*> fam, quantised;
|
||||
for (const Plugin& p : r.plugins())
|
||||
if (p.kind == RAD_PLUGIN_ARCH && p.arch_id == arch_id) {
|
||||
fam.push_back(&p);
|
||||
if (!p.arch_quant.empty()) quantised.push_back(&p);
|
||||
}
|
||||
const Plugin* pick = quantised.size() == 1 ? quantised[0]
|
||||
: quantised.empty() && fam.size() == 1 ? fam[0] : nullptr;
|
||||
if (!pick && quantised.size() > 1) {
|
||||
std::string names;
|
||||
for (const Plugin* p : quantised) names += (names.empty() ? "" : ", ") + p->arch_quant;
|
||||
RAD_ERR("'%s' is quantised by %s and imported weight by weight, and '%s' has more than "
|
||||
"one quantised plugin (%s) to serve it; none is chosen for it",
|
||||
arch_id.c_str(), quant.c_str(), arch_id.c_str(), names.c_str());
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
if (pick) {
|
||||
out->arch_plugin = pick->name;
|
||||
out->arch_version = pick->version;
|
||||
out->arch_id = pick->arch_id;
|
||||
out->arch_quant = pick->arch_quant;
|
||||
RAD_INFO("quantisation '%s' is imported weight by weight; '%s' serves it as %s",
|
||||
quant.c_str(), pick->name.c_str(),
|
||||
pick->arch_quant.empty() ? "(unquantised)" : pick->arch_quant.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
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). List what is installed with its quantisation, to tell an
|
||||
* unsupported architecture from one supported only at another weight format. */
|
||||
std::string have, same;
|
||||
for (const Plugin& p : r.plugins()) {
|
||||
if (p.kind != RAD_PLUGIN_ARCH) continue;
|
||||
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;
|
||||
}
|
||||
|
||||
/* Optional export. Without it, or on failure, every field is zero and the caller uses its own
|
||||
* defaults. A failed probe is not an error: the plugin can still refuse in declare, where it has
|
||||
* the whole configuration 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);
|
||||
}
|
||||
|
||||
const RadAudioFormat* rad_tools_audio_format(const LoadedPlugins& lp, const RadModelMeta& meta) {
|
||||
const Plugin* ap = rad_tools_registry().plugin(lp.arch_plugin);
|
||||
if (!ap || !ap->arch_audio_format) return nullptr;
|
||||
const RadAudioFormat* f = ap->arch_audio_format(&meta);
|
||||
if (!f) return nullptr;
|
||||
/* The plugin's struct may be older than ours: it is copied into a zeroed one up to the size
|
||||
* it states, so a field it predates reads as null (rad_builder.h). */
|
||||
static thread_local RadAudioFormat copy;
|
||||
copy = RadAudioFormat{};
|
||||
const size_t n = f->struct_size < sizeof copy ? f->struct_size : sizeof copy;
|
||||
std::memcpy(©, f, n);
|
||||
copy.struct_size = (uint32_t)sizeof copy;
|
||||
return ©
|
||||
}
|
||||
|
||||
WeightSourceFn rad_container_sources(const RadFile& f) {
|
||||
return [&f](const std::string& name, const Program&, WeightSource* out) {
|
||||
const RadFileEntry* e = f.find(name);
|
||||
if (!e) return RAD_E_NOTFOUND;
|
||||
out->enc = f.encoding(*e);
|
||||
out->rank = e->rank;
|
||||
for (int i = 0; i < RAD_MAX_RANK; ++i) out->shape[i] = e->shape[i];
|
||||
return RAD_OK;
|
||||
};
|
||||
}
|
||||
|
||||
WeightSourceFn CheckpointSources::fn() {
|
||||
return [this](const std::string& name, const Program& prog, WeightSource* out) {
|
||||
return answer(name, prog, out);
|
||||
};
|
||||
}
|
||||
|
||||
int CheckpointSources::answer(const std::string& name, const Program& prog, WeightSource* out) {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
auto it = got_.find(name);
|
||||
if (it == got_.end()) {
|
||||
CkptWeight w;
|
||||
std::string why;
|
||||
const int st = ckpt_resolve(ck_, prog, name, false, &w, &why);
|
||||
/* Not-found is not cached, since declare may map the name later, but its reason is kept
|
||||
* for the loader to report. */
|
||||
if (st == RAD_E_NOTFOUND) {
|
||||
missing_[name] = why;
|
||||
return st;
|
||||
}
|
||||
missing_.erase(name);
|
||||
if (st < 0) {
|
||||
refused_[name] = why;
|
||||
return st;
|
||||
}
|
||||
it = got_.emplace(name, std::move(w)).first;
|
||||
}
|
||||
const CkptWeight& w = it->second;
|
||||
if (!w.trivial) {
|
||||
refused_[name] = w.why;
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
out->enc = w.enc;
|
||||
out->rank = w.rank;
|
||||
for (int i = 0; i < RAD_MAX_RANK; ++i) out->shape[i] = w.shape[i];
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
const CkptWeight* CheckpointSources::find(const std::string& name) const {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
auto it = got_.find(name);
|
||||
return it == got_.end() || !it->second.trivial ? nullptr : &it->second;
|
||||
}
|
||||
|
||||
std::string CheckpointSources::missing(const std::string& name) const {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
auto it = missing_.find(name);
|
||||
return it == missing_.end() ? std::string() : it->second;
|
||||
}
|
||||
|
||||
std::vector<std::string> CheckpointSources::refused() const {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
std::vector<std::string> out;
|
||||
for (const auto& [n, why] : refused_) out.push_back(n + ": " + why);
|
||||
return out;
|
||||
}
|
||||
|
||||
int rad_tools_declare(const LoadedPlugins& lp, const RadModelMeta& meta, const RadBuildCtx& ctx,
|
||||
Program* out, const std::function<int(RadBuilder*, int64_t)>& also,
|
||||
const Program* ref, const WeightSourceFn& sources, bool instances) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
|
||||
Registry& r = rad_tools_registry();
|
||||
const Plugin* ap = r.plugin(lp.arch_plugin);
|
||||
if (!ap || !ap->arch_declare) {
|
||||
RAD_ERR("architecture plugin '%s' is not loaded or exports no rad_arch_declare",
|
||||
lp.arch_plugin.c_str());
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
|
||||
Builder b(r, meta, ctx);
|
||||
if (ref) b.set_reference(ref);
|
||||
if (sources) b.set_sources(sources);
|
||||
b.set_instances(instances);
|
||||
|
||||
int s = ap->arch_declare(&b, &meta, &ctx);
|
||||
if (s < 0) {
|
||||
RAD_ERR("%s: rad_arch_declare returned %s", lp.arch_plugin.c_str(), rad_strerror(s));
|
||||
for (const auto& e : b.errors()) RAD_ERR(" %s", e.c_str());
|
||||
return s;
|
||||
}
|
||||
|
||||
/* The sampler declares into the same builder before finish(). An unresolved sampler op is not
|
||||
* a declare failure (a deployment that never sends `typical_p` needs no typical kernel), so a
|
||||
* negative return here is structural. Skipped for embedding programs and image generators,
|
||||
* which sample no token. */
|
||||
if (also && b.program().pooled_buf == RAD_NULL_HANDLE && !b.program().is_generator()) {
|
||||
/* This rank's vocabulary width, taken from the declared logits buffer rather than
|
||||
* re-derived from n_vocab and world_size, which would break when a plugin does not split
|
||||
* the vocabulary (arch/common/rad_arch.h does not). A wrong width does not crash; it
|
||||
* samples the wrong tokens. */
|
||||
int64_t lw = 0;
|
||||
if (b.program().logits_buf != RAD_NULL_HANDLE &&
|
||||
(size_t)b.program().logits_buf < b.program().buffers.size()) {
|
||||
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; every structural error is reported (spec §3.1). */
|
||||
for (const auto& e : b.errors()) RAD_ERR(" %s", e.c_str());
|
||||
if (s < 0) return s;
|
||||
if (b.status() < 0) return b.status();
|
||||
|
||||
*out = std::move(b.program());
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,158 @@
|
||||
/* startup.h -- steps 1 through 4 of spec §1's startup sequence, shared by the engine and the
|
||||
* tools.
|
||||
*
|
||||
* 1. Load kernel plugins from $RADIANCE_HOME/kernels/, in the configured hierarchy order.
|
||||
* 3. Look up the architecture id in $RADIANCE_HOME/architectures/.
|
||||
* 4. Declare.
|
||||
*
|
||||
* In core because rad-convert, rad-check and rad-tune are the engine's startup with a different
|
||||
* last step (spec §4.4, §15, §17). A second implementation could disagree on hierarchy order,
|
||||
* which decides the layout baked into a container.
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_core.h"
|
||||
#include "format/radfile.h"
|
||||
#include "format/checkpoint.h"
|
||||
#include "plugin/registry.h"
|
||||
#include "build/rad_build.h"
|
||||
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* A loaded plugin, as a tool names it. */
|
||||
struct PluginId { std::string name, version; };
|
||||
|
||||
struct LoadedPlugins {
|
||||
/* Kernel plugins in hierarchy order, which decides selection. */
|
||||
std::vector<PluginId> kernels;
|
||||
std::string arch_plugin;
|
||||
std::string arch_version;
|
||||
std::string arch_id;
|
||||
/* The quantisation half of the selection key, "" for an unquantised container. */
|
||||
std::string arch_quant;
|
||||
|
||||
/* `name@version`, space separated, in hierarchy order; what a benchmark records as the
|
||||
* libraries 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 is a ':'-separated search path, first home first, so a directory of one's own
|
||||
* plugins can precede an installation. Each home may hold kernels/, architectures/ and
|
||||
* quantizers/; a plugin earlier on the path shadows one with the same file name later. Non-plugin
|
||||
* files (the tuning cache, rad-kbench fixtures) are read from the first home that has them and
|
||||
* written to the first home. */
|
||||
std::vector<std::string> rad_home_dirs(const std::string& home);
|
||||
/* `<home>/<rel>` for the first home on the path that has it; the first home's when none does. */
|
||||
std::string rad_home_file(const std::string& home, const std::string& rel);
|
||||
|
||||
/* Loads into the process-lifetime registry (rad_tools_registry).
|
||||
*
|
||||
* `arch_id` and `quant` together are the selection key (spec §2.4, rad_builder.h): a family has
|
||||
* one plugin per weight format, all answering the same architecture id. `quant` is the container's
|
||||
* descriptor (RadModelMeta::quant, RadFileHeader::quant); "" is unquantised and matches only a
|
||||
* plugin that says "".
|
||||
*
|
||||
* `imported`: the checkpoint's quantisation is imported weight by weight (Checkpoint::imports), so
|
||||
* its descriptor names the producing tool and no plugin claims it. The family's quantised plugin
|
||||
* serves it: the one plugin claiming a descriptor, or the only plugin if none does. Two quantised
|
||||
* plugins are refused by name. `out->arch_quant` is the chosen descriptor, which a container
|
||||
* converted from it records. */
|
||||
int rad_tools_load_plugins(const std::string& radiance_home,
|
||||
const std::vector<std::string>& hierarchy,
|
||||
const std::string& arch_id,
|
||||
const std::string& quant,
|
||||
LoadedPlugins* out,
|
||||
bool imported = false);
|
||||
|
||||
/* The architecture plugin's rad_arch_probe answers, given before declare. */
|
||||
int rad_tools_probe(const LoadedPlugins& plugins, const RadModelMeta& meta, RadArchProbe* out);
|
||||
|
||||
/* The architecture plugin's declared reply format (rad_arch_chat_format), or null when it
|
||||
* declares none and the format is to be derived from the chat template. */
|
||||
const RadChatFormat* rad_tools_chat_format(const LoadedPlugins& plugins, const RadModelMeta& meta);
|
||||
|
||||
/* The architecture plugin's declared audio format (rad_arch_audio_format), or null when it
|
||||
* declares none -- a model the speech routes do not serve. A format whose struct_size is too
|
||||
* small to hold a field reads that field as null. */
|
||||
const RadAudioFormat* rad_tools_audio_format(const LoadedPlugins& plugins, const RadModelMeta& meta);
|
||||
|
||||
/* Run declare.
|
||||
*
|
||||
* `also` declares into the same builder after the architecture plugin, which is how the sampler
|
||||
* chain joins the Program: its ops resolve through the same hierarchy, so a missing sampler kernel
|
||||
* is in the same miss list rather than found at the first request (spec §3.1, §13). Empty for the
|
||||
* tools, which have no sampler.
|
||||
*
|
||||
* `ref` makes this a sizing declare (RadBuildCtx::shape_probe, Builder::set_reference): the plugin
|
||||
* declares against `ref`'s bands, nothing is selected or initialised, and the result is used only
|
||||
* for its buffers.
|
||||
*
|
||||
* `sources` answers rad_weight_encoding (Builder::set_sources): container entries, checkpoint
|
||||
* tensors, or a recipe. Empty: every weight is plain in its declared dtype.
|
||||
*
|
||||
* `instances` false selects every kernel and initialises none (Builder::set_instances), for
|
||||
* callers that launch nothing, such as rad-convert. */
|
||||
int rad_tools_declare(const LoadedPlugins& plugins, const RadModelMeta& meta,
|
||||
const RadBuildCtx& ctx, Program* out,
|
||||
const std::function<int(RadBuilder*, int64_t logits_width)>& also = {},
|
||||
const Program* ref = nullptr, const WeightSourceFn& sources = {},
|
||||
bool instances = true);
|
||||
|
||||
/* A container's entries as the source of every declaration's encoding. `f` must outlive the
|
||||
* declare. */
|
||||
WeightSourceFn rad_container_sources(const RadFile& f);
|
||||
|
||||
/* A checkpoint served directly as the source (spec §4.3). Each declared weight is resolved
|
||||
* through the name map once and kept for the loader, which reads the same tensors. Locked, since
|
||||
* every rank declares concurrently.
|
||||
*
|
||||
* Only trivial encodings are answered (bf16, f16, f32, block-scaled FP8) because nothing is
|
||||
* quantised at load. Anything else is recorded with its reason and answered RAD_E_UNSUPPORTED;
|
||||
* refused() lists them after declare, and the remedy is a container. */
|
||||
class CheckpointSources {
|
||||
public:
|
||||
explicit CheckpointSources(Checkpoint& ck) : ck_(ck) {}
|
||||
WeightSourceFn fn();
|
||||
/* After declare: what `name` resolved to, or null. */
|
||||
const CkptWeight* find(const std::string& name) const;
|
||||
/* Why `name` resolved to nothing, as the name map last answered it; empty if it did. */
|
||||
std::string missing(const std::string& name) const;
|
||||
/* Every weight that is not served as it stands, "name: why", sorted. */
|
||||
std::vector<std::string> refused() const;
|
||||
|
||||
private:
|
||||
int answer(const std::string& name, const Program& prog, WeightSource* out);
|
||||
Checkpoint& ck_;
|
||||
mutable std::mutex mu_;
|
||||
std::map<std::string, CkptWeight> got_;
|
||||
std::map<std::string, std::string> refused_;
|
||||
std::map<std::string, std::string> missing_;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ the reference-kernel gate */
|
||||
/* A reference library (RadPluginReferenceFn) is both the slow fallback for an unsupported model
|
||||
* and the oracle rad-kbench measures against (spec §17). As a silent fallback it runs orders of
|
||||
* magnitude below the machine with no visible sign, so resolving to one is fatal unless
|
||||
* --debug-accept-reference-kernels is passed. */
|
||||
|
||||
int rad_reference_ops(const Program& p, std::vector<std::string>* out);
|
||||
|
||||
/* Report and refuse, or report and continue when `allow`. `what` names the caller ("serve",
|
||||
* "the container's layout") so the message states the consequence. */
|
||||
int rad_gate_reference_kernels(const Program& p, bool allow, const char* what);
|
||||
|
||||
Registry& rad_tools_registry();
|
||||
|
||||
} /* namespace rad */
|
||||
+1027
File diff suppressed because it is too large.
Load diff
+3641
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,88 @@
|
||||
/* aql.h -- declarations shared by the AQL backend's translation units.
|
||||
*
|
||||
* aql_code.cpp reads code objects (offload bundle, ELF note, msgpack metadata), aql.cpp owns the
|
||||
* queues and all submission, and aql_blit.hip holds the backend's own copy and fill kernels.
|
||||
* aql_blit.hip is compiled as HIP, so this header must not pull in HSA.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
namespace aql {
|
||||
|
||||
/* ------------------------------------------------------------------ code objects */
|
||||
|
||||
/* One kernel argument as laid out in the code object's metadata. `hidden` names the implicit
|
||||
* arguments the compiler appends; explicit parameters map in order onto hipLaunchKernel's
|
||||
* `kernelParams`. */
|
||||
enum class Hidden : uint8_t {
|
||||
None, /* an explicit parameter */
|
||||
Pad, /* hidden_none: bytes the compiler reserved and reads nothing from */
|
||||
BlockCountX, BlockCountY, BlockCountZ,
|
||||
GroupSizeX, GroupSizeY, GroupSizeZ,
|
||||
RemainderX, RemainderY, RemainderZ,
|
||||
GlobalOffsetX, GlobalOffsetY, GlobalOffsetZ,
|
||||
GridDims,
|
||||
DynamicLds,
|
||||
Unsupported, /* anything else: a kernel that wants it is refused by name */
|
||||
};
|
||||
|
||||
struct KernelArg {
|
||||
uint32_t offset = 0;
|
||||
uint32_t size = 0;
|
||||
Hidden hidden = Hidden::None;
|
||||
std::string kind; /* the metadata's value_kind, for the refusal message */
|
||||
};
|
||||
|
||||
struct KernelMeta {
|
||||
std::string symbol; /* "<name>.kd" */
|
||||
uint32_t kernarg_size = 0;
|
||||
uint32_t group_size = 0; /* static LDS */
|
||||
uint32_t private_size = 0; /* static scratch */
|
||||
bool dynamic_stack = false;
|
||||
std::vector<KernelArg> args;
|
||||
};
|
||||
|
||||
/* Selects the card's code object from a clang offload bundle, or fails with `*why` naming what
|
||||
* the bundle holds and what the card accepts. `isas` lists the card's accepted targets in the
|
||||
* runtime's order of preference ("amdgcn-amd-amdhsa--gfx1036", then the family's
|
||||
* "amdgcn-amd-amdhsa--gfx10-3-generic"), each with its modes ("gfx942:sramecc+:xnack-"). The
|
||||
* bundle has no total length, so it is walked entry by entry. Compressed bundles are refused;
|
||||
* nothing in this tree builds one. */
|
||||
bool bundle_code_object(const void* bundle, const std::vector<std::string>& isas, const void** out,
|
||||
size_t* out_size, std::string* why);
|
||||
|
||||
/* Every kernel described in an AMDGPU code object's metadata note. */
|
||||
bool code_object_kernels(const void* elf, size_t size, std::vector<KernelMeta>* out,
|
||||
std::string* why);
|
||||
|
||||
/* ------------------------------------------------------------------ fence policy
|
||||
*
|
||||
* Extra fence scope for the next dispatch on this thread, beyond the agent scope every kernel
|
||||
* gets. Set by the backend around its own blits; cleared by the dispatch that consumes it. */
|
||||
enum : uint8_t { kFenceAcquireSystem = 1, kFenceReleaseSystem = 2 };
|
||||
void set_next_fence(uint8_t f);
|
||||
|
||||
} // namespace aql
|
||||
} // namespace rad
|
||||
|
||||
struct RadCopyRange;
|
||||
|
||||
/* Blit kernel launchers, defined in aql_blit.hip. Each issues one kernel onto `stream` through
|
||||
* hipLaunchKernel, which the backend intercepts. The caller guarantees alignment: the 16-byte
|
||||
* forms need both addresses and the length 16-byte aligned. */
|
||||
extern "C" {
|
||||
/* `link`: either side is pinned host memory, so use one narrow workgroup instead of a full grid
|
||||
* (see aql_blit.hip). */
|
||||
int rad_aql_blit_copy(void* dst, const void* src, uint64_t bytes, void* stream, bool link = false);
|
||||
int rad_aql_blit_copy2d(void* dst, uint64_t dpitch, const void* src, uint64_t spitch,
|
||||
uint64_t width, uint64_t height, void* stream);
|
||||
int rad_aql_blit_fill(void* dst, int value, uint64_t bytes, void* stream);
|
||||
/* rad_memcpy_ranges_async's kernel: `prefix` a multiple of 16, both bases 16-byte aligned. */
|
||||
int rad_aql_blit_ranges(void* dst, const void* src, uint64_t prefix, const RadCopyRange* ranges,
|
||||
int n, void* stream);
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
/* aql_blit.hip -- copy and fill kernels behind rad_memcpy_async, rad_memcpy_2d_async and
|
||||
* rad_memset_async on the AQL backend.
|
||||
*
|
||||
* A copy is a kernel on the stream's own queue, like HIP's blit path. The DMA engine would be a
|
||||
* second queue to order against with signals, and its latency exceeds a small copy's run time.
|
||||
* Every address is GPU-reachable (device, peer or pinned host memory); the caller stages
|
||||
* pageable host memory.
|
||||
*
|
||||
* The launchers go through hipLaunchKernel, which the backend intercepts, so these kernels are
|
||||
* dispatched like any kernel library's.
|
||||
*/
|
||||
#include <hip/hip_runtime.h>
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
#include "aql.h"
|
||||
#include "device.h"
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int kThreads = 256;
|
||||
constexpr uint64_t kMaxBlocks = 2048;
|
||||
|
||||
typedef unsigned u32x4 __attribute__((ext_vector_type(4)));
|
||||
|
||||
/* Four loads in flight per thread before the first store: a copy from pinned host memory is
|
||||
* link-latency bound, and one outstanding load per thread leaves most of the link idle. */
|
||||
__global__ __launch_bounds__(kThreads) void aql_copy16(const u32x4* __restrict__ src,
|
||||
u32x4* __restrict__ dst, uint64_t n) {
|
||||
const uint64_t stride = (uint64_t)gridDim.x * kThreads;
|
||||
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 across the link (pinned host memory) is one workgroup of four waves.
|
||||
*
|
||||
* The link delivers ~29 GB/s regardless of grid size, so the copy should hold as few waves as
|
||||
* possible: every wave it holds is denied to compute kernels for the copy's duration (a wide link
|
||||
* copy beside each layer slows a staged prefill by ~15%). Link bandwidth by grid, one card,
|
||||
* 89 MB from pinned host memory:
|
||||
*
|
||||
* 16 x 256 threads, 4 loads in flight 28.9 GB/s
|
||||
* 1 x 256 threads, 16 in flight 28.9
|
||||
* 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 per thread spill. Non-temporal loads and stores make no difference.
|
||||
*
|
||||
* The last round clamps its load indices instead of guarding them, so all its loads are in flight
|
||||
* at once; a guarded load waits for the one before it. */
|
||||
constexpr int kLinkThreads = 128, kLinkDepth = 16;
|
||||
constexpr uint64_t kLinkByteBlocks = 16;
|
||||
|
||||
__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];
|
||||
}
|
||||
}
|
||||
|
||||
/* Ranged copy: the first `prefix_blocks` workgroups copy the prefix as aql_copy16 does, and each
|
||||
* later workgroup copies one range. Ranges are only 4-byte aligned, so they move in words, 16 per
|
||||
* thread per round, with all loads issued before the first store (each is a read across the
|
||||
* link). Loads past the range end clamp to its last word instead of branching, since a guarded
|
||||
* load waits for the one before it. */
|
||||
constexpr int kRangeWords = 16;
|
||||
|
||||
__global__ __launch_bounds__(kThreads) void aql_copy_ranges(const u32x4* __restrict__ src16,
|
||||
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 have one byte per thread in flight, so across the link they
|
||||
* use 16 workgroups instead of the aligned path's one. */
|
||||
const uint64_t cap = link ? kLinkByteBlocks : kMaxBlocks;
|
||||
hipLaunchKernelGGL(aql_copy1, dim3(blocks_for(bytes, 4 * kThreads, cap)), dim3(kThreads),
|
||||
0, s, (const unsigned char*)src, (unsigned char*)dst, bytes);
|
||||
}
|
||||
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();
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
/* aql_code.cpp -- reads AMDGPU code objects: the offload bundle of a HIP fat binary, the ELF
|
||||
* inside it, and the msgpack metadata note that gives each kernel's argument layout.
|
||||
*
|
||||
* The AQL backend dispatches HIP-registered kernels itself, so it needs two things HIP does not
|
||||
* expose: the card's code object, to load into its own executable, and each kernel's argument
|
||||
* layout, to write kernarg segments. Both come from the embedded fat binary.
|
||||
*
|
||||
* Nothing here touches a device, so it builds and is tested without one.
|
||||
*/
|
||||
#include "aql.h"
|
||||
|
||||
#include <cstring>
|
||||
|
||||
namespace rad {
|
||||
namespace aql {
|
||||
|
||||
/* ------------------------------------------------------------------ the offload bundle */
|
||||
|
||||
namespace {
|
||||
|
||||
const char kHsaPrefix[] = "amdgcn-amd-amdhsa--";
|
||||
|
||||
/* A target ID as LLVM writes it after the triple: a processor and target features, each `name+`
|
||||
* or `name-` ("gfx942:sramecc+:xnack-"). A feature absent from a code object's ID means it runs in
|
||||
* either mode; absent from a card's ID, the card has no such mode. */
|
||||
struct TargetId {
|
||||
std::string proc;
|
||||
std::vector<std::pair<std::string, char>> feat;
|
||||
};
|
||||
|
||||
TargetId parse_target_id(const std::string& s) {
|
||||
TargetId t;
|
||||
size_t i = s.find(':');
|
||||
t.proc = s.substr(0, i);
|
||||
while (i != std::string::npos) {
|
||||
const size_t j = s.find(':', i + 1);
|
||||
const std::string f = s.substr(i + 1, j == std::string::npos ? std::string::npos : j - i - 1);
|
||||
if (f.size() > 1 && (f.back() == '+' || f.back() == '-'))
|
||||
t.feat.emplace_back(f.substr(0, f.size() - 1), f.back());
|
||||
i = j;
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
/* The target ID from an ISA name ("amdgcn-amd-amdhsa--gfx1036") or a bundle entry's triple
|
||||
* ("hipv4-amdgcn-amd-amdhsa--gfx1036"); empty for non-AMDGPU targets such as the host entry. */
|
||||
std::string target_id_of(const std::string& name) {
|
||||
const size_t at = name.find(kHsaPrefix);
|
||||
if (at == std::string::npos) return std::string();
|
||||
return name.substr(at + sizeof kHsaPrefix - 1);
|
||||
}
|
||||
|
||||
/* An ISA name's target ID, or the name itself when it carries no HSA prefix. */
|
||||
std::string isa_target(const std::string& isa) {
|
||||
const std::string id = target_id_of(isa);
|
||||
return id.empty() ? isa : id;
|
||||
}
|
||||
|
||||
/* -1 if a code object for `co` cannot run on a card accepting `card`; otherwise the number of
|
||||
* features the code object pins, so one built for the card's exact mode is preferred. */
|
||||
int target_fit(const TargetId& co, const TargetId& card) {
|
||||
if (co.proc != card.proc) return -1;
|
||||
for (const auto& f : co.feat) {
|
||||
bool ok = false;
|
||||
for (const auto& g : card.feat)
|
||||
if (g.first == f.first) { ok = g.second == f.second; break; }
|
||||
if (!ok) return -1;
|
||||
}
|
||||
return (int)co.feat.size();
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool bundle_code_object(const void* bundle, const std::vector<std::string>& isas, const void** out,
|
||||
size_t* out_size, std::string* why) {
|
||||
static const char kMagic[] = "__CLANG_OFFLOAD_BUNDLE__";
|
||||
const unsigned char* b = static_cast<const unsigned char*>(bundle);
|
||||
*out = nullptr;
|
||||
*out_size = 0;
|
||||
if (!b) { *why = "null bundle"; return false; }
|
||||
if (std::memcmp(b, "CCOB", 4) == 0) {
|
||||
*why = "the fat binary is a compressed offload bundle; build the kernel library without "
|
||||
"--offload-compress";
|
||||
return false;
|
||||
}
|
||||
if (std::memcmp(b, kMagic, sizeof kMagic - 1) != 0) {
|
||||
*why = "the fat binary does not start with a clang offload bundle header";
|
||||
return false;
|
||||
}
|
||||
uint64_t n = 0;
|
||||
std::memcpy(&n, b + 24, 8);
|
||||
if (n == 0 || n > 4096) { *why = "offload bundle with an implausible entry count"; return false; }
|
||||
|
||||
/* Device entries are "<kind>-amdgcn-amd-amdhsa--<target ID>"; both kinds, "hip" and "hipv4",
|
||||
* carry the same code object format for this purpose. */
|
||||
struct Entry { uint64_t off, size; TargetId id; std::string text; };
|
||||
std::vector<Entry> ents;
|
||||
const unsigned char* p = b + 32;
|
||||
for (uint64_t i = 0; i < n; ++i) {
|
||||
uint64_t off = 0, size = 0, tl = 0;
|
||||
std::memcpy(&off, p, 8);
|
||||
std::memcpy(&size, p + 8, 8);
|
||||
std::memcpy(&tl, p + 16, 8);
|
||||
if (tl > 4096) { *why = "offload bundle entry with an implausible triple"; return false; }
|
||||
const std::string triple(reinterpret_cast<const char*>(p + 24), (size_t)tl);
|
||||
p += 24 + tl;
|
||||
const std::string id = target_id_of(triple);
|
||||
if (size == 0 || id.empty()) continue;
|
||||
ents.push_back({ off, size, parse_target_id(id), id });
|
||||
}
|
||||
|
||||
/* Walk the card's ISA list in its own order: the exact processor first, then its family's
|
||||
* generic target. An exact-chip build wins where present; a family build runs on every
|
||||
* member. Within one target, a code object pinned to the card's mode wins. */
|
||||
for (const std::string& isa : isas) {
|
||||
const TargetId card = parse_target_id(isa_target(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() ? "" : ", ") + isa_target(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 code object metadata uses: maps, arrays, strings, integers, booleans and nil. Parsed
|
||||
* into a DOM: the metadata is looked up by key, is a few hundred KB at most, and is read once per
|
||||
* module at its first dispatch. */
|
||||
namespace {
|
||||
|
||||
struct MP {
|
||||
enum T : uint8_t { Nil, Bool, Int, Str, Arr, Map, Other } t = Nil;
|
||||
int64_t i = 0;
|
||||
const char* s = nullptr;
|
||||
uint32_t n = 0;
|
||||
std::vector<MP> a; /* array items, or map keys and values interleaved */
|
||||
|
||||
const MP* get(const char* key) const {
|
||||
if (t != Map) return nullptr;
|
||||
const size_t kl = std::strlen(key);
|
||||
for (size_t k = 0; k + 1 < a.size(); k += 2)
|
||||
if (a[k].t == Str && a[k].n == kl && std::memcmp(a[k].s, key, kl) == 0) return &a[k + 1];
|
||||
return nullptr;
|
||||
}
|
||||
std::string str() const { return t == Str ? std::string(s, n) : std::string(); }
|
||||
};
|
||||
|
||||
struct Reader {
|
||||
const unsigned char* p;
|
||||
const unsigned char* e;
|
||||
bool ok = true;
|
||||
|
||||
uint64_t be(int nb) {
|
||||
if (e - p < nb) { ok = false; return 0; }
|
||||
uint64_t v = 0;
|
||||
for (int k = 0; k < nb; ++k) v = (v << 8) | p[k];
|
||||
p += nb;
|
||||
return v;
|
||||
}
|
||||
void str(MP* m, uint32_t n) {
|
||||
if ((uint64_t)(e - p) < n) { ok = false; return; }
|
||||
m->t = MP::Str; m->s = reinterpret_cast<const char*>(p); m->n = n; p += n;
|
||||
}
|
||||
void items(MP* m, uint32_t n, int depth) {
|
||||
m->a.resize(n);
|
||||
for (uint32_t k = 0; k < n && ok; ++k) read(&m->a[k], depth + 1);
|
||||
}
|
||||
void read(MP* m, int depth) {
|
||||
if (!ok || p >= e || depth > 64) { ok = false; return; }
|
||||
const unsigned char c = *p++;
|
||||
if (c <= 0x7f) { m->t = MP::Int; m->i = c; return; }
|
||||
if (c >= 0xe0) { m->t = MP::Int; m->i = (int8_t)c; return; }
|
||||
if ((c & 0xf0) == 0x80) { m->t = MP::Map; items(m, 2u * (c & 0x0f), depth); return; }
|
||||
if ((c & 0xf0) == 0x90) { m->t = MP::Arr; items(m, c & 0x0f, depth); return; }
|
||||
if ((c & 0xe0) == 0xa0) { str(m, c & 0x1f); return; }
|
||||
switch (c) {
|
||||
case 0xc0: m->t = MP::Nil; return;
|
||||
case 0xc2: m->t = MP::Bool; m->i = 0; return;
|
||||
case 0xc3: m->t = MP::Bool; m->i = 1; return;
|
||||
case 0xcc: m->t = MP::Int; m->i = (int64_t)be(1); return;
|
||||
case 0xcd: m->t = MP::Int; m->i = (int64_t)be(2); return;
|
||||
case 0xce: m->t = MP::Int; m->i = (int64_t)be(4); return;
|
||||
case 0xcf: m->t = MP::Int; m->i = (int64_t)be(8); return;
|
||||
case 0xd0: m->t = MP::Int; m->i = (int8_t)be(1); return;
|
||||
case 0xd1: m->t = MP::Int; m->i = (int16_t)be(2); return;
|
||||
case 0xd2: m->t = MP::Int; m->i = (int32_t)be(4); return;
|
||||
case 0xd3: m->t = MP::Int; m->i = (int64_t)be(8); return;
|
||||
case 0xca: m->t = MP::Other; be(4); return;
|
||||
case 0xcb: m->t = MP::Other; be(8); return;
|
||||
case 0xd9: str(m, (uint32_t)be(1)); return;
|
||||
case 0xda: str(m, (uint32_t)be(2)); return;
|
||||
case 0xdb: str(m, (uint32_t)be(4)); return;
|
||||
case 0xc4: case 0xc5: case 0xc6: {
|
||||
const uint32_t n = (uint32_t)be(c == 0xc4 ? 1 : c == 0xc5 ? 2 : 4);
|
||||
str(m, n); m->t = MP::Other; return;
|
||||
}
|
||||
case 0xdc: m->t = MP::Arr; items(m, (uint32_t)be(2), depth); return;
|
||||
case 0xdd: m->t = MP::Arr; items(m, (uint32_t)be(4), depth); return;
|
||||
case 0xde: m->t = MP::Map; items(m, 2u * (uint32_t)be(2), depth); return;
|
||||
case 0xdf: m->t = MP::Map; items(m, 2u * (uint32_t)be(4), depth); return;
|
||||
default: ok = false; return; /* ext types: never in code object metadata */
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Hidden hidden_kind(const std::string& k) {
|
||||
if (k.compare(0, 7, "hidden_") != 0) return Hidden::None;
|
||||
static const struct { const char* n; Hidden h; } kTab[] = {
|
||||
{ "hidden_none", Hidden::Pad },
|
||||
{ "hidden_block_count_x", Hidden::BlockCountX },
|
||||
{ "hidden_block_count_y", Hidden::BlockCountY },
|
||||
{ "hidden_block_count_z", Hidden::BlockCountZ },
|
||||
{ "hidden_group_size_x", Hidden::GroupSizeX },
|
||||
{ "hidden_group_size_y", Hidden::GroupSizeY },
|
||||
{ "hidden_group_size_z", Hidden::GroupSizeZ },
|
||||
{ "hidden_remainder_x", Hidden::RemainderX },
|
||||
{ "hidden_remainder_y", Hidden::RemainderY },
|
||||
{ "hidden_remainder_z", Hidden::RemainderZ },
|
||||
{ "hidden_global_offset_x", Hidden::GlobalOffsetX },
|
||||
{ "hidden_global_offset_y", Hidden::GlobalOffsetY },
|
||||
{ "hidden_global_offset_z", Hidden::GlobalOffsetZ },
|
||||
{ "hidden_grid_dims", Hidden::GridDims },
|
||||
{ "hidden_dynamic_lds_size", Hidden::DynamicLds },
|
||||
};
|
||||
for (const auto& t : kTab) if (k == t.n) return t.h;
|
||||
return Hidden::Unsupported;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
/* ------------------------------------------------------------------ the metadata note */
|
||||
|
||||
bool code_object_kernels(const void* elf, size_t size, std::vector<KernelMeta>* out,
|
||||
std::string* why) {
|
||||
out->clear();
|
||||
const unsigned char* b = static_cast<const unsigned char*>(elf);
|
||||
if (size < 64 || std::memcmp(b, "\x7f" "ELF", 4) != 0 || b[4] != 2 /* ELFCLASS64 */) {
|
||||
*why = "not a 64-bit ELF code object";
|
||||
return false;
|
||||
}
|
||||
uint64_t phoff = 0;
|
||||
uint16_t phentsize = 0, phnum = 0;
|
||||
std::memcpy(&phoff, b + 32, 8);
|
||||
std::memcpy(&phentsize, b + 54, 2);
|
||||
std::memcpy(&phnum, b + 56, 2);
|
||||
if (phentsize < 56 || phoff + (uint64_t)phentsize * phnum > size) {
|
||||
*why = "code object program headers run past its end";
|
||||
return false;
|
||||
}
|
||||
for (uint16_t h = 0; h < phnum; ++h) {
|
||||
const unsigned char* ph = b + phoff + (uint64_t)h * phentsize;
|
||||
uint32_t type = 0;
|
||||
uint64_t off = 0, fsz = 0;
|
||||
std::memcpy(&type, ph, 4);
|
||||
std::memcpy(&off, ph + 8, 8);
|
||||
std::memcpy(&fsz, ph + 32, 8);
|
||||
if (type != 4 /* PT_NOTE */ || off + fsz > size) continue;
|
||||
const unsigned char* q = b + off;
|
||||
const unsigned char* qe = q + fsz;
|
||||
while (qe - q >= 12) {
|
||||
uint32_t namesz = 0, descsz = 0, ntype = 0;
|
||||
std::memcpy(&namesz, q, 4);
|
||||
std::memcpy(&descsz, q + 4, 4);
|
||||
std::memcpy(&ntype, q + 8, 4);
|
||||
const unsigned char* name = q + 12;
|
||||
const unsigned char* desc = name + ((namesz + 3u) & ~3u);
|
||||
const unsigned char* next = desc + ((descsz + 3u) & ~3u);
|
||||
if (next > qe) break;
|
||||
q = next;
|
||||
if (ntype != 32 /* NT_AMDGPU_METADATA */ || namesz != 7 ||
|
||||
std::memcmp(name, "AMDGPU", 6) != 0)
|
||||
continue;
|
||||
|
||||
Reader r{ desc, desc + descsz };
|
||||
MP root;
|
||||
r.read(&root, 0);
|
||||
if (!r.ok || root.t != MP::Map) { *why = "malformed AMDGPU metadata"; return false; }
|
||||
const MP* ks = root.get("amdhsa.kernels");
|
||||
if (!ks || ks->t != MP::Arr) { *why = "metadata has no amdhsa.kernels"; return false; }
|
||||
for (const MP& k : ks->a) {
|
||||
KernelMeta m;
|
||||
const MP* sym = k.get(".symbol");
|
||||
if (!sym) continue;
|
||||
m.symbol = sym->str();
|
||||
if (const MP* v = k.get(".kernarg_segment_size")) m.kernarg_size = (uint32_t)v->i;
|
||||
if (const MP* v = k.get(".group_segment_fixed_size")) m.group_size = (uint32_t)v->i;
|
||||
if (const MP* v = k.get(".private_segment_fixed_size")) m.private_size = (uint32_t)v->i;
|
||||
if (const MP* v = k.get(".uses_dynamic_stack")) m.dynamic_stack = v->i != 0;
|
||||
if (const MP* as = k.get(".args"); as && as->t == MP::Arr) {
|
||||
for (const MP& a : as->a) {
|
||||
KernelArg ka;
|
||||
if (const MP* v = a.get(".offset")) ka.offset = (uint32_t)v->i;
|
||||
if (const MP* v = a.get(".size")) ka.size = (uint32_t)v->i;
|
||||
if (const MP* v = a.get(".value_kind")) ka.kind = v->str();
|
||||
ka.hidden = hidden_kind(ka.kind);
|
||||
m.args.push_back(std::move(ka));
|
||||
}
|
||||
}
|
||||
out->push_back(std::move(m));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
*why = "code object has no AMDGPU metadata note";
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace aql
|
||||
} // namespace rad
|
||||
@@ -0,0 +1,480 @@
|
||||
/* device.h -- the device layer's internal interface.
|
||||
*
|
||||
* `abi/rad_device.h` is what the engine and plugins call. This header is the seam between its
|
||||
* backend implementations, plus queries for which backend is active.
|
||||
*
|
||||
* The seam is a vtable, not an `#ifdef` per call site. The indirect call is unmeasurable next to
|
||||
* any copy worth enqueuing, and in exchange each `rad_dev_*` symbol has one definition, so the
|
||||
* backends cannot drift into different contracts. That matters because the host backend is where
|
||||
* everything above the kernels is developed (docs/IMPLEMENTATION.md).
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_abi.h"
|
||||
#include "rad_device.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
/* An event that orders work on one card only. Its record makes the stream's writes visible to
|
||||
* that card and nothing else: another stream of the same card may wait on it and the host may
|
||||
* query or sync it for timing, but the host must not read device-written memory on its strength
|
||||
* and no other card may wait on it. The gain is the cheaper release: a system-scope release waits
|
||||
* for every in-flight write to host memory, ~1-10 us per record while the link streams weights. */
|
||||
extern "C" int rad_event_create_local(RadEvent* out);
|
||||
/* Event purpose, fixed at creation. RAD_EVENT_LOCAL is rad_event_create_local's scope.
|
||||
* RAD_EVENT_HOST_WAIT records complete with an interrupt a host thread can block on; without it
|
||||
* records complete silently and only a stream can wait on them. rad_event_create is
|
||||
* RAD_EVENT_HOST_WAIT, rad_event_create_local is RAD_EVENT_LOCAL alone, and rad_event_sync refuses
|
||||
* an event made without RAD_EVENT_HOST_WAIT. */
|
||||
enum : unsigned {
|
||||
RAD_EVENT_LOCAL = 1u,
|
||||
RAD_EVENT_HOST_WAIT = 2u,
|
||||
};
|
||||
extern "C" int rad_event_create_as(RadEvent* out, unsigned flags);
|
||||
/* The host has just written memory that a kernel issued after this call reads, with no host wait
|
||||
* in between (e.g. a host-site op's output read over the link by the next device op). */
|
||||
extern "C" void rad_dev_host_wrote(void);
|
||||
|
||||
/* One range of a ranged copy: `bytes` from source offset `src` to destination offset `dst`, all
|
||||
* three multiples of four. */
|
||||
struct RadCopyRange {
|
||||
int64_t src;
|
||||
int64_t dst;
|
||||
int64_t bytes;
|
||||
};
|
||||
/* Copies src[0, prefix) to dst[0, prefix) (a multiple of 16, possibly zero), then every range,
|
||||
* in one dispatch. The kernel reads `ranges` when it runs, so the list must be device-reachable
|
||||
* (pinned host memory beside `src`) and stay unchanged until the stream passes the copy. One
|
||||
* workgroup copies one range, so callers cut long runs into ranges of a few KB. */
|
||||
extern "C" int rad_memcpy_ranges_async(void* dst, const void* src, int64_t prefix,
|
||||
const RadCopyRange* ranges, int n, RadStream s);
|
||||
|
||||
/* One copy of a list: `bytes` from `src` to `dst`, both absolute addresses. */
|
||||
struct RadCopySeg {
|
||||
const void* src;
|
||||
void* dst;
|
||||
int64_t bytes;
|
||||
};
|
||||
/* Many unrelated copies, in list order on the stream, on the card's DMA engine where the backend
|
||||
* has one (otherwise segment by segment). The list itself is read at the call; the bytes it names
|
||||
* must live until the copy runs. An empty list enqueues nothing but performs the card's first-list
|
||||
* setup, so a caller can pay that cost at bring-up.
|
||||
*
|
||||
* For bulk link copies while the card computes (e.g. a layer's pooled experts in the prefill
|
||||
* stager). A copy kernel holds a CU slot for the link's duration and waits for a free one at
|
||||
* launch: beside busy kernels, 1.3 MB pinned-host copies run at 2.3 GB/s as kernels versus
|
||||
* 28.7 GB/s (link rate) on the DMA engine, at no cost to the kernels (aql.cpp, "the DMA lane").
|
||||
*
|
||||
* RAD_COPY_YIELD makes the list yield to the card's collectives: between ~1 MB pieces it waits
|
||||
* while a stream of that card holds the link (rad_link_hold). */
|
||||
#define RAD_COPY_YIELD 1u
|
||||
extern "C" int rad_memcpy_list_async(const RadCopySeg* segs, int n, unsigned flags, RadStream s);
|
||||
|
||||
/* Holds the card's link for the work `s` issues between two calls. `on` = 1 where step-critical
|
||||
* link traffic (a collective) starts, 0 where it ends, or 2 where the work in between released the
|
||||
* hold itself (rad_link_gate). RAD_COPY_YIELD lists for that card pause between pieces while held.
|
||||
* A card's holds alternate on/off in issue order across all its streams; they never nest or
|
||||
* overlap. Between the two calls the holding stream must not wait on anything behind a yielding
|
||||
* list, or the list and the hold deadlock. A backend without a DMA engine holds nothing.
|
||||
*
|
||||
* Why: collective peer bytes and stager copies share the inbound link, and the DMA engine takes
|
||||
* its share at full rate. A 4 MB all-reduce message takes 165 us alone and 301 us beside a layer's
|
||||
* copies; the step waits on the collective, while the copies have the rest of the layer. */
|
||||
extern "C" int rad_link_hold(RadStream s, int on);
|
||||
|
||||
/* The hold word, for a launch that ends its own hold: a 64-bit word reachable by every engine and
|
||||
* kernel of the card, odd while the link is held. A launch handed this address releases the hold
|
||||
* by decrementing the word once, only if odd, as soon as its awaited bytes have landed; follow it
|
||||
* with rad_link_hold(s, 2). Null where the backend holds nothing. */
|
||||
extern "C" void* rad_link_gate(RadStream s);
|
||||
|
||||
/* Device half of the expert prefetch (core/runtime/xprefetch.cpp). A backend that cannot have a
|
||||
* dispatch complete a signal, or has no spare DMA engine, leaves these out; rad_xp_supported is
|
||||
* then 0 and the prefetch is off.
|
||||
*
|
||||
* A ride is a signal completed by the next dispatch on a stream, instead of a separate barrier
|
||||
* packet. That dispatch keeps its ordering bit, so the signal covers everything before it.
|
||||
* rad_ride_wait puts a barrier waiting on it onto another stream and recycles the signal behind
|
||||
* that barrier. A ride polled by the DMA engine is returned with rad_ride_release once nothing can
|
||||
* poll it: immediately (`after` null) when the polling list has finished, else once `after` is
|
||||
* `packets` dispatches further on.
|
||||
*
|
||||
* rad_xp_list gives the card's prefetch DMA queue a list: wait for `mark` (a ride, or null), copy
|
||||
* the `n` ranges, then write `done_val` to `done` (pinned host memory, or null). rad_xp_behind
|
||||
* counts lists handed over and not yet finished. The prefetch ring is uncached device memory
|
||||
* (rad_dev_alloc_uncached): the engine writes it and kernels read it, so no cache may hold a
|
||||
* slot's previous contents. */
|
||||
extern "C" int rad_xp_supported(int device);
|
||||
extern "C" int rad_xp_stream_create(RadStream* out);
|
||||
extern "C" int rad_ride(RadStream s, void** token);
|
||||
extern "C" int rad_ride_wait(RadStream s, void* token);
|
||||
extern "C" void rad_ride_release(void* token, RadStream after, int64_t packets);
|
||||
extern "C" int rad_xp_list(int device, void* mark, int n, const uint64_t* src, const uint64_t* dst,
|
||||
const uint64_t* bytes, uint32_t* done, uint32_t done_val);
|
||||
extern "C" int64_t rad_xp_behind(int device);
|
||||
extern "C" void* rad_dev_alloc_uncached(int64_t bytes);
|
||||
extern "C" void rad_dev_free_uncached(void* p);
|
||||
|
||||
/* A gate on a stream: the stream stops at the point rad_stream_gate enqueues and goes on once the
|
||||
* host calls rad_gate_open. Everything enqueued behind the gate meanwhile is then ready at once, so
|
||||
* the device runs it back to back however long the host took to submit it. For timing a batch of
|
||||
* launches without the host's submission rate in the measurement (tools/kbench_timer.cpp); the
|
||||
* engine has no use for it.
|
||||
*
|
||||
* Behind a closed gate the queue only fills. A caller enqueues at most rad_gate_room(s) more
|
||||
* submissions, counting each launch's own (a kernel may issue several), and must not wait on the
|
||||
* stream before opening the gate. The backends refuse with RAD_E_STATE, rather than deadlock, a
|
||||
* submission that would wait for room and a rad_stream_sync on a gated stream; an event sync on a
|
||||
* record behind the gate is not caught. Open every gate before destroying its stream.
|
||||
*
|
||||
* The gate itself acquires at system scope, so nothing behind it takes the acquire a first
|
||||
* dispatch after a host wait otherwise takes. rad_gate_room counts the submissions that fit
|
||||
* before the queue is full or before a dispatch would take the periodic system-scope acquire
|
||||
* (an L2 invalidate, see aql.cpp "fences"); on a stream without a closed gate it is the same
|
||||
* count with the device still draining. `gate` is single-use: opening it frees it. Not inside a
|
||||
* tape capture. RAD_E_UNSUPPORTED (and a room of 0) on a backend without gates. */
|
||||
extern "C" int rad_stream_gate(RadStream s, void** gate);
|
||||
extern "C" int rad_gate_open(void* gate);
|
||||
extern "C" int64_t rad_gate_room(RadStream s);
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* A recorded pass, owned by the backend that recorded it. See DeviceBackend::tape_begin. */
|
||||
typedef void* RadTape;
|
||||
|
||||
/* ------------------------------------------------------------------ active backend */
|
||||
/* Decided once at first use and cached. Used by the planner (a host backend has only a budget,
|
||||
* no VRAM tier), the selector (only RAD_DOMAIN_HOST can run) and tests that skip device-only
|
||||
* assertions. */
|
||||
bool device_is_host();
|
||||
const char* device_backend_name(); /* "host" or "aql" */
|
||||
|
||||
/* ------------------------------------------------------------------ two contract notes
|
||||
*
|
||||
* Properties of rad_device.h that the frozen header does not state; tests/device_test.cpp pins
|
||||
* them against a real card.
|
||||
*
|
||||
* 1. `rad_memset_async` requires a device-accessible destination: RAD_MEM_DEVICE,
|
||||
* RAD_MEM_HOST_PINNED or RAD_MEM_HOST_MAPPED. hipMemsetAsync refuses pageable RAD_MEM_HOST.
|
||||
* The host backend cannot reproduce that refusal, so this is the one asymmetry between the
|
||||
* two (see d_memset_async in hip.cpp). `rad_memcpy_async` has no such restriction.
|
||||
*
|
||||
* 2. Both backends refuse a null RadStream. HIP's stream 0 serialises against every blocking
|
||||
* stream, contrary to spec §5.4 (no host synchronisation in a transfer). The engine never uses
|
||||
* the default stream, so null is a bug.
|
||||
*/
|
||||
|
||||
/* ------------------------------------------------------------------ the backend vtable */
|
||||
/* 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 wrote memory that kernels issued from here on read, with no host wait in between:
|
||||
* do whatever a wait would have done to make host writes visible to the device. */
|
||||
void (*host_wrote)(void);
|
||||
|
||||
int (*memcpy_async)(void* dst, const void* src, int64_t bytes, RadStream s);
|
||||
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);
|
||||
int (*memcpy_list_async)(const RadCopySeg* segs, int n, unsigned flags, RadStream s);
|
||||
int (*link_hold)(RadStream s, int on);
|
||||
void* (*link_gate)(RadStream s);
|
||||
|
||||
/* ---- recorded passes. Null on a backend without them; the run phase then issues every
|
||||
* pass. See Ctx::run_step for what a tape is for.
|
||||
*
|
||||
* `tape_begin` captures every submission this thread makes (dispatches, event records and
|
||||
* waits) outside `tape_pause` (which nests). `tape_mark` returns the record count, so the
|
||||
* caller can cut the tape at its own host work. `tape_end` returns the tape, or null when
|
||||
* `keep` is 0 or the pass did something a tape cannot reproduce (reason in
|
||||
* rad_dev_last_error). `tape_play` resubmits records [from, to) onto their recorded queues.
|
||||
* `tape_destroy` may be called while a play is queued; the tape is freed once unreachable. */
|
||||
int (*tape_begin)(void);
|
||||
int (*tape_mark)(void);
|
||||
void (*tape_pause)(int on);
|
||||
RadTape (*tape_end)(int keep);
|
||||
int (*tape_len)(RadTape t);
|
||||
int (*tape_play)(RadTape t, int from, int to);
|
||||
/* First record at which two tapes differ, or -1 if they agree (same submissions to the same
|
||||
* queues, same packets apart from argument addresses, same argument bytes). The difference is
|
||||
* described into `why`. */
|
||||
int (*tape_diff)(RadTape a, RadTape b, char* why, int cap);
|
||||
void (*tape_destroy)(RadTape t);
|
||||
/* `tape_record`: record `i`'s kind (0 dispatch, 1 event record or wait) and queue.
|
||||
* `tape_set_overlap`, the one edit a closed tape accepts: play dispatch `i` without the barrier
|
||||
* bit, so it launches while earlier packets on its queue still run. The caller sets it only
|
||||
* where the dispatch touches nothing those packets write, and on at most kTapeOverlapRun
|
||||
* consecutive dispatches; see Ctx::haz_mark. */
|
||||
int (*tape_record)(RadTape t, int i, int* kind, uint32_t* queue);
|
||||
int (*tape_set_overlap)(RadTape t, int i, int on);
|
||||
|
||||
|
||||
/* ---- elastic memory: an address range of fixed size whose backing comes and goes.
|
||||
*
|
||||
* Lets two pools that take turns share memory: the KV cache backs only what live sessions
|
||||
* hold, and the expert plane keeps the rest resident instead of streaming it over the link.
|
||||
*
|
||||
* Free-then-reallocate does not work: the KV pool is layer-major (core/mem/kv.h), layer i at
|
||||
* `base + i * n_blocks * layer_bytes_per_block`, so unused blocks are a stripe inside each
|
||||
* layer, not a tail. Reserving the maximum range and backing part of it keeps every stride
|
||||
* where the kernels expect it.
|
||||
*
|
||||
* A backend without elastic memory leaves these null and pools are sized once at startup;
|
||||
* that is a supported configuration.
|
||||
*
|
||||
* Contract:
|
||||
* `vmem_reserve` takes address space, no pages.
|
||||
* `vmem_commit` backs one granule and `vmem_decommit` unbacks one. The driver unmaps a
|
||||
* mapping only exactly as it was mapped (four granules mapped in one call cannot be unmapped
|
||||
* singly), so VMem issues one call per granule.
|
||||
* `vmem_protect` grants this device read/write access to an already-backed range. It is
|
||||
* separate from commit because access set on a granule adjacent to an accessible one is
|
||||
* refused, while the whole contiguous run is accepted; VMem names the run.
|
||||
* `vmem_release` takes a range with nothing committed in it.
|
||||
*
|
||||
* Overlap bookkeeping lives once in VMem below, not in each backend. */
|
||||
int64_t (*vmem_granularity)(void); /* commit quantum; 0 = unsupported */
|
||||
void* (*vmem_reserve)(int64_t bytes, int64_t align);
|
||||
void (*vmem_release)(void* base, int64_t bytes);
|
||||
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. VRAM in use on a card by all processes, as the driver counts it, read
|
||||
* without entering the device runtime (a dashboard polls it, and a runtime call can block on
|
||||
* a lock the launch path holds). Available once props() has been read for the device;
|
||||
* otherwise, or without such a counter, RAD_E_UNSUPPORTED. */
|
||||
int (*vram_used)(int device, int64_t* out);
|
||||
|
||||
/* ---- plugin device code. `code_mark` counts fat-binary registrations so far; `code_runs`
|
||||
* reports whether every registration in [from, to) has a code object `device` runs (1), not
|
||||
* (0, reason in `why`), or unknown (< 0). The plugin loader brackets each dlopen with marks.
|
||||
* Null on a backend that loads no device code. */
|
||||
size_t (*code_mark)(void);
|
||||
int (*code_runs)(size_t from, size_t to, int device, char* why, int cap);
|
||||
|
||||
/* ---- 1 when the device is integrated graphics: its "device memory" is host memory shared
|
||||
* with every process. Null (answers 0) on a backend with no such devices. */
|
||||
int (*integrated)(int device);
|
||||
|
||||
/* ---- 1 when `self` can access `peer`'s memory directly, 0 when not, < 0 when unknown. A
|
||||
* query only; rad_dev_enable_peer maps the memory. Null (answers 1) on a backend whose devices
|
||||
* share one address space. */
|
||||
int (*peer_access)(int self, int peer);
|
||||
|
||||
/* ---- the card's PCI address, "0000:03:00.0", into `out`; RAD_E_UNSUPPORTED for non-PCI
|
||||
* devices. The startup report (core/diag/diag.h) uses it to join the runtime's device index to
|
||||
* the kernel's view of the card (link, power limits, IOMMU group). */
|
||||
int (*pci_address)(int device, char* out, int cap);
|
||||
/* ---- the device runtime's name and version, "HIP 7.2.25403", into `out`. Null on a backend
|
||||
* with no runtime. */
|
||||
int (*runtime_version)(char* out, int cap);
|
||||
/* ---- what carries rad_memcpy_list_async for `device`, into `out`: the card's DMA engine on
|
||||
* the process's own queue, or why not. Null on a backend that copies segment by segment. */
|
||||
int (*dma_lane)(int device, char* out, int cap);
|
||||
|
||||
/* ---- expert prefetch device half: see rad_xp_supported. Last in the table, so a backend
|
||||
* listing its entries positionally leaves them null. */
|
||||
int (*xp_supported)(int device);
|
||||
int (*xp_stream_create)(RadStream* out);
|
||||
int (*ride)(RadStream s, void** token);
|
||||
int (*ride_wait)(RadStream s, void* token);
|
||||
void (*ride_release)(void* token, RadStream after, int64_t packets);
|
||||
int (*xp_list)(int device, void* mark, int n, const uint64_t* src, const uint64_t* dst,
|
||||
const uint64_t* bytes, uint32_t* done, uint32_t done_val);
|
||||
int64_t (*xp_behind)(int device);
|
||||
void* (*alloc_uncached)(int64_t bytes);
|
||||
void (*free_uncached)(void* p);
|
||||
|
||||
/* ---- gates: see rad_stream_gate. Null on a backend without them. */
|
||||
int (*stream_gate)(RadStream s, void** gate);
|
||||
int (*gate_open)(void* gate);
|
||||
int64_t (*gate_room)(RadStream s);
|
||||
};
|
||||
|
||||
|
||||
const DeviceBackend* host_backend(void);
|
||||
|
||||
/* The current backend's recorded passes; RAD_E_UNSUPPORTED (or null) from one that has none. */
|
||||
bool tape_supported();
|
||||
int tape_begin();
|
||||
int tape_mark();
|
||||
void tape_pause(bool on);
|
||||
RadTape tape_end(bool keep);
|
||||
int tape_len(RadTape t);
|
||||
int tape_play(RadTape t, int from, int to);
|
||||
int tape_diff(RadTape a, RadTape b, std::string* why);
|
||||
void tape_destroy(RadTape t);
|
||||
int tape_record(RadTape t, int i, int* kind, uint32_t* queue);
|
||||
int tape_set_overlap(RadTape t, int i, bool on);
|
||||
|
||||
/* The current backend's DeviceBackend::peer_access. */
|
||||
int dev_peer_access(int self, int peer);
|
||||
|
||||
/* The current backend's DeviceBackend::vram_used. */
|
||||
int dev_vram_used(int device, int64_t* out);
|
||||
|
||||
/* The current backend's DeviceBackend::code_mark and code_runs. Without them the mark is 0 and
|
||||
* every plugin runs (1). */
|
||||
size_t dev_code_mark();
|
||||
int dev_code_runs(size_t from, size_t to, int device, std::string* why);
|
||||
|
||||
/* The current backend's DeviceBackend::integrated. */
|
||||
bool dev_integrated(int device);
|
||||
|
||||
/* The current backend's DeviceBackend::pci_address and runtime_version, "" where it has none. */
|
||||
std::string dev_pci_address(int device);
|
||||
std::string dev_runtime_version();
|
||||
/* The current backend's DeviceBackend::dma_lane, "" where it has none. */
|
||||
std::string dev_dma_lane(int device);
|
||||
|
||||
/* Longest run of dispatches a played tape leaves unordered. Of any kTapeOverlapRun + 1
|
||||
* consecutive packets on a queue one carries the barrier bit, so a launched packet still proves
|
||||
* that everything more than that many packets earlier has completed. Argument slots and tape
|
||||
* lifetimes are reclaimed on that guarantee. */
|
||||
constexpr int kTapeOverlapRun = 6;
|
||||
|
||||
/* ------------------------------------------------------------------ the allocation ledger
|
||||
* What rad_dev_alloc has handed out since process start, by RAD_MEM_* kind. It does not see a
|
||||
* kernel plugin that calls hipMalloc directly; see the ledger in dispatch.cpp. */
|
||||
void rad_dev_alloc_totals(int kind, int64_t* bytes, int64_t* count);
|
||||
|
||||
/* Event handles created and not yet destroyed, process-wide. */
|
||||
int64_t rad_dev_live_events(void);
|
||||
/* Calls to rad_event_sync and rad_stream_sync since process start, from any thread: the host
|
||||
* blocks the ABI makes. */
|
||||
int64_t rad_dev_host_blocks(void);
|
||||
|
||||
/* ------------------------------------------------------------------ elastic memory
|
||||
* One reserved address range and which granules inside it are backed.
|
||||
*
|
||||
* The interval bookkeeping lives here, not in the backends, because the driver refuses a commit
|
||||
* overlapping a commit and a decommit covering a hole. Backends get granule-aligned, disjoint
|
||||
* ranges and make no decisions.
|
||||
*
|
||||
* The roundings differ on purpose: commit rounds outward, so every requested byte is backed;
|
||||
* decommit rounds inward, so a granule holding any byte still in use is kept. A shared rounding
|
||||
* would either strand memory or unmap live data (a kernel fault at a valid address).
|
||||
*
|
||||
* Not thread-safe. A range is owned by the owner of the pool it backs, and commit/decommit is
|
||||
* policy, not step-path work. */
|
||||
class VMem {
|
||||
public:
|
||||
/* Whether the backend has elastic memory. Without it callers size pools whole (a supported
|
||||
* configuration; see DeviceBackend). */
|
||||
static bool supported();
|
||||
static int64_t granularity(); /* 0 when unsupported */
|
||||
|
||||
VMem() = default;
|
||||
~VMem() { release(); }
|
||||
VMem(const VMem&) = delete;
|
||||
VMem& operator=(const VMem&) = delete;
|
||||
/* Movable, since owners live in vectors. The source is left empty so its destructor does not
|
||||
* unmap the range the destination now owns. */
|
||||
VMem(VMem&& o) noexcept
|
||||
: base_(o.base_), size_(o.size_), committed_(o.committed_), ext_(std::move(o.ext_)) {
|
||||
o.base_ = nullptr;
|
||||
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. `align` defaults to the granularity. Reserve the
|
||||
* maximum the pool may ever reach; the range cannot grow later without moving addresses. */
|
||||
int reserve(int64_t bytes, int64_t align = 0);
|
||||
void release(); /* decommits whatever is still backed, then frees the VA */
|
||||
|
||||
void* base() const { return base_; }
|
||||
int64_t size() const { return size_; }
|
||||
int64_t committed() const { return committed_; } /* bytes actually backed right now */
|
||||
|
||||
/* Idempotent and clamped to the range. commit() backs every unbacked granule touching
|
||||
* [off, off+bytes); decommit() unbacks every backed granule wholly inside it. Doing nothing is
|
||||
* success. */
|
||||
int commit(int64_t off, int64_t bytes);
|
||||
int decommit(int64_t off, int64_t bytes);
|
||||
|
||||
/* Whether every byte of [off, off+bytes) is backed; check before handing a range to a
|
||||
* kernel. */
|
||||
bool is_committed(int64_t off, int64_t bytes) const;
|
||||
|
||||
private:
|
||||
void* base_ = nullptr;
|
||||
int64_t size_ = 0;
|
||||
int64_t committed_ = 0;
|
||||
/* Backed extents (offset, bytes): sorted, disjoint and never adjacent, since a touching
|
||||
* commit merges. Length tracks live regions, not calls. */
|
||||
std::vector<std::pair<int64_t, int64_t>> ext_;
|
||||
|
||||
/* Adds a newly mapped piece and merges it with whatever it touches. */
|
||||
void add_extent(int64_t off, int64_t bytes);
|
||||
void drop_extent(int64_t off, int64_t bytes);
|
||||
};
|
||||
|
||||
/* Bytes backed by every VMem in the process, for Engine::start's receipt. VMem commits bypass the
|
||||
* rad_dev_alloc ledger, so without this the engine's accounting would miss the elastic pools. */
|
||||
int64_t rad_dev_vmem_committed(void);
|
||||
|
||||
#if defined(RAD_HAVE_HIP) && RAD_HAVE_HIP
|
||||
/* Null when the build has HIP but the machine shows no device, so a machine with ROCm installed
|
||||
* but no card runs the host backend instead of failing at the first hipMalloc. Configure decides
|
||||
* which kernels are compiled; this decides whether there is a card to run them. */
|
||||
const DeviceBackend* hip_backend_if_present(void);
|
||||
/* The HIP backend with streams, events, copies and fills replaced by AQL packets the engine writes
|
||||
* itself (aql.cpp). Aborts with the reason on a machine it cannot run on. */
|
||||
const DeviceBackend* aql_backend_if_present(void);
|
||||
/* Bytes copied to or from pageable host memory so far; each such copy is a host wait. */
|
||||
int64_t aql_pageable_bytes(void);
|
||||
/* Fat binaries registered so far, counted whichever backend runs: the registration hooks are this
|
||||
* build's exported symbols and see every dlopen'ed plugin's device code, card or not. Serves as
|
||||
* the host backend's code_mark in a HIP build. */
|
||||
size_t aql_code_registered(void);
|
||||
#endif
|
||||
|
||||
/* ------------------------------------------------------------------ the error slot */
|
||||
/* Both backends write here; rad_dev_last_error() drains it. Thread-local because spec §1 gives each
|
||||
* tensor-parallel rank and the mover their own thread, and an error must be reported on the thread
|
||||
* that caused it. */
|
||||
void device_set_error(const char* fmt, ...) __attribute__((format(printf, 1, 2)));
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,202 @@
|
||||
/* directio.cpp -- see directio.h for why the page cache is not wanted here. */
|
||||
#include "directio.h"
|
||||
#include "../rad_internal.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cerrno>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace rad {
|
||||
namespace {
|
||||
|
||||
/* Bounce buffer size; allocated on first misaligned use only. */
|
||||
constexpr int64_t kBounceBytes = 1 << 20;
|
||||
|
||||
int64_t align_down(int64_t v, int64_t a) { return v / a * a; }
|
||||
|
||||
/* Reads up to `bytes`, stopping at end of file. Returns the byte count, or a negative error. */
|
||||
int64_t pread_some(int fd, void* dst, int64_t bytes, int64_t off) {
|
||||
int64_t done = 0;
|
||||
while (done < bytes) {
|
||||
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;
|
||||
}
|
||||
|
||||
/* Fill `bytes` exactly. A short pread inside the file is a torn read, not a smaller one: end of
|
||||
* file inside a range the caller said was there is an error. */
|
||||
int pread_exact(int fd, void* dst, int64_t bytes, int64_t off) {
|
||||
const int64_t got = pread_some(fd, dst, bytes, off);
|
||||
if (got < 0) return (int)got;
|
||||
return got == bytes ? RAD_OK : RAD_E_IO;
|
||||
}
|
||||
|
||||
int pwrite_exact(int fd, const void* src, int64_t bytes, int64_t off) {
|
||||
int64_t done = 0;
|
||||
while (done < bytes) {
|
||||
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: a partial-block write reads the block first (see write_at). */
|
||||
int oflags = want_write ? O_RDWR : O_RDONLY;
|
||||
if (flags & RAD_DIO_CREATE) oflags |= O_CREAT;
|
||||
if (flags & RAD_DIO_TRUNC) oflags |= O_TRUNC;
|
||||
|
||||
fd_ = ::open(path, oflags | O_DIRECT, 0600);
|
||||
direct_ = fd_ >= 0;
|
||||
|
||||
if (fd_ < 0 && (errno == EINVAL || errno == ENOTSUP || errno == EOPNOTSUPP)) {
|
||||
/* 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;
|
||||
|
||||
/* Fast path: one pread straight into the caller's pinned buffer. Every .rad extent lands here
|
||||
* (movement units and rad_dev_alloc pools are both RAD_ALIGN_UNIT-aligned). */
|
||||
if (aligned) return pread_exact(fd_, dst, bytes, off);
|
||||
|
||||
/* O_DIRECT rejects unaligned transfers with EINVAL, so read an aligned superset through the
|
||||
* bounce and copy out. This serves file tails and header/footer reads, never the mover; a
|
||||
* step-path read landing here indicates a layout bug. */
|
||||
RAD_TRY(bounce_ready());
|
||||
|
||||
const int64_t lo = align_down(off, A);
|
||||
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 fine only if it still covers the requested slice. */
|
||||
if (got < e - base) return RAD_E_IO;
|
||||
std::memcpy((uint8_t*)dst + (s - off), bounce_ + (s - base), (size_t)(e - s));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ write */
|
||||
|
||||
/* Aligned writes go straight through; anything else is a read-modify-write of whole blocks. */
|
||||
int DirectFile::write_at(const void* src, int64_t off, int64_t bytes) {
|
||||
if (fd_ < 0) return RAD_E_STATE;
|
||||
if (!src || off < 0 || bytes < 0) return RAD_E_INVAL;
|
||||
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 fully covered interior blocks. The extra
|
||||
* reads are deliberate: this path is for correctness at boundaries, not throughput. */
|
||||
const int64_t got = pread_some(fd_, bounce_, span, base);
|
||||
if (got < 0) return (int)got;
|
||||
if (got < span) std::memset(bounce_ + got, 0, (size_t)(span - got));
|
||||
|
||||
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 to a block boundary; truncate back to the real end. */
|
||||
const int64_t want = std::max(old_size, off + bytes);
|
||||
if (size() > want && ::ftruncate(fd_, (off_t)want) != 0) return RAD_E_IO;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,66 @@
|
||||
/* directio.h -- the file tier's reader (spec §5.4): O_DIRECT reads into pinned buffers, used by
|
||||
* the weight tier and the KV tier.
|
||||
*
|
||||
* The page cache is avoided for two reasons:
|
||||
* - it is a second copy of every byte already headed for a pinned buffer;
|
||||
* - it evicts. A large tier read through the page cache throws out the mapped `.rad` pool's
|
||||
* pages, which shows up later as an untraceable decode stall.
|
||||
*
|
||||
* O_DIRECT requires the file offset, transfer length and buffer address to be block-aligned.
|
||||
* rad_dev_alloc memory is (host.cpp) and .rad pads movement units to RAD_ALIGN_UNIT
|
||||
* (rad_format.h), so every mover read takes the unbounced path. The bounce is for other callers.
|
||||
*/
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
|
||||
namespace rad {
|
||||
|
||||
enum {
|
||||
RAD_DIO_READ = 1,
|
||||
RAD_DIO_WRITE = 2, /* implies read: a partial block is a read-modify-write */
|
||||
RAD_DIO_CREATE = 4,
|
||||
RAD_DIO_TRUNC = 8,
|
||||
|
||||
/* Open buffered when the filesystem refuses O_DIRECT, instead of failing. Off by default: a
|
||||
* silent buffered fallback makes the weight tier ~3x slower and is invisible in a profile.
|
||||
* For tests, which run on whatever /tmp is. */
|
||||
RAD_DIO_ALLOW_BUFFERED = 16,
|
||||
};
|
||||
|
||||
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, so callers
|
||||
* need no byte-count check. */
|
||||
int read_at(void* dst, int64_t off, int64_t bytes);
|
||||
int write_at(const void* src, int64_t off, int64_t bytes);
|
||||
|
||||
/* The alignment every fast-path extent must satisfy. A fixed 4096 rather than the device's
|
||||
* logical block size (often 512, see STATX_DIOALIGN): it covers every real requirement, equals
|
||||
* RAD_ALIGN_UNIT, and keeps behaviour independent of the filesystem. */
|
||||
static constexpr int64_t alignment() { return 4096; }
|
||||
|
||||
private:
|
||||
int bounce_ready();
|
||||
|
||||
int fd_ = -1;
|
||||
bool direct_ = false;
|
||||
uint8_t* bounce_ = nullptr;
|
||||
int64_t bounce_bytes_ = 0;
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,649 @@
|
||||
/* dispatch.cpp -- picks a backend once, then forwards.
|
||||
*
|
||||
* The only definition of every rad_dev_* / rad_stream_* / rad_event_* symbol. host.cpp and hip.cpp
|
||||
* export vtables only, so there is no #ifdef above this file and both backends share one contract.
|
||||
*
|
||||
* A build with HIP still runs the host backend when no device is visible (e.g. a CI container
|
||||
* with ROCm headers and no /dev/kfd); the chosen backend is logged at Info.
|
||||
*/
|
||||
#include "device.h"
|
||||
#include "../rad_internal.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdarg>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <atomic>
|
||||
#include <cstdlib>
|
||||
#include <iterator>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <cstdint>
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* ------------------------------------------------------------------ the error slot */
|
||||
/* Thread-local and cleared by reading, per the ABI. Each rank and the mover run on their own
|
||||
* thread (spec §1), so an error must stay on the thread that raised it. */
|
||||
static thread_local std::string t_last_error;
|
||||
|
||||
void device_set_error(const char* f, ...) {
|
||||
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, not Error: callers often recover (e.g. a pool retrying smaller), and fatal ones are
|
||||
* reported by the caller with more context. */
|
||||
RAD_DEBUG("device: %s", buf);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ selection */
|
||||
|
||||
/* The startup line's list of every visible device by index and arch. A machine may report more
|
||||
* devices than accelerators: an APU shows up beside discrete cards and claims system RAM as
|
||||
* "VRAM". The arch tells them apart. Filtering is the engine's decision (via rad_dev_props). */
|
||||
static std::string device_inventory(const DeviceBackend* b) {
|
||||
std::string s;
|
||||
const int n = b->count();
|
||||
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;
|
||||
}
|
||||
|
||||
#if defined(RAD_HAVE_HIP) && RAD_HAVE_HIP
|
||||
/* With amdgpu.cwsr_enable=0 (compute wave save/restore off) a queue eviction hangs the GPU. The
|
||||
* driver evicts a process's queues when card-mapped host memory is moved or reclaimed, and a serve
|
||||
* maps gigabytes of it. Without CWSR the driver waits for the queue to drain, a busy queue never
|
||||
* does, MES fails REMOVE_QUEUE and the card resets. Warned here as the backend comes up, not only
|
||||
* in the startup report: a hang during load kills the process first, and rad-kbench and rad-tune
|
||||
* print no report. */
|
||||
static void warn_cwsr_off() {
|
||||
FILE* f = std::fopen("/sys/module/amdgpu/parameters/cwsr_enable", "r");
|
||||
if (!f) return;
|
||||
int v = -1;
|
||||
const int got = std::fscanf(f, "%d", &v);
|
||||
std::fclose(f);
|
||||
if (got == 1 && v == 0)
|
||||
RAD_WARN("device: amdgpu cwsr_enable is 0, so the driver cannot preempt a running queue: "
|
||||
"any queue eviction (host memory the card maps, moved under memory pressure) waits "
|
||||
"for a queue a serve never lets drain, and ends in a GPU hang and reset. Set "
|
||||
"amdgpu.cwsr_enable=1 (module option, then rebuild the initramfs and reboot)");
|
||||
}
|
||||
|
||||
/* The host backend in a HIP build still counts plugin GPU code. This build's fat-binary
|
||||
* registration hooks see every dlopen'ed kernel library, card or no card, so the plugin loader can
|
||||
* tell which library brought device code. A serving engine drops those device rows from selection
|
||||
* (Registry::set_no_device_code); a selection-only tool keeps them. */
|
||||
static DeviceBackend g_host_beside_hip;
|
||||
#endif
|
||||
|
||||
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());
|
||||
warn_cwsr_off();
|
||||
return b;
|
||||
}
|
||||
RAD_INFO("device: built with HIP but no device is visible -- using the host backend");
|
||||
g_host_beside_hip = *host_backend();
|
||||
g_host_beside_hip.code_mark = aql_code_registered;
|
||||
const DeviceBackend* b = &g_host_beside_hip;
|
||||
#else
|
||||
const DeviceBackend* b = host_backend();
|
||||
#endif
|
||||
RAD_INFO("device: host backend, %d device(s) [%s]", b->count(), device_inventory(b).c_str());
|
||||
return b;
|
||||
}
|
||||
|
||||
/* Selected exactly once, under std::call_once; read from every rank thread. */
|
||||
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
|
||||
*
|
||||
* Counts every device allocation the engine makes. The VRAM budget (core/mem/vram_budget.cpp)
|
||||
* spends the card down to --gpu-headroom-mib, so whatever lands outside the two pools and is not
|
||||
* derived from the buffer plan or run configuration must be counted here.
|
||||
*
|
||||
* Not seen: plugins that call hipMalloc directly (libr4d's split-tail workspaces and all-reduce
|
||||
* peer scratch). Engine::start reads the card back after allocation for that reason.
|
||||
*
|
||||
* RADIANCE_TRACE_ALLOC=N logs each allocation of at least N bytes.
|
||||
*
|
||||
* RADIANCE_DEBUG_POISON_ALLOC=B fills every fresh DEVICE allocation with byte B (0..255), so a
|
||||
* read-before-write shows up as garbage instead of lucky zeros (as after a driver reset, "VRAM is
|
||||
* lost"). A correct engine serves the same output with it set. RADIANCE_DEBUG_POISON_RANGE=lo:hi
|
||||
* limits the fill to device allocations with ordinal in [lo, hi), counted from 1 per allocating
|
||||
* thread (the trace's `#n on this thread`), for bisecting. The fill is synchronous on one stream
|
||||
* per thread and device, kept until exit: a stream is a hardware queue, and per-allocation queue
|
||||
* churn is slow and faults in ROCr's Trim path. Bad values abort at the first allocation. */
|
||||
namespace rad {
|
||||
namespace {
|
||||
|
||||
struct Ledger {
|
||||
std::atomic<int64_t> bytes{0};
|
||||
std::atomic<int64_t> count{0};
|
||||
};
|
||||
Ledger g_ledger[4]; /* indexed by RAD_MEM_*; rad_dev_alloc bounds the kind */
|
||||
|
||||
/* Live event handles, counted here so the number is backend-independent; the only place an
|
||||
* event leaked at teardown shows. */
|
||||
std::atomic<int64_t> g_live_events{0};
|
||||
/* Host blocks through the ABI (rad_event_sync, rad_stream_sync), counted here so a test can
|
||||
* assert that a path never stops the host, whichever backend runs it. */
|
||||
std::atomic<int64_t> g_host_blocks{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;
|
||||
}
|
||||
|
||||
/* -1 when off; otherwise the byte. */
|
||||
int poison_byte() {
|
||||
static const int v = [] {
|
||||
const char* e = std::getenv("RADIANCE_DEBUG_POISON_ALLOC");
|
||||
if (!e || !*e) return -1;
|
||||
char* end = nullptr;
|
||||
const long x = std::strtol(e, &end, 0);
|
||||
if (*end || x < 0 || x > 255) {
|
||||
RAD_ERR("RADIANCE_DEBUG_POISON_ALLOC=%s is not a byte (0..255)", e);
|
||||
std::abort();
|
||||
}
|
||||
return (int)x;
|
||||
}();
|
||||
return v;
|
||||
}
|
||||
|
||||
/* [lo, hi) over device-allocation ordinals; the whole run when unset. */
|
||||
bool poison_in_range(int64_t ordinal) {
|
||||
static const std::pair<int64_t, int64_t> r = [] {
|
||||
const char* e = std::getenv("RADIANCE_DEBUG_POISON_RANGE");
|
||||
long long lo = 0, hi = INT64_MAX;
|
||||
if (e && *e && (std::sscanf(e, "%lld:%lld", &lo, &hi) != 2 || lo < 0 || hi <= lo)) {
|
||||
RAD_ERR("RADIANCE_DEBUG_POISON_RANGE=%s is not lo:hi with 0 <= lo < hi", e);
|
||||
std::abort();
|
||||
}
|
||||
return std::make_pair((int64_t)lo, (int64_t)hi);
|
||||
}();
|
||||
return ordinal >= r.first && ordinal < r.second;
|
||||
}
|
||||
|
||||
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 >= (int)std::size(g_ledger)) {
|
||||
if (bytes) *bytes = 0;
|
||||
if (count) *count = 0;
|
||||
return;
|
||||
}
|
||||
if (bytes) *bytes = g_ledger[kind].bytes.load(std::memory_order_relaxed);
|
||||
if (count) *count = g_ledger[kind].count.load(std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
int64_t rad_dev_live_events(void) { return g_live_events.load(std::memory_order_relaxed); }
|
||||
int64_t rad_dev_host_blocks(void) { return g_host_blocks.load(std::memory_order_relaxed); }
|
||||
|
||||
|
||||
/* ------------------------------------------------------------------ elastic memory */
|
||||
/* See device.h. Interval arithmetic and rounding here; the backends do the mapping. */
|
||||
|
||||
namespace {
|
||||
std::atomic<int64_t> g_vmem_committed{0};
|
||||
} /* namespace */
|
||||
|
||||
int64_t rad_dev_vmem_committed(void) { return g_vmem_committed.load(std::memory_order_relaxed); }
|
||||
|
||||
/* Both checks: a backend may have the entries on a driver with no virtual memory manager
|
||||
* (granularity 0). Checking only the pointers would reserve a range that can never be backed. */
|
||||
bool VMem::supported() { return dev()->vmem_reserve != nullptr && VMem::granularity() > 0; }
|
||||
int64_t VMem::granularity() {
|
||||
if (!dev()->vmem_granularity) return 0;
|
||||
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;
|
||||
/* Round up to a granule: a partial last granule could never be committed. */
|
||||
const int64_t want = align_up(bytes, g);
|
||||
void* p = dev()->vmem_reserve(want, align);
|
||||
if (!p) return RAD_E_NOMEM;
|
||||
base_ = p;
|
||||
size_ = want;
|
||||
committed_ = 0;
|
||||
ext_.clear();
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void VMem::release() {
|
||||
if (!base_) { size_ = 0; committed_ = 0; ext_.clear(); return; }
|
||||
/* Decommit before release: releasing a range with pages still mapped leaks them, and some
|
||||
* drivers refuse the free. One granule at a time, as each was mapped. */
|
||||
const int64_t g = granularity();
|
||||
for (const auto& e : ext_) {
|
||||
if (dev()->vmem_decommit && g > 0)
|
||||
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 */
|
||||
}
|
||||
/* The granules to map are gathered before mapping any: add_extent merges, so walking ext_ while
|
||||
* mapping would skip entries and map the tail twice (the driver refuses a double map).
|
||||
*
|
||||
* Driver rules:
|
||||
* - A mapping can only be unbacked exactly as it was backed, so each granule is mapped
|
||||
* separately; that lets the pool hand back the top of its range.
|
||||
* - Access cannot be granted per granule: a granule adjacent to an accessible one is refused on
|
||||
* its own. Access is granted once per merged extent the new granules belong to; re-granting
|
||||
* access to a range is free. */
|
||||
int VMem::commit(int64_t off, int64_t bytes) {
|
||||
if (!base_ || bytes <= 0) return bytes <= 0 ? RAD_OK : RAD_E_INVAL;
|
||||
const int64_t g = granularity();
|
||||
if (g <= 0) return RAD_E_UNSUPPORTED;
|
||||
/* Round outward: every requested byte must be committed. */
|
||||
const int64_t lo = (off < 0 ? 0 : off / g * g);
|
||||
int64_t hi = align_up(off + bytes, g);
|
||||
if (hi > size_) hi = size_;
|
||||
if (lo >= hi) return RAD_OK;
|
||||
|
||||
std::vector<int64_t> want;
|
||||
want.reserve((size_t)((hi - lo) / g));
|
||||
for (int64_t o = lo; o < hi; o += g)
|
||||
if (!is_committed(o, g)) want.push_back(o);
|
||||
if (want.empty()) return RAD_OK;
|
||||
|
||||
/* On a failure part way, what already mapped stays mapped and recorded: a partial grow is
|
||||
* usable, untracked mappings are not. */
|
||||
int rc = RAD_OK;
|
||||
size_t took = 0;
|
||||
for (; took < want.size(); ++took) {
|
||||
rc = dev()->vmem_commit((char*)base_ + want[took], g);
|
||||
if (rc < 0) break;
|
||||
add_extent(want[took], g);
|
||||
}
|
||||
|
||||
/* Grant access even if the grow stopped short, so the granules that did map are usable. */
|
||||
int prc = RAD_OK;
|
||||
if (took > 0 && dev()->vmem_protect) {
|
||||
for (const auto& e : ext_) {
|
||||
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 inaccessible memory faults the first kernel that touches it. Undo exactly
|
||||
* what this call mapped; earlier extents were already accessible. */
|
||||
for (size_t i = 0; i < took; ++i) {
|
||||
if (dev()->vmem_decommit) (void)dev()->vmem_decommit((char*)base_ + want[i], g);
|
||||
drop_extent(want[i], g);
|
||||
}
|
||||
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;
|
||||
/* Round inward: a granule holding any byte outside the range stays. */
|
||||
const int64_t lo = align_up(off < 0 ? 0 : off, g);
|
||||
int64_t hi = (off + bytes) / g * g;
|
||||
if (hi > size_) hi = size_;
|
||||
if (lo >= hi) return RAD_OK;
|
||||
|
||||
/* Gathered first and unmapped per granule, as in commit. */
|
||||
std::vector<int64_t> drop;
|
||||
for (int64_t o = lo; o < hi; o += g)
|
||||
if (is_committed(o, g)) drop.push_back(o);
|
||||
|
||||
for (const int64_t o : drop) {
|
||||
const int rc = dev()->vmem_decommit((char*)base_ + o, g);
|
||||
if (rc < 0) return rc;
|
||||
drop_extent(o, g);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void VMem::add_extent(int64_t off, int64_t bytes) {
|
||||
committed_ += bytes;
|
||||
g_vmem_committed.fetch_add(bytes, std::memory_order_relaxed);
|
||||
/* Insert in order, then merge touching neighbours, so is_committed() stays a short scan
|
||||
* although pools grow one granule at a time. */
|
||||
size_t i = 0;
|
||||
while (i < ext_.size() && ext_[i].first < off) ++i;
|
||||
ext_.insert(ext_.begin() + (long)i, { off, bytes });
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Precondition: the piece lies wholly inside one extent (decommit only drops committed granules).
|
||||
* What remains of that extent is nothing, a head, a tail, or both. */
|
||||
void VMem::drop_extent(int64_t off, int64_t bytes) {
|
||||
committed_ -= bytes;
|
||||
g_vmem_committed.fetch_sub(bytes, std::memory_order_relaxed);
|
||||
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(); }
|
||||
/* The device this thread last selected, for the poison fill's stream (rad_dev_alloc). */
|
||||
static thread_local int t_device = 0;
|
||||
static thread_local std::map<int, RadStream> t_poison_stream;
|
||||
int rad_dev_set(int device) {
|
||||
const int st = dev()->set(device);
|
||||
if (st == RAD_OK) t_device = device;
|
||||
return st;
|
||||
}
|
||||
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) {
|
||||
/* Poison ordinals are per thread: each rank allocates in a fixed order on its own thread, but
|
||||
* threads interleave, so a process-wide ordinal would not be repeatable. */
|
||||
thread_local int64_t t_device_ordinal = 0;
|
||||
void* p = dev()->alloc(bytes, kind);
|
||||
if (p && kind >= 0 && kind < (int)std::size(rad::g_ledger)) {
|
||||
rad::g_ledger[kind].bytes.fetch_add(bytes, std::memory_order_relaxed);
|
||||
const int64_t total = rad::g_ledger[kind].count.fetch_add(1, std::memory_order_relaxed) + 1;
|
||||
const int64_t ordinal = kind == RAD_MEM_DEVICE ? ++t_device_ordinal : total;
|
||||
const int64_t floor_ = rad::trace_floor();
|
||||
if (floor_ >= 0 && bytes >= floor_)
|
||||
RAD_INFO("alloc %s %s (#%lld on this thread; %lld live in %lld allocations)",
|
||||
rad::kind_name(kind), rad::humanb(bytes).c_str(), (long long)ordinal,
|
||||
(long long)rad::g_ledger[kind].bytes.load(std::memory_order_relaxed),
|
||||
(long long)total);
|
||||
/* Poison fill (see the ledger header): synchronous, so it lands before p is returned. */
|
||||
const int poison = rad::poison_byte();
|
||||
if (poison >= 0 && kind == RAD_MEM_DEVICE && rad::poison_in_range(ordinal)) {
|
||||
RadStream& s = t_poison_stream[t_device];
|
||||
if (!s && dev()->stream_create(&s, 0) != RAD_OK) s = nullptr;
|
||||
if (!s || dev()->memset_async(p, poison, bytes, s) != RAD_OK ||
|
||||
dev()->stream_sync(s) != RAD_OK)
|
||||
RAD_WARN("poison: device allocation #%lld (%s) was not filled",
|
||||
(long long)ordinal, rad::humanb(bytes).c_str());
|
||||
else if (floor_ >= 0 && bytes >= floor_)
|
||||
RAD_INFO("poison: device allocation #%lld filled with 0x%02x", (long long)ordinal,
|
||||
poison);
|
||||
}
|
||||
}
|
||||
return p;
|
||||
}
|
||||
void rad_dev_free(void* p, int kind) {
|
||||
/* The ledger counts allocations, not live bytes: rad_dev_free has no size. The engine frees
|
||||
* only at teardown, so the two agree while running. */
|
||||
dev()->free(p, kind);
|
||||
}
|
||||
void* rad_dev_host_ptr(void* p) { return dev()->host_ptr(p); }
|
||||
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) {
|
||||
rad::g_host_blocks.fetch_add(1, std::memory_order_relaxed);
|
||||
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; }
|
||||
/* These getters answer "" on failure and restore the error slot, so the next
|
||||
* rad_dev_last_error reader does not see an unrelated error. `get` fills a buffer of `n` bytes. */
|
||||
template <class Get> static std::string dev_string(int n, Get get) {
|
||||
std::string buf((size_t)n, '\0');
|
||||
const std::string before = t_last_error;
|
||||
if (get(buf.data(), n) < 0) {
|
||||
t_last_error = before;
|
||||
return std::string();
|
||||
}
|
||||
buf.resize(std::strlen(buf.c_str()));
|
||||
return buf;
|
||||
}
|
||||
std::string dev_pci_address(int device) {
|
||||
if (!dev()->pci_address) return std::string();
|
||||
return dev_string(64, [&](char* b, int n) { return dev()->pci_address(device, b, n); });
|
||||
}
|
||||
std::string dev_dma_lane(int device) {
|
||||
if (!dev()->dma_lane) return std::string();
|
||||
return dev_string(256, [&](char* b, int n) { return dev()->dma_lane(device, b, n); });
|
||||
}
|
||||
std::string dev_runtime_version() {
|
||||
if (!dev()->runtime_version) return std::string();
|
||||
return dev_string(128, [&](char* b, int n) { return dev()->runtime_version(b, n); });
|
||||
}
|
||||
int dev_peer_access(int self, int peer) {
|
||||
if (self == peer) return 1;
|
||||
return dev()->peer_access ? dev()->peer_access(self, peer) : 1;
|
||||
}
|
||||
size_t dev_code_mark() { return dev()->code_mark ? dev()->code_mark() : 0; }
|
||||
int dev_code_runs(size_t from, size_t to, int device, std::string* why) {
|
||||
if (!dev()->code_runs || from >= to) return 1;
|
||||
char buf[1024];
|
||||
buf[0] = 0;
|
||||
const int r = dev()->code_runs(from, to, device, buf, (int)sizeof buf);
|
||||
if (why) *why = buf;
|
||||
return r;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
|
||||
extern "C" {
|
||||
|
||||
|
||||
int rad_event_create_as(RadEvent* out, unsigned flags) {
|
||||
const int s = dev()->event_create(out, flags);
|
||||
if (s >= 0 && out && *out) rad::g_live_events.fetch_add(1, std::memory_order_relaxed);
|
||||
return s;
|
||||
}
|
||||
int rad_event_create(RadEvent* out) { return rad_event_create_as(out, RAD_EVENT_HOST_WAIT); }
|
||||
int rad_event_create_local(RadEvent* out) { return rad_event_create_as(out, RAD_EVENT_LOCAL); }
|
||||
void rad_event_destroy(RadEvent e) {
|
||||
if (!e) return;
|
||||
rad::g_live_events.fetch_sub(1, std::memory_order_relaxed);
|
||||
dev()->event_destroy(e);
|
||||
}
|
||||
int rad_event_record(RadEvent e, RadStream s) { return dev()->event_record(e, s); }
|
||||
int rad_event_wait(RadStream s, RadEvent e) { return dev()->event_wait(s, e); }
|
||||
int rad_event_query(RadEvent e) { return dev()->event_query(e); }
|
||||
int rad_event_sync(RadEvent e) {
|
||||
rad::g_host_blocks.fetch_add(1, std::memory_order_relaxed);
|
||||
return dev()->event_sync(e);
|
||||
}
|
||||
void rad_dev_host_wrote(void) { dev()->host_wrote(); }
|
||||
int rad_event_elapsed_ms(RadEvent a, RadEvent b, float* out) {
|
||||
return dev()->event_elapsed_ms(a, b, out);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
int rad_memcpy_list_async(const RadCopySeg* segs, int n, unsigned flags, RadStream s) {
|
||||
if (const auto f = dev()->memcpy_list_async) return f(segs, n, flags, s);
|
||||
for (int i = 0; i < n; ++i) RAD_TRY(dev()->memcpy_async(segs[i].dst, segs[i].src, segs[i].bytes, s));
|
||||
return RAD_OK;
|
||||
}
|
||||
int rad_link_hold(RadStream s, int on) {
|
||||
if (const auto f = dev()->link_hold) return f(s, on);
|
||||
return RAD_OK;
|
||||
}
|
||||
void* rad_link_gate(RadStream s) {
|
||||
if (const auto f = dev()->link_gate) return f(s);
|
||||
return nullptr;
|
||||
}
|
||||
int rad_xp_supported(int device) {
|
||||
const auto* d = dev();
|
||||
return d->xp_supported && d->xp_stream_create && d->ride && d->ride_wait && d->ride_release && d->xp_list &&
|
||||
d->xp_behind && d->alloc_uncached && d->free_uncached && d->xp_supported(device);
|
||||
}
|
||||
int rad_xp_stream_create(RadStream* out) {
|
||||
if (const auto f = dev()->xp_stream_create) return f(out);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
int rad_ride(RadStream s, void** token) {
|
||||
if (const auto f = dev()->ride) return f(s, token);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
int rad_ride_wait(RadStream s, void* token) {
|
||||
if (const auto f = dev()->ride_wait) return f(s, token);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
void rad_ride_release(void* token, RadStream after, int64_t packets) {
|
||||
if (const auto f = dev()->ride_release) f(token, after, packets);
|
||||
}
|
||||
int rad_xp_list(int device, void* mark, int n, const uint64_t* src, const uint64_t* dst, const uint64_t* bytes,
|
||||
uint32_t* done, uint32_t done_val) {
|
||||
if (const auto f = dev()->xp_list) return f(device, mark, n, src, dst, bytes, done, done_val);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
int64_t rad_xp_behind(int device) {
|
||||
if (const auto f = dev()->xp_behind) return f(device);
|
||||
return 0;
|
||||
}
|
||||
void* rad_dev_alloc_uncached(int64_t bytes) {
|
||||
if (const auto f = dev()->alloc_uncached) return f(bytes);
|
||||
return nullptr;
|
||||
}
|
||||
void rad_dev_free_uncached(void* p) {
|
||||
if (const auto f = dev()->free_uncached) f(p);
|
||||
}
|
||||
int rad_stream_gate(RadStream s, void** gate) {
|
||||
if (gate) *gate = nullptr;
|
||||
if (const auto f = dev()->stream_gate) return f(s, gate);
|
||||
rad::device_set_error("rad_stream_gate: the %s backend has no gates", dev()->name);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
int rad_gate_open(void* gate) {
|
||||
if (const auto f = dev()->gate_open) return f(gate);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
int64_t rad_gate_room(RadStream s) {
|
||||
if (const auto f = dev()->gate_room) return f(s);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Cleared by reading. Never null; "" when nothing failed. */
|
||||
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" */
|
||||
@@ -0,0 +1,388 @@
|
||||
/* hip.cpp -- the HIP half of the device backend: devices, memory and elastic memory.
|
||||
*
|
||||
* Streams, events, copies and fills are AQL packets on engine-owned queues (aql.cpp), which
|
||||
* starts from this table and fills in the rest, pinned host memory included because the copies
|
||||
* must recognise it.
|
||||
*
|
||||
* Thin by design: each entry point is one hip* call plus error capture, so it cannot diverge from
|
||||
* the host backend, where the logic is tested (docs/IMPLEMENTATION.md). Policy belongs in the
|
||||
* component that wants it.
|
||||
*
|
||||
* Compiles to nothing without RAD_HAVE_HIP, so the source list needs no backend split.
|
||||
*/
|
||||
#include "device.h"
|
||||
|
||||
#if defined(RAD_HAVE_HIP) && RAD_HAVE_HIP
|
||||
|
||||
#include "../rad_internal.h"
|
||||
|
||||
#include <hip/hip_runtime.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <mutex>
|
||||
#include <new>
|
||||
#include <vector>
|
||||
#include <cstring>
|
||||
#include <cstdio>
|
||||
#include <strings.h>
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace rad {
|
||||
namespace {
|
||||
|
||||
/* Maps a hipError_t to a coarse RAD_E_* class; the detail goes to rad_dev_last_error(). */
|
||||
int hip_fail(hipError_t e, const char* who) {
|
||||
device_set_error("%s: %s (%s)", who, hipGetErrorString(e), hipGetErrorName(e));
|
||||
switch (e) {
|
||||
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 void callers (frees, destroys): a failing teardown is still logged, since it means the
|
||||
* pointer was not what the caller thought. */
|
||||
void hip_note(hipError_t e, const char* who) {
|
||||
if (e != hipSuccess) RAD_WARN("device: %s: %s", who, hipGetErrorString(e));
|
||||
}
|
||||
#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
|
||||
*
|
||||
* On a card that also drives a display, hipMemGetInfo's "free" sits up to 0.7 GiB below the
|
||||
* amdgpu driver's own per-card accounting, and that gap is allocatable. So read the driver's
|
||||
* counters (bytes, per card, all processes) from the drm node matched by PCI slot. The node's
|
||||
* total must equal HIP's total, so both describe the same memory; any failure returns -1 and the
|
||||
* caller keeps hipMemGetInfo. -1 on every non-amdgpu platform.
|
||||
*
|
||||
* The node's `mem_info_vram_used` is also kept open per device for d_vram_used, so an observer
|
||||
* reads the card through that descriptor and never through the runtime. */
|
||||
constexpr int kMaxVramNodes = 64;
|
||||
std::atomic<int> g_vram_used_fd[kMaxVramNodes] = {}; /* 0: not opened; else the fd plus one */
|
||||
|
||||
static int64_t sysfs_vram_free(int device, int64_t total) {
|
||||
char bus[64] = {0};
|
||||
if (hipDeviceGetPCIBusId(bus, (int)sizeof bus, device) != hipSuccess || !bus[0]) return -1;
|
||||
const size_t buslen = std::strlen(bus);
|
||||
|
||||
for (int c = 0; c < 64; ++c) {
|
||||
char path[160];
|
||||
std::snprintf(path, sizeof path, "/sys/class/drm/card%d/device/uevent", c);
|
||||
FILE* f = std::fopen(path, "r");
|
||||
if (!f) continue;
|
||||
bool match = false;
|
||||
char line[256];
|
||||
while (std::fgets(line, (int)sizeof line, f))
|
||||
if (!std::strncmp(line, "PCI_SLOT_NAME=", 14) &&
|
||||
!strncasecmp(line + 14, bus, buslen)) { match = true; break; }
|
||||
std::fclose(f);
|
||||
if (!match) continue;
|
||||
|
||||
auto read_u64 = [&](const char* leaf, long long* out_v) {
|
||||
char p[160];
|
||||
std::snprintf(p, sizeof p, "/sys/class/drm/card%d/device/%s", c, leaf);
|
||||
FILE* g = std::fopen(p, "r");
|
||||
if (!g) return false;
|
||||
const bool ok = std::fscanf(g, "%lld", out_v) == 1 && *out_v >= 0;
|
||||
std::fclose(g);
|
||||
return ok;
|
||||
};
|
||||
long long tot = 0, used = 0;
|
||||
if (!read_u64("mem_info_vram_total", &tot) || !read_u64("mem_info_vram_used", &used))
|
||||
return -1;
|
||||
if (tot != (long long)total) return -1; /* different accountings; do not mix them */
|
||||
if (device >= 0 && device < kMaxVramNodes &&
|
||||
g_vram_used_fd[device].load(std::memory_order_acquire) == 0) {
|
||||
char p[160];
|
||||
std::snprintf(p, sizeof p, "/sys/class/drm/card%d/device/mem_info_vram_used", c);
|
||||
const int fd = ::open(p, O_RDONLY | O_CLOEXEC);
|
||||
int none = 0;
|
||||
if (fd >= 0 && !g_vram_used_fd[device].compare_exchange_strong(none, fd + 1))
|
||||
::close(fd);
|
||||
}
|
||||
return total - (int64_t)used;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
/* A sysfs attribute is regenerated by a read at offset 0, so read with pread at 0. */
|
||||
int d_vram_used(int device, int64_t* out) {
|
||||
if (!out || device < 0 || device >= kMaxVramNodes) return RAD_E_INVAL;
|
||||
const int fd = g_vram_used_fd[device].load(std::memory_order_acquire) - 1;
|
||||
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 in bytes, or -1. */
|
||||
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);
|
||||
|
||||
/* Intended truncation: HIP's fields are 256 bytes, ours 128 and 32. The explicit precision
|
||||
* silences gcc's truncation warning; real values are a few dozen characters. */
|
||||
snprintf(out->name, sizeof out->name, "%.*s", (int)(sizeof out->name) - 1, p.name);
|
||||
snprintf(out->arch, sizeof out->arch, "%.*s", (int)(sizeof out->arch) - 1, p.gcnArchName);
|
||||
/* Strip feature suffixes ("gfx1201:sramecc-:xnack-"): plugin constraints match the bare
|
||||
* target. */
|
||||
if (char* c = std::strchr(out->arch, ':')) *c = '\0';
|
||||
|
||||
out->device_id = device;
|
||||
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 switch to `device` and back. props is not
|
||||
* called per step. */
|
||||
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;
|
||||
}
|
||||
/* Prefer the driver's counter where readable (see sysfs_vram_free). */
|
||||
{
|
||||
const int64_t sf = sysfs_vram_free(device, out->vram_bytes);
|
||||
if (sf >= 0) {
|
||||
out->vram_free = sf;
|
||||
} else if (d_integrated(device)) {
|
||||
/* Integrated GPU whose reported memory exceeds the driver's carve-out: the rest is
|
||||
* system RAM, and the runtime's free figure ignores other processes using it. Bound
|
||||
* it by MemAvailable. (A carve-out reported as-is is answered by sysfs above.) */
|
||||
const int64_t avail = host_mem_available();
|
||||
if (avail >= 0 && avail < out->vram_free) out->vram_free = avail;
|
||||
}
|
||||
}
|
||||
/* A failed restore leaves this thread on the wrong card; under TP that is a rank working on
|
||||
* its neighbour's memory, so it is logged. */
|
||||
if (moved) HIP_NOTE(hipSetDevice(prev));
|
||||
|
||||
/* Whether any peer is reachable, for the report; pairs go through rad_dev_enable_peer. */
|
||||
int n = d_count();
|
||||
for (int i = 0; i < n && !out->supports_p2p; ++i) {
|
||||
if (i == device) continue;
|
||||
int can = 0;
|
||||
if (hipDeviceCanAccessPeer(&can, device, i) == hipSuccess && can) out->supports_p2p = 1;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int d_peer_access(int self, int peer) {
|
||||
int can = 0;
|
||||
HIP_TRY(hipDeviceCanAccessPeer(&can, self, peer));
|
||||
return can ? 1 : 0;
|
||||
}
|
||||
|
||||
/* The runtime's bus id in the kernel's spelling (lower case, four-digit domain), matching
|
||||
* /sys/bus/pci/devices. */
|
||||
int d_pci_address(int device, char* out, int cap) {
|
||||
if (!out || cap <= 0) return RAD_E_INVAL;
|
||||
char bus[64] = { 0 };
|
||||
HIP_TRY(hipDeviceGetPCIBusId(bus, (int)sizeof bus, device));
|
||||
unsigned dom = 0, b = 0, d = 0, f = 0;
|
||||
if (std::sscanf(bus, "%x:%x:%x.%x", &dom, &b, &d, &f) != 4) {
|
||||
device_set_error("hipDeviceGetPCIBusId(%d): '%s' is not a PCI address", device, bus);
|
||||
return RAD_E_IO;
|
||||
}
|
||||
std::snprintf(out, (size_t)cap, "%04x:%02x:%02x.%x", dom, b, d, f);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* HIP_VERSION's encoding: major * 10^7 + minor * 10^5 + patch. */
|
||||
int d_runtime_version(char* out, int cap) {
|
||||
if (!out || cap <= 0) return RAD_E_INVAL;
|
||||
int v = 0;
|
||||
HIP_TRY(hipRuntimeGetVersion(&v));
|
||||
std::snprintf(out, (size_t)cap, "HIP %d.%d.%d", v / 10000000, (v / 100000) % 100, v % 100000);
|
||||
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: init() runs per resolved instance (spec §2.1) and several may
|
||||
* want the same pair. */
|
||||
if (e != hipSuccess && e != hipErrorPeerAccessAlreadyEnabled)
|
||||
return hip_fail(e, "hipDeviceEnablePeerAccess");
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ memory */
|
||||
|
||||
void* d_alloc(int64_t bytes, int kind) {
|
||||
if (bytes <= 0) {
|
||||
device_set_error("rad_dev_alloc(%lld): size must be positive", (long long)bytes);
|
||||
return nullptr;
|
||||
}
|
||||
void* p = nullptr;
|
||||
hipError_t e = hipSuccess;
|
||||
switch (kind) {
|
||||
case RAD_MEM_DEVICE:
|
||||
e = hipMalloc(&p, (size_t)bytes);
|
||||
break;
|
||||
case RAD_MEM_HOST_PINNED:
|
||||
case RAD_MEM_HOST_MAPPED:
|
||||
/* Pinned by the AQL backend through ROCr (aql.cpp, "pinned host memory, in pieces"). */
|
||||
device_set_error("rad_dev_alloc: pinned host memory is the AQL backend's");
|
||||
return nullptr;
|
||||
case RAD_MEM_HOST:
|
||||
/* Pageable, page-aligned so it can be an O_DIRECT target. */
|
||||
if (posix_memalign(&p, 4096, (size_t)((bytes + 4095) / 4096 * 4096)) != 0) p = nullptr;
|
||||
if (!p) e = hipErrorOutOfMemory;
|
||||
break;
|
||||
default:
|
||||
device_set_error("rad_dev_alloc: unknown memory kind %d", kind);
|
||||
return nullptr;
|
||||
}
|
||||
if (e != hipSuccess || !p) {
|
||||
hip_fail(e == hipSuccess ? hipErrorOutOfMemory : e, "rad_dev_alloc");
|
||||
return nullptr;
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
void d_free(void* p, int kind) {
|
||||
if (!p) return;
|
||||
switch (kind) {
|
||||
case RAD_MEM_DEVICE: HIP_NOTE(hipFree(p)); break;
|
||||
case RAD_MEM_HOST: std::free(p); break;
|
||||
case RAD_MEM_HOST_PINNED:
|
||||
case RAD_MEM_HOST_MAPPED:
|
||||
RAD_WARN("rad_dev_free(%p): pinned host memory is the AQL backend's; leaked", p);
|
||||
break;
|
||||
default:
|
||||
RAD_WARN("rad_dev_free(%p): unknown memory kind %d; leaked rather than freed with the "
|
||||
"wrong allocator", p, kind);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void* d_host_ptr(void* p) {
|
||||
if (!p) return nullptr;
|
||||
hipPointerAttribute_t a{};
|
||||
if (hipPointerGetAttributes(&a, p) != hipSuccess) return nullptr;
|
||||
return a.hostPointer;
|
||||
}
|
||||
|
||||
void* d_device_ptr(void* p) {
|
||||
if (!p) return nullptr;
|
||||
hipPointerAttribute_t a{};
|
||||
if (hipPointerGetAttributes(&a, p) != hipSuccess) return nullptr;
|
||||
if (a.devicePointer) return a.devicePointer;
|
||||
/* Mapped host allocation not resolved by the attribute query. */
|
||||
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: filled in by the AQL backend (aql.cpp). */
|
||||
nullptr, nullptr, nullptr,
|
||||
nullptr, nullptr, nullptr, nullptr,
|
||||
nullptr, nullptr, nullptr,
|
||||
nullptr,
|
||||
nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
|
||||
/* Recorded passes: AQL backend. */
|
||||
nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
|
||||
|
||||
/* Elastic memory: AQL backend, through HSA (aql.cpp, "elastic memory, through HSA"). */
|
||||
nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
|
||||
|
||||
d_vram_used,
|
||||
/* Plugin device code: AQL backend, which owns the fat-binary registrations. */
|
||||
nullptr, nullptr,
|
||||
d_integrated,
|
||||
d_peer_access,
|
||||
d_pci_address,
|
||||
d_runtime_version,
|
||||
};
|
||||
|
||||
} /* namespace */
|
||||
|
||||
|
||||
|
||||
const DeviceBackend* hip_backend_if_present(void) {
|
||||
int n = 0;
|
||||
hipError_t e = hipGetDeviceCount(&n);
|
||||
if (e != hipSuccess || n <= 0) {
|
||||
/* Supported configuration (host backend); dispatch.cpp logs it at Info. */
|
||||
RAD_DEBUG("device: hipGetDeviceCount -> %s, %d device(s)", hipGetErrorName(e), n);
|
||||
return nullptr;
|
||||
}
|
||||
return &g_hip;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_HAVE_HIP */
|
||||
@@ -0,0 +1,825 @@
|
||||
/* host.cpp -- the host device backend.
|
||||
*
|
||||
* A primary development target, not a fallback: without ROCm the whole engine (builder, planner,
|
||||
* mover, scheduler, KV manager, tokeniser, sampler host reference, server) runs and is tested
|
||||
* through these calls (docs/IMPLEMENTATION.md). It is also where RAD_DOMAIN_HOST kernels run when
|
||||
* the planner puts a layer on the CPU (spec §5.1).
|
||||
*
|
||||
* The streams are real: each is an in-order queue with its own worker thread, and an event is a
|
||||
* sequence number the stream reaches. Inline "async" calls would let ordering bugs (a missing
|
||||
* rad_event_wait, a buffer reused before a copy landed) pass here and corrupt a real device.
|
||||
*
|
||||
* No allocation on the step path: the queue is a fixed-capacity ring of POD tasks, not
|
||||
* std::function, which would heap-allocate inside rad_memcpy_async.
|
||||
*/
|
||||
#include "device.h"
|
||||
#include "../rad_internal.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#include <sys/mman.h>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace rad {
|
||||
namespace {
|
||||
|
||||
using Clock = std::chrono::steady_clock;
|
||||
|
||||
/* Every allocation kind is page-aligned host memory. 4096 is RAD_ALIGN_UNIT and the O_DIRECT
|
||||
* buffer alignment (directio.cpp), so pools here are file-tier targets without a bounce. */
|
||||
constexpr int64_t kAlign = 4096;
|
||||
|
||||
/* Per-stream queue depth: enough that a layer's mover transfers plus compute issues never hit
|
||||
* backpressure, small enough for a ring of a few tens of KiB. Enqueue onto a full ring blocks, as
|
||||
* on a saturated hardware queue. */
|
||||
constexpr size_t kQueueDepth = 1024;
|
||||
|
||||
/* libr4d all-reduce supports at most 8 ranks (spec §9), so more fake devices are useless. */
|
||||
constexpr int kMaxFakeDevices = 8;
|
||||
|
||||
/* ------------------------------------------------------------------ events */
|
||||
|
||||
/* An event is two sequence numbers: `recorded` advances on the host at rad_event_record,
|
||||
* `completed` on the stream worker when it reaches that record. Complete when completed has caught
|
||||
* up, so re-recording makes it pending again, as in HIP.
|
||||
*
|
||||
* `refs` counts the handle plus every queued task naming the event. HIP allows destroying an event
|
||||
* whose record or wait is still queued; freeing it at destroy would leave the worker locking a
|
||||
* freed mutex and wedge the stream. */
|
||||
struct HostEvent {
|
||||
std::mutex m;
|
||||
std::condition_variable cv;
|
||||
uint64_t recorded = 0;
|
||||
uint64_t completed = 0;
|
||||
Clock::time_point stamp{}; /* when the worker reached the most recent record */
|
||||
std::atomic<int> refs{1};
|
||||
bool host = false; /* RAD_EVENT_HOST_WAIT */
|
||||
};
|
||||
|
||||
void event_retain(HostEvent* e) { e->refs.fetch_add(1, std::memory_order_relaxed); }
|
||||
|
||||
/* The last reference, handle or task, frees it. */
|
||||
void event_release(HostEvent* e) {
|
||||
if (e->refs.fetch_sub(1, std::memory_order_acq_rel) == 1) delete e;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ tasks */
|
||||
|
||||
struct Task {
|
||||
enum Kind : uint8_t { Copy, Copy2D, Ranges, Memset, Record, Wait, Stop };
|
||||
Kind kind = Stop;
|
||||
void* dst = nullptr;
|
||||
const void* src = nullptr;
|
||||
int64_t a = 0, b = 0, c = 0, d = 0;
|
||||
const void* aux = nullptr;
|
||||
HostEvent* ev = nullptr;
|
||||
uint64_t seq = 0;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ streams */
|
||||
|
||||
struct HostStream {
|
||||
std::mutex m;
|
||||
std::condition_variable cv_work; /* worker waits on this for a task or a stop */
|
||||
std::condition_variable cv_room; /* producers wait on this when the ring is full */
|
||||
std::condition_variable cv_done; /* rad_stream_sync waits on this */
|
||||
|
||||
std::vector<Task> ring;
|
||||
size_t head = 0; /* next slot to pop */
|
||||
size_t tail = 0; /* next slot to push */
|
||||
size_t count = 0;
|
||||
|
||||
uint64_t submitted = 0; /* tasks ever pushed */
|
||||
uint64_t retired = 0; /* tasks ever finished executing */
|
||||
int gates = 0; /* closed gates (rad_stream_gate) queued on this stream */
|
||||
|
||||
std::thread worker;
|
||||
};
|
||||
|
||||
void stream_run(HostStream* s);
|
||||
|
||||
/* Push one task, blocking while the ring is full. Fails only behind a closed gate: the ring cannot
|
||||
* drain until the host opens it, and the host is the caller. Destroy queues its stop behind
|
||||
* submitted work, so there is no closing state. */
|
||||
int stream_push(HostStream* s, const Task& t) {
|
||||
std::unique_lock<std::mutex> lk(s->m);
|
||||
if (s->count >= s->ring.size() && s->gates > 0) {
|
||||
device_set_error("a submission onto a full stream behind a closed gate: open the gate "
|
||||
"(rad_gate_open) first");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
s->cv_room.wait(lk, [s] { return s->count < s->ring.size(); });
|
||||
s->ring[s->tail] = t;
|
||||
s->tail = (s->tail + 1) % s->ring.size();
|
||||
++s->count;
|
||||
++s->submitted;
|
||||
lk.unlock();
|
||||
s->cv_work.notify_one();
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void stream_run(HostStream* s) {
|
||||
for (;;) {
|
||||
Task t;
|
||||
{
|
||||
std::unique_lock<std::mutex> lk(s->m);
|
||||
s->cv_work.wait(lk, [s] { return s->count > 0; });
|
||||
t = s->ring[s->head];
|
||||
s->head = (s->head + 1) % s->ring.size();
|
||||
--s->count;
|
||||
}
|
||||
s->cv_room.notify_one();
|
||||
|
||||
bool done = false;
|
||||
switch (t.kind) {
|
||||
case Task::Copy:
|
||||
std::memcpy(t.dst, t.src, (size_t)t.a);
|
||||
break;
|
||||
|
||||
case Task::Copy2D:
|
||||
/* a = dpitch, b = spitch, c = width bytes, d = height rows. */
|
||||
for (int64_t r = 0; r < t.d; ++r)
|
||||
std::memcpy((uint8_t*)t.dst + r * t.a, (const uint8_t*)t.src + r * t.b,
|
||||
(size_t)t.c);
|
||||
break;
|
||||
|
||||
case Task::Ranges: {
|
||||
/* a = prefix bytes, b = range count; the list is read now, as the device's is. */
|
||||
std::memcpy(t.dst, t.src, (size_t)t.a);
|
||||
const RadCopyRange* r = (const RadCopyRange*)t.aux;
|
||||
for (int64_t i = 0; i < t.b; ++i)
|
||||
std::memcpy((uint8_t*)t.dst + r[i].dst, (const uint8_t*)t.src + r[i].src,
|
||||
(size_t)r[i].bytes);
|
||||
break;
|
||||
}
|
||||
|
||||
case Task::Memset:
|
||||
std::memset(t.dst, (int)t.a, (size_t)t.b);
|
||||
break;
|
||||
|
||||
case Task::Record: {
|
||||
std::lock_guard<std::mutex> lk(t.ev->m);
|
||||
if (t.seq > t.ev->completed) {
|
||||
t.ev->completed = t.seq;
|
||||
t.ev->stamp = Clock::now();
|
||||
}
|
||||
t.ev->cv.notify_all();
|
||||
break;
|
||||
}
|
||||
|
||||
case Task::Wait: {
|
||||
/* The stream blocks, not a host thread (spec §5.4). Waiting on an event recorded
|
||||
* later on this same stream wedges it, as it would a hardware queue. */
|
||||
std::unique_lock<std::mutex> lk(t.ev->m);
|
||||
t.ev->cv.wait(lk, [&t] { return t.ev->completed >= t.seq; });
|
||||
break;
|
||||
}
|
||||
|
||||
case Task::Stop:
|
||||
done = true;
|
||||
break;
|
||||
}
|
||||
/* After the event lock is released: this may be the last reference. */
|
||||
if (t.ev) event_release(t.ev);
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(s->m);
|
||||
++s->retired;
|
||||
}
|
||||
s->cv_done.notify_all();
|
||||
if (done) return;
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ allocation bookkeeping */
|
||||
|
||||
struct AllocRec {
|
||||
int64_t bytes = 0;
|
||||
int kind = 0;
|
||||
int device = 0;
|
||||
};
|
||||
|
||||
std::mutex& alloc_mutex() { static std::mutex m; return m; }
|
||||
std::unordered_map<void*, AllocRec>& alloc_table() {
|
||||
static std::unordered_map<void*, AllocRec> t;
|
||||
return t;
|
||||
}
|
||||
|
||||
/* Per-device VRAM accounting, so vram_free moves and the planner's fit checks are exercised
|
||||
* (spec §5.3). */
|
||||
std::atomic<int64_t> g_used[kMaxFakeDevices];
|
||||
|
||||
/* A mutex-guarded map is fine: allocation happens at load and pool construction, never inside
|
||||
* rad_arch_step. */
|
||||
void alloc_note(void* p, int64_t bytes, int kind, int device) {
|
||||
std::lock_guard<std::mutex> lk(alloc_mutex());
|
||||
alloc_table()[p] = AllocRec{bytes, kind, device};
|
||||
}
|
||||
|
||||
/* The record of allocation `p`, removed from the table when `take`. */
|
||||
bool alloc_find(void* p, AllocRec* out, bool take = false) {
|
||||
std::lock_guard<std::mutex> lk(alloc_mutex());
|
||||
auto it = alloc_table().find(p);
|
||||
if (it == alloc_table().end()) return false;
|
||||
*out = it->second;
|
||||
if (take) alloc_table().erase(it);
|
||||
return true;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ 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 so the count cannot change under a rank thread. RADIANCE_HOST_DEVICES fakes
|
||||
* several devices in one address space for testing tensor parallel without cards (spec §9). */
|
||||
static int n = [] {
|
||||
int64_t v = env_i64("RADIANCE_HOST_DEVICES", 1);
|
||||
if (v < 1) v = 1;
|
||||
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: one thread per rank, one device per rank (spec §1). */
|
||||
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 fake per-device VRAM budget. Read on every call so a test can change it. Default: half of
|
||||
* physical RAM, split across the fake devices so their sum is loadable. */
|
||||
int64_t host_vram_bytes() {
|
||||
int64_t mib = env_i64("RADIANCE_HOST_VRAM_MIB", 0);
|
||||
if (mib > 0) return mib << 20;
|
||||
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;
|
||||
|
||||
/* Hardware threads split across fake devices, like the budget. */
|
||||
unsigned hw = std::thread::hardware_concurrency();
|
||||
out->n_cu = (int)((hw ? hw : 1u) / (unsigned)host_count());
|
||||
if (out->n_cu < 1) out->n_cu = 1;
|
||||
|
||||
/* A host lane is one element wide. */
|
||||
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;
|
||||
|
||||
/* A CPU has no LDS. Nonzero because budget arithmetic divides by it; a conventional
|
||||
* per-workgroup figure, not a limit host kernels should honour. */
|
||||
out->lds_bytes = 64 * 1024;
|
||||
|
||||
/* All fake devices share one address space. */
|
||||
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 kinds are the same memory here, but the kind is recorded so mismatched frees are
|
||||
* caught. The size is rounded up to whole pages so DirectFile can read an aligned superset
|
||||
* into it without overrunning. */
|
||||
if (posix_memalign(&p, (size_t)kAlign, (size_t)align_up(bytes, kAlign)) != 0 || !p) {
|
||||
device_set_error("rad_dev_alloc(%lld, kind=%d): out of host memory",
|
||||
(long long)bytes, kind);
|
||||
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_find(p, &r, /*take=*/true)) {
|
||||
/* Not ours: freeing it would corrupt the heap, so refuse and warn. */
|
||||
RAD_WARN("rad_dev_free(%p, kind=%d): pointer was not allocated by the device layer",
|
||||
p, kind);
|
||||
return;
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
/* Host and device views are the same pointer (spec §5.1 zero-copy is trivial here). Null for a
|
||||
* pointer the device layer did not allocate. */
|
||||
void* h_host_ptr(void* p) {
|
||||
if (!p) return nullptr;
|
||||
AllocRec r;
|
||||
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 ignored: raising a thread's scheduling class needs privileges and buys nothing
|
||||
* on a one-thread queue. */
|
||||
(void)high_priority;
|
||||
auto* s = new (std::nothrow) HostStream();
|
||||
if (!s) { device_set_error("rad_stream_create: out of memory"); return RAD_E_NOMEM; }
|
||||
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 submitted work, so destroy drains rather than discards. */
|
||||
stream_push(s, t);
|
||||
if (s->worker.joinable()) s->worker.join();
|
||||
delete s;
|
||||
}
|
||||
|
||||
int h_stream_sync(RadStream st) {
|
||||
if (!st) {
|
||||
device_set_error("rad_stream_sync: null stream");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
auto* s = (HostStream*)st;
|
||||
std::unique_lock<std::mutex> lk(s->m);
|
||||
if (s->gates > 0) {
|
||||
device_set_error("rad_stream_sync: the stream waits at a closed gate, which only "
|
||||
"rad_gate_open releases");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
/* Waits only for work submitted before this call, as hipStreamSynchronize does; the
|
||||
* scheduler relies on sync returning while another thread keeps pushing. */
|
||||
const uint64_t target = s->submitted;
|
||||
s->cv_done.wait(lk, [s, target] { return s->retired >= target; });
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* RAD_EVENT_LOCAL is meaningless here; RAD_EVENT_HOST_WAIT is kept so event_sync refuses events
|
||||
* created without it, as on a card. */
|
||||
int h_event_create(RadEvent* out, unsigned flags) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
auto* e = new (std::nothrow) HostEvent();
|
||||
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; queued tasks keep the event alive (see HostEvent). */
|
||||
void h_event_destroy(RadEvent ev) { if (ev) event_release((HostEvent*)ev); }
|
||||
|
||||
int h_event_record(RadEvent ev, RadStream st) {
|
||||
if (!ev || !st) {
|
||||
device_set_error("rad_event_record: null %s", ev ? "stream" : "event");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
auto* e = (HostEvent*)ev;
|
||||
uint64_t seq;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(e->m);
|
||||
seq = ++e->recorded; /* pending from this instant, on the host, before the push */
|
||||
}
|
||||
Task t;
|
||||
t.kind = Task::Record;
|
||||
t.ev = e;
|
||||
t.seq = seq;
|
||||
event_retain(e);
|
||||
return stream_push((HostStream*)st, t);
|
||||
}
|
||||
|
||||
int h_event_wait(RadStream st, RadEvent ev) {
|
||||
if (!ev || !st) {
|
||||
device_set_error("rad_event_wait: null %s", ev ? "stream" : "event");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
auto* e = (HostEvent*)ev;
|
||||
uint64_t target;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(e->m);
|
||||
target = e->recorded;
|
||||
}
|
||||
/* Waiting on a never-recorded event is a no-op, matching hipStreamWaitEvent; the mover relies
|
||||
* on it. */
|
||||
if (target == 0) return RAD_OK;
|
||||
Task t;
|
||||
t.kind = Task::Wait;
|
||||
t.ev = e;
|
||||
t.seq = target;
|
||||
event_retain(e);
|
||||
return stream_push((HostStream*)st, t);
|
||||
}
|
||||
|
||||
int h_event_query(RadEvent ev) {
|
||||
if (!ev) return RAD_E_INVAL;
|
||||
auto* e = (HostEvent*)ev;
|
||||
std::lock_guard<std::mutex> lk(e->m);
|
||||
return e->completed >= e->recorded ? 1 : 0;
|
||||
}
|
||||
|
||||
/* Host kernels read host memory directly, so there is nothing to make visible. */
|
||||
void h_host_wrote(void) {}
|
||||
|
||||
int h_event_sync(RadEvent ev) {
|
||||
if (!ev) return RAD_E_INVAL;
|
||||
auto* e = (HostEvent*)ev;
|
||||
if (!e->host) {
|
||||
device_set_error("rad_event_sync: the event was made without RAD_EVENT_HOST_WAIT");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
std::unique_lock<std::mutex> lk(e->m);
|
||||
const uint64_t target = e->recorded;
|
||||
e->cv.wait(lk, [e, target] { return e->completed >= target; });
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int h_event_elapsed_ms(RadEvent a, RadEvent b, float* out) {
|
||||
if (!a || !b || !out) return RAD_E_INVAL;
|
||||
/* An event's stamp, if it was recorded and has completed. */
|
||||
auto stamp = [](RadEvent ev, Clock::time_point* t) {
|
||||
auto* e = (HostEvent*)ev;
|
||||
std::lock_guard<std::mutex> lk(e->m);
|
||||
if (e->recorded == 0 || e->completed < e->recorded) return false;
|
||||
*t = e->stamp;
|
||||
return true;
|
||||
};
|
||||
Clock::time_point ta, tb;
|
||||
if (!stamp(a, &ta) || !stamp(b, &tb)) return RAD_E_STATE;
|
||||
*out = std::chrono::duration<float, std::milli>(tb - ta).count();
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* A null stream is refused on both backends. HIP's stream 0 implicitly synchronises with every
|
||||
* blocking stream, which spec §5.4 forbids for transfers; accepting it here would hide such a
|
||||
* caller until it ran on a card. */
|
||||
int check_stream(RadStream s, const char* who) {
|
||||
if (s) return RAD_OK;
|
||||
device_set_error("%s: null stream -- radiance does not use the default stream, "
|
||||
"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"));
|
||||
/* The card's copy kernel moves 16-byte pieces (aql.cpp, a_memcpy_ranges_async), so the same
|
||||
* calls are refused here: a caller passing the host suite must run on a card. Whether the
|
||||
* memory is pinned cannot be told on this backend. */
|
||||
if (!dst || !src || prefix < 0 || (prefix & 15) || n < 0 || (n > 0 && !ranges)) {
|
||||
device_set_error("rad_memcpy_ranges_async(%p <- %p, prefix %lld (a multiple of 16), %d "
|
||||
"ranges): invalid argument", dst, src, (long long)prefix, n);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (prefix == 0 && n == 0) return RAD_OK;
|
||||
if (((uintptr_t)dst | (uintptr_t)src) & 15) {
|
||||
device_set_error("rad_memcpy_ranges_async(%p <- %p): both bases must be 16-byte aligned",
|
||||
dst, src);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
Task t;
|
||||
t.kind = Task::Ranges;
|
||||
t.dst = dst;
|
||||
t.src = src;
|
||||
t.a = prefix;
|
||||
t.b = n;
|
||||
t.aux = ranges;
|
||||
return stream_push((HostStream*)st, t);
|
||||
}
|
||||
|
||||
/* One copy task per segment, in list order. The list is read at the call, as on the device. */
|
||||
int h_memcpy_list_async(const RadCopySeg* segs, int n, unsigned, RadStream st) {
|
||||
RAD_TRY(check_stream(st, "rad_memcpy_list_async"));
|
||||
if (n < 0 || (n > 0 && !segs)) {
|
||||
device_set_error("rad_memcpy_list_async: %d segments at %p", n, (const void*)segs);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
for (int i = 0; i < n; ++i) RAD_TRY(h_memcpy_async(segs[i].dst, segs[i].src, segs[i].bytes, st));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ gates */
|
||||
/* A gate is a wait task on an event whose one record only the host completes: recorded is 1 from
|
||||
* the start and rad_gate_open sets completed. The task holds a reference, so the event outlives
|
||||
* the handle until the worker has passed it. */
|
||||
struct HostGate {
|
||||
HostEvent* e = nullptr;
|
||||
HostStream* s = nullptr;
|
||||
};
|
||||
|
||||
int h_stream_gate(RadStream st, void** out) {
|
||||
RAD_TRY(check_stream(st, "rad_stream_gate"));
|
||||
if (!out) return RAD_E_INVAL;
|
||||
auto* s = (HostStream*)st;
|
||||
auto* e = new (std::nothrow) HostEvent();
|
||||
auto* g = new (std::nothrow) HostGate();
|
||||
if (!e || !g) {
|
||||
delete e;
|
||||
delete g;
|
||||
device_set_error("rad_stream_gate: out of memory");
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
e->recorded = 1;
|
||||
Task t;
|
||||
t.kind = Task::Wait;
|
||||
t.ev = e;
|
||||
t.seq = 1;
|
||||
event_retain(e);
|
||||
const int rc = stream_push(s, t);
|
||||
if (rc < 0) {
|
||||
event_release(e);
|
||||
event_release(e);
|
||||
delete g;
|
||||
return rc;
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(s->m);
|
||||
++s->gates;
|
||||
}
|
||||
g->e = e;
|
||||
g->s = s;
|
||||
*out = g;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int h_gate_open(void* p) {
|
||||
auto* g = (HostGate*)p;
|
||||
if (!g || !g->e) return RAD_E_INVAL;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g->e->m);
|
||||
g->e->completed = 1;
|
||||
}
|
||||
g->e->cv.notify_all();
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g->s->m);
|
||||
--g->s->gates;
|
||||
}
|
||||
event_release(g->e);
|
||||
delete g;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int64_t h_gate_room(RadStream st) {
|
||||
if (!st) return 0;
|
||||
auto* s = (HostStream*)st;
|
||||
std::lock_guard<std::mutex> lk(s->m);
|
||||
return (int64_t)(s->ring.size() - s->count);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ elastic memory */
|
||||
/* Elastic memory via mmap, the same mechanism as the card's VMM: PROT_NONE reserves address space
|
||||
* without pages, MAP_FIXED read/write backs a granule, and PROT_NONE over it returns the pages.
|
||||
* Decommitted ranges come back zeroed and addresses never move, as on the HIP path.
|
||||
*
|
||||
* The granule is the pool alignment (the card's 2 MiB), not the 4 KiB page, so pool sizing that
|
||||
* passes here does not strand memory on a card. */
|
||||
constexpr int64_t kVmemGranule = RAD_ALIGN_POOL;
|
||||
|
||||
int64_t h_vmem_granularity(void) { return kVmemGranule; }
|
||||
|
||||
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 and unmap the head and tail, so the range is exactly
|
||||
* [base, base+bytes) and release is one munmap with no side table. */
|
||||
const size_t raw_len = (size_t)(bytes + align);
|
||||
void* raw = ::mmap(nullptr, raw_len, PROT_NONE,
|
||||
MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
|
||||
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 rather than munmap: a hole in the reservation could be handed to an unrelated
|
||||
* mmap. */
|
||||
void* p = ::mmap(addr, (size_t)bytes, PROT_NONE,
|
||||
MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
|
||||
if (p != addr) {
|
||||
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;
|
||||
}
|
||||
|
||||
/* Commit already maps read/write, so this is a no-op mprotect. It is implemented anyway so the
|
||||
* host suite exercises the ranges VMem computes for the card. */
|
||||
int h_vmem_protect(void* addr, int64_t bytes) {
|
||||
if (!addr || bytes <= 0) return RAD_E_INVAL;
|
||||
if (::mprotect(addr, (size_t)bytes, PROT_READ | PROT_WRITE) != 0) {
|
||||
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 >= host_count()) 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,
|
||||
h_memcpy_list_async,
|
||||
nullptr, nullptr, /* no DMA engine, so no link to hold */
|
||||
/* No recorded passes: host streams run work as issued. */
|
||||
nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
|
||||
|
||||
/* Elastic memory: see above. */
|
||||
h_vmem_granularity, h_vmem_reserve, h_vmem_release, h_vmem_commit, h_vmem_decommit,
|
||||
h_vmem_protect,
|
||||
|
||||
h_vram_used,
|
||||
nullptr, nullptr, /* no device code to register */
|
||||
nullptr, nullptr, /* not integrated graphics; one address space */
|
||||
nullptr, nullptr, nullptr, /* no PCI address, runtime or DMA engine */
|
||||
/* No expert prefetch. */
|
||||
nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
|
||||
|
||||
h_stream_gate, h_gate_open, h_gate_room,
|
||||
};
|
||||
|
||||
} /* namespace */
|
||||
|
||||
const DeviceBackend* host_backend(void) { return &g_host; }
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,439 @@
|
||||
/* checks.cpp -- what in the configuration or on the machine costs speed or correctness, and what to
|
||||
* do about it.
|
||||
*
|
||||
* Each check is a pure function of the facts (no file or device access), so tests pass a machine
|
||||
* described in a struct. A finding states what was seen with numbers, why it matters, and a fix.
|
||||
*
|
||||
* Warn: a cost or risk to act on. Note: a trade-off, or worth knowing when reading a benchmark.
|
||||
* Load-dependent findings (a parked link) are raised only when the card was busy, since an idle
|
||||
* PCIe link parks at its lowest speed by design.
|
||||
*/
|
||||
#include "diag/diag.h"
|
||||
#include "rad_internal.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdlib>
|
||||
#include <map>
|
||||
#include <set>
|
||||
|
||||
namespace rad {
|
||||
namespace diag {
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int64_t kGiB = (int64_t)1 << 30;
|
||||
constexpr int64_t kMiB = (int64_t)1 << 20;
|
||||
|
||||
void add(std::vector<Finding>* out, Finding::Level lv, const char* id, std::string what,
|
||||
std::string why, std::string fix) {
|
||||
Finding f;
|
||||
f.level = lv;
|
||||
f.id = id;
|
||||
f.what = std::move(what);
|
||||
f.why = std::move(why);
|
||||
f.fix = std::move(fix);
|
||||
out->push_back(std::move(f));
|
||||
}
|
||||
|
||||
std::vector<const CardFacts*> served(const Facts& f) {
|
||||
std::vector<const CardFacts*> out;
|
||||
for (const CardFacts& c : f.cards)
|
||||
if (c.rank >= 0) out.push_back(&c);
|
||||
std::sort(out.begin(), out.end(),
|
||||
[](const CardFacts* a, const CardFacts* b) { return a->rank < b->rank; });
|
||||
return out;
|
||||
}
|
||||
|
||||
/* Whether the serving cards' DMA is translated: from their IOMMU groups where known, else the
|
||||
* machine's mode. */
|
||||
bool translated(const Facts& f) {
|
||||
bool any = false, dma = false;
|
||||
for (const CardFacts* c : served(f)) {
|
||||
if (c->iommu_type.empty()) continue;
|
||||
any = true;
|
||||
if (c->iommu_type != "identity") dma = true;
|
||||
}
|
||||
return any ? dma : f.host.iommu == "translated";
|
||||
}
|
||||
|
||||
/* An amdgpu device with at least 4 GiB of VRAM. Excludes small iGPU carve-outs, includes an APU
|
||||
* configured with tens of GiB. */
|
||||
bool servable_gpu(const CardFacts& c) {
|
||||
return c.vendor == "0x1002" && c.driver == "amdgpu" && c.vram_total >= ((int64_t)4 << 30);
|
||||
}
|
||||
|
||||
std::string card_name(const CardFacts& c) {
|
||||
return c.rank >= 0 ? fmt("card %s (rank %d)", c.bdf.c_str(), c.rank) : "card " + c.bdf;
|
||||
}
|
||||
|
||||
std::string hop_link(const PciHop& h, bool cur) {
|
||||
return cur ? link_text(h.cur_speed, h.cur_width) : link_text(h.max_speed, h.max_width);
|
||||
}
|
||||
|
||||
/* ---- the link ------------------------------------------------------------------------------ */
|
||||
|
||||
/* A hop below its own maximum while the card is busy: link power management stuck a level down,
|
||||
* or a link retrained narrower. Every hop is checked, because the card's endpoint can read full
|
||||
* speed while the root port above an on-card switch runs at half. */
|
||||
void check_link_under_load(const Facts& f, std::vector<Finding>* out) {
|
||||
for (const CardFacts* c : served(f)) {
|
||||
if (c->busy_percent < kBusyPercent) continue;
|
||||
for (const PciHop& h : c->chain) {
|
||||
const double cur = link_gts(h.cur_speed), mx = link_gts(h.max_speed);
|
||||
const bool slow = cur > 0 && mx > 0 && cur < mx;
|
||||
const bool narrow = h.cur_width > 0 && h.max_width > 0 && h.cur_width < h.max_width;
|
||||
if (!slow && !narrow) continue;
|
||||
add(out, Finding::Warn, "link-below-max",
|
||||
fmt("%s: the PCIe link at %s runs %s of its %s while the card is %d%% busy",
|
||||
card_name(*c).c_str(), h.bdf.c_str(), hop_link(h, true).c_str(),
|
||||
hop_link(h, false).c_str(), c->busy_percent),
|
||||
"every copy between host memory and the card -- experts streamed from the host "
|
||||
"pool, the all-reduce through host memory, the embedding read in place -- and "
|
||||
"every kernel launch's packet fetch cross this link, so the card serves at the "
|
||||
"slower link's rate and a tensor-parallel step waits for it",
|
||||
"a link stuck one level down after long uptime has been cleared by a reboot; "
|
||||
"check that it recovers under load (GET /diagnostics during a long prefill), and "
|
||||
"reseat or move the card if it trains narrow");
|
||||
break;
|
||||
}
|
||||
if (c->dpm_pcie_cur >= 0 && c->dpm_pcie_cur + 1 < (int)c->dpm_pcie.size())
|
||||
add(out, Finding::Warn, "link-dpm-below-top",
|
||||
fmt("%s: the card's PCIe power level is %s, not its top level %s, while it is "
|
||||
"%d%% busy", card_name(*c).c_str(), c->dpm_pcie[(size_t)c->dpm_pcie_cur].c_str(),
|
||||
c->dpm_pcie.back().c_str(), c->busy_percent),
|
||||
"the SMU picks the link's speed from this table; a level below the top under load "
|
||||
"is half the host bandwidth or less",
|
||||
"a reboot has cleared a level stuck after long uptime; pp_dpm_pcie can pin a level "
|
||||
"(echo 2 | sudo tee /sys/class/drm/CARD/device/pp_dpm_pcie with "
|
||||
"power_dpm_force_performance_level manual), with the server stopped");
|
||||
}
|
||||
}
|
||||
|
||||
/* A hop whose maximum is below the card's (older slot, riser, lane split). Often the board's
|
||||
* design, not a fault; a Note. */
|
||||
void check_link_capped(const Facts& f, std::vector<Finding>* out) {
|
||||
for (const CardFacts* c : served(f)) {
|
||||
if (c->chain.size() < 2) continue;
|
||||
const PciHop& ep = c->chain.back();
|
||||
const double card = link_gts(ep.max_speed);
|
||||
for (size_t i = 0; i + 1 < c->chain.size(); ++i) {
|
||||
const PciHop& h = c->chain[i];
|
||||
const double mx = link_gts(h.max_speed);
|
||||
const bool slower = mx > 0 && card > 0 && mx < card;
|
||||
const bool narrower = h.max_width > 0 && ep.max_width > 0 && h.max_width < ep.max_width;
|
||||
if (!slower && !narrower) continue;
|
||||
add(out, Finding::Note, "link-capped",
|
||||
fmt("%s: the card's link is %s at most, and %s above it is %s at most",
|
||||
card_name(*c).c_str(), hop_link(ep, false).c_str(), h.bdf.c_str(),
|
||||
hop_link(h, false).c_str()),
|
||||
"the host side of the link bounds what the card can move to and from host memory: "
|
||||
"streamed experts, the host pool and the all-reduce when it goes through host memory",
|
||||
"a slot with the card's full width and speed (the board manual says which slots "
|
||||
"share lanes), or no riser; nothing to do if the board has no faster slot");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- the cards against each other ----------------------------------------------------------- */
|
||||
|
||||
/* A tensor-parallel step ends when its slowest rank does, so differently configured cards serve
|
||||
* at the slower one's pace. */
|
||||
void check_cards_differ(const Facts& f, std::vector<Finding>* out) {
|
||||
const auto cs = served(f);
|
||||
if (cs.size() < 2) return;
|
||||
std::vector<std::string> diffs;
|
||||
auto field = [&](const char* what, auto get, auto show) {
|
||||
std::map<std::string, std::vector<std::string>> by;
|
||||
for (const CardFacts* c : cs) by[show(get(*c))].push_back(c->bdf);
|
||||
if (by.size() < 2) return;
|
||||
std::string d = std::string(what) + ":";
|
||||
for (const auto& [v, bdfs] : by) {
|
||||
d += " " + v + " on";
|
||||
for (const std::string& b : bdfs) d += " " + b;
|
||||
d += ";";
|
||||
}
|
||||
d.pop_back();
|
||||
diffs.push_back(d);
|
||||
};
|
||||
auto str = [](const std::string& s) { return s.empty() ? std::string("unknown") : s; };
|
||||
field("root port link", [](const CardFacts& c) {
|
||||
return c.chain.empty() ? std::string() : hop_link(c.chain.front(), false); }, str);
|
||||
field("power cap", [](const CardFacts& c) { return c.power_cap_uw; },
|
||||
watts_text);
|
||||
field("voltage offset", [](const CardFacts& c) { return c.vddgfx_offset; }, str);
|
||||
field("top PCIe power level", [](const CardFacts& c) {
|
||||
return c.dpm_pcie.empty() ? std::string() : c.dpm_pcie.back(); }, str);
|
||||
field("runtime power management", [](const CardFacts& c) { return c.runtime_control; }, str);
|
||||
field("target", [](const CardFacts& c) { return c.gfx; }, str);
|
||||
if (diffs.empty()) return;
|
||||
std::string what = "the cards serving this model are not set up alike -- ";
|
||||
for (size_t i = 0; i < diffs.size(); ++i) what += (i ? "; " : "") + diffs[i];
|
||||
add(out, Finding::Warn, "cards-differ", what,
|
||||
"a tensor-parallel step waits for its slowest rank in every all-reduce, so the whole "
|
||||
"server runs at the pace of the card with the lower limit or the slower link",
|
||||
"make the settings match (the power cap and voltage offset are per card under "
|
||||
"/sys/class/drm/cardN/device; set them with the server stopped)");
|
||||
}
|
||||
|
||||
/* A power cap below the card's default. Compared to the default, not the maximum: stock cards
|
||||
* ship below the board maximum (300 W of 330 W on an R9700). */
|
||||
void check_power_cap(const Facts& f, std::vector<Finding>* out) {
|
||||
for (const CardFacts* c : served(f)) {
|
||||
if (c->power_cap_uw <= 0 || c->power_cap_default_uw <= 0) continue;
|
||||
if (c->power_cap_uw >= c->power_cap_default_uw) continue;
|
||||
add(out, Finding::Note, "power-cap-below-default",
|
||||
fmt("%s: the power cap is %lld W, below the card's default of %lld W",
|
||||
card_name(*c).c_str(), (long long)(c->power_cap_uw / 1000000),
|
||||
(long long)(c->power_cap_default_uw / 1000000)),
|
||||
"under a sustained load the power cap is what sets the clock on these cards "
|
||||
"(scripts/cardclock.py shows which limit binds)",
|
||||
fmt("echo %lld | sudo tee /sys/class/drm/%s/device/hwmon/hwmon*/power1_cap restores "
|
||||
"the default, with the server stopped; nothing to do if the cap was lowered on "
|
||||
"purpose", (long long)c->power_cap_default_uw,
|
||||
c->drm.empty() ? "cardN" : c->drm.c_str()));
|
||||
}
|
||||
}
|
||||
|
||||
void check_small_bar(const Facts& f, std::vector<Finding>* out) {
|
||||
for (const CardFacts* c : served(f)) {
|
||||
if (c->vram_visible <= 0 || c->vram_total <= 0) continue;
|
||||
if (c->vram_visible * 10 >= c->vram_total * 9) continue;
|
||||
add(out, Finding::Warn, "small-bar",
|
||||
fmt("%s: the host and the other cards see %s of its %s of VRAM", card_name(*c).c_str(),
|
||||
humanb(c->vram_visible).c_str(), humanb(c->vram_total).c_str()),
|
||||
"without Resizable BAR a peer can address only a window of the card's memory, which "
|
||||
"limits peer-to-peer collectives and copies into VRAM from the host",
|
||||
"enable Resizable BAR (\"Re-Size BAR Support\" and \"Above 4G Decoding\") in the "
|
||||
"firmware setup");
|
||||
}
|
||||
}
|
||||
|
||||
/* Overdrive offset with runtime suspend enabled. The driver re-uploads the offset on every resume,
|
||||
* and on RDNA4 that upload can fail ("Failed to upload customized OD settings"). Whether the
|
||||
* firmware kept it is not readable here; a card that lost it clocks lower at the same cap. */
|
||||
void check_od_runtime_pm(const Facts& f, std::vector<Finding>* out) {
|
||||
for (const CardFacts* c : served(f)) {
|
||||
if (c->vddgfx_offset.empty() || c->vddgfx_offset == "0 mV") continue;
|
||||
if (c->runtime_control != "auto") continue;
|
||||
add(out, Finding::Note, "od-runtime-suspend",
|
||||
fmt("%s: a voltage offset of %s is set and the card runtime-suspends when idle "
|
||||
"(power/control auto)", card_name(*c).c_str(), c->vddgfx_offset.c_str()),
|
||||
"the driver re-uploads overdrive settings on every resume and can fail to (\"Failed "
|
||||
"to upload customized OD settings\" in the kernel log); a card that resumed without "
|
||||
"its offset clocks lower at the same power cap, and in a tensor-parallel world sets "
|
||||
"the pace for every card",
|
||||
fmt("echo on | sudo tee /sys/bus/pci/devices/%s/power/control keeps it resumed; check "
|
||||
"`journalctl -k | grep -i overdrive` for failed uploads", c->bdf.c_str()));
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- the host ------------------------------------------------------------------------------- */
|
||||
|
||||
void check_cwsr(const Facts& f, std::vector<Finding>* out) {
|
||||
if (f.host.cwsr_enable != 0) return;
|
||||
add(out, Finding::Warn, "cwsr-off", "amdgpu cwsr_enable is 0",
|
||||
"the driver cannot preempt a running queue: any queue eviction (host memory the card maps, "
|
||||
"moved under memory pressure) waits for a queue a serve never lets drain, and ends in a "
|
||||
"GPU hang and reset",
|
||||
"amdgpu.cwsr_enable=1 as a module option, then rebuild the initramfs and reboot");
|
||||
}
|
||||
|
||||
void check_huge_pages(const Facts& f, const RunFacts& r, std::vector<Finding>* out) {
|
||||
if (f.host.thp_enabled != "never") return;
|
||||
if (r.host_pool_mib <= 0 && r.pinned_bytes < kGiB) return;
|
||||
const bool tr = translated(f);
|
||||
add(out, tr ? Finding::Warn : Finding::Note, "thp-never",
|
||||
"transparent huge pages are off (/sys/kernel/mm/transparent_hugepage/enabled is never), so "
|
||||
"every pinned range is 4 KiB pages",
|
||||
tr ? "with an IOMMU translating the cards' reads each page is a translation of its "
|
||||
"own; a host pool streamed at 4 KiB pages measured 10-21% slower prefill"
|
||||
: "with the IOMMU in passthrough the page size has not measured slower; it "
|
||||
"matters as soon as the IOMMU translates",
|
||||
"echo madvise | sudo tee /sys/kernel/mm/transparent_hugepage/enabled (or "
|
||||
"transparent_hugepage=madvise on the kernel command line)");
|
||||
}
|
||||
|
||||
void check_iommu(const Facts& f, const RunFacts& r, std::vector<Finding>* out) {
|
||||
if (!translated(f)) return;
|
||||
if (r.host_weight_bytes <= 0 && r.host_pool_mib <= 0 && r.tp < 2) return;
|
||||
std::string groups;
|
||||
for (const CardFacts* c : served(f))
|
||||
if (!c->iommu_type.empty()) groups += (groups.empty() ? "" : ", ") + c->bdf + " " + c->iommu_type;
|
||||
add(out, Finding::Note, "iommu-translated",
|
||||
"the IOMMU translates the cards' DMA (" + (groups.empty() ? f.host.iommu_why : groups) + ")",
|
||||
"every read a card makes of host memory -- the host pool, the embedding in RAM, the "
|
||||
"all-reduce through host memory -- goes through an IOMMU translation; with huge pages that "
|
||||
"is cheap, at 4 KiB pages it measured 10-21% prefill",
|
||||
std::string("iommu=pt on the kernel command line (amd_iommu=pt / intel_iommu=pt), if "
|
||||
"nothing on the machine needs DMA isolation; otherwise keep transparent huge "
|
||||
"pages at madvise or always") +
|
||||
(r.tp > 1 ? "; with more than one card, check that peer access survives the change "
|
||||
"(--p2p on refuses to start without it): iommu=pt removed it on an Intel "
|
||||
"VT-d host (GUIDE §7.2)"
|
||||
: ""));
|
||||
}
|
||||
|
||||
void check_memory(const Facts& f, const RunFacts& r, std::vector<Finding>* out) {
|
||||
const HostFacts& h = f.host;
|
||||
if (h.mem_available >= 0 && h.mem_total > 0 &&
|
||||
(h.mem_available < 2 * kGiB || h.mem_available * 20 < h.mem_total))
|
||||
add(out, Finding::Warn, "memory-low",
|
||||
fmt("%s of %s of RAM is available after startup", humanb(h.mem_available).c_str(),
|
||||
humanb(h.mem_total).c_str()),
|
||||
"the page cache is what a container read in place and the n-gram rows read from disk "
|
||||
"come through; with it starved every step waits on the drive, and the kernel starts "
|
||||
"reclaiming and swapping",
|
||||
"lower --host-pool-mib or --prefix-cache-mib, or stop what else holds memory");
|
||||
if (h.swap_total > 0 && h.swap_free >= 0 && h.swap_total - h.swap_free > 256 * kMiB)
|
||||
add(out, Finding::Note, "swap-in-use",
|
||||
fmt("%s of swap is in use", humanb(h.swap_total - h.swap_free).c_str()),
|
||||
"a host thread that faults on a swapped page stalls the step it is part of",
|
||||
"free memory, or turn swap off on a machine that only serves");
|
||||
if (h.cgroup_mem_limit > 0 && h.mem_total > 0 && h.cgroup_mem_limit < h.mem_total &&
|
||||
r.pinned_bytes > 0 && r.pinned_bytes * 10 > h.cgroup_mem_limit * 8)
|
||||
add(out, Finding::Warn, "cgroup-limit",
|
||||
fmt("the container's memory limit is %s and the process pins %s",
|
||||
humanb(h.cgroup_mem_limit).c_str(), humanb(r.pinned_bytes).c_str()),
|
||||
"pinned memory counts against the limit and cannot be reclaimed; what is left is all "
|
||||
"the page cache and the process's own allocations get before the OOM killer",
|
||||
"raise the container's memory limit or lower the pools");
|
||||
}
|
||||
|
||||
void check_memlock(const Facts& f, const RunFacts& r, std::vector<Finding>* out) {
|
||||
if (f.host.memlock_soft == -2 || f.host.memlock_soft < 0) return;
|
||||
if (r.locked_bytes > 0 || r.ngram_placement != "disk") return;
|
||||
add(out, Finding::Note, "memlock-limited",
|
||||
fmt("RLIMIT_MEMLOCK is %s and the n-gram table is read from the container on disk",
|
||||
humanb(f.host.memlock_soft).c_str()),
|
||||
"a locked copy of the table in RAM is one of the faster tiers, and the memlock limit is "
|
||||
"one of the things that keeps --ngram-placement auto off it",
|
||||
"Docker: ulimits memlock -1 (--ulimit memlock=-1); systemd: LimitMEMLOCK=infinity");
|
||||
}
|
||||
|
||||
void check_cpu(const Facts& f, std::vector<Finding>* out) {
|
||||
const HostFacts& h = f.host;
|
||||
if (h.cpu_governor.empty() || h.cpu_governor == "performance") return;
|
||||
if (h.cpu_governor == "powersave" && h.cpu_epp == "performance") return;
|
||||
if (h.cpu_governor == "schedutil") return;
|
||||
add(out, Finding::Note, "cpu-governor",
|
||||
fmt("the CPU governor is %s%s", h.cpu_governor.c_str(),
|
||||
h.cpu_epp.empty() ? "" : (" with energy preference " + h.cpu_epp).c_str()),
|
||||
"the host side of a step -- scheduling, sampling, the n-gram gather, launch bookkeeping -- "
|
||||
"is single-threaded per rank, and a core that ramps slowly shows as host gap between steps",
|
||||
"cpupower frequency-set -g performance, or echo performance | sudo tee "
|
||||
"/sys/devices/system/cpu/cpu*/cpufreq/energy_performance_preference");
|
||||
}
|
||||
|
||||
/* ---- the engine ----------------------------------------------------------------------------- */
|
||||
|
||||
void check_engine(const Facts& f, const RunFacts& r, std::vector<Finding>* out) {
|
||||
std::string gpus;
|
||||
for (const CardFacts& c : f.cards)
|
||||
if (servable_gpu(c))
|
||||
gpus += (gpus.empty() ? "" : ", ") + c.bdf + (c.gfx.empty() ? "" : " " + c.gfx);
|
||||
if (r.host_backend && !gpus.empty())
|
||||
add(out, Finding::Warn, "host-backend",
|
||||
"the engine serves on the CPU although this machine has an AMD GPU (" + gpus + ")",
|
||||
r.device_build ? "the device runtime found no card it could use, so every op runs on the host"
|
||||
: "this build has no device runtime (built without HIP), so every op runs "
|
||||
"on the host",
|
||||
r.device_build
|
||||
? "the device lines at the top of the log say why: /dev/kfd and /dev/dri must be "
|
||||
"passed to a container with the render and video groups, ROCm must support the "
|
||||
"card, and HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES must not hide it"
|
||||
: "build with ROCm (RAD_WITH_HIP=ON, hipcc on the PATH), or run the image");
|
||||
for (const std::string& why : r.ignored)
|
||||
add(out, Finding::Note, "device-ignored", "a device was left out: " + why,
|
||||
"a rank placed on a slower or different card would set the pace of every step",
|
||||
"ROCR_VISIBLE_DEVICES names the cards to use explicitly");
|
||||
if (r.tp > 1 && r.p2p == 0 && !r.p2p_forced_off)
|
||||
add(out, Finding::Note, "p2p-off",
|
||||
"the cards cannot reach each other's memory directly" +
|
||||
(r.p2p_blocked.empty() ? std::string() : " (" + r.p2p_blocked + ")"),
|
||||
"the collectives exchange through pinned host memory, which crosses each card's link "
|
||||
"twice",
|
||||
"peer access needs Resizable BAR and the cards under one root complex; whether the "
|
||||
"IOMMU's mode allows it depends on the platform -- iommu=pt removed it on an Intel "
|
||||
"VT-d host (GUIDE §7.2) -- so check `--p2p on`, which refuses to start without it, "
|
||||
"before and after changing the mode");
|
||||
if (r.tp > 1 && r.tp_wire_lossy)
|
||||
add(out, Finding::Note, "tp-wire-lossy",
|
||||
fmt("--tp-wire wht6: all-reduce messages from %lld KiB up carry a quantised payload",
|
||||
(long long)r.tp_wire_min_kb),
|
||||
"faster prefill, but the model does not compute the exact function; two runs on "
|
||||
"different world sizes are not comparable token for token",
|
||||
"--tp-wire exact when exactness matters more than prefill speed");
|
||||
/* Only when the operator turned it off; an engine-side reason is shown in the configuration. */
|
||||
if (!r.prefix_cache && r.prefix_cache_off_why.empty())
|
||||
add(out, Finding::Note, "prefix-cache-off", "prefix caching is off (--no-prefix-cache)",
|
||||
"every request prefills its whole prompt, including the conversation it shares with "
|
||||
"the turn before",
|
||||
"drop --no-prefix-cache");
|
||||
if (r.host_weight_bytes > 0)
|
||||
add(out, Finding::Note, "experts-from-host",
|
||||
fmt("%s of weights a rank live in the pinned host pool and cross PCIe when they are "
|
||||
"used", humanb(r.host_weight_bytes).c_str()),
|
||||
"a prefill step streams every routed layer's pooled experts onto the card, so its speed "
|
||||
"is bounded by the link; decode reads the ones it routes to",
|
||||
"more VRAM for the experts: a shorter --max-model-len or fewer --max-num-seqs, "
|
||||
"--embedding-placement ram, --kv-cache-dtype fp8, or more cards (--tp)");
|
||||
if (r.file_weight_bytes > 0)
|
||||
add(out, Finding::Warn, "weights-from-disk",
|
||||
fmt("%s of weights a rank are read from the container on disk as they are needed",
|
||||
humanb(r.file_weight_bytes).c_str()),
|
||||
"a step that needs them is paced by the drive",
|
||||
"a larger --host-pool-mib (if RAM allows) or more VRAM for the weights");
|
||||
if (r.reference_kernels)
|
||||
add(out, Finding::Warn, "reference-kernels",
|
||||
"--debug-accept-reference-kernels: ops may run on the reference implementation",
|
||||
"the reference library is an oracle, orders of magnitude slower than a device kernel",
|
||||
"install a kernel library for this card and drop the flag");
|
||||
if (r.profile_ops)
|
||||
add(out, Finding::Warn, "profile-ops",
|
||||
"--profile-ops times every op, which restores synchronisations",
|
||||
"the run is slower and its numbers are not comparable against an unprofiled one",
|
||||
"drop --profile-ops for anything measured");
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
std::vector<Finding> check(const Facts& f, const RunFacts& r) {
|
||||
std::vector<Finding> out;
|
||||
check_engine(f, r, &out);
|
||||
check_link_under_load(f, &out);
|
||||
check_cards_differ(f, &out);
|
||||
check_link_capped(f, &out);
|
||||
check_small_bar(f, &out);
|
||||
check_power_cap(f, &out);
|
||||
check_od_runtime_pm(f, &out);
|
||||
check_cwsr(f, &out);
|
||||
check_memory(f, r, &out);
|
||||
check_huge_pages(f, r, &out);
|
||||
check_iommu(f, r, &out);
|
||||
check_memlock(f, r, &out);
|
||||
check_cpu(f, &out);
|
||||
/* Warnings first; stable, so each group keeps the order above. */
|
||||
std::stable_sort(out.begin(), out.end(),
|
||||
[](const Finding& a, const Finding& b) { return a.level > b.level; });
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string link_text(const std::string& speed, int width) {
|
||||
std::string s = speed;
|
||||
const size_t p = s.find(" PCIe");
|
||||
if (p != std::string::npos) s.erase(p);
|
||||
if (s.empty()) s = "?";
|
||||
return width > 0 ? fmt("%s x%d", s.c_str(), width) : s;
|
||||
}
|
||||
|
||||
std::string watts_text(int64_t uw) {
|
||||
return uw < 0 ? std::string("unknown") : fmt("%lld W", (long long)(uw / 1000000));
|
||||
}
|
||||
|
||||
double link_gts(const std::string& speed) {
|
||||
return speed.empty() ? 0.0 : std::strtod(speed.c_str(), nullptr);
|
||||
}
|
||||
|
||||
} /* namespace diag */
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,207 @@
|
||||
/* diag.h -- the startup report: what was configured, what it runs on, and what looks wrong.
|
||||
*
|
||||
* One block at the end of startup, instead of decisions scattered through the log (defaults are
|
||||
* never logged at all): every option with its value and source, the machine as the kernel
|
||||
* describes it, and findings that cost speed or correctness, each with a fix.
|
||||
*
|
||||
* Each part is built from data, not a list kept beside the code:
|
||||
* Configuration every row of the option table (core/config.cpp); a value startup resolved
|
||||
* carries its reason (Decision).
|
||||
* Hardware read from /proc and /sys under a root, so tests can supply a tree and a
|
||||
* FROM-scratch container (no shell, lspci or rocm-smi) reads the same files.
|
||||
* Findings small functions over the two above (checks.cpp), testable without a card.
|
||||
*
|
||||
* A field that could not be read is reported as unknown, never omitted.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
struct Config;
|
||||
namespace diag {
|
||||
|
||||
/* ------------------------------------------------------------------ decisions */
|
||||
/* One value startup resolved, and why. `key` is the option it resolves (`--placement`), shown on
|
||||
* that option's row, or a topic of its own (`vram split`). Recording a key again replaces the
|
||||
* earlier answer, so a later stage can revise a choice. */
|
||||
struct Decision {
|
||||
std::string key;
|
||||
std::string value;
|
||||
std::string why;
|
||||
};
|
||||
|
||||
void decide(std::vector<Decision>* list, const std::string& key, const std::string& value,
|
||||
const std::string& why);
|
||||
|
||||
/* ------------------------------------------------------------------ the configuration table */
|
||||
/* One option: the value in force, its source (`default`, `command line`, an environment
|
||||
* variable, or `auto` when startup derived it), and the reason when derived. */
|
||||
struct ConfigRow {
|
||||
std::string flag;
|
||||
std::string value;
|
||||
std::string source;
|
||||
std::string why;
|
||||
};
|
||||
|
||||
/* Every option in core/config.cpp's table, in order, with the value `c` holds and its source
|
||||
* from Config::given. Secrets are not shown: --api-key is "set" or "not set". */
|
||||
std::vector<ConfigRow> config_rows(const Config& c);
|
||||
|
||||
/* The options the table holds, for a test that every one reaches the report. */
|
||||
std::vector<std::string> config_option_names();
|
||||
|
||||
/* ------------------------------------------------------------------ hardware */
|
||||
/* One PCIe link between the root port and a card. Speeds are the kernel's strings
|
||||
* ("32.0 GT/s PCIe"), widths in lanes; -1 / "" where the file is absent (some bridges inside a
|
||||
* card's own switch). */
|
||||
struct PciHop {
|
||||
std::string bdf;
|
||||
std::string cur_speed, max_speed;
|
||||
int cur_width = -1, max_width = -1;
|
||||
};
|
||||
|
||||
struct CardFacts {
|
||||
std::string bdf; /* 0000:03:00.0 */
|
||||
std::string vendor, pci_device; /* 0x1002, 0x7551 */
|
||||
std::string driver; /* the bound kernel driver, "" for none */
|
||||
std::string drm; /* card1, "" when the driver made no DRM node */
|
||||
std::string gfx; /* gfx1201, from the KFD topology; "" when unknown */
|
||||
int simd = -1; /* SIMDs the KFD topology reports */
|
||||
int numa_node = -1;
|
||||
int64_t vram_total = -1, vram_visible = -1; /* the BAR the host and the peers see */
|
||||
int busy_percent = -1;
|
||||
std::string runtime_status; /* active | suspended, "" when unknown */
|
||||
std::string runtime_control; /* auto | on */
|
||||
std::string iommu_type; /* the card's IOMMU group: identity, DMA, DMA-FQ */
|
||||
std::vector<PciHop> chain; /* root port first, the card's own link last */
|
||||
std::vector<std::string> dpm_pcie; /* the SMU's link levels, as listed */
|
||||
int dpm_pcie_cur = -1; /* the level marked current, -1 unknown */
|
||||
std::string sclk, mclk; /* "500-2350 MHz", the lowest and highest DPM level */
|
||||
int64_t power_cap_uw = -1, power_cap_default_uw = -1, power_cap_max_uw = -1;
|
||||
std::string vddgfx_offset; /* "-75 mV" from pp_od_clk_voltage, "" when unknown */
|
||||
bool integrated = false; /* the KFD topology's node has no local memory of its own */
|
||||
|
||||
/* Filled by the engine for the cards it uses. */
|
||||
std::string name; /* the runtime's product name */
|
||||
int rank = -1; /* the tensor-parallel rank it serves, -1 none */
|
||||
int device = -1; /* the backend's device index, -1 none */
|
||||
std::string dma; /* what carries its copy lists (dev_dma_lane), "" unknown */
|
||||
};
|
||||
|
||||
struct HostFacts {
|
||||
std::string cpu_model;
|
||||
int cores = -1, threads = -1;
|
||||
int64_t mem_total = -1, mem_available = -1, swap_total = -1, swap_free = -1;
|
||||
std::string kernel, distro;
|
||||
std::string container; /* "docker", "podman", "" for none seen */
|
||||
int64_t cgroup_mem_limit = -1; /* bytes; -2 is "max", -1 unknown */
|
||||
int64_t memlock_soft = -1; /* bytes; -2 is unlimited, -1 unknown */
|
||||
std::string thp_enabled, thp_defrag, thp_shmem; /* the selected word of each */
|
||||
std::string iommu; /* passthrough | translated | off | unknown */
|
||||
std::string iommu_why; /* what that was read from */
|
||||
std::string cmdline; /* the boot parameters that bear on a card, space separated */
|
||||
int64_t ttm_pages_limit = -1; /* pages; TTM's limit on the system memory it allocates */
|
||||
int64_t page_size = 4096;
|
||||
int cwsr_enable = -1;
|
||||
std::string io_uring; /* available | refused (why) | unknown */
|
||||
std::string cpu_governor, cpu_epp, cpu_driver;
|
||||
std::string runtime; /* the device runtime's version, "" for none */
|
||||
};
|
||||
|
||||
struct Facts {
|
||||
HostFacts host;
|
||||
std::vector<CardFacts> cards; /* every display-class PCI device, in address order */
|
||||
};
|
||||
|
||||
/* Reads /proc and /sys under `root` ("" is the live system). Never fails: unreadable fields are
|
||||
* left unknown.
|
||||
*
|
||||
* `managed`, when given, lists the cards (by PCI address) whose power-management files are read:
|
||||
* DPM tables, overdrive, busy percentage, hwmon power limits. The driver answers those from the
|
||||
* SMU under its power-management lock and wakes a runtime-suspended card to do so, so a serving
|
||||
* process reads them only for its own cards. Null reads them for every card. */
|
||||
Facts collect(const std::string& root, const std::vector<std::string>* managed = nullptr);
|
||||
|
||||
/* Fills what only a system call answers for the live process: the memlock limit and whether
|
||||
* io_uring is allowed (a container's seccomp profile may refuse it). */
|
||||
void probe_process(HostFacts* h);
|
||||
|
||||
/* Sorted names of the variables in `env` (environ-shaped, null-terminated) starting with
|
||||
* `prefix`. Names only: values may be paths, host names or tokens, and the report gets pasted
|
||||
* into issues. */
|
||||
std::vector<std::string> env_names(char* const* env, const char* prefix);
|
||||
|
||||
/* ------------------------------------------------------------------ what the engine did */
|
||||
struct RunFacts {
|
||||
std::string version; /* the engine's, for the report's first line */
|
||||
bool device_build = true; /* built with a device runtime (HIP) */
|
||||
int tp = 1;
|
||||
bool host_backend = false;
|
||||
bool failed = false; /* startup stopped; the report is what it got to */
|
||||
int p2p = -1; /* 1 peer to peer, 0 through host memory, -1 n/a */
|
||||
bool p2p_forced_off = false; /* --p2p off */
|
||||
std::string p2p_blocked; /* the pairs the driver refused */
|
||||
std::vector<std::string> ignored; /* devices left out, each with the reason */
|
||||
bool tp_wire_lossy = false;
|
||||
int64_t tp_wire_min_kb = 0;
|
||||
bool prefix_cache = true;
|
||||
/* Why the engine disabled prefix caching itself (KL mode, an embedding model); "" when it is
|
||||
* on or the operator turned it off. */
|
||||
std::string prefix_cache_off_why;
|
||||
int64_t host_pool_mib = 0; /* a rank, as configured */
|
||||
int64_t pinned_bytes = -1; /* every pinned host allocation the process made */
|
||||
int64_t host_weight_bytes = 0; /* weights a rank reads from the pinned host pool */
|
||||
int64_t file_weight_bytes = 0; /* and from the container on disk */
|
||||
int64_t locked_bytes = 0; /* memory locked for a host gather (an n-gram copy) */
|
||||
std::string ngram_placement; /* where an n-gram table went, "" for a model without one */
|
||||
bool reference_kernels = false;
|
||||
bool profile_ops = false;
|
||||
bool deterministic = false;
|
||||
/* Names of the RADIANCE_* variables set (env_names): settings outside the option table,
|
||||
* such as the log level, a pinned tuning or an instrument left on. */
|
||||
std::vector<std::string> environment;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ findings */
|
||||
struct Finding {
|
||||
enum Level { Note = 0, Warn = 1 };
|
||||
Level level = Note;
|
||||
std::string id; /* stable, for a test or a grep: "link-below-max" */
|
||||
std::string what; /* what was seen, with the numbers */
|
||||
std::string why; /* what it costs */
|
||||
std::string fix; /* what to do: a flag, a setting, a command */
|
||||
};
|
||||
|
||||
std::vector<Finding> check(const Facts& f, const RunFacts& r);
|
||||
|
||||
/* ------------------------------------------------------------------ the report */
|
||||
std::string render(const std::vector<ConfigRow>& config, const std::vector<Decision>& derived,
|
||||
const Facts& f, const RunFacts& r, const std::vector<Finding>& findings);
|
||||
|
||||
/* The same, as a JSON object in text: {"configuration", "derived", "hardware", "findings"}. */
|
||||
std::string to_json(const std::vector<ConfigRow>& config, const std::vector<Decision>& derived,
|
||||
const Facts& f, const RunFacts& r, const std::vector<Finding>& findings);
|
||||
|
||||
/* Merges the decisions into the option rows: a decision whose key is an option's flag supplies
|
||||
* that row's value and reason (and `auto` as its source when the option was not given). The
|
||||
* decisions no row took are returned in `derived`, in the order they were made. */
|
||||
void merge(std::vector<ConfigRow>* rows, const std::vector<Decision>& decisions,
|
||||
std::vector<Decision>* derived);
|
||||
|
||||
/* "32.0 GT/s PCIe" -> 32.0; 0 when it does not parse. */
|
||||
double link_gts(const std::string& speed);
|
||||
|
||||
/* "32.0 GT/s x16" from a sysfs speed and width; "?" for an unknown speed. */
|
||||
std::string link_text(const std::string& speed, int width);
|
||||
|
||||
/* "300 W" from microwatts; "unknown" when negative. */
|
||||
std::string watts_text(int64_t uw);
|
||||
|
||||
/* Busy percentage above which a link below its maximum is not idle parking. */
|
||||
constexpr int kBusyPercent = 30;
|
||||
|
||||
} /* namespace diag */
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,286 @@
|
||||
/* report.cpp -- the startup report, as text for the log and as JSON for /diagnostics.
|
||||
*
|
||||
* Text layout: one line per option with value and source (the reason below any derived value),
|
||||
* the host in a few lines, a block per card, then findings with fixes. Text and JSON render from
|
||||
* the same structs.
|
||||
*/
|
||||
#include "diag/diag.h"
|
||||
#include "rad_internal.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
namespace rad {
|
||||
namespace diag {
|
||||
|
||||
void decide(std::vector<Decision>* list, const std::string& key, const std::string& value,
|
||||
const std::string& why) {
|
||||
for (Decision& d : *list)
|
||||
if (d.key == key) { d.value = value; d.why = why; return; }
|
||||
list->push_back({ key, value, why });
|
||||
}
|
||||
|
||||
void merge(std::vector<ConfigRow>* rows, const std::vector<Decision>& decisions,
|
||||
std::vector<Decision>* derived) {
|
||||
derived->clear();
|
||||
for (const Decision& d : decisions) {
|
||||
auto it = std::find_if(rows->begin(), rows->end(),
|
||||
[&](const ConfigRow& r) { return r.flag == d.key; });
|
||||
if (it == rows->end()) { derived->push_back(d); continue; }
|
||||
it->value = d.value;
|
||||
it->why = d.why;
|
||||
if (it->source == "default") it->source = "auto";
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
std::string or_unknown(const std::string& s) { return s.empty() ? "unknown" : s; }
|
||||
std::string bytes_or_unknown(int64_t b) { return b < 0 ? "unknown" : humanb(b); }
|
||||
|
||||
/* Continuation lines of a multi-line value, indented under the column they belong to. */
|
||||
void indented(std::string* out, const std::string& text, int indent) {
|
||||
size_t at = 0;
|
||||
while (at <= text.size()) {
|
||||
size_t nl = text.find('\n', at);
|
||||
if (nl == std::string::npos) nl = text.size();
|
||||
const std::string l = text.substr(at, nl - at);
|
||||
if (!l.empty()) *out += std::string((size_t)indent, ' ') + l + "\n";
|
||||
at = nl + 1;
|
||||
}
|
||||
}
|
||||
|
||||
std::string short_bdf(const std::string& b) {
|
||||
return b.rfind("0000:", 0) == 0 ? b.substr(5) : b;
|
||||
}
|
||||
|
||||
|
||||
std::string host_lines(const HostFacts& h, const RunFacts& r) {
|
||||
std::string o;
|
||||
o += fmt(" host %s | %s cores, %s threads | RAM %s, %s available | swap %s\n",
|
||||
or_unknown(h.cpu_model).c_str(),
|
||||
h.cores > 0 ? std::to_string(h.cores).c_str() : "?",
|
||||
h.threads > 0 ? std::to_string(h.threads).c_str() : "?",
|
||||
bytes_or_unknown(h.mem_total).c_str(), bytes_or_unknown(h.mem_available).c_str(),
|
||||
h.swap_total == 0 ? "none"
|
||||
: h.swap_total < 0 ? "unknown"
|
||||
: fmt("%s, %s used", humanb(h.swap_total).c_str(),
|
||||
humanb(h.swap_total - std::max<int64_t>(h.swap_free, 0)).c_str()).c_str());
|
||||
o += fmt(" system kernel %s | %s | %s | cgroup memory %s | memlock %s\n",
|
||||
or_unknown(h.kernel).c_str(), or_unknown(h.distro).c_str(),
|
||||
h.container.empty() ? "no container seen" : ("in a " + h.container + " container").c_str(),
|
||||
h.cgroup_mem_limit == -2 ? "unlimited" : bytes_or_unknown(h.cgroup_mem_limit).c_str(),
|
||||
h.memlock_soft == -2 ? "unlimited" : bytes_or_unknown(h.memlock_soft).c_str());
|
||||
o += fmt(" memory huge pages %s (defrag %s, shmem %s) | ttm.pages_limit %s "
|
||||
"| pinned by this process %s\n",
|
||||
or_unknown(h.thp_enabled).c_str(), or_unknown(h.thp_defrag).c_str(),
|
||||
or_unknown(h.thp_shmem).c_str(),
|
||||
h.ttm_pages_limit > 0 ? humanb(h.ttm_pages_limit * h.page_size).c_str() : "unknown",
|
||||
bytes_or_unknown(r.pinned_bytes).c_str());
|
||||
o += fmt(" iommu %s (%s)\n", or_unknown(h.iommu).c_str(), or_unknown(h.iommu_why).c_str());
|
||||
o += fmt(" amdgpu cwsr_enable %s | boot parameters: %s\n",
|
||||
h.cwsr_enable < 0 ? "unknown" : std::to_string(h.cwsr_enable).c_str(),
|
||||
h.cmdline.empty() ? "none that bear on a card" : h.cmdline.c_str());
|
||||
o += fmt(" cpu governor %s%s%s | io_uring %s\n", or_unknown(h.cpu_governor).c_str(),
|
||||
h.cpu_epp.empty() ? "" : (", energy preference " + h.cpu_epp).c_str(),
|
||||
h.cpu_driver.empty() ? "" : (" (" + h.cpu_driver + ")").c_str(),
|
||||
or_unknown(h.io_uring).c_str());
|
||||
o += fmt(" runtime %s | backend %s\n",
|
||||
h.runtime.empty() ? "no device runtime" : h.runtime.c_str(),
|
||||
r.host_backend ? "host (CPU)" : "device");
|
||||
return o;
|
||||
}
|
||||
|
||||
std::string card_lines(const CardFacts& c) {
|
||||
std::string o;
|
||||
std::string who = c.rank >= 0 ? fmt("rank %d (device %d)", c.rank, c.device)
|
||||
: c.device >= 0 ? fmt("device %d, not serving", c.device) : "not serving";
|
||||
o += fmt(" card %s %s %s%s%s %s VRAM",
|
||||
c.bdf.c_str(), who.c_str(), c.gfx.empty() ? (c.vendor + ":" + c.pci_device).c_str() : c.gfx.c_str(),
|
||||
c.name.empty() ? "" : " ", c.name.empty() ? "" : ("\"" + c.name + "\"").c_str(),
|
||||
bytes_or_unknown(c.vram_total).c_str());
|
||||
if (c.vram_visible > 0 && c.vram_visible != c.vram_total)
|
||||
o += fmt(" (BAR %s)", humanb(c.vram_visible).c_str());
|
||||
o += fmt(" NUMA %d driver %s%s%s\n", c.numa_node, or_unknown(c.driver).c_str(),
|
||||
c.drm.empty() ? "" : " ", c.drm.c_str());
|
||||
std::string chain;
|
||||
for (const PciHop& h : c.chain)
|
||||
chain += fmt("%s%s %s (max %s)", chain.empty() ? "" : " -> ", short_bdf(h.bdf).c_str(),
|
||||
link_text(h.cur_speed, h.cur_width).c_str(),
|
||||
link_text(h.max_speed, h.max_width).c_str());
|
||||
o += fmt(" link %s [read at %s%% busy%s]\n", chain.empty() ? "unknown" : chain.c_str(),
|
||||
c.busy_percent < 0 ? "?" : std::to_string(c.busy_percent).c_str(),
|
||||
c.busy_percent >= 0 && c.busy_percent < kBusyPercent
|
||||
? ": a link at rest parks below its maximum" : "");
|
||||
if (!c.dpm_pcie.empty()) {
|
||||
std::string t;
|
||||
for (size_t i = 0; i < c.dpm_pcie.size(); ++i)
|
||||
t += fmt("%s%s%s", i ? " | " : "", (int)i == c.dpm_pcie_cur ? "*" : "", c.dpm_pcie[i].c_str());
|
||||
o += " pcie " + t + "\n";
|
||||
}
|
||||
if (!c.dma.empty()) o += " dma " + c.dma + "\n";
|
||||
o += fmt(" power cap %s (default %s, max %s) | voltage offset %s | sclk %s | mclk %s | "
|
||||
"runtime pm %s (control %s) | iommu group %s\n",
|
||||
watts_text(c.power_cap_uw).c_str(), watts_text(c.power_cap_default_uw).c_str(),
|
||||
watts_text(c.power_cap_max_uw).c_str(), or_unknown(c.vddgfx_offset).c_str(),
|
||||
or_unknown(c.sclk).c_str(), or_unknown(c.mclk).c_str(),
|
||||
or_unknown(c.runtime_status).c_str(), or_unknown(c.runtime_control).c_str(),
|
||||
c.iommu_type.empty() ? "none" : c.iommu_type.c_str());
|
||||
return o;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
std::string render(const std::vector<ConfigRow>& config, const std::vector<Decision>& derived,
|
||||
const Facts& f, const RunFacts& r, const std::vector<Finding>& findings) {
|
||||
std::string o;
|
||||
o += "STARTUP REPORT" + (r.version.empty() ? std::string() : " -- radiance " + r.version) +
|
||||
(r.failed ? " -- STARTUP STOPPED; this is what it had resolved when it did\n" : "\n");
|
||||
o += "CONFIGURATION -- every option, the value in force, and where it came from\n";
|
||||
size_t w = 0;
|
||||
for (const ConfigRow& c : config) w = std::max(w, c.flag.size());
|
||||
w = std::min<size_t>(w + 2, 34);
|
||||
for (const ConfigRow& c : config) {
|
||||
const std::string v = c.value.empty() ? "\"\"" : c.value;
|
||||
const std::string first = v.substr(0, v.find('\n'));
|
||||
std::string l = fmt(" %-*s %s", (int)w, c.flag.c_str(), first.c_str());
|
||||
const size_t col = 2 + w + 1 + 44;
|
||||
l += l.size() < col ? std::string(col - l.size(), ' ') : std::string(" ");
|
||||
o += l + "[" + c.source + "]\n";
|
||||
if (first.size() != v.size()) indented(&o, v.substr(first.size() + 1), (int)(3 + w));
|
||||
if (!c.why.empty()) indented(&o, c.why, (int)(5 + w));
|
||||
}
|
||||
o += "ENVIRONMENT -- the RADIANCE_* variables set, by name; their values are not shown\n";
|
||||
if (r.environment.empty()) o += " none\n";
|
||||
for (const std::string& n : r.environment) o += " " + n + "\n";
|
||||
if (!derived.empty()) {
|
||||
o += "DERIVED -- what startup worked out that no single option states\n";
|
||||
for (const Decision& d : derived) {
|
||||
o += fmt(" %-*s %s\n", (int)w, d.key.c_str(), d.value.c_str());
|
||||
if (!d.why.empty()) indented(&o, d.why, (int)(5 + w));
|
||||
}
|
||||
}
|
||||
o += "HARDWARE\n";
|
||||
o += host_lines(f.host, r);
|
||||
for (const CardFacts& c : f.cards) o += card_lines(c);
|
||||
if (f.cards.empty()) o += " no display-class PCI device is visible\n";
|
||||
int nw = 0, nn = 0;
|
||||
for (const Finding& x : findings) (x.level == Finding::Warn ? nw : nn)++;
|
||||
o += fmt("FINDINGS -- %d warning%s, %d note%s\n", nw, nw == 1 ? "" : "s", nn, nn == 1 ? "" : "s");
|
||||
if (findings.empty()) o += " nothing found that costs speed or correctness\n";
|
||||
for (const Finding& x : findings) {
|
||||
o += fmt(" %s %s: %s\n", x.level == Finding::Warn ? "WARN" : "note", x.id.c_str(),
|
||||
x.what.c_str());
|
||||
o += " why: " + x.why + "\n";
|
||||
o += " fix: " + x.fix + "\n";
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
std::string to_json(const std::vector<ConfigRow>& config, const std::vector<Decision>& derived,
|
||||
const Facts& f, const RunFacts& r, const std::vector<Finding>& findings) {
|
||||
using J = nlohmann::ordered_json;
|
||||
J o;
|
||||
o["startup_failed"] = r.failed;
|
||||
J cfg = J::array();
|
||||
for (const ConfigRow& c : config) {
|
||||
J e;
|
||||
e["option"] = c.flag;
|
||||
e["value"] = c.value;
|
||||
e["source"] = c.source;
|
||||
if (!c.why.empty()) e["why"] = c.why;
|
||||
cfg.push_back(std::move(e));
|
||||
}
|
||||
o["configuration"] = std::move(cfg);
|
||||
o["environment"] = r.environment;
|
||||
J der = J::array();
|
||||
for (const Decision& d : derived) der.push_back({ { "topic", d.key }, { "value", d.value }, { "why", d.why } });
|
||||
o["derived"] = std::move(der);
|
||||
|
||||
const HostFacts& h = f.host;
|
||||
J host;
|
||||
host["cpu"] = h.cpu_model;
|
||||
host["cores"] = h.cores;
|
||||
host["threads"] = h.threads;
|
||||
host["mem_total"] = h.mem_total;
|
||||
host["mem_available"] = h.mem_available;
|
||||
host["swap_total"] = h.swap_total;
|
||||
host["swap_free"] = h.swap_free;
|
||||
host["kernel"] = h.kernel;
|
||||
host["distro"] = h.distro;
|
||||
host["container"] = h.container;
|
||||
host["cgroup_mem_limit"] = h.cgroup_mem_limit;
|
||||
host["memlock"] = h.memlock_soft;
|
||||
host["thp"] = { { "enabled", h.thp_enabled }, { "defrag", h.thp_defrag },
|
||||
{ "shmem_enabled", h.thp_shmem } };
|
||||
host["iommu"] = { { "mode", h.iommu }, { "why", h.iommu_why } };
|
||||
host["boot_parameters"] = h.cmdline;
|
||||
host["ttm_pages_limit"] = h.ttm_pages_limit;
|
||||
host["page_size"] = h.page_size;
|
||||
host["cwsr_enable"] = h.cwsr_enable;
|
||||
host["io_uring"] = h.io_uring;
|
||||
host["cpu_governor"] = h.cpu_governor;
|
||||
host["cpu_epp"] = h.cpu_epp;
|
||||
host["cpu_driver"] = h.cpu_driver;
|
||||
host["runtime"] = h.runtime;
|
||||
J cards = J::array();
|
||||
for (const CardFacts& c : f.cards) {
|
||||
J e;
|
||||
e["bdf"] = c.bdf;
|
||||
e["rank"] = c.rank;
|
||||
e["device"] = c.device;
|
||||
e["name"] = c.name;
|
||||
e["vendor"] = c.vendor;
|
||||
e["pci_device"] = c.pci_device;
|
||||
e["gfx"] = c.gfx;
|
||||
e["simd"] = c.simd;
|
||||
e["driver"] = c.driver;
|
||||
e["drm"] = c.drm;
|
||||
e["numa_node"] = c.numa_node;
|
||||
e["vram_total"] = c.vram_total;
|
||||
e["vram_visible"] = c.vram_visible;
|
||||
e["busy_percent"] = c.busy_percent;
|
||||
e["runtime_status"] = c.runtime_status;
|
||||
e["runtime_control"] = c.runtime_control;
|
||||
e["iommu_group_type"] = c.iommu_type;
|
||||
e["dma"] = c.dma;
|
||||
J chain = J::array();
|
||||
for (const PciHop& hp : c.chain)
|
||||
chain.push_back({ { "bdf", hp.bdf }, { "speed", hp.cur_speed }, { "width", hp.cur_width },
|
||||
{ "max_speed", hp.max_speed }, { "max_width", hp.max_width } });
|
||||
e["link_chain"] = std::move(chain);
|
||||
e["pcie_dpm"] = c.dpm_pcie;
|
||||
e["pcie_dpm_current"] = c.dpm_pcie_cur;
|
||||
e["sclk"] = c.sclk;
|
||||
e["mclk"] = c.mclk;
|
||||
e["power_cap_uw"] = c.power_cap_uw;
|
||||
e["power_cap_default_uw"] = c.power_cap_default_uw;
|
||||
e["power_cap_max_uw"] = c.power_cap_max_uw;
|
||||
e["vddgfx_offset"] = c.vddgfx_offset;
|
||||
cards.push_back(std::move(e));
|
||||
}
|
||||
J run;
|
||||
run["version"] = r.version;
|
||||
run["device_build"] = r.device_build;
|
||||
run["tp"] = r.tp;
|
||||
run["host_backend"] = r.host_backend;
|
||||
run["p2p"] = r.p2p;
|
||||
run["p2p_blocked"] = r.p2p_blocked;
|
||||
run["ignored_devices"] = r.ignored;
|
||||
run["pinned_bytes"] = r.pinned_bytes;
|
||||
run["host_weight_bytes"] = r.host_weight_bytes;
|
||||
run["file_weight_bytes"] = r.file_weight_bytes;
|
||||
o["hardware"] = { { "host", std::move(host) }, { "cards", std::move(cards) }, { "run", std::move(run) } };
|
||||
J fs = J::array();
|
||||
for (const Finding& x : findings)
|
||||
fs.push_back({ { "level", x.level == Finding::Warn ? "warn" : "note" }, { "id", x.id },
|
||||
{ "what", x.what }, { "why", x.why }, { "fix", x.fix } });
|
||||
o["findings"] = std::move(fs);
|
||||
/* Replace invalid UTF-8 instead of throwing: paths, boot parameters and product names are
|
||||
* not guaranteed to be UTF-8. */
|
||||
return o.dump(-1, ' ', false, J::error_handler_t::replace);
|
||||
}
|
||||
|
||||
} /* namespace diag */
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,459 @@
|
||||
/* sysinfo.cpp -- the machine, as /proc and /sys describe it.
|
||||
*
|
||||
* Every read is a file under a root; no tool or library is used. The production image is built
|
||||
* FROM scratch (no shell, lspci or rocm-smi), and tests pass a directory tree describing the
|
||||
* machine. What a file does not say is left unknown, never guessed.
|
||||
*/
|
||||
#include "diag/diag.h"
|
||||
#include "rad_internal.h"
|
||||
|
||||
#include <cerrno>
|
||||
#include <cctype>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <sstream>
|
||||
#include <sys/resource.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace rad {
|
||||
namespace diag {
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
namespace {
|
||||
|
||||
std::string slurp(const std::string& path) {
|
||||
std::ifstream f(path);
|
||||
if (!f) return std::string();
|
||||
std::stringstream ss;
|
||||
ss << f.rdbuf();
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
std::string trim(std::string s) {
|
||||
while (!s.empty() && (s.back() == '\n' || s.back() == ' ' || s.back() == '\t' || s.back() == '\r'))
|
||||
s.pop_back();
|
||||
size_t i = 0;
|
||||
while (i < s.size() && (s[i] == ' ' || s[i] == '\t')) ++i;
|
||||
return s.substr(i);
|
||||
}
|
||||
|
||||
/* The first line of a sysfs attribute, trimmed; "" when it cannot be read. */
|
||||
std::string line(const std::string& path) {
|
||||
const std::string s = slurp(path);
|
||||
const size_t nl = s.find('\n');
|
||||
return trim(nl == std::string::npos ? s : s.substr(0, nl));
|
||||
}
|
||||
|
||||
int64_t num(const std::string& path, int64_t dflt = -1) {
|
||||
const std::string s = line(path);
|
||||
if (s.empty()) return dflt;
|
||||
char* end = nullptr;
|
||||
const long long v = std::strtoll(s.c_str(), &end, 0);
|
||||
return end && end != s.c_str() ? (int64_t)v : dflt;
|
||||
}
|
||||
|
||||
/* The bracketed word of a sysfs choice list: "always [madvise] never" -> "madvise". */
|
||||
std::string selected(const std::string& path) {
|
||||
const std::string s = line(path);
|
||||
const size_t a = s.find('['), b = s.find(']');
|
||||
if (a == std::string::npos || b == std::string::npos || b < a) return s;
|
||||
return s.substr(a + 1, b - a - 1);
|
||||
}
|
||||
|
||||
bool exists(const std::string& p) {
|
||||
std::error_code ec;
|
||||
return fs::exists(p, ec);
|
||||
}
|
||||
|
||||
std::vector<std::string> list(const std::string& dir) {
|
||||
std::vector<std::string> out;
|
||||
std::error_code ec;
|
||||
for (fs::directory_iterator it(dir, ec), end; !ec && it != end; it.increment(ec))
|
||||
out.push_back(it->path().filename().string());
|
||||
std::sort(out.begin(), out.end());
|
||||
return out;
|
||||
}
|
||||
|
||||
bool is_bdf(const std::string& s) {
|
||||
unsigned d, b, dv, f;
|
||||
char tail;
|
||||
return s.size() == 12 && std::sscanf(s.c_str(), "%4x:%2x:%2x.%1x%c", &d, &b, &dv, &f, &tail) == 4;
|
||||
}
|
||||
|
||||
/* "0x7551" from a sysfs id file, which the kernel writes with its prefix. */
|
||||
std::string hexid(const std::string& path) { return line(path); }
|
||||
|
||||
/* The lowest and highest level of a pp_dpm_* table, "500-2350 MHz"; the levels are listed in
|
||||
* order, one a line, as "N: 2350Mhz *". */
|
||||
std::string dpm_range(const std::string& path) {
|
||||
std::istringstream in(slurp(path));
|
||||
std::string l;
|
||||
long lo = -1, hi = -1;
|
||||
while (std::getline(in, l)) {
|
||||
const size_t c = l.find(':');
|
||||
const char* p = l.c_str() + (c == std::string::npos ? 0 : c + 1);
|
||||
long v = std::strtol(p, nullptr, 10);
|
||||
if (v <= 0) continue;
|
||||
if (lo < 0 || v < lo) lo = v;
|
||||
if (v > hi) hi = v;
|
||||
}
|
||||
if (lo < 0) return std::string();
|
||||
return fmt("%ld-%ld MHz", lo, hi);
|
||||
}
|
||||
|
||||
/* `pm`: whether the power-management files are read as well (collect's `managed`). */
|
||||
void read_card(const std::string& root, const std::string& bdf, bool pm, CardFacts* c) {
|
||||
const std::string dev = root + "/sys/bus/pci/devices/" + bdf;
|
||||
c->bdf = bdf;
|
||||
c->vendor = hexid(dev + "/vendor");
|
||||
c->pci_device = hexid(dev + "/device");
|
||||
{
|
||||
std::error_code ec;
|
||||
const fs::path drv = fs::read_symlink(dev + "/driver", ec);
|
||||
if (!ec) c->driver = drv.filename().string();
|
||||
}
|
||||
c->numa_node = (int)num(dev + "/numa_node", -1);
|
||||
c->runtime_status = line(dev + "/power/runtime_status");
|
||||
c->runtime_control = line(dev + "/power/control");
|
||||
c->iommu_type = line(dev + "/iommu_group/type");
|
||||
for (const std::string& d : list(dev + "/drm"))
|
||||
if (d.rfind("card", 0) == 0 && d.size() > 4 && std::isdigit((unsigned char)d[4])) c->drm = d;
|
||||
|
||||
/* Every hop up to the root port, not just the card's link: a card with an on-board switch
|
||||
* reports its endpoint at full speed regardless of the slot, so a parked root port shows only
|
||||
* at the root port (and in the card's DPM table). */
|
||||
auto hop = [&](const std::string& at, const std::string& hop_bdf) {
|
||||
PciHop h;
|
||||
h.bdf = hop_bdf;
|
||||
h.cur_speed = line(at + "/current_link_speed");
|
||||
h.max_speed = line(at + "/max_link_speed");
|
||||
h.cur_width = (int)num(at + "/current_link_width", -1);
|
||||
h.max_width = (int)num(at + "/max_link_width", -1);
|
||||
c->chain.push_back(h);
|
||||
};
|
||||
std::error_code ec;
|
||||
const fs::path real = fs::canonical(dev, ec);
|
||||
if (!ec) {
|
||||
for (const fs::path& part : real) {
|
||||
const std::string p = part.string();
|
||||
if (is_bdf(p)) hop(root + "/sys/bus/pci/devices/" + p, p);
|
||||
}
|
||||
}
|
||||
if (c->chain.empty()) hop(dev, bdf);
|
||||
|
||||
c->vram_total = num(dev + "/mem_info_vram_total", -1);
|
||||
c->vram_visible = num(dev + "/mem_info_vis_vram_total", -1);
|
||||
if (!pm) return;
|
||||
c->busy_percent = (int)num(dev + "/gpu_busy_percent", -1);
|
||||
{
|
||||
std::istringstream in(slurp(dev + "/pp_dpm_pcie"));
|
||||
std::string l;
|
||||
while (std::getline(in, l)) {
|
||||
l = trim(l);
|
||||
if (l.empty()) continue;
|
||||
if (l.find('*') != std::string::npos) c->dpm_pcie_cur = (int)c->dpm_pcie.size();
|
||||
l.erase(std::remove(l.begin(), l.end(), '*'), l.end());
|
||||
c->dpm_pcie.push_back(trim(l));
|
||||
}
|
||||
}
|
||||
c->sclk = dpm_range(dev + "/pp_dpm_sclk");
|
||||
c->mclk = dpm_range(dev + "/pp_dpm_mclk");
|
||||
for (const std::string& h : list(dev + "/hwmon")) {
|
||||
const std::string hp = dev + "/hwmon/" + h;
|
||||
if (!exists(hp + "/power1_cap")) continue;
|
||||
c->power_cap_uw = num(hp + "/power1_cap", -1);
|
||||
c->power_cap_default_uw = num(hp + "/power1_cap_default", -1);
|
||||
c->power_cap_max_uw = num(hp + "/power1_cap_max", -1);
|
||||
break;
|
||||
}
|
||||
{
|
||||
/* "OD_VDDGFX_OFFSET:\n-75mV": the offset the driver holds and uploads; whether the
|
||||
* firmware applied it is not in this file. */
|
||||
const std::string od = slurp(dev + "/pp_od_clk_voltage");
|
||||
const size_t at = od.find("OD_VDDGFX_OFFSET:");
|
||||
if (at != std::string::npos) {
|
||||
const char* p = od.c_str() + at + std::strlen("OD_VDDGFX_OFFSET:");
|
||||
char* end = nullptr;
|
||||
const long v = std::strtol(p, &end, 10);
|
||||
if (end && end != p) c->vddgfx_offset = fmt("%ld mV", v);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Each KFD topology GPU node's target and SIMD count, keyed by PCI location:
|
||||
* `location_id` is (bus << 8) | (device << 3) | function. */
|
||||
void read_kfd(const std::string& root, std::vector<CardFacts>* cards) {
|
||||
const std::string nodes = root + "/sys/class/kfd/kfd/topology/nodes";
|
||||
for (const std::string& n : list(nodes)) {
|
||||
/* Line by line, parsing only the needed keys: some values (unique_id, a 64-bit hash)
|
||||
* overflow int64, and a failed stream extraction would stop reading all later keys. */
|
||||
std::istringstream in(slurp(nodes + "/" + n + "/properties"));
|
||||
std::string l;
|
||||
long long loc = -1, dom = 0, gfx = 0, simd = -1;
|
||||
while (std::getline(in, l)) {
|
||||
const size_t sp = l.find_first_of(" \t");
|
||||
if (sp == std::string::npos) continue;
|
||||
const std::string k = l.substr(0, sp);
|
||||
long long* into = k == "location_id" ? &loc
|
||||
: k == "domain" ? &dom
|
||||
: k == "gfx_target_version" ? &gfx
|
||||
: k == "simd_count" ? &simd
|
||||
: nullptr;
|
||||
if (!into) continue;
|
||||
const char* p = l.c_str() + sp + 1;
|
||||
char* end = nullptr;
|
||||
errno = 0;
|
||||
const long long v = std::strtoll(p, &end, 10);
|
||||
if (end != p && errno == 0) *into = v;
|
||||
}
|
||||
if (gfx <= 0 || loc < 0) continue;
|
||||
const std::string bdf = fmt("%04llx:%02llx:%02llx.%llx", dom, (loc >> 8) & 0xff,
|
||||
(loc >> 3) & 0x1f, loc & 7);
|
||||
for (CardFacts& c : *cards) {
|
||||
if (c.bdf != bdf) continue;
|
||||
c.gfx = fmt("gfx%lld%llx%llx", gfx / 10000, (gfx / 100) % 100, gfx % 100);
|
||||
c.simd = (int)simd;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* The binding one of two limits in HostFacts' encoding (bytes, -2 unlimited, -1 unknown): the
|
||||
* smaller number, else unlimited over unknown. */
|
||||
int64_t tighter(int64_t a, int64_t b) {
|
||||
if (a >= 0 && b >= 0) return std::min(a, b);
|
||||
if (a >= 0 || b >= 0) return std::max(a, b);
|
||||
return a == -2 || b == -2 ? -2 : -1;
|
||||
}
|
||||
|
||||
/* The tightest memory limit from a cgroup up to the mount's root. A limit binds every cgroup
|
||||
* below it, so the process's group may say "max" while a parent slice holds the real limit.
|
||||
* `rel` is the /proc/self/cgroup path under `mount`; every level is read, the root included
|
||||
* (inside a cgroup namespace that is the container's own group). */
|
||||
int64_t cgroup_limit(const std::string& mount, std::string rel, const char* file) {
|
||||
int64_t lim = -1;
|
||||
while (!rel.empty() && rel.back() == '/') rel.pop_back();
|
||||
for (;;) {
|
||||
const std::string v = line(mount + rel + "/" + file);
|
||||
if (v == "max") {
|
||||
lim = tighter(lim, -2);
|
||||
} else if (!v.empty()) {
|
||||
char* end = nullptr;
|
||||
errno = 0;
|
||||
const long long n = std::strtoll(v.c_str(), &end, 10);
|
||||
/* Version 1 writes "no limit" as the largest page-aligned number below 2^63. */
|
||||
if (end != v.c_str() && errno == 0 && n >= 0)
|
||||
lim = tighter(lim, n >= ((long long)1 << 62) ? -2 : (int64_t)n);
|
||||
}
|
||||
if (rel.empty()) break;
|
||||
const size_t up = rel.rfind('/');
|
||||
rel.erase(up == std::string::npos ? 0 : up);
|
||||
}
|
||||
return lim;
|
||||
}
|
||||
|
||||
void read_host(const std::string& root, HostFacts* h) {
|
||||
{
|
||||
std::istringstream in(slurp(root + "/proc/cpuinfo"));
|
||||
std::string l;
|
||||
std::set<std::pair<std::string, std::string>> cores;
|
||||
std::string phys;
|
||||
int threads = 0;
|
||||
while (std::getline(in, l)) {
|
||||
const size_t c = l.find(':');
|
||||
if (c == std::string::npos) continue;
|
||||
const std::string k = trim(l.substr(0, c)), v = trim(l.substr(c + 1));
|
||||
if (k == "processor") ++threads;
|
||||
else if (k == "model name" && h->cpu_model.empty()) h->cpu_model = v;
|
||||
else if (k == "physical id") phys = v;
|
||||
else if (k == "core id") cores.insert({ phys, v });
|
||||
}
|
||||
if (threads > 0) h->threads = threads;
|
||||
if (!cores.empty()) h->cores = (int)cores.size();
|
||||
}
|
||||
{
|
||||
std::istringstream in(slurp(root + "/proc/meminfo"));
|
||||
std::string k;
|
||||
long long v;
|
||||
std::string unit;
|
||||
while (in >> k >> v) {
|
||||
std::getline(in, unit);
|
||||
const int64_t b = (int64_t)v * 1024;
|
||||
if (k == "MemTotal:") h->mem_total = b;
|
||||
else if (k == "MemAvailable:") h->mem_available = b;
|
||||
else if (k == "SwapTotal:") h->swap_total = b;
|
||||
else if (k == "SwapFree:") h->swap_free = b;
|
||||
}
|
||||
}
|
||||
h->kernel = line(root + "/proc/sys/kernel/osrelease");
|
||||
{
|
||||
std::istringstream in(slurp(root + "/etc/os-release"));
|
||||
std::string l;
|
||||
while (std::getline(in, l))
|
||||
if (l.rfind("PRETTY_NAME=", 0) == 0) {
|
||||
h->distro = l.substr(12);
|
||||
if (h->distro.size() >= 2 && h->distro.front() == '"') h->distro = h->distro.substr(1, h->distro.size() - 2);
|
||||
}
|
||||
}
|
||||
if (exists(root + "/.dockerenv")) h->container = "docker";
|
||||
else if (exists(root + "/run/.containerenv")) h->container = "podman";
|
||||
else {
|
||||
const std::string cg = slurp(root + "/proc/1/cgroup");
|
||||
if (cg.find("docker") != std::string::npos) h->container = "docker";
|
||||
else if (cg.find("kubepods") != std::string::npos) h->container = "kubernetes";
|
||||
else if (cg.find("containerd") != std::string::npos) h->container = "containerd";
|
||||
}
|
||||
{
|
||||
/* The process's cgroup ("/" inside a container's namespace) and its ancestors. v2 is
|
||||
* the "0::" line; v1's memory controller is ":memory:", where unlimited is a number
|
||||
* near 2^63. */
|
||||
std::istringstream in(slurp(root + "/proc/self/cgroup"));
|
||||
std::string l;
|
||||
int64_t lim = -1;
|
||||
while (std::getline(in, l)) {
|
||||
int64_t v = -1;
|
||||
if (l.rfind("0::", 0) == 0)
|
||||
v = cgroup_limit(root + "/sys/fs/cgroup", l.substr(3), "memory.max");
|
||||
else if (l.find(":memory:") != std::string::npos)
|
||||
v = cgroup_limit(root + "/sys/fs/cgroup/memory", l.substr(l.find(":memory:") + 8),
|
||||
"memory.limit_in_bytes");
|
||||
lim = tighter(lim, v);
|
||||
}
|
||||
h->cgroup_mem_limit = lim;
|
||||
}
|
||||
const std::string thp = root + "/sys/kernel/mm/transparent_hugepage";
|
||||
h->thp_enabled = selected(thp + "/enabled");
|
||||
h->thp_defrag = selected(thp + "/defrag");
|
||||
h->thp_shmem = selected(thp + "/shmem_enabled");
|
||||
{
|
||||
std::istringstream in(line(root + "/proc/cmdline"));
|
||||
std::string t;
|
||||
static const char* const kKeep[] = { "iommu", "amd_iommu", "intel_iommu", "amdgpu.", "ttm.",
|
||||
"transparent_hugepage", "hugepages", "pcie_aspm",
|
||||
"pci=", "default_hugepagesz" };
|
||||
while (in >> t)
|
||||
for (const char* k : kKeep)
|
||||
if (t.rfind(k, 0) == 0) { h->cmdline += (h->cmdline.empty() ? "" : " ") + t; break; }
|
||||
}
|
||||
{
|
||||
/* Passthrough or translated. The cards' IOMMU group type (identity = passthrough) is the
|
||||
* kernel's own answer; IOMMU presence and boot parameters are the fallback for a card
|
||||
* with no group. */
|
||||
const bool any_iommu = !list(root + "/sys/class/iommu").empty();
|
||||
const bool groups = !list(root + "/sys/kernel/iommu_groups").empty();
|
||||
const std::string cl = " " + h->cmdline + " ";
|
||||
if (!any_iommu && !groups) {
|
||||
h->iommu = "off";
|
||||
h->iommu_why = "no IOMMU is registered (/sys/class/iommu is empty)";
|
||||
} else if (cl.find(" iommu=pt ") != std::string::npos ||
|
||||
cl.find(" amd_iommu=pt ") != std::string::npos ||
|
||||
cl.find(" intel_iommu=pt ") != std::string::npos) {
|
||||
h->iommu = "passthrough";
|
||||
h->iommu_why = "iommu=pt on the kernel command line";
|
||||
} else if (cl.find("iommu=off") != std::string::npos) {
|
||||
h->iommu = "off";
|
||||
h->iommu_why = "the kernel command line turns it off";
|
||||
} else {
|
||||
h->iommu = "unknown";
|
||||
h->iommu_why = "an IOMMU is present; its mode is read from the cards' groups below";
|
||||
}
|
||||
}
|
||||
{
|
||||
int64_t lim = num(root + "/sys/module/ttm/parameters/pages_limit", -1);
|
||||
/* 0 means the driver default, half of RAM. */
|
||||
if (lim == 0 && h->mem_total > 0) lim = h->mem_total / 2 / h->page_size;
|
||||
h->ttm_pages_limit = lim;
|
||||
}
|
||||
h->cwsr_enable = (int)num(root + "/sys/module/amdgpu/parameters/cwsr_enable", -1);
|
||||
{
|
||||
const int64_t d = num(root + "/proc/sys/kernel/io_uring_disabled", -1);
|
||||
h->io_uring = d == 0 ? "available" : d == 1 ? "restricted to a group (io_uring_disabled 1)"
|
||||
: d == 2 ? "refused (io_uring_disabled 2)" : "unknown";
|
||||
}
|
||||
const std::string cpu = root + "/sys/devices/system/cpu/cpu0/cpufreq";
|
||||
h->cpu_governor = line(cpu + "/scaling_governor");
|
||||
h->cpu_epp = line(cpu + "/energy_performance_preference");
|
||||
h->cpu_driver = line(cpu + "/scaling_driver");
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
Facts collect(const std::string& root, const std::vector<std::string>* managed) {
|
||||
Facts f;
|
||||
if (root.empty()) {
|
||||
const long ps = sysconf(_SC_PAGE_SIZE);
|
||||
if (ps > 0) f.host.page_size = ps;
|
||||
}
|
||||
read_host(root, &f.host);
|
||||
/* Every display-class device, used by the engine or not (an iGPU, an excluded card). */
|
||||
for (const std::string& d : list(root + "/sys/bus/pci/devices")) {
|
||||
const std::string cls = line(root + "/sys/bus/pci/devices/" + d + "/class");
|
||||
if (cls.rfind("0x03", 0) != 0) continue;
|
||||
const bool pm =
|
||||
!managed || std::find(managed->begin(), managed->end(), d) != managed->end();
|
||||
CardFacts c;
|
||||
read_card(root, d, pm, &c);
|
||||
f.cards.push_back(std::move(c));
|
||||
}
|
||||
read_kfd(root, &f.cards);
|
||||
/* The IOMMU mode as the cards see it, which beats the command line where both exist:
|
||||
* identity is passthrough, DMA / DMA-FQ translated. A machine can mix both (an
|
||||
* identity-mapped iGPU beside a translated discrete card). */
|
||||
std::map<std::string, std::string> by;
|
||||
for (const CardFacts& c : f.cards)
|
||||
if (!c.iommu_type.empty()) by[c.iommu_type] += (by[c.iommu_type].empty() ? "" : ", ") + c.bdf;
|
||||
if (by.size() == 1) {
|
||||
const bool id = by.begin()->first == "identity";
|
||||
f.host.iommu = id ? "passthrough" : "translated";
|
||||
f.host.iommu_why = "the display devices' IOMMU groups are of type " + by.begin()->first;
|
||||
} else if (by.size() > 1) {
|
||||
f.host.iommu = "mixed";
|
||||
f.host.iommu_why.clear();
|
||||
for (const auto& [t, bdfs] : by)
|
||||
f.host.iommu_why += (f.host.iommu_why.empty() ? "" : "; ") + t + " for " + bdfs;
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
void probe_process(HostFacts* h) {
|
||||
struct rlimit rl{};
|
||||
if (getrlimit(RLIMIT_MEMLOCK, &rl) == 0)
|
||||
h->memlock_soft = rl.rlim_cur == RLIM_INFINITY ? -2 : (int64_t)rl.rlim_cur;
|
||||
#ifdef SYS_io_uring_setup
|
||||
/* Try the call: a seccomp profile (Docker's default) refuses it whatever the sysctl says.
|
||||
* One entry, closed at once. */
|
||||
struct { uint32_t sq_entries, cq_entries, flags, sq_thread_cpu, sq_thread_idle, features,
|
||||
wq_fd, resv[3]; uint64_t sq_off[5]; uint64_t cq_off[5]; } p{};
|
||||
static_assert(sizeof(p) == 120, "io_uring_params is 120 bytes");
|
||||
const long fd = syscall(SYS_io_uring_setup, 1, &p);
|
||||
if (fd >= 0) {
|
||||
close((int)fd);
|
||||
h->io_uring = "available";
|
||||
} else {
|
||||
h->io_uring = fmt("refused (%s)", std::strerror(errno));
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
std::vector<std::string> env_names(char* const* env, const char* prefix) {
|
||||
std::vector<std::string> out;
|
||||
const size_t n = std::strlen(prefix);
|
||||
for (char* const* e = env; e && *e; ++e) {
|
||||
if (std::strncmp(*e, prefix, n) != 0) continue;
|
||||
const char* eq = std::strchr(*e, '=');
|
||||
out.emplace_back(*e, eq ? (size_t)(eq - *e) : std::strlen(*e));
|
||||
}
|
||||
std::sort(out.begin(), out.end());
|
||||
return out;
|
||||
}
|
||||
|
||||
} /* namespace diag */
|
||||
} /* namespace rad */
|
||||
+2463
File diff suppressed because it is too large.
Load diff
+432
@@ -0,0 +1,432 @@
|
||||
/* engine.h -- the startup sequence and the step loop: what happens, in order, between a command
|
||||
* line and a served token. Kept thin; each step is one component doing its own job.
|
||||
*
|
||||
* Startup, per spec §1:
|
||||
*
|
||||
* 1. Load kernel plugins from $RADIANCE_HOME/kernels/, in the configured hierarchy order.
|
||||
* 2. Load the model's metadata only: architecture id, dimensions, quantisation, vocab.
|
||||
* 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, and the core resolves each op against the kernel hierarchy. This phase always
|
||||
* completes and reports every resolution failure, not just the first.
|
||||
* 5. Plan. The placement planner assigns every weight a tier and an execution site against
|
||||
* explicit pool budgets.
|
||||
* 6. Load. Weights are mapped and staged according to the plan.
|
||||
* 7. Serve.
|
||||
*
|
||||
* After step 4 the whole model is known statically: every op, its kernel, the weights it touches,
|
||||
* and the order. The rest of the engine relies on that.
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_core.h"
|
||||
#include "build/startup.h"
|
||||
#include "diag/diag.h"
|
||||
#include "mem/hostarena.h"
|
||||
#include "sched/mem_iface.h"
|
||||
#include "sched/scheduler.h"
|
||||
#include "sample/vocab_view.h"
|
||||
#include "runtime/rank_barrier.h"
|
||||
#include "text/tokenizer.h"
|
||||
#include "format/radfile.h"
|
||||
#include "format/table_copy.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
|
||||
namespace rad {
|
||||
|
||||
class Kld;
|
||||
class StallWatch;
|
||||
namespace gen { class Driver; }
|
||||
struct TierPump;
|
||||
struct TierJob;
|
||||
struct StepSlot;
|
||||
|
||||
struct VramFacts; /* mem/vram_budget.h */
|
||||
struct WeightFootprint; /* place/planner.h */
|
||||
|
||||
class Engine {
|
||||
public:
|
||||
explicit Engine(Config cfg);
|
||||
~Engine();
|
||||
|
||||
/* Steps 1..6. Returns negative after printing what failed and why; missing kernels are
|
||||
* reported as a full list. */
|
||||
int start();
|
||||
|
||||
/* Step 7. Blocks until the server is asked to stop. A device fault is not recoverable
|
||||
* in-process, so it exits non-zero rather than serving from a wedged queue (spec §17).
|
||||
* `watch`, when given, is the startup's stall watch (util/stallwatch.h): held until the
|
||||
* server listens, or the KL mode starts scoring, so the stretch from start() to there
|
||||
* reports where it waits like start() itself. */
|
||||
int serve(std::unique_ptr<StallWatch> watch);
|
||||
|
||||
/* --debug-graph and friends: print everything declare and plan learned, without serving. A
|
||||
* first-class mode rather than a verbose-flag side effect, so what runs is always visible. */
|
||||
int dump();
|
||||
|
||||
const Program& program() const;
|
||||
const Config& config() const { return cfg_; }
|
||||
|
||||
/* The startup report (core/diag/diag.h): every option with its value and source, the
|
||||
* machine, and what on it costs speed or correctness. serve() prints it with RAD_OK before
|
||||
* listening; main prints it with the error start() or serve() failed with, so a server that
|
||||
* never came up still logs its setup. The report then repeats the error on an E line, so the
|
||||
* log's tail shows it. */
|
||||
void print_startup_report(int status);
|
||||
/* The report as JSON, with the hardware re-read, since link and clock state only mean
|
||||
* something under load (/diagnostics). The reading is reused for a second and covers only the
|
||||
* serving cards' power-management files (hardware_facts). */
|
||||
std::string diagnostics_json() const;
|
||||
bool startup_report_printed() const { return report_printed_; }
|
||||
|
||||
private:
|
||||
/* One thread per tensor-parallel rank, each owning one device. Ranks share the address
|
||||
* space, so there is no IPC or serialisation and the step batch is shared by pointer rather
|
||||
* than broadcast (spec §1). */
|
||||
struct Rank;
|
||||
std::vector<std::unique_ptr<Rank>> ranks_;
|
||||
/* The tiers' work in flight: the host-memory copies the transfer streams are running. */
|
||||
std::unique_ptr<TierPump> pump_;
|
||||
/* serve()'s startup stall watch, released when the server listens (run_server) or the KL
|
||||
* mode starts (run_kld). */
|
||||
std::unique_ptr<StallWatch> startup_watch_;
|
||||
std::vector<std::thread> rank_threads_;
|
||||
|
||||
Config cfg_;
|
||||
/* The VRAM split each rank actually takes, filled by Engine::plan. Equal to cfg_ on every
|
||||
* rank whose cache costs as much per token as the dearest rank's. A cheaper rank (an
|
||||
* attention-zero rank) gets a KV pool sized for the common token count and the difference in
|
||||
* its weights pool. Pools::configure and the planner must read the rank's entry, never cfg_;
|
||||
* plan() refuses a rank whose plan and weights pool disagree. */
|
||||
std::vector<Config> rank_cfg_;
|
||||
int64_t kv_planned_tokens_ = 0; /* the common token count plan() sized the re-split pools for */
|
||||
|
||||
/* The model's source, one of the two. A container stays mapped for the engine's life because
|
||||
* the mapped and file tiers read it in place (spec §4.3). A checkpoint served directly also
|
||||
* stays mapped and is read once, at load (spec §4.3). */
|
||||
std::unique_ptr<RadFile> file_;
|
||||
std::unique_ptr<Checkpoint> ckpt_;
|
||||
std::unique_ptr<CheckpointSources> ckpt_src_;
|
||||
/* The source rad_weight_encoding answers from: container entries or checkpoint tensors. */
|
||||
WeightSourceFn sources() const;
|
||||
|
||||
RadModelMeta meta_{};
|
||||
LoadedPlugins plugins_;
|
||||
|
||||
/* RadModelMeta holds bare char*, so the strings behind its key/value table must outlive
|
||||
* every declare. */
|
||||
std::vector<std::string> meta_kv_k_, meta_kv_v_;
|
||||
std::vector<const char*> meta_kv_kp_, meta_kv_vp_;
|
||||
|
||||
void (*arch_step_)(RadCtx*, const RadBatch*) = nullptr;
|
||||
|
||||
int load_plugins();
|
||||
int read_metadata();
|
||||
int read_checkpoint_metadata();
|
||||
/* --rope-scaling over the free-form keys, then the startup line and the context checks;
|
||||
* runs on meta_kv_k_/meta_kv_v_ before their pointer arrays are built. */
|
||||
int apply_rope_scaling();
|
||||
int declare();
|
||||
int plan();
|
||||
/* Resolves --embedding-placement, --vision-tower-placement and --ngram-placement into Config
|
||||
* before the card is split (engine_bringup.cpp describes how auto chooses). `wfs` is every
|
||||
* rank's footprint, read for its towers. `host_late` is the pinned host memory startup
|
||||
* allocates after the tables and outside every pool (the checkpoint store, the host
|
||||
* activation arenas), which a table pinned in host memory must leave room for. */
|
||||
int resolve_table_placement(const std::vector<VramFacts>& facts,
|
||||
const std::vector<int64_t>& emb_bytes,
|
||||
const std::vector<WeightFootprint>& wfs, int64_t kv_floor,
|
||||
int64_t ngram_bytes, bool ngram_device, bool ngram_host,
|
||||
int64_t host_late);
|
||||
/* --ngram-placement ram: one copy of the container's [src, src + n) at file offset `foff`,
|
||||
* shared by every rank. Locked for the host gather, or pinned for a device kernel to read
|
||||
* over the link (`card`). */
|
||||
int copy_table(const uint8_t* src, int64_t n, int64_t foff, bool card, void** out,
|
||||
std::string* why);
|
||||
/* An auto-chosen pinned copy failed: move every rank's n-gram gather to the host. */
|
||||
bool ngram_gather_to_host();
|
||||
/* The table copies: locked ones as [base, base + bytes), pinned ones as rad_dev_alloc
|
||||
* RAD_MEM_HOST_MAPPED ranges, and the container address each copies. Freed in ~Engine after
|
||||
* the ranks that read them are gone. */
|
||||
std::vector<TableCopy> table_copies_;
|
||||
std::vector<void*> card_copies_;
|
||||
std::vector<std::pair<const void*, void*>> table_copy_of_;
|
||||
int load_weights();
|
||||
int configure_kv();
|
||||
/* Maps the step's logits rows back to the sequences that wanted them. Not the identity: a
|
||||
* mid-prompt prefill chunk produces no row, and a speculative verify produces 1 + n_spec. */
|
||||
struct StepOut {
|
||||
std::vector<Request*> reqs; /* the requests that wanted a row, in row order */
|
||||
std::vector<int32_t> first_row; /* [n_seq] that entry's first row, or -1 */
|
||||
/* Leading logits rows the sampler reads. RadBatch::n_out also counts the KL mode's scored
|
||||
* rows after them (Request::score). */
|
||||
int32_t n_rows = 0;
|
||||
std::vector<int32_t> rows; /* [n_out] the device's answer, copied back */
|
||||
int32_t* rb = nullptr; /* the pinned readback collect_issue filled */
|
||||
std::vector<float> lg; /* the first row's logits, at -vv */
|
||||
std::vector<int32_t> token; /* [n_seq] */
|
||||
std::vector<int32_t> accepted; /* [n_seq] */
|
||||
std::vector<uint8_t> eos; /* [n_seq] */
|
||||
/* [n_rows] each sampled row's logprobs, for the rows of requests that asked for them;
|
||||
* empty on a step with none. */
|
||||
std::vector<TokenLogprobs> lp;
|
||||
};
|
||||
|
||||
/* The text frontend, loaded from the container. The sampler's grammars walk `vocab_view_`,
|
||||
* which references `vocab_` and must not outlive it. */
|
||||
std::shared_ptr<const Vocab> vocab_;
|
||||
std::unique_ptr<VocabView> vocab_view_;
|
||||
|
||||
/* The chunk geometry, resolved once and shared: the prefix cache needs the checkpoint interval
|
||||
* at configure time and the scheduler the whole geometry at init. Resolving it separately
|
||||
* would let the cache use the raw interval while the scheduler uses the rounded one. */
|
||||
ChunkGeometry geo_;
|
||||
|
||||
/* One scheduler for every rank: one decision per step, one batch, shared by pointer. */
|
||||
Scheduler sched_;
|
||||
std::unique_ptr<IKVManager> kv_iface_;
|
||||
std::unique_ptr<IPrefixCache> pc_iface_;
|
||||
|
||||
/* The release point. Width is tp + 1: the scheduler thread also takes part. */
|
||||
std::unique_ptr<RankBarrier> barrier_;
|
||||
std::atomic<const RadBatch*> step_batch_{nullptr};
|
||||
/* What a release asks the ranks to issue: the forward pass and its sampler (kIssueAll), the
|
||||
* forward pass alone (kIssueModel: the next step's, issued before this one is read back), or
|
||||
* that pass's sampler alone (kIssueSampler, once the host has committed its inputs). Every
|
||||
* release must set it; a stale value would make a draft pass issue only its sampler. */
|
||||
enum { kIssueAll = 0, kIssueModel = 1, kIssueSampler = 2 };
|
||||
std::atomic<int> issue_what_{kIssueAll};
|
||||
std::atomic<int> step_status_{RAD_OK};
|
||||
std::atomic<bool> stopping_{false};
|
||||
/* The error the step loop ended on; RAD_OK while running or after a clean stop. Written once
|
||||
* by fail_loop(); read by the server watcher to stop HTTP and by serve() to return it. */
|
||||
std::atomic<int> loop_status_{RAD_OK};
|
||||
int fail_loop(int st);
|
||||
|
||||
/* This step's scored rows (Request::token_scores): a logits row and the result it fills.
|
||||
* Written by the scheduler thread while the ranks are parked, read by them during the step,
|
||||
* consumed by collect_step. */
|
||||
std::vector<std::pair<int32_t, TokenScores*>> score_rows_;
|
||||
int stage_scored_rows(const StepPlan& plan, const StepOut& so);
|
||||
int issue_scored_rows(Rank& r);
|
||||
int collect_scored_rows();
|
||||
|
||||
/* Gate for the sampler's host work, which runs while the device executes the model.
|
||||
* Staging sampler parameters (and, with a grammar, a whole-vocabulary mask per draft
|
||||
* position) touches no stream: Sampler::run issues every upload on the rank thread. So the
|
||||
* ranks enqueue the model first, the scheduler runs build_step meanwhile, and the ranks wait
|
||||
* here before enqueueing the sampler chain. One-shot per step, reset while the ranks are
|
||||
* parked at the release, so no rank can see a stale ready flag. */
|
||||
std::mutex build_mu_;
|
||||
std::condition_variable build_cv_;
|
||||
bool build_ready_ = false;
|
||||
int build_status_ = RAD_OK;
|
||||
|
||||
/* Scratch for the checkpoint copies: one sequence's state slots, reused so the step path
|
||||
* does not allocate. See state_slots_of. */
|
||||
std::vector<int32_t> ckpt_slots_;
|
||||
std::vector<int32_t> ckpt_win_; /* KVManager::window_rows, same reuse */
|
||||
bool state_slots_of(uint64_t seq, std::vector<int32_t>* out) const;
|
||||
|
||||
int load_vocab();
|
||||
int declare_sampler(int rank, RadBuilder* b, int64_t logits_width, bool sizing = false);
|
||||
/* The build context for every declare of rank `rank` at `max_tok`; the real declare and the
|
||||
* arena's sizing declares differ only in max_tok. */
|
||||
RadBuildCtx build_ctx(int rank, int64_t max_tok) const;
|
||||
void probe_arena_levels();
|
||||
int step_loop();
|
||||
/* Issue the copy of the step's sampled ids to the host, then wait for and interpret them.
|
||||
* Split so the copy is issued before draft passes overwrite the ids, and the wait comes after
|
||||
* them. */
|
||||
int collect_issue(StepOut& so);
|
||||
int collect_step(const RadBatch* b, StepOut& so);
|
||||
int row_logprobs(StepOut& so, int32_t row, int32_t token);
|
||||
/* The step's end on the card: after its last draft pass and the host readbacks, before the
|
||||
* step issued ahead. collect_step waits on this event, not the stream, so the card runs the
|
||||
* next step while the host commits this one. */
|
||||
int mark_step_end(const RadBatch* b, StepOut& so);
|
||||
RadEvent step_end_ = nullptr;
|
||||
|
||||
/* The draft head as declared (rad_declare_drafter), zeroed when no speculative window was
|
||||
* asked for. `kind` selects which of the two drivers below runs. `drafter_name_` owns the
|
||||
* string because RadDrafterDecl::name points into the Program. */
|
||||
RadDrafterDecl drafter_{};
|
||||
std::string drafter_name_;
|
||||
|
||||
/* Serial driver (spec §10): `depth` dependent passes after the step commits, each embedding
|
||||
* the previous proposal. MTP, EAGLE and Medusa-serial have this shape. */
|
||||
std::vector<int32_t> draft_out_; /* [rows][depth], what each pass proposed */
|
||||
|
||||
/* Host side of every step-path readback (sampled tokens, draft proposals). Pinned, because a
|
||||
* device-to-host copy into pageable memory bounces synchronously through a staging buffer and
|
||||
* blocks on the whole stream; into pinned memory it is one more stream packet and the step's
|
||||
* own wait is the only wait. Grown on first use to the largest readback requested. */
|
||||
struct Readback {
|
||||
int32_t* p = nullptr;
|
||||
int64_t n = 0;
|
||||
int32_t* reserve(int64_t count);
|
||||
~Readback();
|
||||
};
|
||||
Readback readback_;
|
||||
/* Embedding program (rad_declare_pooled): no sampler; a step's answer is the pooled buffer's
|
||||
* first n_seq rows. `pooled_host_` is their pinned landing area, [max_seqs, pooled_dim_] f32;
|
||||
* collect_pooled copies them behind the step and hands each row to its sink after the
|
||||
* step's one wait. */
|
||||
bool embedding_ = false;
|
||||
int64_t pooled_dim_ = 0;
|
||||
float* pooled_host_ = nullptr;
|
||||
int collect_pooled_issue(const RadBatch* b, StepOut& so);
|
||||
int collect_pooled(const RadBatch* b, StepOut& so);
|
||||
/* Image generator (rad_declare_generator): the driver that turns requests into passes and the
|
||||
* loop that runs them, replacing the scheduler and step loop (engine_gen.cpp). Null for every
|
||||
* other program. */
|
||||
std::unique_ptr<gen::Driver> gen_;
|
||||
int gen_loop();
|
||||
bool serial_drafting() const;
|
||||
int advance_all(int mode, int round, bool from_proposal, int rows = -1);
|
||||
int issue_serial_drafter(int step, 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: requires that the drafter, if any, runs on the card (a
|
||||
* block drafter and the prompt-lookup drafter both read the committed sequence). */
|
||||
bool pipelining_ = false;
|
||||
int finish_serial_drafter(const StepOut& so);
|
||||
/* Handed from issue_serial_drafter to finish_serial_drafter: the drafting rows, the rounds
|
||||
* asked for, and the rounds that ran. */
|
||||
std::vector<Scheduler::SerialRow> serial_row_;
|
||||
int serial_rounds_ = 0, serial_rows_ = 0, serial_done_ = 0;
|
||||
/* The StepSlots and end-of-generation ids on every rank, and the pinned host copy of rank 0's
|
||||
* slots the step reads back (sched/advance.h). */
|
||||
int step_state_init();
|
||||
void step_state_fini();
|
||||
StepSlot* slots_host_ = nullptr;
|
||||
|
||||
/* Step-time attribution, Debug only (see the barrier in step_loop): time per scheduler phase.
|
||||
* The nine phases sum to the whole step, including the readback, commit and drafter after the
|
||||
* join. */
|
||||
enum Ph { PH_PLAN, PH_BEGIN, PH_BUILD, PH_PRE, PH_RANKS, PH_SAVE, PH_COLLECT, PH_COMMIT,
|
||||
PH_DRAFT, PH_N };
|
||||
double phase_us_[PH_N] = {};
|
||||
int phase_n_ = 0;
|
||||
std::chrono::steady_clock::time_point phase_t_{};
|
||||
void phase_mark(int p);
|
||||
|
||||
/* Block driver (spec §10): a context pass mirroring the step just run, then one pass that
|
||||
* fills every drafted position at once. DFlash2 has this shape. */
|
||||
int run_block_drafter(int step);
|
||||
/* Encoder driver (spec §11, core/engine_mm.cpp): encodes every media item the scheduler waits
|
||||
* on, in passes of whole segments, and reads it back into the item. Runs between steps, never
|
||||
* inside one. */
|
||||
int run_encodes();
|
||||
int32_t enc_step_ = 0;
|
||||
void drain_completed();
|
||||
/* Terminal ids drain_completed() took, reused so steady state allocates nothing. */
|
||||
std::vector<uint64_t> done_;
|
||||
/* The tiers' per-iteration work: collect a landed copy, start the next, make room in a full
|
||||
* arena. Never waits on the device; the scheduler's lock covers only the bookkeeping. */
|
||||
void tier_tick();
|
||||
/* --prefix-cache-ttl, once a second, with or without the tiers (PrefixCache::expire). */
|
||||
void expire_tick(uint64_t now_ns);
|
||||
uint64_t expire_last_ns_ = 0;
|
||||
/* Issue and land every waiting host copy now. Called under the scheduler's lock by an
|
||||
* eviction that would otherwise erase what the copies cover. True when any landed. */
|
||||
bool flush_copies();
|
||||
/* The KV loan: what the cache is not using, lent to every rank's expert slab at addresses the
|
||||
* cache already owns (KVManager, the loan block). Lives here, not in the scheduler, because
|
||||
* rank 0's cache sets the amount while every rank's mover fills or empties slots, and a mover
|
||||
* may only be driven while its rank thread is parked, which this thread knows. `idle` also
|
||||
* runs each mover's own fill, which a busy engine gets from the step. */
|
||||
void loan_tick(bool idle);
|
||||
bool lending_ = false;
|
||||
uint64_t loan_last_ns_ = 0;
|
||||
/* The activation arena's loan (Engine::arena_step). `arena_rows_[k]` is the largest step Ctx
|
||||
* level k serves (level 0 is the full plan); empty when the arena lends nothing. The floor is
|
||||
* the largest recent step: the loan grows past it only after no step that large has run for a
|
||||
* while, so a run of prefill chunks does not refill and recall the slab between chunks. */
|
||||
int arena_step(const RadBatch* b);
|
||||
void arena_tick(uint64_t now_ns);
|
||||
int arena_level(int64_t rows) const;
|
||||
std::vector<int64_t> arena_rows_;
|
||||
/* The span's shared level (Engine::probe_arena_levels): the rows of the level a step of one
|
||||
* interval runs at under --prefill-span, where the prefill stager's ring is the level's own
|
||||
* (stager.h); 0 without one. */
|
||||
int64_t arena_span_rows_ = 0;
|
||||
int64_t arena_floor_ = 0;
|
||||
int64_t arena_last_ = 0;
|
||||
uint64_t arena_floor_ns_ = 0;
|
||||
/* VRAM the budget reserves for allocations after start(), on top of --gpu-headroom-mib: the
|
||||
* step batch's staging (allocated by serve()) and what is built on first use, if ever (the KV
|
||||
* tiers' copy staging, the second compute lane's queue). Bring-up's final VRAM reading is
|
||||
* checked against both. */
|
||||
int64_t late_step_bytes_ = 0;
|
||||
int64_t late_lazy_bytes_ = 0;
|
||||
/* Linear-state snapshot store: pinned host memory, --checkpoint-slots slots, each holding every
|
||||
* rank's shard of one snapshot (KVManager::set_checkpoint_store). Off the card because no
|
||||
* kernel reads a snapshot; it is only copied back into a sequence's state. */
|
||||
HostArena ck_store_;
|
||||
int run_server();
|
||||
/* KL mode (core/kld.h), replacing run_server: submits the corpus documents as scoring
|
||||
* requests and hands every step's scored rows, copied to the host, to `kld_`. One pinned
|
||||
* block per rank, holding a step's tokens of that rank's logits columns. */
|
||||
int run_kld();
|
||||
int score_rows(const RadBatch* b, const StepOut& so);
|
||||
std::unique_ptr<Kld> kld_;
|
||||
std::vector<float*> kld_host_;
|
||||
std::vector<int64_t> kld_vocab0_, kld_width_; /* per rank read: its logits columns */
|
||||
/* The engine half of /server_info, as a JSON object. See the definition in engine.cpp. */
|
||||
std::string engine_info() const;
|
||||
|
||||
/* ---- startup report inputs (engine_diag.cpp). `decisions_` holds each value startup resolved
|
||||
* and why, recorded where it was resolved; the rest are facts only startup saw. */
|
||||
std::vector<diag::Decision> decisions_;
|
||||
void decide(const std::string& key, const std::string& value, const std::string& why) {
|
||||
diag::decide(&decisions_, key, value, why);
|
||||
}
|
||||
std::string devnote_; /* the devices usable_devices left out, and why */
|
||||
int p2p_measured_ = -1; /* 1 peer to peer, 0 through host memory, -1 not asked */
|
||||
std::string p2p_blocked_;
|
||||
bool has_ngram_ = false; /* the model carries an n-gram table */
|
||||
std::string prefix_off_why_; /* why the engine itself turned prefix caching off, or "" */
|
||||
std::vector<std::string> env_set_; /* the RADIANCE_* names set when the engine was made */
|
||||
bool report_printed_ = false;
|
||||
/* Runtime device identity (PCI address, name, integrated flag, runtime version), read once in
|
||||
* start() beside usable_devices. Later reports make no runtime call: after a failed start
|
||||
* there may have been a device fault, and on an HTTP thread (/diagnostics) a runtime call can
|
||||
* wait on a lock the launch path holds (see DeviceBackend::vram_used). */
|
||||
struct DevId { int device = -1; std::string bdf, name; bool integrated = false; };
|
||||
std::vector<DevId> dev_ids_;
|
||||
std::string runtime_version_;
|
||||
void identify_devices(const std::vector<std::string>& names);
|
||||
/* Syscall-only facts (diag::probe_process), read once at the first report: the memlock limit
|
||||
* cannot change under a running process, and the io_uring probe need not repeat per
|
||||
* /diagnostics request. */
|
||||
bool probed_ = false;
|
||||
int64_t memlock_soft_ = -1;
|
||||
std::string io_uring_;
|
||||
/* The last /diagnostics hardware reading, reused for kDiagReuseNs. The SMU answers the card
|
||||
* files under the driver's power-management lock, so a polling client must not become a
|
||||
* stream of SMU requests beside the server. */
|
||||
mutable std::mutex diag_mu_;
|
||||
mutable diag::Facts diag_facts_;
|
||||
mutable uint64_t diag_read_ns_ = 0;
|
||||
/* `serving`: read power-management files only for the cards the ranks serve on
|
||||
* (diag::collect's `managed`). */
|
||||
diag::Facts hardware_facts(bool serving) const;
|
||||
diag::RunFacts run_facts(bool failed) const;
|
||||
|
||||
/* One dispatch of the tiering seam: retire what landed, credit last step's routing, issue
|
||||
* what the heat engine proposes. A member because Rank is private; a no-op on a static plan.
|
||||
* The definition explains why a step is the unit. */
|
||||
void tiering_dispatch(Rank& r, int step);
|
||||
void rank_loop(int rank);
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,155 @@
|
||||
/* engine_diag.cpp -- the startup report's engine half: facts only a started engine has, joined to
|
||||
* the machine's (core/diag/diag.h).
|
||||
*
|
||||
* Cards are joined by PCI address: the runtime numbers devices its own way (a visibility mask
|
||||
* renumbers them, an integrated GPU may come first), while the kernel names them by bus address.
|
||||
*/
|
||||
#include "engine_priv.h"
|
||||
#include "device/device.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
namespace rad {
|
||||
|
||||
namespace {
|
||||
/* How long /diagnostics reuses a reading of the machine. */
|
||||
constexpr uint64_t kDiagReuseNs = 1000000000ull;
|
||||
} /* namespace */
|
||||
|
||||
void Engine::identify_devices(const std::vector<std::string>& names) {
|
||||
dev_ids_.clear();
|
||||
runtime_version_ = dev_runtime_version();
|
||||
for (int d = 0; d < (int)names.size(); ++d) {
|
||||
DevId id;
|
||||
id.device = d;
|
||||
id.bdf = dev_pci_address(d);
|
||||
if (id.bdf.empty()) continue;
|
||||
id.name = names[(size_t)d];
|
||||
id.integrated = dev_integrated(d);
|
||||
dev_ids_.push_back(std::move(id));
|
||||
}
|
||||
}
|
||||
|
||||
diag::Facts Engine::hardware_facts(bool serving) const {
|
||||
std::vector<std::string> mine;
|
||||
for (const DevId& id : dev_ids_)
|
||||
for (const auto& r : ranks_)
|
||||
if (r->device == id.device) mine.push_back(id.bdf);
|
||||
diag::Facts f = diag::collect("", serving ? &mine : nullptr);
|
||||
f.host.runtime = runtime_version_;
|
||||
if (probed_) {
|
||||
f.host.memlock_soft = memlock_soft_;
|
||||
f.host.io_uring = io_uring_;
|
||||
}
|
||||
for (const DevId& id : dev_ids_)
|
||||
for (diag::CardFacts& c : f.cards) {
|
||||
if (c.bdf != id.bdf) continue;
|
||||
c.name = id.name;
|
||||
c.device = id.device;
|
||||
c.integrated = id.integrated;
|
||||
for (const auto& r : ranks_)
|
||||
if (r->device == id.device) c.rank = r->index;
|
||||
if (c.rank >= 0) c.dma = dev_dma_lane(id.device);
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
diag::RunFacts Engine::run_facts(bool failed) const {
|
||||
diag::RunFacts r;
|
||||
r.version = RAD_VERSION;
|
||||
#if defined(RAD_HAVE_HIP) && RAD_HAVE_HIP
|
||||
r.device_build = true;
|
||||
#else
|
||||
r.device_build = false;
|
||||
#endif
|
||||
r.tp = cfg_.tp;
|
||||
r.host_backend = device_is_host();
|
||||
r.failed = failed;
|
||||
r.p2p = cfg_.tp > 1 ? p2p_measured_ : -1;
|
||||
r.p2p_forced_off = cfg_.p2p == RAD_P2P_OFF;
|
||||
r.p2p_blocked = p2p_blocked_;
|
||||
if (!devnote_.empty()) r.ignored.push_back(devnote_);
|
||||
r.tp_wire_lossy = !cfg_.tp_wire_exact;
|
||||
r.tp_wire_min_kb = cfg_.tp_wire_min_kb;
|
||||
r.prefix_cache = cfg_.prefix_cache;
|
||||
r.prefix_cache_off_why = prefix_off_why_;
|
||||
r.host_pool_mib = cfg_.host_pool_mib;
|
||||
{
|
||||
int64_t pinned = 0, mapped = 0, n = 0;
|
||||
rad_dev_alloc_totals(RAD_MEM_HOST_PINNED, &pinned, &n);
|
||||
rad_dev_alloc_totals(RAD_MEM_HOST_MAPPED, &mapped, &n);
|
||||
r.pinned_bytes = pinned + mapped;
|
||||
}
|
||||
/* The most any rank streams from the host, since each step waits for the slowest rank.
|
||||
* Excludes host-placed tables (the embedding, read a few rows per step; the towers, once per
|
||||
* image). */
|
||||
for (const auto& rk : ranks_) {
|
||||
const Plan& p = rk->plan;
|
||||
const int64_t host = p.totals.bytes[(int)Tier::HostPinned] +
|
||||
p.totals.bytes[(int)Tier::HostPageable] - p.forced_host_used;
|
||||
r.host_weight_bytes = std::max(r.host_weight_bytes, std::max<int64_t>(host, 0));
|
||||
r.file_weight_bytes = std::max(r.file_weight_bytes, p.totals.bytes[(int)Tier::SSD]);
|
||||
}
|
||||
for (const TableCopy& t : table_copies_) r.locked_bytes += (int64_t)t.bytes;
|
||||
r.ngram_placement = has_ngram_ ? table_placement_name(cfg_.ngram_resolved) : "";
|
||||
r.reference_kernels = cfg_.accept_reference_kernels;
|
||||
r.profile_ops = cfg_.profile_ops;
|
||||
r.deterministic = cfg_.deterministic;
|
||||
r.environment = env_set_;
|
||||
return r;
|
||||
}
|
||||
|
||||
void Engine::print_startup_report(int status) {
|
||||
report_printed_ = true;
|
||||
if (!probed_) {
|
||||
diag::HostFacts h;
|
||||
diag::probe_process(&h);
|
||||
memlock_soft_ = h.memlock_soft;
|
||||
io_uring_ = h.io_uring;
|
||||
probed_ = true;
|
||||
}
|
||||
std::vector<diag::ConfigRow> rows = diag::config_rows(cfg_);
|
||||
std::vector<diag::Decision> derived;
|
||||
diag::merge(&rows, decisions_, &derived);
|
||||
const diag::Facts f = hardware_facts(false);
|
||||
const diag::RunFacts r = run_facts(status < 0);
|
||||
const std::vector<diag::Finding> found = diag::check(f, r);
|
||||
/* One log call per line: the logger formats into a fixed buffer, and every line keeps the
|
||||
* level tag. */
|
||||
const std::string text = diag::render(rows, derived, f, r, found);
|
||||
size_t at = 0;
|
||||
while (at < text.size()) {
|
||||
size_t nl = text.find('\n', at);
|
||||
if (nl == std::string::npos) nl = text.size();
|
||||
RAD_INFO("%s", text.substr(at, nl - at).c_str());
|
||||
at = nl + 1;
|
||||
}
|
||||
/* Each warning also on its own W line, for readers filtering a log by level. */
|
||||
for (const diag::Finding& x : found)
|
||||
if (x.level == diag::Finding::Warn)
|
||||
RAD_WARN("startup report: %s: %s. Fix: %s", x.id.c_str(), x.what.c_str(), x.fix.c_str());
|
||||
/* Repeat the failure last, since the original error line is now above the report. */
|
||||
if (status < 0)
|
||||
RAD_ERR("startup stopped: %s (the reason is said above the startup report)",
|
||||
rad_strerror(status));
|
||||
}
|
||||
|
||||
std::string Engine::diagnostics_json() const {
|
||||
std::vector<diag::ConfigRow> rows = diag::config_rows(cfg_);
|
||||
std::vector<diag::Decision> derived;
|
||||
diag::merge(&rows, decisions_, &derived);
|
||||
diag::Facts f;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(diag_mu_);
|
||||
const uint64_t now = rad_mono_ns();
|
||||
if (diag_read_ns_ == 0 || now - diag_read_ns_ >= kDiagReuseNs) {
|
||||
diag_facts_ = hardware_facts(true);
|
||||
diag_read_ns_ = now;
|
||||
}
|
||||
f = diag_facts_;
|
||||
}
|
||||
const diag::RunFacts r = run_facts(false);
|
||||
return diag::to_json(rows, derived, f, r, diag::check(f, r));
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,349 @@
|
||||
/* engine_draft.cpp -- the two drafter drivers (spec §10).
|
||||
*
|
||||
* A draft head runs as extra passes after the trunk step. SERIAL runs `depth` dependent passes;
|
||||
* BLOCK runs a context pass, then one pass that fills the whole block. The architecture plugin
|
||||
* declares which (rad_declare_drafter); nothing here depends on the model.
|
||||
*/
|
||||
#include "engine_priv.h"
|
||||
|
||||
#include "sched/scheduler.h"
|
||||
#include "device/device.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* ------------------------------------------------------------------ the card's step state */
|
||||
/* Every rank's zeroed StepSlots and sorted end-of-generation ids, and the pinned host copy of rank
|
||||
* 0's slots the step reads back. Allocated once at start, so the step path never allocates. */
|
||||
int Engine::step_state_init() {
|
||||
std::vector<int32_t> eog;
|
||||
if (vocab_) eog = vocab_->eog();
|
||||
std::sort(eog.begin(), eog.end());
|
||||
eog.erase(std::unique(eog.begin(), eog.end()), eog.end());
|
||||
const int64_t n_slot = cfg_.max_seqs > 0 ? cfg_.max_seqs : 1;
|
||||
const int64_t slot_bytes = n_slot * (int64_t)sizeof(StepSlot);
|
||||
for (auto& rk : ranks_) {
|
||||
RAD_TRY(rad_dev_set(rk->device));
|
||||
rk->step_slots = static_cast<StepSlot*>(rad_dev_alloc(slot_bytes, RAD_MEM_DEVICE));
|
||||
rk->n_eog = (int32_t)eog.size();
|
||||
rk->eog = static_cast<int32_t*>(
|
||||
rad_dev_alloc(std::max<int64_t>(1, (int64_t)eog.size()) * 4, RAD_MEM_DEVICE));
|
||||
if (!rk->step_slots || !rk->eog) {
|
||||
RAD_ERR("step state: no device memory for %lld slot(s) on card %d",
|
||||
(long long)n_slot, rk->device);
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
RAD_TRY(rad_memset_async(rk->step_slots, 0, slot_bytes, rk->ctx.stream()));
|
||||
if (!eog.empty())
|
||||
RAD_TRY(rad_memcpy_async(rk->eog, eog.data(), (int64_t)eog.size() * 4,
|
||||
rk->ctx.stream()));
|
||||
RAD_TRY(rad_stream_sync(rk->ctx.stream()));
|
||||
}
|
||||
if (!ranks_.empty()) RAD_TRY(rad_dev_set(ranks_[0]->device));
|
||||
slots_host_ = static_cast<StepSlot*>(rad_dev_alloc(slot_bytes, RAD_MEM_HOST_PINNED));
|
||||
if (!slots_host_) return RAD_E_NOMEM;
|
||||
RAD_TRY(rad_event_create_as(&step_end_, RAD_EVENT_LOCAL | RAD_EVENT_HOST_WAIT));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void Engine::step_state_fini() {
|
||||
for (auto& rk : ranks_) {
|
||||
(void)rad_dev_set(rk->device);
|
||||
if (rk->step_slots) rad_dev_free(rk->step_slots, RAD_MEM_DEVICE);
|
||||
if (rk->eog) rad_dev_free(rk->eog, RAD_MEM_DEVICE);
|
||||
rk->step_slots = nullptr;
|
||||
rk->eog = nullptr;
|
||||
}
|
||||
if (slots_host_) rad_dev_free(slots_host_, RAD_MEM_HOST_PINNED);
|
||||
slots_host_ = nullptr;
|
||||
if (step_end_) rad_event_destroy(step_end_);
|
||||
step_end_ = nullptr;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the serial driver
|
||||
*
|
||||
* RAD_DRAFT_SERIAL: one head pass per drafted token after the trunk step (MTP, EAGLE, Medusa).
|
||||
* Round 1 consumes the sampled token and the hidden state of the position it came from, which
|
||||
* depends on how many drafts were accepted; it runs in the history pass, whose rows include that
|
||||
* position (RadBatch::draft_out_ids).
|
||||
*
|
||||
* The card, not the host, resolves those positions (sched/advance.h): behind the trunk's sampler
|
||||
* every rank runs the acceptance into its StepSlots, and an advance before each draft pass fills
|
||||
* in its positions and tokens. So the host issues the whole step (trunk, history, every round)
|
||||
* without waiting and reads back once after the last round, instead of idling the card for a
|
||||
* readback, commit and batch build per step.
|
||||
*
|
||||
* Each pass is an ordinary RadBatch through the same barrier and sampler chain; `draft_pass`
|
||||
* tells the plugin to run the head. Tokens go out through set_draft(), like prompt lookup's; a
|
||||
* sequence the head declined keeps n_draft 0, leaving it to the n-gram drafter.
|
||||
*/
|
||||
bool Engine::serial_drafting() const {
|
||||
return drafter_.kind == RAD_DRAFT_SERIAL && drafter_.depth > 0;
|
||||
}
|
||||
|
||||
/* One advance on every rank against the scheduler's latest build, over its first `rows` rows
|
||||
* when given, else all. */
|
||||
int Engine::advance_all(int mode, int round, bool from_proposal, int rows) {
|
||||
for (size_t i = 0; i < ranks_.size(); ++i) {
|
||||
Rank& rk = *ranks_[i];
|
||||
AdvanceArgs a = sched_.advance_args((int)i);
|
||||
if (rows >= 0 && rows < a.n_seq) a.n_seq = rows;
|
||||
a.mode = mode;
|
||||
a.round = round;
|
||||
a.st = rk.step_slots;
|
||||
a.eog = rk.eog;
|
||||
a.n_eog = rk.n_eog;
|
||||
if (from_proposal) {
|
||||
a.src = static_cast<const int32_t*>(drafter_.proposal ? rk.ctx.buf_ptr(drafter_.proposal)
|
||||
: rk.ctx.buf_ptr(rk.tok_buf));
|
||||
a.src_pitch = (drafter_.proposal && drafter_.proposal_pitch > 0)
|
||||
? drafter_.proposal_pitch : 1;
|
||||
} else {
|
||||
a.src = static_cast<const int32_t*>(rk.ctx.buf_ptr(rk.tok_buf));
|
||||
}
|
||||
if (!a.src || !a.st) {
|
||||
RAD_ERR("drafter '%s': rank %zu has no %s to advance from", drafter_.name, i,
|
||||
a.st ? "proposal buffer" : "step state");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
RAD_TRY(step_advance(a, rk.ctx.stream()));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Issue the step's draft passes behind it, without waiting. After the trunk's ranks join: the
|
||||
* acceptance on every rank, the sampled-id readback (before a round can overwrite them), the
|
||||
* history pass and every round, then the final proposal into the slots and their readback.
|
||||
* Nothing synchronises here; collect_step has the step's one wait. */
|
||||
int Engine::issue_serial_drafter(int step, StepOut& so) {
|
||||
serial_rounds_ = 0;
|
||||
serial_rows_ = 0;
|
||||
serial_done_ = 0;
|
||||
/* A step issued ahead continues from the card's acceptance, so run it even without drafts. */
|
||||
if (!serial_drafting()) {
|
||||
if (pipelining_) RAD_TRY(advance_all(ADV_ACCEPT, 0, false));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
RAD_TRY(advance_all(ADV_ACCEPT, 0, false));
|
||||
RAD_TRY(collect_issue(so));
|
||||
|
||||
int rounds = drafter_.depth;
|
||||
serial_row_.resize((size_t)cfg_.max_seqs);
|
||||
/* `n` counts rows that can draft. It can be zero while the history pass still has work (a
|
||||
* mid-prompt sequence has hidden states the head needs but no token to propose from). */
|
||||
const int n = sched_.serial_begin(&rounds, serial_row_.data(), (int)serial_row_.size());
|
||||
if (rounds <= 0) return RAD_OK;
|
||||
serial_rounds_ = rounds;
|
||||
serial_rows_ = n;
|
||||
|
||||
/* RADIANCE_DEBUG_STAGE: running means of a draft pass's host time: batch + advance, greedy
|
||||
* sampler chain, barrier release and issue. They cost the step nothing until their sum exceeds
|
||||
* the previous pass's device time. */
|
||||
static const bool stg = std::getenv("RADIANCE_DEBUG_STAGE") != nullptr;
|
||||
static double a_batch = 0, a_samp = 0, a_rel = 0, a_iss = 0;
|
||||
static long n_pass = 0;
|
||||
|
||||
/* 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, writing the head's own K and V (nothing else does). It is
|
||||
* also draft round 1 for drafting rows, whose inputs are the last row of their history run
|
||||
* (RadBatch::draft_out_ids), so it ends in the lm_head over those rows. Round r >= 2 embeds
|
||||
* round r-1's proposal, which the advance takes from the proposal buffer on the card. */
|
||||
const int drafted = rd == 0 ? (int)db->n_draft_out : n;
|
||||
RAD_TRY(advance_all(rd == 0 ? ADV_HIST : ADV_ROUND, rd, rd > 0));
|
||||
const auto tB = std::chrono::steady_clock::now();
|
||||
|
||||
/* Greedy, not the request's sampler: the target verifies against its own draw
|
||||
* (core/sample/accept.h), so sampling a draft would spend the request's RNG stream and
|
||||
* lower acceptance. A head with its own proposal buffer samples nothing (a zero-row
|
||||
* chain). */
|
||||
for (auto& rk : ranks_) {
|
||||
int s = rk->sampler.build_greedy(drafter_.proposal ? 0 : drafted);
|
||||
if (s < 0) {
|
||||
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);
|
||||
/* Timed separately: the first crossing releases the parked ranks (the wake), the second
|
||||
* waits for them to finish issuing (the issue). */
|
||||
barrier_->arrive_and_wait();
|
||||
const auto tC2 = std::chrono::steady_clock::now();
|
||||
barrier_->arrive_and_wait();
|
||||
const auto tD = std::chrono::steady_clock::now();
|
||||
|
||||
int st = step_status_.load(std::memory_order_acquire);
|
||||
if (st < 0) {
|
||||
RAD_ERR("drafter '%s': pass %d of step %d failed: %s -- the engine cannot continue",
|
||||
drafter_.name, rd, step, rad_strerror(st));
|
||||
return st;
|
||||
}
|
||||
if (stg) {
|
||||
using us = std::chrono::duration<double, std::micro>;
|
||||
a_batch += us(tB - tA).count();
|
||||
a_samp += us(tC - tB).count();
|
||||
a_rel += us(tC2 - tC).count();
|
||||
a_iss += us(tD - tC2).count();
|
||||
if (++n_pass % 400 == 0)
|
||||
RAD_INFO("draft: %ld passes; batch %.1f, sampler %.1f, release %.1f, issue %.1f us "
|
||||
"a pass", n_pass, a_batch / (double)n_pass, a_samp / (double)n_pass,
|
||||
a_rel / (double)n_pass, a_iss / (double)n_pass);
|
||||
}
|
||||
if (rd > 0) serial_done_ = rd;
|
||||
else if (drafted > 0) serial_done_ = 1;
|
||||
}
|
||||
if (serial_done_ <= 0 || n <= 0) return RAD_OK;
|
||||
|
||||
/* The last round's proposal into the slots, then rank 0's slots back to the host. Only the
|
||||
* drafting rows: at depth 1 the last pass is the history pass, whose later rows only carried
|
||||
* history (Scheduler::serial_batch). */
|
||||
RAD_TRY(advance_all(ADV_TAKE, serial_done_, true, n));
|
||||
Rank& r0 = *ranks_[0];
|
||||
RAD_TRY(rad_memcpy_async(slots_host_, r0.step_slots,
|
||||
(int64_t)cfg_.max_seqs * (int64_t)sizeof(StepSlot), r0.ctx.stream()));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* After commit: check the host's acceptance against the card's, publish the proposals through
|
||||
* set_draft, and move the history watermark. The card's acceptance positioned every draft pass,
|
||||
* so a disagreement is a defect and the step is refused. */
|
||||
int Engine::finish_serial_drafter(const StepOut& so) {
|
||||
if (!serial_drafting() || serial_rounds_ <= 0) return RAD_OK;
|
||||
const StepPlan& plan = sched_.plan();
|
||||
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) {
|
||||
/* No draft for a request the sampler will not speculate on (a constraining grammar that
|
||||
* cannot snapshot its state); the sampler would refuse the next step otherwise. */
|
||||
if (!r0.sampler.allows_speculation(serial_row_[(size_t)i].seq)) continue;
|
||||
sched_.set_draft(serial_row_[(size_t)i].seq,
|
||||
&draft_out_[(size_t)i * (size_t)rounds], done);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the block driver
|
||||
*
|
||||
* RAD_DRAFT_BLOCK (block diffusion, e.g. DFlash2): one backbone pass over `block` positions (an
|
||||
* anchor and `block - 1` masked slots) proposes `depth` tokens at once, with no rounds. `block` is
|
||||
* the drafter's own: depth + 1 when the anchor row predicts nothing, depth when it does
|
||||
* (rad_builder.h). Two passes:
|
||||
*
|
||||
* Context pass: mirrors the trunk step just run. The drafter projects the trunk's tapped hidden
|
||||
* states and stores K and V for those positions in its own cache, over exactly the trunk's rows
|
||||
* in order.
|
||||
*
|
||||
* Query pass: the drafter's layers over the block fill every masked position. Its own selector
|
||||
* writes the tokens to the plugin's `proposal` buffer, which is why RAD_DRAFT_BLOCK requires
|
||||
* one.
|
||||
*
|
||||
* Proposals go out through set_draft() like every other.
|
||||
*/
|
||||
int Engine::run_block_drafter(int step) {
|
||||
if (drafter_.kind != RAD_DRAFT_BLOCK || drafter_.depth <= 0) return RAD_OK;
|
||||
|
||||
const int steps = drafter_.depth;
|
||||
/* The row count is the drafter's (defaulted and checked by declare_drafter). */
|
||||
const int block = drafter_.block > 0 ? (int)drafter_.block : drafter_.depth + 1;
|
||||
std::vector<Scheduler::BlockRow> rows((size_t)cfg_.max_seqs);
|
||||
const int n = sched_.block_begin(block, steps, (int)drafter_.window, drafter_.mask_token,
|
||||
rows.data(), (int)rows.size());
|
||||
|
||||
Rank& r0 = *ranks_[0];
|
||||
void* prop = r0.ctx.buf_ptr(drafter_.proposal);
|
||||
if (!prop) {
|
||||
RAD_ERR("drafter '%s': `%s` was declared as the proposal buffer but never planned",
|
||||
drafter_.name, r0.program.buffers[drafter_.proposal].name.c_str());
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
|
||||
/* Neither pass samples (no logits in the context pass; the query pass has its own selector),
|
||||
* so the sampler chain is zero rows. */
|
||||
auto run_pass = [&](const RadBatch* db, const char* what) -> int {
|
||||
for (auto& rk : ranks_) {
|
||||
int s = rk->sampler.build_greedy(0);
|
||||
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));
|
||||
/* Probe after each pass; by the step loop's dump these buffers hold stale values. */
|
||||
if (s >= 0) dump_buffers(r0.ctx, step, what);
|
||||
return s;
|
||||
};
|
||||
|
||||
/* The context pass runs even when nothing drafts: a mid-prompt sequence has hidden states the
|
||||
* drafter will need, and skipping would leave a permanent hole in its cache. */
|
||||
if (const RadBatch* cb = sched_.block_context(step)) RAD_TRY(run_pass(cb, "context"));
|
||||
|
||||
/* Cleared so a query batch that could not be built does not republish the previous step's
|
||||
* proposals. */
|
||||
draft_out_.clear();
|
||||
if (n > 0) {
|
||||
if (const RadBatch* qb = sched_.block_query(step)) {
|
||||
RAD_TRY(run_pass(qb, "query"));
|
||||
const int64_t n_raw = (int64_t)n * steps;
|
||||
int32_t* const raw = readback_.reserve(n_raw);
|
||||
if (!raw) return RAD_E_NOMEM;
|
||||
RAD_TRY(rad_memcpy_async(raw, prop, n_raw * 4, r0.ctx.stream()));
|
||||
RAD_TRY(rad_stream_sync(r0.ctx.stream()));
|
||||
draft_out_.assign(raw, raw + n_raw);
|
||||
}
|
||||
}
|
||||
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 */
|
||||
Loaded 100 of 893 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user