Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3b13fd3266 | ||
|
|
be9bcf820d | ||
|
|
8c5b601ad1 | ||
|
|
3ade1e25fe | ||
|
|
1c104de400 | ||
|
|
17b556d9f5 | ||
|
|
5d4431b8a3 | ||
|
|
ff19013a3d | ||
|
|
267aed6a6c | ||
|
|
5e0cd1e29a | ||
|
|
db547d66d5 | ||
|
|
88b5a04acb | ||
|
|
aac92d7ac7 | ||
|
|
a8c8066d26 | ||
|
|
e4f2d2a6eb | ||
|
|
7a116d6538 | ||
|
|
4cc7ecf24e | ||
|
|
a08bf20d8d | ||
|
|
3ee49eed4d | ||
|
|
4865bd6bb1 | ||
|
|
4fbce0c9ef | ||
|
|
f1113ee91c | ||
|
|
e22a466860 | ||
|
|
fb39c877a6 | ||
|
|
e4dcb562e6 | ||
|
|
49df1dfc57 | ||
|
|
d7dc87f5b1 | ||
|
|
0bca5fdc48 | ||
|
|
0afc96f3e6 | ||
|
|
40611d3e73 | ||
|
|
7f353f9f44 | ||
|
|
4e8cb96622 | ||
|
|
2cd1ef76af | ||
|
|
80e094b31b | ||
|
|
dbe36c47b5 | ||
|
|
9078c297fa | ||
|
|
a3d6bce5d4 | ||
|
|
906a50bbbf | ||
|
|
ade49d3ae6 | ||
|
|
5adb65b07d | ||
|
|
9c61954ca7 | ||
|
|
5a80ee2f8f | ||
|
|
97bd578a7a | ||
|
|
8c5ca11f6d | ||
|
|
db594d2503 | ||
|
|
b93f12042b | ||
|
|
088be423ec | ||
|
|
896ab80f24 | ||
|
|
0158f24402 | ||
|
|
1c3584a840 | ||
|
|
aceef45e1e | ||
|
|
4fc8dda6b4 | ||
|
|
c81cdb2509 | ||
|
|
7955113d55 | ||
|
|
211da10f9b | ||
|
|
7e85e03ed4 | ||
|
|
3efe184aa2 | ||
|
|
d50afd4141 | ||
|
|
689f554596 | ||
|
|
288fbfbf3a | ||
|
|
5da0007ec0 | ||
|
|
9a8fc4114d | ||
|
|
ae134f8d08 | ||
|
|
801b5138ac | ||
|
|
ffd23ecf4d | ||
|
|
475e2fb376 | ||
|
|
6bb1aed7d6 | ||
|
|
e35fdf7504 | ||
|
|
e7d7b97f9f | ||
|
|
b42b7129eb | ||
|
|
7a513e8f19 | ||
|
|
f85f7a335b | ||
|
|
af5653aacc | ||
|
|
92d7ef120b | ||
|
|
7c83bfe500 | ||
|
|
088ca1cbf4 | ||
|
|
db2a57f501 | ||
|
|
e7388f9bcb | ||
|
|
05e8af9e3e | ||
|
|
57c2160aef | ||
|
|
fa7604130f | ||
|
|
8405dbbe38 | ||
|
|
69a02a4830 | ||
|
|
63ffd212eb | ||
|
|
0730cf82f8 | ||
|
|
d0f6b8e49e | ||
|
|
5214c1601a | ||
|
|
01fa666762 | ||
|
|
04247d1125 | ||
|
|
515de81921 | ||
|
|
a2f1a07655 | ||
|
|
9fa78b4cdc | ||
|
|
93b58b8b20 | ||
|
|
fbb7d6c678 | ||
|
|
7244cef0c1 | ||
|
|
818e9133d1 | ||
|
|
5aa5fa0fd2 | ||
|
|
8a1e2ac4da | ||
|
|
584c9d8d84 | ||
|
|
9bb3c3e6db | ||
|
|
aa84ec2ad4 | ||
|
|
bfc249bdc0 | ||
|
|
ce47698795 | ||
|
|
024bdc03f0 | ||
|
|
e1b0fc676f | ||
|
|
55d870efa0 | ||
|
|
6ad95c656a | ||
|
|
478da96ad3 | ||
|
|
a1bf46789d | ||
|
|
65ced7c975 | ||
|
|
0116111613 | ||
|
|
7b4fbf56e1 | ||
|
|
a444bcc963 | ||
|
|
8b1c108a55 | ||
|
|
740dca1b66 | ||
|
|
31126e46ac | ||
|
|
32c571b4f4 | ||
|
|
ed556f7b88 | ||
|
|
607811deac | ||
|
|
d5ff44a730 | ||
|
|
1411e6878e | ||
|
|
af7f96a0a3 | ||
|
|
b424572afd | ||
|
|
b6b8751ccc | ||
|
|
c07e665785 | ||
|
|
aba6b19648 | ||
|
|
1e670fe110 | ||
|
|
e63bb1cdcf | ||
|
|
045205de16 | ||
|
|
6813efe9b7 | ||
|
|
d42b7440a4 | ||
|
|
f9dd69db4e | ||
|
|
af1557b1ef | ||
|
|
c349190569 | ||
|
|
67cf57b864 | ||
|
|
0a7516441d | ||
|
|
14761df127 | ||
|
|
66b2036eb5 | ||
|
|
9ddb563c0d | ||
|
|
e3bb5b3ea2 | ||
|
|
f1a1730c3c | ||
|
|
20e7d61ec7 | ||
|
|
4664ac1c2d | ||
|
|
699fd85c97 | ||
|
|
1f1bc7c2b8 | ||
|
|
08968b530b | ||
|
|
8c454110d9 | ||
|
|
ef84fa3f6b | ||
|
|
a37f07b3f8 | ||
|
|
e06863be2c | ||
|
|
30dda03a6f | ||
|
|
aea55a2b1c | ||
|
|
4cbe901054 | ||
|
|
36731f27d5 | ||
|
|
109ac86d12 | ||
|
|
6cd58a564b | ||
|
|
a03e812360 | ||
|
|
33343c4730 | ||
|
|
a0eb3934b5 | ||
|
|
a81a35f2a6 | ||
|
|
ac6ddac7f7 | ||
|
|
2c81c86350 | ||
|
|
06a2b18848 | ||
|
|
3deabdaeca | ||
|
|
917d5e4b93 | ||
|
|
c48708315d | ||
|
|
e4541c7036 | ||
|
|
3b2050a516 | ||
|
|
5bfb69e4ad | ||
|
|
4366748012 | ||
|
|
87fa1f109e | ||
|
|
31467206e1 | ||
|
|
46bce7f443 | ||
|
|
1fd2432365 | ||
|
|
ca38286812 | ||
|
|
a189bcc444 | ||
|
|
dd97f076e6 | ||
|
|
59e8dfe06f | ||
|
|
b8bca7885a | ||
|
|
e78d484e60 | ||
|
|
d0fd4aa1bb | ||
|
|
9b6eba80c6 | ||
|
|
e912b04f5a | ||
|
|
ca7a7212ec | ||
|
|
946a6f9e2b | ||
|
|
01f08152dc | ||
|
|
304597970f | ||
|
|
cfec01ec8d | ||
|
|
315aea7db9 | ||
|
|
d1b5a45e31 | ||
|
|
590dbcc178 | ||
|
|
73a284d799 | ||
|
|
33f9644701 | ||
|
|
2e558e2dcc | ||
|
|
79ac2bd50d | ||
|
|
742191a244 | ||
|
|
73f94b4345 | ||
|
|
7bd195d394 | ||
|
|
b2228c176b | ||
|
|
8dcd8fdcd7 | ||
|
|
8f2e511fcc | ||
|
|
78ad2096a3 | ||
|
|
bfadfbee76 | ||
|
|
1f50d235ed | ||
|
|
df453ff434 | ||
|
|
eaa14ac72a | ||
|
|
ceb92ea701 | ||
|
|
2e0945c106 | ||
|
|
6b96295f54 | ||
|
|
29057b0c6b | ||
|
|
09ad42e633 | ||
|
|
1f00224501 | ||
|
|
21c4544b61 | ||
|
|
f5d2d74a20 | ||
|
|
6997f8da14 | ||
|
|
6c7bcefefa | ||
|
|
660d410196 | ||
|
|
38c182a2ba | ||
|
|
b988378e70 | ||
|
|
bd3fa646bc | ||
|
|
1d94e416a6 | ||
|
|
ba3ebd380f | ||
|
|
157959fd80 | ||
|
|
aadabde0de | ||
|
|
b27f352259 | ||
|
|
c9bce68d45 | ||
|
|
a8d82678fa | ||
|
|
8ac613ddb9 | ||
|
|
97b4590761 | ||
|
|
c256342bc1 | ||
|
|
66b0dcf019 | ||
|
|
0f011f27e1 | ||
|
|
c3a4775f54 | ||
|
|
b9ecbde0d6 | ||
|
|
5e2e596644 | ||
|
|
3bf9dc9593 | ||
|
|
d893fd05d1 | ||
|
|
5c66eecc8e | ||
|
|
f4981154fc | ||
|
|
392746da6b | ||
|
|
4943bba2fb | ||
|
|
6e8a2f0a94 | ||
|
|
9a960c3da9 | ||
|
|
79cc319db2 | ||
|
|
0ff61a19a2 | ||
|
|
b98c2eb13e | ||
|
|
5736dd11c3 | ||
|
|
90b1229bfc | ||
|
|
e5862f3d26 | ||
|
|
c2403b2e29 | ||
|
|
444b85158b | ||
|
|
965a7caa51 | ||
|
|
4c9a79ca98 | ||
|
|
70be48c6fa | ||
|
|
be09d90c71 | ||
|
|
3ac3954fea | ||
|
|
9bfdd95cb6 | ||
|
|
e30ada33e8 | ||
|
|
1231eefbd3 | ||
|
|
51e4c7f0f0 | ||
|
|
1b4e405969 | ||
|
|
d7e3c2a58a | ||
|
|
b44f7a9bb1 | ||
|
|
981cd1e4e1 | ||
|
|
50ea36f283 | ||
|
|
f2f94fc6e7 | ||
|
|
e46a8ba3d4 | ||
|
|
7b9f33653f | ||
|
|
2fda03ccdd | ||
|
|
b83d53cf19 | ||
|
|
41a1aa00fe | ||
|
|
2a2b756371 | ||
|
|
ddcb9c69bb | ||
|
|
b4c04b6042 | ||
|
|
f0f764d6f5 | ||
|
|
60bcc30e5e | ||
|
|
7da9ccf38b | ||
|
|
f3e4d11872 | ||
|
|
c6ef279a12 | ||
|
|
aafec91773 | ||
|
|
451b136874 | ||
|
|
a58304632a | ||
|
|
6e134fc15f | ||
|
|
c00b882b96 | ||
|
|
5a8c5533d1 | ||
|
|
f87d03d304 | ||
|
|
f713f449c2 | ||
|
|
e0c386ee85 | ||
|
|
8ef50a7708 | ||
|
|
b954585f9f | ||
|
|
220cb3f12c | ||
|
|
be623ba1dc | ||
|
|
c9e34d534c | ||
|
|
8fa226e620 | ||
|
|
bd38e7eced | ||
|
|
8c389c02e7 | ||
|
|
d858aa722b | ||
|
|
f776ecbf2e | ||
|
|
e494369ed9 | ||
|
|
17f0eae420 | ||
|
|
b632c72f5d | ||
|
|
12b7b7889b | ||
|
|
01c7a3334a | ||
|
|
e3d65f3a7c | ||
|
|
28939a99df | ||
|
|
df4e2ea889 | ||
|
|
b87010c7dd | ||
|
|
4bd9c39728 | ||
|
|
7f5218ee5f | ||
|
|
036bd8fec0 | ||
|
|
87c604370d | ||
|
|
8ab6f2a8b3 | ||
|
|
e2e9416843 | ||
|
|
b0a58b5dbf | ||
|
|
aeaf6a4580 | ||
|
|
d6109d7e3e | ||
|
|
030a3a37b7 | ||
|
|
1a900398a3 | ||
|
|
6436410e63 | ||
|
|
7cad854f2b | ||
|
|
72160a9cff | ||
|
|
882050e45a | ||
|
|
0c4292e45b | ||
|
|
cc46e3b714 | ||
|
|
eda0e92e8e | ||
|
|
6f9c084ac6 | ||
|
|
c9c3a98894 | ||
|
|
3b7ef1ed48 | ||
|
|
b466c91b26 | ||
|
|
2420b2b383 | ||
|
|
63416510a0 | ||
|
|
3b278dcec3 | ||
|
|
44490c859a | ||
|
|
dccc6329a9 | ||
|
|
a1b7643310 | ||
|
|
e6787b7bdd | ||
|
|
394b8cd290 | ||
|
|
e0c3f971dc | ||
|
|
19d4e8fe0e | ||
|
|
3af8065cc6 | ||
|
|
a72686b7e7 | ||
|
|
c1c05e9029 | ||
|
|
a0ea6ad1ba | ||
|
|
eb3aa7eae7 | ||
|
|
c6391e6ef9 | ||
|
|
da7b911c64 | ||
|
|
81be3cb63d | ||
|
|
a00e5e7094 | ||
|
|
9782a9afb5 | ||
|
|
326443ca89 | ||
|
|
b88d370722 | ||
|
|
d4d6d6cb3e | ||
|
|
8088c9a783 | ||
|
|
c1c8e40445 | ||
|
|
cebf759a36 | ||
|
|
51b08808de | ||
|
|
c96cfc9e7b | ||
|
|
e14463b8eb | ||
|
|
f98ccd3f56 | ||
|
|
5b98ba37e8 | ||
|
|
9ca20a1fba | ||
|
|
445bf8e0d9 | ||
|
|
340ff8781a | ||
|
|
b43088a334 | ||
|
|
f692c3f446 | ||
|
|
416c231a18 | ||
|
|
95af71af3a | ||
|
|
50b60078ab | ||
|
|
acd256ba25 | ||
|
|
a4403a1a90 | ||
|
|
4a60c64ec5 | ||
|
|
6295ba1d92 | ||
|
|
40442cc81b | ||
|
|
08c3e752f7 | ||
|
|
cb97b1c886 | ||
|
|
5d6de60318 | ||
|
|
f697660b8b | ||
|
|
213403b458 | ||
|
|
a5b2f84450 | ||
|
|
8cb2c0a841 | ||
|
|
4204fa4da7 | ||
|
|
1c96558970 | ||
|
|
48407fb52d | ||
|
|
125854df79 | ||
|
|
1483a1ae17 | ||
|
|
e56d948889 | ||
|
|
a0f9eb29c0 | ||
|
|
ab736ca3e3 | ||
|
|
303060f210 | ||
|
|
36de701090 | ||
|
|
ccb5071228 | ||
|
|
a78352dad1 | ||
|
|
0b18331a34 | ||
|
|
638663e9ff | ||
|
|
dd43d31e93 | ||
|
|
8611feb85e | ||
|
|
1c2f55027c | ||
|
|
523349dd8f | ||
|
|
e4ca20ddf8 | ||
|
|
7169c9da0a | ||
|
|
9c5d4a656c | ||
|
|
702a0970cc | ||
|
|
798fb21e51 | ||
|
|
aa14eea76c | ||
|
|
ded64c0bd3 | ||
|
|
61e275e30f | ||
|
|
9cb04f62a8 | ||
|
|
aa182fc156 | ||
|
|
c776ab9e46 | ||
|
|
d564e6e5b1 | ||
|
|
8be040f599 | ||
|
|
08fa89255c | ||
|
|
742f17f1e3 | ||
|
|
599d904e01 | ||
|
|
51db1729b1 | ||
|
|
d537dc09aa | ||
|
|
c36d04d99c | ||
|
|
1554b451e1 | ||
|
|
d5bb6a6c6e | ||
|
|
757ad11b0d | ||
|
|
aaafebcf0a | ||
|
|
7bba83c075 | ||
|
|
0ac154c803 | ||
|
|
638aa3a683 | ||
|
|
4d8be7099d | ||
|
|
08c85ea527 | ||
|
|
72ab60ed64 | ||
|
|
4e35a00493 | ||
|
|
e53286cdbe | ||
|
|
bf7e473224 | ||
|
|
8bbf402d9e | ||
|
|
769b4c64a6 | ||
|
|
cfa6a668f6 | ||
|
|
7892524801 | ||
|
|
b55791b398 | ||
|
|
141212dd88 | ||
|
|
b264e9bd0c | ||
|
|
55da38afbd | ||
|
|
b34b1ac844 | ||
|
|
34c52ebe96 |
No files matched your search
@@ -5,3 +5,5 @@ build*
|
||||
.claude
|
||||
**/*.rad
|
||||
compile_commands.json
|
||||
dashboard/node_modules
|
||||
dashboard/dist
|
||||
@@ -1,22 +0,0 @@
|
||||
# Codeberg CI (Woodpecker): the full suite on a machine without ROCm -- the CPU-only build, the
|
||||
# same posture as `./build.sh --no-hip` -- on the current Ubuntu LTS. The LTS is chosen, not
|
||||
# assumed: the media codecs must be new enough for the FFmpeg >= 7 callback signatures the mp4
|
||||
# writer binds (24.04's 6.1 does not compile), and the card suites (`*_card`, LABELS "gpu") want
|
||||
# hardware this runner does not have, so the run is the host preset -- everything but gpu and oot.
|
||||
# vendor_sums runs here as everywhere: a changed lift that the vendor record does not carry fails
|
||||
# CI before it fails a user.
|
||||
when:
|
||||
- event: [push, pull_request, tag]
|
||||
|
||||
steps:
|
||||
test:
|
||||
image: ubuntu:26.04
|
||||
commands:
|
||||
- export DEBIAN_FRONTEND=noninteractive
|
||||
- apt-get update -qq
|
||||
- apt-get install -y -qq --no-install-recommends git cmake ninja-build g++ pkg-config jq
|
||||
ca-certificates libavformat-dev libavcodec-dev libavutil-dev libswscale-dev
|
||||
libswresample-dev
|
||||
- cmake -S . -B build -G Ninja -DRAD_WITH_HIP=OFF -DRAD_WITH_FFMPEG=AUTO
|
||||
- cmake --build build -j "$(nproc)"
|
||||
- ctest --preset host # everything but gpu and oot, in the configured build dir
|
||||
+31
-10
@@ -1,7 +1,7 @@
|
||||
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.15.1 LANGUAGES C CXX)
|
||||
project(radiance VERSION 2.3.0 LANGUAGES C CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 20)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
@@ -20,6 +20,7 @@ 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_ENABLE_KV_ROLLBACK_TEST_HOOK "Compile the test-only device KV rollback observer" OFF)
|
||||
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
|
||||
@@ -162,7 +163,7 @@ 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:
|
||||
# IQ8R container that carries its DFlash2 drafter:
|
||||
#
|
||||
# rad-kbench -m <model.rad> --max-cases 1 --record data/kernels.rkb
|
||||
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/data/kernels.rkb)
|
||||
@@ -173,8 +174,8 @@ if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/data/kernels.rkb)
|
||||
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
|
||||
# The 27B is dense with a DFlash2 drafter and gqa 6; the 35B-A3B IQ8R container is routed
|
||||
# (moe_gemm_q, the fused router, 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
|
||||
#
|
||||
@@ -208,8 +209,8 @@ endforeach()
|
||||
install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/data/vectors/LICENSE.qwen-community-1.0.txt
|
||||
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME qwen-community.LICENSE)
|
||||
|
||||
# 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.
|
||||
# The downloader behind a model source naming a repo, `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
|
||||
@@ -299,8 +300,9 @@ if(RAD_HIP_FOUND AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/libr4d/CMakeLists.txt)
|
||||
endif()
|
||||
# libr3d: the RDNA3 kernel library, same shape as libr4d and same guard -- device code needs a HIP
|
||||
# toolchain. It declares itself for `^gfx11` and returns without a target when the build's
|
||||
# RAD_GPU_TARGETS holds no RDNA3, so a gfx12-only build of this tree does not produce it. A card
|
||||
# with no kernel library of its own refuses device-only ops (docs/PLUGIN.md §10).
|
||||
# RAD_GPU_TARGETS holds no RDNA3, so a gfx12-only build of this tree does not produce it, and
|
||||
# declines every machine without a gfx11 card (rad_plugin_open). A card with no kernel library of
|
||||
# its own refuses device-only ops (docs/PLUGIN.md §10).
|
||||
if(RAD_HIP_FOUND AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/libr3d/CMakeLists.txt)
|
||||
add_subdirectory(libr3d)
|
||||
endif()
|
||||
@@ -319,10 +321,27 @@ endif()
|
||||
if(CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64|amd64)$")
|
||||
add_subdirectory(libavx)
|
||||
endif()
|
||||
# exl3: radiance-exl3, EXL3 trellis experts (exllamav3's format) -- the gfx1201 kernel library
|
||||
# exl3r4d (built when RAD_GPU_TARGETS names gfx1201), the host reference exl3ref and the `exl3`
|
||||
# quantiser. See exl3/README.md.
|
||||
add_subdirectory(exl3)
|
||||
add_subdirectory(arch)
|
||||
# spechub: the linear-MTP coupling kernels (--draft-coupling). Built by default; without the flag
|
||||
# no op resolves to its rows.
|
||||
add_subdirectory(plugin/spechub)
|
||||
# glm: GLM-5.3-Flash's own fused kernels, ops only glm5next issues where a library declares them.
|
||||
add_subdirectory(plugin/glm)
|
||||
# EXL3-V3: exl3i, the gfx1201 kernel library for the trellis linears and token tables (left out
|
||||
# without a gfx1201 target; its host tests build either way), exl3quant, the `exl3i` quantiser that
|
||||
# imports EXL3-V3 levels, and the architectures qwen35_exl3 and gemma4_exl3. plugin/exl3import is
|
||||
# their shared decode and headers, not a plugin. Their tests compile against RADIANCE_INCLUDE_DIR,
|
||||
# the include root find_package(radiance) names; in the tree that root is abi/ and the rad_include/
|
||||
# that holds arch/common/ as arch/ (arch/CMakeLists.txt).
|
||||
set(RADIANCE_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/abi ${CMAKE_BINARY_DIR}/rad_include)
|
||||
add_subdirectory(plugin/exl3i)
|
||||
add_subdirectory(plugin/exl3quant)
|
||||
add_subdirectory(plugin/qwen35_exl3)
|
||||
add_subdirectory(plugin/gemma4_exl3)
|
||||
add_subdirectory(tools)
|
||||
if(RAD_BUILD_TESTS)
|
||||
enable_testing()
|
||||
@@ -387,9 +406,11 @@ install(FILES
|
||||
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/yyjson/LICENSE
|
||||
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME yyjson.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)
|
||||
install(FILES dashboard/THIRD-PARTY-LICENSES.txt
|
||||
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME dashboard.LICENSES)
|
||||
+11
-8
@@ -28,10 +28,12 @@
|
||||
# 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:
|
||||
# ./build.sh. They are the targets of the shipped kernel libraries, each of which keeps only its own
|
||||
# family: libr4d takes gfx1201 (RDNA4), libr3d gfx11-generic (every RDNA3 chip) and gfx1151, and
|
||||
# libhalo gfx1151 (Strix Halo), where the loader prefers it over libr3d. On any one card the other
|
||||
# libraries decline or are left out, so the default image serves all three. 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
|
||||
@@ -131,7 +133,7 @@ RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
|
||||
|
||||
# ------------------------------------------------------------------------------------------ build
|
||||
FROM rocm/dev-ubuntu-${UBUNTU_VERSION}:${ROCM_VERSION} AS build
|
||||
ARG GPU_TARGETS=gfx1201
|
||||
ARG GPU_TARGETS="gfx1201;gfx11-generic;gfx1151"
|
||||
# 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=
|
||||
@@ -227,11 +229,12 @@ ARG TEST_EXCLUDE=
|
||||
# perf_event_open, so the tests that bound work count CPU time rather than instructions
|
||||
# (tests/work_counter.h). 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).
|
||||
# (tests/oot_plugins.sh). The `parity` entry (halo_parity: libhalo's tables against libr4d's) is
|
||||
# left out until libhalo has ported the ops libr4d added after it (the test names each one).
|
||||
RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
|
||||
bash /src/docker/llvm-check.sh /build \
|
||||
&& RAD_TEST_CPU_BUDGET_SCALE="${TEST_CPU_BUDGET_SCALE}" \
|
||||
ctest --test-dir /build -LE 'gpu|oot' ${TEST_EXCLUDE:+-E "${TEST_EXCLUDE}"} \
|
||||
ctest --test-dir /build -LE 'gpu|oot|parity' ${TEST_EXCLUDE:+-E "${TEST_EXCLUDE}"} \
|
||||
-j"${TEST_JOBS:-${JOBS:-$(( ($(nproc) + 1) / 2 ))}}" --output-on-failure \
|
||||
&& touch /build/host-tests-passed
|
||||
|
||||
@@ -283,7 +286,7 @@ RUN set -e; R=/rootfs; L=$R/usr/lib/x86_64-linux-gnu; \
|
||||
|
||||
# ---------------------------------------------------------------------------------------- runtime
|
||||
FROM scratch AS runtime
|
||||
ARG GPU_TARGETS=gfx1201
|
||||
ARG GPU_TARGETS="gfx1201;gfx11-generic;gfx1151"
|
||||
ARG VERSION=dev
|
||||
ARG REVISION=unknown
|
||||
|
||||
|
||||
@@ -15,17 +15,51 @@ Written by Deadcode, with contributions from:
|
||||
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, the
|
||||
Gemma 4 31B heretic-ara and Ornith-1.5-35B-A3B compose files, Gemma 4's E2B/E4B form (KV-shared
|
||||
layers, per-layer embeddings, clipped vision linears) with NVIDIA-Nemotron-3.5-Bolt-E4B, its audio
|
||||
w4a8 decode step, the vision tower and window snapshots that let a prefix hit resume, the Gemma 4
|
||||
31B heretic-ara and Ornith-1.5-35B-A3B compose files, Gemma 4's E2B/E4B form (KV-shared layers,
|
||||
per-layer embeddings, clipped vision linears) with NVIDIA-Nemotron-3.5-Bolt-E4B, its audio
|
||||
encoder, its i8a8 linears and its KV heads replicated over ranks, 4-bit weights at decode heights
|
||||
through w4a16_asym, and the Ornith-1.5-122B compose files
|
||||
through w4a16_asym, the Ornith-1.5-122B compose files, the Gemma 4 31B's asymmetric int5 linears
|
||||
(w5a8i8 and w5a16), the junctions at quant_act_i8g's grid (rmsnorm_quant_i8g, gelu_mul_quant_i8g
|
||||
and ar_rmsnorm_quant_i8g) with the prefill overlap on the i8a8, a4 and w5 grids, the 31B's i8g,
|
||||
heretic-ara-i8g and w5 compose files, and Ling-3.0-flash (bailing_hybrid: KDA, dense latent
|
||||
attention, group-limited sigmoid routing, the clipped SwiGLU and its MTP layer as a serial
|
||||
drafter) with mla_attn_paged, its w4a8 recipes and compose files, possessive quantifiers in the
|
||||
tokenizer's patterns, the Grafana dashboard's first screen, and Gemma 4 12B (its picture and audio
|
||||
embedders, a picture's placeholders read both ways on the sliding layers, the windowed attention
|
||||
at head_dim 512, suppress_tokens) with its compose files, and NVIDIA-Nemotron-3.5-Bolt-74B-A9B
|
||||
(nemotronh: Mamba-2 with ssd_update and ple_conv_bias, the latent MoE's ungated relu^2 experts,
|
||||
NoPE attention with KV heads replicated over ranks, the paged attention at head_dim 128 and gqa
|
||||
16, attention sinks) with NVIDIA's LiLiCorr drafter (RadBatch::anchor_rows, the candidate
|
||||
correlator), the C-RADIO vision tower and video tubelets, calibration in layer ranges, its recipes
|
||||
and compose files, and the kernel report's fixture, and Ling-3.0-flash on an IQ8R trunk with its
|
||||
clamped gated products writing rotated int8 codes, Nemotron-3.5-Bolt-74B-A9B on an int8 trunk
|
||||
(rotated experts and the LiLiCorr backbone reading rotated int8 codes), and the bidirectional
|
||||
media span counted from the window group's first position, and Gemma 4 dense on EXL3-V3
|
||||
(gemma4_exl3, with a quantised token table and per-layer table), and NVIDIA's 2-bit
|
||||
Nemotron-3.5-Bolt-74B-A9B on one card
|
||||
- mechkbfan: the token embedding in the pinned host pool
|
||||
- Code000: the n-gram gather on the card and the MTP head's history-pass skip, and the MTP draft
|
||||
coupling with its cooperative verify (--draft-coupling), the W4A8 prefill's tail scale read, the
|
||||
ISA instruments' VGPR granule, back-edge count and fail-closed parse, scored steps
|
||||
(rad_declare_scores, RadBatch::score_only), the gated prefill fold, the short-prompt split row and
|
||||
the rows forms of rmsnorm and rope, and LFM2's 8-bit trunk with the d1-3B recipe
|
||||
the rows forms of rmsnorm and rope, LFM2's 8-bit trunk with the d1-3B recipe, the file tier's
|
||||
routed reads with their own router's counts and its deposit wait, the stop-string hold-back, and
|
||||
the sampler's planes by the step's token bound, its n-gram ban beside a drafter and no candidate
|
||||
cut over a top-1 row, and --prefill-interleave auto[:SHARE], sized from measured step times and
|
||||
served by default, and the diagnose mode, in which the engine measures itself, with its token
|
||||
parity and reproducibility checks, and the HDP flush before every doorbell and the scalar-cache
|
||||
invalidate behind a chained wait, chained launches without the packet processor's acquire, the
|
||||
prefetch stream's half-lap acquire, the queue scratch charged to the VRAM budget, the pinned
|
||||
staging ring sized for sixteen builds, --expert-pin-top's fractional cut, the vision tower left
|
||||
off a build without a media decoder, QSA's score and select skipped where no attention reads them,
|
||||
the register form of the fused all-reduce writes with its wake store, Flash-Next's verify and
|
||||
decode launch order, the coded lossless wire of the two-rank fused writes and its staged form, one
|
||||
patch dispatch for an op's weight tables, hc_read's 48-row decode tile and its prefill up product,
|
||||
the packed MoE prefill run map, the spanned prefill's routed pass and its tail snapshot inside the
|
||||
last chunk, block and traversal verification of the coupled MTP chain (--draft-verify), adaptive
|
||||
and load-aware draft depth (--draft-depth, --draft-depth-load), SuffixDecoding as a step selector
|
||||
(--draft-suffix), and the tiled QSA prefill form, and the qwen35_exl3 QAD plugin skeleton
|
||||
- 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
|
||||
@@ -38,11 +72,15 @@ Written by Deadcode, with contributions from:
|
||||
host) and decode-hot residency (--expert-profile, --expert-pin-top), prefix hits over KV groups of
|
||||
different block sizes and a hybrid's window in the checkpoint slot, --prefix-resume exact,
|
||||
DeepSeek-V4.1-Flash's conversion from its release (the Engram tables, the fused imatrix, the
|
||||
UD-IQ1_S recipe and rad-convert --chat-template), a preempted prefill admitted only with its
|
||||
whole recompute and the running sequences' next blocks free and the bound on its wait
|
||||
(--preempt-wait-ms), prompt lookup alone (--spec-ngram) with each sequence's n-gram index and
|
||||
the gate that verifies a proposal only when it pays, and DeepSeek-V4.1's reply format with its
|
||||
DSML tool calls
|
||||
UD-IQ1_S recipe and rad-convert --chat-template), a preempted prefill admitted only with its whole
|
||||
recompute and the running sequences' next blocks free and the bound on its wait
|
||||
(--preempt-wait-ms), prompt lookup alone (--spec-ngram) with each sequence's n-gram index and the
|
||||
gate that verifies a proposal only when it pays, and DeepSeek-V4.1's reply format with its DSML
|
||||
tool calls, and expert_stats_report.py, and the KL mode's own line in the VRAM shortfall report,
|
||||
and the fresh prefill's room gate (--prefill-room-gate), and DeepSeek-V4.1-Flash on 2.x -- its
|
||||
vision tower, its IQ1_S and IQ2_XXS containers, and linears and experts served in llama.cpp's own
|
||||
blocks with their GEMMs in libref, libavx and libr4d -- and GGML IQ2_XXS and IQ3_XXS packed on the
|
||||
card
|
||||
- hazyumps: static YaRN for the Qwen rotary paths
|
||||
- malic: ParoQuant, with 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
|
||||
@@ -52,12 +90,12 @@ Written by Deadcode, with contributions from:
|
||||
emulator that tests them, the prefill split into two slices with their all-reduces beside the
|
||||
compute, and the vocabulary-sharded draft head; Gemma 4 31B on four cards (its all-reduces fused
|
||||
with the junctions, overlapped with the compute and sent compressed, chained launches with block
|
||||
drafters), the embedding scale rounded as Hugging Face rounds it, block drafters' drafts
|
||||
accepted on the card, z-lab's DFlash drafter drafting on after a prefix-cache hit and the 31B's
|
||||
GPTQ calibration tap, and for speculation the MTP head's first draft read up to where it sits, no
|
||||
step queued behind one that ends its requests, a step's tokens streamed before the drafter's
|
||||
passes end, a block drafter's proposals verified as a tree, the 31B's block-16 DFlash2 tree with
|
||||
its short block under load, a block drafter's window carried in the window snapshot, and window
|
||||
drafters), the embedding scale rounded as Hugging Face rounds it, block drafters' drafts accepted
|
||||
on the card, z-lab's DFlash drafter drafting on after a prefix-cache hit and the 31B's GPTQ
|
||||
calibration tap, and for speculation the MTP head's first draft read up to where it sits, no step
|
||||
queued behind one that ends its requests, a step's tokens streamed before the drafter's passes
|
||||
end, a block drafter's proposals verified as a tree, the 31B's block-16 DFlash2 tree with its
|
||||
short block under load, a block drafter's window carried in the window snapshot, and window
|
||||
snapshots from short prompts
|
||||
- redxherring: --model taking a Hugging Face repo id
|
||||
- Smellyyyy: the idea behind --prefill-interleave
|
||||
@@ -65,8 +103,8 @@ Written by Deadcode, with contributions from:
|
||||
- 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 --host-headroom-mib
|
||||
- zivius: LiquidAI's LFM2 and LFM2-VL and d1's /v1/systemone, after the design of their Codeberg
|
||||
PR 50, Qwen3-ASR with /v1/audio/transcriptions and /v1/realtime, and Fish Audio drama-3 -- its
|
||||
- zivius: LiquidAI's LFM2 and LFM2-VL and d1's /v1/systemone, after the design of their Codeberg PR
|
||||
50, Qwen3-ASR with /v1/audio/transcriptions and /v1/realtime, and Fish Audio drama-3 -- its
|
||||
plugin, its codec encoder and decoder, voice cloning from reference clips, and the torch.save
|
||||
reader
|
||||
- mici81: Gemma 3 dense (TranslateGemma 27B) -- its plugin, the windowed h128 attention, the
|
||||
@@ -84,19 +122,25 @@ Written by Deadcode, with contributions from:
|
||||
below the tip, Gemma 3's fused all-reduce junction on the lossy wire, the three-wave verify's
|
||||
split by depth, the delta net's out-projection read beside its decode recurrent update, the MXFP4
|
||||
feed-forward's gated fold up to 16 rows, the three-wave verify floor bounded by the batch's
|
||||
workgroups, the split-KV row sum read with fetch-inactive, KLATE again for the head-256 gqa6
|
||||
paged prefill, and the preempted-prefill gate past a KV group that holds no blocks
|
||||
workgroups, the split-KV row sum read with fetch-inactive, KLATE again for the head-256 gqa6 paged
|
||||
prefill, the preempted-prefill gate past a KV group that holds no blocks, and the norms' lane sum
|
||||
issuing its reads eight at a time, chained forms for every kernel of Qwen3.8-Flash-Next's decode
|
||||
step with hc_read's forms G, S and B3, and a preempted request publishing its prefix with an
|
||||
overdue one keeping its place, and hc_read's decode forms G, S and B3 restored for ROCm 7.2
|
||||
- eddie168168: the rotated int8 trunk (i8a8h) and the qwen35_w8a8 plugin serving it, and the
|
||||
out-of-tree test at the tree's VOPD setting, and its norm and SiLU producers writing the int8
|
||||
linears' operands directly
|
||||
- davetha: JSON Schema patterns read unanchored, with their shorthand classes and escapes
|
||||
linears' operands directly, and bf16x12, bf16 weights packed losslessly in 12.25 bits, with its
|
||||
GEMMs, and Qwen3.8-27B in bf16 with the DFlash2 drafter rescored against a bf16 head
|
||||
- davetha: JSON Schema patterns read unanchored, with their shorthand classes and escapes, and the
|
||||
README's abliterated Flash-Next container, and the vision-encoder and per-card hardware figures on
|
||||
the dashboard's Performance page
|
||||
- Nunze: the eight-rank all-reduce's bands, weighted shards from the PCIe links and pieces, the
|
||||
sampler's candidate width at eight ranks, the image test stage's parallelism, budgets and
|
||||
exclusions, jinja's dotted integer index, GLM-5.3-Flash's kernels in libr4d and tool calls whose
|
||||
name the opener opens, GLM-5.3-Flash's vision tower and processor, its decode at a few rows and
|
||||
its DSA indexer split over the ranks, a host-tier restore that makes room as pressure does, KV
|
||||
groups every rank holds kept once a host slot, the eight-rank two-shot in ring order, the MLA
|
||||
row form (--tp-attn-split rows), DELETE /sessions, the dispatch stamps of a played pass with
|
||||
groups every rank holds kept once a host slot, the eight-rank two-shot in ring order, the MLA row
|
||||
form (--tp-attn-split rows), DELETE /sessions, the dispatch stamps of a played pass with
|
||||
stampgaps.py, one n-gram table for engines on separate cards (--ngram-placement ram=DIR), GGUF
|
||||
Q8_0, Q4_K and Q6_K tensors imported as their planes, the dense integer rows at the group they
|
||||
compute, and the GDN conv kernels on an f32 weight
|
||||
@@ -104,52 +148,142 @@ Written by Deadcode, with contributions from:
|
||||
sparse latent attention, f32-scaled FP8 and MXFP4 experts under sigmoid routing) and their
|
||||
reference and AVX ops -- a Quark export's block-FP8 layers, the signed QSA ranking, the
|
||||
one-sequence KV floor over the live plan, and prefill staging paid by expert residency
|
||||
- Memoria: the dashboard's decode floor and recent window, the sparklines' percentile range, and
|
||||
the bringup time in /stats, the acceptance tiles' live figures and statsdump's size-capped
|
||||
rotation
|
||||
- Memoria: the dashboard's decode floor and recent window, the sparklines' percentile range, and the
|
||||
bringup time in /stats, the acceptance tiles' live figures and statsdump's size-capped rotation,
|
||||
the dashboard's history line, session extremes, card-count changes and Requests-header JSON
|
||||
export, with the page's JavaScript driven by tests/js, and seven dashboard tile and history
|
||||
defects
|
||||
- C_Tamas: control vectors, loaded when the deployment asks and applied as a per-layer residual
|
||||
projection, KV streaming for a context bigger than VRAM (--kv-resident), and the dashboard's
|
||||
request history, KV streaming traffic and one-unit KV meter
|
||||
request history, KV streaming traffic and one-unit KV meter, and the mapped tier kept in the page
|
||||
cache across a load
|
||||
- J-Nova: Unlimited-OCR, and Sage-A1.5 with its vision tower and its DFlash2 drafter
|
||||
- thekk1: the fp8 QK and PV legs of the h256 prefill attention (--attn-prefill-fp8)
|
||||
- thekk1: the fp8 QK and PV legs of the h256 prefill attention (--attn-prefill-fp8), and the
|
||||
diagnosis of the expert loan held at zero by leftover cache blocks
|
||||
- lortht: Krea 2's rebalance of the text taps and its presets, MiniMax-H3's modulation rows, and
|
||||
keyframes carried through a latent upscale
|
||||
- Quackster: cards with a small PCI BAR, their kernel arguments kept in host memory
|
||||
- farcryjohn: periodic window snapshots that let an edited prompt reuse its prefix
|
||||
- farcryjohn: periodic window snapshots that let an edited prompt reuse its prefix, and
|
||||
Breeze-TTS-2's native voice cloning with its delivery direction (the Qwen3-TTS reference encoder,
|
||||
vq_euclidean and elu), and MiniMax-H3's reference encoder reading host-readable operands (the
|
||||
ref2va and fl2va crash)
|
||||
- gostar: snapshot-backed prefix KV kept across recomputes, and Tencent's Hy-Memory (HYV3) -- its
|
||||
BF16, FP8 and GGUF adapters, its KV scales, its native sectioned tool calls, and its W4 decode
|
||||
(the per-128 I4 expert packing, the one-row W4/W5 epilogue and the fused prologue and folds)
|
||||
(the per-128 I4 expert packing, the one-row W4/W5 epilogue and the fused prologue and folds), and
|
||||
the head-256 prefill softmax rescaled by row rather than by wave, Spark 2.5 (spark25: bf16 and
|
||||
rotated-int8 IQ8R checkpoints, tensor parallelism with exact collectives, reasoning and tagged
|
||||
tool calls) with its DSpark drafter (exact attention and Markov walk ops), the prefill split keyed
|
||||
by live KV bounds, and --gpu-memory-mib, and the calibrated U5 gate and W5NL down recipe, U4 gates
|
||||
with W6NL down experts, Muse Glimmer IQ4R-V4 with a quantised DFlash2, and Qwen3.8-27B's native
|
||||
MTP draft head (vhead, the U2 head over a vocabulary-split target, its coupled proposals and
|
||||
calibration), and Inkling 2 Mini -- its text backbone and loop, its NVFP4 and MXFP8 experts
|
||||
imported, the int8 trunk, the vision tower, tensor parallelism, the DSpark drafter, tool calls,
|
||||
the reasoning count and its decode and prefill kernels (gemm_nt_q_multi, attn_paged_rel's decode
|
||||
and its verify rows sharing each K and V tile, the NVFP4 MoE forms) -- rad-convert's GPU
|
||||
trellis jobs kept fed and --reuse-only, Muse Glimmer's
|
||||
vision tower reading the container's int8 codes in place, and the LoRA plain-bf16 view taken only
|
||||
where an adapter targets it
|
||||
- launch80_assets: tuning collectives as the exchange they serve at the served configuration, the
|
||||
per-layer embeddings' read-ahead queue and gather regimes, and the step loop's stall watch
|
||||
per-layer embeddings' read-ahead queue and gather regimes, and the step loop's stall watch, and
|
||||
Meta Muse Glimmer 30B -- the museglimmer plugins, its windowed vision tower, its DFlash drafter,
|
||||
the ATEM tool dialect and its context extension
|
||||
- hugypufy: M2XFP4 -- its quantiser, its GEMMs and its linears in the Qwen3.8 trunk and the DFlash2
|
||||
drafter -- and the ParoQuant M2XFP4 import
|
||||
- steki: Gemma 4 E2B's per-layer MLP width and the bf16 descriptor for Google's E2B/E4B
|
||||
directories, nomic-embed-text-v2-moe (the nomicbert plugin), its config key aliases and
|
||||
RAD_MAP_TRANSPOSE honouring src_index, an f32 source narrowed to a bf16 declaration at load, and
|
||||
the snapshot store's floor ahead of --host-headroom-mib
|
||||
- steki: Gemma 4 E2B's per-layer MLP width and the bf16 descriptor for Google's E2B/E4B directories,
|
||||
nomic-embed-text-v2-moe (the nomicbert plugin), its config key aliases and RAD_MAP_TRANSPOSE
|
||||
honouring src_index, an f32 source narrowed to a bf16 declaration at load, and the snapshot
|
||||
store's floor ahead of --host-headroom-mib
|
||||
- griffin-warrior: the kernel report's consistency checks and coverage header, collective selftest
|
||||
cases skipped without a peer path, the build's media capability in the diagnostics, and the
|
||||
GUIDE's ROCm SDK and ffmpeg notes
|
||||
- nickreese: GBNF bounded-repetition chains shared across identical operands
|
||||
- Dad_Vibes: hc_read's decode kernels as one grid, its tiled up-mix pipelined and its one-grid
|
||||
wait trapping past its deadline, and gemm_fp8a8's narrow form with its scales staged through LDS
|
||||
and its gated three-tile form at 8 waves
|
||||
- RikshaDriver: libr3d, the RDNA3 (gfx11) kernel library
|
||||
- Dad_Vibes: hc_read's decode kernels as one grid, its tiled up-mix pipelined and its one-grid wait
|
||||
trapping past its deadline, and gemm_fp8a8's narrow form with its scales staged through LDS and
|
||||
its gated three-tile form at 8 waves, and the DeepSeek-V4.1-Flash fork's v1.1 configurations and
|
||||
measurements, with its ports of mikoskinen's full-vocabulary DSpark walk and adaptive-window
|
||||
drafting
|
||||
- RikshaDriver: libr3d, the RDNA3 (gfx11) kernel library, and its wave-matrix rewrite: the GEMMs
|
||||
retiled to 16x128 blocks, the grouped MoE GEMMs, the norms and quantisers, and the QSA and MoE
|
||||
router rows, its MoE GEMMs at w4a8 and w4a4 with dequant_w4, row_topk_merge, ngram_ids and the
|
||||
biased and short GEMMs, and w4a4's reference implementation, and Ling-3.0-tiny on bailing_hybrid
|
||||
from its GGUF releases (the K-quant and IQ4_NL imports, the MLA query LoRA) with libr3d's
|
||||
gemm_nt_f32, ple_conv, grouped router, kda_update, mla_project and mla_attn_paged
|
||||
- fl0l0u: every request entry point bounded, gated and sanitised (JSON parses bounded in depth,
|
||||
errors safe on invalid UTF-8, control bytes kept off the log, the dashboard's CSP, cross-origin
|
||||
browsers refused on the loopback-only routes, method-scoped API-key exemptions), prompt ids that
|
||||
name no vocabulary row refused, and the telemetry the HTTP thread reads made atomic
|
||||
name no vocabulary row refused, and the telemetry the HTTP thread reads made atomic, and the
|
||||
security review of 2.0 and 2.1 with its hardening follow-up
|
||||
- Brandon Bertelsen: Cloudflare's clef and clef-flash with their joint schema head on the card
|
||||
(seg_softmax_pool, a request's words for the plugin), Convai Innovations' Laya decision models,
|
||||
Mica on /v1/systemone, and Metaspace prepending only to text not already starting with its
|
||||
replacement
|
||||
- Gaspa79: NVIDIA's Nemotron 3.5 Embed 1B and 8B -- the nemotron35_embed plugin, its Pixtral
|
||||
tower and their CPU path -- and Nemotron 3.5 Rerank 8B on /rerank, with its BF16 masked mean
|
||||
replacement, and MiniMax-H3's song guide, an audio reference pinned from a frame with both stereo
|
||||
channels kept
|
||||
- Gaspa79: NVIDIA's Nemotron 3.5 Embed 1B and 8B -- the nemotron35_embed plugin, its Pixtral tower
|
||||
and their CPU path -- and Nemotron 3.5 Rerank 8B on /rerank, with its BF16 masked mean
|
||||
(seg_mean_bf16_sum)
|
||||
- overchop: the file tier for large MoEs -- routing-aware reads of only the routed experts, the
|
||||
hot VRAM cache with its deposits and copyless relabels, and GLM-5.3-Flash's experts read
|
||||
file-direct under expert parallelism -- the stall watch counting drive reads as progress, and
|
||||
the DMA lane's lists fenced so a stalled read pointer no longer fills its ring
|
||||
- overchop: the file tier for large MoEs -- routing-aware reads of only the routed experts, the hot
|
||||
VRAM cache with its deposits and copyless relabels, and GLM-5.3-Flash's experts read file-direct
|
||||
under expert parallelism -- the stall watch counting drive reads as progress, and the DMA lane's
|
||||
lists fenced so a stalled read pointer no longer fills its ring
|
||||
- pokesjw: the n-gram reader refilling its reads as they land, and a decode gather waiting on the
|
||||
other rank's read of a row instead of reading it again
|
||||
- AnimusNull: GLM-5.3-Flash on four cards -- its experts split by width, the small-M MXFP4 expert
|
||||
form at the TP4 slices, the indexer's take-all steps -- its E4M3 latent cache (mla_attn's fp8kv
|
||||
rows), and the DMA lane's room check over a reused fence slot, and GLM-5.3-Flash on 2.x: its IQR
|
||||
and IQ8R container, plugin/glm with mla_attn over an int8 latent cache, chained decode launches
|
||||
and tp4.yaml
|
||||
- neuromanMD: libr3d's MXFP4 GEMM leaving VRAM exponent planes unscanned from the host, and its
|
||||
branch-free e4m3_to_f32
|
||||
- everplays: the paged attention at seven queries a KV head, head_dim 128 (Nanbeige4.3-33B), and
|
||||
Recursive Flint -- its plugin, the sink-aware WMMA prefill attention and the fused prologue at
|
||||
rotary_dim 0
|
||||
- Kezi: the decode tile arms of the int4 and int5 x int8 GEMM, and draft trees for Qwen3.8-27B's
|
||||
DFlash2 drafts (the tree verify rows and the gdn fold)
|
||||
- dschmitz: the two-rank fused writes' host-mailbox twins taking their chained forms, the card
|
||||
telemetry's junction temperature, and a replayed tool call's blank arguments read as the empty
|
||||
object with arguments that are not JSON refused naming the call
|
||||
- eniga: the diagnosis of GLM-5.3-Flash's template refused for tools (jinja's unique filter)
|
||||
- tnhnyzc: the mixed-step service-time target (mixed-step-target-ms)
|
||||
- aelfwyne: the diagnosis of draft trees refusing the int8 KV cache's rows
|
||||
- DokterSmol: LiquidAI's LFM3 (lfm3_bf16: bf16, int8 and IQ8R trunks, the windowed attention at
|
||||
head_dim 128 with four queries a KV head on libr4d and libhalo), and LFM3-1.7B on RDNA3 iGPUs in
|
||||
libr3d (the int8 trunk GEMM, attn_paged decode at depth, had_quant_act_i8g at whole groups)
|
||||
- rkcth: Qwen-Image 2.1's, Krea 2's and MiniMax-H3's deployment pixel and reference limits, a video
|
||||
job held through its model's drain, tensor-parallel queues guarded beside single-rank engines,
|
||||
guidance requests refused past the sequence limit, adapter image requests queued in order, model
|
||||
discovery that leaves idle timers alone, host room reserved atomically for loads and fills, idle
|
||||
expert-cache capacity restored, and LoRA rank truncation that drops dependent columns, and Wan 2.2
|
||||
TI2V-5B's text-to-video and first-frame video, Krea 2's instruction edits with one or two
|
||||
references and its registered outfill, LoRA on the image generators (rotated inputs, bias deltas
|
||||
and row-mixer adapters per request, combinations checked without a GPU slot, versioned adapter
|
||||
snapshots), the DSpark drafter's full and local-window KV groups, --draft-max-lanes,
|
||||
--draft-min-accept and --draft-window-ckpt, MiniMax-H3's model-declared sparse attention profiles,
|
||||
the wide scalar head and the opt-in f32 WMMA logits row, and parked weights rebuilt on the CPU,
|
||||
memory ownership kept across a failed handoff, quiescent callbacks serialised, admission errors
|
||||
kept and staging recycled only once its copies land
|
||||
- dowjames: runtime LoRA on a rotated int8 trunk (plain fp GEMM sites over transform-basis weights,
|
||||
the lora_plain kernel library) and served adapters listed as children in /admin/fleet, and the
|
||||
dashboard's per-LoRA attribution
|
||||
- kaczy44: Gemma 4 26B-A4B's vision tower and rad-convert --add-vision
|
||||
- Itoash: a tool-call delimiter that does not end the turn, and Ling 3.0's function names ending at
|
||||
whitespace, and LTX-2's chunk ceiling raised to 40
|
||||
- jintakhan: gemma4_bf16's sliding-window attention ported to gemma4
|
||||
- forestjohnson: the dashboard behind a reverse proxy at a relative path
|
||||
- zihaomu: libr3d's packed dense IQR GEMM and routed IQR expert gate/up rows on gfx1100, libhalo's
|
||||
GEMV decode form for the w4nl64a8i8h MoE down, memory.card-headroom-mib on single-model
|
||||
tensor-parallel budgets, and the build with ROCm's clang as the host compiler
|
||||
- Hero422: the EXL3 dense rows on the card (exl3r4d's fast dense row and its prefill form),
|
||||
qwen35_exl3's tensor parallelism and the token table as a Lloyd codebook (embed_tq)
|
||||
- kevinjd: memory.queue-reserve, the hardware queues a card keeps ready, closed when a model leaves
|
||||
the card
|
||||
- Foundry: memory.pinned-numa-node
|
||||
- Warzuponus: Inkling 2's tool calls (message_open and object_args_key) and jinja's tojson with
|
||||
sort_keys
|
||||
- morevgalex: int8 experts for drama-3 (fishomni)
|
||||
- millaguie: Inkling 2's image processor, transformers' bit for bit, and reasoning_effort "none"
|
||||
and "minimal" passed to a template that takes them as levels
|
||||
- lowell80: the tested C++ compiler in the build guide
|
||||
- kepler_62f: hfget's file sizes measured with stat
|
||||
|
||||
This product includes software from the following projects, each under the MIT License. The
|
||||
license text is in the file named beside each.
|
||||
@@ -158,9 +292,16 @@ license text is in the file named beside each.
|
||||
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
|
||||
yyjson Copyright (c) 2020 YaoYuan vendor/yyjson/LICENSE
|
||||
cpp-httplib Copyright (c) 2017 yhirose vendor/cpp-httplib/LICENSE
|
||||
|
||||
The dashboard's page, compiled into the server from core/server/dashboard_page.h, carries
|
||||
third-party software built into it: React, Base UI and Floating UI, uPlot, shadcn/ui's components
|
||||
and helpers, Tailwind CSS's generated style and tw-animate-css (MIT), class-variance-authority
|
||||
(Apache-2.0), the Lucide icons (ISC), and the Geist and Geist Mono typefaces (SIL Open Font License
|
||||
1.1, Copyright the Geist Project Authors). dashboard/THIRD-PARTY-LICENSES.txt lists every package
|
||||
with its version and license text, as the page's build wrote it.
|
||||
|
||||
tests/data/chat/hyv3/chat_template.jinja is Tencent's Hy-Memory-30B-A3B chat template,
|
||||
copied unchanged from tencent/Hy-Memory-30B-A3B on Hugging Face.
|
||||
Copyright (C) 2026 Tencent. All rights reserved. Licensed under Apache-2.0 (LICENSE).
|
||||
@@ -205,3 +346,22 @@ f88f8d9104726747791283ab156d2fcdb29e90a7:
|
||||
https://huggingface.co/nvidia/Nemotron-3.5-Rerank-8B-BF16/tree/f88f8d9104726747791283ab156d2fcdb29e90a7
|
||||
It is covered by the same retained OpenMDW-1.1 license.
|
||||
Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
||||
|
||||
radiance-exl3
|
||||
-------------
|
||||
|
||||
exl3/ is radiance-exl3 (Copyright 2026 Dylan Johnston, Apache-2.0; exl3/LICENSE and exl3/NOTICE),
|
||||
imported from mikoskinen/r9700-exact-serving: the EXL3 kernel libraries exl3r4d and exl3ref, the
|
||||
exl3 quantiser and their common decode. arch/common/exl3/ carries copies of three of its headers.
|
||||
Its EXL3 decode is a transcription of exllamav3's (Copyright (c) 2025 Turboderp, MIT License), whose
|
||||
notice exl3/NOTICE reproduces.
|
||||
|
||||
r9700-exact-serving
|
||||
-------------------
|
||||
|
||||
Parts of the DeepSeek-V4.1-Flash support are ported from mikoskinen/r9700-exact-serving
|
||||
(Copyright 2026 Mikael Koskinen, Apache-2.0): libr4d's multi-row decode forms of the ggml GEMMs
|
||||
(r4d_ds41_ggml_mr.hip), the full-vocabulary DSpark walk (r4d_ds41_walk.hip) and their r4d_selftest checks, the weight sidecar
|
||||
(core/engine_bringup.cpp, tools/rad_sidecar.cpp), and the scheduler's depth-0 and lookup / head
|
||||
hybrid drafting (core/sched/draft.cpp, core/sched/scheduler.cpp). The commits each came from are
|
||||
named in this repository's history.
|
||||
@@ -6,7 +6,10 @@ APIs, Anthropic's Messages API and llama-server's native one, so their clients a
|
||||
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
|
||||
The bundled device kernels target AMD RDNA4 (`libr4d`: `gfx1200`, `gfx1201`), RDNA3 (`libr3d`:
|
||||
`gfx11xx`) and Strix Halo (`libhalo`: `gfx1151`); EXL3-V3 trellis linears, for the Qwen3.5-3.8
|
||||
dense and Gemma 4 dense architectures under `plugin/`, have a `gfx1201` library of their own
|
||||
(`plugin/exl3i`). The serve settings
|
||||
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,
|
||||
@@ -17,58 +20,79 @@ To support the development of radiance: [Patreon](https://patreon.com/StillDeadC
|
||||
|
||||
## Models
|
||||
|
||||
| model | container | get it | compose file |
|
||||
| model | container | get it | fleet 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` |
|
||||
| Ornith-1.5-35B-A3B FP8, MTP, vision | `ornith-1.5-35b-a3b-fp8.rad` (35 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-35b-a3b-fp8) | `ornith-1.5-35b-a3b.yaml` |
|
||||
| Ornith-1.5-35B-A3B w4a8: 4-bit experts (GPTQ), MTP, vision, fits one card | `ornith-1.5-35b-a3b-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-35b-a3b-w4a8) | `ornith-1.5-35b-a3b-w4a8.yaml` |
|
||||
| Ornith-1.5-122B FP8, MTP, vision, four cards | `ornith-1.5-122b-fp8.rad` (118 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-122b-fp8) | `ornith-1.5-122b.yaml` |
|
||||
| Ornith-1.5-122B FP8, DFlash2 drafter, vision, four cards | `ornith-1.5-122b-fp8-dflash2.rad` (116 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-122b-fp8-dflash2) | `ornith-1.5-122b-df2.yaml` |
|
||||
| Ornith-1.5-122B w4a8: 4-bit experts (GPTQ), MTP, vision, four cards | `ornith-1.5-122b-w4a8.rad` (65 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-122b-w4a8) | `ornith-1.5-122b-w4a8.yaml` |
|
||||
| Ornith-1.5-122B w4a8: 4-bit experts (GPTQ), DFlash2 drafter, vision, four cards | `ornith-1.5-122b-w4a8-dflash2.rad` (64 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-122b-w4a8-dflash2) | `ornith-1.5-122b-w4a8-df2.yaml` |
|
||||
| Sage-A1.5 FP8, MTP, vision | `sage-a1.5-fp8.rad` (35 GiB) | [download](https://huggingface.co/Aijuus/sage-a1.5-fp8) | `sage-a1.5.yaml`, `sage-a1.5-tp1.yaml` |
|
||||
| Sage-A1.5 FP8, DFlash2 drafter, vision | `sage-a1.5-fp8-df2.rad` (34 GiB) | [download](https://huggingface.co/Aijuus/sage-a1.5-fp8-df2) | `sage-a1.5-df2.yaml` |
|
||||
| MiniCPM5-2B FP8, DSpark drafter | `minicpm5-2b-fp8.rad` (3 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-fp8) | `minicpm5-2b.yaml` |
|
||||
| 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` |
|
||||
| Gemma 4 31B heretic-ara (refusals removed): GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-heretic-ara-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-heretic-ara-w4a8) | `gemma4-31b-heretic-ara-w4a8.yaml` |
|
||||
| Gemma 4 31B: int4 trunk, int8 activations and lm_head, DFlash drafter, vision | `gemma4-31b-dense-w4a8-df.rad` (22 GiB) | [download](https://huggingface.co/Ashlyn4202025/gemma4-31b-w4a8-dflash) | `gemma4-31b-w4a8-df.yaml` |
|
||||
| Gemma 4 31B Q8: int8 trunk and lm_head (Q8_0's grid at group 128), int8 DFlash drafter, vision | `gemma4-31b-dense-q8-df.rad` (33 GiB) | [convert](#convert-a-checkpoint) | `gemma4-31b-q8-df.yaml` |
|
||||
| Gemma 4 31B on four cards: int4 trunk, int8 activations and lm_head, RedHatAI's DFlash2 drafter, vision | `gemma4-31b-dense-w4a8-df2-qkv.rad` (23 GiB) | [download](https://huggingface.co/Ashlyn4202025/gemma4-31b-w4a8-dflash2) | `gemma4-31b-w4a8-df2-tp4.yaml` |
|
||||
| Gemma 4 31B on four or two cards: int4 trunk, int8 activations and lm_head, a block-16 DFlash2 drafter (15 drafts a step, verified as a tree), vision | `gemma4-31b-dense-w4a8-df2b16-qkv.rad` (23 GiB) | [download](https://huggingface.co/Ashlyn4202025/gemma4-31b-w4a8-dflash2-b16) | `gemma4-31b-w4a8-df2b16-tp4.yaml`, `gemma4-31b-w4a8-df2b16-tp2.yaml` |
|
||||
| NVIDIA-Nemotron-3.5-Bolt-E4B bf16 (Gemma 4 E4B), NVIDIA's DFlash drafter, vision, audio | `nemotron-3.5-bolt-e4b-bf16.rad` (17 GiB) | [download](https://huggingface.co/keptn/nemotron-3.5-bolt-e4b-bf16) | `nemotron-3.5-bolt-e4b-bf16.yaml` |
|
||||
| NVIDIA-Nemotron-3.5-Bolt-E4B int8 (i8a8, Gemma 4 E4B), NVIDIA's DFlash drafter, vision, audio | `nemotron-3.5-bolt-e4b-i8g.rad` (13 GiB) | [download](https://huggingface.co/keptn/nemotron-3.5-bolt-e4b-i8g) | `nemotron-3.5-bolt-e4b-i8g.yaml` |
|
||||
| NVIDIA-Nemotron-3.5-Bolt-E4B 4-bit (int4 feed-forward, GPTQ, Gemma 4 E4B), NVIDIA's DFlash drafter, vision, audio | `nemotron-3.5-bolt-e4b-a4.rad` (12 GiB) | [download](https://huggingface.co/keptn/nemotron-3.5-bolt-e4b-a4) | `nemotron-3.5-bolt-e4b-a4.yaml` |
|
||||
| Qwen-Image 2.1 FP8: text to image and image edits | `qwen-image-2.1-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-fp8) | `qwen-image-2.1.yaml` |
|
||||
| Qwen-Image 2.1 Turbo FP8: the same in 8 steps | `qwen-image-2.1-turbo-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-turbo-fp8) | `qwen-image-2.1-turbo.yaml` |
|
||||
| Krea 2 Turbo FP8: text to image, one card | `krea-2-turbo-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/krea-2-turbo-radiance-fp8) | `krea-2-turbo.yaml` |
|
||||
| Krea 2 Raw FP8: the same, undistilled | `krea-2-raw-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/krea-2-raw-radiance-fp8) | `krea-2-raw.yaml` |
|
||||
| FLUX.3 [klein] FP8: text to image and edits from up to ten pictures, one card | `flux-3-klein-fp8.rad` (9.3 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-flux-3-klein-fp8) | `flux-3-klein.yaml` |
|
||||
| FLUX.3 [klein] base FP8 | `flux-3-klein-base-fp8.rad` (9.3 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-flux-3-klein-base-fp8) | `flux-3-klein.yaml` |
|
||||
| LTX-2.5 distilled FP8: video with its stereo soundtrack from text or a first frame, one card | `ltx-2.5-distilled-fp8.rad` (37 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-ltx-2.5-distilled-fp8) | `ltx-2.5.yaml` |
|
||||
| LTX-2.5 base FP8 | `ltx-2.5-fp8.rad` (37 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-ltx-2.5-fp8) | `ltx-2.5.yaml` |
|
||||
| MiniMax-H3 FP8: video with its stereo soundtrack from text | `minimax-h3-fp8.rad` (60 GiB) | [download](https://huggingface.co/StillDeadcode/minimax-h3-fp8) | `minimax-h3.yaml` |
|
||||
| FastH3 8-Step V2 FP8: the same in eight steps | `fasth3-8-step-v2-fp8.rad` (62 GiB) | [download](https://huggingface.co/StillDeadcode/fasth3-8-step-v2-fp8) | `fasth3.yaml` |
|
||||
| MiniMax-Music3 bf16: songs from lyrics and a description | `minimax-music3-bf16.rad` (20 GiB) | [download](https://huggingface.co/StillDeadcode/minimax-music3-bf16) | `minimax-music3.yaml` |
|
||||
| Unlimited-OCR bf16: document parsing with the DeepEncoder tower | `unlimited-ocr-bf16.rad` (6.2 GiB) | [download](https://huggingface.co/Aijuus/unlimited-ocr-bf16) | `unlimited-ocr-bf16.yaml` |
|
||||
| Breeze-TTS-2 bf16: speech, whole, streamed or live, one card | `breeze-tts2-bf16.rad` (5.5 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-breeze-tts2-bf16) | `breeze-tts2.yaml` |
|
||||
| Fish Audio drama-3: speech with speaker tags and inline direction, voices cloned from reference clips, whole, streamed or live; block-FP8 experts, two cards | `drama3-fp8.rad` (36 GiB) | [convert](#convert-a-checkpoint) | `drama3.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` |
|
||||
| TranslateGemma 27B MXFP4 (GPTQ), translation; optional DFlash2 drafter | `translategemma-27b-mxfp4-gptq.rad` (17 GiB) | [convert](#convert-a-checkpoint) | `translategemma-27b.yaml` |
|
||||
| GLM-5.3-Flash: MXFP4 experts and block-FP8 attention (AMD Quark), MTP, vision, eight cards | `glm53-flash-mxfp4.rad` (172 GiB) | [convert](#convert-a-checkpoint) | `glm53-flash.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` |
|
||||
| Stable Diffusion XL bf16 and its finetunes (Illustrious, NoobAI, Pony): text to image, one card | `illustrious-xl-v2.0-bf16.rad` (6.4 GiB), from any single-file SDXL checkpoint | [convert](#convert-a-checkpoint) | `sdxl.yaml` |
|
||||
| EmbeddingGemma 2 bf16: text, image, video and audio embeddings, one card | `embeddinggemma2-bf16.rad` (1.4 GiB) | [convert](#convert-a-checkpoint) | `embeddinggemma2.yaml` |
|
||||
| nomic-embed-text-v2-moe bf16: text embeddings, one card | `nomic-embed-v2-moe-bf16.rad` (959 MB) | [convert](#convert-a-checkpoint) | - |
|
||||
| Qwen3.8-Flash-Next: IQR-V4 experts, int8 trunk, MTP, vision | `qwen3.8-next-flash-iqr-v4.rad` (113 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-next-flash-iqr-v4) | `tp1.yaml`, `tp2.yaml` |
|
||||
| GLM-5.3-Flash: IQR-V4 experts, IQ8R trunk, int8 latent cache, four cards with the experts tiered to host memory | `glm53-flash-iqr-v4.rad` (159 GiB) | [download](https://huggingface.co/animusnull/glm-5.3-flash-iqr-v4) | `tp4.yaml` |
|
||||
| DeepSeek-V4.1-Flash 1017 uncensored (refusals removed): llama.cpp's blocks at 2.83 bits a weight (its DSpark drafter's MXFP4 experts are not served), exact fp8 cache, two or four cards with the experts tiered to host memory ([docs/ARCHITECTURES.md](docs/ARCHITECTURES.md#deepseek41-deepseek-v41-flash)) | `deepseek-v4.1-flash-1017-uncensored.rad` (134 GiB of experts) | [download](https://huggingface.co/bakon3/DeepSeek-V4.1-Flash-1017-uncensored-rad) | — |
|
||||
| Qwen3.8-Flash-Next abliterated (refusals removed): IQR-V4 trunk (GPTQ), codebook experts (round to nearest), MTP, vision | `qwen3.8-flash-next-uncensored-iqr-v4.rad` (113 GiB) | [download](https://huggingface.co/davetha/qwen3.8-flash-next-uncensored-iqr-v4) | — |
|
||||
| Qwen3.8-Flash-Next: calibrated Q5 expert down (w5nl, group 64), BF16 PLE, vision | `qwen4exp-w5dn64-bf16ple-gptq.rad` (166 GiB) | [download](https://huggingface.co/gostar77/qwen3.8-flash-next-radiance-q5-w5dn64-bf16ple) | — |
|
||||
| Qwen3.8-Flash-Next IQ5R-V4: U5 trunk, W5NL expert down, BF16 PLE and vision | `qwen3.8-flash-next-iq5r.rad` (175 GiB) | [download](https://huggingface.co/gostar77/qwen3.8-flash-next-iq5r-v4-u5-w5-bf16ple) | — |
|
||||
| Qwen3.8-Flash-Next: U4 expert gate/up, W6NL expert down, BF16 PLE and vision | `qwen3.8-flash-next-u4-w6-bf16ple.rad` (170 GiB) | [download](https://huggingface.co/gostar77/qwen3.8-flash-next-u4-w6-bf16ple) | — |
|
||||
| Qwen3.8-27B IQ8R (rotated int8), DFlash2 drafter, vision | `qwen3.8-27b-iq8r-dflash.rad` (29 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-27b-iq8r-dflash) | `tp2.yaml` |
|
||||
| Qwen3.8-27B IQR-V4, 2.5 to 8 bits a weight ([docs/IQR.md](docs/IQR.md)), DFlash2 drafter, vision | `qwen3.8-27b-iq2r-v4.rad` .. `qwen3.8-27b-iq8r-v4.rad` (10 to 28 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-27b-iqr-v4) | `tp1.yaml` (IQ4R-L) |
|
||||
| Hemmingway-1.5 (Qwen3.8-27B fine-tune) IQ4R-S, tool-tail GPTQ; this version serves the trunk, not the MTP block | `hemmingway-1.5-iq4r-s-tool-tail-mtp-gptq.rad` (14 GiB) | [download](https://huggingface.co/gostar77/hemmingway-1.5-iq4r-s-tool-tail-mtp-gptq) | — |
|
||||
| Qwen3.6-35B-A3B IQ8R, MTP | `qwen3.6-35b-a3b-iq8r.rad` (35 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.6-35b-a3b-iq8r) | — |
|
||||
| MiniCPM5-2B IQ8R, DSpark drafter | `minicpm5-2b-iq8r.rad` (3 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-iq8r) | `tp1.yaml`, `tp2.yaml` |
|
||||
| MiniCPM5-2B bf16 (served without its drafter) | `minicpm5-2b-bf16.rad` (5 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-bf16) | — |
|
||||
| Spark X2.6 4B bf16: thinking and tool calls, one to four cards | `spark-x2.6-4b-radiance-bf16.rad` (8.3 GiB), with DSpark `spark-x2.6-4b-radiance-bf16-dspark.rad` (10 GiB) | [download](https://huggingface.co/gostar77/spark-x2.6-4b-radiance) | — |
|
||||
| Spark X2.6 4B IQ8R: rotated int8 trunk, optional bf16 head, layers 0-11 kept bf16, optional DSpark | `spark-x2.6-4b-radiance-iq8r-diverse.rad` .. `spark-x2.6-4b-radiance-iq8r-bf16-head-dspark.rad` (4.5 to 6.6 GiB) | [download](https://huggingface.co/gostar77/spark-x2.6-4b-radiance) | — |
|
||||
| Hy-Memory-30B-A3B bf16 | `hy-memory-30b-a3b-bf16.rad` (56 GiB) | [download](https://huggingface.co/gostar77/hy-memory-30b-a3b-radiance) | — |
|
||||
| Hy-Memory-30B-A3B W4 GPTQ: attention, dense MLP and routed experts | `hy-memory-30b-a3b-w4-gptq-full-1m.rad` (15 GiB) | [download](https://huggingface.co/gostar77/hy-memory-30b-a3b-radiance) | — |
|
||||
| Gemma 4 31B: GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-w4a8) | — |
|
||||
| Gemma 4 31B w5: GPTQ int5 trunk (a scale and a zero point per 128 weights), MTP, vision | `gemma4-31b-w5.rad` (23 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-w5) | — |
|
||||
| Gemma 4 31B heretic-ara (refusals removed): GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-heretic-ara-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-heretic-ara-w4a8) | — |
|
||||
| Gemma 4 31B: int8 trunk and lm_head (no calibration), MTP, vision | `gemma4-31b-i8g.rad` (33 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-i8g) | — |
|
||||
| Gemma 4 31B heretic-ara (refusals removed): int8 trunk and lm_head (no calibration), MTP, vision | `gemma4-31b-heretic-ara-i8g.rad` (33 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-heretic-ara-i8g) | — |
|
||||
| Gemma 4 31B Q8: int8 trunk and lm_head (Q8_0's grid at group 128), int8 DFlash drafter, vision | `gemma4-31b-dense-q8-df.rad` (33 GiB) | [convert](#convert-a-checkpoint) | — |
|
||||
| Gemma 4 12B bf16: MTP, vision, audio | `gemma4-12b-bf16.rad` (25 GiB) | [download](https://huggingface.co/keptn/gemma4-12b-bf16) | — |
|
||||
| Gemma 4 12B int8 (i8a8): MTP, vision, audio | `gemma4-12b-i8g.rad` (14 GiB) | [download](https://huggingface.co/keptn/gemma4-12b-i8g) | — |
|
||||
| Qwen-Image 2.1 IQ8R: text to image and image edits | `qwen-image-2.1-iq8r.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-iq8r) | `tp1.yaml`, `tp2.yaml` |
|
||||
| Qwen-Image 2.1 Turbo IQ8R: the same in 8 steps | `qwen-image-2.1-turbo-iq8r.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-turbo-iq8r) | — |
|
||||
| Krea 2 Turbo IQ8R: text to image, one card | `krea-2-turbo-iq8r.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/krea-2-turbo-radiance-iq8r) | — |
|
||||
| Krea 2 Raw IQ8R: the same, undistilled | `krea-2-raw-iq8r.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/krea-2-raw-radiance-iq8r) | — |
|
||||
| FLUX.3 [klein] IQ8R: text to image and edits from up to ten pictures, one card | `flux-3-klein-iq8r.rad` (9.4 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-flux-3-klein-iq8r) | — |
|
||||
| FLUX.3 [klein] base IQ8R | `flux-3-klein-base-iq8r.rad` (9.3 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-flux-3-klein-base-iq8r) | — |
|
||||
| LTX-2.5 distilled IQ8R: video with its stereo soundtrack from text or a first frame, one card | `ltx-2.5-distilled-iq8r.rad` (37 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-ltx-2.5-distilled-iq8r) | — |
|
||||
| LTX-2.5 base IQ8R | `ltx-2.5-iq8r.rad` (37 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-ltx-2.5-iq8r) | — |
|
||||
| MiniMax-H3, int8 DiT: video with its stereo soundtrack from text | `minimax-h3-i8.rad` (63 GiB) | [download](https://huggingface.co/StillDeadcode/minimax-h3-i8) | `tp2.yaml` |
|
||||
| FastH3 8-Step V2, int8 DiT: the same in eight steps | `fasth3-8-step-v2-i8.rad` (65 GiB) | [download](https://huggingface.co/StillDeadcode/fasth3-8-step-v2-i8) | — |
|
||||
| MiniMax-Music3 bf16: songs from lyrics and a description | `minimax-music3-bf16.rad` (20 GiB) | [download](https://huggingface.co/StillDeadcode/minimax-music3-bf16) | `tp1.yaml`, `tp2.yaml` |
|
||||
| Unlimited-OCR bf16: document parsing with the DeepEncoder tower | `unlimited-ocr-bf16.rad` (6.2 GiB) | [download](https://huggingface.co/Aijuus/unlimited-ocr-bf16) | — |
|
||||
| Breeze-TTS-2 bf16: speech, whole, streamed or live, one card | `breeze-tts2-bf16.rad` (5.5 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-breeze-tts2-bf16) | `tp1.yaml`, `tp2.yaml` |
|
||||
| Fish Audio drama-3: speech with speaker tags and directions, two cards | `drama3-i8.rad` (37 GiB) | [convert](data/recipes/drama3-i8.recipe) | — |
|
||||
| TranslateGemma 27B, int8 trunk: translation | `translategemma-27b-i8.rad` (28 GiB) | [download](https://huggingface.co/StillDeadcode/translategemma-27b-i8) | — |
|
||||
| Qwen3.8-27B bf16 | `qwen3.8-27b-bf16.rad` (50 GiB) | [convert](#convert-a-checkpoint) | — |
|
||||
| Qwen3.8-Flash-Next bf16, a disk-streamed reference | `qwen3.8-flash-next-bf16.rad` (335 GiB) | [convert](#convert-a-checkpoint) | — |
|
||||
| Stable Diffusion XL bf16 and its finetunes (Illustrious, NoobAI, Pony): text to image, one card | `illustrious-xl-v2.0-bf16.rad` (6.4 GiB), from any single-file SDXL checkpoint | [convert](#convert-a-checkpoint) | — |
|
||||
| EmbeddingGemma 2 bf16: text, image, video and audio embeddings, one card | `embeddinggemma2-bf16.rad` (1.4 GiB) | [convert](#convert-a-checkpoint) | `tp1.yaml`, `tp2.yaml` |
|
||||
| nomic-embed-text-v2-moe bf16: text embeddings, one card | `nomic-embed-v2-moe-bf16.rad` (959 MB) | [convert](#convert-a-checkpoint) | — |
|
||||
| LiquidAI LFM3-1.7B IQ8R: rotated int8 trunk, bf16 head; text, tool calls and reasoning, one card | `lfm3-1.7b-iq8r.rad` (2.5 GiB) | [convert](#convert-a-checkpoint) with `data/recipes/lfm3-1.7b-iq8r.recipe` | — |
|
||||
| LiquidAI LFM3-1.7B bf16: text, tool calls and reasoning, one card | `lfm3-1.7b-bf16.rad` (3.8 GiB) | [convert](#convert-a-checkpoint) | — |
|
||||
| Meta Muse Glimmer 30B bf16: text, images and video; sliding-window rotary layers between NoPE full ones, a windowed ViT | `muse-glimmer-30b-bf16.rad` (56 GiB) | [convert](#convert-a-checkpoint) | — |
|
||||
| Meta Muse Glimmer 30B w4a8: int4 trunk, images and video, one card | `muse-glimmer-30b-w4a8.rad` (16 GiB) | [convert](#convert-a-checkpoint) | — |
|
||||
| Meta Muse Glimmer 30B IQ8R: rotated int8 trunk, int8 head, DFlash drafter, images and video | `muse-glimmer-30b-iq8r-dflash.rad` (36 GiB) | [download](https://huggingface.co/StillDeadcode/muse-glimmer-30b-iq8r-dflash) | — |
|
||||
| Meta Muse Glimmer 30B IQ4R-V4: trellis trunk, DFlash2, BF16 vision | `muse-glimmer-30b-iq4r-v4-df2.rad` (24 GiB) | [download](https://huggingface.co/gostar77/muse-glimmer-30b-iq4r-v4-radiance) | — |
|
||||
| Meta Muse Glimmer 30B IQ4R-S-V4: smaller trellis trunk, DFlash2, BF16 vision | `muse-glimmer-30b-iq4r-s-v4-df2-bf16vision.rad` (19.6 GiB) | [download](https://huggingface.co/gostar77/muse-glimmer-30b-iq4r-s-v4-radiance) | — |
|
||||
| Meta Muse Glimmer 30B IQ4R-S-V4, int8 vision (needs [#564](https://codeberg.org/StillDeadcode/radiance/pulls/564)) | `muse-glimmer-30b-iq4r-s-v4-df2-i8vision.rad` (17.8 GiB) | [download](https://huggingface.co/gostar77/muse-glimmer-30b-iq4r-s-v4-radiance) | — |
|
||||
| Recursive Flint (39.8B, about 2.5B active) IQ8R: rotated int8 trunk and experts, two cards | `flint-iq8r.rad` (38 GiB) | [download](https://huggingface.co/StillDeadcode/flint-iq8r) | — |
|
||||
| Ling-3.0-tiny IQ8R: rotated int8 trunk and experts, one card | `ling-3.0-tiny-iq8r.rad` (7.9 GiB) | [download](https://huggingface.co/StillDeadcode/ling-3.0-tiny-iq8r) | — |
|
||||
| NVIDIA Nemotron-3.5-Bolt-74B-A9B 2-bit: NVIDIA's IQ2_XXS experts and Q8_0 linears as stored, IQ8R Mamba projections, LiLiCorr drafter, one card | `nemotron74-2bit.rad` (26.66 GiB of weights) | [convert](data/recipes/nemotron74-nvidia-24gb-iq8r.recipe) | — |
|
||||
| Nemotron 3.5 Embed 1B BF16: text and image embeddings, one card | the checkpoint as it ships | [NVIDIA checkpoint](https://huggingface.co/nvidia/Nemotron-3.5-Embed-1B-BF16) | — |
|
||||
| Nemotron 3.5 Embed 8B BF16: text and image embeddings, one card | the checkpoint as it ships | [NVIDIA checkpoint](https://huggingface.co/nvidia/Nemotron-3.5-Embed-8B-BF16) | — |
|
||||
| Nemotron 3.5 Rerank 8B BF16: text/image document relevance, one card | the checkpoint as it ships | [NVIDIA checkpoint](https://huggingface.co/nvidia/Nemotron-3.5-Rerank-8B-BF16) | — |
|
||||
| Anima Aesthetic FP8: anime and illustration, text to image, one card (Base and Turbo convert the same way) | `anima-aesthetic-fp8.rad` (3.0 GiB) | [convert](#convert-a-checkpoint) | `anima.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) | — |
|
||||
| Nemotron 3.5 Rerank 8B BF16: text/image document relevance, one card | the checkpoint as it ships | [NVIDIA checkpoint](https://huggingface.co/nvidia/Nemotron-3.5-Rerank-8B-BF16) | `tp1.yaml`, `tp2.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) | `tp1.yaml`, `tp2.yaml` |
|
||||
| Inkling 2 Mini IQ4R-V4 + DFlash2: the experts IQR-V4's four-bit computed trellis (GPTQ against recorded Hessians), the attention and the head rotated int8, the embedding int8, incoai's DFlash2 drafter (four-bit computed trellis, down int8), the vision tower bf16; text and images, one or two cards (`draft-window: adaptive`) ([geometry](docs/ARCHITECTURES.md#inkling2-inkling-2-mini)) | `inkling-2-mini-iq4r-v4.rad` (14.43 GiB) | [download](https://huggingface.co/StillDeadcode/inkling-2-mini-iq4r-v4) · [convert](data/recipes/inkling2-mini-iq4r-v4.recipe) | — |
|
||||
|
||||
**Not served by this version.** A container whose weights are block FP8, MXFP4, M2XFP4 or
|
||||
ParoQuant, or whose experts read E4M3 activations, is refused at startup by the name of the first
|
||||
such weight. That is every FP8 and MXFP4 container of the models above, and the models that have
|
||||
no int8 container yet: Ornith-1.5 (35B-A3B and 122B), Sage-A1.5, Ling-3.0-flash-Sante and
|
||||
Anima's FP8 container (Anima converted to bf16 is served). Each returns with an int8 container.
|
||||
A container with an int8 or bf16 trunk and a block-FP8 drafter (NVIDIA-Nemotron-3.5-Bolt-E4B,
|
||||
the Gemma 4 31B DFlash and DFlash2 containers, MiniCPM5-2B bf16), or with GGUF blocks and an
|
||||
MXFP4 drafter (the DeepSeek-V4.1-Flash container's DSpark), serves without the drafter under
|
||||
`num-speculative-tokens: 0`.
|
||||
|
||||
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
|
||||
@@ -76,7 +100,7 @@ file. Download one into your models directory (the transfer resumes if interrupt
|
||||
|
||||
```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
|
||||
curl -LC - -O https://huggingface.co/StillDeadcode/minicpm5-2b-iq8r/resolve/main/minicpm5-2b-iq8r.rad
|
||||
```
|
||||
|
||||
The Gemma 4 container is keptn42's: GPTQ calibrated in transformers, with an int8 lm_head; its
|
||||
@@ -86,38 +110,22 @@ with a scale search, bf16 lm_head); see [Convert a checkpoint](#convert-a-checkp
|
||||
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.
|
||||
|
||||
TranslateGemma 27B is converted from Google's bf16 checkpoint in three steps: an int8 container to
|
||||
calibrate in, its Gram matrices over translation prompts, then MXFP4 with GPTQ
|
||||
(`data/recipes/translategemma-27b-*.recipe`, the steps in docs/ARCHITECTURES.md). On two R9700s it
|
||||
decodes 56 tok/s a stream (205 at four) and scores mean KL 0.042 against the bf16 model on held-out
|
||||
translations; with a DFlash2 drafter, 152 a stream. Its chat template takes structured turns
|
||||
naming the two languages and refuses the plain turn the server renders at startup, so
|
||||
`translategemma-27b.yaml` serves a plain Gemma 3 template (`deploy/compose/gemma3.jinja`) and a
|
||||
client sends on `/v1/completions` the prompt the checkpoint's template renders.
|
||||
|
||||
GLM-5.3-Flash is converted from AMD's Quark export (`amd/GLM-5.3-Flash-Quark-MXFP4`) with
|
||||
`data/recipes/glm53-mxfp4.recipe`, which keeps every weight as stored except the latent
|
||||
attention's small kv_b, decoded to bf16. At 172 GiB it takes eight R9700s (`--tp 8`), every expert
|
||||
resident, and its own MTP layer drafts. On eight R9700s it prefills 3958 tok/s at 6k tokens,
|
||||
decodes 166 tok/s on one stream and 426 over eight, and 506 under eight streams of agent turns.
|
||||
Pictures go through its own vision tower, up to 4096 tokens an image at the default encoder pass
|
||||
(`--mm-max-patches 32000` serves the checkpoint's 8000); the KV cache is bf16. Its template knows
|
||||
the reasoning efforts `low` and
|
||||
`high` and renders any other as its maximum, so `glm53-flash.yaml` maps `medium` and `xhigh`
|
||||
to `high`.
|
||||
|
||||
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.
|
||||
TranslateGemma 27B is converted from Google's bf16 checkpoint with
|
||||
`data/recipes/translategemma-27b-i8a8.recipe`, an int8 trunk rounded without calibration data.
|
||||
Its chat template takes structured turns
|
||||
naming the two languages and refuses the plain turn the server renders at startup, so its entry
|
||||
serves a plain Gemma 3 template, `deploy/compose/gemma3.jinja` (`override-chat-template` names it;
|
||||
in a compose file, mount it into the container), and a client sends on `/v1/completions` the prompt
|
||||
the checkpoint's template renders.
|
||||
|
||||
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.
|
||||
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. Krea 2 is under the Krea 2 Community License and Krea's
|
||||
acceptable use policy, FLUX.3 [klein] under the FLUX Kommunity License (non-commercial use),
|
||||
LTX-2.5 under the LTX-2.x Community License, and an SDXL finetune under its checkpoint's own
|
||||
license.
|
||||
|
||||
The MiniMax-H3 containers serve OpenAI's video jobs (`/v1/videos`): a video with its stereo
|
||||
soundtrack from a prompt, 5 to 14 s, up to 1344x768. On two R9700s a 5.17 s clip at 1344x768 takes
|
||||
@@ -147,21 +155,28 @@ card works best with Resizable BAR on (Above 4G Decoding and Resizable BAR in th
|
||||
without it the engine keeps kernel arguments in pinned host memory, and every dispatch reads them
|
||||
over the link. 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:
|
||||
built for `gfx1201` (RDNA4), `gfx11-generic` (RDNA3) and `gfx1151` (Strix Halo). Pull it, clone
|
||||
this repository for its compose files, then start 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
|
||||
docker compose -f tp2.yaml up -d # two cards; tp1.yaml for one (RADIANCE_GPU), tp4.yaml for four
|
||||
docker compose -f tp2.yaml logs -f
|
||||
docker compose -f tp2.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).
|
||||
A file serves all its models from one container behind one port, and brings a model onto the cards
|
||||
when a request names it ([`docs/MULTIMODEL.md`](docs/MULTIMODEL.md)): a request's `model` is the
|
||||
entry's name (`flashnext`, `qwen3.8-27b`, `minicpm5-2b`, ...). The entries are in
|
||||
`tp1.radiance.yaml`, `tp2.radiance.yaml` and `tp4.radiance.yaml` beside the compose files, the server's configuration as
|
||||
it reads it. Delete the entries of the containers
|
||||
you do not have; any other model from the table is added as an entry with its keys from the table
|
||||
under [Run without Docker](#run-without-docker). The two files take the same port, so run one at a
|
||||
time. Running without compose, and the reason for each `docker run` option, is in
|
||||
[`docs/DOCKER.md`](docs/DOCKER.md).
|
||||
|
||||
To build the image yourself, for example for other cards, run `docker/build.sh -t 'gfx1200;gfx1201'`
|
||||
in the clone (it needs `docker buildx` and tests the build as it goes). Then set
|
||||
@@ -170,8 +185,13 @@ in the clone (it needs `docker buildx` and tests the build as it goes). Then set
|
||||
## 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:
|
||||
ROCm 10.1 or 7.2 (`hipcc`; set `ROCM_PATH` if it is not `/opt/rocm`).
|
||||
|
||||
The C++20 compiler is tested with the clang included in the ROCm 10.1 distribution; other
|
||||
compilers may produce compile errors in the C++ architecture plugins. Pull requests for
|
||||
cross-compiler build issues are not accepted.
|
||||
|
||||
Clone the repository and build in it:
|
||||
|
||||
```sh
|
||||
git clone https://codeberg.org/StillDeadcode/radiance.git && cd radiance
|
||||
@@ -190,74 +210,143 @@ prefix gets `bin/`, `include/radiance/`, `lib/cmake/radiance/`, `libexec/radianc
|
||||
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
|
||||
on 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>
|
||||
The server reads its settings from a YAML file: `server:` holds the listener, `memory:` the
|
||||
per-card VRAM budget, and `models:` one entry whose name is the model id requests use. Every key
|
||||
is named as in the [`docs/GUIDE.md`](docs/GUIDE.md) §4.11 reference; `radiance --help` prints it.
|
||||
|
||||
```yaml
|
||||
# radiance.yaml
|
||||
server:
|
||||
port: 8000
|
||||
models:
|
||||
minicpm5-2b-iq8r:
|
||||
model: /srv/models/rad/minicpm5-2b-iq8r.rad # or a Hugging Face repo id: StillDeadcode/minicpm5-2b-iq8r
|
||||
```
|
||||
|
||||
`--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),
|
||||
```sh
|
||||
export RADIANCE_HOME=$PWD/build/radiance_home # the plugins; an install finds its own
|
||||
build/bin/radiance --config radiance.yaml --check # validate the file, serve nothing
|
||||
build/bin/radiance --config radiance.yaml
|
||||
```
|
||||
|
||||
`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` (`server.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.
|
||||
`server.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.
|
||||
The server takes no other command-line options. A command line written for an earlier release
|
||||
(`radiance --model ... --tp 2`) is refused with the same settings printed as YAML, and
|
||||
`rad-yaml FLAGS...` prints that file without starting anything:
|
||||
`rad-yaml --model x.rad --tp 2 > radiance.yaml`. [`docs/MULTIMODEL.md`](docs/MULTIMODEL.md) §4
|
||||
describes the file's levels.
|
||||
|
||||
| model | flags |
|
||||
Each row holds the keys a model is served with in a file of its own (the Flash-Next rows leave out
|
||||
`prefix-cache-mib`). They go under the model's entry, except `gpu-headroom-mib`, which goes under
|
||||
`memory:` and in a file of several models holds for all of them. `tp1.radiance.yaml` and
|
||||
`tp2.radiance.yaml` carry their models' entries as set for sharing the cards; a model added to either takes its row from
|
||||
here.
|
||||
|
||||
| model | keys |
|
||||
|---|---|
|
||||
| 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` |
|
||||
| MiniMax-H3 and FastH3 | `--tp 2 --vision-tower-placement ram` |
|
||||
| MiniMax-Music3 | `--tp 2` |
|
||||
| Breeze-TTS-2 | `--tp 1` |
|
||||
| Fish Audio drama-3 | `--tp 2` |
|
||||
| Qwen3.8-Flash-Next | `tp: 2, tp-wire: wht6, max-num-seqs: 8, max-model-len: 200000, placement: expert_tiered, host-pool-mib: 24576, gpu-headroom-mib: 96, kv-cache-dtype: i8, num-speculative-tokens: 3, max-num-batched-tokens: 2048` |
|
||||
| Qwen3.8-Flash-Next, one card | `tp: 1, max-num-seqs: 4, max-model-len: 200000, placement: expert_tiered, host-pool-mib: 43000, gpu-headroom-mib: 96, kv-cache-dtype: i8, num-speculative-tokens: 3, max-num-batched-tokens: 4096, checkpoint-interval: 4096` |
|
||||
| Qwen3.8-Flash-Next, four ranks | `tp: 4, max-num-seqs: 8, max-model-len: 200000, placement: expert_tiered, host-pool-mib: 49152, gpu-headroom-mib: 96, kv-cache-dtype: i8, 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: 24576, gpu-headroom-mib: 96, kv-cache-dtype: i8, num-speculative-tokens: 3, max-num-batched-tokens: 2048` |
|
||||
| GLM-5.3-Flash | `tp: 4, placement: expert_tiered, host-pool-mib: 65536, max-num-seqs: 4, max-model-len: 262144, max-num-batched-tokens: 2048, kv-cache-dtype: i8, num-speculative-tokens: 0, prefill-interleave: 4, prefix-cache-mib: 32768, gpu-headroom-mib: 96`, and `server.kernels: glm,libr4d,libavx,libref` |
|
||||
| DeepSeek-V4.1-Flash | `tp: 2, max-num-seqs: 4, max-model-len: 262144, placement: expert_tiered, host-pool-mib: 73728, gpu-headroom-mib: 96, kv-cache-dtype: fp8, ngram-placement: disk, prefix-resume: nearest, num-speculative-tokens: 16, spec-ngram: 16, spec-ngram-max: 8, draft-window: adaptive, max-num-batched-tokens: 2048, expert-profile: data/deepseek41-expert-profile.json, chat-template-kwargs: {"enable_thinking":false}`; four cards: `tp: 4, host-pool-mib: 16384`, and on cards with unequal links `expert-split` ([docs/ARCHITECTURES.md](docs/ARCHITECTURES.md#deepseek41-deepseek-v41-flash)) |
|
||||
| Qwen3.8-27B IQ8R and IQR-V4, Qwen3.6-35B-A3B | `tp: 2, max-num-seqs: 32, max-model-len: 200000, kv-cache-dtype: i8` |
|
||||
| Qwen3.8-27B bf16 | `tp: 2, max-num-seqs: 8, max-model-len: 200000, kv-cache-dtype: i8` |
|
||||
| MiniCPM5-2B IQ8R and bf16 | `tp: 2, max-num-seqs: 32, max-model-len: 131072, kv-cache-dtype: i8, 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: true, host-pool-mib: 24576, gpu-headroom-mib: 768, deterministic: true, 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` |
|
||||
| MiniMax-H3 and FastH3 | `tp: 2, vision-tower-placement: ram` |
|
||||
| MiniMax-Music3 | `tp: 2`, or `tp: 1` (20.5 GiB of weights on the card) |
|
||||
| Breeze-TTS-2 | `tp: 1` |
|
||||
| Gemma 4 31B (GPTQ int4) | `tp: 2, max-num-seqs: 8, max-model-len: 65536, kv-cache-dtype: i8, num-speculative-tokens: 3, max-num-batched-tokens: 2048, temp: 1.0, top-p: 0.95, top-k: 64` |
|
||||
| Gemma 4 31B w5, heretic-ara int4, int8 and heretic-ara int8 | `tp: 2, max-num-seqs: 8, max-model-len: 65536, kv-cache-dtype: i8, vision-tower-placement: ram, num-speculative-tokens: 3, max-num-batched-tokens: 2048, temp: 1.0, top-p: 0.95, top-k: 64` |
|
||||
| Gemma 4 31B Q8 | `tp: 2, max-num-seqs: 8, max-model-len: 65536, kv-cache-dtype: i8, num-speculative-tokens: 0, max-num-batched-tokens: 2048, temp: 1.0, top-p: 0.95, top-k: 64` |
|
||||
| Gemma 4 12B bf16 | `tp: 2, max-num-seqs: 8, max-model-len: 65536, kv-cache-dtype: bf16, num-speculative-tokens: 3, max-num-batched-tokens: 2048, mm-max-patches: 1120, temp: 1.0, top-p: 0.95, top-k: 64, chat-template-kwargs: {"enable_thinking":false}` |
|
||||
| Gemma 4 12B int8 | `tp: 1, max-num-seqs: 8, max-model-len: 65536, kv-cache-dtype: bf16, num-speculative-tokens: 3, max-num-batched-tokens: 2048, mm-max-patches: 1120, temp: 1.0, top-p: 0.95, top-k: 64, chat-template-kwargs: {"enable_thinking":false}` |
|
||||
| NVIDIA-Nemotron-3.5-Bolt-E4B bf16, int8 and 4-bit, without the drafter | `tp: 2, max-num-seqs: 8, max-model-len: 65536, kv-cache-dtype: bf16, num-speculative-tokens: 0, mm-max-patches: 2520, vision-tower-placement: ram, temp: 1.0, top-p: 0.95, top-k: 64, chat-template-kwargs: {"enable_thinking":false}`; `tp: 1` on one card |
|
||||
| TranslateGemma 27B | `tp: 2, max-num-seqs: 8, max-model-len: 16384, kv-cache-dtype: i8`, and `override-chat-template` naming `deploy/compose/gemma3.jinja` |
|
||||
| Unlimited-OCR | `tp: 1, max-num-seqs: 8, max-model-len: 32768, kv-cache-dtype: i8, gpu-headroom-mib: 96`, and `override-chat-template` naming `deploy/chat-templates/unlimited-ocr-parser.jinja` (`/chat-templates/unlimited-ocr-parser.jinja` in the compose files' container) |
|
||||
| Krea 2 Turbo and Raw, FLUX.3 [klein] and its base, Stable Diffusion XL | `tp: 1` |
|
||||
| LTX-2.5 distilled and base | `tp: 1, vision-tower-placement: ram` |
|
||||
| EmbeddingGemma 2 | `tp: 1, max-num-seqs: 64, max-num-batched-tokens: 8192` |
|
||||
| Qwen3-ASR 1.7B | `tp: 1, max-num-seqs: 16` |
|
||||
|
||||
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
|
||||
The 27B in IQ8R and IQR-V4, the 35B-A3B, MiniCPM5 and the Flash-Next bf16 reference run at up to
|
||||
32 sequences a step. The other Flash-Next rows and the 27B in bf16 keep 8, the one-card Flash-Next
|
||||
row 4: 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
|
||||
On one card a Flash-Next prefill step copies every pooled expert across the link once, so a
|
||||
4096-token step shares that copy among twice the tokens of a 2048-token one (26K-token prompts:
|
||||
2545 against 1413 tok/s); the checkpoint interval matches the step because a prefill chunk never
|
||||
crosses a checkpoint. At 4 sequences that row's cache holds 301K tokens. The Flash-Next bf16 row
|
||||
is a reference to calibrate and compare against, a step taking tens of seconds whatever its size;
|
||||
its 32K of context keeps QSA's score plane for a 32K-token step at 1 GiB.
|
||||
|
||||
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
|
||||
`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` with `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
|
||||
Four ranks is a capacity configuration: its per-step rate against `tp: 2` on the same cards has
|
||||
not been measured, and its tiering keys 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
|
||||
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
|
||||
`host-pool-mib` is what a model pins for its weights in all, each rank an equal share: the
|
||||
four-rank row pins 48 GiB of RAM (12 GiB a rank) 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).
|
||||
`ttm.pages_limit` does not count. A 64 GiB machine serves the one-card Flash-Next row alone, with
|
||||
`prefix-cache-mib: 4096`, at about 49 GiB pinned ([`docs/GUIDE.md`](docs/GUIDE.md) §7). In
|
||||
`tp1.yaml` its entry carries `prefix-cache-mib: 1024` so its host pins fit such a host beside the
|
||||
8 GiB the fleet keeps free; there it is unloaded when another model loads, and on a 61 GB host it
|
||||
answered its next request after 17 to 19 s, loaded from its container again.
|
||||
|
||||
Add `--api-key KEY` to require `Authorization: Bearer KEY` (or `X-Api-Key: KEY`). `--debug-graph`
|
||||
The Gemma 4 rows sample as the checkpoint's `generation_config` states, and a request switches
|
||||
thinking (`chat_template_kwargs`). `vision-tower-placement: ram` keeps the vision tower in host
|
||||
memory, so its VRAM goes to the KV cache. The 31B takes its full 262,144-token context at
|
||||
`max-model-len: 262144, max-num-seqs: 2`. The 12B keeps a bf16 cache because an 8-bit one costs it
|
||||
more than it saves; on Bolt-E4B an E4M3 cache cost 9x the KL and the int8 cache is unmeasured. The
|
||||
Bolt-E4B row serves without speculation because the published containers' drafters are block FP8.
|
||||
|
||||
EmbeddingGemma 2 takes an input in one step, so its `max-num-batched-tokens` is the longest input
|
||||
as well as the batch. A live Qwen3-ASR session holds one sequence, so its `max-num-seqs` is the
|
||||
most sessions served at once. On one card LTX-2.5's adapter slots fit at `max-lora-rank: 16,
|
||||
max-loras: 1` (433 MiB).
|
||||
|
||||
In a file of several models, Qwen-Image's grant counts two sequences of `max-model-len` tokens of
|
||||
cache, which at the model's own 33600 tokens is 55.8 GiB on one card and 32.6 GiB a card on two,
|
||||
more than the cards. `tp1.yaml` sets `max-model-len: 8192` (it needs 29.7 GiB; pictures up to
|
||||
about 1.9 megapixels, 1024x1024 being 4096 tokens) and `tp2.yaml` `20480` (25.4 GiB a card; the
|
||||
default 2048x2048 is 16384 tokens). Alone in a file it loads at its own length, its cache taking
|
||||
what the cards have left. It sizes its buffers itself and warns that it does not take
|
||||
`image-gen-max-pixels` or `image-gen-max-refs`.
|
||||
|
||||
Add `server.api-key: KEY` (or `server.api-key-env: VAR`, which reads it from the environment) to
|
||||
require `Authorization: Bearer KEY` (or `X-Api-Key: KEY`). `debug-graph: true` on the model
|
||||
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}'
|
||||
-d '{"model":"minicpm5-2b-iq8r","messages":[{"role":"user","content":"hi"}],"max_tokens":50}'
|
||||
```
|
||||
|
||||
An image model answers OpenAI's images API instead, with base64 pictures:
|
||||
@@ -277,6 +366,8 @@ budgets, long context, speculative decoding and operating a server.
|
||||
`data/recipes/` names. Download checkpoints with `scripts/hfget.sh <org/repo> <dir>`.
|
||||
|
||||
```sh
|
||||
# Spark X2.6 uses the checkpoint's BF16 weights, tokenizer and chat template; no recipe required.
|
||||
build/bin/rad-convert /srv/models/hf/XHToken-Spark-X2.6-4B -o spark-x2.6-4b-bf16.rad --max-ctx 4096
|
||||
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
|
||||
@@ -292,9 +383,17 @@ build/bin/rad-convert /srv/models/hf/google/gemma-4-31B-it -o gemma4-31b-dense-q
|
||||
--recipe data/recipes/gemma4-31b-dense-bf16-q8-df.recipe \
|
||||
--set quantization_config.quant_method=compressed-tensors \
|
||||
--draft-model /srv/models/hf/z-lab/gemma-4-31B-it-DFlash
|
||||
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
|
||||
# Meta's Muse Glimmer 30B, as it ships (bf16), with an int4 trunk and int8 attention values, or
|
||||
# with an IQ8R trunk and an int8 head
|
||||
build/bin/rad-convert /srv/models/hf/meta-models/Muse-Glimmer-30B -o muse-glimmer-30b-bf16.rad \
|
||||
--recipe data/recipes/museglimmer-30b-bf16.recipe
|
||||
build/bin/rad-convert /srv/models/hf/meta-models/Muse-Glimmer-30B -o muse-glimmer-30b-w4a8.rad \
|
||||
--recipe data/recipes/museglimmer-30b-w4a8.recipe \
|
||||
--set quantization_config.quant_method=compressed-tensors
|
||||
build/bin/rad-convert /srv/models/hf/meta-models/Muse-Glimmer-30B -o muse-glimmer-30b-iq8r-dflash.rad \
|
||||
--draft-model /srv/models/hf/meta-models/Muse-Glimmer-30B-assistant \
|
||||
--recipe data/recipes/museglimmer-30b-iq8r.recipe \
|
||||
--set quantization_config.quant_method=compressed-tensors
|
||||
build/bin/rad-convert /srv/models/hf/ukisai/Swift-1.5-Qwen3.8-27b-W4A16-AWQ -o swift15-27b-w4a16.rad \
|
||||
--recipe data/recipes/q38-27b-w4a16.recipe
|
||||
# Any single-file SDXL checkpoint (SDXL 1.0, Illustrious, NoobAI, Pony, a civitai finetune), with
|
||||
@@ -306,15 +405,20 @@ build/bin/rad-convert /srv/models/hf/OnomaAIResearch/Illustrious-XL-v2.0/Illustr
|
||||
|
||||
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), written at its own numbers when the kernels read them in another spelling (an int4
|
||||
W4A16 release, compressed-tensors' AWQ and GPTQ or AutoRound's, on the 4-bit GEMMs with
|
||||
`data/recipes/q38-27b-w4a16.recipe`), and converted from its exact dequantisation when no kernel
|
||||
reads it: NVFP4 (compressed-tensors' and NVIDIA ModelOpt's) to the MXFP4 kernels, an AutoRound
|
||||
Flash-Next's int4 block projections to int8. [docs/GUIDE.md](docs/GUIDE.md) names the recipes of record
|
||||
own precision needs no container: its directory is the entry's `model`
|
||||
(`model: /srv/models/hf/Qwen/Qwen3.8-27B`). A release someone else quantised to an integer grid is
|
||||
written at its own numbers where the kernels read them (an int4 W4A16 release, compressed-tensors'
|
||||
AWQ and GPTQ or AutoRound's, on the 4-bit GEMMs with `data/recipes/q38-27b-w4a16.recipe`). Block
|
||||
FP8, MXFP4, NVFP4 and ParoQuant releases are not served: convert the model's bf16 checkpoint with
|
||||
an int8 recipe. [docs/GUIDE.md](docs/GUIDE.md) names the recipes of record
|
||||
with their `rad-convert` commands.
|
||||
|
||||
Spark X2.6 runs BF16 at `tp: 1`, `2`, `3` or `4` -- and `8`, the worlds libr4d has an exact
|
||||
all-reduce for -- without a drafter or quantisation recipe. Its checkpoint's chat template enables
|
||||
thinking by default; replies return reasoning in `reasoning_content`. Set
|
||||
`chat_template_kwargs.enable_thinking` to `false` for a non-thinking request. Tool calls use the
|
||||
checkpoint's tagged format and are returned as OpenAI `tool_calls`.
|
||||
|
||||
## Test
|
||||
|
||||
```sh
|
||||
@@ -333,6 +437,7 @@ ctest --test-dir build -L oot # rebuilds every bundled plugin out o
|
||||
|---|---|
|
||||
| [`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/DIAGNOSE.md`](docs/DIAGNOSE.md) | `diagnose`: the engine measures itself, and what makes a run a measurement |
|
||||
| [`docs/DOCKER.md`](docs/DOCKER.md) | the image and the compose files |
|
||||
| [`docs/PREPARING_YOUR_RIG.md`](docs/PREPARING_YOUR_RIG.md) | a two-R9700 machine from firmware setup to a serving model |
|
||||
| [`docs/PLUGIN.md`](docs/PLUGIN.md) | writing a kernel library, architecture or quantiser plugin, including one for another AMD card |
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+50
-5
@@ -19,7 +19,7 @@ extern "C" {
|
||||
* version is refused at load with both versions printed. Each also exports the layout's fingerprint
|
||||
* (rad_abi_layout.h), so two layouts given one number are refused as well. 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 32u
|
||||
#define RAD_ABI_VERSION 44u
|
||||
|
||||
/* ================================================================== plugin identity */
|
||||
/* One value per plugin, not flags (QUANT is 3). RAD_PLUGIN_QUANT is a quantiser plugin:
|
||||
@@ -60,6 +60,16 @@ typedef struct RadArgs {
|
||||
void* instance; /* whatever init() returned for this resolved instance */
|
||||
int rank; /* tensor-parallel rank and world size, for collectives */
|
||||
int world_size;
|
||||
/* ABI 35: host-side maximum KV length represented by this exact launch operand (a seqused
|
||||
* span or a supported one-sequence prefill boundary), or -1 when it cannot be proven. In a
|
||||
* decode, verify or draft pass it is instead the step's context bound plus its longest query,
|
||||
* which the recorded pass's key holds. Plugins
|
||||
* must not infer it from a device pointer or synchronously read device memory to get it. */
|
||||
int32_t kv_used_max_h;
|
||||
/* The current rank's WGP count (HIP multiProcessorCount on RDNA); lets split launchers use
|
||||
* exactly the same per-device occupancy as architecture pass-key callbacks without querying
|
||||
* the process-global current device on the hot path. */
|
||||
int32_t wgp_count;
|
||||
} RadArgs;
|
||||
|
||||
/* Read a parameter by key. Inline definitions, because a plugin links only the ABI headers and
|
||||
@@ -152,7 +162,8 @@ typedef int (*RadLayoutFn)(const RadParam* p, int n_p, int operand, const RadEnc
|
||||
|
||||
/* 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. */
|
||||
* so it has to keep pace with the disk. The planes are read only: the loader may hand them
|
||||
* straight out of its read buffer, which the copies for other ranks read at the same time. */
|
||||
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);
|
||||
@@ -465,15 +476,20 @@ typedef struct RadKernelInfo {
|
||||
* 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.
|
||||
* fusion. Non-null also counts in rad-kbench's fusion-claim column. */
|
||||
RadFuseFn replaces;
|
||||
/* Flags describing runtime behavior relevant to core safety decisions. Zero means none.
|
||||
*
|
||||
* 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;
|
||||
uint64_t capabilities;
|
||||
} RadKernelInfo;
|
||||
|
||||
/* This row's launch grid can depend on live seqused during prefill. */
|
||||
#define RAD_KERNEL_CAP_DYNAMIC_PREFILL_SPLIT (1ull << 0)
|
||||
|
||||
/* ================================================================== 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
|
||||
@@ -500,6 +516,15 @@ const RadKernelInfo* rad_kernel_at(int i);
|
||||
typedef int (*RadPluginOpenFn) (void);
|
||||
typedef void (*RadPluginCloseFn)(void);
|
||||
|
||||
/* Optional, symbol `rad_plugin_freed`. The core has freed the device memory [base, base + bytes)
|
||||
* and nothing launched against it runs any more. A kernel library that keeps state keyed by an
|
||||
* operand's address (a counter block per output buffer, made at the first launch and replayed by
|
||||
* recorded passes) drops what it keeps for addresses inside the range. A process serving several
|
||||
* models frees an engine's memory when it unloads the model, so state kept past that would pile
|
||||
* up with every load. Called from the freeing thread, any number of times, possibly for ranges the
|
||||
* plugin never saw. */
|
||||
typedef void (*RadPluginFreedFn)(const void* base, int64_t bytes);
|
||||
|
||||
/* 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
|
||||
@@ -519,7 +544,17 @@ typedef int (*RadKernelConcurrentFn)(int i);
|
||||
* do, adds exactly once. The record is RAD_CHAIN_REC_BYTES at byte RAD_CHAIN_KARG_OFF of the
|
||||
* kernel's argument segment: { magic, target, ctr, check }, with check = magic ^ target ^ ctr ^
|
||||
* RAD_CHAIN_CHECK. A record whose magic or check does not match means: run without waiting and do
|
||||
* not add. Without the symbol, or with 0, the engine never asks. Symbol name: `rad_kernel_chain`. */
|
||||
* not add. Without the symbol, or with 0, the engine never asks.
|
||||
*
|
||||
* 2 instead of 1 adds a second promise: the chained form's own acquire covers everything it reads
|
||||
* behind the wait, scalar loads included. A compiler's agent-scope fence invalidates the vector
|
||||
* caches only; a load every lane shares may be a scalar one, served from the scalar data cache,
|
||||
* which still holds what was there before the launch in front wrote. A form that invalidates that
|
||||
* cache behind its acquire (`s_dcache_inv`), or reads no operand through it, may say 2. Where
|
||||
* every chainable row an engine loads says 2, the engine issues a chained launch that has lost
|
||||
* its barrier bit without the packet processor's acquire as well: on an R9700 that acquire holds
|
||||
* the processor ~0.9 us a launch, and it comes too early to serve a kernel that then waits for
|
||||
* the launch in front. With 1 the packets keep it. Symbol name: `rad_kernel_chain`. */
|
||||
typedef int (*RadKernelChainFn)(int i);
|
||||
#define RAD_CHAIN_KARG_OFF 992
|
||||
#define RAD_CHAIN_REC_BYTES 32
|
||||
@@ -545,6 +580,16 @@ typedef int (*RadKernelChainFn)(int i);
|
||||
typedef int (*RadKernelCollectiveFn)(int i);
|
||||
#define RAD_LINK_ENDED 1
|
||||
|
||||
/* Optional promise about kernel `i` of rad_kernel_at: nonzero means that, gathering rows of a table
|
||||
* the engine reads in place from the container (the mapped tier, e.g. --ngram-placement disk), it
|
||||
* fetches them itself -- direct reads into a row cache of its own -- rather than by touching the
|
||||
* mapping. The engine then leaves those rows alone. Without the symbol, or with 0, the engine asks
|
||||
* the page cache for every page a host gather's rows cover before the launch, so the kernel's page
|
||||
* faults wait on reads issued together rather than one at a time (core/runtime/rowprefetch.h); for
|
||||
* a kernel that reads the file itself that would read each row twice. Symbol name:
|
||||
* `rad_kernel_fetches_rows`. */
|
||||
typedef int (*RadKernelFetchesRowsFn)(int i);
|
||||
|
||||
/* 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
|
||||
|
||||
@@ -17,7 +17,7 @@ ABI_FIELD(RadArchProbe, gen_patches)
|
||||
ABI_FIELD(RadArchProbe, gen_audio)
|
||||
ABI_FIELD(RadArchProbe, gen_ctx)
|
||||
ABI_FIELD(RadArchProbe, gen_video)
|
||||
ABI_FIELD(RadArchProbe, kv_quant_ok)
|
||||
ABI_FIELD(RadArchProbe, kv_fp8_ok)
|
||||
ABI_FIELD(RadArchProbe, chain_pays)
|
||||
ABI_FIELD(RadArchProbe, kv_stream_ok)
|
||||
ABI_FIELD(RadArchProbe, control_vector_ok)
|
||||
@@ -26,6 +26,8 @@ ABI_FIELD(RadArchProbe, state_f16_ok)
|
||||
ABI_FIELD(RadArchProbe, tree_pays)
|
||||
ABI_FIELD(RadArchProbe, gen_max_pixels)
|
||||
ABI_FIELD(RadArchProbe, gen_max_refs)
|
||||
ABI_FIELD(RadArchProbe, gen_shape)
|
||||
ABI_FIELD(RadArchProbe, ckpt_snap_ok)
|
||||
ABI_STRUCT(RadArgs)
|
||||
ABI_FIELD(RadArgs, t)
|
||||
ABI_FIELD(RadArgs, n_t)
|
||||
@@ -36,6 +38,8 @@ ABI_FIELD(RadArgs, scratch_bytes)
|
||||
ABI_FIELD(RadArgs, instance)
|
||||
ABI_FIELD(RadArgs, rank)
|
||||
ABI_FIELD(RadArgs, world_size)
|
||||
ABI_FIELD(RadArgs, kv_used_max_h)
|
||||
ABI_FIELD(RadArgs, wgp_count)
|
||||
ABI_STRUCT(RadBatch)
|
||||
ABI_FIELD(RadBatch, phase)
|
||||
ABI_FIELD(RadBatch, step)
|
||||
@@ -93,6 +97,18 @@ ABI_FIELD(RadBatch, plugin_words)
|
||||
ABI_FIELD(RadBatch, plugin_cu)
|
||||
ABI_FIELD(RadBatch, plugin_words_h)
|
||||
ABI_FIELD(RadBatch, plugin_cu_h)
|
||||
ABI_FIELD(RadBatch, sgen_b)
|
||||
ABI_FIELD(RadBatch, kv_used_max_h)
|
||||
ABI_FIELD(RadBatch, positions_h)
|
||||
ABI_FIELD(RadBatch, n_bidi)
|
||||
ABI_FIELD(RadBatch, bidi_row)
|
||||
ABI_FIELD(RadBatch, bidi_n)
|
||||
ABI_FIELD(RadBatch, bidi_seq)
|
||||
ABI_FIELD(RadBatch, bidi_used)
|
||||
ABI_FIELD(RadBatch, anchor_rows)
|
||||
ABI_FIELD(RadBatch, ckpt_cut)
|
||||
ABI_FIELD(RadBatch, ckpt_cu)
|
||||
ABI_FIELD(RadBatch, vl_mask)
|
||||
ABI_STRUCT(RadBufDecl)
|
||||
ABI_FIELD(RadBufDecl, dtype)
|
||||
ABI_FIELD(RadBufDecl, rank)
|
||||
@@ -118,8 +134,6 @@ ABI_FIELD(RadBuildCtx, max_enc_patches)
|
||||
ABI_FIELD(RadBuildCtx, max_out_rows)
|
||||
ABI_FIELD(RadBuildCtx, max_audio_frames)
|
||||
ABI_FIELD(RadBuildCtx, max_mixed_tok)
|
||||
ABI_FIELD(RadBuildCtx, kv_quant)
|
||||
ABI_FIELD(RadBuildCtx, attn_prefill_fp8)
|
||||
ABI_FIELD(RadBuildCtx, kv_resident_blocks)
|
||||
ABI_FIELD(RadBuildCtx, kv_stream_ok)
|
||||
ABI_FIELD(RadBuildCtx, cvec)
|
||||
@@ -134,6 +148,12 @@ ABI_FIELD(RadBuildCtx, calib_layer_hi)
|
||||
ABI_FIELD(RadBuildCtx, calib_tokens)
|
||||
ABI_FIELD(RadBuildCtx, gen_max_pixels)
|
||||
ABI_FIELD(RadBuildCtx, gen_max_refs)
|
||||
ABI_FIELD(RadBuildCtx, expert_file_tier)
|
||||
ABI_FIELD(RadBuildCtx, slot_base)
|
||||
ABI_FIELD(RadBuildCtx, span_pass_step)
|
||||
ABI_FIELD(RadBuildCtx, draft_head_off)
|
||||
ABI_FIELD(RadBuildCtx, expert_split)
|
||||
ABI_FIELD(RadBuildCtx, dspark_walk)
|
||||
ABI_STRUCT(RadAudioGenBatch)
|
||||
ABI_FIELD(RadAudioGenBatch, n_lane)
|
||||
ABI_FIELD(RadAudioGenBatch, lane)
|
||||
@@ -180,6 +200,7 @@ ABI_FIELD(RadAudioGenBatch, ref_cu)
|
||||
ABI_FIELD(RadAudioGenBatch, ref_cu_h)
|
||||
ABI_FIELD(RadAudioGenBatch, ref_frame)
|
||||
ABI_FIELD(RadAudioGenBatch, ref_frame_h)
|
||||
ABI_FIELD(RadAudioGenBatch, prompt_cu_h)
|
||||
ABI_STRUCT(RadAudioGenDecl)
|
||||
ABI_FIELD(RadAudioGenDecl, name)
|
||||
ABI_FIELD(RadAudioGenDecl, tmpl)
|
||||
@@ -220,6 +241,8 @@ ABI_FIELD(RadAudioGenDecl, ref_rate)
|
||||
ABI_FIELD(RadAudioGenDecl, ref_hop)
|
||||
ABI_FIELD(RadAudioGenDecl, ref_max_samples)
|
||||
ABI_FIELD(RadAudioGenDecl, ref_max)
|
||||
ABI_FIELD(RadAudioGenDecl, tmpl_ref_instruct)
|
||||
ABI_FIELD(RadAudioGenDecl, neg_tmpl_ref)
|
||||
ABI_STRUCT(RadControlVector)
|
||||
ABI_FIELD(RadControlVector, dir)
|
||||
ABI_FIELD(RadControlVector, scales)
|
||||
@@ -266,6 +289,9 @@ ABI_FIELD(RadChatFormat, object_string_close)
|
||||
ABI_FIELD(RadChatFormat, object_bare_keys)
|
||||
ABI_FIELD(RadChatFormat, reasoning_anywhere)
|
||||
ABI_FIELD(RadChatFormat, arg_json_value_prefix)
|
||||
ABI_FIELD(RadChatFormat, content_open)
|
||||
ABI_FIELD(RadChatFormat, object_args_key)
|
||||
ABI_FIELD(RadChatFormat, message_open)
|
||||
ABI_STRUCT(RadConstraint)
|
||||
ABI_FIELD(RadConstraint, key)
|
||||
ABI_FIELD(RadConstraint, op)
|
||||
@@ -311,6 +337,8 @@ ABI_FIELD(RadEncoderDecl, max_patches)
|
||||
ABI_FIELD(RadEncoderDecl, n_embd)
|
||||
ABI_FIELD(RadEncoderDecl, out)
|
||||
ABI_FIELD(RadEncoderDecl, one_grid)
|
||||
ABI_FIELD(RadEncoderDecl, bidirectional)
|
||||
ABI_FIELD(RadEncoderDecl, span_rows)
|
||||
ABI_STRUCT(RadEncoding)
|
||||
ABI_FIELD(RadEncoding, scheme)
|
||||
ABI_FIELD(RadEncoding, transform)
|
||||
@@ -432,6 +460,8 @@ ABI_FIELD(RadGenBatch, size_px)
|
||||
ABI_FIELD(RadGenBatch, entry_h)
|
||||
ABI_FIELD(RadGenBatch, tokens_h)
|
||||
ABI_FIELD(RadGenBatch, cond_opts)
|
||||
ABI_FIELD(RadGenBatch, ref_log_bias)
|
||||
ABI_FIELD(RadGenBatch, mode_sigma)
|
||||
ABI_STRUCT(RadGeneratorDecl)
|
||||
ABI_FIELD(RadGeneratorDecl, name)
|
||||
ABI_FIELD(RadGeneratorDecl, layout)
|
||||
@@ -500,6 +530,7 @@ ABI_FIELD(RadKVGroupBatch, state_index_pitch)
|
||||
ABI_FIELD(RadKVGroupBatch, block_size)
|
||||
ABI_FIELD(RadKVGroupBatch, max_blocks)
|
||||
ABI_FIELD(RadKVGroupBatch, stream)
|
||||
ABI_FIELD(RadKVGroupBatch, seqused_h)
|
||||
ABI_STRUCT(RadKVGroupDecl)
|
||||
ABI_FIELD(RadKVGroupDecl, kind)
|
||||
ABI_FIELD(RadKVGroupDecl, dtype)
|
||||
@@ -541,6 +572,7 @@ ABI_FIELD(RadKernelInfo, relayout)
|
||||
ABI_FIELD(RadKernelInfo, opd_shape)
|
||||
ABI_FIELD(RadKernelInfo, unrelayout)
|
||||
ABI_FIELD(RadKernelInfo, replaces)
|
||||
ABI_FIELD(RadKernelInfo, capabilities)
|
||||
ABI_STRUCT(RadLayout)
|
||||
ABI_FIELD(RadLayout, tag)
|
||||
ABI_FIELD(RadLayout, dtype)
|
||||
@@ -699,6 +731,44 @@ ABI_FIELD(RadSampleParams, hist_len)
|
||||
ABI_FIELD(RadSampleParams, mask_row)
|
||||
ABI_FIELD(RadSampleParams, flags)
|
||||
ABI_FIELD(RadSampleParams, dry_rep_limit)
|
||||
ABI_STRUCT(RadShapeGenBatch)
|
||||
ABI_FIELD(RadShapeGenBatch, lane)
|
||||
ABI_FIELD(RadShapeGenBatch, patches)
|
||||
ABI_FIELD(RadShapeGenBatch, step)
|
||||
ABI_FIELD(RadShapeGenBatch, n_steps)
|
||||
ABI_FIELD(RadShapeGenBatch, sigma)
|
||||
ABI_FIELD(RadShapeGenBatch, sigma_next)
|
||||
ABI_FIELD(RadShapeGenBatch, cfg)
|
||||
ABI_FIELD(RadShapeGenBatch, pair)
|
||||
ABI_FIELD(RadShapeGenBatch, lanes)
|
||||
ABI_FIELD(RadShapeGenBatch, flags)
|
||||
ABI_FIELD(RadShapeGenBatch, seed)
|
||||
ABI_FIELD(RadShapeGenBatch, lat_cu)
|
||||
ABI_FIELD(RadShapeGenBatch, n_query)
|
||||
ABI_FIELD(RadShapeGenBatch, query)
|
||||
ABI_FIELD(RadShapeGenBatch, query_cu)
|
||||
ABI_STRUCT(RadShapeGenDecl)
|
||||
ABI_FIELD(RadShapeGenDecl, name)
|
||||
ABI_FIELD(RadShapeGenDecl, canvas)
|
||||
ABI_FIELD(RadShapeGenDecl, border_ratio)
|
||||
ABI_FIELD(RadShapeGenDecl, enc_size)
|
||||
ABI_FIELD(RadShapeGenDecl, enc_patch)
|
||||
ABI_FIELD(RadShapeGenDecl, pix_mean)
|
||||
ABI_FIELD(RadShapeGenDecl, pix_std)
|
||||
ABI_FIELD(RadShapeGenDecl, latent_rows)
|
||||
ABI_FIELD(RadShapeGenDecl, latent_channels)
|
||||
ABI_FIELD(RadShapeGenDecl, step_rows)
|
||||
ABI_FIELD(RadShapeGenDecl, default_steps)
|
||||
ABI_FIELD(RadShapeGenDecl, max_steps)
|
||||
ABI_FIELD(RadShapeGenDecl, default_guidance)
|
||||
ABI_FIELD(RadShapeGenDecl, bounds)
|
||||
ABI_FIELD(RadShapeGenDecl, level)
|
||||
ABI_FIELD(RadShapeGenDecl, default_resolution)
|
||||
ABI_FIELD(RadShapeGenDecl, min_resolution)
|
||||
ABI_FIELD(RadShapeGenDecl, max_resolution)
|
||||
ABI_FIELD(RadShapeGenDecl, max_lanes)
|
||||
ABI_FIELD(RadShapeGenDecl, max_query)
|
||||
ABI_FIELD(RadShapeGenDecl, field_out)
|
||||
ABI_STRUCT(RadTensor)
|
||||
ABI_FIELD(RadTensor, data)
|
||||
ABI_FIELD(RadTensor, dtype)
|
||||
@@ -892,3 +962,7 @@ ABI_FIELD(RadMtpCoupleState, x)
|
||||
ABI_FIELD(RadMtpCoupleState, count)
|
||||
ABI_FIELD(RadMtpCoupleState, ids)
|
||||
ABI_FIELD(RadMtpCoupleState, q)
|
||||
ABI_FIELD(RadMtpCoupleState, nkids)
|
||||
ABI_FIELD(RadMtpCoupleState, scheme)
|
||||
ABI_FIELD(RadMtpCoupleState, blk)
|
||||
ABI_FIELD(RadMtpCoupleState, pad_)
|
||||
+321
-88
@@ -56,35 +56,27 @@ 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 */
|
||||
/* RadBuildCtx::kv_quant. A layout groups each head's dims by 32 with an f16 scale per group, the
|
||||
* group's absmax over the largest code. A token's row in a head, at head_dim HD (a multiple of 32):
|
||||
/* A paged cache group's dtype says how a token's row in a head is laid out, at head_dim HD:
|
||||
*
|
||||
* RAD_KVQ_V4 (fp8_v4), 25 * HD / 16 bytes:
|
||||
* [0, HD) K, E4M3 as the fp8 cache stores it
|
||||
* [HD, 3HD/2) V's int4 codes, dim d in the nibble at bit 4 * (d % 2) of byte d / 2
|
||||
* [3HD/2, 25HD/16) V's scales (absmax / 7)
|
||||
* RAD_KVQ_K6V4 (k6_v4), 22 * HD / 16 bytes:
|
||||
* [0, HD/2) K's low four bits, as V's codes above
|
||||
* [HD/2, 3HD/4) K's high two bits, a 4-byte word per 16 dims whose byte j holds dims 2j
|
||||
* and 2j+1 in bits 0-3 and dims 8+2j and 9+2j in bits 4-7
|
||||
* [3HD/4, 5HD/4) V's int4 codes
|
||||
* [5HD/4, 21HD/16) K's scales (absmax / 31)
|
||||
* [21HD/16, 22HD/16) V's scales (absmax / 7)
|
||||
*
|
||||
* Codes are two's complement (int4 -7..7, int6 -31..31). The group is declared at RAD_F8E4M3 with
|
||||
* head_dim the row's bytes / 2 so the core sizes pages from it; only the layout's kernels read
|
||||
* it. */
|
||||
enum {
|
||||
RAD_KVQ_NONE = 0,
|
||||
RAD_KVQ_V4 = 1,
|
||||
RAD_KVQ_K6V4 = 2
|
||||
};
|
||||
* RAD_BF16, 4 * HD bytes: K then V, as the model computes them.
|
||||
* RAD_I8, 2 * HD + 4 bytes: K and V as int8 codes with one f16 scale each per (token, head):
|
||||
* [0, HD) K's int8 codes (two's complement, -127..127)
|
||||
* [HD, 2HD) V's int8 codes
|
||||
* [2HD, 2HD + 2) K's scale (the head's absmax / 127)
|
||||
* [2HD + 2, 2HD + 4) V's scale (absmax / 127)
|
||||
* The plugin declares HD; the core adds the scales' bytes (rad_kv_row_elems). */
|
||||
|
||||
/* The products of the prefill attention a deployment accepts in e4m3 (RadBuildCtx::
|
||||
* attn_prefill_fp8, `attn_paged`'s `prefill_fp8`): bits, so both is 3. */
|
||||
/* Elements of a token's row in one head of a paged group declared at `dtype` and `head_dim`: K
|
||||
* then V, and under the int8 cache the two f16 scales after them. */
|
||||
static inline int64_t rad_kv_row_elems(uint32_t dtype, int64_t head_dim) {
|
||||
return 2 * head_dim + (dtype == RAD_I8 ? 4 : 0);
|
||||
}
|
||||
|
||||
/* RadArchProbe::chain_pays. */
|
||||
enum {
|
||||
RAD_ATTN_FP8_QK = 1, /* Q.K^T, the query rounded to e4m3 after the softmax scale */
|
||||
RAD_ATTN_FP8_PV = 2 /* P.V, the probabilities rounded to e4m3 */
|
||||
RAD_CHAIN_NONE = 0,
|
||||
RAD_CHAIN_SPEC = 1, /* with a drafter decoding speculatively */
|
||||
RAD_CHAIN_ALWAYS = 2 /* with or without one */
|
||||
};
|
||||
|
||||
typedef struct RadBuildCtx {
|
||||
@@ -111,17 +103,16 @@ typedef struct RadBuildCtx {
|
||||
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.
|
||||
/* The KV cache dtype, a deployment choice rather than a property of the checkpoint.
|
||||
*
|
||||
* 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. `kv_quant` below narrows the trunk's attention cache further.
|
||||
* architecture in this tree. RAD_I8 is the other value every paged attention serves, the
|
||||
* int8 cache above: the attention kernels band on it and the store writes each token's codes
|
||||
* and scales. RAD_F8E4M3 reaches only a plugin whose probe sets RadArchProbe::kv_fp8_ok.
|
||||
*
|
||||
* 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 kv_dtype; /* RAD_DT_INVALID = the plugin's default (bf16); RAD_I8; RAD_F8E4M3 */
|
||||
int is_draft; /* this builder scope is a drafter (spec §10) */
|
||||
const char* scope; /* "", "draft", "vision", "audio" -- prefixes declared names */
|
||||
|
||||
@@ -172,25 +163,6 @@ typedef struct RadBuildCtx {
|
||||
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
|
||||
int64_t max_mixed_tok;
|
||||
|
||||
/* A narrower layout of the trunk's attention cache under kv_dtype RAD_F8E4M3, from
|
||||
* --kv-cache-dtype fp8_v4 or k6_v4: a RAD_KVQ_* (below). The engine sets it only for a plugin
|
||||
* whose probe has the layout's bit in RadArchProbe::kv_quant_ok and refuses the flag
|
||||
* otherwise, so no plugin sees it that would store plain E4M3 instead. A drafter's cache stays
|
||||
* E4M3.
|
||||
*
|
||||
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
|
||||
int kv_quant;
|
||||
|
||||
/* ---- appended in ABI 26 (fp8 prefill attention) */
|
||||
/* RAD_ATTN_FP8_* bits from --attn-prefill-fp8: the attention products the deployment accepts
|
||||
* in e4m3 rather than exactly. 0 (the zero-initialised default) is exact. A plugin passes a
|
||||
* nonzero value on as `attn_paged`'s `prefill_fp8` (docs/OPS.md) and omits the parameter at
|
||||
* 0, so an exact declare is unchanged. The engine refuses to start when no resolved kernel
|
||||
* takes it, so a plugin that ignores the field is refused rather than silently exact.
|
||||
*
|
||||
* Zero-defaulted and in the padding after kv_quant, so no other field moves. */
|
||||
int attn_prefill_fp8;
|
||||
|
||||
/* ---- appended in ABI 30 (KV streaming) */
|
||||
/* --kv-resident in tokens, 0 when nothing streams: the ring a streamed group carves is this in
|
||||
* whole blocks, raised to the engine's floors and clamped to the context. A plugin states it as
|
||||
@@ -295,8 +267,64 @@ typedef struct RadBuildCtx {
|
||||
* fixed buffers ignores them, and the core says so at startup. */
|
||||
int64_t gen_max_pixels;
|
||||
int64_t gen_max_refs;
|
||||
|
||||
/* ---- appended in ABI 37 (where a routed expert may live) */
|
||||
/* --weights-disk-tier: nonzero when weights may stay in the container. An expert read from the
|
||||
* drive has to be stored whole, so a plugin that can lay its routed experts out either way
|
||||
* keeps them whole for this; 0 leaves it free to split them across the ranks by width. */
|
||||
int expert_file_tier;
|
||||
|
||||
/* ---- appended in ABI 38 (several engines in one process) */
|
||||
/* The first of this engine's slots. Each engine in the process holds a contiguous block of
|
||||
* slots, one per rank, so an instance's slot, `slot_base + rank` (rad_build_slot), is unique
|
||||
* among the ranks of every engine alive, where `rank` is unique only within one engine. A
|
||||
* plugin keeps per-instance state (handles, geometry, its step's view of the model) indexed by
|
||||
* the slot, and reads it back in step() with rad_slot(). Zero, the default, makes the slot the
|
||||
* rank: one engine in a process, or a test driving a plugin alone. Two engines may serve the
|
||||
* same plugin at once only when it says so (rad_arch_multi_instance). */
|
||||
int slot_base;
|
||||
|
||||
/* ---- appended in ABI 42 (--prefill-span-pass step) */
|
||||
/* Nonzero: where the plugin runs a step wider than max_mixed_tok serially (it pipelines no
|
||||
* part of it), its routed block may take the whole step in one pass rather than one pass a
|
||||
* checkpoint interval, and size the planes that hold a row per (token, expert slot) for
|
||||
* max_tok rows. 0, the zero-initialised default, keeps the interval-tall passes. A plugin
|
||||
* without such a pass ignores it. */
|
||||
int span_pass_step;
|
||||
/* ---- appended in ABI 44 (prompt-lookup head-off, expert split, DSpark walk) */
|
||||
/* Nonzero from --spec-ngram: the deployment drafts by prompt lookup only, in the core, and
|
||||
* verifies up to `max_spec` drafts a step. The plugin declares no draft head, so a head the
|
||||
* container carries stays off the card, but sizes every verify buffer, state ring and kernel
|
||||
* band for `max_spec` as at any speculative serve. rad_ctx_draft_head() below is the test.
|
||||
* The engine refuses to start when a head is declared anyway, rather than load one it was
|
||||
* told to leave out.
|
||||
*
|
||||
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
|
||||
int draft_head_off;
|
||||
/* --expert-split: the routed experts a layer each rank holds, comma-separated counts in rank
|
||||
* order ("104,88,104,88"), for a plugin that gives each rank whole experts
|
||||
* (arch/common/rad_expert_split.h). Null or empty: the even split. A plugin without expert
|
||||
* parallelism ignores it. */
|
||||
const char* expert_split;
|
||||
/* --dspark-walk: nonzero asks a DSpark drafter to walk its Markov tables over the whole
|
||||
* vocabulary, as the reference implementation does, instead of re-ranking the head's top
|
||||
* candidates. The trunk verifies every draft, so the output does not depend on it. 0, the
|
||||
* zero-initialised default, keeps the re-rank. */
|
||||
int dspark_walk;
|
||||
} RadBuildCtx;
|
||||
|
||||
/* The most instances (engine ranks) one process holds at once; every slot is below it. */
|
||||
#define RAD_MAX_SLOTS 32
|
||||
|
||||
/* The declaring instance's slot (see RadBuildCtx::slot_base). */
|
||||
static inline int rad_build_slot(const RadBuildCtx* c) { return c->slot_base + c->rank; }
|
||||
|
||||
/* Whether a declare should include the container's draft head: the deployment speculates and
|
||||
* does not draft by prompt lookup alone. */
|
||||
static inline int rad_ctx_draft_head(const RadBuildCtx* ctx) {
|
||||
return ctx && ctx->max_spec > 0 && !ctx->draft_head_off;
|
||||
}
|
||||
|
||||
/* ================================================================== control vectors */
|
||||
/* A direction per layer, in the shape llama.cpp's `--cvec-mode project` applies it:
|
||||
*
|
||||
@@ -469,7 +497,7 @@ enum {
|
||||
typedef struct RadKVGroupDecl {
|
||||
int kind; /* RAD_KV_* */
|
||||
uint32_t dtype;
|
||||
int64_t window; /* RAD_KV_WINDOW: the window; RAD_KV_RING: the ring's W; 0 otherwise */
|
||||
int64_t window; /* RAD_KV_WINDOW: the window; RAD_KV_RING: the ring's W; else 0 */
|
||||
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} */
|
||||
@@ -539,12 +567,12 @@ int rad_buf_concurrent(RadBuilder* b, rad_buf buf);
|
||||
|
||||
/* ---- appended in ABI 27 (the second lane's window) */
|
||||
/* The second lane's window: every op the architecture issues on lane 1 is declared between
|
||||
* rad_lane1_window_begin and rad_lane1_window_end. With a window a rad_buf_concurrent buffer is live
|
||||
* over the window and its own declared uses instead of the whole program, so buffers used only
|
||||
* rad_lane1_window_begin and rad_lane1_window_end. With a window a rad_buf_concurrent buffer is
|
||||
* live over the window and its own declared uses instead of the whole program, so buffers used only
|
||||
* outside the window (a drafter's, the heads') can share its bytes. The runtime holds the
|
||||
* architecture to it: an op issued on lane 1 outside the window fails the step by name, and an op
|
||||
* issued on lane 0 outside the window joins lane 1 first when lane 1 has work pending. Optional, one
|
||||
* window a program; call both at declare, in order. */
|
||||
* issued on lane 0 outside the window joins lane 1 first when lane 1 has work pending. Optional,
|
||||
* one window a program; call both at declare, in order. */
|
||||
int rad_lane1_window_begin(RadBuilder* b);
|
||||
int rad_lane1_window_end(RadBuilder* b);
|
||||
|
||||
@@ -614,7 +642,8 @@ int rad_op_declared(RadBuilder* b, const char* op);
|
||||
* 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, RAD_MAP_WNORM = 2, RAD_MAP_ROWS = 3,
|
||||
RAD_MAP_TRANSPOSE = 4, RAD_MAP_EMA = 5, RAD_MAP_TAP = 6, RAD_MAP_COLS = 7 };
|
||||
RAD_MAP_TRANSPOSE = 4, RAD_MAP_EMA = 5, RAD_MAP_TAP = 6, RAD_MAP_COLS = 7,
|
||||
RAD_MAP_MUL = 8 };
|
||||
|
||||
typedef struct RadNameMap {
|
||||
const char* declared; /* the name given to rad_decl_weight */
|
||||
@@ -675,8 +704,13 @@ typedef struct RadNameMap {
|
||||
* run on a single frame reads only its last temporal tap, so [cout, cin, kt, kh, kw] read at tap -1
|
||||
* of dimension 2 is the 2-D convolution it then is.
|
||||
*
|
||||
* TRANSPOSE, EMA, TAP and COLS are computed at convert in f32, like WNORM, and stored as the recipe
|
||||
* says. */
|
||||
* RAD_MAP_MUL is the elementwise product of src[0] and src[1], two tensors of one shape: a gain a
|
||||
* checkpoint ships as two factors that the model only ever multiplies (DeepSeek-V4.1's Engram gate,
|
||||
* q_weight * k_weight, which llama.cpp's converter folds into one engram_gate the same way). Two
|
||||
* bf16 factors multiply exactly in f32.
|
||||
*
|
||||
* TRANSPOSE, EMA, TAP, COLS and MUL are computed at convert in f32, like WNORM, and stored as the
|
||||
* recipe says. */
|
||||
|
||||
int rad_decl_name_map(RadBuilder* b, const RadNameMap* m);
|
||||
|
||||
@@ -737,16 +771,19 @@ int rad_declare_plugin_words(RadBuilder* b, int64_t max_words);
|
||||
* 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).
|
||||
* position at once (DFlash2 and other block-diffusion drafters). HISTORY runs just the serial
|
||||
* history pass (draft_pass < 0, every hidden row, n_draft_out = 0) to collect calibration
|
||||
* inputs. It is for --calib-corpus with max_spec = 0; it declares and produces no proposals.
|
||||
*
|
||||
* `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 */
|
||||
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 */
|
||||
RAD_DRAFT_HISTORY = 3, /* calibration-only serial history pass, depth zero */
|
||||
} RadDraftKind;
|
||||
|
||||
typedef struct RadDrafterDecl {
|
||||
@@ -776,7 +813,7 @@ typedef struct RadDrafterDecl {
|
||||
* 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:, :]`.
|
||||
* 0..depth-1. DSpark.
|
||||
*
|
||||
* 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.
|
||||
@@ -828,6 +865,23 @@ int rad_drafter_shared_kv(RadBuilder* b, int pos_offset);
|
||||
* the drafter's passes (the KL mode drafts nothing, so trees do not apply there). */
|
||||
int rad_drafter_tree(RadBuilder* b, rad_buf parents);
|
||||
|
||||
/* The model's routing counts live in `table`: an i32 RAD_BUF_PERSIST device buffer of at least
|
||||
* [layers, n_expert], one row per layer that reports (rad_route_report's `layer`, so a head past
|
||||
* the trunk counts) and n_expert the model's expert count. Each layer's router writes its counts
|
||||
* into its own row and the report names that row as RadRouting::expert_count; the core takes it
|
||||
* in place and copies the pass's rows to the host once, at the end of the pass. Without a table
|
||||
* the core keeps the rows itself and a report costs one copy dispatch per routed layer on the
|
||||
* compute stream, since a plugin cannot bind the core's rows as operands of a recorded pass. A
|
||||
* report naming any other buffer is still copied, into the layer's row of the table.
|
||||
*
|
||||
* A row per layer also means a consumer that reads a layer's counts later in stream order (the
|
||||
* file stager, at the layer's first expert op) reads that layer's, which one buffer shared by
|
||||
* every layer does not guarantee once a later layer's router has run.
|
||||
*
|
||||
* Called at most once. The row count is checked when a context binds, where the reporting layers
|
||||
* are known. Additive export; RAD_ABI_VERSION does not move. */
|
||||
int rad_route_table(RadBuilder* b, rad_buf table);
|
||||
|
||||
/* Whether this engine's launches chain (RadKernelChainFn, abi/rad_abi.h): the core's decision, on
|
||||
* the AQL backend only, which keeps a completion counter per queue, where the model's plugin
|
||||
* measured a gain with its speculative drafter (RadArchProbe::chain_pays) and that drafter decodes
|
||||
@@ -886,6 +940,21 @@ typedef struct RadEncoderDecl {
|
||||
* position tables or kernels are per geometry; the core ends a pass where the grid changes.
|
||||
* 0 packs segments of any grid into a pass. */
|
||||
int32_t one_grid;
|
||||
|
||||
/* ---- appended in ABI 32 (runs the language model reads both ways) */
|
||||
/* 1: the language model attends the placeholders of one picture or video frame to each other
|
||||
* both ways (Gemma 4's use_bidirectional_attention "vision"), text before and after them
|
||||
* causally. The core then ends no prefill chunk inside such a run and states each trunk pass's
|
||||
* runs (RadBatch::n_bidi). 0 for an audio encoder. */
|
||||
int32_t bidirectional;
|
||||
|
||||
/* ---- appended in ABI 44 (typed span rows) */
|
||||
/* A span the language model embeds by position type, not contiguously: `span_rows` is the
|
||||
* learned row each non-image position takes -- [4, n_embd] bf16, index 0 image_start, 1 unused
|
||||
* (the encoder's own rows), 2 image_newline, 3 image_end. DeepSeek-V4.1's span is one
|
||||
* placeholder id repeated, so the engine needs these rows to build the span's embeddings
|
||||
* (Item::types says which row a position takes). Null: the span is embedded contiguously. */
|
||||
rad_buf span_rows;
|
||||
} RadEncoderDecl;
|
||||
|
||||
int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d);
|
||||
@@ -1119,6 +1188,14 @@ int rad_lora_root(RadBuilder* b, const char* native, const char* spellings);
|
||||
int rad_lora_alias(RadBuilder* b, const char* native, const char* from, const char* to,
|
||||
int64_t from_lo, int64_t from_hi, int64_t to_lo);
|
||||
|
||||
/* Is checkpoint tensor `src` a runtime-LoRA target of this build? 1 when an adapter configured
|
||||
* for this startup targets it, 0 otherwise (no adapter, a different module, a tower, the drafter,
|
||||
* or a generator source outside a declared root). The same predicate as lora::source_targeted:
|
||||
* the leaf of a `.weight` name. A plugin asks before the weight exists, and sets a LoRA-only
|
||||
* declaration (the plain bf16 view of a rotated int8 trunk weight) only on 1. Null or an empty
|
||||
* name is 0. Additive export; RAD_ABI_VERSION does not move. */
|
||||
int rad_lora_source_targeted(RadBuilder* b, const char* src);
|
||||
|
||||
/* ================================================================== the audio generator */
|
||||
/* A program that makes audio from text: an autoregressive language model writes the piece frame by
|
||||
* frame, with classifier-free guidance (each request runs a conditional and an unconditional
|
||||
@@ -1138,8 +1215,9 @@ int rad_lora_alias(RadBuilder* b, const char* native, const char* from, const ch
|
||||
* conditions on, and runs the language model over the frame's embedding
|
||||
* (one row a branch, appended to that branch's KV). It writes `status` for
|
||||
* each lane: >= 0 a frame was made, -1 the model ended the piece instead.
|
||||
* RAD_GEN_PASS_WINDOW one denoising step of one or more windows, each a run of a request's frames
|
||||
* (two entries a window with guidance, conditional and unconditional).
|
||||
* RAD_GEN_PASS_WINDOW one denoising step of one or more windows, each a run of a request's
|
||||
* frames (two entries a window with guidance, conditional and
|
||||
* unconditional).
|
||||
* RAD_GEN_PASS_VOCODE one finished window's latents to samples, in `audio_out`, which the core
|
||||
* reads back; with `voc_chunk`, the frames [voc_frame0, voc_frame0 +
|
||||
* voc_latents) of one lane, of which the first `voc_left` are context and
|
||||
@@ -1246,13 +1324,22 @@ typedef struct RadAudioGenDecl {
|
||||
* prepare() has limited to those a caller may write), and so is the text after it. A clip is
|
||||
* mono f32 in [-1, 1] at `ref_rate`, right-padded with zeros to a whole number of `ref_hop`
|
||||
* samples, each `ref_hop` samples one frame; a request's clips hold at most `ref_max_samples`
|
||||
* samples together. NULL `tmpl_ref`: references are refused. */
|
||||
* samples together. With two branches, references require default_cfg 1 and a plain
|
||||
* neg_tmpl: guidance 1 repeats the conditional prompt and frame map in both branches.
|
||||
* Reference direction is opt-in through the templates appended below. NULL `tmpl_ref`:
|
||||
* references are refused. */
|
||||
const char* tmpl_ref;
|
||||
const char* ref_item;
|
||||
int64_t ref_rate;
|
||||
int64_t ref_hop;
|
||||
int64_t ref_max_samples;
|
||||
int32_t ref_max;
|
||||
/* ABI 40: reference-plus-instructions uses tmpl_ref_instruct ({references},
|
||||
* {instructions}, {input} once each). Its guidance baseline is neg_tmpl_ref
|
||||
* ({references}, {input}, no instructions). Both branches retain the same clips;
|
||||
* their text lengths and reference-frame maps may differ. NULL: direction refused. */
|
||||
const char* tmpl_ref_instruct;
|
||||
const char* neg_tmpl_ref;
|
||||
} RadAudioGenDecl;
|
||||
|
||||
int rad_declare_audio_generator(RadBuilder* b, const RadAudioGenDecl* d);
|
||||
@@ -1282,10 +1369,11 @@ int rad_declare_audio_generator(RadBuilder* b, const RadAudioGenDecl* d);
|
||||
* Geometry. A video of n chunks has `frames_per_chunk n + frames_tail` frames at
|
||||
* `fps_num / fps_den` a second and `latents_per_chunk n + latents_tail` latent frames, each of
|
||||
* (height / latent_scale) x (width / latent_scale) latents of `latent_channels`; the denoiser
|
||||
* reads them in `patch` x `patch` patches. Chunk c of n is `frames_per_chunk` frames, the last
|
||||
* `frames_per_chunk + frames_tail`. A side is a multiple of `size_multiple` pixels, at least
|
||||
* `min_side`, the area at most `max_area`, and the long side over the short at most `max_aspect`.
|
||||
* The soundtrack has round(frames / fps * audio_rate) latents a channel, each
|
||||
* reads them in `patch` x `patch` patches. A positive `frames_tail` adds frames to the last
|
||||
* chunk. A negative `frames_tail` trims the first chunk, which must still emit at least one
|
||||
* frame. Every other chunk has `frames_per_chunk` frames. A side is a multiple of `size_multiple`
|
||||
* pixels, at least `min_side`, the area at most `max_area`, and the long side over the short at
|
||||
* most `max_aspect`. The soundtrack has round(frames / fps * audio_rate) latents a channel, each
|
||||
* `sample_rate / audio_rate` samples.
|
||||
*
|
||||
* The rotary positions of a pass's rows are the plugin's (rad_arch_video_positions), which a video
|
||||
@@ -1337,6 +1425,9 @@ enum { RAD_GEN_PASS_VCOND = 8, RAD_GEN_PASS_VSTEP = 9, RAD_GEN_PASS_ADECODE = 10
|
||||
RAD_GEN_PASS_VDECODE = 11, RAD_GEN_PASS_VUPSCALE = 12,
|
||||
RAD_GEN_PASS_VENCODE = 13, RAD_GEN_PASS_AENCODE = 14 };
|
||||
|
||||
enum { RAD_VIDEO_SCHEDULE_UNIPC = 2 };
|
||||
enum { RAD_VIDEO_GUIDANCE_FULL = 1, RAD_VIDEO_GUIDANCE_CFG = 2 };
|
||||
|
||||
typedef struct RadVideoGenDecl {
|
||||
const char* name; /* "minimax-h3" -- the served model id and messages */
|
||||
|
||||
@@ -1355,7 +1446,7 @@ typedef struct RadVideoGenDecl {
|
||||
/* The size and length a request that names none is made at. */
|
||||
int64_t default_width, default_height, default_chunks;
|
||||
|
||||
/* The soundtrack. */
|
||||
/* The soundtrack. All four fields are zero for a video-only model. */
|
||||
int64_t sample_rate, audio_rate, audio_channels, audio_latent_channels;
|
||||
|
||||
/* The sampler (above). */
|
||||
@@ -1365,7 +1456,7 @@ typedef struct RadVideoGenDecl {
|
||||
/* `max_lanes` requests may hold state at once. `frames_out` is [>= the frames of the largest
|
||||
* chunk, height, width, 3] u8 on the device, the frames a VDECODE pass made, row-major RGB;
|
||||
* `audio_out` is [>= the samples of the longest soundtrack, audio_channels] f32, interleaved,
|
||||
* what an ADECODE pass made. */
|
||||
* what an ADECODE pass made. Set audio_out to RAD_NULL_HANDLE for video-only models. */
|
||||
int64_t max_lanes;
|
||||
rad_buf frames_out;
|
||||
rad_buf audio_out;
|
||||
@@ -1391,7 +1482,11 @@ typedef struct RadVideoGenDecl {
|
||||
* `base_seq` (`base_shift`) to `max_seq` (`max_shift`); then, with `shift_terminal` > 0,
|
||||
* stretched so the last is shift_terminal; and a closing 0. A trained schedule (n_rungs > 0)
|
||||
* is the rungs taken to f32 and a closing 0, with default_steps and max_steps both n_rungs.
|
||||
* Both modalities step the same sigmas; shift_video and shift_audio are unused. */
|
||||
* Both modalities step the same sigmas; shift_video and shift_audio are unused.
|
||||
* RAD_VIDEO_SCHEDULE_UNIPC: Wan's shifted 1000-step flow training grid and
|
||||
* order-two UniPC BH2 update, with integer model timesteps. The request
|
||||
* names the number of evaluations. Only video, with no trained rungs or
|
||||
* latent upscaler. shift_video supplies the default shift. */
|
||||
int32_t sched_kind;
|
||||
int32_t dyn_shift;
|
||||
double base_shift, max_shift;
|
||||
@@ -1406,11 +1501,13 @@ typedef struct RadVideoGenDecl {
|
||||
/* The text rows of every VSTEP pass, whatever the prompt's length (0: the prompt's tokens):
|
||||
* a model whose text encoder writes a fixed number of rows. */
|
||||
int64_t step_text_rows;
|
||||
/* Guidance terms (RadVideoGenBatch::guidance_h) when `guidance` is 1: the defaults a request
|
||||
* that names none gets, the video's scale, spatio-temporal scale, modality scale and rescale,
|
||||
* then the soundtrack's four. A request whose video or soundtrack scale is not 1 is guided
|
||||
* against a negative prompt: its own, else `default_negative` (null: ""). The VCOND pass then
|
||||
* carries both prompts, the positive first (two cu_seqlens entries). */
|
||||
/* Guidance terms (RadVideoGenBatch::guidance_h) when `guidance` is nonzero: the defaults a
|
||||
* request that names none gets, the video's scale, spatio-temporal scale, modality scale and
|
||||
* rescale, then the soundtrack's four. A request whose video or soundtrack scale is not 1 is
|
||||
* guided against a negative prompt: its own, else `default_negative` (null: ""). The VCOND pass
|
||||
* then carries both prompts, the positive first (two cu_seqlens entries).
|
||||
* RAD_VIDEO_GUIDANCE_CFG accepts only the video and soundtrack CFG scales and negative
|
||||
* prompt. */
|
||||
int32_t guidance;
|
||||
double guidance_default[8];
|
||||
const char* default_negative;
|
||||
@@ -1471,6 +1568,87 @@ typedef struct RadVideoGenDecl {
|
||||
|
||||
int rad_declare_video_generator(RadBuilder* b, const RadVideoGenDecl* d);
|
||||
|
||||
/* ================================================================== the shape generator */
|
||||
/* A program that makes a 3-D shape from one picture: an image encoder reads the picture, a
|
||||
* denoiser steps a set of latent rows by flow matching, guided against an unconditioned branch,
|
||||
* and a decoder turns the latent into an occupancy field that the core samples at points of its
|
||||
* choosing and meshes. The core drives the passes (RadBatch::gen, RadShapeGenBatch), one request
|
||||
* a pass:
|
||||
*
|
||||
* RAD_GEN_PASS_SCOND the request's picture through the image encoder into the request's
|
||||
* lane: what the denoiser reads of it at every step, for both branches
|
||||
* (the picture's and the unconditioned one).
|
||||
* RAD_GEN_PASS_SSTEP one denoising step of one lane over both branches, `step_rows` rows:
|
||||
* each branch's conditioning and latent, laid out as the plugin likes, the
|
||||
* latents two entries of `latent_rows` (the conditioned first) for the
|
||||
* image generator's sampler ops. The first step draws the lane's noise.
|
||||
* RAD_GEN_PASS_SLATENT the lane's final latent through the decoder's network, into the lane:
|
||||
* what every query pass of the request reads. Runs once, after the last
|
||||
* step.
|
||||
* RAD_GEN_PASS_SQUERY the field at `n_query` points (RadShapeGenBatch::query, at most
|
||||
* `max_query`), one f32 a point in `field_out`, which the core reads
|
||||
* back.
|
||||
*
|
||||
* The picture. The core decodes it with its alpha (opaque without one) and prepares it as
|
||||
* Hunyuan3D-2's ImageProcessorV2 and image encoder do: the alpha's bounding box (its last row and
|
||||
* column left out, as the reference's slice leaves them) scaled with OpenCV's INTER_AREA to
|
||||
* (1 - border_ratio) of the longer side of the square that holds the picture, centred on it and
|
||||
* flattened onto white; that square resized to `canvas` x `canvas` with INTER_CUBIC; then as 0..1
|
||||
* values bilinearly resized to `enc_size` x `enc_size` (half-pixel centres, torchvision's), each
|
||||
* channel normalised by `pix_mean` and `pix_std`, and cut into (enc_size / enc_patch)^2 patches of
|
||||
* enc_patch x enc_patch pixels, row-major, each patch's values channel-major then row-major (a
|
||||
* convolution's weight order). An SCOND pass carries those patches.
|
||||
*
|
||||
* The sampler: a request's `steps` are sigma grid points, sigma_i = i / (steps - 1) for i in
|
||||
* [0, steps), numpy's linspace(0, 1) taken to f32; the latent starts as noise at sigma 0 and an
|
||||
* evaluation at each sigma but the last steps it to the next (the reference evaluates at the
|
||||
* last too, against itself, a step of zero). The model's timestep is sigma, the guided velocity
|
||||
* neg + cfg (pos - neg), and the step x + (sigma_next - sigma) v.
|
||||
*
|
||||
* The field: the decoder's logit at a point, inside the shape above `level`. The core samples the
|
||||
* cube [-bounds, bounds]^3 on a grid of `resolution` cells a side ((resolution + 1)^3 points,
|
||||
* numpy's linspace in f32 along each axis), coarse to fine as FlashVDM's hierarchical decoding
|
||||
* does: the whole grid at the coarsest level (resolution halved while it stays at least 63), then
|
||||
* at each finer level only the points near where the coarser one crosses `level` or is within
|
||||
* 0.95 of it. The surface is marching cubes over the finest grid, a vertex at grid index g placed
|
||||
* at g 2 bounds / (resolution + 1) - bounds, as the reference places it.
|
||||
*
|
||||
* A program declares exactly one of this, the other generators, logits or pooled vectors. */
|
||||
enum { RAD_GEN_PASS_SCOND = 15, RAD_GEN_PASS_SSTEP = 16, RAD_GEN_PASS_SLATENT = 17,
|
||||
RAD_GEN_PASS_SQUERY = 18 };
|
||||
|
||||
typedef struct RadShapeGenDecl {
|
||||
const char* name; /* "hunyuan3d-2" -- the served model id and messages */
|
||||
|
||||
/* The picture (above). */
|
||||
int64_t canvas;
|
||||
double border_ratio;
|
||||
int64_t enc_size, enc_patch;
|
||||
double pix_mean[3], pix_std[3];
|
||||
|
||||
/* The latent: `latent_rows` rows of `latent_channels` a branch; a step's rows, both branches
|
||||
* with their conditioning. */
|
||||
int64_t latent_rows, latent_channels, step_rows;
|
||||
|
||||
/* The sampler (above) and the guidance a request that names none runs at. */
|
||||
int64_t default_steps, max_steps;
|
||||
double default_guidance;
|
||||
|
||||
/* The field (above): the cube's half side, the iso value, and the grid's resolution a request
|
||||
* that names none is sampled at, with the range a request may name. */
|
||||
double bounds;
|
||||
double level;
|
||||
int64_t default_resolution, min_resolution, max_resolution;
|
||||
|
||||
/* `max_lanes` requests may hold state at once. `field_out` is a device f32 buffer of at least
|
||||
* `max_query` elements. */
|
||||
int64_t max_lanes;
|
||||
int64_t max_query;
|
||||
rad_buf field_out;
|
||||
} RadShapeGenDecl;
|
||||
|
||||
int rad_declare_shape_generator(RadBuilder* b, const RadShapeGenDecl* d);
|
||||
|
||||
/* ================================================================== diagnostics */
|
||||
/* A plugin may annotate the graph dump. Free-form, printed under --debug-graph. */
|
||||
void rad_note(RadBuilder* b, const char* fmt, ...);
|
||||
@@ -1499,6 +1677,13 @@ const char* rad_arch_quant(void);
|
||||
* move. */
|
||||
int rad_arch_serves_imports(void);
|
||||
|
||||
/* Nonzero when every piece of per-instance state the plugin keeps is indexed by
|
||||
* rad_build_slot() / rad_slot(), so several engines in one process may run it at once
|
||||
* (docs/MULTIMODEL.md §3.3). Optional: absent or zero, the core runs the plugin for one engine at
|
||||
* a time and refuses a second engine on it by name. arch/common/rad_arch.h writes it with
|
||||
* RAD_ARCH_MULTI_INSTANCE(). */
|
||||
int rad_arch_multi_instance(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.
|
||||
*
|
||||
@@ -1558,17 +1743,19 @@ typedef struct RadArchProbe {
|
||||
* `gen_rows` (its largest pass: a step's packed sequence at the largest size and length). It
|
||||
* keeps no KV. */
|
||||
int32_t gen_video;
|
||||
/* The RadBuildCtx::kv_quant layouts the plugin serves for this model, bit 1 << RAD_KVQ_*:
|
||||
* libr4d has their rows for its attention geometry. A layout whose bit is clear is refused at
|
||||
* startup with the plugin named. */
|
||||
int32_t kv_quant_ok;
|
||||
/* Nonzero when the plugin serves an E4M3 cache for this model (--kv-cache-dtype fp8,
|
||||
* RadBuildCtx::kv_dtype RAD_F8E4M3): GLM-5.3's latent attention, DeepSeek-V4.1's compressed
|
||||
* latent and index keys (block-scaled entries, rad_kv_fp8.h). The engine refuses the flag
|
||||
* for a plugin that leaves it zero, naming the int8 cache every paged attention serves. */
|
||||
int32_t kv_fp8_ok;
|
||||
|
||||
/* ---- appended in ABI 26 (chained launches, control vectors) */
|
||||
/* Nonzero when this plugin measured its speculative step faster with chained launches
|
||||
* (RadKernelChainFn: a dependent kernel waits in its own prologue rather than behind the
|
||||
* queue's barrier bit). With a drafter decoding speculatively on the AQL backend, the core
|
||||
* then takes them. Zero keeps them off: plain decode measured slower chained, and a plugin
|
||||
* that never measured them asks for nothing. */
|
||||
/* How this plugin measured chained launches (RadKernelChainFn: a dependent kernel waits in its
|
||||
* own prologue rather than behind the queue's barrier bit), a RAD_CHAIN_*. SPEC: its
|
||||
* speculative step is faster with them, and the core takes them on the AQL backend while a
|
||||
* drafter decodes speculatively. ALWAYS: its plain decode is faster too, and the core takes
|
||||
* them with or without a drafter. Zero keeps them off: some models' plain decode measured
|
||||
* slower chained, and a plugin that never measured them asks for nothing. */
|
||||
int32_t chain_pays;
|
||||
/* ---- appended in ABI 30 (KV streaming) */
|
||||
/* Nonzero when the architecture can stream a KV group between host memory and a VRAM ring: its
|
||||
@@ -1605,6 +1792,20 @@ typedef struct RadArchProbe {
|
||||
* gen_patches answer for them. */
|
||||
int64_t gen_max_pixels;
|
||||
int64_t gen_max_refs;
|
||||
|
||||
/* ---- appended in ABI 33 (the shape generator) */
|
||||
/* Nonzero for a shape generator, which the engine sizes as it does a video generator from
|
||||
* `gen_rows` (its largest pass: a step's two branches, or a query pass's points). It keeps no
|
||||
* KV. */
|
||||
int32_t gen_shape;
|
||||
|
||||
/* ---- appended in ABI 43 (a checkpoint inside the step), in the padding behind gen_shape */
|
||||
/* Nonzero when the plugin serves RadBatch::ckpt_cut: a step of one prefill sequence whose
|
||||
* checkpoint lies inside it runs its recurrence in two pieces and snapshots between them
|
||||
* (rad_ckpt_snap). The scheduler then takes a prompt's tail snapshot inside its last chunk
|
||||
* rather than ending the chunk there and running the rows past it as a step of their own.
|
||||
* Zero keeps that step. */
|
||||
int32_t ckpt_snap_ok;
|
||||
} RadArchProbe;
|
||||
|
||||
int rad_arch_probe(const RadModelMeta* meta, RadArchProbe* out);
|
||||
@@ -1734,6 +1935,30 @@ typedef struct RadChatFormat {
|
||||
* decides how its value is read, whatever the schema says; the grammar writes the one the
|
||||
* schema calls for. NULL: the schema alone types a value. */
|
||||
const char* arg_json_value_prefix;
|
||||
|
||||
/* A header the model writes first when it answers without reasoning, in place of
|
||||
* reasoning_open: the reply then starts with this literal, which is dropped, and the rest is
|
||||
* content. A reply that starts with anything else, or with only part of it, is read as
|
||||
* written. When the model does reason, its header after the block is reasoning_close's.
|
||||
* NULL or "": the reply starts with its content. */
|
||||
const char* content_open;
|
||||
|
||||
/* RAD_CHAT_ARGS_OBJECT: the object after the name is an envelope that names the call again
|
||||
* and holds the arguments under this key, `{"name":NAME,"KEY":{...}}` (Inkling 2's
|
||||
* `<|content_invoke_tool_json|>{"name":"f","args":{...}}`). The reply's arguments are KEY's
|
||||
* value. The grammar writes the envelope compactly in that order; a reply that writes the
|
||||
* keys the other way round, names another function or leaves the envelope out is still read,
|
||||
* as not strict. JSON objects only: no object_string_open, no bare keys. NULL or "": the
|
||||
* object is the arguments. */
|
||||
const char* object_args_key;
|
||||
|
||||
/* A header every message of the reply starts with (Inkling 2's `<|message_model|>`): before
|
||||
* reasoning_open it is part of the block's opener, before content_open it is the content's
|
||||
* header, and both are dropped there; before anything else it is read as written, which
|
||||
* makes it a call's name_prefix when the format names it so (`<|message_model|>NAME...`).
|
||||
* Needs reasoning_open or content_open; with tool calls, name_prefix must be this literal
|
||||
* and call_open and section_open empty. NULL or "": messages have no header of their own. */
|
||||
const char* message_open;
|
||||
} RadChatFormat;
|
||||
|
||||
/* Return the format, or NULL for "derive it from the chat template". Called once at startup. */
|
||||
@@ -1846,6 +2071,14 @@ int rad_arch_declare(RadBuilder* b, const RadModelMeta* meta, const RadB
|
||||
struct RadCtx;
|
||||
struct RadBatch;
|
||||
void rad_arch_step(struct RadCtx* c, const struct RadBatch* batch);
|
||||
/* Optional. Return a stable fingerprint of actual dispatch geometry whose grid depends on live
|
||||
* per-group seqused values. `kv_used_max_h[g]` is the host maximum for batch->kv[g], and
|
||||
* rad_ctx_wgp_count(c) supplies the device's WGP count. Return 0 when exact geometry is unknown;
|
||||
* that pass runs live and is not recorded. Only prefill and mixed launches read the live maximum:
|
||||
* in a decode, verify or draft pass every launch reads the step's keyed context bound
|
||||
* (RadArgs::kv_used_max_h), so such a pass needs no geometry here and returns nonzero. */
|
||||
uint64_t rad_arch_pass_key(struct RadCtx* c, const struct RadBatch* batch,
|
||||
const int32_t* kv_used_max_h);
|
||||
|
||||
#ifdef __cplusplus
|
||||
} /* extern "C" */
|
||||
|
||||
+2
-1
@@ -354,7 +354,8 @@ static inline int rad_enc_valid(const RadEncoding* e) {
|
||||
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[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;
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
/* rad_gdn_anchor.h -- the layout of a gated-delta-net state slot under the `anchor` state form.
|
||||
*
|
||||
* docs/OPS.md, `state_form`: a speculating sequence keeps one committed state (the anchor) and,
|
||||
* in a second slot of the same shape, one replay record per verified row: the row's normalised
|
||||
* key once per 32-row group of head_v, its raw value row, and its decay exponent and beta once
|
||||
* per group. The next step replays the first `num_accepted` records onto the anchor.
|
||||
*
|
||||
* Three parties read this layout and must agree: libr4d's kernels
|
||||
* (r4d_gdn_recurrent_update_k128_v128_bf16_fp32state.hip), libref's reference
|
||||
* (libref/ref_gdn.cpp, AnchorLayout) and the core's acceptance of a tree verify
|
||||
* (rad_drafter_tree, core/sched/advance_impl.h, ADV_COMPACT), which moves the accepted path's
|
||||
* records to the front of the block so the next step's replay reads a chain. Everything here is
|
||||
* in elements of the state's dtype, inside one head's [head_v, head_k] block of the factor slot:
|
||||
*
|
||||
* record t at t * fstr
|
||||
* [0, groups*K) the normalised k, one copy per 32-row group
|
||||
* [groups*K, groups*K + V) the raw v row
|
||||
* [groups*K + V, +2*groups) (decay exponent, beta) per group
|
||||
* the shift marker at tmax * fstr, past the last record
|
||||
*
|
||||
* libr4d's K = V = 128 kernel has fstr 648, tmax 16 and the marker at 10368. */
|
||||
#ifndef RAD_GDN_ANCHOR_H
|
||||
#define RAD_GDN_ANCHOR_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
static inline int64_t rad_gdn_anchor_groups(int64_t head_v) { return (head_v + 31) / 32; }
|
||||
|
||||
/* Elements of one record. */
|
||||
static inline int64_t rad_gdn_anchor_fstr(int64_t head_k, int64_t head_v) {
|
||||
const int64_t g = rad_gdn_anchor_groups(head_v);
|
||||
return g * head_k + head_v + 2 * g;
|
||||
}
|
||||
|
||||
/* Records a head's block holds: 16, or as many as fit before the marker on a small head. */
|
||||
static inline int64_t rad_gdn_anchor_tmax(int64_t head_k, int64_t head_v) {
|
||||
const int64_t fstr = rad_gdn_anchor_fstr(head_k, head_v);
|
||||
const int64_t fit = fstr > 0 ? (head_v * head_k - 1) / fstr : 0;
|
||||
return fit < 16 ? fit : 16;
|
||||
}
|
||||
|
||||
/* The marker's element offset. */
|
||||
static inline int64_t rad_gdn_anchor_mark(int64_t head_k, int64_t head_v) {
|
||||
return rad_gdn_anchor_tmax(head_k, head_v) * rad_gdn_anchor_fstr(head_k, head_v);
|
||||
}
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
#endif /* RAD_GDN_ANCHOR_H */
|
||||
@@ -0,0 +1,189 @@
|
||||
#ifndef RAD_KV_FP8_H
|
||||
#define RAD_KV_FP8_H
|
||||
|
||||
/* Block-scaled E4M3 cache entries (docs/OPS.md "Block-scaled E4M3 cache entries"): one compressed
|
||||
* or index entry of n values as n E4M3 codes, then n / block scale bytes, then zeros to a multiple
|
||||
* of 16 bytes. A value is code x scale in f32: two E4M3 significands (4 bits each) multiply to at
|
||||
* most 8 significant bits, so the product is exact in f32 and in bf16, and a reader widening an
|
||||
* entry gets the very bf16 value an exact entry was packed from.
|
||||
*
|
||||
* e4m3_e4m3_16 an E4M3 scale a block of 16 (quant_roundtrip fp4_e2m1 / e4m3 / 16 output)
|
||||
* e4m3_ue8m0_32 a power-of-two scale a block of 32: byte e is 2^(e - 127), 0 is zero
|
||||
* (quant_roundtrip fp4_e2m1 or fp8_e4m3 / ue8m0 / 32 output)
|
||||
*
|
||||
* entry_store packs (rad_kvf_pack_block); attn_sparse_sink (latent_format) and index_score
|
||||
* (key_format) widen (rad_kvf_value). The packing is exact for every block the named
|
||||
* quant_roundtrip produced:
|
||||
* - e4m3_e4m3_16: the block's own scale s is amax / c for its largest code c in {6, 4, 3, 2,
|
||||
* 1.5, 1, 0.5}, so searching those for an E4M3 scale under which every value comes back bit
|
||||
* for bit finds one (re-deriving s by quant_roundtrip's rule is not exact where E4M3 is
|
||||
* subnormal). A block no scale reproduces (not quant_roundtrip output) takes the rule, lossy.
|
||||
* - e4m3_ue8m0_32: the smallest power of two s' with amax / s' <= 448 (at least 2^-126) is at
|
||||
* most the block's own scale, so every value / s' is its code times 2^j, j >= 0, at most 448:
|
||||
* an E4M3 value. Other blocks round to nearest, lossy.
|
||||
* The sign of zero is kept (code 0x80).
|
||||
*
|
||||
* Plain C (abi_c_test), and host-and-device under HIP, so libref, libavx and libr4d's entry_store
|
||||
* run this very code; the E4M3 conversions are rad_plugin.h's, restated here for the device. */
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
|
||||
#if defined(__HIPCC__) || defined(__CUDACC__)
|
||||
#define RAD_KVF_HD __host__ __device__
|
||||
#else
|
||||
#define RAD_KVF_HD
|
||||
#endif
|
||||
|
||||
enum {
|
||||
RAD_KVF_BF16 = 0, /* bf16 values, 2 bytes each (the default) */
|
||||
RAD_KVF_E4M3_E4M3_16 = 1,
|
||||
RAD_KVF_E4M3_UE8M0_32 = 2
|
||||
};
|
||||
|
||||
/* A format name to its RAD_KVF_*; null or "bf16" is RAD_KVF_BF16, anything unknown -1. Host. */
|
||||
static inline int rad_kvf_parse(const char* s) {
|
||||
if (!s || !strcmp(s, "bf16")) return RAD_KVF_BF16;
|
||||
if (!strcmp(s, "e4m3_e4m3_16")) return RAD_KVF_E4M3_E4M3_16;
|
||||
if (!strcmp(s, "e4m3_ue8m0_32")) return RAD_KVF_E4M3_UE8M0_32;
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Values a scale covers; 0 for bf16. */
|
||||
static inline RAD_KVF_HD int64_t rad_kvf_block(int f) {
|
||||
return f == RAD_KVF_E4M3_E4M3_16 ? 16 : f == RAD_KVF_E4M3_UE8M0_32 ? 32 : 0;
|
||||
}
|
||||
|
||||
/* Bytes of one entry of n values (n a multiple of the block); 0 when n does not fit the format. */
|
||||
static inline RAD_KVF_HD int64_t rad_kvf_bytes(int f, int64_t n) {
|
||||
const int64_t blk = rad_kvf_block(f);
|
||||
if (f == RAD_KVF_BF16) return 2 * n;
|
||||
if (blk < 1 || n < 1 || n % blk) return 0;
|
||||
return (n + n / blk + 15) / 16 * 16;
|
||||
}
|
||||
|
||||
typedef union { float f; uint32_t u; } RadKvfBits;
|
||||
static inline RAD_KVF_HD uint32_t rad_kvf_bits(float x) { RadKvfBits b; b.f = x; return b.u; }
|
||||
static inline RAD_KVF_HD float rad_kvf_float(uint32_t u) { RadKvfBits b; b.u = u; return b.f; }
|
||||
|
||||
/* rad_plugin.h's rad_fp8e4m3_to_f32: OCP E4M3 (e4m3fn), S1111111 the only NaN. */
|
||||
static inline RAD_KVF_HD float rad_kvf_e4m3(uint8_t b) {
|
||||
const uint32_t s = (uint32_t)(b >> 7) << 31;
|
||||
const uint32_t e = (uint32_t)(b >> 3) & 0xfu;
|
||||
uint32_t m = (uint32_t)b & 0x7u;
|
||||
if (e == 0u) {
|
||||
int sh = 0;
|
||||
if (m == 0u) return rad_kvf_float(s);
|
||||
while (!(m & 0x8u)) { m <<= 1; ++sh; }
|
||||
m &= 0x7u;
|
||||
return rad_kvf_float(s | ((uint32_t)(127 - 6 - sh) << 23) | (m << 20));
|
||||
}
|
||||
if (e == 0xfu && m == 0x7u) return rad_kvf_float(s | 0x7fc00000u);
|
||||
return rad_kvf_float(s | ((e - 7u + 127u) << 23) | (m << 20));
|
||||
}
|
||||
|
||||
/* rad_plugin.h's rad_f32_to_fp8e4m3: nearest even, saturating at +-448, NaN to S1111111. */
|
||||
static inline RAD_KVF_HD uint8_t rad_kvf_to_e4m3(float f) {
|
||||
const uint32_t u = rad_kvf_bits(f);
|
||||
const uint8_t s = (uint8_t)((u >> 24) & 0x80u);
|
||||
const uint32_t a = u & 0x7fffffffu;
|
||||
int e;
|
||||
uint32_t m;
|
||||
if (a > 0x7f800000u) return (uint8_t)(s | 0x7fu);
|
||||
if (a >= 0x43e00000u) return (uint8_t)(s | 0x7eu);
|
||||
e = (int)(a >> 23) - 127;
|
||||
m = a & 0x7fffffu;
|
||||
if (e < -10) return s;
|
||||
if (e < -6) {
|
||||
const 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;
|
||||
const 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);
|
||||
}
|
||||
}
|
||||
|
||||
/* A scale byte's f32. */
|
||||
static inline RAD_KVF_HD float rad_kvf_scale(int f, uint8_t b) {
|
||||
return f == RAD_KVF_E4M3_E4M3_16 ? rad_kvf_e4m3(b) : rad_kvf_float((uint32_t)b << 23);
|
||||
}
|
||||
|
||||
/* Value d of an entry `e` of n values. */
|
||||
static inline RAD_KVF_HD float rad_kvf_value(int f, const uint8_t* e, int64_t n, int64_t d) {
|
||||
return rad_kvf_e4m3(e[d]) * rad_kvf_scale(f, e[n + d / rad_kvf_block(f)]);
|
||||
}
|
||||
|
||||
/* One block's codes under scale `sc` (> 0), each the E4M3 nearest x / sc; returns 1 when every
|
||||
* code times sc gives x back bit for bit. */
|
||||
static inline RAD_KVF_HD int rad_kvf_codes(const float* x, int nb, float sc, uint8_t* codes) {
|
||||
int exact = 1, i;
|
||||
for (i = 0; i < nb; ++i) {
|
||||
const uint8_t c = rad_kvf_to_e4m3(x[i] / sc);
|
||||
codes[i] = c;
|
||||
if (rad_kvf_bits(rad_kvf_e4m3(c) * sc) != rad_kvf_bits(x[i])) exact = 0;
|
||||
}
|
||||
return exact;
|
||||
}
|
||||
|
||||
/* One block of rad_kvf_block(f) values `x` (bf16 values as f32) packed: its codes into `codes`,
|
||||
* its scale byte returned. */
|
||||
static inline RAD_KVF_HD uint8_t rad_kvf_pack_block(int f, const float* x, uint8_t* codes) {
|
||||
const int nb = (int)rad_kvf_block(f);
|
||||
float am = 0.0f;
|
||||
int i;
|
||||
for (i = 0; i < nb; ++i) {
|
||||
const float a = x[i] < 0.0f ? -x[i] : x[i];
|
||||
if (a > am) am = a;
|
||||
}
|
||||
if (!(am > 0.0f)) { /* zeros (and NaN, which no cache value is): signs only */
|
||||
for (i = 0; i < nb; ++i) codes[i] = (uint8_t)((rad_kvf_bits(x[i]) >> 24) & 0x80u);
|
||||
return 0;
|
||||
}
|
||||
if (f == RAD_KVF_E4M3_E4M3_16) {
|
||||
uint8_t sb;
|
||||
int c;
|
||||
for (c = 0; c < 7; ++c) {
|
||||
/* amax / c, c = 6, 4, 3, 2, 1.5, 1, 0.5: the largest e2m1 code */
|
||||
const float cand = c == 0 ? 6.0f : c == 1 ? 4.0f : c == 2 ? 3.0f : c == 3 ? 2.0f
|
||||
: c == 4 ? 1.5f : c == 5 ? 1.0f : 0.5f;
|
||||
const float sc = am / cand;
|
||||
sb = rad_kvf_to_e4m3(sc);
|
||||
if (sb == 0 || rad_kvf_bits(rad_kvf_e4m3(sb)) != rad_kvf_bits(sc)) continue;
|
||||
if (rad_kvf_codes(x, nb, sc, codes)) return sb;
|
||||
}
|
||||
/* quant_roundtrip's rule, fp8(max(amax, 6 * 2^-9) / 6): lossy */
|
||||
sb = rad_kvf_to_e4m3((am > 6.0f * 0.001953125f ? am : 6.0f * 0.001953125f) / 6.0f);
|
||||
(void)rad_kvf_codes(x, nb, rad_kvf_e4m3(sb), codes);
|
||||
return sb;
|
||||
}
|
||||
{
|
||||
/* 2^e with am / 2^e <= 448, the smallest: am in [2^E, 2^(E+1)) gives E - 8 or E - 7 */
|
||||
int e = (int)((rad_kvf_bits(am) >> 23) & 0xffu) - 127 - 8;
|
||||
if (e < -126) e = -126;
|
||||
if (am > 448.0f * rad_kvf_float((uint32_t)(e + 127) << 23)) ++e;
|
||||
(void)rad_kvf_codes(x, nb, rad_kvf_float((uint32_t)(e + 127) << 23), codes);
|
||||
return (uint8_t)(e + 127);
|
||||
}
|
||||
}
|
||||
|
||||
/* An entry of n values `x` packed into `e` (rad_kvf_bytes(f, n) bytes, the padding zeroed). */
|
||||
static inline RAD_KVF_HD void rad_kvf_pack(int f, const float* x, int64_t n, uint8_t* e) {
|
||||
const int64_t nb = rad_kvf_block(f), bytes = rad_kvf_bytes(f, n);
|
||||
int64_t b;
|
||||
for (b = 0; b < n / nb; ++b) e[n + b] = rad_kvf_pack_block(f, x + b * nb, e + b * nb);
|
||||
for (b = n + n / nb; b < bytes; ++b) e[b] = 0;
|
||||
}
|
||||
|
||||
#endif /* RAD_KV_FP8_H */
|
||||
@@ -0,0 +1,331 @@
|
||||
/* rad_mtp_block.h -- BLOCK VERIFICATION of a linear MTP draft chain (--draft-verify block).
|
||||
*
|
||||
* Sun, Mendlovic, Leviathan, Aharoni, Beirami, Ro, Suresh, "Block Verification Accelerates
|
||||
* Speculative Decoding" (arXiv 2403.10444): the chain's draft tokens X_1 .. X_g are accepted or
|
||||
* rejected JOINTLY. Token-wise speculative sampling (what --draft-coupling does at each row) is
|
||||
* optimal per token; block verification is optimal for the whole block: the expected number of
|
||||
* accepted tokens is never lower and the output law is the target's, exactly.
|
||||
*
|
||||
* With P_i = the target's law after X^i (the sampler's filtered candidate softmax at verify row i,
|
||||
* i = 0 .. g-1) and Q_{i+1} = the head's law the draft X_{i+1} was sampled from (the coupled state
|
||||
* of round i + 1, the FP64 softmax of the reranked top 8):
|
||||
*
|
||||
* p_0 = 1, p_i = min(1, p_{i-1} P_{i-1}(X_i) / Q_i(X_i)) i = 1 .. g
|
||||
* S_i = sum_x max(p_i P_i(x) - Q_{i+1}(x), 0) i = 0 .. g-1
|
||||
* h_i = S_i / (S_i + 1 - p_i) (i < g), h_g = p_g
|
||||
*
|
||||
* for i = g, g-1, ..., 0: accept the block's first i tokens with probability h_i; the first
|
||||
* success is tau. (h_0 = 1: it always stops.)
|
||||
* tau = g: X_1 .. X_g are emitted and the next token is the ordinary draw from P_g.
|
||||
* tau < g: X_1 .. X_tau are emitted, then Y ~ max(p_tau P_tau - Q_{tau+1}, 0) normalised.
|
||||
*
|
||||
* Exactness is checked in tests/mtp_block_test.cpp by exact enumeration of the draft tree of a toy
|
||||
* model (the law of the emitted tokens computed in closed form, to 1e-12) and by a chi-square of
|
||||
* the real device-shared code, with a negative control (the same rule with a wrong residual).
|
||||
*
|
||||
* Y may equal X_{tau+1}; the core then takes that draft as accepted (ADV_ACCEPT: "the draft is the
|
||||
* sampler's token at this row") and reads the next row, which keeps its ordinary pick: a draw from
|
||||
* the target's law given exactly the tokens emitted so far, so the extra tokens continue the same
|
||||
* autoregressive sample. The verify op therefore writes only rows 0 .. tau of the block and leaves
|
||||
* every later row alone.
|
||||
*
|
||||
* Relation to --draft-coupling: the DRAFT half is shared (x ~ Q at temperature 1 from the head's
|
||||
* top 8, coupled states with their FP64 Q); only the verify half differs. Maximal coupling decides
|
||||
* row k from P_k and Q_{k+1} alone, so it is a per-row rule the core's token comparison walks
|
||||
* unchanged. Block verification decides row k from the rows after it (h_i for i > k), so the two
|
||||
* rules cannot be applied to the same row; `--draft-verify block` replaces the coupling's verify
|
||||
* and requires the coupled drafting (it switches it on), and it is for a LINEAR chain; Traversal
|
||||
* Verification (abi/rad_mtp_traversal.h, 2505.12398) is the walk that also covers a node with
|
||||
* several children.
|
||||
*/
|
||||
#ifndef RAD_MTP_BLOCK_H
|
||||
#define RAD_MTP_BLOCK_H
|
||||
|
||||
#include "rad_spechub.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
|
||||
#ifdef __HIPCC__
|
||||
#define RAD_BLK_HD __host__ __device__
|
||||
#else
|
||||
#define RAD_BLK_HD
|
||||
#endif
|
||||
|
||||
#define RAD_MTP_BLOCK_MAX RAD_MTP_COUPLE_MAX_ROUNDS /* g: the chain's longest block */
|
||||
#define RAD_MTP_BLOCK_KEY_STOP 0x424c4b53544f5000ull /* the h_i uniforms, per block */
|
||||
|
||||
/* Summation structure. The device decides a block with one workgroup of RAD_MTP_BLOCK_LANES
|
||||
* threads, so every FP64 sum over a row's candidate plane is DEFINED as this fixed tree, which the
|
||||
* host reference mirrors operation for operation (FP64 addition is not associative: the tree is
|
||||
* the definition, not an approximation):
|
||||
* - plane slot j belongs to lane j % LANES; a lane adds its live slots in ascending j;
|
||||
* - the lanes are reduced inside each group of RAD_MTP_BLOCK_WAVE by the butterfly
|
||||
* a[l] = a[l] + a[l ^ d], d = 16, 8, 4, 2, 1 (every lane of a group ends with the same bits),
|
||||
* and the LANES / WAVE group sums are added as ((g0 + g1) + (g2 + g3)).
|
||||
* The exp() of a slot is the same libm / device function on both sides. */
|
||||
#define RAD_MTP_BLOCK_LANES 128
|
||||
#define RAD_MTP_BLOCK_WAVE 32
|
||||
|
||||
/* One verify row's candidate plane, dense (n slots, holes id < 0 and -inf scores skipped), with
|
||||
* `valid` and `top` the scan of the whole plane (rad_mtp_block_scan makes it on the host; the
|
||||
* device reduces the same two values across its workgroup: a max and an OR are order free). */
|
||||
struct RadBlockRow {
|
||||
const int32_t* ids;
|
||||
const float* val;
|
||||
int64_t n;
|
||||
int valid;
|
||||
float top;
|
||||
};
|
||||
|
||||
/* The dense row's validity and maximum, as rad_mtp_couple_decide scans them. */
|
||||
static inline RAD_BLK_HD void rad_mtp_block_scan(RadBlockRow* r, int64_t vocab) {
|
||||
float top = -INFINITY;
|
||||
int valid = 1;
|
||||
for (int64_t j = 0; j < r->n; ++j) {
|
||||
if (r->ids[j] < 0) continue;
|
||||
if (r->ids[j] >= vocab || r->val[j] != r->val[j] || r->val[j] == INFINITY) valid = 0;
|
||||
else if (r->val[j] > top) top = r->val[j];
|
||||
}
|
||||
r->valid = valid;
|
||||
r->top = top;
|
||||
}
|
||||
|
||||
static inline RAD_BLK_HD bool rad_mtp_block_live(int32_t id, float v) {
|
||||
return id >= 0 && v != -INFINITY;
|
||||
}
|
||||
|
||||
/* A lane's partial sums of one row: v[0..7] the mass on Q's ids (by their place in the state),
|
||||
* v[8] the mass off Q's support, v[9] the total. */
|
||||
struct RadBlockAcc { double v[10]; };
|
||||
|
||||
static inline RAD_BLK_HD int rad_mtp_block_find(const RadMtpCoupleState& s, int32_t id) {
|
||||
int k = 0;
|
||||
while (k < s.count && id != s.ids[k]) ++k;
|
||||
return k;
|
||||
}
|
||||
|
||||
/* Adds the live slot (id, v) to a lane's partial. */
|
||||
static inline RAD_BLK_HD void rad_mtp_block_acc_add(RadBlockAcc* a, const RadMtpCoupleState& s,
|
||||
int32_t id, float v, float top) {
|
||||
const double w = ::exp((double)v - top);
|
||||
const int k = rad_mtp_block_find(s, id);
|
||||
for (int kk = 0; kk < 8; ++kk) a->v[kk] += kk == k ? w : 0.0;
|
||||
a->v[8] += k >= s.count ? w : 0.0;
|
||||
a->v[9] += w;
|
||||
}
|
||||
|
||||
/* The lanes' partials reduced by the tree above (the host form; the device does the butterfly with
|
||||
* shuffles and adds the four group sums the same way). */
|
||||
static inline RAD_BLK_HD RadBlockAcc rad_mtp_block_tree(const RadBlockAcc* lane) {
|
||||
RadBlockAcc grp[RAD_MTP_BLOCK_LANES / RAD_MTP_BLOCK_WAVE];
|
||||
for (int w = 0; w < RAD_MTP_BLOCK_LANES / RAD_MTP_BLOCK_WAVE; ++w) {
|
||||
RadBlockAcc a[RAD_MTP_BLOCK_WAVE], t[RAD_MTP_BLOCK_WAVE];
|
||||
for (int l = 0; l < RAD_MTP_BLOCK_WAVE; ++l) a[l] = lane[w * RAD_MTP_BLOCK_WAVE + l];
|
||||
for (int d = RAD_MTP_BLOCK_WAVE / 2; d > 0; d >>= 1) {
|
||||
for (int l = 0; l < RAD_MTP_BLOCK_WAVE; ++l) t[l] = a[l];
|
||||
for (int l = 0; l < RAD_MTP_BLOCK_WAVE; ++l)
|
||||
for (int c = 0; c < 10; ++c) a[l].v[c] = t[l].v[c] + t[l ^ d].v[c];
|
||||
}
|
||||
grp[w] = a[0];
|
||||
}
|
||||
RadBlockAcc o;
|
||||
for (int c = 0; c < 10; ++c) o.v[c] = (grp[0].v[c] + grp[1].v[c]) + (grp[2].v[c] + grp[3].v[c]);
|
||||
return o;
|
||||
}
|
||||
|
||||
/* P_i over Q_{i+1}'s support (pq, normalised, duplicate candidates aggregated), the mass off that
|
||||
* support (pout), the normaliser `sum` and the index `ix` of the draft token in the state's ids. */
|
||||
struct RadBlockStat {
|
||||
double pq[8];
|
||||
double pout, sum;
|
||||
int ix;
|
||||
};
|
||||
|
||||
/* The stat from the reduced partials `t` (what the device builds from its workgroup's tree). */
|
||||
static inline RAD_BLK_HD bool rad_mtp_block_stat_from(const RadBlockAcc& t, int valid, float top,
|
||||
const RadMtpCoupleState& s, RadBlockStat* o) {
|
||||
if (!valid || top == -INFINITY) return false;
|
||||
const double sum = t.v[9];
|
||||
if (!(sum > 0) || !rad_spechub_finite(sum)) return false;
|
||||
o->ix = -1;
|
||||
for (int k = 0; k < 8; ++k) o->pq[k] = k < s.count ? t.v[k] : 0.0;
|
||||
for (int k = 0; k < s.count; ++k) {
|
||||
o->pq[k] /= sum;
|
||||
if (s.ids[k] == s.x) o->ix = k;
|
||||
}
|
||||
o->pout = t.v[8] / sum;
|
||||
o->sum = sum;
|
||||
return o->ix >= 0;
|
||||
}
|
||||
|
||||
static inline RAD_BLK_HD bool rad_mtp_block_stat(const RadBlockRow& r, const RadMtpCoupleState& s,
|
||||
RadBlockStat* o) {
|
||||
if (!r.valid || r.top == -INFINITY) return false;
|
||||
RadBlockAcc lane[RAD_MTP_BLOCK_LANES];
|
||||
for (int l = 0; l < RAD_MTP_BLOCK_LANES; ++l)
|
||||
for (int c = 0; c < 10; ++c) lane[l].v[c] = 0;
|
||||
for (int64_t j = 0; j < r.n; ++j)
|
||||
if (rad_mtp_block_live(r.ids[j], r.val[j]))
|
||||
rad_mtp_block_acc_add(&lane[j % RAD_MTP_BLOCK_LANES], s, r.ids[j], r.val[j], r.top);
|
||||
return rad_mtp_block_stat_from(rad_mtp_block_tree(lane), r.valid, r.top, s, o);
|
||||
}
|
||||
|
||||
/* The block's weights. p[i] (i = 0 .. g), h[i] (i = 0 .. g). */
|
||||
struct RadBlockPlan {
|
||||
int g;
|
||||
double p[RAD_MTP_BLOCK_MAX + 1];
|
||||
double h[RAD_MTP_BLOCK_MAX + 1];
|
||||
double s[RAD_MTP_BLOCK_MAX + 1]; /* S_i, the residual's mass (s[g] unused) */
|
||||
};
|
||||
|
||||
/* The residual mass of one token of row i at weight p: max(p P(x) - Q(x), 0) on Q's support,
|
||||
* p P(x) off it. */
|
||||
static inline RAD_BLK_HD double rad_mtp_block_resid_sum(const RadMtpCoupleState& s,
|
||||
const RadBlockStat& t, double p) {
|
||||
double r = p * t.pout;
|
||||
for (int k = 0; k < s.count; ++k) r += rad_spechub_positive(p * t.pq[k] - s.q[k]);
|
||||
return r;
|
||||
}
|
||||
|
||||
/* st[i] / stat[i] for i = 0 .. g-1. */
|
||||
static inline RAD_BLK_HD void rad_mtp_block_plan(const RadMtpCoupleState* st,
|
||||
const RadBlockStat* stat, int g,
|
||||
RadBlockPlan* o) {
|
||||
o->g = g;
|
||||
o->p[0] = 1.0;
|
||||
for (int i = 0; i < g; ++i) {
|
||||
const double ratio = stat[i].pq[stat[i].ix] / st[i].q[stat[i].ix];
|
||||
const double v = o->p[i] * ratio;
|
||||
o->p[i + 1] = v < 1.0 ? v : 1.0;
|
||||
}
|
||||
for (int i = 0; i < g; ++i) {
|
||||
const double S = rad_mtp_block_resid_sum(st[i], stat[i], o->p[i]);
|
||||
o->s[i] = S;
|
||||
const double den = S + (1.0 - o->p[i]);
|
||||
o->h[i] = (den > 0 && rad_spechub_finite(den)) ? S / den : 1.0;
|
||||
}
|
||||
o->s[g] = 0;
|
||||
o->h[g] = o->p[g];
|
||||
}
|
||||
|
||||
/* tau: the first i, counting down from g, whose uniform falls below h_i. The uniforms are keyed by
|
||||
* the block's first output position, so no row's own draws are reused. */
|
||||
static inline RAD_BLK_HD int rad_mtp_block_tau(const RadBlockPlan& pl, uint64_t seed,
|
||||
uint64_t pos0) {
|
||||
for (int i = pl.g; i > 0; --i)
|
||||
if (rad_spechub_uniform(seed, pos0, RAD_MTP_BLOCK_KEY_STOP + (uint64_t)i) < pl.h[i])
|
||||
return i;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* One lane's partials of the residual draw: `off` the off-support masses p * (w / sum) (slots whose
|
||||
* id is not among Q's), `all` the plain weights (the fallback draw from P itself), and the last
|
||||
* positive id of each, in the lane's slot order. */
|
||||
struct RadBlockLane { double off, all; int32_t last_off, last_all; };
|
||||
|
||||
static inline RAD_BLK_HD void rad_mtp_block_lane_add(RadBlockLane* a, const RadMtpCoupleState& s,
|
||||
const RadBlockStat& t, double p, int32_t id,
|
||||
float v, float top) {
|
||||
const double w = ::exp((double)v - top);
|
||||
a->all += w;
|
||||
if (w > 0) a->last_all = id;
|
||||
if (rad_mtp_block_find(s, id) >= s.count) {
|
||||
const double m = p * (w / t.sum);
|
||||
a->off += m;
|
||||
if (m > 0) a->last_off = id;
|
||||
}
|
||||
}
|
||||
|
||||
/* Y ~ max(p P - Q, 0) normalised (state s, row r, stat t) with the uniform u in [0, 1). The mass
|
||||
* is walked in a fixed order: the ids of Q (place k = 0 .. count-1, mass max(p pq[k] - q[k], 0)),
|
||||
* then the other live slots lane by lane (the lanes of the tree above, each lane's slots in
|
||||
* ascending order; the lane totals are added in lane order). The walk subtracts the masses from
|
||||
* c = u * total and stops at the first negative; inside the lane it stops in, the walk restarts
|
||||
* from the c at the lane's start, so the structure is exactly what the workgroup computes. When
|
||||
* the total underflows to zero (FP64 cancellation with p = 1: P == Q) Y is drawn from P itself
|
||||
* over all live slots in the same lane order, a branch that depends on (P, Q) only. False: no live
|
||||
* candidate. */
|
||||
static inline RAD_BLK_HD bool rad_mtp_block_resid_walk(const RadBlockRow& r,
|
||||
const RadMtpCoupleState& s,
|
||||
const RadBlockStat& t, double p, double u,
|
||||
const RadBlockLane* lane, int32_t* out) {
|
||||
double on[8];
|
||||
double total = 0;
|
||||
for (int k = 0; k < s.count; ++k) {
|
||||
on[k] = rad_spechub_positive(p * t.pq[k] - s.q[k]);
|
||||
total += on[k];
|
||||
}
|
||||
double offt = 0;
|
||||
for (int l = 0; l < RAD_MTP_BLOCK_LANES; ++l) offt += lane[l].off;
|
||||
total += offt;
|
||||
const bool resid = total > 0 && rad_spechub_finite(total);
|
||||
double c = resid ? u * total : u * t.sum;
|
||||
int32_t last = -1;
|
||||
if (resid) {
|
||||
for (int k = 0; k < s.count; ++k)
|
||||
if (on[k] > 0) { last = s.ids[k]; c -= on[k]; if (c < 0) { *out = last; return true; } }
|
||||
}
|
||||
for (int l = 0; l < RAD_MTP_BLOCK_LANES; ++l) {
|
||||
const double T = resid ? lane[l].off : lane[l].all;
|
||||
const int32_t ll = resid ? lane[l].last_off : lane[l].last_all;
|
||||
if (!(T > 0)) continue;
|
||||
if (ll >= 0) last = ll;
|
||||
if (c - T < 0) {
|
||||
double cl = c;
|
||||
int32_t lastl = -1;
|
||||
for (int64_t j = l; j < r.n; j += RAD_MTP_BLOCK_LANES) {
|
||||
if (!rad_mtp_block_live(r.ids[j], r.val[j])) continue;
|
||||
const double w = ::exp((double)r.val[j] - r.top);
|
||||
double m;
|
||||
if (resid) {
|
||||
if (rad_mtp_block_find(s, r.ids[j]) < s.count) continue;
|
||||
m = p * (w / t.sum);
|
||||
} else {
|
||||
m = w;
|
||||
}
|
||||
if (m > 0) { lastl = r.ids[j]; cl -= m; if (cl < 0) { *out = lastl; return true; } }
|
||||
}
|
||||
*out = lastl >= 0 ? lastl : ll;
|
||||
return *out >= 0;
|
||||
}
|
||||
c -= T;
|
||||
}
|
||||
*out = last;
|
||||
return last >= 0;
|
||||
}
|
||||
|
||||
static inline RAD_BLK_HD bool rad_mtp_block_resid_draw(const RadBlockRow& r,
|
||||
const RadMtpCoupleState& s,
|
||||
const RadBlockStat& t, double p, double u,
|
||||
int32_t* out) {
|
||||
RadBlockLane lane[RAD_MTP_BLOCK_LANES];
|
||||
for (int l = 0; l < RAD_MTP_BLOCK_LANES; ++l) lane[l] = RadBlockLane{ 0, 0, -1, -1 };
|
||||
for (int64_t j = 0; j < r.n; ++j)
|
||||
if (rad_mtp_block_live(r.ids[j], r.val[j]))
|
||||
rad_mtp_block_lane_add(&lane[j % RAD_MTP_BLOCK_LANES], s, t, p, r.ids[j], r.val[j],
|
||||
r.top);
|
||||
return rad_mtp_block_resid_walk(r, s, t, p, u, lane, out);
|
||||
}
|
||||
|
||||
/* The whole decision on the host: rows[0 .. g-1] / st[0 .. g-1] are the block's verify rows and
|
||||
* their coupled states (round i + 1 at row i), pos0 the first row's output position. Writes tau and
|
||||
* *y; *y = -1 when tau == g (the g-th row's ordinary draw stands). False for an invalid target. */
|
||||
static inline RAD_BLK_HD bool rad_mtp_block_decide(const RadMtpCoupleState* st,
|
||||
const RadBlockRow* rows, int g, uint64_t seed,
|
||||
uint64_t pos0, int* tau, int32_t* y) {
|
||||
RadBlockStat stat[RAD_MTP_BLOCK_MAX];
|
||||
RadBlockPlan pl;
|
||||
if (g < 1 || g > RAD_MTP_BLOCK_MAX) return false;
|
||||
for (int i = 0; i < g; ++i)
|
||||
if (!rad_mtp_block_stat(rows[i], st[i], &stat[i])) return false;
|
||||
rad_mtp_block_plan(st, stat, g, &pl);
|
||||
const int t = rad_mtp_block_tau(pl, seed, pos0);
|
||||
*tau = t;
|
||||
*y = -1;
|
||||
if (t >= g) return true;
|
||||
const double u = rad_spechub_uniform(seed, pos0 + (uint64_t)t, RAD_SAMPLE_KEY_RESID);
|
||||
return rad_mtp_block_resid_draw(rows[t], st[t], stat[t], pl.p[t], u, y);
|
||||
}
|
||||
|
||||
#endif /* __cplusplus */
|
||||
#endif /* RAD_MTP_BLOCK_H */
|
||||
@@ -0,0 +1,442 @@
|
||||
/* rad_mtp_rrs.h -- recursive rejection sampling over a node's SIBLING drafts under
|
||||
* --draft-coupling on: the draft side (children sampled without replacement from Q) and the
|
||||
* verify side (the walk over a node's children against the target's P), as plain code the host
|
||||
* oracle, the device kernels and the tests share, so they cannot drift. Traversal verification
|
||||
* (abi/rad_mtp_traversal.h) walks nodes that drafted several children; the serial head of this
|
||||
* engine drafts one (nkids <= 1, the chain), so nothing in the engine draws siblings yet: the
|
||||
* header is the verify side's definition and its tests (tests/mtp_rrs_test.cpp). The short proof:
|
||||
*
|
||||
* Draft. A node whose head pass left the law Q (the FP64 T1 softmax of the reranked top 8,
|
||||
* rad_mtp_couple_build_q) drafts its children x_1, x_2, ... by Gumbel-top-k over log Q: add an
|
||||
* independent Gumbel to every log q_i and take the entries in descending order. That is sampling
|
||||
* without replacement (Plackett-Luce): x_1 ~ Q, x_2 ~ Q(. | not x_1), ... The first m of them are
|
||||
* the node's children, m chosen by anything that does not read the values x_j it applies to
|
||||
* (a fixed count, or a rule over the slot priorities, the j-th largest q of Q, never the drawn
|
||||
* token).
|
||||
*
|
||||
* Verify (Sequoia, Chen et al. 2024, Alg. 1; SpecInfer's multi-step verification with the draft
|
||||
* law renormalised after each removal). P_1 = the target's law, q_1 = Q. For i = 1..m:
|
||||
* accept x_i with probability min(1, P_i(x_i) / q_i(x_i));
|
||||
* on rejection P_{i+1} = norm(max(P_i - q_i, 0)), q_{i+1} = q_i without x_i, renormalised.
|
||||
* All rejected: the token is a draw from P_{m+1}. Exactness (induction on m): after a rejection of
|
||||
* the first draft the continuation depends on x_1 only through q_2, and P_2 = norm(max(P - q, 0))
|
||||
* does not depend on x_1 at all, so by the hypothesis it emits ~ P_2 whatever x_1 was; then
|
||||
* P(emit y) = sum_x q(x) min(1, P(x)/q(x)) [x = y] + P(reject) P_2(y) = min(P, q)(y) +
|
||||
* max(P - q, 0)(y) = P(y). The emitted token is the accepted child's token, or a residual draw that
|
||||
* has no mass on any rejected child (P_{i+1}(x_i) = 0 after a rejection), so the core's rule
|
||||
* "follow the first child whose token is the sampler's token at the row" (ADV_ACCEPT) walks exactly
|
||||
* the decision made here and needs no change.
|
||||
*
|
||||
* Wire: the node's RadMtpCoupleState holds Q (ids, q), the children in draft order in ids[0 ..
|
||||
* nkids), x = ids[0]. A state with nkids <= 1 is the chain's (rad_mtp_couple_decide, bit for bit).
|
||||
*/
|
||||
#ifndef RAD_MTP_RRS_H
|
||||
#define RAD_MTP_RRS_H
|
||||
|
||||
#include "rad_spechub.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
|
||||
#ifdef __HIPCC__
|
||||
#define RAD_RRS_HD __host__ __device__
|
||||
#else
|
||||
#define RAD_RRS_HD
|
||||
#endif
|
||||
|
||||
#define RAD_MTP_RRS_KEY_TREE 0x4d54524545474d42ull /* the draft's Gumbel stream */
|
||||
#define RAD_MTP_RRS_KEY_ACCEPT 0x41435054ull
|
||||
|
||||
static inline RAD_RRS_HD uint64_t rad_mtp_rrs_mix(uint64_t z) {
|
||||
z += 0x9e3779b97f4a7c15ull;
|
||||
z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ull;
|
||||
z = (z ^ (z >> 27)) * 0x94d049bb133111ebull;
|
||||
return z ^ (z >> 31);
|
||||
}
|
||||
|
||||
/* The open-interval uniform of candidate `c` of draft node `node`: (seed, base) name the draft
|
||||
* stream (the request's seed and its pre-commit output length, which no later step reuses). */
|
||||
static inline RAD_RRS_HD double rad_mtp_rrs_gumbel_u(uint64_t seed, uint64_t base,
|
||||
uint64_t node, int c) {
|
||||
uint64_t z = rad_mtp_rrs_mix(seed ^ RAD_MTP_RRS_KEY_TREE);
|
||||
z = rad_mtp_rrs_mix(z ^ base);
|
||||
z = rad_mtp_rrs_mix(z + node * 16u + (uint64_t)c);
|
||||
return ((double)(z >> 11) + 0.5) * 0x1p-53;
|
||||
}
|
||||
|
||||
/* Gumbel-top-k order of Q's support: order[0 .. s.count) are indices into s.ids, the draft order
|
||||
* (descending of log q + Gumbel, ties to the lower index). Draws one uniform per support entry from
|
||||
* the state's own draw, node `node`. */
|
||||
static inline RAD_RRS_HD void rad_mtp_rrs_order(const RadMtpCoupleState& s, uint64_t node,
|
||||
int* order) {
|
||||
double key[8];
|
||||
for (int i = 0; i < s.count; ++i) {
|
||||
const double u = rad_mtp_rrs_gumbel_u(s.draw.seed, s.draw.base, node, i);
|
||||
key[i] = ::log(s.q[i]) - ::log(-::log(u));
|
||||
order[i] = i;
|
||||
}
|
||||
for (int i = 1; i < s.count; ++i) { /* insertion sort, stable */
|
||||
const int o = order[i];
|
||||
int j = i;
|
||||
while (j > 0 && key[order[j - 1]] < key[o]) { order[j] = order[j - 1]; --j; }
|
||||
order[j] = o;
|
||||
}
|
||||
}
|
||||
|
||||
/* Draw the node's children: reorder Q's support into the draft order (ids and q together), set
|
||||
* x = ids[0] and nkids = `nkids`. */
|
||||
static inline RAD_RRS_HD void rad_mtp_rrs_draw(RadMtpCoupleState* s, uint64_t node, int nkids) {
|
||||
int order[8];
|
||||
rad_mtp_rrs_order(*s, node, order);
|
||||
int32_t ids[8];
|
||||
double q[8];
|
||||
for (int i = 0; i < s->count; ++i) { ids[i] = s->ids[order[i]]; q[i] = s->q[order[i]]; }
|
||||
for (int i = 0; i < s->count; ++i) { s->ids[i] = ids[i]; s->q[i] = q[i]; }
|
||||
s->x = s->ids[0];
|
||||
s->nkids = nkids < s->count ? nkids : s->count;
|
||||
}
|
||||
|
||||
/* The SLOT priorities of a node's law: slot j carries the log of the j-th LARGEST q of Q
|
||||
* (descending, ties by position), -inf past the support. They are a function of Q alone, never of
|
||||
* which token was drawn into which slot, so a rule that reads only them admits children by a
|
||||
* quantity independent of the values the children take. `s` is read before the draw reorders it
|
||||
* or after (the multiset of q is the same). */
|
||||
static inline RAD_RRS_HD void rad_mtp_rrs_slot_logq(const RadMtpCoupleState& s, float* ov) {
|
||||
double qs[8];
|
||||
const int n = s.count < 8 ? s.count : 8;
|
||||
for (int i = 0; i < n; ++i) qs[i] = s.q[i];
|
||||
for (int i = 1; i < n; ++i) {
|
||||
const double v = qs[i];
|
||||
int j = i;
|
||||
while (j > 0 && qs[j - 1] < v) { qs[j] = qs[j - 1]; --j; }
|
||||
qs[j] = v;
|
||||
}
|
||||
for (int c = 0; c < 8; ++c) ov[c] = c < n ? (float)::log(qs[c]) : -INFINITY;
|
||||
}
|
||||
|
||||
/* The longest prefix of the state's children that are the first `n` of `kid[]` (the tree's
|
||||
* children of this row, in node order, repeats dropped): what a verify may keep when a window cut
|
||||
* the tree short. 0 when even the first differs. */
|
||||
static inline RAD_RRS_HD int rad_mtp_rrs_prefix(const RadMtpCoupleState& s, const int32_t* kid,
|
||||
int n) {
|
||||
const int have = s.nkids >= 1 ? s.nkids : 1;
|
||||
int m = 0;
|
||||
while (m < have && m < n && m < s.count && s.ids[m] == kid[m]) ++m;
|
||||
return s.nkids >= 2 ? m : (n >= 1 && s.x == kid[0] ? 1 : 0);
|
||||
}
|
||||
|
||||
/* The acceptance uniform of the i-th child at output position `pos`: the first is the chain's. */
|
||||
static inline RAD_RRS_HD double rad_mtp_rrs_uaccept(uint64_t seed, uint64_t pos, int i) {
|
||||
return rad_spechub_uniform(seed, pos,
|
||||
i == 0 ? (uint64_t)RAD_SAMPLE_KEY_ACCEPT
|
||||
: RAD_MTP_RRS_KEY_ACCEPT ^ rad_mtp_rrs_mix((uint64_t)i));
|
||||
}
|
||||
|
||||
/* The verify of a node with nkids >= 2 children: the recursion above over the sampler's surviving
|
||||
* candidates (ids/val, n of them, FP64 P = softmax of val). Writes the emitted token to *out and
|
||||
* returns true, or false for an invalid target (the row keeps the ordinary token).
|
||||
*
|
||||
* The decision reads the live candidates (id >= 0, value not -inf) in ascending order through a
|
||||
* view `C::each(f)`, f(id, w, k) -> bool (false stops): w = exp(val - top) in FP64, k the id's slot
|
||||
* in the state's support (the first match) or s.count when it is outside. The host view
|
||||
* (RadRrsHostCands) computes them on the fly; the device verify (plugin/spechub/spechub.hip)
|
||||
* compacts the live candidates and computes every w and k with the whole workgroup, then runs this
|
||||
* same function on one lane over the stored values, so the ordered sums, and with them the token,
|
||||
* are the host's. `pq_out` and `sum_out` (optional) hand back P's masses on the support and their
|
||||
* normaliser (the export). */
|
||||
template <class C>
|
||||
static inline RAD_RRS_HD bool rad_mtp_rrs_decide_over(const RadMtpCoupleState& s, const C& cs,
|
||||
uint64_t seed, uint64_t pos, int32_t* out,
|
||||
double* pq_out = nullptr,
|
||||
double* sum_out = nullptr) {
|
||||
double sum = 0, pq[8] = {}, wout = 0;
|
||||
cs.each([&](int32_t, double w, int k) {
|
||||
sum += w;
|
||||
if (k < s.count) pq[k] += w; else wout += w;
|
||||
return true;
|
||||
});
|
||||
if (!(sum > 0) || !rad_spechub_finite(sum)) return false;
|
||||
if (pq_out) for (int k = 0; k < 8; ++k) pq_out[k] = pq[k];
|
||||
if (sum_out) *sum_out = sum;
|
||||
/* P over Q's support (normalised), and the off-support mass's scale `so` (P_i(y) = so * w / sum
|
||||
* there). qr: the draft law with the drawn children removed. */
|
||||
double r[8], qr[8], so = 1.0;
|
||||
for (int k = 0; k < s.count; ++k) { r[k] = pq[k] / sum; qr[k] = s.q[k]; }
|
||||
const double pout = wout / sum;
|
||||
bool direct = false;
|
||||
for (int i = 0; i < s.nkids && !direct; ++i) {
|
||||
double sq = 0;
|
||||
for (int k = 0; k < s.count; ++k) sq += qr[k];
|
||||
if (!(sq > 0)) break;
|
||||
const double qx = qr[i] / sq;
|
||||
if (r[i] >= qx || rad_mtp_rrs_uaccept(seed, pos, i) * qx < r[i]) {
|
||||
*out = s.ids[i];
|
||||
return true;
|
||||
}
|
||||
double z = so * pout;
|
||||
for (int k = 0; k < s.count; ++k) {
|
||||
const double d = r[k] - qr[k] / sq;
|
||||
r[k] = d > 0 ? d : 0;
|
||||
z += r[k];
|
||||
}
|
||||
if (!(z > 0) || !rad_spechub_finite(z)) { direct = true; break; }
|
||||
for (int k = 0; k < s.count; ++k) r[k] /= z;
|
||||
so /= z;
|
||||
qr[i] = 0;
|
||||
}
|
||||
const double u = rad_spechub_uniform(seed, pos, RAD_SAMPLE_KEY_RESID);
|
||||
double c;
|
||||
int32_t last = -1;
|
||||
if (direct) {
|
||||
c = u * sum;
|
||||
bool hit = false;
|
||||
cs.each([&](int32_t id, double w, int) {
|
||||
if (w > 0) { last = id; c -= w; if (c < 0) { hit = true; return false; } }
|
||||
return true;
|
||||
});
|
||||
*out = last;
|
||||
(void)hit;
|
||||
return true;
|
||||
}
|
||||
double total = 0;
|
||||
for (int k = 0; k < s.count; ++k) total += r[k];
|
||||
total += so * pout;
|
||||
c = u * total;
|
||||
unsigned seen = 0;
|
||||
bool hit = false;
|
||||
cs.each([&](int32_t id, double w, int k) {
|
||||
double m;
|
||||
if (k < s.count) {
|
||||
if (seen & (1u << k)) return true;
|
||||
seen |= 1u << k;
|
||||
m = r[k];
|
||||
} else {
|
||||
m = so * (w / sum);
|
||||
}
|
||||
if (m > 0) { last = id; c -= m; if (c < 0) { hit = true; return false; } }
|
||||
return true;
|
||||
});
|
||||
*out = last;
|
||||
(void)hit;
|
||||
return last >= 0;
|
||||
}
|
||||
|
||||
/* The host view: the candidates as the sampler wrote them, weights computed as they are read. */
|
||||
struct RadRrsHostCands {
|
||||
const RadMtpCoupleState& s;
|
||||
const int32_t* ids; const float* val; int64_t n; float top;
|
||||
template <class F> RAD_RRS_HD void each(F&& f) const {
|
||||
for (int64_t j = 0; j < n; ++j) {
|
||||
if (ids[j] < 0 || val[j] == -INFINITY) continue;
|
||||
int k = 0;
|
||||
while (k < s.count && ids[j] != s.ids[k]) ++k;
|
||||
if (!f(ids[j], ::exp((double)val[j] - top), k)) return;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
static inline RAD_RRS_HD bool rad_mtp_rrs_decide(const RadMtpCoupleState& s, const int32_t* ids,
|
||||
const float* val, int64_t n, int64_t vocab,
|
||||
uint64_t seed, uint64_t pos, int32_t* out) {
|
||||
float top = -INFINITY;
|
||||
for (int64_t j = 0; j < n; ++j) {
|
||||
if (ids[j] < 0) continue;
|
||||
if (ids[j] >= vocab || val[j] != val[j] || val[j] == INFINITY) return false;
|
||||
if (val[j] > top) top = val[j];
|
||||
}
|
||||
if (top == -INFINITY) return false;
|
||||
return rad_mtp_rrs_decide_over(s, RadRrsHostCands{ s, ids, val, n, top }, seed, pos, out);
|
||||
}
|
||||
|
||||
/* ================================================================== RheoSampling siblings
|
||||
*
|
||||
* --draft-siblings rheo (--draft-rheo-m m). Hu et al. 2025 (arXiv 2502.18779, Thm 8, the greedy
|
||||
* multi-draft verifier) and RheoSampling (arXiv 2609.21827): instead of Gumbel-top-k siblings, a
|
||||
* node's children are
|
||||
* T = the m tokens of largest Q, in descending q order (deterministic, slots 0 .. m-1), and
|
||||
* u ~ Qt, ONE token sampled from the tail law Qt(x) = Q(x) / z over the support outside T,
|
||||
* z = Q(outside T), in slot m;
|
||||
* the draft order stored in the state is ids = [T..., u, the rest of the support in descending q],
|
||||
* scheme = m + 1. A node whose support has no more than m tokens has no tail child (all of it
|
||||
* is T).
|
||||
*
|
||||
* Verify (derived here, not quoted; the law is checked by tests/mtp_rrs_test.cpp by exhaustive
|
||||
* enumeration). P = the target's law, children present = the first nkids of the draft order.
|
||||
* tail child present (nkids > |T|, i.e. with a prefix draft order every T token is a child):
|
||||
* accept u with probability min(1, P(u) / Qt(u)) -> emit u
|
||||
* else emit y ~ R / |R|, R(y) = P(y) y in T or off Q's support,
|
||||
* R(y) = max(P(y) - Qt(y), 0) y in the tail support (R(u) = 0 here)
|
||||
* otherwise (the tail slot was pruned or cut by a window, or Q has no tail): emit y ~ P directly.
|
||||
* Exactness: P(emit y) = min(P, Qt)(y) [y in tail] + (1 - A) R(y) / |R| with |R| = 1 - A,
|
||||
* A = sum_tail min(P, Qt), and min(P, Qt) + R = P on the tail, R = P elsewhere: P(emit y) = P(y).
|
||||
* It needs only that u ~ Qt independently of the verifier's uniforms (a separate draft stream), and
|
||||
* that WHICH slots exist depends on Q and the tree's budget alone (never on the value of u): both
|
||||
* hold, the slot priorities are rad_mtp_rrs_slot_logq_rheo. The emitted token is a child with
|
||||
* probability P(T) + A = sum_T P + sum_tail min(P, Qt), Thm 8's value, and a residual draw never
|
||||
* lands on u (R(u) = 0 when u was rejected), so the core's "follow the first child whose token is
|
||||
* the sampler's" walks the decision made here.
|
||||
* m = 0 is the single-draft maximal coupling of the chain (rad_mtp_couple_decide) with the sampled
|
||||
* child in slot 0.
|
||||
*/
|
||||
/* The candidate index of the tail draw in the draft stream (0..7 are Gumbel's). */
|
||||
#define RAD_MTP_RRS_KEY_TAIL_C 8
|
||||
|
||||
/* Slot priorities of a rheo node (functions of Q alone, non-increasing): slots 0 .. m-1 carry the
|
||||
* log of the j-th largest q, slot m RheoSampling's proxy log min{q_(m-1), z} (z = the tail mass;
|
||||
* with m = 0, z = 1), -inf for the other slots and for slots past the support. */
|
||||
static inline RAD_RRS_HD void rad_mtp_rrs_slot_logq_rheo(const RadMtpCoupleState& s, int m,
|
||||
float* ov) {
|
||||
double qs[8];
|
||||
const int n = s.count < 8 ? s.count : 8;
|
||||
for (int i = 0; i < n; ++i) qs[i] = s.q[i];
|
||||
for (int i = 1; i < n; ++i) {
|
||||
const double v = qs[i];
|
||||
int j = i;
|
||||
while (j > 0 && qs[j - 1] < v) { qs[j] = qs[j - 1]; --j; }
|
||||
qs[j] = v;
|
||||
}
|
||||
const int nt = m < n ? m : n;
|
||||
for (int c = 0; c < 8; ++c) ov[c] = c < nt ? (float)::log(qs[c]) : -INFINITY;
|
||||
if (n > nt) {
|
||||
double z = 0;
|
||||
for (int i = nt; i < n; ++i) z += qs[i];
|
||||
if (z > 1) z = 1;
|
||||
const double ref = nt > 0 ? qs[nt - 1] : 1.0;
|
||||
ov[nt] = (float)::log(z < ref ? z : ref);
|
||||
}
|
||||
}
|
||||
|
||||
/* Draw a rheo node's children: reorder Q's support into [top-m by q desc, the sampled tail child,
|
||||
* the rest by q desc], set x = ids[0], scheme = m + 1 and nkids = min(nkids, children possible).
|
||||
* The tail child is the inverse-CDF draw of Qt with the draft stream's uniform of (seed, base,
|
||||
* node). */
|
||||
static inline RAD_RRS_HD void rad_mtp_rrs_draw_rheo_u(RadMtpCoupleState* s, double ut, int nkids,
|
||||
int m) {
|
||||
int ord[8];
|
||||
const int n = s->count;
|
||||
for (int i = 0; i < n; ++i) ord[i] = i;
|
||||
for (int i = 1; i < n; ++i) { /* descending q, stable */
|
||||
const int o = ord[i];
|
||||
int j = i;
|
||||
while (j > 0 && s->q[ord[j - 1]] < s->q[o]) { ord[j] = ord[j - 1]; --j; }
|
||||
ord[j] = o;
|
||||
}
|
||||
const int nt = m < n ? m : n;
|
||||
if (n > nt) {
|
||||
double z = 0;
|
||||
for (int i = nt; i < n; ++i) z += s->q[ord[i]];
|
||||
double c = ut * z;
|
||||
int pick = n - 1;
|
||||
for (int i = nt; i < n; ++i) { c -= s->q[ord[i]]; if (c < 0) { pick = i; break; } }
|
||||
const int o = ord[pick];
|
||||
for (int i = pick; i > nt; --i) ord[i] = ord[i - 1];
|
||||
ord[nt] = o;
|
||||
}
|
||||
int32_t ids[8];
|
||||
double q[8];
|
||||
for (int i = 0; i < n; ++i) { ids[i] = s->ids[ord[i]]; q[i] = s->q[ord[i]]; }
|
||||
for (int i = 0; i < n; ++i) { s->ids[i] = ids[i]; s->q[i] = q[i]; }
|
||||
const int cap = nt + (n > nt ? 1 : 0);
|
||||
s->x = s->ids[0];
|
||||
s->scheme = m + 1;
|
||||
s->nkids = nkids < cap ? nkids : cap;
|
||||
}
|
||||
static inline RAD_RRS_HD void rad_mtp_rrs_draw_rheo(RadMtpCoupleState* s, uint64_t node, int nkids,
|
||||
int m) {
|
||||
const double ut =
|
||||
rad_mtp_rrs_gumbel_u(s->draw.seed, s->draw.base, node, RAD_MTP_RRS_KEY_TAIL_C);
|
||||
rad_mtp_rrs_draw_rheo_u(s, ut, nkids, m);
|
||||
}
|
||||
|
||||
/* The verify of a rheo node (any nkids >= 0): the rule above. Same contract as
|
||||
* rad_mtp_rrs_decide. */
|
||||
static inline RAD_RRS_HD bool rad_mtp_rrs_decide_rheo_u(const RadMtpCoupleState& s,
|
||||
const int32_t* ids, const float* val,
|
||||
int64_t n, int64_t vocab, double u_accept,
|
||||
double u_resid, int32_t* out) {
|
||||
float top = -INFINITY;
|
||||
for (int64_t j = 0; j < n; ++j) {
|
||||
if (ids[j] < 0) continue;
|
||||
if (ids[j] >= vocab || val[j] != val[j] || val[j] == INFINITY) return false;
|
||||
if (val[j] > top) top = val[j];
|
||||
}
|
||||
if (top == -INFINITY) return false;
|
||||
double sum = 0, pq[8] = {};
|
||||
for (int64_t j = 0; j < n; ++j) {
|
||||
if (ids[j] < 0 || val[j] == -INFINITY) continue;
|
||||
const double w = ::exp((double)val[j] - top);
|
||||
sum += w;
|
||||
for (int k = 0; k < s.count; ++k)
|
||||
if (ids[j] == s.ids[k]) { pq[k] += w; break; }
|
||||
}
|
||||
if (!(sum > 0) || !rad_spechub_finite(sum)) return false;
|
||||
const int m = s.scheme - 1;
|
||||
const int nt = m < s.count ? m : s.count;
|
||||
const bool tail = m >= 0 && s.count > nt && s.nkids > nt;
|
||||
double qt[8] = {}, r[8] = {};
|
||||
bool dominated = true;
|
||||
for (int k = 0; k < s.count; ++k) pq[k] /= sum;
|
||||
if (tail) {
|
||||
double z = 0;
|
||||
for (int k = nt; k < s.count; ++k) z += s.q[k];
|
||||
for (int k = nt; k < s.count; ++k) {
|
||||
const double v = nt == 0 ? s.q[k] : s.q[k] / z;
|
||||
qt[k] = v > 1 ? 1 : v; /* clamp: rounding must not push a one-token tail past 1 */
|
||||
dominated = dominated && pq[k] >= qt[k];
|
||||
}
|
||||
for (int k = 0; k < s.count; ++k)
|
||||
r[k] = k < nt ? pq[k] : rad_spechub_positive(pq[k] - qt[k]);
|
||||
}
|
||||
/* mass of candidate j in R (the tail case) or in P (otherwise); Q tokens count once. */
|
||||
unsigned seen = 0;
|
||||
auto mass = [&](int64_t j) -> double {
|
||||
if (ids[j] < 0 || val[j] == -INFINITY) return 0;
|
||||
for (int k = 0; k < s.count; ++k)
|
||||
if (s.ids[k] == ids[j]) {
|
||||
if (seen & (1u << k)) return 0;
|
||||
seen |= 1u << k;
|
||||
return tail ? r[k] : pq[k];
|
||||
}
|
||||
return ::exp((double)val[j] - top) / sum;
|
||||
};
|
||||
double resid = 0;
|
||||
if (tail) {
|
||||
for (int64_t j = 0; j < n; ++j) resid += mass(j);
|
||||
seen = 0;
|
||||
}
|
||||
if (!tail || (!dominated && !(resid > 0 && rad_spechub_finite(resid)))) {
|
||||
double c = u_resid * sum; /* P itself, in the sampler's candidate order */
|
||||
int32_t last = -1;
|
||||
for (int64_t j = 0; j < n; ++j)
|
||||
if (ids[j] >= 0 && val[j] != -INFINITY) {
|
||||
const double w = ::exp((double)val[j] - top);
|
||||
if (w > 0) { last = ids[j]; c -= w; if (c < 0) { *out = last; return true; } }
|
||||
}
|
||||
*out = last;
|
||||
return last >= 0;
|
||||
}
|
||||
const int iu = nt;
|
||||
if (pq[iu] >= qt[iu] || u_accept * qt[iu] < pq[iu]) {
|
||||
*out = s.ids[iu];
|
||||
return true;
|
||||
}
|
||||
double c = u_resid * resid;
|
||||
int32_t last = -1;
|
||||
for (int64_t j = 0; j < n; ++j) {
|
||||
if (ids[j] == s.ids[iu]) continue;
|
||||
const double mm = mass(j);
|
||||
if (mm > 0) { last = ids[j]; c -= mm; if (c < 0) { *out = last; return true; } }
|
||||
}
|
||||
*out = last;
|
||||
return last >= 0;
|
||||
}
|
||||
static inline RAD_RRS_HD bool rad_mtp_rrs_decide_rheo(const RadMtpCoupleState& s,
|
||||
const int32_t* ids, const float* val,
|
||||
int64_t n, int64_t vocab, uint64_t seed,
|
||||
uint64_t pos, int32_t* out) {
|
||||
return rad_mtp_rrs_decide_rheo_u(s, ids, val, n, vocab,
|
||||
rad_spechub_uniform(seed, pos, RAD_SAMPLE_KEY_ACCEPT),
|
||||
rad_spechub_uniform(seed, pos, RAD_SAMPLE_KEY_RESID), out);
|
||||
}
|
||||
|
||||
#endif /* __cplusplus */
|
||||
#endif /* RAD_MTP_RRS_H */
|
||||
@@ -0,0 +1,565 @@
|
||||
/* rad_mtp_traversal.h -- Traversal Verification (Weng et al., arXiv 2505.12398) of a draft under
|
||||
* sampling (--draft-verify traversal, needs --draft-coupling on). The walk is defined on a tree;
|
||||
* the serial head of this engine drafts a chain, a tree of one child a node, which the sampler
|
||||
* stages (core/sample/sampler.cpp). Plain code shared by the host oracle, the device kernel and the
|
||||
* tests; the short form of the argument:
|
||||
*
|
||||
* Row-wise verification (rad_mtp_rrs_decide) decides each node on its own. Traversal verification
|
||||
* decides a whole ROOT-TO-LEAF PATH at once, bottom-up, and so can accept a longer prefix from the
|
||||
* same tree (for a chain it is Block Verification, never worse than token-level rejection
|
||||
* sampling).
|
||||
*
|
||||
* State of a node v during the walk: p_v (its acceptance rate, a sequence-level ratio), the target
|
||||
* law M_b(.|v) restricted to what has not been rejected below it (r), and the law the NEXT child of
|
||||
* v was drawn from.
|
||||
* - A child c of v enters with p_c = min(1, p_v * r(c)/qn(c)), qn the law c was drawn from GIVEN
|
||||
* the children tried before it.
|
||||
* - The walk descends to the first leaf and tests eta < p_leaf. Accept: the path is accepted and
|
||||
* the final token is drawn from that node's current residual law r (the plain target if none of
|
||||
* its children was rejected). Reject: the leaf is deleted and its parent v is updated:
|
||||
* S = sum_x [ p_v r(x) - qn(x) ]+
|
||||
* p_v' = S / (S + 1 - p_v)
|
||||
* r' = [ p_v r - qn ]+ / S
|
||||
* and the walk continues with v's next child, or tests v itself once it has none.
|
||||
* The walk keeps the PRODUCT m(x) = p_v r(x) (on the draft support per slot, and one number for
|
||||
* everything off it, where qn is zero), which is all the rules read: p_c = min(1, m(c)/qn(c)), and
|
||||
* the update is one division, m' = [m - qn]+ / (S + 1 - p_v), p_v' = S / (S + 1 - p_v), the
|
||||
* off-support mass scaled alike; the final token is drawn in proportion to m. A node entered with
|
||||
* rate p keeps its target law unscaled and the factor p beside it (sc) until its first child is
|
||||
* rejected, so entering a node costs one division (the child's rate) and no pass over its law.
|
||||
* Exactness (Theorem 3.3 of the paper, Lemma A.2 by induction over a node's descendants): the
|
||||
* subtree of v is accepted with probability p_v and, given that, the token after v follows r. One
|
||||
* step of the induction, for a child drawn from ANY law qn that may depend on the children before
|
||||
* it: P(accepted through a child x) = qn(x) min(1, p_v r(x)/qn(x)) = min(qn(x), p_v r(x));
|
||||
* P(the child's subtree is rejected) = 1 - p_v + S; the rest then accepts with p_v' and r', which
|
||||
* adds (1 - p_v + S) p_v' r'(x) = [p_v r(x) - qn(x)]+, and the two sum to p_v r(x). It needs the
|
||||
* tree's shape to be independent of the drawn tokens (a chain's is), and each child's own law:
|
||||
* - Gumbel-top-k siblings (the default, Plackett-Luce without replacement): qn is the node's Q
|
||||
* with the children already tried removed, renormalised;
|
||||
* - RheoSampling siblings (state.scheme = m + 1, abi/rad_mtp_rrs.h): the
|
||||
* sampled tail child is tried FIRST with qn = Qt, the tail law, then the deterministic top-q
|
||||
* children in their order, each with qn = a point mass on its token. A point mass accepts with
|
||||
* p_v r(c) and leaves r without c; tried in this order the node's children take
|
||||
* sum_tail min(P, Qt) + P(T) of the target, the greedy multi-draft verifier's value (Hu et al.
|
||||
* 2025, Thm 8).
|
||||
* tests/mtp_rrs_test.cpp checks the walk by exact enumeration and by chi-square, and shows that
|
||||
* plausible mistakes (token-level ratios, no (1 - p) term, with-replacement update for
|
||||
* without-replacement drafts, a rheo node walked as a Gumbel one) fail the same statistic.
|
||||
*
|
||||
* THE TARGET LAW IN FIXED POINT. The walk reads a row's target law only through its mass on the
|
||||
* node's draft support (eight ids), the mass off it and the total; the final token needs the
|
||||
* off-support candidates in order. Each live candidate's weight is an INTEGER:
|
||||
*
|
||||
* m_j = floor(2^40 * e(val_j - top)), e(x) = rad_mtp_trav_mass's FP32 exponential
|
||||
*
|
||||
* (top the row's largest value; the scale drops a bit per doubling of the plane past 4096 slots so
|
||||
* a row's total stays below 2^53). Integer addition is associative, so the sums are the same bits
|
||||
* whatever order a workgroup adds them in: the device kernel (plugin/spechub/spechub.hip) splits a
|
||||
* row over its threads any way it likes and still equals this header's serial loops, with no
|
||||
* reduction tree to mirror. e() is basic FP32 arithmetic and integer shifts, identical on host and
|
||||
* device (no libm call, no contraction: -ffp-contract=off, and the attribute below for a host
|
||||
* build that enables FMA).
|
||||
* Why FP32 suffices: the algorithm is exact for whatever positive weights define the law, as long
|
||||
* as every decision reads the same ones, which the integers guarantee. The law it realises is P~(y)
|
||||
* = m_y / sum m, within 2^-22 relative per candidate (e's error, tests/mtp_rrs_test.cpp checks it)
|
||||
* plus 2^-40 absolute of the softmax of the sampler's FP32 candidates: the accuracy class of the
|
||||
* uncoupled sample_pick (FP32 expf, FP32 running sum, a 24-bit uniform), which is the law a request
|
||||
* gets without speculation. The 8-wide FP64 sums of the walk are a fixed tree (rad_mtp_trav_sum8),
|
||||
* so a device may run them on one lane or across eight.
|
||||
*
|
||||
* Wire: no new state. The walk reads the same RadMtpCoupleState rows as the row-wise verify and
|
||||
* writes the SAME plane the core already walks (ADV_ACCEPT: the first child whose token is the
|
||||
* sampler's token at the row): on the accepted path every row's token is its path child's token and
|
||||
* the last row's token is the final one; the other rows are not on the walk and keep the pick.
|
||||
*/
|
||||
#ifndef RAD_MTP_TRAVERSAL_H
|
||||
#define RAD_MTP_TRAVERSAL_H
|
||||
|
||||
#include "rad_spechub.h"
|
||||
#include "rad_mtp_rrs.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
|
||||
#define RAD_MTP_TRAV_MAX_DEPTH 16
|
||||
#define RAD_MTP_TRAV_MAX_ROWS 64 /* rows of one request the walk reads (first ones) */
|
||||
#define RAD_MTP_TRAV_KEY 0x54524156ull /* "TRAV": the walk's acceptance uniforms */
|
||||
#define RAD_MTP_TRAV_QBITS 40 /* a candidate's mass unit: 2^-40 of the top's */
|
||||
|
||||
/* A host build with FMA enabled must not contract the exponential's products into its sums: the
|
||||
* device does not (-ffp-contract=off), and the masses have to be the same bits. */
|
||||
#if defined(__GNUC__) && !defined(__clang__)
|
||||
#define RAD_TRAV_STRICT __attribute__((optimize("fp-contract=off")))
|
||||
#else
|
||||
#define RAD_TRAV_STRICT
|
||||
#endif
|
||||
|
||||
/* Test-only switches; the engine passes the zero value. */
|
||||
struct RadMtpTravOpt {
|
||||
int ctl = 0; /* negative controls: 1 token-level ratios, 2 no (1 - p) term, 3 q never
|
||||
renormalised (the with-replacement update on without-replacement drafts),
|
||||
4 a RheoSampling node walked as a Gumbel one */
|
||||
/* Enumeration (tests): >= 0 replaces the uniforms -- test number `accept_at` (1-based) accepts
|
||||
* and every earlier one rejects; `p_test[i]` receives the acceptance rate of test i + 1 and
|
||||
* `*n_tests` their count. */
|
||||
int accept_at = -1;
|
||||
double* p_test = nullptr;
|
||||
int* n_tests = nullptr;
|
||||
int max_tests = 0;
|
||||
double u_final = -1.0; /* >= 0: the final token's uniform (rad_mtp_trav_walk) */
|
||||
};
|
||||
|
||||
struct RadMtpTravOut {
|
||||
int n = 0; /* nodes on the path, root first */
|
||||
int node[RAD_MTP_TRAV_MAX_DEPTH + 2] = {};
|
||||
int32_t y = -1; /* the final token ... */
|
||||
bool has_y = false; /* ... when the last node carries a valid state */
|
||||
};
|
||||
|
||||
/* ---------------------------------------------------------------- the target law in fixed point */
|
||||
|
||||
/* The mass unit of a plane of n candidates: 2^-qbits of the top candidate's weight, so that a
|
||||
* row's total stays below 2^53 (exact in FP64). */
|
||||
static inline RAD_RRS_HD int rad_mtp_trav_qbits(int64_t n) {
|
||||
int q = RAD_MTP_TRAV_QBITS;
|
||||
for (int64_t c = 4096; c < n && q > 20; c <<= 1) --q;
|
||||
return q;
|
||||
}
|
||||
|
||||
/* floor(2^qbits * e^(v - top)) for a live candidate (v <= top, both finite): the FP32 exponential
|
||||
* of Cephes' expf (argument reduction by n ln 2 in two parts, a degree-5 polynomial in the reduced
|
||||
* argument), taken as a 24-bit mantissa and shifted. Zero below 2^-41 of the top. Basic IEEE FP32
|
||||
* operations and integer shifts only. */
|
||||
RAD_TRAV_STRICT static inline RAD_RRS_HD uint64_t rad_mtp_trav_mass(float v, float top, int qbits) {
|
||||
#if defined(__clang__)
|
||||
#pragma clang fp contract(off)
|
||||
#endif
|
||||
const float x = v - top;
|
||||
if (!(x > -28.5f)) return 0;
|
||||
const int n = (int)(x * 1.44269504088896341f - 0.5f); /* round(x / ln 2), x <= 0 */
|
||||
const float fn = (float)n;
|
||||
float r = x - fn * 0.693359375f;
|
||||
r = r - fn * -2.12194440e-4f;
|
||||
const float z = r * r;
|
||||
float y = 1.9875691500e-4f;
|
||||
y = y * r + 1.3981999507e-3f;
|
||||
y = y * r + 8.3334519073e-3f;
|
||||
y = y * r + 4.1665795894e-2f;
|
||||
y = y * r + 1.6666665459e-1f;
|
||||
y = y * r + 5.0000001201e-1f;
|
||||
y = y * z + r;
|
||||
y = y + 1.0f; /* e^r, in [0.70, 1.42] */
|
||||
const uint32_t mant = (uint32_t)(y * 8388608.0f); /* y * 2^23, below 2^24 */
|
||||
const int sh = qbits + n - 23;
|
||||
if (sh >= 0) return (uint64_t)mant << sh;
|
||||
return sh > -32 ? (uint64_t)(mant >> -sh) : 0;
|
||||
}
|
||||
|
||||
/* An integer below 2^53 as a double, exactly, the same way on host and device. */
|
||||
static inline RAD_RRS_HD double rad_mtp_trav_u2d(uint64_t x) {
|
||||
return (double)(uint32_t)(x >> 32) * 4294967296.0 + (double)(uint32_t)x;
|
||||
}
|
||||
/* The integer part of a double in [0, 2^53). */
|
||||
static inline RAD_RRS_HD uint64_t rad_mtp_trav_d2u(double d) {
|
||||
const uint32_t hi = (uint32_t)(d * (1.0 / 4294967296.0));
|
||||
const double lo = d - (double)hi * 4294967296.0;
|
||||
return ((uint64_t)hi << 32) + (uint64_t)(uint32_t)lo;
|
||||
}
|
||||
|
||||
/* Candidate id's slot in a node's support (the first match), or cnt when it is outside. */
|
||||
static inline RAD_RRS_HD int rad_mtp_trav_slot(const int32_t* sid, int cnt, int32_t id) {
|
||||
int k = 0;
|
||||
while (k < cnt && id != sid[k]) ++k;
|
||||
return k;
|
||||
}
|
||||
|
||||
/* A row's validity and largest value, as rad_mtp_couple_decide scans them: false for an id past the
|
||||
* vocabulary, a NaN or +inf among the ids >= 0, or no finite value at all. */
|
||||
static inline RAD_RRS_HD bool rad_mtp_trav_row_top(const int32_t* ids, const float* val, int64_t n,
|
||||
int64_t vocab, float* top_out) {
|
||||
float top = -INFINITY;
|
||||
for (int64_t j = 0; j < n; ++j) {
|
||||
if (ids[j] < 0) continue;
|
||||
if (ids[j] >= vocab || val[j] != val[j] || val[j] == INFINITY) return false;
|
||||
if (val[j] > top) top = val[j];
|
||||
}
|
||||
*top_out = top;
|
||||
return top != -INFINITY;
|
||||
}
|
||||
|
||||
/* One row's target law over a node's support `sid[0 .. cnt)`: the masses on the support slots
|
||||
* (duplicate candidates aggregated at the first matching slot), off it, and the total. The serial
|
||||
* definition; a workgroup adds the same integers in its own order. */
|
||||
struct RadTravLaw {
|
||||
uint64_t pq[8];
|
||||
uint64_t off, sum;
|
||||
};
|
||||
static inline RAD_RRS_HD void rad_mtp_trav_row_law(const int32_t* ids, const float* val, int64_t n,
|
||||
float top, const int32_t* sid, int cnt,
|
||||
RadTravLaw* o) {
|
||||
const int qb = rad_mtp_trav_qbits(n);
|
||||
for (int k = 0; k < 8; ++k) o->pq[k] = 0;
|
||||
o->off = 0; o->sum = 0;
|
||||
for (int64_t j = 0; j < n; ++j) {
|
||||
if (ids[j] < 0 || val[j] == -INFINITY) continue;
|
||||
const uint64_t m = rad_mtp_trav_mass(val[j], top, qb);
|
||||
o->sum += m;
|
||||
const int k = rad_mtp_trav_slot(sid, cnt, ids[j]);
|
||||
if (k < cnt) o->pq[k] += m; else o->off += m;
|
||||
}
|
||||
}
|
||||
|
||||
/* The off-support candidate that holds unit `t` of the off-support mass, candidates in ascending
|
||||
* slot order (t < the row's off-support mass). -1 when there is none. */
|
||||
static inline RAD_RRS_HD int32_t rad_mtp_trav_off_token(const int32_t* ids, const float* val,
|
||||
int64_t n, float top, const int32_t* sid,
|
||||
int cnt, uint64_t t) {
|
||||
const int qb = rad_mtp_trav_qbits(n);
|
||||
for (int64_t j = 0; j < n; ++j) {
|
||||
if (ids[j] < 0 || val[j] == -INFINITY) continue;
|
||||
if (rad_mtp_trav_slot(sid, cnt, ids[j]) < cnt) continue;
|
||||
const uint64_t m = rad_mtp_trav_mass(val[j], top, qb);
|
||||
if (t < m) return ids[j];
|
||||
t -= m;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- the prepared tree */
|
||||
|
||||
/* The eight-wide FP64 sums of the walk, as one fixed tree: the xor-4, xor-2, xor-1 butterfly of
|
||||
* eight lanes (IEEE addition is commutative, so every lane ends with the same bits). */
|
||||
static inline RAD_RRS_HD double rad_mtp_trav_sum8(const double* v) {
|
||||
return ((v[0] + v[4]) + (v[2] + v[6])) + ((v[1] + v[5]) + (v[3] + v[7]));
|
||||
}
|
||||
|
||||
/* A node's draft side in the walk's canonical order: the children first, in draft order (a chain's
|
||||
* one child is x). `nk` the children the walk may try, `nt` -1 for Gumbel-top-k siblings, else the
|
||||
* number of deterministic top-q children of a RheoSampling node (its tail child is slot nt, `tail`
|
||||
* whether the node carries it), `swap` the stored slot that changed places with slot 0 (a chain row
|
||||
* whose x was not first; else 0).
|
||||
* False when the state names no child (unreachable for a rad_mtp_couple_state_valid state). */
|
||||
static inline RAD_RRS_HD bool rad_mtp_trav_canon(const RadMtpCoupleState& s, int ctl,
|
||||
int32_t* ids, double* q, int* nk, int* nt,
|
||||
int* tail, int* swap) {
|
||||
/* Every index below is a constant: a device lane keeps the state and result in registers. */
|
||||
*swap = 0;
|
||||
*tail = 0;
|
||||
if (s.scheme > 0 && ctl != 4) {
|
||||
for (int k = 0; k < 8; ++k) {
|
||||
ids[k] = k < s.count ? s.ids[k] : -1;
|
||||
q[k] = k < s.count ? s.q[k] : 0.0;
|
||||
}
|
||||
const int m = s.scheme - 1;
|
||||
const int t = m < s.count ? m : s.count;
|
||||
const int cap = t + (s.count > t ? 1 : 0);
|
||||
*nt = t;
|
||||
*nk = s.nkids < cap ? (s.nkids > 0 ? s.nkids : 0) : cap;
|
||||
*tail = *nk > t;
|
||||
return true;
|
||||
}
|
||||
*nt = -1;
|
||||
*nk = s.nkids >= 2 ? (s.nkids < s.count ? s.nkids : s.count) : 1;
|
||||
/* a chain row: x to the front (the first slot that holds it changes places with slot 0) */
|
||||
int kx = 0;
|
||||
if (s.nkids < 2) {
|
||||
kx = 8;
|
||||
for (int k = 7; k >= 0; --k)
|
||||
if (k < s.count && s.ids[k] == s.x) kx = k;
|
||||
}
|
||||
const bool found = kx < 8;
|
||||
int32_t idx = -1;
|
||||
double qx = 0.0;
|
||||
for (int k = 0; k < 8; ++k) {
|
||||
idx = k == kx ? s.ids[k] : idx;
|
||||
qx = k == kx ? s.q[k] : qx;
|
||||
}
|
||||
for (int k = 0; k < 8; ++k) {
|
||||
const bool in = found && k < s.count;
|
||||
const int32_t idk = k == 0 ? idx : (k == kx ? s.ids[0] : s.ids[k]);
|
||||
const double qk = k == 0 ? qx : (k == kx ? s.q[0] : s.q[k]);
|
||||
ids[k] = in ? idk : -1;
|
||||
q[k] = in ? qk : 0.0;
|
||||
}
|
||||
*swap = found ? kx : 0;
|
||||
return found;
|
||||
}
|
||||
|
||||
/* One request's tree as the walk reads it, node-indexed (node 0 the root, parents before
|
||||
* children). Plain data: the device keeps it in LDS and fills it with a workgroup. */
|
||||
struct RadTravTree {
|
||||
int n; /* nodes */
|
||||
int ok[RAD_MTP_TRAV_MAX_ROWS]; /* an eligible state with a valid target law */
|
||||
int nk[RAD_MTP_TRAV_MAX_ROWS]; /* children the walk tries */
|
||||
int nt[RAD_MTP_TRAV_MAX_ROWS]; /* -1 Gumbel; else a rheo node's top children */
|
||||
int tail[RAD_MTP_TRAV_MAX_ROWS]; /* a rheo node that carries its tail child */
|
||||
int ci[RAD_MTP_TRAV_MAX_ROWS]; /* children tried so far */
|
||||
int child[RAD_MTP_TRAV_MAX_ROWS][8]; /* slot k's child node, or -1 */
|
||||
int32_t ids[RAD_MTP_TRAV_MAX_ROWS][8]; /* the support, canonical order, -1 past it */
|
||||
double qr[RAD_MTP_TRAV_MAX_ROWS][8]; /* the draft law (Gumbel: tried ones zeroed) */
|
||||
double m[RAD_MTP_TRAV_MAX_ROWS][8]; /* rate * residual on the support slots (the
|
||||
target's law itself until the node is
|
||||
entered) */
|
||||
double moff[RAD_MTP_TRAV_MAX_ROWS]; /* the same off the support, in all */
|
||||
double sc[RAD_MTP_TRAV_MAX_ROWS]; /* the factor m and moff still owe: the node's
|
||||
rate from its entry to its first rejected
|
||||
child, then 1 */
|
||||
double p[RAD_MTP_TRAV_MAX_ROWS]; /* the node's acceptance rate */
|
||||
uint64_t off[RAD_MTP_TRAV_MAX_ROWS]; /* the off-support mass in units (final draw) */
|
||||
float top[RAD_MTP_TRAV_MAX_ROWS]; /* the row's largest value */
|
||||
int stack[RAD_MTP_TRAV_MAX_DEPTH + 1];
|
||||
};
|
||||
|
||||
/* Node v's laws from its canonical draft side and its row's integer law (`valid`: the row scanned
|
||||
* clean and its total is positive). */
|
||||
static inline RAD_RRS_HD void rad_mtp_trav_set_law(RadTravTree* t, int v, bool valid, float top,
|
||||
const RadTravLaw& w) {
|
||||
const bool ok = valid && w.sum > 0;
|
||||
const double sum = ok ? rad_mtp_trav_u2d(w.sum) : 1.0;
|
||||
for (int k = 0; k < 8; ++k) t->m[v][k] = ok ? rad_mtp_trav_u2d(w.pq[k]) / sum : 0.0;
|
||||
t->moff[v] = ok ? rad_mtp_trav_u2d(w.off) / sum : 0.0;
|
||||
t->off[v] = ok ? w.off : 0;
|
||||
t->top[v] = top;
|
||||
t->ci[v] = 0;
|
||||
t->ok[v] = ok;
|
||||
}
|
||||
|
||||
/* The slot of node v's j-th tried child. Gumbel: the draft order. Rheo: the sampled tail child
|
||||
* first (when the node carries it), then the deterministic ones. */
|
||||
static inline RAD_RRS_HD int rad_mtp_trav_try_slot(const RadTravTree& t, int v, int j) {
|
||||
const int nt = t.nt[v];
|
||||
if (nt < 0) return j;
|
||||
return t.tail[v] ? (j == 0 ? nt : j - 1) : j;
|
||||
}
|
||||
|
||||
/* The law node v's j-th tried child was drawn from, at support slot k. `isq` is the reciprocal of
|
||||
* rad_mtp_trav_try_norm: the sum of the node's remaining draft law (Gumbel) or of its tail's
|
||||
* (rheo). */
|
||||
static inline RAD_RRS_HD double rad_mtp_trav_try_norm(const RadTravTree& t, int v) {
|
||||
const int nt = t.nt[v];
|
||||
if (nt < 0) return rad_mtp_trav_sum8(t.qr[v]);
|
||||
double tail[8];
|
||||
for (int k = 0; k < 8; ++k) tail[k] = k >= nt ? t.qr[v][k] : 0.0;
|
||||
return rad_mtp_trav_sum8(tail);
|
||||
}
|
||||
static inline RAD_RRS_HD double rad_mtp_trav_try_q(const RadTravTree& t, int v, int j, double isq,
|
||||
int k) {
|
||||
const int nt = t.nt[v];
|
||||
if (nt < 0) return t.qr[v][k] * isq;
|
||||
const int slot = rad_mtp_trav_try_slot(t, v, j);
|
||||
if (slot != nt) return k == slot ? 1.0 : 0.0; /* a deterministic child: a point mass */
|
||||
if (k < nt) return 0.0;
|
||||
const double q = nt == 0 ? t.qr[v][k] : t.qr[v][k] * isq;
|
||||
return q > 1.0 ? 1.0 : q; /* clamp: rounding must not push a one-token tail past 1 */
|
||||
}
|
||||
/* m / q for node v's j-th tried child at its own slot i, m the child's mass in the node's law: the
|
||||
* child's rate before the cap, in one division (m * sq / qr rather than m / (qr / sq)). Negative
|
||||
* when the law has no mass there (the child is not tried). */
|
||||
static inline RAD_RRS_HD double rad_mtp_trav_try_ratio(const RadTravTree& t, int v, int j, int i,
|
||||
double m) {
|
||||
const int nt = t.nt[v];
|
||||
const double q = t.qr[v][i];
|
||||
if (nt >= 0 && i != nt) return m; /* a point mass */
|
||||
if (!(q > 0)) return -1.0;
|
||||
if (nt == 0) return q < 1.0 ? m / q : m;
|
||||
const double sq = rad_mtp_trav_try_norm(t, v);
|
||||
return q < sq ? m * sq / q : m; /* the law's value is at most 1 */
|
||||
}
|
||||
|
||||
/* The walk over a prepared tree: the accepted path into path[0 .. *n_path). Returns false when
|
||||
* nothing was decided (an invalid root state: every row keeps the pick). `pos0` is the root row's
|
||||
* output position, the coordinate of the acceptance uniforms. Updates the tree in place: the last
|
||||
* node's m / moff are its residual law (up to the node's factor sc), which
|
||||
* rad_mtp_trav_final_pick reads. */
|
||||
static inline RAD_RRS_HD bool rad_mtp_trav_walk_tree(RadTravTree& t, uint64_t seed, uint64_t pos0,
|
||||
int* path, int* n_path,
|
||||
const RadMtpTravOpt& opt = RadMtpTravOpt{}) {
|
||||
int top = 0, tests = 0;
|
||||
t.stack[0] = 0;
|
||||
t.p[0] = 1.0;
|
||||
t.sc[0] = 1.0; /* the root's m is the target's law itself */
|
||||
*n_path = 0;
|
||||
if (!t.ok[0]) return false;
|
||||
for (;;) {
|
||||
const int v = t.stack[top];
|
||||
if (t.ok[v] && t.ci[v] < t.nk[v]) {
|
||||
const int j = t.ci[v];
|
||||
const int i = rad_mtp_trav_try_slot(t, v, j);
|
||||
/* p_c = min(1, p_v r(c) / qn(c)); control 1 drops p_v (token-level ratios) */
|
||||
const double f = opt.ctl == 1 ? (t.p[v] > 0 ? t.sc[v] / t.p[v] : 0.0) : t.sc[v];
|
||||
const double ratio = rad_mtp_trav_try_ratio(t, v, j, i, f * t.m[v][i]);
|
||||
const int c = top < RAD_MTP_TRAV_MAX_DEPTH && ratio >= 0 ? t.child[v][i] : -1;
|
||||
if (c < 0) { /* a child the verify no longer carries: cut here */
|
||||
t.nk[v] = j;
|
||||
continue;
|
||||
}
|
||||
const double pc = ratio < 1.0 ? ratio : 1.0;
|
||||
t.p[c] = pc;
|
||||
t.sc[c] = pc; /* the child's law becomes rate * law, when it is first needed */
|
||||
t.stack[++top] = c;
|
||||
continue;
|
||||
}
|
||||
/* a leaf: the sequence-level test */
|
||||
++tests;
|
||||
bool accept;
|
||||
if (opt.accept_at >= 0) {
|
||||
if (opt.p_test && tests <= opt.max_tests) opt.p_test[tests - 1] = t.p[v];
|
||||
if (opt.n_tests) *opt.n_tests = tests;
|
||||
accept = tests == opt.accept_at;
|
||||
} else {
|
||||
const double u = rad_spechub_uniform(
|
||||
seed, pos0, RAD_MTP_TRAV_KEY ^ rad_mtp_rrs_mix((uint64_t)tests));
|
||||
accept = u < t.p[v];
|
||||
}
|
||||
if (accept) {
|
||||
*n_path = top + 1;
|
||||
for (int i = 0; i <= top; ++i) path[i] = t.stack[i];
|
||||
return true;
|
||||
}
|
||||
if (top == 0) return false; /* the root always accepts (p = 1); only roundoff gets here */
|
||||
--top;
|
||||
const int g = t.stack[top];
|
||||
const int j = t.ci[g];
|
||||
const double isq = 1.0 / rad_mtp_trav_try_norm(t, g);
|
||||
const double pold = t.p[g], sc = t.sc[g];
|
||||
double d[8];
|
||||
for (int k = 0; k < 8; ++k) {
|
||||
const double x = sc * t.m[g][k] - rad_mtp_trav_try_q(t, g, j, isq, k);
|
||||
d[k] = x > 0 ? x : 0;
|
||||
}
|
||||
const double moff = sc * t.moff[g];
|
||||
const double S = moff + rad_mtp_trav_sum8(d);
|
||||
if (!(S > 0) || !rad_spechub_finite(S)) {
|
||||
/* nothing of the target is left above the draft: this node cannot accept, nor can a
|
||||
* child of it */
|
||||
t.p[g] = 0;
|
||||
t.sc[g] = 0;
|
||||
} else {
|
||||
const double den = opt.ctl == 2 ? S : S + 1.0 - pold;
|
||||
const double inv = 1.0 / den;
|
||||
const double pn = S * inv;
|
||||
t.p[g] = pn < 1.0 ? pn : 1.0; /* a rate is at most 1: rounding may not push it past */
|
||||
for (int k = 0; k < 8; ++k) t.m[g][k] = d[k] * inv;
|
||||
t.moff[g] = moff * inv;
|
||||
t.sc[g] = 1.0;
|
||||
}
|
||||
/* Gumbel siblings are drawn WITHOUT replacement: the remaining Q renormalises */
|
||||
if (t.nt[g] < 0 && opt.ctl != 3) t.qr[g][j] = 0;
|
||||
++t.ci[g];
|
||||
}
|
||||
}
|
||||
|
||||
/* The final token of node v's residual law (in proportion to m on the support slots and moff off
|
||||
* it: the node's factor sc is common to both and cancels), by the uniform u: the support slots
|
||||
* first, in the canonical order, then the off-support candidates in slot order. kind 0: no token
|
||||
* (the row keeps the pick); 1: the token of support slot `slot`; 2: the off-support candidate
|
||||
* holding unit `t` of the row's off-support mass (rad_mtp_trav_off_token). */
|
||||
struct RadTravPick {
|
||||
int kind, slot;
|
||||
uint64_t t;
|
||||
};
|
||||
static inline RAD_RRS_HD RadTravPick rad_mtp_trav_final_pick(const RadTravTree& t, int v,
|
||||
double u) {
|
||||
RadTravPick o;
|
||||
o.kind = 0; o.slot = -1; o.t = 0;
|
||||
const double woff = t.moff[v];
|
||||
const double total = rad_mtp_trav_sum8(t.m[v]) + woff;
|
||||
if (!(total > 0) || !rad_spechub_finite(total)) return o;
|
||||
double c = u * total;
|
||||
int last = -1;
|
||||
for (int k = 0; k < 8; ++k) {
|
||||
const double m = t.m[v][k];
|
||||
if (m > 0) {
|
||||
last = k;
|
||||
c -= m;
|
||||
if (c < 0) { o.kind = 1; o.slot = k; return o; }
|
||||
}
|
||||
}
|
||||
const uint64_t off = t.off[v];
|
||||
if (woff > 0 && off > 0) {
|
||||
const double frac = c / woff;
|
||||
uint64_t tt = frac < 1.0 ? rad_mtp_trav_d2u(frac * rad_mtp_trav_u2d(off)) : off - 1;
|
||||
if (tt >= off) tt = off - 1;
|
||||
o.kind = 2; o.t = tt;
|
||||
return o;
|
||||
}
|
||||
if (last >= 0) { o.kind = 1; o.slot = last; }
|
||||
return o;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- a tree behind an interface
|
||||
*
|
||||
* The tree the walk reads (a Tree type provides):
|
||||
* const RadMtpCoupleState* state(int v) the node's bound state, or null (node is a leaf)
|
||||
* bool cand(int v, const int32_t** ids, const float** val, int64_t* n) target candidates
|
||||
* int child(int v, int32_t token) the node's first child row with that token, or -1
|
||||
* int64_t vocab()
|
||||
* rad_mtp_trav_walk prepares the nodes the walk can reach (in discovery order, at most
|
||||
* RAD_MTP_TRAV_MAX_ROWS), walks and draws the final token: the host reference and the tests. */
|
||||
template <class Tree>
|
||||
static inline bool rad_mtp_trav_walk(const Tree& T, int root, uint64_t seed, uint64_t pos0,
|
||||
RadMtpTravOut* out, RadMtpTravOpt opt = RadMtpTravOpt{},
|
||||
RadTravTree* keep = nullptr, int* ids_out = nullptr) {
|
||||
RadTravTree local;
|
||||
RadTravTree& t = keep ? *keep : local;
|
||||
int id[RAD_MTP_TRAV_MAX_ROWS]; /* node -> the tree's own id */
|
||||
struct Row { const int32_t* ids; const float* val; int64_t n; };
|
||||
Row rows[RAD_MTP_TRAV_MAX_ROWS];
|
||||
t.n = 1;
|
||||
id[0] = root;
|
||||
for (int a = 0; a < t.n; ++a) {
|
||||
const int v = id[a];
|
||||
t.ok[a] = 0; t.nk[a] = 0; t.nt[a] = -1; t.tail[a] = 0; t.ci[a] = 0;
|
||||
t.moff[a] = 0; t.sc[a] = 1.0; t.p[a] = 0; t.off[a] = 0; t.top[a] = -INFINITY;
|
||||
for (int k = 0; k < 8; ++k) {
|
||||
t.child[a][k] = -1; t.ids[a][k] = -1; t.qr[a][k] = 0; t.m[a][k] = 0;
|
||||
}
|
||||
rows[a] = Row{ nullptr, nullptr, 0 };
|
||||
const RadMtpCoupleState* sp = T.state(v);
|
||||
if (!sp) continue;
|
||||
int swap = 0;
|
||||
if (!rad_mtp_trav_canon(*sp, opt.ctl, t.ids[a], t.qr[a], &t.nk[a], &t.nt[a], &t.tail[a],
|
||||
&swap))
|
||||
continue;
|
||||
const int32_t* ids = nullptr; const float* val = nullptr;
|
||||
int64_t n = 0;
|
||||
if (!T.cand(v, &ids, &val, &n)) continue;
|
||||
rows[a] = Row{ ids, val, n };
|
||||
float top = -INFINITY;
|
||||
RadTravLaw w{};
|
||||
const bool valid = rad_mtp_trav_row_top(ids, val, n, T.vocab(), &top);
|
||||
if (valid) rad_mtp_trav_row_law(ids, val, n, top, t.ids[a], sp->count, &w);
|
||||
rad_mtp_trav_set_law(&t, a, valid, top, w);
|
||||
if (!t.ok[a]) continue;
|
||||
for (int k = 0; k < t.nk[a]; ++k) {
|
||||
const int c = T.child(v, t.ids[a][k]);
|
||||
if (c < 0 || t.n >= RAD_MTP_TRAV_MAX_ROWS) continue;
|
||||
t.child[a][k] = t.n;
|
||||
id[t.n++] = c;
|
||||
}
|
||||
}
|
||||
int path[RAD_MTP_TRAV_MAX_DEPTH + 1], np = 0;
|
||||
if (ids_out) for (int a = 0; a < t.n; ++a) ids_out[a] = id[a];
|
||||
if (!rad_mtp_trav_walk_tree(t, seed, pos0, path, &np, opt)) return false;
|
||||
out->n = np;
|
||||
for (int i = 0; i < np; ++i) out->node[i] = id[path[i]];
|
||||
out->has_y = false;
|
||||
const int f = path[np - 1];
|
||||
if (t.ok[f]) {
|
||||
const double ur = opt.u_final >= 0
|
||||
? opt.u_final
|
||||
: rad_spechub_uniform(seed, pos0 + (uint64_t)(np - 1), RAD_SAMPLE_KEY_RESID);
|
||||
const RadTravPick pk = rad_mtp_trav_final_pick(t, f, ur);
|
||||
if (pk.kind == 1) { out->y = t.ids[f][pk.slot]; out->has_y = true; }
|
||||
if (pk.kind == 2) {
|
||||
int cnt = 0;
|
||||
while (cnt < 8 && t.ids[f][cnt] >= 0) ++cnt;
|
||||
out->y = rad_mtp_trav_off_token(rows[f].ids, rows[f].val, rows[f].n, t.top[f],
|
||||
t.ids[f], cnt, pk.t);
|
||||
out->has_y = out->y >= 0;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
#endif /* __cplusplus */
|
||||
#endif /* RAD_MTP_TRAVERSAL_H */
|
||||
+4
-2
@@ -51,7 +51,8 @@ RAD_PHILOX_HD float rad_philox_normal(uint64_t seed, uint64_t e) {
|
||||
* (an audio window's noise is stream 1 + its index). */
|
||||
RAD_PHILOX_HD float rad_philox_normal_s(uint64_t seed, uint64_t stream, uint64_t e) {
|
||||
const uint64_t g = e >> 2;
|
||||
uint32_t c[4] = { (uint32_t)g, (uint32_t)(g >> 32), (uint32_t)stream, (uint32_t)(stream >> 32) };
|
||||
uint32_t c[4] = { (uint32_t)g, (uint32_t)(g >> 32), (uint32_t)stream,
|
||||
(uint32_t)(stream >> 32) };
|
||||
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];
|
||||
@@ -67,7 +68,8 @@ RAD_PHILOX_HD float rad_philox_normal_s(uint64_t seed, uint64_t stream, uint64_t
|
||||
* it. */
|
||||
RAD_PHILOX_HD float rad_philox_uniform_s(uint64_t seed, uint64_t stream, uint64_t e) {
|
||||
const uint64_t g = e >> 2;
|
||||
uint32_t c[4] = { (uint32_t)g, (uint32_t)(g >> 32), (uint32_t)stream, (uint32_t)(stream >> 32) };
|
||||
uint32_t c[4] = { (uint32_t)g, (uint32_t)(g >> 32), (uint32_t)stream,
|
||||
(uint32_t)(stream >> 32) };
|
||||
rad_philox4x32_10(c, (uint32_t)seed, (uint32_t)(seed >> 32));
|
||||
return ((float)(c[e & 3u] >> 8) + 0.5f) * (1.0f / 16777216.0f);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
/* rad_prefill_split.h -- host-pure live-KV prefill split law shared by libr4d launchers and
|
||||
* architecture pass-key callbacks. Keep this independent of HIP so callbacks can run before tape
|
||||
* lookup without a device copy or launch.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
|
||||
/* `bq` query positions per workgroup, `tile` keys per KV tile. `units` counts the workgroups that
|
||||
* do work: a ragged batch's grid is sized from its longest sequence, but a shorter sequence's
|
||||
* tiles past its end exit at once. Each split keeps at least eight tiles of the supplied context.
|
||||
*/
|
||||
static inline int rad_prefill_splits_law(int bq, int tile, int q_len, int total_q, int num_seqs,
|
||||
int kv_heads, int max_ctx, int wgps) {
|
||||
const long n = std::max(1, num_seqs);
|
||||
const long qt = std::min(n * ((std::max(1, q_len) + bq - 1) / bq),
|
||||
(std::max(1, total_q) + (long)(bq - 1) * n) / bq);
|
||||
const long units = (long)std::max(1, kv_heads) * std::max(1L, qt);
|
||||
if (units >= wgps) return 1;
|
||||
const int s1 = (int)(wgps / units), s2 = (int)(2L * wgps / units);
|
||||
int sp = s2 > 2 * s1 ? s2 : s1;
|
||||
const int cap = ((max_ctx > 0 ? max_ctx : (1 << 30) - 1) + tile - 1) / tile / 8;
|
||||
sp = std::min(sp, std::max(1, cap));
|
||||
return std::max(1, std::min(sp, 64));
|
||||
}
|
||||
|
||||
/* The launcher's live-context refinement of the initial model-bound law. */
|
||||
static inline int rad_prefill_splits_for_live(int bq, int tile, int q_len, int total_q,
|
||||
int num_seqs, int kv_heads, int max_ctx,
|
||||
int used_ctx, int wgps) {
|
||||
int splits = rad_prefill_splits_law(bq, tile, q_len, total_q, num_seqs, kv_heads, max_ctx,
|
||||
wgps);
|
||||
if (splits > 1 && used_ctx > 0 && (max_ctx <= 0 || used_ctx < max_ctx))
|
||||
splits = rad_prefill_splits_law(bq, tile, q_len, total_q, num_seqs, kv_heads, used_ctx,
|
||||
wgps);
|
||||
return splits;
|
||||
}
|
||||
|
||||
/* Fingerprint one actual launch tuple in packet-global sizes. Use this instead of the raw context
|
||||
* so equal split grids share a recording key as live context advances. */
|
||||
static inline uint64_t rad_prefill_grid_key(int q_len, int bq, int splits, int kv_heads,
|
||||
int num_seqs, int threads) {
|
||||
const uint64_t gx = (uint64_t)((std::max(1, q_len) + bq - 1) / bq) *
|
||||
(uint64_t)std::max(1, splits) * (uint64_t)threads;
|
||||
const uint64_t gy = (uint64_t)std::max(1, kv_heads);
|
||||
const uint64_t gz = (uint64_t)std::max(1, num_seqs);
|
||||
uint64_t h = 0x9e3779b97f4a7c15ull;
|
||||
const uint64_t grid[3] = {gx, gy, gz};
|
||||
for (uint64_t v : grid) {
|
||||
h ^= v + 0x9e3779b97f4a7c15ull + (h << 6) + (h >> 2);
|
||||
h *= 0xbf58476d1ce4e5b9ull;
|
||||
}
|
||||
return h | 1;
|
||||
}
|
||||
+1
-1
@@ -32,7 +32,7 @@ extern "C" {
|
||||
|
||||
/* 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" */
|
||||
const char* name; /* the 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 */
|
||||
|
||||
+151
-21
@@ -68,8 +68,10 @@ typedef struct RadKVGroupBatch {
|
||||
int64_t state_index_pitch;
|
||||
int64_t block_size;
|
||||
int64_t max_blocks;
|
||||
/* Null unless this group streams (RadKVStream). Trailing and zero-defaulted. */
|
||||
/* Null unless this group streams (RadKVStream). */
|
||||
const RadKVStream* stream;
|
||||
/* ABI 35: host mirror of seqused, kept through this batch for exact sliced-launch bounds. */
|
||||
const int32_t* seqused_h;
|
||||
} RadKVGroupBatch;
|
||||
|
||||
typedef struct RadBatch {
|
||||
@@ -175,7 +177,7 @@ typedef struct RadBatch {
|
||||
* banding the decode half with it would give eight rows a thousand-row GEMM's band.
|
||||
*
|
||||
* The decode value is read by the GDN blocks and the fp8 gated attention's per-band issue
|
||||
* (rad_block_attn_gated_fp8.h), which also bands its prefill half on the prefill value; the
|
||||
* (rad_block_attn_gated_q.h), which also bands its prefill half on the prefill value; 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;
|
||||
@@ -286,7 +288,8 @@ typedef struct RadBatch {
|
||||
/* ---- appended in ABI 26 (control vectors) */
|
||||
/* Host-side: nonzero when some row of this pass takes the loaded control vector (its
|
||||
* `projection_on_rows` entry is 1). A projection skips a zero row anyway, so a block issues
|
||||
* no projection op when this is 0 and the pass is the one a deployment without a vector runs. */
|
||||
* no projection op when this is 0 and the pass is the one a deployment without a vector
|
||||
* runs. */
|
||||
int32_t control_vector;
|
||||
|
||||
/* ---- appended in ABI 26 (per-segment encoder grids) */
|
||||
@@ -325,6 +328,61 @@ typedef struct RadBatch {
|
||||
const int32_t* plugin_cu; /* [n_seq + 1] device */
|
||||
const int32_t* plugin_words_h;
|
||||
const int32_t* plugin_cu_h;
|
||||
|
||||
/* ---- appended in ABI 33 (the shape generator) */
|
||||
/* A shape generator's pass (rad_declare_shape_generator; `gen` is one of its
|
||||
* RAD_GEN_PASS_S*): its payload. Null on every other step. */
|
||||
const struct RadShapeGenBatch* sgen_b;
|
||||
|
||||
/* ---- appended in ABI 34: host-side max seqused per entry of kv[], for an architecture's
|
||||
* optional recorded-pass geometry key. Null when the batch has no host summary. */
|
||||
const int32_t* kv_used_max_h;
|
||||
/* ABI 35: host mirror of positions, for a one-sequence prefill op whose exact KV bound is the
|
||||
* position immediately after its first query piece. Valid through the batch's issue pass. */
|
||||
const int32_t* positions_h;
|
||||
/* ---- appended in ABI 35 (runs read both ways) */
|
||||
/* The runs of a trunk pass whose rows attend to each other both ways
|
||||
* (RadEncoderDecl::bidirectional): a picture's or a video frame's placeholders inside one
|
||||
* sequence's chunk. The pass attends them causally like every other row; the plugin attends a
|
||||
* run's rows again without the causal bound, over the keys before `bidi_used` (the position
|
||||
* after the run's last token, counted as the window group's seqused is: from the first
|
||||
* position of its table), in place of that result. The scheduler ends no chunk inside such
|
||||
* a run, so its keys are this pass's or, after a prefix hit, the cache's; a run longer than any
|
||||
* step is cut where its chunk ends, and that chunk's rows see the run up to the cut.
|
||||
*
|
||||
* host: n_bidi and, per run, its first row in this pass, its rows and the index of its sequence
|
||||
* in the per-sequence arrays; device: [n_bidi] the keys a run's rows see. 0 runs on every other
|
||||
* pass. */
|
||||
int64_t n_bidi;
|
||||
const int32_t* bidi_row; /* host */
|
||||
const int32_t* bidi_n; /* host */
|
||||
const int32_t* bidi_seq; /* host */
|
||||
const int32_t* bidi_used; /* device */
|
||||
/* ---- appended in ABI 36 (a block drafter's anchor row) */
|
||||
/* A block drafter's query pass (draft_pass 1): [n_seq] device, for each drafting sequence the
|
||||
* row of its last committed position in the context pass just run, whose rows are the verify
|
||||
* step's in order. -1 for a row the card did not position. A drafter that conditions on the
|
||||
* context state at the anchor (LiLiCorr) gathers it there; the query rows themselves sit past
|
||||
* that position. Null on every other pass. */
|
||||
const int32_t* anchor_rows;
|
||||
/* ---- appended in ABI 43 (a checkpoint inside the step) */
|
||||
/* A step of one prefill sequence (n_seq 1, no decode rows) whose linear-state checkpoint lies
|
||||
* inside it rather than at its end: host, the rows before the checkpoint (its position less
|
||||
* the sequence's context), 0 on every other step. Set only for a plugin that asked
|
||||
* (RadArchProbe::ckpt_snap_ok). Such a plugin runs its recurrence over [0, ckpt_cut) and
|
||||
* [ckpt_cut, n_tok) as two pieces -- each what a chunk of those rows computes -- and calls
|
||||
* rad_ckpt_snap for each stateful layer between them, so the snapshot is the state a chunk
|
||||
* ending at the checkpoint leaves, without a step of its own for the rows past it.
|
||||
* `ckpt_cu` is [3] device: {0, ckpt_cut, n_tok}, a piece's cu_seqlens at +0 and +1; null when
|
||||
* ckpt_cut is 0. */
|
||||
int32_t ckpt_cut;
|
||||
const int32_t* ckpt_cu;
|
||||
/* ---- appended in ABI 44 (image-span rows) ---- */
|
||||
/* [n_tok] i32 device: 1 for a token inside an image span (every row of the span -- the aligner
|
||||
* row, image_start, image_end and image_newline), 0 for text. The MoE gate selects experts by
|
||||
* `bias_vl` on those rows and by `bias` elsewhere. Null on a step with no image span, and the
|
||||
* gate then runs its unmasked select. Trailing, so ABI 43's checkpoint fields stay put. */
|
||||
const int32_t* vl_mask;
|
||||
} RadBatch;
|
||||
|
||||
/* What a generator pass carries beside the step batch's own fields, which keep their meanings:
|
||||
@@ -369,7 +427,8 @@ typedef struct RadGenBatch {
|
||||
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)}. */
|
||||
/* [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. */
|
||||
@@ -464,6 +523,14 @@ typedef struct RadGenBatch {
|
||||
/* COND: the request's RAD_GEN_COND_* options, 0 for none and on every other pass. Only
|
||||
* options the plugin declares (RadGeneratorDecl::cond_opts) are set. */
|
||||
int32_t cond_opts;
|
||||
/* ---- appended Krea 2 reference attention (release assigns the ABI version) */
|
||||
/* DENOISE: one natural-log bias a sequence on target queries to reference keys.
|
||||
* Finite biases are in [-16, 16]; zero leaves dense attention unchanged.
|
||||
* The driver uses negative infinity internally to isolate outfill reference queries. */
|
||||
const float* ref_log_bias;
|
||||
/* DENOISE: three timesteps a sequence, one per text/reference/target span.
|
||||
* Registered outfill leaves the source reference at timestep zero. */
|
||||
const float* mode_sigma;
|
||||
} RadGenBatch;
|
||||
|
||||
/* A request's conditioning options on a COND pass (RadGenBatch::cond_opts). */
|
||||
@@ -482,7 +549,7 @@ 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 */
|
||||
RAD_GEN_F_PREVIEW = 4 /* write the step's clean-latent estimate to the lane's preview */
|
||||
};
|
||||
|
||||
/* What an audio generator's pass carries beside the step batch's own fields (rad_builder.h,
|
||||
@@ -587,6 +654,9 @@ typedef struct RadAudioGenBatch {
|
||||
const int32_t* ref_cu_h;
|
||||
const int32_t* ref_frame;
|
||||
const int32_t* ref_frame_h;
|
||||
/* ABI 40: PROMPT branch boundaries on the host, [n_seq + 1], including unequal
|
||||
* reference-direction branches. Same rows as RadBatch::cu_seqlens on device. */
|
||||
const int32_t* prompt_cu_h;
|
||||
} RadAudioGenBatch;
|
||||
|
||||
/* A window entry's flags on a WINDOW pass. FIRST is RAD_GEN_F_FIRST's bit and the others are clear
|
||||
@@ -636,7 +706,9 @@ typedef struct RadVideoGenBatch {
|
||||
/* ---- VSTEP */
|
||||
int32_t step; /* from 0; the first draws the lane's noise */
|
||||
/* f32 [16]: the video's timestep, sigma and next sigma, then the soundtrack's; from [6] the
|
||||
* res_multistep scalars of the video, then of the soundtrack (`sampler`, below). */
|
||||
* res_multistep scalars of the video, then of the soundtrack (`sampler`, below).
|
||||
* For UniPC, the timestep is Wan's unnormalised integer timestep as f32.
|
||||
* Eight flow_unipc_step coefficients start at RAD_VIDEO_UNIPC_COEFF_OFFSET. */
|
||||
const float* sched;
|
||||
const float* pos; /* f32 [3, n_tok]: RAD_VPOS_STEP */
|
||||
/* u32 [2, 2]: the video's noise seed and the soundtrack's, low word first (VSTEP, VUPSCALE and
|
||||
@@ -683,12 +755,14 @@ typedef struct RadVideoGenBatch {
|
||||
* (k-diffusion's res_multistep at eta 0), which keeps the previous step's estimate. Its scalars
|
||||
* are sched[6..10] for the video and sched[11..15] for the soundtrack: sigma, r = next sigma /
|
||||
* sigma, the weights hb1 and hb2 of this step's estimate and the previous one, and the order,
|
||||
* 1 where there is no previous estimate on the same grid. */
|
||||
* 1 where there is no previous estimate on the same grid. RAD_SAMPLER_UNIPC uses
|
||||
* the coefficients at RAD_VIDEO_UNIPC_COEFF_OFFSET and a three-plane history. */
|
||||
int32_t sampler;
|
||||
/* VENCODE: f32 [enc_frames, enc_height, enc_width, 3] RGB in 0..255, the frames padded to
|
||||
* whole clips by repeating the last (rad_arch_encode_geom's entry 23). AENCODE: f32
|
||||
* [enc_channels, enc_n_samples], each channel padded with zeros to the hop (entry 0). Both:
|
||||
* the pass's geometry as rad_arch_encode_geom gave it, i32 on the device, and the media's
|
||||
* the pass's geometry as rad_arch_encode_geom gave it, i32 in pinned host memory also readable
|
||||
* by device kernels (mixed-site encoders share it), and the media's
|
||||
* kind (RAD_ENC_*, below) and its number within the kind from 1. */
|
||||
const float* enc_pixels;
|
||||
int32_t enc_frames, enc_height, enc_width;
|
||||
@@ -702,7 +776,8 @@ typedef struct RadVideoGenBatch {
|
||||
* height, latent width, latent frames, soundtrack latents} in presentation order and 3 a
|
||||
* keyframe {frame, latent frames, soundtrack latents}, then the prompt's vision pads: a count
|
||||
* and {first token, tokens} of each picture's run. A reference's kind is RAD_VREF_PICTURE,
|
||||
* _AUDIO or _VIDEO; its slot is its encode pass's. */
|
||||
* _AUDIO or _VIDEO; its slot is its encode pass's. A keyframe with soundtrack latents is the
|
||||
* song guide (RAD_ENC_GUIDE), which has no picture: its latent frames are 0. */
|
||||
const int32_t* ref_tab;
|
||||
/* VSTEP: i32, rad_arch_video_pack's `mod`: the boundaries of the modulation groups, then the
|
||||
* cell each reads; `seg_cu` then holds the segment boundaries. A request without references
|
||||
@@ -710,16 +785,56 @@ typedef struct RadVideoGenBatch {
|
||||
const int32_t* mod_cu;
|
||||
} RadVideoGenBatch;
|
||||
|
||||
enum { RAD_SAMPLER_EULER = 0, RAD_SAMPLER_RES_MULTISTEP = 1 };
|
||||
enum { RAD_SAMPLER_EULER = 0, RAD_SAMPLER_RES_MULTISTEP = 1, RAD_SAMPLER_UNIPC = 2 };
|
||||
enum { RAD_VIDEO_UNIPC_COEFF_OFFSET = 6 };
|
||||
|
||||
/* What a shape generator's pass carries beside the step batch's own fields (rad_builder.h,
|
||||
* RadShapeGenDecl, describes the passes). Every pass is one request's, in lane `lane`:
|
||||
*
|
||||
* SCOND `n_tok` is the picture's patches, `patches` [n_tok, 3 enc_patch^2] f32.
|
||||
* SSTEP `n_tok` is step_rows. The two branches' latents are entries 0 (the picture's) and 1
|
||||
* (the unconditioned one) of the image generator's sampler ops (`randn_lanes`,
|
||||
* `lane_gather`, `flow_euler`): `lat_cu` bounds them and the per-entry arrays are
|
||||
* theirs, entry 0 guided against entry 1 (`pair` {1, -2}) at the request's scale.
|
||||
* SLATENT `n_tok` is latent_rows; nothing of the pass's own.
|
||||
* SQUERY `n_tok` is n_query, `query` [n_query, 3] f32: x, y, z a point, and `query_cu`
|
||||
* {0, n_query}.
|
||||
*
|
||||
* `lanes` and `lat_cu` are staged on every pass; the latent's rows are lat_cu[0..1]. Every
|
||||
* pointer is device memory. */
|
||||
typedef struct RadShapeGenBatch {
|
||||
int32_t lane;
|
||||
|
||||
/* ---- SCOND */
|
||||
const float* patches;
|
||||
|
||||
/* ---- SSTEP: the step (from 0) of the request's `n_steps` evaluations, then the two
|
||||
* entries' sampler operands, [2] each but `seed` [2, 2] (low word first) and `lat_cu` [3]. */
|
||||
int32_t step, n_steps;
|
||||
const float* sigma;
|
||||
const float* sigma_next;
|
||||
const float* cfg;
|
||||
const int32_t* pair;
|
||||
const int32_t* lanes;
|
||||
const int32_t* flags; /* RAD_GEN_F_FIRST on entry 0 of the first step */
|
||||
const uint32_t* seed;
|
||||
const int32_t* lat_cu;
|
||||
|
||||
/* ---- SQUERY */
|
||||
int64_t n_query;
|
||||
const float* query;
|
||||
const int32_t* query_cu;
|
||||
} RadShapeGenBatch;
|
||||
|
||||
/* RadVideoGenBatch::enc_kind: the media an encode pass carries, numbered from 1 within a kind. A
|
||||
* keyframe is 1 for the first frame and 2 for the last. */
|
||||
* keyframe is 1 for the first frame and 2 for the last. Additive; RAD_ABI_VERSION does not move. */
|
||||
enum {
|
||||
RAD_ENC_IMAGE = 1, /* a reference picture; Vencode */
|
||||
RAD_ENC_VIDEO = 2, /* a reference video; Vencode */
|
||||
RAD_ENC_VAUDIO = 3, /* the soundtrack of reference video `enc_slot`; Aencode */
|
||||
RAD_ENC_AUDIO = 4, /* a standalone soundtrack; Aencode */
|
||||
RAD_ENC_KEYFRAME = 5 /* a first or last frame; Vencode */
|
||||
RAD_ENC_KEYFRAME = 5, /* a first or last frame; Vencode */
|
||||
RAD_ENC_GUIDE = 6 /* a song guide: a keyframe's soundtrack with no picture; Aencode */
|
||||
};
|
||||
|
||||
/* RadVideoGenBatch::ref_tab: a reference's kind. */
|
||||
@@ -794,7 +909,8 @@ typedef struct RadOperand {
|
||||
* 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(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
|
||||
@@ -845,6 +961,13 @@ int rad_lane_join(RadCtx* c, int from, int to);
|
||||
* the status it set, so a helper can `return rad_step_fail(...)`. */
|
||||
int rad_step_fail(RadCtx* c, const char* what);
|
||||
|
||||
/* A step with a checkpoint inside it (RadBatch::ckpt_cut): copy layer `layer`'s state of the
|
||||
* stateful KV group `group` -- the sequence's committed slot as the issue stands -- into the
|
||||
* engine's checkpoint stage, on the current lane's stream. Called between the two pieces of the
|
||||
* recurrence, once for every stateful group and layer the plugin holds. A no-op returning RAD_OK
|
||||
* on a step with no checkpoint inside it, so a caller need not test. */
|
||||
int rad_ckpt_snap(RadCtx* c, rad_kvgroup group, int layer);
|
||||
|
||||
/* ================================================================== run-phase queries */
|
||||
const RadBatch* rad_batch(RadCtx* c);
|
||||
/* The position of model layer `layer` among `group`'s bound layers, or -1 when this rank has no
|
||||
@@ -860,7 +983,13 @@ int rad_kv_stage_layer(RadCtx* c, rad_kvgroup group, const RadKVGrou
|
||||
int layer);
|
||||
int rad_kv_stage_next(RadCtx* c, rad_kvgroup group, int layer);
|
||||
int rad_rank(RadCtx* c);
|
||||
/* The instance's slot, rad_build_slot() of the declare that built it: what a plugin indexes its
|
||||
* per-instance state by. */
|
||||
int rad_slot(RadCtx* c);
|
||||
int rad_world_size(RadCtx* c);
|
||||
/* Workgroups the current rank's card can run concurrently (HIP multiProcessorCount on RDNA;
|
||||
* 32 on the host backend or when the backend has no positive count). */
|
||||
int rad_ctx_wgp_count(RadCtx* c);
|
||||
RadStream rad_stream(RadCtx* c);
|
||||
|
||||
/* The routing result for a MoE layer, resolved on device against the current residency table.
|
||||
@@ -899,13 +1028,13 @@ int32_t* rad_route_counts(RadCtx* c, int layer, int64_t n_expert);
|
||||
* 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. */
|
||||
* `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;
|
||||
@@ -913,7 +1042,8 @@ typedef struct RadPrefetchNext {
|
||||
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 */
|
||||
counts (rad_route_counts), -1 for nowhere; null when each
|
||||
expert's count is at its own index */
|
||||
} RadPrefetchNext;
|
||||
|
||||
/* At this layer's router input: `h` rows [r0, r0 + rows) of n_embd bf16, read in place on another
|
||||
|
||||
+38
-16
@@ -37,7 +37,23 @@ typedef struct RadMtpCoupleState {
|
||||
int32_t status, round, x, count;
|
||||
int32_t ids[8];
|
||||
double q[8];
|
||||
/* The node drafted `nkids` children, sampled without replacement from q, and ids[0 .. nkids)
|
||||
* are them in draft order (x == ids[0]; ids[nkids .. count) the rest of the support).
|
||||
* nkids <= 1 is the linear chain's single draw, whose ids keep the shortlist's order, and what
|
||||
* the serial MTP head writes (abi/rad_mtp_rrs.h states the siblings' law; the traversal walk of
|
||||
* abi/rad_mtp_traversal.h reads it). Zero from every writer that is not a sibling draw. */
|
||||
int32_t nkids;
|
||||
/* The sibling scheme of those children: 0 = Gumbel-top-k without replacement (the only one a
|
||||
* writer in this engine produces), m + 1 = RheoSampling's m deterministic top-q children plus
|
||||
* one sampled from the tail law (abi/rad_mtp_rrs.h). Zero from every other writer. */
|
||||
int32_t scheme;
|
||||
/* --draft-verify block (abi/rad_mtp_block.h): the length g of the block this row's chain is
|
||||
* verified as one (the rows 0 .. g-1 bound to rounds 1 .. g, staged on every row of it); 0 for
|
||||
* token-by-token verification. Written by the sampler's staging only; zero from the device. */
|
||||
int32_t blk;
|
||||
int32_t pad_;
|
||||
} RadMtpCoupleState;
|
||||
#define RAD_MTP_COUPLE_MAX_RHEO_M 7
|
||||
#define RAD_MTP_COUPLE_DRAW_WORDS (sizeof(RadMtpCoupleDraw) / 4)
|
||||
#define RAD_MTP_COUPLE_STATE_WORDS (sizeof(RadMtpCoupleState) / 4)
|
||||
#define RAD_MTP_COUPLE_MAX_ROUNDS 8
|
||||
@@ -46,7 +62,7 @@ typedef struct RadMtpCoupleState {
|
||||
#define RAD_MTP_COUPLE_KEY_DRAFT 0x4d5450434f55504cull
|
||||
#ifdef __cplusplus
|
||||
static_assert(sizeof(RadMtpCoupleDraw) == 32, "MTP coupling draw wire");
|
||||
static_assert(sizeof(RadMtpCoupleState) == 152, "MTP coupling state wire");
|
||||
static_assert(sizeof(RadMtpCoupleState) == 168, "MTP coupling state wire");
|
||||
static_assert(offsetof(RadMtpCoupleState, q) % 8 == 0, "MTP coupling q alignment");
|
||||
#endif
|
||||
|
||||
@@ -101,6 +117,10 @@ static inline RAD_SPECHUB_HD bool rad_mtp_couple_state_valid(const RadMtpCoupleS
|
||||
sum += s.q[i];
|
||||
has_x |= s.ids[i] == s.x;
|
||||
}
|
||||
if (s.nkids < 0 || s.nkids > s.count || (s.nkids >= 2 && s.ids[0] != s.x)) return false;
|
||||
if (s.scheme < 0 || s.scheme > RAD_MTP_COUPLE_MAX_RHEO_M + 1 ||
|
||||
(s.scheme && s.nkids >= 1 && s.ids[0] != s.x))
|
||||
return false;
|
||||
return has_x && (sum - 1) <= 1e-12 && (1 - sum) <= 1e-12;
|
||||
}
|
||||
|
||||
@@ -180,9 +200,9 @@ static inline RAD_SPECHUB_HD int rad_mtp_couple_pick(const RadMtpCoupleState& s,
|
||||
|
||||
/* Residual mass r(y) = max(0, P(y) - Q(y)) of one candidate. Q tokens use their P aggregated over
|
||||
* duplicate candidates, counted once at the first occurrence (`seen`). */
|
||||
static inline RAD_SPECHUB_HD double rad_mtp_couple_mass(const RadMtpCoupleState& s, const double* pq,
|
||||
int32_t id, float v, float top, double sum,
|
||||
unsigned* seen) {
|
||||
static inline RAD_SPECHUB_HD double rad_mtp_couple_mass(const RadMtpCoupleState& s,
|
||||
const double* pq, int32_t id, float v,
|
||||
float top, double sum, unsigned* seen) {
|
||||
if (id < 0 || v == -INFINITY) return 0;
|
||||
for (int k = 0; k < s.count; ++k)
|
||||
if (s.ids[k] == id) {
|
||||
@@ -278,14 +298,15 @@ static inline RAD_SPECHUB_HD bool rad_mtp_couple_decide(const RadMtpCoupleState&
|
||||
* ids are in the vocabulary (rad_mtp_couple_build_q), x_l ~ Q_l at the draw's
|
||||
* (seed, base, KEY_DRAFT + l + 1), and pid = x_l for position l + 1.
|
||||
*
|
||||
* Q_l depends on the committed text (through the drafter's pass and the anchor) and on x_0..x_{l-1},
|
||||
* never on the target's verification, and it is stored exactly in the state row the verify reads,
|
||||
* which is all the maximal coupling needs to be exact (rad_mtp_couple_decide). The pairwise term is
|
||||
* what makes Q_l follow the walk's own earlier samples rather than the drafter's marginal.
|
||||
* Q_l depends on the committed text (through the drafter's pass and the anchor) and on
|
||||
* x_0..x_{l-1}, never on the target's verification, and it is stored exactly in the state row the
|
||||
* verify reads, which is all the maximal coupling needs to be exact (rad_mtp_couple_decide). The
|
||||
* pairwise term is what makes Q_l follow the walk's own earlier samples rather than the drafter's
|
||||
* marginal.
|
||||
*
|
||||
* Bit-identical on host and device: each candidate's edge is RAD_DFLASH_EDGE_PARTS partial sums,
|
||||
* each a serial fmaf chain over a contiguous slice of the rank, added in order and then to the unary
|
||||
* score. The plugin builds with -ffp-contract=off, so nothing else is fused. */
|
||||
* each a serial fmaf chain over a contiguous slice of the rank, added in order and then to the
|
||||
* unary score. The plugin builds with -ffp-contract=off, so nothing else is fused. */
|
||||
#define RAD_DFLASH_EDGE_PARTS 8
|
||||
#define RAD_DFLASH_COUPLE_MAX_K 32
|
||||
#define RAD_DFLASH_COUPLE_MAX_R 512
|
||||
@@ -318,15 +339,15 @@ static inline RAD_SPECHUB_HD float rad_dflash_edge_part(const float* a, const ui
|
||||
*
|
||||
* The eight are taken in descending score, ties to the lower index, among candidates with an id
|
||||
* in [0, vocab); a NaN score is never taken (build_q would refuse it). */
|
||||
static inline RAD_SPECHUB_HD int32_t rad_dflash_couple_step(const float* sc, const int32_t* id,
|
||||
int K, float q_temp,
|
||||
const RadMtpCoupleDraw& d, bool card_ok,
|
||||
int round, int64_t vocab,
|
||||
int32_t greedy_x, RadMtpCoupleState* s) {
|
||||
static inline RAD_SPECHUB_HD int32_t rad_dflash_couple_step(
|
||||
const float* sc, const int32_t* id, int K, float q_temp, const RadMtpCoupleDraw& d,
|
||||
bool card_ok, int round, int64_t vocab, int32_t greedy_x, RadMtpCoupleState* s) {
|
||||
s->draw = d;
|
||||
s->pos = 0;
|
||||
s->round = round;
|
||||
s->count = 0;
|
||||
s->nkids = 0; /* a walk's position is one draw: the chain's wire */
|
||||
s->scheme = 0;
|
||||
for (int i = 0; i < 8; ++i) { s->ids[i] = -1; s->q[i] = 0; }
|
||||
if (d.mode != 1) {
|
||||
s->status = 0;
|
||||
@@ -403,7 +424,8 @@ static inline void rad_dflash_couple_walk(const int32_t* cand, const float* unar
|
||||
sc[c] = un[c] + acc;
|
||||
}
|
||||
}
|
||||
pid = rad_dflash_couple_step(sc, id, K, q_temp, d, card_ok, (int)l + 1, vocab, tokens[l], s);
|
||||
pid = rad_dflash_couple_step(sc, id, K, q_temp, d, card_ok, (int)l + 1, vocab, tokens[l],
|
||||
s);
|
||||
tokens[l] = pid;
|
||||
}
|
||||
}
|
||||
|
||||
+4
-2
@@ -16,7 +16,8 @@ extern "C" {
|
||||
|
||||
/* ------------------------------------------------------------------ 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). */
|
||||
* 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 */
|
||||
@@ -277,7 +278,8 @@ typedef struct RadParam {
|
||||
#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 })
|
||||
#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,
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
/* Geometry and the relative-position buckets of Wan's UMT5 encoder. */
|
||||
#pragma once
|
||||
|
||||
#include "rad_types.h"
|
||||
|
||||
namespace rad_umt5 {
|
||||
|
||||
constexpr int head_width = 64;
|
||||
constexpr int max_tokens = 512;
|
||||
constexpr int buckets = 32;
|
||||
|
||||
#if defined(__HIPCC__)
|
||||
__host__ __device__
|
||||
#endif
|
||||
inline int bucket(int distance) {
|
||||
// Wan T5RelativeEmbedding's 32 bidirectional buckets, max_distance 128.
|
||||
// Integer thresholds are the first distance in each logarithmic bucket.
|
||||
const int sign = distance > 0 ? buckets / 2 : 0;
|
||||
const int64_t mag = distance >= 0 ? distance : -static_cast<int64_t>(distance);
|
||||
if (mag < 8) return sign + static_cast<int>(mag);
|
||||
return sign + 8 + (mag >= 12) + (mag >= 16) + (mag >= 23) + (mag >= 32) +
|
||||
(mag >= 46) + (mag >= 64) + (mag >= 91);
|
||||
}
|
||||
|
||||
inline int validate(const RadTensor* const* matrices, const RadTensor* cu,
|
||||
const RadTensor* bias, int64_t heads, int64_t segments, int64_t& rows) {
|
||||
if (heads < 1 || heads > 128 || segments < 1 || segments > INT32_MAX - 1)
|
||||
return RAD_E_SHAPE;
|
||||
if (cu->dtype != RAD_I32 || bias->dtype != RAD_BF16) return RAD_E_DTYPE;
|
||||
if (cu->rank != 1 || cu->shape[0] != segments + 1 || bias->rank != 2 ||
|
||||
bias->shape[0] != buckets || bias->shape[1] != heads) return RAD_E_SHAPE;
|
||||
rows = matrices[0]->shape[0];
|
||||
const int64_t width = heads * head_width;
|
||||
if (rows < segments || rows > INT32_MAX || rows > segments * max_tokens) return RAD_E_SHAPE;
|
||||
if (cu->stride[0] != 1 || bias->stride[1] != 1 || bias->stride[0] < heads ||
|
||||
bias->stride[0] > (INT64_MAX - heads) / buckets) return RAD_E_STRIDE;
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
const RadTensor* t = matrices[i];
|
||||
if (t->dtype != RAD_BF16) return RAD_E_DTYPE;
|
||||
if (t->rank != 2 || t->shape[0] != rows || t->shape[1] != width) return RAD_E_SHAPE;
|
||||
if (t->stride[1] != 1 || t->stride[0] < width ||
|
||||
t->stride[0] > (INT64_MAX - width) / rows) return RAD_E_STRIDE;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} // namespace rad_umt5
|
||||
@@ -0,0 +1,21 @@
|
||||
/* The BF16 tanh GELU used by Wan's UMT5 feed-forward gate. */
|
||||
#pragma once
|
||||
|
||||
#include <cmath>
|
||||
|
||||
namespace rad_umt5 {
|
||||
|
||||
template<class Round>
|
||||
#if defined(__HIPCC__)
|
||||
__device__
|
||||
#endif
|
||||
inline float gelu(float x, Round round) {
|
||||
// PyTorch's BF16 cube uses two BF16 products. The remaining eager
|
||||
// operations also materialize BF16 before the next operation consumes them.
|
||||
const float cube = round(round(x * x) * x);
|
||||
const float inner = round(x + round(0.044715f * cube));
|
||||
const float activation = round(::tanhf(round(0.7978845608028654f * inner)));
|
||||
return round(round(0.5f * x) * round(1.0f + activation));
|
||||
}
|
||||
|
||||
} // namespace rad_umt5
|
||||
@@ -0,0 +1,32 @@
|
||||
/* Shared scalar arithmetic for the flow_unipc_step host and device ops. */
|
||||
#pragma once
|
||||
|
||||
namespace rad_unipc {
|
||||
|
||||
enum Coefficient {
|
||||
SIGMA, CORRECT_SAMPLE, CORRECT_CLEAN, CORRECT_PREVIOUS_DELTA, CORRECT_CURRENT_DELTA,
|
||||
PREDICT_SAMPLE, PREDICT_CLEAN, PREDICT_DELTA, COUNT,
|
||||
};
|
||||
|
||||
#if defined(__HIPCC__)
|
||||
__host__ __device__
|
||||
#endif
|
||||
inline float advance(const float* coefficients, float sample, float velocity,
|
||||
float& last_sample, float& last_clean, float& older_clean) {
|
||||
const float clean = sample - coefficients[SIGMA] * velocity;
|
||||
if (coefficients[CORRECT_SAMPLE] > 0.0f) {
|
||||
sample = coefficients[CORRECT_SAMPLE] * last_sample +
|
||||
coefficients[CORRECT_CLEAN] * last_clean +
|
||||
coefficients[CORRECT_PREVIOUS_DELTA] * (older_clean - last_clean) +
|
||||
coefficients[CORRECT_CURRENT_DELTA] * (clean - last_clean);
|
||||
}
|
||||
const float next = coefficients[PREDICT_SAMPLE] * sample +
|
||||
coefficients[PREDICT_CLEAN] * clean +
|
||||
coefficients[PREDICT_DELTA] * (last_clean - clean);
|
||||
last_sample = sample;
|
||||
older_clean = last_clean;
|
||||
last_clean = clean;
|
||||
return next;
|
||||
}
|
||||
|
||||
} // namespace rad_unipc
|
||||
@@ -0,0 +1,99 @@
|
||||
/* Wan TI2V's latent patch layout and three-axis rotary dimensions. */
|
||||
#pragma once
|
||||
|
||||
#include "rad_types.h"
|
||||
|
||||
namespace rad_wan_dit {
|
||||
|
||||
constexpr int head_width = 128;
|
||||
constexpr int pairs = head_width / 2;
|
||||
constexpr int spatial_pairs = pairs / 3;
|
||||
constexpr int time_pairs = pairs - 2 * spatial_pairs;
|
||||
constexpr int max_axis = 1024;
|
||||
|
||||
#if defined(__HIPCC__)
|
||||
__host__ __device__
|
||||
#endif
|
||||
inline int pair_axis(int pair) {
|
||||
return pair < time_pairs ? 0 : pair < time_pairs + spatial_pairs ? 1 : 2;
|
||||
}
|
||||
|
||||
#if defined(__HIPCC__)
|
||||
__host__ __device__
|
||||
#endif
|
||||
inline int pair_in_axis(int pair, int axis) {
|
||||
return axis == 0 ? pair : pair - time_pairs - (axis - 1) * spatial_pairs;
|
||||
}
|
||||
|
||||
#if defined(__HIPCC__)
|
||||
__host__ __device__
|
||||
#endif
|
||||
inline bool grid_rows(int64_t t, int64_t h, int64_t w, int64_t& rows) {
|
||||
if (t < 1 || t > max_axis || h < 1 || h > max_axis || w < 1 || w > max_axis)
|
||||
return false;
|
||||
rows = t * h * w;
|
||||
return true;
|
||||
}
|
||||
|
||||
#if defined(__HIPCC__)
|
||||
__host__ __device__
|
||||
#endif
|
||||
inline bool latent_grid(const int32_t* dims, int64_t& height, int64_t& width, int64_t& rows) {
|
||||
if (dims[1] % 2 || dims[2] % 2) return false;
|
||||
height = dims[1] / 2;
|
||||
width = dims[2] / 2;
|
||||
return grid_rows(dims[0], height, width, rows);
|
||||
}
|
||||
|
||||
#if defined(__HIPCC__)
|
||||
__host__ __device__
|
||||
#endif
|
||||
inline int64_t coordinate(int64_t row, int axis, int64_t h, int64_t w) {
|
||||
return axis == 0 ? row / (h * w) : axis == 1 ? (row / w) % h : row % w;
|
||||
}
|
||||
|
||||
#if defined(__HIPCC__)
|
||||
__host__ __device__
|
||||
#endif
|
||||
inline int64_t unpack_offset(int64_t row, int64_t channel, int64_t height, int64_t width,
|
||||
int64_t channels, int64_t pitch) {
|
||||
const int64_t x = row % (2 * width);
|
||||
const int64_t y = (row / (2 * width)) % (2 * height);
|
||||
const int64_t t = row / (4 * height * width);
|
||||
const int64_t patch = (t * height + y / 2) * width + x / 2;
|
||||
return patch * pitch + ((y % 2) * 2 + x % 2) * channels + channel;
|
||||
}
|
||||
|
||||
inline int check_matrix(const RadTensor* t, uint32_t dtype, int64_t rows, int64_t width) {
|
||||
if (t->dtype != dtype) return RAD_E_DTYPE;
|
||||
if (t->rank != 2 || t->shape[0] != rows || t->shape[1] != width || rows < 1 || width < 1)
|
||||
return RAD_E_SHAPE;
|
||||
if (t->stride[1] != 1 || t->stride[0] < width ||
|
||||
t->stride[0] > (INT64_MAX / 4 - width) / rows) return RAD_E_STRIDE;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
inline int check_grid(const RadTensor* grid) {
|
||||
if (grid->dtype != RAD_I32) return RAD_E_DTYPE;
|
||||
if (grid->rank != 1 || grid->shape[0] != 3) return RAD_E_SHAPE;
|
||||
return grid->stride[0] == 1 ? RAD_OK : RAD_E_STRIDE;
|
||||
}
|
||||
|
||||
// A layer has six learned modulation rows. The head uses two, both
|
||||
// conditioned by the same time embedding rather than six projected rows.
|
||||
inline int check_modulation(const RadTensor* time, const RadTensor* table,
|
||||
const RadTensor* split, int64_t width, bool head) {
|
||||
const int64_t steps = time->shape[0];
|
||||
if (steps != (split ? 2 : 1)) return RAD_E_SHAPE;
|
||||
const int rc = check_matrix(time, RAD_F32, steps, head ? width : 6 * width);
|
||||
if (rc < 0) return rc;
|
||||
if (table->dtype != RAD_F32 || (split && split->dtype != RAD_I32)) return RAD_E_DTYPE;
|
||||
if (table->rank != 3 || table->shape[0] != 1 || table->shape[1] != (head ? 2 : 6) ||
|
||||
table->shape[2] != width || (split && (split->rank != 1 || split->shape[0] != 1)))
|
||||
return RAD_E_SHAPE;
|
||||
if (table->stride[1] != width || table->stride[2] != 1)
|
||||
return RAD_E_STRIDE;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} // namespace rad_wan_dit
|
||||
@@ -0,0 +1,108 @@
|
||||
/* Wan's chunked causal convolution and decoder resampling layout. */
|
||||
#pragma once
|
||||
|
||||
#include "rad_wan_dit.h"
|
||||
|
||||
namespace rad_wan_vae {
|
||||
|
||||
constexpr int64_t max_spatial_axis = 8192;
|
||||
constexpr int64_t max_chunk_frames = 8;
|
||||
|
||||
#if defined(__HIPCC__)
|
||||
__host__ __device__
|
||||
#endif
|
||||
inline bool frame_plane(const int32_t* geom, int64_t offsets, int64_t& plane) {
|
||||
if (geom[0] + 1LL != offsets || geom[0] < 1 || geom[0] > max_chunk_frames ||
|
||||
geom[1] < 1 || geom[1] > max_spatial_axis || geom[2] < 1 || geom[2] > max_spatial_axis)
|
||||
return false;
|
||||
plane = (int64_t)geom[1] * geom[2];
|
||||
return true;
|
||||
}
|
||||
|
||||
inline int check_history(const RadTensor* x, const RadTensor* history, const RadTensor* out,
|
||||
bool temporal, int64_t& plane, int64_t& frames) {
|
||||
const int64_t rows = x->shape[0], channels = x->shape[1], cached = history->shape[0];
|
||||
if (rows < 1 || rows > INT32_MAX || channels < 1 || channels > 4096 ||
|
||||
cached < 2 || cached > INT32_MAX || (cached & 1)) return RAD_E_SHAPE;
|
||||
plane = cached / 2;
|
||||
if (rows % plane) return RAD_E_SHAPE;
|
||||
frames = rows / plane;
|
||||
int rc = rad_wan_dit::check_matrix(x, RAD_BF16, rows, channels);
|
||||
if (rc < 0) return rc;
|
||||
rc = rad_wan_dit::check_matrix(history, RAD_BF16, cached, channels);
|
||||
if (rc < 0) return rc;
|
||||
return rad_wan_dit::check_matrix(out, RAD_BF16, temporal ? rows : rows + cached,
|
||||
temporal ? 3 * channels : channels);
|
||||
}
|
||||
|
||||
template<bool Temporal>
|
||||
#if defined(__HIPCC__)
|
||||
__host__ __device__
|
||||
#endif
|
||||
inline void history_cell(const uint16_t* x, uint16_t* history, uint16_t* out,
|
||||
int64_t pixel, int64_t c, int64_t plane, int64_t frames,
|
||||
int64_t x_ld, int64_t h_ld, int64_t y_ld, bool reset) {
|
||||
uint16_t older = reset ? 0 : history[pixel * h_ld + c];
|
||||
uint16_t newer = reset ? 0 : history[(plane + pixel) * h_ld + c];
|
||||
if constexpr (!Temporal) {
|
||||
out[pixel * y_ld + c] = older;
|
||||
out[(plane + pixel) * y_ld + c] = newer;
|
||||
}
|
||||
for (int64_t frame = 0; frame < frames; ++frame) {
|
||||
const int64_t row = frame * plane + pixel;
|
||||
const uint16_t value = x[row * x_ld + c];
|
||||
if constexpr (Temporal) {
|
||||
uint16_t* tap = out + row * y_ld + c * 3;
|
||||
tap[0] = older;
|
||||
tap[1] = newer;
|
||||
tap[2] = value;
|
||||
} else {
|
||||
out[(row + 2 * plane) * y_ld + c] = value;
|
||||
}
|
||||
older = newer;
|
||||
newer = value;
|
||||
}
|
||||
history[pixel * h_ld + c] = older;
|
||||
history[(plane + pixel) * h_ld + c] = newer;
|
||||
}
|
||||
|
||||
inline int check_expand(const RadTensor* x, const RadTensor* out, int64_t cin, int64_t cout,
|
||||
int64_t st, int64_t s, int64_t drop, bool temporal) {
|
||||
const int64_t rows = x->shape[0], expanded = out->shape[0];
|
||||
if (cin < 1 || cin > 4096 || cout < 1 || cout > 4096 || st < 1 || st > 2 || s < 1 || s > 2 ||
|
||||
drop < 0 || drop >= st || rows > INT32_MAX || expanded > INT32_MAX)
|
||||
return RAD_E_SHAPE;
|
||||
if (temporal ? (st != 2 || s != 1 || cin != 2 * cout || drop != 0)
|
||||
: ((cout * st * s * s) % cin != 0)) return RAD_E_SHAPE;
|
||||
const int rc = rad_wan_dit::check_matrix(x, RAD_BF16, rows, cin);
|
||||
if (rc < 0) return rc;
|
||||
return rad_wan_dit::check_matrix(out, RAD_BF16, expanded, cout);
|
||||
}
|
||||
|
||||
#if defined(__HIPCC__)
|
||||
__host__ __device__
|
||||
#endif
|
||||
inline bool check_expand_grid(const int32_t* geom, int64_t rows, int64_t expanded,
|
||||
int64_t st, int64_t s, int64_t drop) {
|
||||
const int64_t t = geom[0], h = geom[1], w = geom[2];
|
||||
if (t < 1 || t > 1024 || h < 1 || h > max_spatial_axis || w < 1 || w > max_spatial_axis)
|
||||
return false;
|
||||
return rows == t * h * w && expanded == (t * st - drop) * h * w * s * s;
|
||||
}
|
||||
|
||||
#if defined(__HIPCC__)
|
||||
__host__ __device__
|
||||
#endif
|
||||
inline int64_t expand_offset(int64_t row, int64_t c, int64_t h, int64_t w, int64_t cin,
|
||||
int64_t cout, int64_t st, int64_t s, int64_t drop, bool temporal,
|
||||
int64_t pitch) {
|
||||
const int64_t out_w = w * s, out_h = h * s;
|
||||
const int64_t x = row % out_w, y = (row / out_w) % out_h;
|
||||
const int64_t t = row / (out_w * out_h) + drop;
|
||||
const int64_t src_row = ((t / st) * h + y / s) * w + x / s;
|
||||
if (temporal) return src_row * pitch + (t % st) * cout + c;
|
||||
const int64_t repeated = ((c * st + t % st) * s + y % s) * s + x % s;
|
||||
return src_row * pitch + repeated / (cout * st * s * s / cin);
|
||||
}
|
||||
|
||||
} // namespace rad_wan_vae
|
||||
+23
-51
@@ -44,7 +44,7 @@
|
||||
* ============================== WHAT IS QUANTISED ==============================
|
||||
*
|
||||
* One plugin serves bf16 and block-fp8 containers: the text encoder's linears and the DiT blocks'
|
||||
* attention and MLP linears are LinearFP8s (rad_fp8.h), bf16 throughout when the first DiT
|
||||
* attention and MLP linears are LinearQs (rad_linear.h), bf16 throughout when the first DiT
|
||||
* projection is plain. The adapter, the modulation and embedding linears, the final layer and the
|
||||
* VAE stay bf16. Every linear a LoRA for Anima names is a plain capable GEMM (gemm_nt or gemm_nt_q
|
||||
* without rotation), its activation applied by a separate op.
|
||||
@@ -52,13 +52,12 @@
|
||||
* One card: tensor parallelism is refused.
|
||||
*/
|
||||
#include <arch/rad_arch.h>
|
||||
#include <arch/rad_fp8.h>
|
||||
#include <arch/rad_linear.h>
|
||||
#include <arch/rad_vae2d.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
@@ -95,9 +94,9 @@ static const double kLatStd[16] = { 2.8184, 1.4541, 2.3275, 2.6558, 1.2196, 1.77
|
||||
/* ================================================================== the model */
|
||||
struct TeLayer {
|
||||
rad_weight w_n1 = 0, w_n2 = 0, w_qn = 0, w_kn = 0;
|
||||
LinearFP8 qkv{}, o{}, gate_up{}, down{};
|
||||
QuantFP8 q_h{}, q_attn{}, q_h2{};
|
||||
GateQuantFP8 gq{};
|
||||
LinearQ qkv{}, o{}, gate_up{}, down{};
|
||||
QuantAct q_h{}, q_attn{}, q_h2{};
|
||||
GateQuant gq{};
|
||||
rad_op op_n1 = 0, op_qkr = 0, op_attn = 0, op_add1 = 0, op_n2 = 0, op_add2 = 0;
|
||||
};
|
||||
|
||||
@@ -119,8 +118,8 @@ struct DitLayer {
|
||||
rad_weight w_qn = 0, w_kn = 0, w_cqn = 0, w_ckn = 0;
|
||||
rad_weight w_mod1[3] = { 0, 0, 0 }, w_mod2[3] = { 0, 0, 0 };
|
||||
rad_op op_mod1[3] = { 0, 0, 0 }, op_mod2[3] = { 0, 0, 0 }, op_modadd[3] = { 0, 0, 0 };
|
||||
LinearFP8 qkv{}, o{}, cq{}, ck{}, cv{}, co{}, l1{}, l2{};
|
||||
QuantFP8 q_attn{}, q_cattn{}, q_ffn{};
|
||||
LinearQ qkv{}, o{}, cq{}, ck{}, cv{}, co{}, l1{}, l2{};
|
||||
QuantAct q_attn{}, q_cattn{}, q_ffn{};
|
||||
rad_op op_n1 = 0, op_qkr = 0, op_attn = 0;
|
||||
rad_op op_n2 = 0, op_cqn = 0, op_ckn = 0, op_cattn = 0;
|
||||
rad_op op_n3 = 0, op_gelu = 0;
|
||||
@@ -143,7 +142,7 @@ struct Model {
|
||||
rad_weight w_tok = 0, w_tnorm = 0;
|
||||
rad_op op_embed = 0, op_tnorm = 0;
|
||||
rad_buf b_tx = 0, b_tkv = 0, b_th2 = 0, b_tgu = 0, b_src = 0;
|
||||
ActFP8 a_th{}, a_tattn{}, a_tffn{};
|
||||
ActQ a_th{}, a_tattn{}, a_tffn{};
|
||||
std::vector<TeLayer> te;
|
||||
|
||||
/* ---- the adapter */
|
||||
@@ -168,10 +167,10 @@ struct Model {
|
||||
rad_op op_g3 = 0, op_fn = 0, op_final = 0, op_euler = 0;
|
||||
rad_buf b_lat = 0, b_h = 0, b_qkv = 0, b_cq = 0, b_ck = 0, b_cv = 0, b_ao = 0, b_l1 = 0;
|
||||
rad_buf b_fz = 0, b_v = 0;
|
||||
ActFP8 a_hm{}, a_attn{}, a_ffn{}, a_ctx{};
|
||||
ActQ a_hm{}, a_attn{}, a_ffn{}, a_ctx{};
|
||||
std::vector<DitLayer> dit;
|
||||
LinearFP8 qkv0{};
|
||||
QuantFP8 q_ctx{};
|
||||
LinearQ qkv0{};
|
||||
QuantAct q_ctx{};
|
||||
|
||||
/* ---- the per-image state and the conditioning store (PERSIST) */
|
||||
rad_buf b_state = 0, b_prev = 0, b_store = 0;
|
||||
@@ -184,13 +183,7 @@ struct Model {
|
||||
std::string mul, add;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
|
||||
static rad_weight wcopy(RadBuilder* b, const char* dn, const char* src, uint32_t dtype,
|
||||
std::initializer_list<int64_t> shape, int access, int group) {
|
||||
if (map_copy(b, dn, src) < 0) return 0;
|
||||
return decl_w(b, dn, dtype, shape, access, RAD_SHARD_NONE, grp_layer(group));
|
||||
}
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* A plain bf16 linear without a bias: gemm_nt, the activation a separate op. `src` is one
|
||||
* checkpoint name, or several stacked along dim 0. */
|
||||
@@ -200,11 +193,7 @@ static rad_op dense(RadBuilder* b, const char* dn, std::initializer_list<const c
|
||||
if (map_linear(b, dn, src) < 0) return 0;
|
||||
*w = decl_w(b, dn, RAD_BF16, { N, K }, access, RAD_SHARD_NONE, grp_layer(group), 0, parts);
|
||||
if (!*w) return 0;
|
||||
return rw(b, 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)),
|
||||
{ in }, { out });
|
||||
return gemm_op(b, rows, N, K, *w, in, out);
|
||||
}
|
||||
|
||||
/* A bf16 linear with a bias. */
|
||||
@@ -215,27 +204,7 @@ static rad_op dense_bias(RadBuilder* b, Names& nm, const char* dn, const char* s
|
||||
group);
|
||||
*bias = wcopy(b, nm.f("%s.bias", dn), nm.ckpt("%s.bias", src), RAD_BF16, { N }, access, group);
|
||||
if (!*w || !*bias) return 0;
|
||||
return rw(b, 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_WEIGHTS(*w, *bias)),
|
||||
{ in }, { out });
|
||||
}
|
||||
|
||||
static rad_op unary(RadBuilder* b, const char* op, int64_t rows, int64_t n, rad_buf in,
|
||||
rad_buf out) {
|
||||
return rw(b, RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ in }, { out });
|
||||
}
|
||||
|
||||
static rad_op add_op(RadBuilder* b, int64_t rows, int64_t n, rad_buf a, rad_buf c, rad_buf y) {
|
||||
return rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ a, c }, { y });
|
||||
return gemm_bias_op(b, rows, N, K, *w, *bias, in, out);
|
||||
}
|
||||
|
||||
/* An RMS norm with a gain, `rows` rows of `n`. */
|
||||
@@ -702,7 +671,7 @@ static int declare_dit(RadBuilder* b, Model& m) {
|
||||
const bool q = !g.w_bf16;
|
||||
rad_op op = q ? RAD_OP(b, "rms_mod_quant_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), RAD_F64("eps", eps),
|
||||
RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_INT("group", RAD_SCALE_GROUP),
|
||||
RAD_INT("gated", gated ? 1 : 0), RAD_STR("dtype", "bf16"),
|
||||
RAD_STR("norm", "layer")),
|
||||
RAD_NOWEIGHTS)
|
||||
@@ -978,8 +947,9 @@ static int find_prefix(RadBuilder* b, Model& m, const char** marker) {
|
||||
|
||||
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];
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(check_format(meta, ctx));
|
||||
@@ -1014,9 +984,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
gd.eps = 1e-6f;
|
||||
|
||||
/* ---- bf16 or block fp8: what the container holds for the first DiT projection decides it
|
||||
* for every LinearFP8 of the text encoder and the DiT (rad_fp8.h, Geom::w_bf16). */
|
||||
* for every LinearQ of the text encoder and the DiT (rad_linear.h, Geom::w_bf16). */
|
||||
{
|
||||
LinearFP8& probe = m.qkv0;
|
||||
LinearQ& probe = m.qkv0;
|
||||
RAD_ARCH_TRY(probe.probe(b, nm, gd, nm.f("dit.blk.0.attn_qkv"),
|
||||
{ nm.ckpt("%sblocks.0.self_attn.q_proj.weight", m.pre.c_str()),
|
||||
nm.ckpt("%sblocks.0.self_attn.k_proj.weight", m.pre.c_str()),
|
||||
@@ -1335,7 +1305,7 @@ static void step_decode(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
if (!batch->gen || !batch->gen_b) {
|
||||
rad_step_fail(c, "anima is an image generator and runs generator passes only");
|
||||
return;
|
||||
@@ -1361,6 +1331,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(anima)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(anima, "anima", "", "0.1.0",
|
||||
"Anima (Base, Aesthetic, Turbo): Qwen3-0.6B through the LLM adapter, Cosmos-Predict2's "
|
||||
"2B diffusion transformer and the Qwen-Image VAE; bf16 or block-fp8 linears")
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/bailing_hybrid -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(bailing_hybrid LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(bailing_hybrid architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/bailing_hybrid.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/bailing_hybrid_gguf -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(bailing_hybrid_gguf LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(bailing_hybrid_gguf architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/bailing_hybrid_gguf.cpp)
|
||||
@@ -0,0 +1,12 @@
|
||||
/* bailing_hybrid_gguf -- the GGUF variant of bailing_hybrid for the tiny family's
|
||||
* IQ4_NL release: the same declaration and step, claiming the ftype-25 descriptor so the
|
||||
* quantised GGUF converts and serves. As in hyv3_gguf, a thin include over the family's
|
||||
* implementation with the namespace, the plugin name and the quant redefined. */
|
||||
#define bailing_hybrid bailing_hybrid_gguf
|
||||
#define BAILING_HYBRID_PLUGIN "bailing_hybrid_gguf"
|
||||
#define BAILING_HYBRID_QUANT "gguf_ftype_25"
|
||||
#include "../bailing_hybrid/bailing_hybrid.cpp"
|
||||
|
||||
/* GGUF file_type names the quant, never an imported tool descriptor: imports stay
|
||||
* with the family's bf16 plugin (rad_builder.h, rad_arch_serves_imports). */
|
||||
RAD_ARCH_SERVES_IMPORTS(0)
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/bailing_hybrid_gguf_q4km -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(bailing_hybrid_gguf_q4km LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(bailing_hybrid_gguf_q4km architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/bailing_hybrid_gguf_q4km.cpp)
|
||||
@@ -0,0 +1,12 @@
|
||||
/* bailing_hybrid_gguf_q4km -- the GGUF variant of bailing_hybrid for the tiny family's
|
||||
* Q4_K_M release: the same declaration and step, claiming the ftype-15 descriptor so the
|
||||
* quantised GGUF converts and serves. As in hyv3_gguf, a thin include over the family's
|
||||
* implementation with the namespace, the plugin name and the quant redefined. */
|
||||
#define bailing_hybrid bailing_hybrid_gguf_q4km
|
||||
#define BAILING_HYBRID_PLUGIN "bailing_hybrid_gguf_q4km"
|
||||
#define BAILING_HYBRID_QUANT "gguf_ftype_15"
|
||||
#include "../bailing_hybrid/bailing_hybrid.cpp"
|
||||
|
||||
/* GGUF file_type names the quant, never an imported tool descriptor: imports stay
|
||||
* with the family's bf16 plugin (rad_builder.h, rad_arch_serves_imports). */
|
||||
RAD_ARCH_SERVES_IMPORTS(0)
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/bailing_hybrid_gguf_q5km -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(bailing_hybrid_gguf_q5km LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(bailing_hybrid_gguf_q5km architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/bailing_hybrid_gguf_q5km.cpp)
|
||||
@@ -0,0 +1,12 @@
|
||||
/* bailing_hybrid_gguf_q5km -- the GGUF variant of bailing_hybrid for the tiny family's
|
||||
* Q5_K_M release: the same declaration and step, claiming the ftype-17 descriptor so the
|
||||
* quantised GGUF converts and serves. As in hyv3_gguf, a thin include over the family's
|
||||
* implementation with the namespace, the plugin name and the quant redefined. */
|
||||
#define bailing_hybrid bailing_hybrid_gguf_q5km
|
||||
#define BAILING_HYBRID_PLUGIN "bailing_hybrid_gguf_q5km"
|
||||
#define BAILING_HYBRID_QUANT "gguf_ftype_17"
|
||||
#include "../bailing_hybrid/bailing_hybrid.cpp"
|
||||
|
||||
/* GGUF file_type names the quant, never an imported tool descriptor: imports stay
|
||||
* with the family's bf16 plugin (rad_builder.h, rad_arch_serves_imports). */
|
||||
RAD_ARCH_SERVES_IMPORTS(0)
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/bailing_hybrid_gguf_q6k -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(bailing_hybrid_gguf_q6k LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(bailing_hybrid_gguf_q6k architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/bailing_hybrid_gguf_q6k.cpp)
|
||||
@@ -0,0 +1,12 @@
|
||||
/* bailing_hybrid_gguf_q6k -- the GGUF variant of bailing_hybrid for the tiny family's
|
||||
* Q6_K release: the same declaration and step, claiming the ftype-18 descriptor so the
|
||||
* quantised GGUF converts and serves. As in hyv3_gguf, a thin include over the family's
|
||||
* implementation with the namespace, the plugin name and the quant redefined. */
|
||||
#define bailing_hybrid bailing_hybrid_gguf_q6k
|
||||
#define BAILING_HYBRID_PLUGIN "bailing_hybrid_gguf_q6k"
|
||||
#define BAILING_HYBRID_QUANT "gguf_ftype_18"
|
||||
#include "../bailing_hybrid/bailing_hybrid.cpp"
|
||||
|
||||
/* GGUF file_type names the quant, never an imported tool descriptor: imports stay
|
||||
* with the family's bf16 plugin (rad_builder.h, rad_arch_serves_imports). */
|
||||
RAD_ARCH_SERVES_IMPORTS(0)
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/bailing_hybrid_gguf_q80 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(bailing_hybrid_gguf_q80 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(bailing_hybrid_gguf_q80 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/bailing_hybrid_gguf_q80.cpp)
|
||||
@@ -0,0 +1,12 @@
|
||||
/* bailing_hybrid_gguf_q80 -- the GGUF variant of bailing_hybrid for the tiny family's
|
||||
* Q8_0 release: the same declaration and step, claiming the ftype-7 descriptor so the
|
||||
* quantised GGUF converts and serves. As in hyv3_gguf, a thin include over the family's
|
||||
* implementation with the namespace, the plugin name and the quant redefined. */
|
||||
#define bailing_hybrid bailing_hybrid_gguf_q80
|
||||
#define BAILING_HYBRID_PLUGIN "bailing_hybrid_gguf_q80"
|
||||
#define BAILING_HYBRID_QUANT "gguf_ftype_7"
|
||||
#include "../bailing_hybrid/bailing_hybrid.cpp"
|
||||
|
||||
/* GGUF file_type names the quant, never an imported tool descriptor: imports stay
|
||||
* with the family's bf16 plugin (rad_builder.h, rad_arch_serves_imports). */
|
||||
RAD_ARCH_SERVES_IMPORTS(0)
|
||||
+340
-127
@@ -1,8 +1,9 @@
|
||||
/* breeze -- Breeze-TTS-2: speech from text, with an optional description of the voice; 24 kHz mono.
|
||||
/* breeze -- Breeze-TTS-2: speech from text, voice design or a reference recording; 24 kHz mono.
|
||||
*
|
||||
* ============================== THE MODEL ==============================
|
||||
*
|
||||
* Four networks (BreezeBlue's BreezeForConditionalGeneration and its audio tokenizer):
|
||||
* Four generation networks (BreezeBlue's BreezeForConditionalGeneration and its audio tokenizer),
|
||||
* plus the reference-audio encoder in reference.h for voice cloning:
|
||||
*
|
||||
* Text encoder: T5Gemma 2's text encoder, Gemma 3 1B's shape (26 layers of 1152, 4 query heads
|
||||
* over one KV head of 256, gelu-tanh GLU 6912, sandwich RMS norms with a (1 + w) gain), read
|
||||
@@ -39,8 +40,8 @@
|
||||
*
|
||||
* A request is a lane: its branches' last hidden states, its first codes so far (the penalty's
|
||||
* history), and every frame's sixteen codes, which the vocoder reads back. The depth decoder's
|
||||
* sequence is rebuilt every frame and recomputed whole at each of its fifteen steps (causal
|
||||
* attention keeps the positions not yet written out of every result it reads).
|
||||
* sixteen positions are computed incrementally, each from the keys and values the earlier
|
||||
* positions of its sequence stored (step_depth_inc).
|
||||
*
|
||||
* One card: the model is 3.6B parameters, and a speech in flight is bound by the step's latency,
|
||||
* which tensor parallelism would only lengthen.
|
||||
@@ -51,6 +52,7 @@
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
@@ -85,6 +87,8 @@ constexpr int64_t kVocChunk = 4, kConvCtx = 12, kAttnWin = 72;
|
||||
constexpr int64_t kVocContext = 2 + (kAttnWin - 1) + kConvCtx;
|
||||
constexpr int64_t kConvFrames = kConvCtx + kVocChunk;
|
||||
constexpr int64_t kCbBins = 2048, kCbDim = 256;
|
||||
/* One clean reference of at most ten seconds (rounded to complete codec frames). */
|
||||
constexpr int64_t kMaxRefFrames = 125, kMaxRefSamples = kMaxRefFrames * kSamplesPerFrame;
|
||||
/* The codec's sequence rates, rows a frame: the transformer's frames, the convolutions' frames,
|
||||
* the two upsamplings', and each decoder block's output (8, 5, 4, 3 times). */
|
||||
constexpr int kRates = 8;
|
||||
@@ -160,7 +164,34 @@ struct Llama3 {
|
||||
double factor = 0, low = 0, high = 0, orig = 0;
|
||||
};
|
||||
|
||||
struct RefConv {
|
||||
rad_weight w = 0, b = 0;
|
||||
rad_op op = 0;
|
||||
};
|
||||
struct RefLayer {
|
||||
rad_weight n1 = 0, b1 = 0, n2 = 0, b2 = 0, qkv = 0, o = 0, fc1 = 0, fc2 = 0;
|
||||
rad_weight ls1 = 0, ls2 = 0;
|
||||
rad_op norm1 = 0, norm2 = 0, proj = 0, rope = 0, attn = 0, out = 0;
|
||||
rad_op f1 = 0, act = 0, f2 = 0, scale1 = 0, scale2 = 0, add1 = 0, add2 = 0;
|
||||
};
|
||||
struct Reference {
|
||||
RefConv first{}, res1[4]{}, res2[4]{}, down[4]{}, last{}, sample{};
|
||||
rad_buf x[5]{}, a[5]{}, h[4]{}, z = 0, pad = 0, sampled = 0;
|
||||
rad_op elu[5]{}, elu_h[4]{};
|
||||
rad_buf th = 0, qkv = 0, attn = 0, o = 0, ff = 0, act = 0;
|
||||
RefLayer layer[8]{};
|
||||
rad_buf index = 0, cu = 0, text_pos = 0, text_cu = 0;
|
||||
rad_op indices = 0, copy_i = 0, copy_f = 0, text_indices = 0;
|
||||
rad_buf q[2]{}, codes = 0, eos_codes = 0;
|
||||
rad_weight qi[2]{}, cb[16]{};
|
||||
rad_op project[2]{}, quant[16]{}, embed = 0, eos = 0;
|
||||
};
|
||||
|
||||
struct Model {
|
||||
Reference ref{};
|
||||
/* The model holds the reference encoder (reference_stored), whose first weight is then already
|
||||
* in the name map. */
|
||||
bool ref_stored = false;
|
||||
Names nm{""};
|
||||
Llama3 l3{};
|
||||
Geom ge{}, gl{}, gd{}; /* the text encoder's, the backbone's, the depth decoder's */
|
||||
@@ -176,7 +207,6 @@ struct Model {
|
||||
|
||||
/* ---- the backbone */
|
||||
rad_weight w_norm = 0, w_head = 0;
|
||||
rad_op op_norm = 0;
|
||||
rad_buf b_x = 0, b_h = 0, b_q = 0, b_k = 0, b_v = 0, b_attn = 0, b_h2 = 0, b_gu = 0, b_ff = 0;
|
||||
rad_buf b_last = 0;
|
||||
std::vector<LmLayer> lm;
|
||||
@@ -202,6 +232,19 @@ struct Model {
|
||||
rad_buf b_dgu = 0, b_dff = 0, b_didx = 0, b_dpos = 0, b_dcu = 0, b_demb = 0, b_drow = 0;
|
||||
rad_buf b_dsel = 0, b_dplane = 0, b_dlog = 0;
|
||||
std::vector<LmLayer> dep;
|
||||
/* The incremental form (step_depth_inc): each layer's keys and values at the frame's
|
||||
* positions, [n_layer * R, kv width] (sequence s's position j at row l R + 16 s + j); the
|
||||
* bounds {0, 1} of a one-row query run and {0, p + 1} of pass p's key run; the pass's
|
||||
* positions. */
|
||||
rad_buf b_dkc = 0, b_dvc = 0, b_dcuq = 0, b_dcuk = 0, b_dposi = 0;
|
||||
rad_op op_dcuq = 0, op_dcuk[16] = {}, op_dposi[16] = {}, op_dnorm_i = 0;
|
||||
std::vector<rad_op> op_dsk, op_dsv, op_dxa;
|
||||
/* Its first pass, positions 0 and 1 together (2 S rows, a sequence's pair adjacent): the
|
||||
* pairs' rows {2 s} and {2 s + 1}, their positions {0, 1, 0, 1, ...}, a pair's store rows
|
||||
* {0, 1}, the pair's query bounds {0, 2}, and the causal attention over a pair. */
|
||||
rad_buf b_dev = 0, b_dodd = 0, b_dpos2 = 0, b_d01 = 0, b_dcuq2 = 0;
|
||||
rad_op op_dev = 0, op_dodd = 0, op_dpos2 = 0, op_d01 = 0, op_dcuq2 = 0;
|
||||
std::vector<rad_op> op_dxa2;
|
||||
|
||||
/* ---- the codec (VOCODE) */
|
||||
rad_weight w_cb0 = 0, w_cbr = 0, w_qo0 = 0, w_qor = 0;
|
||||
@@ -218,14 +261,14 @@ struct Model {
|
||||
rad_op op_fs = 0, op_fcast = 0, op_cnst = 0, op_ccu[8] = {};
|
||||
VConv fin{};
|
||||
rad_buf b_rq0 = 0, b_rqr = 0, b_qz = 0, b_qt = 0, b_pre = 0, b_cx = 0, b_ch = 0, b_cqkv = 0;
|
||||
rad_buf b_cattn = 0, b_co = 0, b_cgu = 0, b_cff = 0, b_cn = 0, b_cy = 0;
|
||||
rad_buf b_cattn = 0, b_co = 0, b_cgu = 0, b_cff = 0, b_cy = 0;
|
||||
rad_buf b_cconst = 0, b_ccu[8] = {};
|
||||
rad_buf b_ux[3] = {}, b_ua = 0, b_ub = 0, b_uh = 0, b_ug = 0;
|
||||
rad_buf b_vs[5] = {}, b_vt[5] = {}, b_va[5] = {}, b_vb[5] = {};
|
||||
rad_buf b_vout = 0, b_audio = 0;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* ================================================================== declare helpers */
|
||||
static rad_op norm_op(RadBuilder* b, int64_t rows, int64_t n, double eps, rad_weight w, rad_buf x,
|
||||
@@ -237,57 +280,6 @@ static rad_op norm_op(RadBuilder* b, int64_t rows, int64_t n, double eps, rad_we
|
||||
{ x }, { y });
|
||||
}
|
||||
|
||||
static rad_op add_op(RadBuilder* b, int64_t rows, int64_t n, rad_buf a, rad_buf c, rad_buf y) {
|
||||
return rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ a, c }, { y });
|
||||
}
|
||||
|
||||
static rad_op gemm_op(RadBuilder* b, int64_t rows, int64_t N, int64_t K, rad_weight w, rad_buf x,
|
||||
rad_buf y) {
|
||||
return rw(b, 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)),
|
||||
{ x }, { y });
|
||||
}
|
||||
|
||||
static rad_op gemm_bias_op(RadBuilder* b, int64_t rows, int64_t N, int64_t K, rad_weight w,
|
||||
rad_weight bias, rad_buf x, rad_buf y) {
|
||||
return rw(b, 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_WEIGHTS(w, bias)),
|
||||
{ x }, { y });
|
||||
}
|
||||
|
||||
static rad_op rows_op(RadBuilder* b, const char* op, int64_t rows, int64_t n,
|
||||
std::initializer_list<rad_buf> in, std::initializer_list<rad_buf> out) {
|
||||
return rw(b, RAD_OP(b, op,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
in, out);
|
||||
}
|
||||
|
||||
static rad_op mulw_op(RadBuilder* b, int64_t rows, int64_t n, rad_weight w, rad_buf x, rad_buf y) {
|
||||
return rw(b, RAD_OP(b, "mul_weight",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w)),
|
||||
{ x }, { y });
|
||||
}
|
||||
|
||||
static rad_op iota_op(RadBuilder* b, int64_t rows, int64_t start, int64_t step, rad_buf y) {
|
||||
return rw(b, RAD_OP(b, "iota",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("start", start),
|
||||
RAD_INT("step", step)),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, { y });
|
||||
}
|
||||
|
||||
static rad_op cu_op(RadBuilder* b, int64_t mult, rad_buf len, rad_buf y) {
|
||||
return rw(b, RAD_OP(b, "cu_repeat",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, 2), RAD_INT("mult", mult)),
|
||||
@@ -796,6 +788,74 @@ static int declare_frame(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
/* Each layer's attention also reads the frame's sequence offsets. */
|
||||
for (const LmLayer& L : m.dep) RAD_ARCH_TRY(rad_op_reads(b, L.op_attn, &m.b_dcu, 1));
|
||||
|
||||
/* The incremental form (step_depth_inc): pass p runs only position p, one row a sequence,
|
||||
* through the stack's own ops, and its attention reads the keys and values the earlier passes
|
||||
* stored. Its tables are PERSIST, so the planner never lays them over anything; the stack's
|
||||
* buffers it uses in another order are carried through the read-out below. */
|
||||
{
|
||||
const int64_t kd = gd.n_head_kv * gd.head_dim, hd = gd.head_dim;
|
||||
m.b_dkc = decl_b(b, nm.f("dep.kc"), RAD_BF16, { gd.n_layer * R, kd }, RAD_BUF_PERSIST);
|
||||
m.b_dvc = decl_b(b, nm.f("dep.vc"), RAD_BF16, { gd.n_layer * R, kd }, RAD_BUF_PERSIST);
|
||||
m.b_dcuq = decl_b(b, nm.f("dep.cuq"), RAD_I32, { 2 }, RAD_BUF_PERSIST);
|
||||
m.b_dcuk = decl_b(b, nm.f("dep.cuk"), RAD_I32, { 2 * kCodes }, RAD_BUF_PERSIST);
|
||||
m.b_dposi = decl_b(b, nm.f("dep.posi"), RAD_I32, { S }, RAD_BUF_PERSIST);
|
||||
m.op_dcuq = iota_op(b, 2, 0, 1, m.b_dcuq);
|
||||
for (int p = 0; p < kCodes; ++p) {
|
||||
m.op_dcuk[p] = iota_op(b, 2, 0, p + 1, m.b_dcuk);
|
||||
m.op_dposi[p] = iota_op(b, S, p, 0, m.b_dposi);
|
||||
}
|
||||
for (int64_t l = 0; l < gd.n_layer; ++l) {
|
||||
auto scat = [&](rad_buf src, rad_buf cache) {
|
||||
return rw(b, RAD_OP(b, "scatter_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", kd),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ src, m.b_didx }, { cache });
|
||||
};
|
||||
m.op_dsk.push_back(scat(m.b_dk, m.b_dkc));
|
||||
m.op_dsv.push_back(scat(m.b_dv, m.b_dvc));
|
||||
m.op_dxa.push_back(rw(b, RAD_OP(b, "attn_cross",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("head_dim", hd),
|
||||
RAD_INT("gqa", gd.n_head / gd.n_head_kv),
|
||||
RAD_INT("causal", 0), RAD_STR("dtype", "bf16"),
|
||||
RAD_F64("scale", 1.0 / std::sqrt((double)hd))),
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.b_dq, m.b_dkc, m.b_dvc, m.b_dcuq, m.b_dcuk }, { m.b_dattn }));
|
||||
if (!m.op_dsk.back() || !m.op_dsv.back() || !m.op_dxa.back()) return RAD_E_INVAL;
|
||||
}
|
||||
m.b_dev = decl_b(b, nm.f("dep.ev"), RAD_I32, { S }, RAD_BUF_PERSIST);
|
||||
m.b_dodd = decl_b(b, nm.f("dep.odd"), RAD_I32, { S }, RAD_BUF_PERSIST);
|
||||
m.b_dpos2 = decl_b(b, nm.f("dep.pos2"), RAD_I32, { 2 * S }, RAD_BUF_PERSIST);
|
||||
m.b_d01 = decl_b(b, nm.f("dep.01"), RAD_I32, { 2 }, RAD_BUF_PERSIST);
|
||||
m.b_dcuq2 = decl_b(b, nm.f("dep.cuq2"), RAD_I32, { 2 }, RAD_BUF_PERSIST);
|
||||
m.op_dev = iota_op(b, S, 0, 2, m.b_dev);
|
||||
m.op_dodd = iota_op(b, S, 1, 2, m.b_dodd);
|
||||
m.op_dpos2 = rw(b, RAD_OP(b, "iota",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, 2 * S), RAD_INT("start", 0),
|
||||
RAD_INT("step", 1), RAD_INT("period", 2)),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, { m.b_dpos2 });
|
||||
m.op_d01 = iota_op(b, 2, 0, 1, m.b_d01);
|
||||
m.op_dcuq2 = iota_op(b, 2, 0, 2, m.b_dcuq2);
|
||||
for (int64_t l = 0; l < gd.n_layer; ++l) {
|
||||
m.op_dxa2.push_back(rw(b, RAD_OP(b, "attn_cross",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, 2), RAD_INT("head_dim", hd),
|
||||
RAD_INT("gqa", gd.n_head / gd.n_head_kv),
|
||||
RAD_INT("causal", 1), RAD_STR("dtype", "bf16"),
|
||||
RAD_F64("scale", 1.0 / std::sqrt((double)hd))),
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.b_dq, m.b_dkc, m.b_dvc, m.b_dcuq2, m.b_dcuk }, { m.b_dattn }));
|
||||
if (!m.op_dxa2.back()) return RAD_E_INVAL;
|
||||
}
|
||||
if (!m.b_dev || !m.b_dodd || !m.b_dpos2 || !m.b_d01 || !m.b_dcuq2 || !m.op_dev ||
|
||||
!m.op_dodd || !m.op_dpos2 || !m.op_d01 || !m.op_dcuq2)
|
||||
return RAD_E_INVAL;
|
||||
m.op_dnorm_i = norm_op(b, S, Dd, gd.eps, m.w_dnorm, m.b_dx, m.b_dplane);
|
||||
if (!m.b_dkc || !m.b_dvc || !m.b_dcuq || !m.b_dcuk || !m.b_dposi || !m.op_dcuq ||
|
||||
!m.op_dnorm_i)
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
m.op_dgather = rows_op(b, "gather_rows", S, Dd, { m.b_dx, m.b_didx }, { m.b_dsel });
|
||||
m.op_dnorm = norm_op(b, S, Dd, gd.eps, m.w_dnorm, m.b_dsel, m.b_dplane);
|
||||
m.op_dhead = rw(b, RAD_OP(b, "logits_gemm",
|
||||
@@ -813,10 +873,15 @@ static int declare_frame(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
RAD_INT("sup_hi", kSupHi)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.b_dlog }, { m.b_codes });
|
||||
/* The buffers the next run of the stack reads stay live through this one's read-out. */
|
||||
/* The buffers the next run of the stack reads stay live through this one's read-out; the
|
||||
* incremental form also reads the stack's row buffers in its own order (layer 0's residual is
|
||||
* the projected row, the read-out reads the residual itself). */
|
||||
{
|
||||
const rad_buf carried[] = { m.b_dseq, m.b_dpos, m.b_dcu, m.b_didx };
|
||||
RAD_ARCH_TRY(rad_op_reads(b, m.op_dsamp[kCodes - 1], carried, 4));
|
||||
const rad_buf carried[] = { m.b_dseq, m.b_dpos, m.b_dcu, m.b_didx, m.b_drow, m.b_demb,
|
||||
m.b_dx, m.b_dh, m.b_dq, m.b_dk, m.b_dv, m.b_dattn, m.b_dh2,
|
||||
m.b_dgu, m.b_dff };
|
||||
RAD_ARCH_TRY(rad_op_reads(b, m.op_dsamp[kCodes - 1], carried,
|
||||
(int)(sizeof carried / sizeof carried[0])));
|
||||
}
|
||||
|
||||
/* ---- the frame's codes into the lane's history; the next input of the backbone */
|
||||
@@ -1158,12 +1223,8 @@ static int declare_codec(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
rows[4], m.b_vt[4], 0, m.b_vout, m.b_ccu[7]));
|
||||
m.b_audio = decl_b(b, nm.f("codec.audio"), RAD_F32, { kVocChunk * kSamplesPerFrame, 1 },
|
||||
RAD_BUF_PERSIST);
|
||||
m.op_fcast = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, (int64_t)kVocChunk * kSamplesPerFrame),
|
||||
RAD_INT("n", 1), RAD_STR("from", "bf16"),
|
||||
RAD_STR("to", "f32")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.b_vout }, { m.b_audio });
|
||||
m.op_fcast = cast_op(b, (int64_t)kVocChunk * kSamplesPerFrame, 1, "bf16", "f32", m.b_vout,
|
||||
m.b_audio);
|
||||
return m.w_cb0 && m.w_cbr && m.w_qo0 && m.w_qor && m.w_ip && m.b_ip && m.w_cn && m.w_op &&
|
||||
m.b_op && m.op_fs && m.op_fcast && m.op_cnst
|
||||
? RAD_OK
|
||||
@@ -1183,10 +1244,13 @@ static int check_format(const RadModelMeta* meta) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
#include "reference.h"
|
||||
|
||||
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];
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(check_format(meta));
|
||||
@@ -1213,6 +1277,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_ARCH_TRY(declare_encoder(b, meta, m));
|
||||
RAD_ARCH_TRY(declare_frame(b, meta, m));
|
||||
RAD_ARCH_TRY(declare_codec(b, meta, m));
|
||||
/* A container converted before the reference encoder was in the recipe holds the generator
|
||||
* alone: it serves speech as before, and with no reference templates declared below the
|
||||
* server refuses a request that brings references, saying the model clones no voice. */
|
||||
m.ref_stored = reference_stored(b, m);
|
||||
if (m.ref_stored) RAD_ARCH_TRY(declare_reference(b, meta, m));
|
||||
|
||||
if (!ctx->shape_probe) {
|
||||
RadAudioGenDecl d{};
|
||||
@@ -1220,6 +1289,17 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
d.tmpl = kTemplate;
|
||||
d.tmpl_plain = kPlain;
|
||||
d.neg_tmpl = kPlain;
|
||||
d.branches = 2;
|
||||
if (m.ref_stored) {
|
||||
d.tmpl_ref = "{references}<bos>[S0]{input}";
|
||||
d.tmpl_ref_instruct = "{references}<bos>[S0]<ins_bos>{instructions}<ins_eos>{input}";
|
||||
d.neg_tmpl_ref = d.tmpl_ref;
|
||||
d.ref_item = "<bos>[S0]{text}{audio}<|audio_eos|>";
|
||||
d.ref_rate = kSampleRate;
|
||||
d.ref_hop = kSamplesPerFrame;
|
||||
d.ref_max_samples = kMaxRefSamples;
|
||||
d.ref_max = 1;
|
||||
}
|
||||
d.prompt_whole = 1;
|
||||
d.first_frame = 0;
|
||||
d.max_prompt = kMaxPrompt;
|
||||
@@ -1266,44 +1346,198 @@ static void step_backbone(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
m.b_h2, m.b_gu, m.b_ff, pos, cu, layer++);
|
||||
}
|
||||
|
||||
static void step_text(RadCtx* c, const Model& m, int64_t T, RadOperand tokens,
|
||||
RadOperand pos, RadOperand cu, RadOperand output) {
|
||||
const int64_t qd = m.ge.n_head * m.ge.head_dim, kd = m.ge.n_head_kv * m.ge.head_dim;
|
||||
/* The encoder over each branch's prompt, bidirectional within it; its projection is the
|
||||
* backbone's input. */
|
||||
RAD_ISSUE_N(c, m.op_eembed, T, tokens, RAD_W(m.w_etok),
|
||||
brows(m.b_ex, T));
|
||||
for (const EncLayer& L : m.enc) {
|
||||
RAD_ISSUE_N(c, L.op_n1, T, brows(m.b_ex, T), RAD_W(L.w_n1), brows(m.b_eh, T));
|
||||
RAD_ISSUE_N(c, L.op_qkv, T, brows(m.b_eh, T), RAD_W(L.w_qkv), brows(m.b_eqkv, T));
|
||||
RAD_ISSUE_N(c, L.op_qknr, T, brows(m.b_eqkv, T), pos, RAD_W(L.w_qn), RAD_W(L.w_kn));
|
||||
RAD_ISSUE_N(c, L.op_attn, T, bcol(m.b_eqkv, 0, qd, T), bcol(m.b_eqkv, qd, kd, T),
|
||||
bcol(m.b_eqkv, qd + kd, kd, T), cu, brows(m.b_eattn, T));
|
||||
RAD_ISSUE_N(c, L.op_o, T, brows(m.b_eattn, T), RAD_W(L.w_o), brows(m.b_eo, T));
|
||||
RAD_ISSUE_N(c, L.op_n2, T, brows(m.b_eo, T), RAD_W(L.w_n2), brows(m.b_eh, T));
|
||||
RAD_ISSUE_N(c, L.op_add1, T, brows(m.b_ex, T), brows(m.b_eh, T), brows(m.b_ex, T));
|
||||
RAD_ISSUE_N(c, L.op_n3, T, brows(m.b_ex, T), RAD_W(L.w_n3), brows(m.b_eh, T));
|
||||
RAD_ISSUE_N(c, L.op_gu, T, brows(m.b_eh, T), RAD_W(L.w_gu), brows(m.b_egu, T));
|
||||
RAD_ISSUE_N(c, L.op_act, T, brows(m.b_egu, T), brows(m.b_eff, T));
|
||||
RAD_ISSUE_N(c, L.op_down, T, brows(m.b_eff, T), RAD_W(L.w_down), brows(m.b_eo, T));
|
||||
RAD_ISSUE_N(c, L.op_n4, T, brows(m.b_eo, T), RAD_W(L.w_n4), brows(m.b_eh, T));
|
||||
RAD_ISSUE_N(c, L.op_add2, T, brows(m.b_ex, T), brows(m.b_eh, T), brows(m.b_ex, T));
|
||||
}
|
||||
RAD_ISSUE_N(c, m.op_enorm, T, brows(m.b_ex, T), RAD_W(m.w_enorm), brows(m.b_eh, T));
|
||||
RAD_ISSUE_N(c, m.op_eproj, T, brows(m.b_eh, T), RAD_W(m.w_eproj), output);
|
||||
}
|
||||
|
||||
/* rvq_embed reads codebook 0 from its first table and codebooks 1..15 from its
|
||||
* second table, whose row zero must therefore be the start of codebook 1. */
|
||||
static RadOperand residual_codebooks(const Model& m) {
|
||||
RadOperand t = RAD_W(m.w_cb);
|
||||
t.offset = (int64_t)kVocab * m.gl.n_embd;
|
||||
t.rows = (int64_t)(kCodes - 1) * kVocab;
|
||||
return t;
|
||||
}
|
||||
|
||||
static void step_prompt(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
const RadAudioGenBatch* A = batch->agen_b;
|
||||
const int64_t T = batch->n_tok;
|
||||
const int64_t qd = m.ge.n_head * m.ge.head_dim, kd = m.ge.n_head_kv * m.ge.head_dim;
|
||||
const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1);
|
||||
const RadOperand pos = praw(batch->positions, RAD_I32, T);
|
||||
/* The encoder over each branch's prompt, bidirectional within it; its projection is the
|
||||
* backbone's input. */
|
||||
RAD_ISSUE(c, m.op_eembed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_etok),
|
||||
brows(m.b_ex, T));
|
||||
for (const EncLayer& L : m.enc) {
|
||||
RAD_ISSUE(c, L.op_n1, brows(m.b_ex, T), RAD_W(L.w_n1), brows(m.b_eh, T));
|
||||
RAD_ISSUE(c, L.op_qkv, brows(m.b_eh, T), RAD_W(L.w_qkv), brows(m.b_eqkv, T));
|
||||
RAD_ISSUE(c, L.op_qknr, brows(m.b_eqkv, T), pos, RAD_W(L.w_qn), RAD_W(L.w_kn));
|
||||
RAD_ISSUE_N(c, L.op_attn, T, bcol(m.b_eqkv, 0, qd, T), bcol(m.b_eqkv, qd, kd, T),
|
||||
bcol(m.b_eqkv, qd + kd, kd, T), cu, brows(m.b_eattn, T));
|
||||
RAD_ISSUE(c, L.op_o, brows(m.b_eattn, T), RAD_W(L.w_o), brows(m.b_eo, T));
|
||||
RAD_ISSUE(c, L.op_n2, brows(m.b_eo, T), RAD_W(L.w_n2), brows(m.b_eh, T));
|
||||
RAD_ISSUE(c, L.op_add1, brows(m.b_ex, T), brows(m.b_eh, T), brows(m.b_ex, T));
|
||||
RAD_ISSUE(c, L.op_n3, brows(m.b_ex, T), RAD_W(L.w_n3), brows(m.b_eh, T));
|
||||
RAD_ISSUE(c, L.op_gu, brows(m.b_eh, T), RAD_W(L.w_gu), brows(m.b_egu, T));
|
||||
RAD_ISSUE(c, L.op_act, brows(m.b_egu, T), brows(m.b_eff, T));
|
||||
RAD_ISSUE(c, L.op_down, brows(m.b_eff, T), RAD_W(L.w_down), brows(m.b_eo, T));
|
||||
RAD_ISSUE(c, L.op_n4, brows(m.b_eo, T), RAD_W(L.w_n4), brows(m.b_eh, T));
|
||||
RAD_ISSUE(c, L.op_add2, brows(m.b_ex, T), brows(m.b_eh, T), brows(m.b_ex, T));
|
||||
if (A->n_ref) {
|
||||
if (!A->prompt_cu_h || A->prompt_cu_h[0] != 0 ||
|
||||
A->prompt_cu_h[batch->n_seq] != T) {
|
||||
rad_step_fail(c, "breeze: reference prompt needs its host branch boundaries");
|
||||
return;
|
||||
}
|
||||
step_reference(c, batch, m);
|
||||
const Reference& E = m.ref;
|
||||
RAD_ISSUE_N(c, E.text_indices, kMaxPrompt, brows(E.text_pos, kMaxPrompt));
|
||||
RAD_ISSUE_N(c, E.eos, 16, brows(E.eos_codes, 16));
|
||||
/* Each branch has two independent text-encoder segments around its audio. The
|
||||
* backbone alone attends across the concatenation. Never encode audio placeholders
|
||||
* or the audio EOS as text, and reset rotary positions for each text segment. */
|
||||
for (int64_t branch = 0; branch < batch->n_seq; ++branch) {
|
||||
const int64_t end = A->prompt_cu_h[branch + 1];
|
||||
for (int64_t t = A->prompt_cu_h[branch]; t < end;) {
|
||||
const int32_t f = A->ref_frame_h[t];
|
||||
if (f >= 0) {
|
||||
int64_t n = 1;
|
||||
while (t + n < end && A->ref_frame_h[t + n] == f + n) ++n;
|
||||
if (t + n >= end) {
|
||||
rad_step_fail(c, "breeze: reference frames need their audio EOS row");
|
||||
return;
|
||||
}
|
||||
RAD_ISSUE_N(c, E.embed, n, bcol(E.codes, f, n, 16), RAD_W(m.w_cb),
|
||||
residual_codebooks(m), brow_slice(m.b_x, t, n, m.gl.n_embd));
|
||||
t += n;
|
||||
RAD_ISSUE_N(c, E.embed, 1, brows(E.eos_codes, 16), RAD_W(m.w_cb),
|
||||
residual_codebooks(m), brow_slice(m.b_x, t, 1, m.gl.n_embd));
|
||||
++t;
|
||||
} else {
|
||||
int64_t n = 1;
|
||||
while (t + n < end && A->ref_frame_h[t + n] < 0) ++n;
|
||||
ref_bounds(c, E, E.text_cu, n);
|
||||
step_text(c, m, n, praw(batch->token_ids + t, RAD_I32, n),
|
||||
brows(E.text_pos, n), brows(E.text_cu, 2),
|
||||
brow_slice(m.b_x, t, n, m.gl.n_embd));
|
||||
t += n;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
step_text(c, m, T, praw(batch->token_ids, RAD_I32, T),
|
||||
praw(batch->positions, RAD_I32, T),
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), brows(m.b_x, T));
|
||||
}
|
||||
RAD_ISSUE(c, m.op_enorm, brows(m.b_ex, T), RAD_W(m.w_enorm), brows(m.b_eh, T));
|
||||
RAD_ISSUE(c, m.op_eproj, brows(m.b_eh, T), RAD_W(m.w_eproj), brows(m.b_x, T));
|
||||
step_backbone(c, batch, m);
|
||||
bool any_last = false;
|
||||
for (int64_t i = 0; i < A->n_lane; ++i) any_last = any_last || A->last_h[i];
|
||||
if (any_last) store_hidden(c, m, A, batch->n_seq, A->last_row, T);
|
||||
}
|
||||
|
||||
/* The depth decoder's sixteen positions of every sequence, one pass for positions 0 and 1 (each
|
||||
* sequence's pair causal over itself) and one pass for each position p >= 2 alone (S rows). Each
|
||||
* pass stores its keys and values in the per-layer store and attends over positions 0..p from it,
|
||||
* one sequence at a time: the stack is causal, so a position's states never change once computed,
|
||||
* and every GEMM runs at decode height instead of re-running the stack over all 16 S rows
|
||||
* fifteen times a frame. On the 8060S that took a frame from 131 ms to 77. */
|
||||
static void step_depth_inc(RadCtx* c, const Model& m, int64_t S, const RadOperand& seed,
|
||||
const RadOperand& frame, const RadOperand& cfg,
|
||||
const std::function<RadOperand(int)>& codes,
|
||||
const std::function<RadOperand(int)>& idx) {
|
||||
const Geom& g = m.gd;
|
||||
const int64_t Rx = (int64_t)kCodes * m.S; /* a layer's rows in the store */
|
||||
const int64_t kd = g.n_head_kv * g.head_dim, qd = g.n_head * g.head_dim;
|
||||
const RadOperand cuq = brows(m.b_dcuq, 2), cuq2 = brows(m.b_dcuq2, 2);
|
||||
RAD_ISSUE_N(c, m.op_dcuq, 2, cuq);
|
||||
RAD_ISSUE_N(c, m.op_dcuq2, 2, cuq2);
|
||||
RAD_ISSUE_N(c, m.op_d01, 2, brows(m.b_d01, 2));
|
||||
RAD_ISSUE_N(c, m.op_dev, S, brows(m.b_dev, S));
|
||||
RAD_ISSUE_N(c, m.op_dodd, S, brows(m.b_dodd, S));
|
||||
RAD_ISSUE_N(c, m.op_dpos2, 2 * S, brows(m.b_dpos2, 2 * S));
|
||||
/* Pass 1 runs positions 0 and 1 (T = 2 S rows, sequence s's pair at rows 2 s and 2 s + 1, in
|
||||
* b_dseq); pass p >= 2 position p alone (S rows, layer 0's input the projected row). */
|
||||
for (int p = 1; p < kCodes; ++p) {
|
||||
const bool pair = p == 1;
|
||||
const int64_t T = pair ? 2 * S : S;
|
||||
const RadOperand cuk = brow_slice(m.b_dcuk, p, 2, 2);
|
||||
const RadOperand pos = pair ? brows(m.b_dpos2, T) : brows(m.b_dposi, S);
|
||||
RAD_ISSUE_N(c, m.op_dcuk[p], 2, cuk);
|
||||
if (pair) {
|
||||
RAD_ISSUE_N(c, m.op_din[0], S, brows(m.b_plane, S), RAD_W(m.w_din), brows(m.b_drow, S));
|
||||
RAD_ISSUE_N(c, m.op_dscat, S, brows(m.b_drow, S), brows(m.b_dev, S), brows(m.b_dseq, T));
|
||||
} else {
|
||||
RAD_ISSUE_N(c, m.op_dposi[p], S, pos);
|
||||
}
|
||||
RAD_ISSUE_N(c, m.op_demb[p], S, codes(p - 1), RAD_W(m.w_cb), RAD_W(m.w_cb),
|
||||
brows(m.b_demb, S));
|
||||
RAD_ISSUE_N(c, m.op_din[p], S, brows(m.b_demb, S), RAD_W(m.w_din), brows(m.b_drow, S));
|
||||
if (pair)
|
||||
RAD_ISSUE_N(c, m.op_dscat, S, brows(m.b_drow, S), brows(m.b_dodd, S), brows(m.b_dseq, T));
|
||||
for (size_t l = 0; l < m.dep.size(); ++l) {
|
||||
const LmLayer& L = m.dep[l];
|
||||
const rad_buf x_in = l > 0 ? m.b_dx : pair ? m.b_dseq : m.b_drow;
|
||||
RAD_ISSUE(c, L.op_n1, brows(x_in, T), RAD_W(L.w_n1), brows(m.b_dh, T));
|
||||
RAD_ISSUE(c, L.op_q, brows(m.b_dh, T), RAD_W(L.w_q), brows(m.b_dq, T));
|
||||
RAD_ISSUE(c, L.op_k, brows(m.b_dh, T), RAD_W(L.w_k), brows(m.b_dk, T));
|
||||
RAD_ISSUE(c, L.op_v, brows(m.b_dh, T), RAD_W(L.w_v), brows(m.b_dv, T));
|
||||
RAD_ISSUE(c, L.op_rq, brows(m.b_dq, T), pos);
|
||||
RAD_ISSUE(c, L.op_rk, brows(m.b_dk, T), pos);
|
||||
const int64_t l0 = (int64_t)l * Rx;
|
||||
if (pair) {
|
||||
/* A pair's two rows into its sequence's first two store rows, then causal over
|
||||
* them. */
|
||||
for (int64_t sq = 0; sq < S; ++sq) {
|
||||
const RadOperand kc = brow_slice(m.b_dkc, l0 + kCodes * sq, kCodes, kd);
|
||||
const RadOperand vc = brow_slice(m.b_dvc, l0 + kCodes * sq, kCodes, kd);
|
||||
RAD_ISSUE_N(c, m.op_dsk[l], 2, brow_slice(m.b_dk, 2 * sq, 2, kd),
|
||||
brows(m.b_d01, 2), kc);
|
||||
RAD_ISSUE_N(c, m.op_dsv[l], 2, brow_slice(m.b_dv, 2 * sq, 2, kd),
|
||||
brows(m.b_d01, 2), vc);
|
||||
RAD_ISSUE_N(c, m.op_dxa2[l], 2, brow_slice(m.b_dq, 2 * sq, 2, qd), kc, vc, cuq2,
|
||||
cuk, brow_slice(m.b_dattn, 2 * sq, 2, qd));
|
||||
}
|
||||
} else {
|
||||
RAD_ISSUE_N(c, m.op_dsk[l], S, brows(m.b_dk, S), idx(p),
|
||||
brow_slice(m.b_dkc, l0, Rx, kd));
|
||||
RAD_ISSUE_N(c, m.op_dsv[l], S, brows(m.b_dv, S), idx(p),
|
||||
brow_slice(m.b_dvc, l0, Rx, kd));
|
||||
for (int64_t sq = 0; sq < S; ++sq)
|
||||
RAD_ISSUE_N(c, m.op_dxa[l], 1, brow_slice(m.b_dq, sq, 1, qd),
|
||||
brow_slice(m.b_dkc, l0 + kCodes * sq, kCodes, kd),
|
||||
brow_slice(m.b_dvc, l0 + kCodes * sq, kCodes, kd), cuq, cuk,
|
||||
brow_slice(m.b_dattn, sq, 1, qd));
|
||||
}
|
||||
RAD_ISSUE(c, L.op_o, brows(m.b_dattn, T), RAD_W(L.w_o), brows(m.b_dh2, T));
|
||||
RAD_ISSUE(c, L.op_add1, brows(x_in, T), brows(m.b_dh2, T), brows(m.b_dx, T));
|
||||
RAD_ISSUE(c, L.op_n2, brows(m.b_dx, T), RAD_W(L.w_n2), brows(m.b_dh, T));
|
||||
RAD_ISSUE(c, L.op_gu, brows(m.b_dh, T), RAD_W(L.w_gu), brows(m.b_dgu, T));
|
||||
RAD_ISSUE(c, L.op_act, brows(m.b_dgu, T), brows(m.b_dff, T));
|
||||
RAD_ISSUE(c, L.op_down, brows(m.b_dff, T), RAD_W(L.w_down), brows(m.b_dh2, T));
|
||||
RAD_ISSUE(c, L.op_add2, brows(m.b_dx, T), brows(m.b_dh2, T), brows(m.b_dx, T));
|
||||
}
|
||||
if (pair) {
|
||||
/* Position 1's rows are the read-out's. */
|
||||
RAD_ISSUE_N(c, m.op_dgather, S, brows(m.b_dx, T), brows(m.b_dodd, S), brows(m.b_dsel, S));
|
||||
RAD_ISSUE_N(c, m.op_dnorm, S, brows(m.b_dsel, S), RAD_W(m.w_dnorm), brows(m.b_dplane, S));
|
||||
} else {
|
||||
RAD_ISSUE_N(c, m.op_dnorm_i, S, brows(m.b_dx, S), RAD_W(m.w_dnorm), brows(m.b_dplane, S));
|
||||
}
|
||||
RadOperand head = RAD_W(m.w_dheads);
|
||||
head.offset = (int64_t)(p - 1) * kVocab * g.n_embd;
|
||||
head.rows = kVocab;
|
||||
RAD_ISSUE_N(c, m.op_dhead, S, brows(m.b_dplane, S), head, brows(m.b_dlog, S));
|
||||
RAD_ISSUE_N(c, m.op_dsamp[p], S, brows(m.b_dlog, S), seed, frame, codes(p), cfg, RAD_NONE,
|
||||
RAD_NONE);
|
||||
}
|
||||
}
|
||||
|
||||
static void step_frame(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
const RadAudioGenBatch* A = batch->agen_b;
|
||||
const int64_t n = A->n_lane, S = 2 * n, R = (int64_t)kCodes * S, D = m.gl.n_embd;
|
||||
const int64_t Dd = m.gd.n_embd, Sx = m.S; /* Sx: the codes' and indices' row pitch */
|
||||
const int64_t n = A->n_lane, S = 2 * n;
|
||||
const int64_t Sx = m.S; /* the codes' and indices' row pitch */
|
||||
const RadOperand seed = praw(A->seed, RAD_U32, 2 * n), frame = praw(A->frame, RAD_I32, n);
|
||||
const RadOperand lanes = praw(A->lane, RAD_I32, n), slot = praw(A->slot, RAD_I32, S);
|
||||
const RadOperand cfg = praw(A->cfg, RAD_F32, n);
|
||||
@@ -1326,41 +1560,13 @@ static void step_frame(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
/* 2. the depth decoder's sequences: 16 rows each, the hidden state's projection at position 0
|
||||
* and each code's from position 1 */
|
||||
for (int p = 0; p < kCodes; ++p) RAD_ISSUE_N(c, m.op_iota[p], S, idx(p));
|
||||
RAD_ISSUE_N(c, m.op_dpos, R, brows(m.b_dpos, R));
|
||||
RAD_ISSUE_N(c, m.op_dzero, R, brows(m.b_dseq, R));
|
||||
RAD_ISSUE_N(c, m.op_dcu, S + 1, praw(batch->cu_seqlens + 1, RAD_I32, 1), brows(m.b_dcu, S + 1));
|
||||
RAD_ISSUE_N(c, m.op_din[0], S, brows(m.b_plane, S), RAD_W(m.w_din), brows(m.b_drow, S));
|
||||
RAD_ISSUE_N(c, m.op_dscat, S, brows(m.b_drow, S), idx(0), brows(m.b_dseq, R));
|
||||
const RadOperand dpos_r = brows(m.b_dpos, R);
|
||||
const RadOperand dcu = brows(m.b_dcu, S + 1);
|
||||
for (int p = 1; p < kCodes; ++p) {
|
||||
/* Code p - 1 into position p. */
|
||||
RAD_ISSUE_N(c, m.op_demb[p], S, codes(p - 1), RAD_W(m.w_cb), RAD_W(m.w_cb),
|
||||
brows(m.b_demb, S));
|
||||
RAD_ISSUE_N(c, m.op_din[p], S, brows(m.b_demb, S), RAD_W(m.w_din), brows(m.b_drow, S));
|
||||
RAD_ISSUE_N(c, m.op_dscat, S, brows(m.b_drow, S), idx(p), brows(m.b_dseq, R));
|
||||
int layer = 0;
|
||||
for (const LmLayer& L : m.dep)
|
||||
step_layer(c, m, m.gd, L, batch, R, m.b_dx, &L == &m.dep[0] ? m.b_dseq : m.b_dx, m.b_dh,
|
||||
m.b_dq, m.b_dk, m.b_dv, m.b_dattn, m.b_dh2, m.b_dgu, m.b_dff, dpos_r, dcu,
|
||||
layer++);
|
||||
RAD_ISSUE_N(c, m.op_dgather, S, brows(m.b_dx, R), idx(p), brows(m.b_dsel, S));
|
||||
RAD_ISSUE_N(c, m.op_dnorm, S, brows(m.b_dsel, S), RAD_W(m.w_dnorm), brows(m.b_dplane, S));
|
||||
RadOperand head = RAD_W(m.w_dheads);
|
||||
head.offset = (int64_t)(p - 1) * kVocab * Dd;
|
||||
head.rows = kVocab;
|
||||
RAD_ISSUE_N(c, m.op_dhead, S, brows(m.b_dplane, S), head, brows(m.b_dlog, S));
|
||||
RAD_ISSUE_N(c, m.op_dsamp[p], S, brows(m.b_dlog, S), seed, frame, codes(p), cfg, RAD_NONE,
|
||||
RAD_NONE);
|
||||
}
|
||||
step_depth_inc(c, m, S, seed, frame, cfg, codes, idx);
|
||||
|
||||
/* 3. the frame into its lane's history, and the backbone over the frame's embedding */
|
||||
RAD_ISSUE_N(c, m.op_store, n, brows(m.b_codes, kCodes), lanes, frame,
|
||||
brows(m.b_status, m.lanes), brows(m.b_codes_all, m.lanes * kCodes));
|
||||
RadOperand t1 = RAD_W(m.w_cb);
|
||||
t1.offset = (int64_t)kVocab * D;
|
||||
t1.rows = (int64_t)(kCodes - 1) * kVocab;
|
||||
RAD_ISSUE_N(c, m.op_fb, S, brows(m.b_codes, kCodes), RAD_W(m.w_cb), t1, brows(m.b_x, S));
|
||||
RAD_ISSUE_N(c, m.op_fb, S, brows(m.b_codes, kCodes), RAD_W(m.w_cb), residual_codebooks(m),
|
||||
brows(m.b_x, S));
|
||||
step_backbone(c, batch, m);
|
||||
store_hidden(c, m, A, S, A->last_row, S);
|
||||
}
|
||||
@@ -1475,7 +1681,7 @@ static void step_vocode(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
if (!batch->gen || !batch->agen_b) {
|
||||
rad_step_fail(c, "breeze is an audio generator and runs generator passes only");
|
||||
return;
|
||||
@@ -1503,6 +1709,11 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
static int64_t text_prepare(int field, const char* in, char* out, int64_t cap) {
|
||||
if (!in) return RAD_E_INVAL;
|
||||
std::string r = in;
|
||||
if (field == RAD_TEXT_REFERENCE) {
|
||||
for (const char* marker : {"<bos>", "<eos>", "<|AUDIO|>", "<|audio_eos|>",
|
||||
"<ins_bos>", "<ins_eos>"})
|
||||
if (r.find(marker) != std::string::npos) return RAD_E_INVAL;
|
||||
}
|
||||
if (field == RAD_TEXT_INSTRUCTIONS) {
|
||||
const size_t a = r.find_first_not_of(" \t\r\n"), z = r.find_last_not_of(" \t\r\n");
|
||||
r = a == std::string::npos ? std::string() : r.substr(a, z - a + 1);
|
||||
@@ -1521,6 +1732,8 @@ RAD_ARCH_PROBE(breeze)
|
||||
extern "C" int64_t rad_arch_text_prepare(int field, const char* in, char* out, int64_t cap) {
|
||||
return breeze::text_prepare(field, in, out, cap);
|
||||
}
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(breeze, "breeze", "", "0.1.0",
|
||||
"Breeze-TTS-2: a T5Gemma 2 text encoder over a Qwen3 backbone with a 16-codebook "
|
||||
"depth decoder and the Qwen3-TTS 12 Hz codec; 24 kHz mono speech")
|
||||
|
||||
@@ -0,0 +1,281 @@
|
||||
/* Breeze's Qwen3-TTS/Mimi reference encoder. Included inside namespace breeze after the
|
||||
* ordinary networks. Kept in f32, as the released audio tokenizer encodes references. */
|
||||
static rad_op ref_rows(RadBuilder* b, const char* op, int64_t rows, int64_t n,
|
||||
std::initializer_list<rad_buf> in, std::initializer_list<rad_buf> out,
|
||||
const char* dtype = "f32") {
|
||||
return rw(b, RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_STR("dtype", dtype)), RAD_NOWEIGHTS), in, out);
|
||||
}
|
||||
|
||||
static rad_op ref_gemm(RadBuilder* b, int64_t rows, int64_t n, int64_t k, rad_weight w,
|
||||
rad_buf x, rad_buf y) {
|
||||
return rw(b, RAD_OP(b, "gemm_nt", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", n),
|
||||
RAD_INT("K", k), RAD_STR("dtype", "f32")), RAD_WEIGHTS(w)), {x}, {y});
|
||||
}
|
||||
|
||||
static int ref_conv(RadBuilder* b, Model& m, RefConv& C, const char* name, const char* src,
|
||||
int64_t ci, int64_t co, int64_t k, int64_t st, int64_t rate, int64_t rows,
|
||||
rad_buf x, rad_buf res, rad_buf y, bool bias = true) {
|
||||
/* The first convolution's weight is mapped by reference_stored when that ran. */
|
||||
C.w = (m.ref_stored && &C == &m.ref.first)
|
||||
? decl_w(b, m.nm.f("ref.%s.weight", name), RAD_F32, {co, ci, k}, RAD_ACCESS_PER_TOKEN,
|
||||
RAD_SHARD_NONE, grp_layer(kGrpCodec + 1))
|
||||
: wcopy(b, m.nm, m.nm.f("ref.%s.weight", name), m.nm.ckpt("%s.weight", src),
|
||||
RAD_F32, {co, ci, k}, kGrpCodec + 1);
|
||||
if (bias) C.b = wcopy(b, m.nm, m.nm.f("ref.%s.bias", name), m.nm.ckpt("%s.bias", src),
|
||||
RAD_F32, {co}, kGrpCodec + 1);
|
||||
const rad_weight weights[] = {C.w, C.b};
|
||||
C.op = rw(b, RAD_OP(b, "conv1d", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("cin", ci),
|
||||
RAD_INT("cout", co), RAD_INT("k", k), RAD_INT("dil", 1),
|
||||
RAD_INT("causal", 1), RAD_INT("stride", st), RAD_INT("cu_div", rate),
|
||||
RAD_STR("dtype", "f32")), weights, bias ? 2 : 1),
|
||||
{x, m.ref.cu, res}, {y});
|
||||
return C.w && (!bias || C.b) && C.op ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* Whether the model holds the reference encoder, asked of its first convolution through the name
|
||||
* map entry declared here (the one ref_conv would declare). A builder with no model behind it
|
||||
* answers no. */
|
||||
static bool reference_stored(RadBuilder* b, Model& m) {
|
||||
const std::string dn = m.nm.f("ref.first.weight");
|
||||
if (map_copy(b, dn.c_str(),
|
||||
m.nm.ckpt("%s.weight", "audio_tokenizer.encoder.encoder.layers.0.conv")) < 0)
|
||||
return false;
|
||||
RadEncoding enc{};
|
||||
return weight_enc(b, dn.c_str(), &enc);
|
||||
}
|
||||
|
||||
static int declare_reference(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
Reference& E = m.ref;
|
||||
Names& nm = m.nm;
|
||||
const char* ec = "audio_tokenizer.encoder_config";
|
||||
if (rad_meta_geti(meta, nm.f("%s.hidden_size", ec), 0) != 512 ||
|
||||
rad_meta_geti(meta, nm.f("%s.num_hidden_layers", ec), 0) != 8 ||
|
||||
rad_meta_geti(meta, nm.f("%s.num_filters", ec), 0) != 64 ||
|
||||
rad_meta_geti(meta, nm.f("%s.use_causal_conv", ec), 1) != 1 ||
|
||||
rad_meta_geti(meta, nm.f("%s.use_conv_shortcut", ec), 0) != 0) {
|
||||
fprintf(stderr, "radiance: breeze: reference encoder is not the released Qwen3-TTS encoder\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
constexpr int64_t R = kMaxRefSamples / 960; /* SEANet's 25 Hz output */
|
||||
constexpr int64_t NI = 2 * kMaxPrompt + 3;
|
||||
E.index = decl_b(b, nm.f("ref.index"), RAD_I32, {NI}, RAD_BUF_PERSIST);
|
||||
E.indices = iota_op(b, NI, 0, 1, E.index);
|
||||
E.cu = decl_b(b, nm.f("ref.cu"), RAD_I32, {2}, RAD_BUF_PERSIST);
|
||||
E.text_pos = decl_b(b, nm.f("ref.text_pos"), RAD_I32, {kMaxPrompt}, RAD_BUF_PERSIST);
|
||||
E.text_cu = decl_b(b, nm.f("ref.text_cu"), RAD_I32, {2}, RAD_BUF_PERSIST);
|
||||
E.text_indices = iota_op(b, kMaxPrompt, 0, 1, E.text_pos);
|
||||
E.copy_i = rw(b, RAD_OP(b, "int_affine", RAD_PARAMS(RAD_INT("M", 1), RAD_STR("src", "0"),
|
||||
RAD_STR("mul", "1"), RAD_STR("add", "0")), RAD_NOWEIGHTS),
|
||||
{E.index}, {E.cu, E.text_cu});
|
||||
E.copy_f = rw(b, RAD_OP(b, "cast", RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", 512),
|
||||
RAD_STR("from", "f32"), RAD_STR("to", "f32")), RAD_NOWEIGHTS), {}, {});
|
||||
int64_t rows = kMaxRefSamples, ch = 64, rate = 1;
|
||||
static const int64_t stride[] = {4, 5, 6, 8};
|
||||
for (int i = 0; i < 5; ++i) {
|
||||
E.x[i] = decl_b(b, nm.f("ref.x%d", i), RAD_F32, {rows, ch});
|
||||
E.a[i] = decl_b(b, nm.f("ref.a%d", i), RAD_F32, {rows, ch});
|
||||
E.elu[i] = ref_rows(b, "elu", rows, ch, {E.x[i]}, {E.a[i]});
|
||||
if (i < 4) {
|
||||
E.h[i] = decl_b(b, nm.f("ref.h%d", i), RAD_F32, {rows, ch / 2});
|
||||
E.elu_h[i] = ref_rows(b, "elu", rows, ch / 2, {E.h[i]}, {E.h[i]});
|
||||
rows /= stride[i]; ch *= 2;
|
||||
}
|
||||
}
|
||||
RAD_ARCH_TRY(ref_conv(b, m, E.first, "first", "audio_tokenizer.encoder.encoder.layers.0.conv",
|
||||
1, 64, 7, 1, 1, kMaxRefSamples, 0, 0, E.x[0]));
|
||||
rows = kMaxRefSamples; ch = 64; rate = 1;
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
const int li = 1 + 3 * i;
|
||||
RAD_ARCH_TRY(ref_conv(b, m, E.res1[i], nm.f("res%d.1", i),
|
||||
nm.ckpt("audio_tokenizer.encoder.encoder.layers.%d.block.1.conv", li),
|
||||
ch, ch / 2, 3, 1, rate, rows, E.a[i], 0, E.h[i]));
|
||||
RAD_ARCH_TRY(ref_conv(b, m, E.res2[i], nm.f("res%d.2", i),
|
||||
nm.ckpt("audio_tokenizer.encoder.encoder.layers.%d.block.3.conv", li),
|
||||
ch / 2, ch, 1, 1, rate, rows, E.h[i], E.x[i], E.x[i]));
|
||||
RAD_ARCH_TRY(ref_conv(b, m, E.down[i], nm.f("down%d", i),
|
||||
nm.ckpt("audio_tokenizer.encoder.encoder.layers.%d.conv", li + 2),
|
||||
ch, 2 * ch, 2 * stride[i], stride[i], rate, rows,
|
||||
E.a[i], 0, E.x[i + 1]));
|
||||
rows /= stride[i]; rate *= stride[i]; ch *= 2;
|
||||
}
|
||||
E.z = decl_b(b, nm.f("ref.z"), RAD_F32, {R, 512});
|
||||
RAD_ARCH_TRY(ref_conv(b, m, E.last, "last", "audio_tokenizer.encoder.encoder.layers.14.conv",
|
||||
1024, 512, 3, 1, 960, R, E.a[4], 0, E.z));
|
||||
E.th = decl_b(b, nm.f("ref.th"), RAD_F32, {R, 512});
|
||||
E.qkv = decl_b(b, nm.f("ref.qkv"), RAD_F32, {R, 1536});
|
||||
E.attn = decl_b(b, nm.f("ref.attn"), RAD_F32, {R, 512});
|
||||
E.o = decl_b(b, nm.f("ref.o"), RAD_F32, {R, 512});
|
||||
E.ff = decl_b(b, nm.f("ref.ff"), RAD_F32, {R, 2048});
|
||||
E.act = decl_b(b, nm.f("ref.act"), RAD_F32, {R, 2048});
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
RefLayer& L = E.layer[i];
|
||||
auto w = [&](const char* dn, const char* sn, std::initializer_list<int64_t> sh) {
|
||||
return wcopy(b, nm, nm.f("ref.t%d.%s", i, dn),
|
||||
nm.ckpt("audio_tokenizer.encoder.encoder_transformer.layers.%d.%s", i, sn),
|
||||
RAD_F32, sh, kGrpCodec + 1);
|
||||
};
|
||||
L.n1 = w("n1", "input_layernorm.weight", {512});
|
||||
L.b1 = w("b1", "input_layernorm.bias", {512});
|
||||
L.n2 = w("n2", "post_attention_layernorm.weight", {512});
|
||||
L.b2 = w("b2", "post_attention_layernorm.bias", {512});
|
||||
L.ls1 = w("ls1", "self_attn_layer_scale.scale", {512});
|
||||
L.ls2 = w("ls2", "mlp_layer_scale.scale", {512});
|
||||
const char* qn = nm.f("ref.t%d.qkv", i);
|
||||
RAD_ARCH_TRY(map_concat(b, qn, {
|
||||
nm.ckpt("audio_tokenizer.encoder.encoder_transformer.layers.%d.self_attn.q_proj.weight", i),
|
||||
nm.ckpt("audio_tokenizer.encoder.encoder_transformer.layers.%d.self_attn.k_proj.weight", i),
|
||||
nm.ckpt("audio_tokenizer.encoder.encoder_transformer.layers.%d.self_attn.v_proj.weight", i)}));
|
||||
L.qkv = decl_w(b, qn, RAD_F32, {1536, 512}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp_layer(kGrpCodec + 1));
|
||||
L.o = w("out", "self_attn.o_proj.weight", {512, 512});
|
||||
L.fc1 = w("fc1", "mlp.fc1.weight", {2048, 512});
|
||||
L.fc2 = w("fc2", "mlp.fc2.weight", {512, 2048});
|
||||
auto ln = [&](rad_weight nw, rad_weight nb) {
|
||||
return rw(b, RAD_OP(b, "layernorm", RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", 512),
|
||||
RAD_F64("eps", 1e-5), RAD_STR("dtype", "f32")), RAD_WEIGHTS(nw, nb)),
|
||||
{E.z}, {E.th});
|
||||
};
|
||||
L.norm1 = ln(L.n1, L.b1); L.norm2 = ln(L.n2, L.b2);
|
||||
L.proj = ref_gemm(b, R, 1536, 512, L.qkv, E.th, E.qkv);
|
||||
L.rope = rw(b, RAD_OP(b, "rope", RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("head_dim", 64),
|
||||
RAD_INT("n_head", 8), RAD_INT("n_head_kv", 8), RAD_F64("theta", 10000),
|
||||
RAD_F64("scale", 1), RAD_STR("mode", "neox")), RAD_NOWEIGHTS),
|
||||
{E.qkv, E.index}, {E.qkv});
|
||||
L.attn = rw(b, RAD_OP(b, "attn_dense", RAD_PARAMS(RAD_RANGE("M", 1, R),
|
||||
RAD_INT("head_dim", 64), RAD_INT("gqa", 1), RAD_INT("causal", 1),
|
||||
RAD_F64("scale", 0.125), RAD_INT("window", 250), RAD_INT("max_seqlen", R),
|
||||
RAD_STR("dtype", "f32")), RAD_NOWEIGHTS), {E.qkv, E.cu}, {E.attn});
|
||||
L.out = ref_gemm(b, R, 512, 512, L.o, E.attn, E.o);
|
||||
L.f1 = ref_gemm(b, R, 2048, 512, L.fc1, E.th, E.ff);
|
||||
L.act = ref_rows(b, "gelu", R, 2048, {E.ff}, {E.act});
|
||||
L.f2 = ref_gemm(b, R, 512, 2048, L.fc2, E.act, E.o);
|
||||
auto scale = [&](rad_weight sw) {
|
||||
return rw(b, RAD_OP(b, "mul_weight", RAD_PARAMS(RAD_RANGE("M", 1, R),
|
||||
RAD_INT("n", 512), RAD_STR("dtype", "f32")), RAD_WEIGHTS(sw)), {E.o}, {E.o});
|
||||
};
|
||||
L.scale1 = scale(L.ls1); L.scale2 = scale(L.ls2);
|
||||
L.add1 = ref_rows(b, "add", R, 512, {E.z, E.o}, {E.z});
|
||||
L.add2 = ref_rows(b, "add", R, 512, {E.z, E.o}, {E.z});
|
||||
if (!L.n1 || !L.b1 || !L.n2 || !L.b2 || !L.qkv || !L.o || !L.fc1 || !L.fc2 ||
|
||||
!L.ls1 || !L.ls2 || !L.norm1 || !L.norm2 || !L.proj || !L.rope || !L.attn ||
|
||||
!L.out || !L.f1 || !L.act || !L.f2 || !L.scale1 || !L.scale2 || !L.add1 || !L.add2)
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* The last downsample uses replicate padding. Prepending two copies of the first row,
|
||||
* using the ordinary causal conv, then dropping its first output is exactly that pad. */
|
||||
E.pad = decl_b(b, nm.f("ref.pad"), RAD_F32, {R + 2, 512});
|
||||
E.sampled = decl_b(b, nm.f("ref.sampled"), RAD_F32, {kMaxRefFrames + 1, 512});
|
||||
RAD_ARCH_TRY(rad_op_reads(b, E.copy_f, &E.z, 1));
|
||||
RAD_ARCH_TRY(rad_op_writes(b, E.copy_f, &E.pad, 1));
|
||||
RAD_ARCH_TRY(ref_conv(b, m, E.sample, "sample", "audio_tokenizer.encoder.downsample.conv",
|
||||
512, 512, 4, 2, 1, R + 2, E.pad, 0, E.sampled, false));
|
||||
E.codes = decl_b(b, nm.f("ref.codes"), RAD_I32, {16, kMaxRefFrames}, RAD_BUF_PERSIST);
|
||||
E.eos_codes = decl_b(b, nm.f("ref.eos_codes"), RAD_I32, {16, 1}, RAD_BUF_PERSIST);
|
||||
for (int part = 0; part < 2; ++part) {
|
||||
const char* qs = part ? "acoustic_residual_vector_quantizer" : "semantic_residual_vector_quantizer";
|
||||
E.q[part] = decl_b(b, nm.f("ref.q%d", part), RAD_F32, {kMaxRefFrames, 256});
|
||||
E.qi[part] = wcopy(b, nm, nm.f("ref.q%d.in", part),
|
||||
nm.ckpt("audio_tokenizer.encoder.quantizer.%s.input_proj.weight", qs),
|
||||
RAD_F32, {256, 512}, kGrpCodec + 1);
|
||||
/* A 1x1 Conv1d weight's trailing singleton is immaterial to GEMM's matrix view. */
|
||||
E.project[part] = ref_gemm(b, kMaxRefFrames, 256, 512, E.qi[part], E.sampled, E.q[part]);
|
||||
const int first = part ? 1 : 0, count = part ? 15 : 1;
|
||||
for (int j = 0; j < count; ++j) {
|
||||
const int k = first + j;
|
||||
const char* dn = nm.f("ref.cb%d", k);
|
||||
RAD_ARCH_TRY(map_ema(b, dn,
|
||||
nm.ckpt("audio_tokenizer.encoder.quantizer.%s.layers.%d.codebook.embed_sum", qs, j),
|
||||
nm.ckpt("audio_tokenizer.encoder.quantizer.%s.layers.%d.codebook.cluster_usage", qs, j)));
|
||||
E.cb[k] = decl_w(b, dn, RAD_F32, {2048, 256}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp_layer(kGrpCodec + 1));
|
||||
E.quant[k] = rw(b, RAD_OP(b, "vq_euclidean", RAD_PARAMS(RAD_RANGE("M", 1, kMaxRefFrames),
|
||||
RAD_INT("n", 256), RAD_INT("bins", 2048), RAD_STR("dtype", "f32")),
|
||||
RAD_WEIGHTS(E.cb[k])), {E.q[part]}, {E.q[part], E.codes});
|
||||
if (!E.cb[k] || !E.quant[k]) return RAD_E_INVAL;
|
||||
}
|
||||
if (!E.qi[part] || !E.project[part]) return RAD_E_INVAL;
|
||||
}
|
||||
E.embed = rw(b, RAD_OP(b, "rvq_embed", RAD_PARAMS(RAD_RANGE("M", 1, kMaxRefFrames),
|
||||
RAD_INT("n_embd", m.gl.n_embd), RAD_INT("n_codes", 16), RAD_INT("vocab", kVocab),
|
||||
RAD_INT("off0", 0), RAD_F64("scale", 1), RAD_INT("round", 1),
|
||||
RAD_STR("dtype", "bf16")), RAD_WEIGHTS(m.w_cb, m.w_cb)), {E.codes}, {m.b_x});
|
||||
E.eos = iota_op(b, 16, 0, 0, E.eos_codes);
|
||||
RAD_ARCH_TRY(rad_op_reads(b, E.embed, &E.eos_codes, 1));
|
||||
/* Both branches' text segments are encoded separately at position zero. These buffers must
|
||||
* remain live through each segment's encoder, projection and the backbone prefill. */
|
||||
for (const EncLayer& L : m.enc) {
|
||||
RAD_ARCH_TRY(rad_op_reads(b, L.op_qknr, &E.text_pos, 1));
|
||||
RAD_ARCH_TRY(rad_op_reads(b, L.op_attn, &E.text_cu, 1));
|
||||
}
|
||||
return E.indices && E.copy_i && E.copy_f && E.text_indices && E.embed && E.eos ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* Copy the endpoints of an iota into a two-entry cu, without a host upload or ABI change. */
|
||||
static void ref_bounds(RadCtx* c, const Reference& E, rad_buf cu, int64_t len) {
|
||||
RAD_ISSUE_N(c, E.copy_i, 1, brow_slice(E.index, 0, 1, 1), brow_slice(cu, 0, 1, 1));
|
||||
RAD_ISSUE_N(c, E.copy_i, 1, brow_slice(E.index, len, 1, 1), brow_slice(cu, 1, 1, 1));
|
||||
}
|
||||
|
||||
static void step_reference(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
const Reference& E = m.ref;
|
||||
const auto* A = batch->agen_b;
|
||||
const int64_t L = A->ref_samples, R = L / 960, F = R / 2;
|
||||
RAD_ISSUE_N(c, E.indices, 2 * kMaxPrompt + 3, brows(E.index, 2 * kMaxPrompt + 3));
|
||||
const RadOperand raw_cu = praw(A->ref_cu, RAD_I32, 2);
|
||||
auto conv = [&](const RefConv& C, RadOperand x, RadOperand res, RadOperand y,
|
||||
int64_t rows, RadOperand cu) {
|
||||
RAD_ISSUE_N(c, C.op, rows, x, RAD_W(C.w), cu, res, y, C.b ? RAD_W(C.b) : RAD_NONE);
|
||||
};
|
||||
conv(E.first, praw(A->ref_audio, RAD_F32, L), RAD_NONE, brows(E.x[0], L), L, raw_cu);
|
||||
static const int64_t stride[] = {4, 5, 6, 8};
|
||||
int64_t rows = L;
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
RAD_ISSUE_N(c, E.elu[i], rows, brows(E.x[i], rows), brows(E.a[i], rows));
|
||||
conv(E.res1[i], brows(E.a[i], rows), RAD_NONE, brows(E.h[i], rows), rows, raw_cu);
|
||||
RAD_ISSUE_N(c, E.elu_h[i], rows, brows(E.h[i], rows), brows(E.h[i], rows));
|
||||
conv(E.res2[i], brows(E.h[i], rows), brows(E.x[i], rows), brows(E.x[i], rows), rows, raw_cu);
|
||||
RAD_ISSUE_N(c, E.elu[i], rows, brows(E.x[i], rows), brows(E.a[i], rows));
|
||||
conv(E.down[i], brows(E.a[i], rows), RAD_NONE, brows(E.x[i + 1], rows / stride[i]), rows, raw_cu);
|
||||
rows /= stride[i];
|
||||
}
|
||||
RAD_ISSUE_N(c, E.elu[4], R, brows(E.x[4], R), brows(E.a[4], R));
|
||||
conv(E.last, brows(E.a[4], R), RAD_NONE, brows(E.z, R), R, raw_cu);
|
||||
ref_bounds(c, E, E.cu, R);
|
||||
const RadOperand cu = brows(E.cu, 2), pos = brows(E.index, R);
|
||||
for (const RefLayer& T : E.layer) {
|
||||
auto norm = [&](rad_op op, rad_weight w, rad_weight bias) {
|
||||
RAD_ISSUE_N(c, op, R, brows(E.z, R), RAD_W(w), RAD_W(bias), brows(E.th, R));
|
||||
};
|
||||
auto gemm = [&](rad_op op, rad_buf x, rad_weight w, rad_buf y) {
|
||||
RAD_ISSUE_N(c, op, R, brows(x, R), RAD_W(w), brows(y, R));
|
||||
};
|
||||
norm(T.norm1, T.n1, T.b1);
|
||||
gemm(T.proj, E.th, T.qkv, E.qkv);
|
||||
RAD_ISSUE_N(c, T.rope, R, brows(E.qkv, R), pos);
|
||||
RAD_ISSUE_N(c, T.attn, R, bcol(E.qkv, 0, 512, R), bcol(E.qkv, 512, 512, R),
|
||||
bcol(E.qkv, 1024, 512, R), cu, brows(E.attn, R));
|
||||
gemm(T.out, E.attn, T.o, E.o);
|
||||
RAD_ISSUE_N(c, T.scale1, R, brows(E.o, R), RAD_W(T.ls1), brows(E.o, R));
|
||||
RAD_ISSUE_N(c, T.add1, R, brows(E.z, R), brows(E.o, R), brows(E.z, R));
|
||||
norm(T.norm2, T.n2, T.b2);
|
||||
gemm(T.f1, E.th, T.fc1, E.ff);
|
||||
RAD_ISSUE_N(c, T.act, R, brows(E.ff, R), brows(E.act, R));
|
||||
gemm(T.f2, E.act, T.fc2, E.o);
|
||||
RAD_ISSUE_N(c, T.scale2, R, brows(E.o, R), RAD_W(T.ls2), brows(E.o, R));
|
||||
RAD_ISSUE_N(c, T.add2, R, brows(E.z, R), brows(E.o, R), brows(E.z, R));
|
||||
}
|
||||
RAD_ISSUE_N(c, E.copy_f, 1, brow_slice(E.z, 0, 1, 512), brow_slice(E.pad, 0, 1, 512));
|
||||
RAD_ISSUE_N(c, E.copy_f, 1, brow_slice(E.z, 0, 1, 512), brow_slice(E.pad, 1, 1, 512));
|
||||
RAD_ISSUE_N(c, E.copy_f, R, brows(E.z, R), brow_slice(E.pad, 2, R, 512));
|
||||
ref_bounds(c, E, E.cu, R + 2);
|
||||
conv(E.sample, brows(E.pad, R + 2), RAD_NONE, brows(E.sampled, F + 1), R + 2, cu);
|
||||
for (int p = 0; p < 2; ++p) {
|
||||
RAD_ISSUE_N(c, E.project[p], F, brow_slice(E.sampled, 1, F, 512), RAD_W(E.qi[p]), brows(E.q[p], F));
|
||||
for (int k = p ? 1 : 0; k < (p ? 16 : 1); ++k) {
|
||||
RadOperand codes = brow_slice(E.codes, k, 1, kMaxRefFrames);
|
||||
codes.cols = F;
|
||||
RAD_ISSUE_N(c, E.quant[k], F, brows(E.q[p], F), RAD_W(E.cb[k]), codes);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,11 +21,12 @@ namespace clef_bf16 {
|
||||
using namespace rad::arch;
|
||||
|
||||
/* One head per rank beside the trunk's own per-rank state (qwen35_bf16::g_model). */
|
||||
static ClefHead g_head[MAX_RANKS];
|
||||
static ClefHead g_head[MAX_SLOTS];
|
||||
|
||||
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;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
if (!ClefHead::present(meta)) {
|
||||
std::fprintf(stderr, "radiance: clef_bf16 serves a container converted with "
|
||||
"--set decision.type=clef and the head added (--add "
|
||||
@@ -36,13 +37,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
/* The trunk's declare does not take part in sizing declares (no probe), so its state and the
|
||||
* head's are the real ones. The head goes after the vision tower: its buffers join the same
|
||||
* arena, and it reads the final norm's rows, the lm_head and the trunk's cache block size. */
|
||||
qwen35_bf16::Model& m = qwen35_bf16::g_model[ctx->rank];
|
||||
qwen35_bf16::Model& m = qwen35_bf16::g_model[rad_build_slot(ctx)];
|
||||
/* The lm_head's row would be sampled once and discarded: with this fill declared, the trunk
|
||||
* skips the lm_head on a step every sampled row of which carries a request's words
|
||||
* (plugin_words_cover_rows) and leaves zero rows instead. */
|
||||
m.op_logits_fill = clef_logits_fill(b, m.nm, m.g, m.b_logits);
|
||||
if (!m.op_logits_fill) return RAD_E_INVAL;
|
||||
ClefHead& h = g_head[ctx->rank];
|
||||
ClefHead& h = g_head[rad_build_slot(ctx)];
|
||||
h = ClefHead{};
|
||||
return h.declare(b, meta, ctx, m.nm, m.g, m.b_h, m.b_logits, m.w_lm_head, m.kv_full,
|
||||
(int)m.g.n_layer + 256);
|
||||
@@ -52,8 +53,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
qwen35_bf16::step(c, batch);
|
||||
/* An encoder pass runs the tower alone and leaves no rows for the head. */
|
||||
if (batch->enc) return;
|
||||
qwen35_bf16::Model& m = qwen35_bf16::g_model[rad_rank(c)];
|
||||
ClefHead& h = g_head[rad_rank(c)];
|
||||
qwen35_bf16::Model& m = qwen35_bf16::g_model[rad_slot(c)];
|
||||
ClefHead& h = g_head[rad_slot(c)];
|
||||
/* The final norm's rows are still in `h` after the trunk's step; the logits row of each
|
||||
* sampled sequence has been written, and the head adds its values beside it. */
|
||||
h.step_tokens(c, batch, m.b_h);
|
||||
@@ -62,6 +63,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
|
||||
} /* namespace clef_bf16 */
|
||||
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(clef_bf16, "clef", "", "0.1.0",
|
||||
"Cloudflare's clef / clef-flash (9B, 27B): the Qwen3.5 trunk of qwen35_bf16, bf16, "
|
||||
"with the joint schema head on the card for /v1/systemone")
|
||||
@@ -21,11 +21,12 @@ namespace clef_fp8 {
|
||||
|
||||
using namespace rad::arch;
|
||||
|
||||
static ClefHead g_head[MAX_RANKS];
|
||||
static ClefHead g_head[MAX_SLOTS];
|
||||
|
||||
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;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
if (!ClefHead::present(meta)) {
|
||||
std::fprintf(stderr, "radiance: clef_fp8 serves a container converted with "
|
||||
"--set decision.type=clef and the head added (--add "
|
||||
@@ -33,13 +34,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RAD_ARCH_TRY(qwen35_clef_fp8::declare(b, meta, ctx));
|
||||
qwen35_clef_fp8::Model& m = qwen35_clef_fp8::g_model[ctx->rank];
|
||||
qwen35_clef_fp8::Model& m = qwen35_clef_fp8::g_model[rad_build_slot(ctx)];
|
||||
/* The lm_head's row would be sampled once and discarded: with this fill declared, the trunk
|
||||
* skips the lm_head on a step every sampled row of which carries a request's words
|
||||
* (plugin_words_cover_rows) and leaves zero rows instead. */
|
||||
m.op_logits_fill = clef_logits_fill(b, m.nm, m.g, m.b_logits);
|
||||
if (!m.op_logits_fill) return RAD_E_INVAL;
|
||||
ClefHead& h = g_head[ctx->rank];
|
||||
ClefHead& h = g_head[rad_build_slot(ctx)];
|
||||
h = ClefHead{};
|
||||
return h.declare(b, meta, ctx, m.nm, m.g, m.a_h.x, m.b_logits, m.w_lm_head, m.kv_full,
|
||||
(int)m.g.n_layer + 256);
|
||||
@@ -49,8 +50,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
qwen35_clef_fp8::step(c, batch);
|
||||
/* An encoder pass leaves no rows for the head, and a drafter's pass is not a trunk step. */
|
||||
if (batch->enc || batch->draft_pass != 0) return;
|
||||
qwen35_clef_fp8::Model& m = qwen35_clef_fp8::g_model[rad_rank(c)];
|
||||
ClefHead& h = g_head[rad_rank(c)];
|
||||
qwen35_clef_fp8::Model& m = qwen35_clef_fp8::g_model[rad_slot(c)];
|
||||
ClefHead& h = g_head[rad_slot(c)];
|
||||
/* The final norm's rows are in `a_h.x` after either of the trunk's step paths. */
|
||||
h.step_tokens(c, batch, m.a_h.x);
|
||||
if (batch->n_out > 0) h.step_heads(c, batch, m.b_logits, m.w_lm_head);
|
||||
@@ -59,6 +60,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
} /* namespace clef_fp8 */
|
||||
|
||||
RAD_ARCH_PROBE(qwen35_clef_fp8)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(clef_fp8, "clef", "fp8_e4m3", "0.1.0",
|
||||
"Cloudflare's clef / clef-flash (9B, 27B): the Qwen3.5 trunk of qwen35_fp8, "
|
||||
"block-scaled fp8, with the joint schema head on the card for /v1/systemone")
|
||||
@@ -0,0 +1,8 @@
|
||||
Copied, unmodified apart from one include path, from radiance-exl3 in this tree (exl3/, Apache-2.0,
|
||||
Copyright 2026 Dylan Johnston; see exl3/LICENSE and exl3/NOTICE):
|
||||
exl3_abi.h exl3/include/exl3_abi.h (op schemas, operand positions, interface version)
|
||||
exl3_encoding.h exl3/include/exl3_encoding.h (the canonical exl3 encoding; "../common/" dropped)
|
||||
exl3_decode.h exl3/common/exl3_decode.h (declarations; the block uses the inline helpers only)
|
||||
rad_block_moe_q.h reads a layer's EXL3 encoding and issues the extension's whole-expert ops
|
||||
(moe_exl3_gate_up, moe_exl3_down) by their positions here. arch/common is installed on its own, so
|
||||
it carries copies; ctest's exl3_vendor_check fails when they drift from exl3/.
|
||||
@@ -0,0 +1,909 @@
|
||||
/* exl3_abi.h -- the interface between the EXL3 plugins: the two routed-expert GEMM ops, the routing
|
||||
* contract they read, the weight planes they read, and one parse of their geometry.
|
||||
* Header-only C. The encoding itself is include/exl3_encoding.h.
|
||||
*
|
||||
* Every library that implements `moe_exl3_gate_up` / `moe_exl3_down` exports exl3_schema_at() as its
|
||||
* schemas -- the reference (kernels/exl3ref) and the device library (kernels/exl3r4d) -- so the two
|
||||
* cannot declare different schemas (the loader refuses the second plugin if they do: docs/OPS.md
|
||||
* :139-150 at radiance 1.3.0) and `rad-schemas exl3ref.so exl3r4d.so` prints no difference.
|
||||
* docs/OPS-exl3.md is the prose form of the schemas below and is checked against them.
|
||||
*
|
||||
* Both sides check EXL3_IFACE_VERSION. Bump it on ANY change below: a schema, an operand position,
|
||||
* the routing contract, the planes' forms or the geometry rule.
|
||||
*
|
||||
* VERSION 2: ONE WEIGHT-TABLE OPERAND PER PLANE PER PARITY CLASS. Version 1 carried all of an
|
||||
* expert's planes in one table operand, and at radiance 1.3.0 that weight could be served by no host
|
||||
* row without a layout hook (core/build/rad_builder.cpp:1385, 1453-1460) and handed to the per-op
|
||||
* oracle only decoded to dense W (core/runtime/oracle.cpp:425-560), which a reference computing in
|
||||
* exllamav3's rounding order cannot read. One plane an operand is stored as it is wherever no kernel
|
||||
* re-lays it, and the oracle passes a single-plane selection through unchanged
|
||||
* (core/format/encoding.cpp:306-321). See "THE PLANES" below.
|
||||
*
|
||||
* VERSION 3: "EPI 1", gate_up's epilogue doing down's first step. Both ops take a REQUIRED flag
|
||||
* `h_rot`. With h_rot = 1, gate_up also reads down's input scales (`dn_suh`, `dn_suh_odd`) and writes
|
||||
* h ALREADY ROTATED for down -- exactly down's step 1, so the pair is bit-identical to the h_rot = 0
|
||||
* pair -- and down reads it as rotated and skips that step. Down's operands are unchanged; gate_up's
|
||||
* operands after `svh` move by one (and by two after `svh_odd`). With h_rot = 0 both ops compute what
|
||||
* version 2 computed, to the bit.
|
||||
*
|
||||
* VERSION 4: gate_up's input rotation as an op of its own, so an architecture can issue independent
|
||||
* work between the rotation and the routed GEMM. A third op, `moe_exl3_prep_gu`, writes xr -- every
|
||||
* sorted row's input rotated for gate and for up, exactly the prologue gate_up runs -- and gate_up
|
||||
* takes a REQUIRED flag `a_rot`: with a_rot = 1 its `a` IS that xr and it does not rotate (nor read
|
||||
* suh / suh.1). prep_gu -> gate_up(a_rot = 1) gives the bits gate_up(a_rot = 0) gives. With a_rot = 0
|
||||
* gate_up is version 3's, to the bit. Operand lists of gate_up and down are unchanged; prep_gu is
|
||||
* schema 2, after them.
|
||||
*
|
||||
* VERSION 5: a FOURTH op, `moe_exl3_gate_up_down`, the whole routed-expert chain of a decode pass as
|
||||
* one op -- prep_gu's rotation, gate_up with h_rot = 1, down with h_rot = 1 -- so a library can run it
|
||||
* as ONE launch (exl3r4d's fused kernel: no dispatch boundaries, down's work fills gate_up's tail). Its
|
||||
* output is exactly down's y from gate_up(a_rot = 0, h_rot = 1) -> down(h_rot = 1) on the same
|
||||
* operands, to the bit; h and xr are the op's own scratch. Operands: gate_up's planes, then down's
|
||||
* codes and svh (down's suh is gate_up's dn_suh, the same weight), per class (THE OPS below). The
|
||||
* three earlier ops are unchanged; the planes enumeration gains EXL3_P_DN_CODES and EXL3_P_DN_SVH (-1
|
||||
* for the earlier ops). Schema 3, after them.
|
||||
*
|
||||
* VERSION 6: FOUR-CLASS FORMS of gate_up, down and prep_gu -- `moe_exl3_gate_up_mod4`,
|
||||
* `moe_exl3_down_mod4`, `moe_exl3_prep_gu_mod4` -- the experts as four classes by number mod 4, radiance's
|
||||
* `moe_gemm_q_mod4` beside `moe_gemm_q` (its docs/OPS.md, "moe_gemm_q_mod4"): four ranks splitting a five-block
|
||||
* expert give the extra block four places to go instead of two. Separate ops, because the declaration divides a
|
||||
* table op's weights over its table operands by count alone, so the operand list IS the class count. Each is its
|
||||
* two-class op with three more class table sets and N_q / K_q for N_odd / K_odd (THE OPS below). The four earlier
|
||||
* ops are unchanged, to the schema; the new ones are schemas 4, 5, 6, after them. No four-class gate_up_down: its
|
||||
* fused launch's two views do not fit the engine's kernel-argument slot at four classes (docs/OPS-exl3.md).
|
||||
*
|
||||
* VERSION 7: the four-class gate_up_down, `moe_exl3_gate_up_down_mod4` -- version 5's op over
|
||||
* version 6's four classes: gate_up_down's parameters with N_q / K_q for N_odd / K_odd, its operands with classes
|
||||
* 1..3's seven tables after the routing. Its output is exactly moe_exl3_down_mod4(h_rot = 1) of
|
||||
* moe_exl3_gate_up_mod4(a_rot = 0, h_rot = 1) on the same operands, to the bit. Version 6's reason against it was the
|
||||
* slot: a fused kernel that reads no implicit argument has no hidden block, so the explicit 704 bytes fit the 768
|
||||
* (exl3r4d's exl3r4d_gd_mod4.hip). The seven earlier ops are unchanged, to the schema; it is schema 7, after them.
|
||||
*/
|
||||
#ifndef EXL3_ABI_H
|
||||
#define EXL3_ABI_H
|
||||
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "exl3_encoding.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define EXL3_IFACE_VERSION 10
|
||||
|
||||
/* THE FEWEST TOKENS a pass issues moe_exl3_gate_up_down for, and exl3r4d fuses it from -- one build-time value for
|
||||
* the architecture's issue band (QWEN4EXP_EXL3_GD) and the library's fused launch (EXL3R4D_GD_MIN_TOK's default), so
|
||||
* both move together. Not an interface fact: below it the same bits come from the other forms (3 tokens already take
|
||||
* gate_up's split-K 1, so the fused launch at 3 is the split chain's bits). Why 3: at 3 tokens the fused launch beats
|
||||
* the split chain on gfx1201 (tp2 about 76 vs 82 us a layer, tp1 about 138 vs 146), and a whole decode step at 3
|
||||
* concurrent streams is about 1-3% faster with every other concurrency unchanged. An architecture built with 3 (or 1)
|
||||
* loads and serves at tp2. At 1-2 tokens the fused launch is not taken: gate_up runs split-K 2 there and the fused
|
||||
* launch split-K 1 (EXL3R4D_GD_SK2 is a bit-identical split-K-2 arm), and at one stream the fused launch does not make
|
||||
* the engine's step faster. */
|
||||
#ifndef EXL3_GD_MIN_ROWS
|
||||
#define EXL3_GD_MIN_ROWS 3
|
||||
#endif
|
||||
|
||||
/* ===================================================================== THE ROUTING CONTRACT
|
||||
*
|
||||
* What the in-tree router hands a routed-expert GEMM, as read in radiance 1.3.0. Both ops
|
||||
* below consume it exactly as `moe_gemm_q` does, so the in-tree router, scatter and gather serve
|
||||
* them unchanged. Every claim cites the line that makes it.
|
||||
*
|
||||
* WHO WRITES IT. `router_topk` (softmax over ALL n_expert logits, top_k, optional renormalise)
|
||||
* then `moe_scatter`, or the two fused as `router_topk_scatter`, or with the router GEMM in front
|
||||
* as `router_gemm_topk_scatter` (docs/OPS.md:567-570, 601-641; libref/ref_registry.cpp:876-886).
|
||||
* The block reports the five buffers to the heat engine with rad_route_report (abi/rad_runtime.h
|
||||
* :352-369; the struct is RadRouting, :356-364); nothing is read back on the compute stream.
|
||||
*
|
||||
* expert_ids i32 [n_tok, top_k] device. The router's choice for each (token, slot);
|
||||
* RadRouting::expert_ids (rad_runtime.h:357).
|
||||
* expert_w f32 [n_tok, top_k] device. The routing weight of each (token, slot)
|
||||
* (rad_runtime.h:358). NOT READ BY EITHER OP HERE: the
|
||||
* gather (`moe_gather`, or `ar_gather_hc_write` at tp2) multiplies
|
||||
* it in as it sums a token's slots in ascending slot order
|
||||
* (docs/OPS.md:572; libref/ref_registry.cpp:907-909).
|
||||
* sorted_tok i32 [n_tok * top_k] device. The FLATTENED (token, slot) index token*top_k + slot,
|
||||
* grouped by expert by a STABLE counting sort -- not the bare
|
||||
* token id (libref/ref_moe.cpp:3-10; ref_registry.cpp:880-881).
|
||||
* Row i of every expert GEMM output belongs to pair sorted_tok[i].
|
||||
* expert_offset i32 [n_expert + 1] device. Expert e's rows are [off[e], off[e+1]);
|
||||
* off[n_expert] is the LIVE row count (rad_runtime.h:361;
|
||||
* libref/ref_moe.cpp:135-140).
|
||||
* expert_count i32 [n_expert] device. off[e+1] - off[e]; the heat engine's histogram,
|
||||
* written in place via rad_route_counts (rad_runtime.h:359,
|
||||
* 371-377). Not read by either op here.
|
||||
*
|
||||
* DROPPED SLOTS. A slot whose expert is outside the range the sort owns -- [expert_base,
|
||||
* expert_base + n_expert), which is how expert parallelism is spelt, or a negative id for a padded
|
||||
* batch row -- is not counted, and sorted_tok[off[n_expert] .. n_tok*top_k) is -1
|
||||
* (libref/ref_moe.cpp:11-13, 122-126, 144; ref_registry.cpp:364-371, 880-886).
|
||||
*
|
||||
* ROWS PAST off[n_expert] ARE ZEROED BY THE GEMM, WHATEVER sorted_tok HOLDS THERE. Two reasons
|
||||
* a row can be past the live count: a dropped slot (-1), or a PROTECTED expert's row. A layer
|
||||
* that keeps a few experts at bf16 sorts them last (`protect`, docs/OPS.md:646-651) and hands the
|
||||
* quantised GEMMs n_expert = the regular count, so off[n_expert] stops short of the protected
|
||||
* rows, which hold valid flat indices; the protected pair writes those rows AFTER the quantised
|
||||
* down GEMM zeroed them (arch/common/rad_block_moe_q.h:1611-1622). libr4d zeroes every row past
|
||||
* the live count (libr4d/r4d_moe.hip:83-86, 1834-1841, 2221-2222); libref zeroes a row only when
|
||||
* sorted_tok is negative (libref/ref_moe.cpp:285-288), which agrees on dropped slots and not on
|
||||
* protected rows. These ops follow libr4d: row i is zero when i >= off[n_expert] OR
|
||||
* sorted_tok[i] < 0 (or i < off[0], a row no expert owns), across the whole output width.
|
||||
*
|
||||
* WHICH EXPERT OWNS ROW i: the e with off[e] <= i < off[e+1] (experts with no rows have
|
||||
* off[e] == off[e+1] and own nothing). Under `protect` the offsets are in SORT order, not id
|
||||
* order -- the regular experts closed up, then the protected ones (docs/OPS.md:646-651) -- and the
|
||||
* weight tables are declared in the same order (rad_block_moe_q.h:831-834), so "expert e" below
|
||||
* always means offsets index e.
|
||||
*
|
||||
* TWO EXPERT COUNTS. The router's n_expert is the model's; the sort's (`n_local`, or the
|
||||
* scatter's n_expert) is this rank's slice and sizes expert_offset (docs/OPS.md:609-615). The
|
||||
* `n_expert` parameter of both ops below is the SORT's: the length of expert_offset minus one.
|
||||
* Under the intra-expert width split every rank holds a slice of EVERY expert, so the two are
|
||||
* equal there; under expert parallelism they are not.
|
||||
*
|
||||
* THE ROW ORDER OF THE ACTIVATION. The in-tree grouped GEMM says it with `a_order`
|
||||
* (docs/OPS.md:700-721). Here it is FIXED per op and not a parameter: gate_up reads one row per
|
||||
* TOKEN, row sorted_tok[i] / top_k (a_order "token"); down reads one row per (token, slot) in the
|
||||
* scatter's order, row i itself (a_order "sorted"). Gathering the down input a second time hands
|
||||
* every slot of a token the first slot's intermediate and stays fluent -- the failure the
|
||||
* parameter exists to prevent (docs/OPS.md:713-721) -- so the order is part of each op's name.
|
||||
*
|
||||
* `M` IS THE TOKEN COUNT OF A PASS, not the sorted row count (rad_block_moe_q.h:1052-1054): the
|
||||
* kernels read the row count T off the output and M is what the scratch hook and the operand
|
||||
* descriptions size from. T = M * top_k at every issue the in-tree block makes.
|
||||
*/
|
||||
|
||||
/* ===================================================================== THE TWO OPS
|
||||
*
|
||||
* Exact semantics, rounding points and refusals: docs/OPS-exl3.md (the checked prose form). In
|
||||
* one line each, per live row i of expert e, token t = sorted_tok[i] / top_k:
|
||||
*
|
||||
* moe_exl3_gate_up h[i] = f16( silu(had(f16(had(f16(a[t] * suh))) @ What_gate) * svh_gate)
|
||||
* * (had(f16(had(f16(a[t] * suh.1))) @ What_up) * svh_up) )
|
||||
* moe_exl3_down y[i] = bf16( had(f16(had(f16(h[i] * suh))) @ What) * svh )
|
||||
*
|
||||
* moe_exl3_prep_gu xr[i] = [ f16(had(f16(a[t] * suh_e))) | f16(had(f16(a[t] * suh.1_e))) ]
|
||||
* -- gate_up's step 1 for its two halves, side by side (below, "XR"); gate_up with
|
||||
* a_rot = 1 reads xr[i] where it would have computed it.
|
||||
*
|
||||
* moe_exl3_gate_up_down y[i] = moe_exl3_down(h_rot = 1)( moe_exl3_gate_up(a_rot = 0, h_rot = 1)(a) )[i]
|
||||
* -- the decode chain as ONE op (version 5): the same rotations, roundings and zero rules, h and
|
||||
* xr in the op's scratch, nothing but y written.
|
||||
*
|
||||
* h_rot = 1 ("EPI 1"): gate_up writes h'[i] = f16(had(f16(h[i] * dn_suh_e))) per 128-block --
|
||||
* down's own first step, with down's suh of the same expert -- and zeros past the class's width as
|
||||
* before; down then reads its input as that rotated activation, y[i] = bf16(had(h'[i] @ What) * svh),
|
||||
* and does not read its suh. Issued as a PAIR (both flags 1, or both 0) the pair's output is the same
|
||||
* bits either way; mixing the flags is a caller error nothing here can see.
|
||||
*
|
||||
* had = the normalised 128-block Hadamard (common/exl3_decode.h exl3_had128). `expert_w` is NOT
|
||||
* applied by either: the gather does it, exactly as for `moe_gemm_q`.
|
||||
*
|
||||
* THE EXPERTS ARE TWO CLASSES BY PARITY, as `moe_gemm_q`'s are (docs/OPS.md:677-688): the even
|
||||
* experts at [N, K], the odd ones at [N_odd, K_odd] (each defaulting to N, K), expert e at entry
|
||||
* e / 2 of class e % 2 -- because a rank holding 3 of an expert's five 128-column blocks for one
|
||||
* parity and 2 for the other (a rank holds whole 128-blocks) has two geometries. Each class is one
|
||||
* table operand per plane. The output is the WIDER class's width and a narrower class writes zeros
|
||||
* past its own.
|
||||
*
|
||||
* THE ODD CLASS ABSENT (every one of its tables a null RadTensor.data) means ONE class: expert e at
|
||||
* entry e of the even tables, every expert at [N, K]; N_odd / K_odd, if given, must equal N / K. A
|
||||
* partly absent odd set is refused. NOTE: at 1.3.0 an architecture cannot issue an absent table:
|
||||
* the declaration divides its weight list EVENLY over every table position, optional or not
|
||||
* (core/build/rad_builder.cpp:697-731), and an issue naming another run is refused
|
||||
* (core/runtime/issue.cpp:249-254). So the engine always passes both classes (at tp1 with
|
||||
* N_odd == N, K_odd == K, as the in-tree block does); absence is for a caller holding operands
|
||||
* directly -- a harness, a tool -- and is what a shape description without N_odd and K_odd means.
|
||||
*
|
||||
* THE _mod4 OPS (version 6) TAKE FOUR CLASSES BY NUMBER MOD 4, as `moe_gemm_q_mod4`'s are: class q at [N_q, K_q]
|
||||
* (N_0, K_0 being N, K; each N_q, K_q defaulting to N, K), expert e at entry e / 4 of class e % 4, so class q holds
|
||||
* ceil((n_expert - q) / 4) entries. Every class's tables are REQUIRED (no absent form: the architecture issues all
|
||||
* four, and a caller with one geometry has the two-class ops). Everything else -- the routing, the zero rules, the
|
||||
* output the widest class's width with a narrower class zero past its own, h_rot, a_rot, xr -- is the two-class
|
||||
* op's, word for word, with "the odd class" read as "classes 1, 2 and 3".
|
||||
*
|
||||
* PARAMETERS (both ops):
|
||||
* M the token count of the pass (the op's ranged parameter)
|
||||
* N, K class 0's weight [rows, cols] = [out features, in features] of this rank's slice.
|
||||
* gate_up: N = 2 * width (gate rows then up rows, stacked), K = hidden;
|
||||
* down: N = hidden, K = width
|
||||
* n_expert the length of expert_offset minus one (the sort's expert count)
|
||||
* top_k slots per token
|
||||
* dtype "exl3k2" .. "exl3k8": the codes' K, bits per weight (exl3_gemm_dtype); "exl3k1h" .. "exl3k3h" the
|
||||
* half-integer K 1.5 .. 3.5 (exllamav3 1.6, codebook mul1 only; codes the u(2KA+1) [1x2] pair plane)
|
||||
* codebook "mul1" | "mcg" | "3inst": the trellis codebook (the encoding's transform names it;
|
||||
* the architecture passes it so the geometry says what is decoded -- a host row has no
|
||||
* layout hook through which to see the encoding)
|
||||
* N_odd, K_odd class 1's [rows, cols]; optional, default N, K
|
||||
* h_rot 0 or 1, REQUIRED: whether h crosses between the two ops rotated (above). Required and
|
||||
* not optional because a constraint on an absent key never holds (core/util/rad_util.cpp
|
||||
* :264-265): a row that does not implement h_rot = 1 says RAD_CEQ("h_rot", 0) and is
|
||||
* refused BY NAME at selection, which it could not if callers might omit the key.
|
||||
* Any other value is RAD_E_INVAL.
|
||||
* a_rot gate_up only, 0 or 1, REQUIRED (for the reason h_rot is): 1 when gate_up's `a` is the
|
||||
* xr moe_exl3_prep_gu wrote -- sorted rows, already rotated -- rather than the token rows.
|
||||
* A row that does not implement it says RAD_CEQ("a_rot", 0). Any other value RAD_E_INVAL.
|
||||
*
|
||||
* moe_exl3_gate_up_down takes gate_up's parameters without the flags (h_rot = 1 and a_rot = 0 are what it is):
|
||||
* M, N, K, n_expert, top_k, dtype, codebook, N_odd?, K_odd?. Down's geometry follows: [K, N / 2] (and
|
||||
* [K_odd, N_odd / 2]); both matrices are the same K and codebook (an architecture whose two projections differ
|
||||
* issues the separate ops).
|
||||
*
|
||||
* moe_exl3_prep_gu takes M, K, n_expert, top_k, dtype (the routed GEMMs' "exl3kK": the family it
|
||||
* belongs to, so a library serving one K constrains all three ops alike) and K_odd?: the classes'
|
||||
* input widths are all it needs of the weight.
|
||||
*
|
||||
* The _mod4 ops take the same parameters with N_1?, K_1?, N_2?, K_2?, N_3?, K_3? in place of N_odd?, K_odd?
|
||||
* (prep_gu_mod4: K_1?, K_2?, K_3?), `moe_gemm_q_mod4`'s names.
|
||||
*
|
||||
* OPERANDS, in schema order (moe_gemm_q's pattern: the even tables, the routing, the odd tables,
|
||||
* the output):
|
||||
* gate_up a, codes, suh, suh1, svh, dn_suh?, sorted_tok, expert_offset,
|
||||
* codes_odd?, suh_odd?, suh1_odd?, svh_odd?, dn_suh_odd? -> h
|
||||
* down h, codes, suh, svh, sorted_tok, expert_offset, codes_odd?, suh_odd?, svh_odd? -> y
|
||||
* prep_gu a, suh, suh1, sorted_tok, expert_offset, suh_odd?, suh1_odd? -> xr
|
||||
* the _mod4 ops: class 0's tables, the routing, then class 1's, 2's and 3's tables (suffix _1, _2, _3; every one
|
||||
* required but dn_suh_q, as dn_suh), then the output -- `moe_gemm_q_mod4`'s pattern
|
||||
* gate_up_down a, codes, suh, suh1, svh, dn_suh, dn_codes, dn_svh, sorted_tok, expert_offset,
|
||||
* codes_odd?, suh_odd?, suh1_odd?, svh_odd?, dn_suh_odd?, dn_codes_odd?, dn_svh_odd? -> y
|
||||
* (dn_suh is down's suh; dn_codes / dn_svh are down's codes and svh, [K, N / 2] and [K, 1])
|
||||
* dn_suh / dn_suh_odd are DOWN's suh tables of the same experts (entry [1, rows/2]); read only with
|
||||
* h_rot = 1, where they are required (and dn_suh_odd with the odd class).
|
||||
*
|
||||
* THE DECLARATION: the weight list is divided evenly over the table positions in this order
|
||||
* (rad_builder.cpp:703-731), so an architecture lists the even class's codes run, its suh run,
|
||||
* [its suh.1 run,] its svh run, [gate_up: its dn_suh run,] then the odd class's in the same order --
|
||||
* each run the class's experts in entry order, each weight a one-plane view
|
||||
* (`RadWeightDecl::planes` = "codes", "suh", "suh.1", "svh") of the expert's one `exl3` encoding.
|
||||
* An odd expert count gives the even tables one more each, which is the rule's own remainder
|
||||
* (:711-729). EVERY TABLE POSITION TAKES ITS SHARE, OPTIONAL OR NOT, so an architecture issuing
|
||||
* gate_up binds dn_suh (and dn_suh_odd) whatever h_rot is -- the natural run is the one down's own
|
||||
* suh table already names (down's suh weights, read by two ops); with h_rot = 0 it is not read.
|
||||
* prep_gu's suh / suh1 runs are gate_up's (the same weights, read by both); gate_up binds them at
|
||||
* a_rot = 1 too and does not read them.
|
||||
*
|
||||
* XR, moe_exl3_prep_gu's output and gate_up's `a` at a_rot = 1: f16 [T, 2 * max(K, K_odd)], one row
|
||||
* per SORTED row (row i is slot sorted_tok[i], like the outputs). Row i of expert e (class c, input
|
||||
* width K_c) holds columns [0, K_c) the gate half's rotated input (suh) and [K_c, 2 * K_c) the up
|
||||
* half's (suh.1) -- a narrower class uses the first 2 * K_c of the row. It is the layout exl3r4d's
|
||||
* prep kernels write in both bands, decode and prefill (xr[row][m * K_c + k], row pitch 2 * x_cols;
|
||||
* kernels/exl3r4d/exl3r4d.hip, exl3r4d_prefill.hip).
|
||||
* WHAT IS NOT WRITTEN, and is left as it was: every row outside the experts' runs [off[0],
|
||||
* off[n_expert]) -- dropped slots, protected experts' rows -- and the columns past 2 * K_c. gate_up
|
||||
* reads none of them (its output rows there are zero whatever xr holds). A row inside a run whose
|
||||
* sorted_tok is negative (no scatter writes one) is zero. "Not written" is exact, so the per-op
|
||||
* oracle, which runs the host row on the pre-launch copy (core/runtime/oracle.cpp:405-423), compares
|
||||
* those bytes equal; a library that wrote them would be the one disagreeing.
|
||||
*
|
||||
* ONE a_rot PER DECLARED OP, A CHOICE PER PASS. a_rot is a fixed parameter like every other but M, so
|
||||
* an architecture that wants prep_gu + gate_up(a_rot = 1) at decode and gate_up(a_rot = 0) above it
|
||||
* declares gate_up twice -- a_rot = 1 with M ranged over the decode band, beside prep_gu over the same
|
||||
* band, and a_rot = 0 -- and picks at issue by the pass's row count. That is how the in-tree block
|
||||
* already chooses its router form: `router_gemm_topk_scatter` declared for M in [1,
|
||||
* router_fused_rows] and issued only when rows <= router_fused_rows, else the separate pair or the
|
||||
* split router (arch/common/rad_block_moe_q.h:1438-1447, 1527-1551). Both gate_up declarations
|
||||
* read the same weights, so their rows must ask the same stored form of `codes`.
|
||||
*/
|
||||
|
||||
/* The ops, as exl3_positions() and exl3_geom_parse() take them. 0 and 1 are what version 3's
|
||||
* `gate_up` flag passed, so a caller written for it is unchanged. A four-class form (v6, v7) is its op | EXL3_MOD4. */
|
||||
enum { EXL3_DOWN = 0, EXL3_GATE_UP = 1, EXL3_PREP_GU = 2, EXL3_GU_DN = 3, EXL3_MOD4 = 4,
|
||||
EXL3_DOWN4 = EXL3_MOD4 | EXL3_DOWN, EXL3_GATE_UP4 = EXL3_MOD4 | EXL3_GATE_UP,
|
||||
EXL3_PREP_GU4 = EXL3_MOD4 | EXL3_PREP_GU, EXL3_GU_DN4 = EXL3_MOD4 | EXL3_GU_DN };
|
||||
/* The two-class op a form is of (what it computes); EXL3_MOD4 says only how its experts are tabled. */
|
||||
static inline int exl3_op_base(int op) { return op & ~EXL3_MOD4; }
|
||||
|
||||
/* Where each operand of an op sits. `plane[c][p]` is class c's table of plane p (EXL3_P_*), -1 for a
|
||||
* plane the op does not have (down has no suh.1 and no dn_suh; prep_gu has only suh and suh.1) and for
|
||||
* every plane of a class past the op's `n_cls` (2, or 4 for a _mod4 op).
|
||||
* EXL3_P_DN_SUH is gate_up's view of DOWN's suh plane (h_rot = 1); the expert's own weight is planes
|
||||
* EXL3_P_CODES..EXL3_P_SVH. */
|
||||
enum { EXL3_P_CODES = 0, EXL3_P_SUH = 1, EXL3_P_SUH1 = 2, EXL3_P_SVH = 3, EXL3_P_DN_SUH = 4,
|
||||
EXL3_P_DN_CODES = 5, EXL3_P_DN_SVH = 6, EXL3_N_P = 7 };
|
||||
enum { EXL3_MAX_CLS = 4 };
|
||||
|
||||
typedef struct Exl3Positions {
|
||||
int x, sorted, offset, y, n_opd, n_cls;
|
||||
int plane[EXL3_MAX_CLS][EXL3_N_P];
|
||||
int ids; /* the router's top-k ids (OPTIONAL operand; prep_gu_mod4 only), -1 for every other op */
|
||||
} Exl3Positions;
|
||||
|
||||
static inline const Exl3Positions* exl3_positions(int op) {
|
||||
#define EXL3_NO_CLASS { -1, -1, -1, -1, -1, -1, -1 }
|
||||
static const Exl3Positions gu = { 0, 6, 7, 13, 14, 2, { { 1, 2, 3, 4, 5, -1, -1 }, { 8, 9, 10, 11, 12, -1, -1 },
|
||||
EXL3_NO_CLASS, EXL3_NO_CLASS }, -1 };
|
||||
static const Exl3Positions dn = { 0, 4, 5, 9, 10, 2, { { 1, 2, -1, 3, -1, -1, -1 }, { 6, 7, -1, 8, -1, -1, -1 },
|
||||
EXL3_NO_CLASS, EXL3_NO_CLASS }, -1 };
|
||||
static const Exl3Positions pg = { 0, 3, 4, 7, 8, 2, { { -1, 1, 2, -1, -1, -1, -1 }, { -1, 5, 6, -1, -1, -1, -1 },
|
||||
EXL3_NO_CLASS, EXL3_NO_CLASS }, -1 };
|
||||
static const Exl3Positions gd = { 0, 8, 9, 17, 18, 2, { { 1, 2, 3, 4, 5, 6, 7 }, { 10, 11, 12, 13, 14, 15, 16 },
|
||||
EXL3_NO_CLASS, EXL3_NO_CLASS }, -1 };
|
||||
static const Exl3Positions gu4 = { 0, 6, 7, 23, 24, 4, { { 1, 2, 3, 4, 5, -1, -1 }, { 8, 9, 10, 11, 12, -1, -1 },
|
||||
{ 13, 14, 15, 16, 17, -1, -1 },
|
||||
{ 18, 19, 20, 21, 22, -1, -1 } }, -1 };
|
||||
static const Exl3Positions dn4 = { 0, 4, 5, 15, 16, 4, { { 1, 2, -1, 3, -1, -1, -1 }, { 6, 7, -1, 8, -1, -1, -1 },
|
||||
{ 9, 10, -1, 11, -1, -1, -1 },
|
||||
{ 12, 13, -1, 14, -1, -1, -1 } }, -1 };
|
||||
static const Exl3Positions pg4 = { 0, 3, 4, 11, 13, 4, { { -1, 1, 2, -1, -1, -1, -1 }, { -1, 5, 6, -1, -1, -1, -1 },
|
||||
{ -1, 7, 8, -1, -1, -1, -1 },
|
||||
{ -1, 9, 10, -1, -1, -1, -1 } }, 12 };
|
||||
static const Exl3Positions gd4 = { 0, 8, 9, 31, 32, 4, { { 1, 2, 3, 4, 5, 6, 7 }, { 10, 11, 12, 13, 14, 15, 16 },
|
||||
{ 17, 18, 19, 20, 21, 22, 23 },
|
||||
{ 24, 25, 26, 27, 28, 29, 30 } }, -1 };
|
||||
#undef EXL3_NO_CLASS
|
||||
switch (op) {
|
||||
case EXL3_GU_DN: return &gd;
|
||||
case EXL3_PREP_GU: return &pg;
|
||||
case EXL3_GATE_UP: return &gu;
|
||||
case EXL3_DOWN4: return &dn4;
|
||||
case EXL3_GATE_UP4: return &gu4;
|
||||
case EXL3_PREP_GU4: return &pg4;
|
||||
case EXL3_GU_DN4: return &gd4;
|
||||
default: return &dn;
|
||||
}
|
||||
}
|
||||
|
||||
#define EXL3_OP_GATE_UP "moe_exl3_gate_up"
|
||||
#define EXL3_OP_DOWN "moe_exl3_down"
|
||||
#define EXL3_OP_PREP_GU "moe_exl3_prep_gu"
|
||||
#define EXL3_OP_GU_DN "moe_exl3_gate_up_down"
|
||||
#define EXL3_OP_GATE_UP4 "moe_exl3_gate_up_mod4"
|
||||
#define EXL3_OP_DOWN4 "moe_exl3_down_mod4"
|
||||
#define EXL3_OP_PREP_GU4 "moe_exl3_prep_gu_mod4"
|
||||
#define EXL3_OP_GU_DN4 "moe_exl3_gate_up_down_mod4"
|
||||
|
||||
/* An op's id (EXL3_*) from its name, or -1. */
|
||||
static inline int exl3_op_of(const char* name) {
|
||||
static const char* const names[] = { EXL3_OP_DOWN, EXL3_OP_GATE_UP, EXL3_OP_PREP_GU, EXL3_OP_GU_DN,
|
||||
EXL3_OP_DOWN4, EXL3_OP_GATE_UP4, EXL3_OP_PREP_GU4, EXL3_OP_GU_DN4 };
|
||||
for (int i = 0; name && i < (int)(sizeof names / sizeof names[0]); ++i)
|
||||
if (!strcmp(name, names[i])) return i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* The schemas, in this order: 0 gate_up, 1 down, 2 prep_gu, 3 gate_up_down, 4 gate_up_mod4, 5 down_mod4,
|
||||
* 6 prep_gu_mod4, 7 gate_up_down_mod4. A plugin's rad_kernel_schema_count / rad_kernel_schema_at answer with these. Static locals in a
|
||||
* static inline function, so a translation unit that includes this header and never asks pays nothing and warns
|
||||
* about nothing. */
|
||||
static inline int exl3_schema_count(void) { return 8; }
|
||||
|
||||
static inline const RadOpSchema* exl3_schema_at(int i) {
|
||||
#define EXL3_GEMM_PARAMS \
|
||||
{ "M", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE }, \
|
||||
{ "N", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE }, \
|
||||
{ "K", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE }, \
|
||||
{ "n_expert", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE }, \
|
||||
{ "top_k", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE }, \
|
||||
{ "dtype", RAD_P_STR, RAD_REQUIRED, RAD_PROLE_NONE }, \
|
||||
{ "codebook", RAD_P_STR, RAD_REQUIRED, RAD_PROLE_NONE }, \
|
||||
{ "N_odd", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE }, \
|
||||
{ "K_odd", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE }, \
|
||||
{ "h_rot", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE }
|
||||
static const RadParamSpec p_gu[] = {
|
||||
EXL3_GEMM_PARAMS,
|
||||
{ "a_rot", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
/* v8: the SwiGLU clamp (DeepSeek's swiglu_limit): gate = min(gate, limit), up = clamp(up, -limit, limit)
|
||||
* before silu(gate) * up; absent or 0 is none */
|
||||
{ "limit", RAD_P_F64, RAD_OPTIONAL, RAD_PROLE_NONE },
|
||||
/* v9, the token-count-invariant form: 1 = a row's bytes do not depend on the launch's token count -- a
|
||||
* library whose decode band picks a form by the token count (exl3r4d: split-K 2 at <= 2 tokens where the grid
|
||||
* fits, split-K 1 above) takes the one form at every count; absent or 0 is the library's own rule. The
|
||||
* result is defined as without it (a summation order, not a different product). */
|
||||
{ "bi", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE },
|
||||
/* v10, the in-launch copy ring: MiB of the prefill band's scratch for a copy ring -- in the map
|
||||
* form the launch may copy the routed experts whose codes sit in a host pool (rad_host_pool_ranges) onto the
|
||||
* card inside the GEMM launch, while the resident experts compute, and read the copies (the same bytes);
|
||||
* absent or 0 is no ring. A placement of the same bytes, not a different product. */
|
||||
{ "xring", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE },
|
||||
};
|
||||
static const RadParamSpec p_dn[] = { EXL3_GEMM_PARAMS };
|
||||
#undef EXL3_GEMM_PARAMS
|
||||
static const RadParamSpec p_pg[] = {
|
||||
{ "M", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "K", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "n_expert", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "top_k", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "dtype", RAD_P_STR, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "K_odd", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE },
|
||||
};
|
||||
static const RadOperandSpec gate_up[14] = {
|
||||
{ "a", RAD_OPD_IN, 0 },
|
||||
{ "codes", RAD_OPD_WTAB, 0 },
|
||||
{ "suh", RAD_OPD_WTAB, 0 },
|
||||
{ "suh1", RAD_OPD_WTAB, 0 },
|
||||
{ "svh", RAD_OPD_WTAB, 0 },
|
||||
{ "dn_suh", RAD_OPD_WTAB, 1 },
|
||||
{ "sorted_tok", RAD_OPD_IN, 0 },
|
||||
{ "expert_offset", RAD_OPD_IN, 0 },
|
||||
{ "codes_odd", RAD_OPD_WTAB, 1 },
|
||||
{ "suh_odd", RAD_OPD_WTAB, 1 },
|
||||
{ "suh1_odd", RAD_OPD_WTAB, 1 },
|
||||
{ "svh_odd", RAD_OPD_WTAB, 1 },
|
||||
{ "dn_suh_odd", RAD_OPD_WTAB, 1 },
|
||||
{ "h", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
static const RadOperandSpec down[10] = {
|
||||
{ "h", RAD_OPD_IN, 0 },
|
||||
{ "codes", RAD_OPD_WTAB, 0 },
|
||||
{ "suh", RAD_OPD_WTAB, 0 },
|
||||
{ "svh", RAD_OPD_WTAB, 0 },
|
||||
{ "sorted_tok", RAD_OPD_IN, 0 },
|
||||
{ "expert_offset", RAD_OPD_IN, 0 },
|
||||
{ "codes_odd", RAD_OPD_WTAB, 1 },
|
||||
{ "suh_odd", RAD_OPD_WTAB, 1 },
|
||||
{ "svh_odd", RAD_OPD_WTAB, 1 },
|
||||
{ "y", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
static const RadParamSpec p_gd[] = {
|
||||
{ "M", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "N", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "K", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "n_expert", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "top_k", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "dtype", RAD_P_STR, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "codebook", RAD_P_STR, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "N_odd", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE },
|
||||
{ "K_odd", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE },
|
||||
};
|
||||
static const RadOperandSpec gate_up_down[18] = {
|
||||
{ "a", RAD_OPD_IN, 0 },
|
||||
{ "codes", RAD_OPD_WTAB, 0 },
|
||||
{ "suh", RAD_OPD_WTAB, 0 },
|
||||
{ "suh1", RAD_OPD_WTAB, 0 },
|
||||
{ "svh", RAD_OPD_WTAB, 0 },
|
||||
{ "dn_suh", RAD_OPD_WTAB, 0 },
|
||||
{ "dn_codes", RAD_OPD_WTAB, 0 },
|
||||
{ "dn_svh", RAD_OPD_WTAB, 0 },
|
||||
{ "sorted_tok", RAD_OPD_IN, 0 },
|
||||
{ "expert_offset", RAD_OPD_IN, 0 },
|
||||
{ "codes_odd", RAD_OPD_WTAB, 1 },
|
||||
{ "suh_odd", RAD_OPD_WTAB, 1 },
|
||||
{ "suh1_odd", RAD_OPD_WTAB, 1 },
|
||||
{ "svh_odd", RAD_OPD_WTAB, 1 },
|
||||
{ "dn_suh_odd", RAD_OPD_WTAB, 1 },
|
||||
{ "dn_codes_odd", RAD_OPD_WTAB, 1 },
|
||||
{ "dn_svh_odd", RAD_OPD_WTAB, 1 },
|
||||
{ "y", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
static const RadOperandSpec prep_gu[8] = {
|
||||
{ "a", RAD_OPD_IN, 0 },
|
||||
{ "suh", RAD_OPD_WTAB, 0 },
|
||||
{ "suh1", RAD_OPD_WTAB, 0 },
|
||||
{ "sorted_tok", RAD_OPD_IN, 0 },
|
||||
{ "expert_offset", RAD_OPD_IN, 0 },
|
||||
{ "suh_odd", RAD_OPD_WTAB, 1 },
|
||||
{ "suh1_odd", RAD_OPD_WTAB, 1 },
|
||||
{ "xr", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
/* v6, the four-class forms: the two-class op's parameters with N_q / K_q for N_odd / K_odd, and its operands with
|
||||
* classes 1..3's tables after the routing (every one required but dn_suh_q, as dn_suh). */
|
||||
#define EXL3_MOD4_SHAPE \
|
||||
{ "M", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE }, \
|
||||
{ "N", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE }, \
|
||||
{ "K", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE }, \
|
||||
{ "n_expert", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE }, \
|
||||
{ "top_k", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE }, \
|
||||
{ "dtype", RAD_P_STR, RAD_REQUIRED, RAD_PROLE_NONE }, \
|
||||
{ "codebook", RAD_P_STR, RAD_REQUIRED, RAD_PROLE_NONE }, \
|
||||
{ "N_1", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE }, \
|
||||
{ "K_1", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE }, \
|
||||
{ "N_2", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE }, \
|
||||
{ "K_2", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE }, \
|
||||
{ "N_3", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE }, \
|
||||
{ "K_3", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE }, \
|
||||
{ "h_rot", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE }
|
||||
static const RadParamSpec p_gu4[] = {
|
||||
EXL3_MOD4_SHAPE,
|
||||
{ "a_rot", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
};
|
||||
static const RadParamSpec p_dn4[] = { EXL3_MOD4_SHAPE };
|
||||
#undef EXL3_MOD4_SHAPE
|
||||
static const RadParamSpec p_pg4[] = {
|
||||
{ "M", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "K", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "n_expert", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "top_k", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "dtype", RAD_P_STR, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "K_1", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE },
|
||||
{ "K_2", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE },
|
||||
{ "K_3", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE },
|
||||
};
|
||||
#define EXL3_GU_CLASS(q) \
|
||||
{ "codes_" #q, RAD_OPD_WTAB, 0 }, \
|
||||
{ "suh_" #q, RAD_OPD_WTAB, 0 }, \
|
||||
{ "suh1_" #q, RAD_OPD_WTAB, 0 }, \
|
||||
{ "svh_" #q, RAD_OPD_WTAB, 0 }, \
|
||||
{ "dn_suh_" #q, RAD_OPD_WTAB, 1 }
|
||||
static const RadOperandSpec gate_up4[24] = {
|
||||
{ "a", RAD_OPD_IN, 0 },
|
||||
{ "codes", RAD_OPD_WTAB, 0 },
|
||||
{ "suh", RAD_OPD_WTAB, 0 },
|
||||
{ "suh1", RAD_OPD_WTAB, 0 },
|
||||
{ "svh", RAD_OPD_WTAB, 0 },
|
||||
{ "dn_suh", RAD_OPD_WTAB, 1 },
|
||||
{ "sorted_tok", RAD_OPD_IN, 0 },
|
||||
{ "expert_offset", RAD_OPD_IN, 0 },
|
||||
EXL3_GU_CLASS(1), EXL3_GU_CLASS(2), EXL3_GU_CLASS(3),
|
||||
{ "h", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
#undef EXL3_GU_CLASS
|
||||
#define EXL3_DN_CLASS(q) \
|
||||
{ "codes_" #q, RAD_OPD_WTAB, 0 }, \
|
||||
{ "suh_" #q, RAD_OPD_WTAB, 0 }, \
|
||||
{ "svh_" #q, RAD_OPD_WTAB, 0 }
|
||||
static const RadOperandSpec down4[16] = {
|
||||
{ "h", RAD_OPD_IN, 0 },
|
||||
{ "codes", RAD_OPD_WTAB, 0 },
|
||||
{ "suh", RAD_OPD_WTAB, 0 },
|
||||
{ "svh", RAD_OPD_WTAB, 0 },
|
||||
{ "sorted_tok", RAD_OPD_IN, 0 },
|
||||
{ "expert_offset", RAD_OPD_IN, 0 },
|
||||
EXL3_DN_CLASS(1), EXL3_DN_CLASS(2), EXL3_DN_CLASS(3),
|
||||
{ "y", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
#undef EXL3_DN_CLASS
|
||||
#define EXL3_PG_CLASS(q) \
|
||||
{ "suh_" #q, RAD_OPD_WTAB, 0 }, \
|
||||
{ "suh1_" #q, RAD_OPD_WTAB, 0 }
|
||||
static const RadOperandSpec prep_gu4[13] = {
|
||||
{ "a", RAD_OPD_IN, 0 },
|
||||
{ "suh", RAD_OPD_WTAB, 0 },
|
||||
{ "suh1", RAD_OPD_WTAB, 0 },
|
||||
{ "sorted_tok", RAD_OPD_IN, 0 },
|
||||
{ "expert_offset", RAD_OPD_IN, 0 },
|
||||
EXL3_PG_CLASS(1), EXL3_PG_CLASS(2), EXL3_PG_CLASS(3),
|
||||
{ "xr", RAD_OPD_OUT, 0 },
|
||||
{ "topk_ids", RAD_OPD_IN, 1 }, /* optional: the router's [M, top_k] expert ids */
|
||||
};
|
||||
#undef EXL3_PG_CLASS
|
||||
static const RadParamSpec p_gd4[] = {
|
||||
{ "M", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "N", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "K", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "n_expert", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "top_k", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "dtype", RAD_P_STR, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "codebook", RAD_P_STR, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "N_1", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE },
|
||||
{ "K_1", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE },
|
||||
{ "N_2", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE },
|
||||
{ "K_2", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE },
|
||||
{ "N_3", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE },
|
||||
{ "K_3", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE },
|
||||
};
|
||||
#define EXL3_GD_CLASS(q) \
|
||||
{ "codes_" #q, RAD_OPD_WTAB, 0 }, \
|
||||
{ "suh_" #q, RAD_OPD_WTAB, 0 }, \
|
||||
{ "suh1_" #q, RAD_OPD_WTAB, 0 }, \
|
||||
{ "svh_" #q, RAD_OPD_WTAB, 0 }, \
|
||||
{ "dn_suh_" #q, RAD_OPD_WTAB, 0 }, \
|
||||
{ "dn_codes_" #q, RAD_OPD_WTAB, 0 }, \
|
||||
{ "dn_svh_" #q, RAD_OPD_WTAB, 0 }
|
||||
static const RadOperandSpec gate_up_down4[32] = {
|
||||
{ "a", RAD_OPD_IN, 0 },
|
||||
{ "codes", RAD_OPD_WTAB, 0 },
|
||||
{ "suh", RAD_OPD_WTAB, 0 },
|
||||
{ "suh1", RAD_OPD_WTAB, 0 },
|
||||
{ "svh", RAD_OPD_WTAB, 0 },
|
||||
{ "dn_suh", RAD_OPD_WTAB, 0 },
|
||||
{ "dn_codes", RAD_OPD_WTAB, 0 },
|
||||
{ "dn_svh", RAD_OPD_WTAB, 0 },
|
||||
{ "sorted_tok", RAD_OPD_IN, 0 },
|
||||
{ "expert_offset", RAD_OPD_IN, 0 },
|
||||
EXL3_GD_CLASS(1), EXL3_GD_CLASS(2), EXL3_GD_CLASS(3),
|
||||
{ "y", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
#undef EXL3_GD_CLASS
|
||||
static const RadOpSchema s[8] = {
|
||||
{ EXL3_OP_GATE_UP, p_gu, (int)(sizeof p_gu / sizeof p_gu[0]), gate_up, 14,
|
||||
"EXL3 routed experts, gate and up: per sorted row, a[sorted_tok/top_k] scaled by suh "
|
||||
"(suh.1 for up) and rotated, times W_hat, rotated back and scaled by svh, then "
|
||||
"f16(silu(gate) * up); with h_rot = 1 that then scaled by down's suh (dn_suh) and "
|
||||
"rotated, which is down's first step; with a_rot = 1 `a` is moe_exl3_prep_gu's xr and "
|
||||
"the input rotation is not redone. One weight table a plane a parity class, expert e "
|
||||
"at entry e/2; rows past expert_offset[n_expert] are zero. expert_w is not applied. "
|
||||
"docs/OPS-exl3.md." },
|
||||
{ EXL3_OP_DOWN, p_dn, (int)(sizeof p_dn / sizeof p_dn[0]), down, 10,
|
||||
"EXL3 routed experts, down: per sorted row, h[i] scaled by suh and rotated (with h_rot = "
|
||||
"1: h[i] as gate_up already rotated it), times W_hat, rotated back and scaled by svh, "
|
||||
"bf16. One weight table a plane a parity class, expert e at entry e/2; rows past "
|
||||
"expert_offset[n_expert] are zero. expert_w is not applied. docs/OPS-exl3.md." },
|
||||
{ EXL3_OP_PREP_GU, p_pg, (int)(sizeof p_pg / sizeof p_pg[0]), prep_gu, 8,
|
||||
"EXL3 routed experts, gate_up's input rotation as an op: per sorted row, "
|
||||
"a[sorted_tok/top_k] scaled by suh and rotated, then by suh.1 and rotated, side by side "
|
||||
"(xr, f16 [T, 2*max(K, K_odd)]) -- what moe_exl3_gate_up with a_rot = 1 reads. Rows "
|
||||
"past expert_offset[n_expert] are zero. docs/OPS-exl3.md." },
|
||||
{ EXL3_OP_GU_DN, p_gd, (int)(sizeof p_gd / sizeof p_gd[0]), gate_up_down, 18,
|
||||
"EXL3 routed experts, the decode chain as one op: y = moe_exl3_down(h_rot = 1) of "
|
||||
"moe_exl3_gate_up(a_rot = 0, h_rot = 1) of a, on the same routing; dn_suh / dn_codes / dn_svh "
|
||||
"are down's planes ([K, N/2]); h and the rotated input are scratch. Rows past "
|
||||
"expert_offset[n_expert] are zero. docs/OPS-exl3.md." },
|
||||
{ EXL3_OP_GATE_UP4, p_gu4, (int)(sizeof p_gu4 / sizeof p_gu4[0]), gate_up4, 24,
|
||||
"moe_exl3_gate_up over FOUR classes of experts by number mod 4 (moe_gemm_q_mod4's): class q at "
|
||||
"[N_q, K_q], expert e at entry e/4 of class e%4; otherwise moe_exl3_gate_up. docs/OPS-exl3.md." },
|
||||
{ EXL3_OP_DOWN4, p_dn4, (int)(sizeof p_dn4 / sizeof p_dn4[0]), down4, 16,
|
||||
"moe_exl3_down over FOUR classes of experts by number mod 4 (moe_gemm_q_mod4's): class q at "
|
||||
"[N_q, K_q], expert e at entry e/4 of class e%4; otherwise moe_exl3_down. docs/OPS-exl3.md." },
|
||||
{ EXL3_OP_PREP_GU4, p_pg4, (int)(sizeof p_pg4 / sizeof p_pg4[0]), prep_gu4, 13,
|
||||
"moe_exl3_prep_gu over FOUR classes of experts by number mod 4: class q's input width K_q, "
|
||||
"expert e at entry e/4 of class e%4; xr f16 [T, 2*max(K_q)]; otherwise moe_exl3_prep_gu. "
|
||||
"topk_ids (optional, i32 [M, top_k]): the router's expert of each (token, slot), the sort's input -- "
|
||||
"a speed hint only, the output does not depend on it. docs/OPS-exl3.md." },
|
||||
{ EXL3_OP_GU_DN4, p_gd4, (int)(sizeof p_gd4 / sizeof p_gd4[0]), gate_up_down4, 32,
|
||||
"moe_exl3_gate_up_down over FOUR classes of experts by number mod 4: y = moe_exl3_down_mod4(h_rot = 1) of "
|
||||
"moe_exl3_gate_up_mod4(a_rot = 0, h_rot = 1) of a; class q at [N_q, K_q], expert e at entry e/4 of class "
|
||||
"e%4; otherwise moe_exl3_gate_up_down. docs/OPS-exl3.md." },
|
||||
};
|
||||
return i >= 0 && i < 8 ? &s[i] : 0;
|
||||
}
|
||||
|
||||
/* THE DECODE BAND'S ARITHMETIC ABOVE THE DECODE BAND (the "dk" ops). Two more op names,
|
||||
* moe_exl3_gate_up_dk / moe_exl3_down_dk, with moe_exl3_gate_up's / moe_exl3_down's parameters, operands and result
|
||||
* definition to the letter -- what they add is a PROMISE about the bytes: a library's row for them writes, for every
|
||||
* (token, slot), exactly the bytes its DECODE-BAND row of moe_exl3_gate_up / moe_exl3_down writes for that token in a
|
||||
* pass of at most 16 tokens, whatever the pass's other tokens (the decode band is M-invariant per row, and a run longer
|
||||
* than a pass's 16 rows is taken 16 at a time). An architecture that must give a decode row the same bytes at any
|
||||
* step height (batch invariance), and would otherwise have to cut a decode segment into passes of <= 16 tokens,
|
||||
* declares them over the heights above 16 it wants as ONE pass and issues them for decode rows only; a prefill segment of the same height keeps
|
||||
* moe_exl3_gate_up / moe_exl3_down (whose M > 16 rows are free to round differently: exl3r4d's MTX form does). Names of
|
||||
* their own, not a parameter of the old ops, so the eight schemas above stay what every other library exports (a
|
||||
* loader refuses a library whose schema for a shared name differs). Two-class form only. exl3_dk_schema_at(0 / 1). */
|
||||
#define EXL3_OP_GATE_UP_DK "moe_exl3_gate_up_dk"
|
||||
#define EXL3_OP_DOWN_DK "moe_exl3_down_dk"
|
||||
static inline int exl3_dk_schema_count(void) { return 2; }
|
||||
static inline const RadOpSchema* exl3_dk_schema_at(int i) {
|
||||
static RadOpSchema s[2];
|
||||
static int made = 0;
|
||||
if (!made) {
|
||||
s[0] = *exl3_schema_at(0);
|
||||
s[0].op = EXL3_OP_GATE_UP_DK;
|
||||
s[0].doc = "moe_exl3_gate_up at more than 16 tokens with the decode band's bytes: every (token, slot) row is "
|
||||
"what the library's decode-band moe_exl3_gate_up writes for that token in a pass of <= 16 tokens "
|
||||
"(lever P; a_rot 0, h_rot 1). docs/OPS-exl3.md.";
|
||||
s[1] = *exl3_schema_at(1);
|
||||
s[1].op = EXL3_OP_DOWN_DK;
|
||||
s[1].doc = "moe_exl3_down at more than 16 tokens with the decode band's bytes: every (token, slot) row is "
|
||||
"what the library's decode-band moe_exl3_down writes for that token in a pass of <= 16 tokens "
|
||||
"(lever P; h_rot 1). docs/OPS-exl3.md.";
|
||||
made = 1;
|
||||
}
|
||||
return i >= 0 && i < 2 ? &s[i] : 0;
|
||||
}
|
||||
|
||||
/* ===================================================================== THE PLANES
|
||||
*
|
||||
* A table's entry e is one plane of one expert, exactly as the container holds it (the canonical
|
||||
* `exl3` encoding, include/exl3_encoding.h) -- this rank's slice of it, [rows, cols] in the plane's
|
||||
* own elements, the extents the core gives a plane (rad_enc_plane_dims, abi/rad_encoding.h:236-245):
|
||||
*
|
||||
* codes uK [R, C] element (i, j) = the K-bit trellis symbol of W_hat[i][j], LSB-first rows
|
||||
* suh f16 [1, C] input scales (the gate's, for gate_up) TILED [0x1]
|
||||
* suh1 f16 [1, C] gate_up only: the up half's input scales (plane suh.1) TILED [0x1]
|
||||
* svh f16 [R, 1] output scales (gate rows then up rows, for gate_up) TILED [1x0]
|
||||
* dn_suh f16 [1, R/2] gate_up only: DOWN's suh of the same expert (down's [hidden, R/2] weight)
|
||||
*
|
||||
* with [R, C] the class's [rows, cols]. A reader takes the scales by element count (any rank whose
|
||||
* extents multiply to C or R), because the architecture's declared shape is what an issue carries.
|
||||
* A table operand is the engine's pointer table (stride[0] == 0) or the STACKED form a tool uses --
|
||||
* one rank-3 tensor [entries, rows, cols] with a real leading stride, which is also the form the
|
||||
* per-op oracle hands a host row (core/runtime/oracle.cpp:328-347, 405-418).
|
||||
*
|
||||
* What a DEVICE row stores is its own business (its layout hook; codes alone is what a trellis
|
||||
* kernel re-lays). The host reference has no layout hook and reads the planes as they are, which a
|
||||
* one-plane weight nobody re-lays is (rad_builder.cpp:1385, 1404-1411) -- so the host-only engine
|
||||
* serves it -- and which the per-op oracle restores for a plane a device row did re-lay: the device
|
||||
* row's unrelayout gives back the canonical plane, and a one-plane selection reaches the host row
|
||||
* as those bytes in the dtype its shape hook names (oracle.cpp:456-548, encoding.cpp:306-321). */
|
||||
|
||||
/* The extents of plane p of class c's [rows, cols] weight (dn_suh: down's suh, [1, rows / 2]; dn_codes / dn_svh,
|
||||
* moe_exl3_gate_up_down's down planes: [cols, rows / 2] and [cols, 1] -- [rows, cols] being gate_up's). */
|
||||
static inline void exl3_plane_extents(int64_t rows, int64_t cols, int p, int64_t* r, int64_t* c) {
|
||||
if (p == EXL3_P_DN_CODES || p == EXL3_P_DN_SVH) {
|
||||
*r = cols;
|
||||
*c = p == EXL3_P_DN_SVH ? 1 : rows / 2;
|
||||
return;
|
||||
}
|
||||
*r = p == EXL3_P_SUH || p == EXL3_P_SUH1 || p == EXL3_P_DN_SUH ? 1 : rows;
|
||||
*c = p == EXL3_P_SVH ? 1 : p == EXL3_P_DN_SUH ? rows / 2 : cols;
|
||||
}
|
||||
|
||||
/* ===================================================================== THE GEOMETRY, PARSED ONCE
|
||||
*
|
||||
* Every implementation reads the parameters through this, so a device row can never accept a
|
||||
* geometry its reference refuses. `two_classes` is whether the odd tables are present -- an operand
|
||||
* fact the parameters do not carry; a shape hook, which has no operands, passes
|
||||
* exl3_geom_two_classes(). A _mod4 op ignores it: its four classes are always present. */
|
||||
typedef struct Exl3Geom {
|
||||
int op; /* the two-class op: EXL3_DOWN, EXL3_GATE_UP, EXL3_PREP_GU, EXL3_GU_DN (a _mod4 op's base) */
|
||||
int gate_up; /* 1 for gate_up AND prep_gu (stacked: suh and suh.1), 0 for down */
|
||||
int64_t M; /* tokens (a shape hook reads a range's high bound) */
|
||||
int64_t n_expert, top_k;
|
||||
int bits, codebook; /* K and EXL3_CB_* */
|
||||
int n_class; /* 2 with the odd tables, 1 without; 4 for a _mod4 op */
|
||||
int h_rot; /* 1: h crosses rotated (gate_up writes, down reads, down's step 1) */
|
||||
int a_rot; /* gate_up: 1 when `a` is prep_gu's xr */
|
||||
double limit; /* v8, moe_exl3_gate_up only: the SwiGLU clamp, 0 none (gate <= limit, |up| <= limit) */
|
||||
int64_t rows[EXL3_MAX_CLS], cols[EXL3_MAX_CLS]; /* class c's weight [rows, cols], c < n_class (prep_gu: rows 0,
|
||||
* it has no N); past n_class, class 0's */
|
||||
int64_t x_cols; /* max(cols): the token input's width (gate_up a_rot = 1: xr is 2 * x_cols) */
|
||||
int64_t y_cols; /* the output's width: max(rows)/2 gate_up, max(rows) down, 2 * x_cols prep_gu */
|
||||
} Exl3Geom;
|
||||
|
||||
/* Does this geometry name an odd class? -- N_odd or K_odd given. What a shape description of the
|
||||
* odd tables follows (present, or RAD_OPD_F_ABSENT). */
|
||||
static inline int exl3_geom_two_classes(const RadParam* p, int n_p) {
|
||||
return rad_param_find(p, n_p, "N_odd") != 0 || rad_param_find(p, n_p, "K_odd") != 0;
|
||||
}
|
||||
|
||||
/* RAD_OK, or: RAD_E_SCHEMA a required parameter absent; RAD_E_DTYPE a dtype or codebook this
|
||||
* interface has no name for; RAD_E_INVAL h_rot or a_rot neither 0 nor 1; RAD_E_SHAPE extents the
|
||||
* format cannot hold -- K % 128 (the input rotation), N % 128 for down and N % 256 for gate_up
|
||||
* (each half's output rotation, and with it the h_rot rotation of N / 2), a non-positive count, or
|
||||
* N_odd/K_odd differing from N/K without the odd class. `op` is EXL3_DOWN, EXL3_GATE_UP or
|
||||
* EXL3_PREP_GU (version 3 callers passed gate_up's 0/1, which are the first two), EXL3_GU_DN, or a _mod4
|
||||
* form (EXL3_DOWN4, EXL3_GATE_UP4, EXL3_PREP_GU4, EXL3_GU_DN4: N_q / K_q, every class checked as class 0 is). */
|
||||
static inline int exl3_geom_parse(const RadParam* p, int n_p, int op_in, int two_classes, Exl3Geom* g) {
|
||||
static const char* const common[] = { "M", "K", "n_expert", "top_k", "dtype" };
|
||||
static const char* const gemm[] = { "N", "codebook", "h_rot" };
|
||||
static const char* const nq[EXL3_MAX_CLS] = { "N", "N_1", "N_2", "N_3" };
|
||||
static const char* const kq[EXL3_MAX_CLS] = { "K", "K_1", "K_2", "K_3" };
|
||||
const int mod4 = (op_in & EXL3_MOD4) != 0, op = exl3_op_base(op_in);
|
||||
const int prep = op == EXL3_PREP_GU, gd = op == EXL3_GU_DN, gate_up = op == EXL3_GATE_UP || prep || gd;
|
||||
const char* dt = rad_param_gets(p, n_p, "dtype", 0);
|
||||
const char* cb = rad_param_gets(p, n_p, "codebook", 0);
|
||||
const int64_t N = rad_param_geti(p, n_p, "N", 0), K = rad_param_geti(p, n_p, "K", 0);
|
||||
const int64_t No = rad_param_geti(p, n_p, "N_odd", N), Ko = rad_param_geti(p, n_p, "K_odd", K);
|
||||
const int64_t rows_mult = gate_up ? 256 : 128;
|
||||
int c;
|
||||
memset(g, 0, sizeof *g);
|
||||
for (c = 0; c < (int)(sizeof common / sizeof common[0]); ++c)
|
||||
if (!rad_param_find(p, n_p, common[c])) return RAD_E_SCHEMA;
|
||||
for (c = 0; !prep && c < (int)(sizeof gemm / sizeof gemm[0]) - (gd ? 1 : 0); ++c) /* gd: no h_rot (last) */
|
||||
if (!rad_param_find(p, n_p, gemm[c])) return RAD_E_SCHEMA;
|
||||
if (op == EXL3_GATE_UP && !rad_param_find(p, n_p, "a_rot")) return RAD_E_SCHEMA;
|
||||
if (!dt || (!prep && !cb)) return RAD_E_SCHEMA; /* present, but not as strings */
|
||||
g->op = op;
|
||||
g->gate_up = gate_up;
|
||||
g->M = rad_param_getdim(p, n_p, "M", 0);
|
||||
g->n_expert = rad_param_geti(p, n_p, "n_expert", 0);
|
||||
g->top_k = rad_param_geti(p, n_p, "top_k", 0);
|
||||
g->h_rot = prep ? 0 : gd ? 1 : (int)rad_param_geti(p, n_p, "h_rot", -1);
|
||||
g->a_rot = op == EXL3_GATE_UP ? (int)rad_param_geti(p, n_p, "a_rot", -1) : 0;
|
||||
g->bits = exl3_gemm_bits(dt);
|
||||
g->codebook = prep ? -1 : exl3_codebook_from_name(cb);
|
||||
if (g->bits < 0 || (!prep && g->codebook < 0)) return RAD_E_DTYPE;
|
||||
if (exl3_bits_half(g->bits) && !prep && g->codebook != EXL3_CB_MUL1) return RAD_E_DTYPE; /* exllamav3 1.6: half-integer K is mul1 only */
|
||||
if ((g->h_rot != 0 && g->h_rot != 1) || (g->a_rot != 0 && g->a_rot != 1)) return RAD_E_INVAL;
|
||||
g->limit = op == EXL3_GATE_UP ? rad_param_getf(p, n_p, "limit", 0.0) : 0.0;
|
||||
if (!(g->limit >= 0.0) || g->limit > 65504.0) return RAD_E_INVAL; /* NaN, negative or past f16 */
|
||||
if (g->M < 1 || g->n_expert < 1 || g->top_k < 1) return RAD_E_SHAPE;
|
||||
if (!mod4 && !two_classes && ((!prep && No != N) || Ko != K)) return RAD_E_SHAPE;
|
||||
g->n_class = mod4 ? 4 : two_classes ? 2 : 1;
|
||||
for (c = 0; c < EXL3_MAX_CLS; ++c) { /* two-class ops: class 1 is the odd class, 2 and 3 class 0 again */
|
||||
const int has = mod4 || c == 1;
|
||||
g->rows[c] = prep ? 0 : !has ? N : mod4 ? rad_param_geti(p, n_p, nq[c], N) : No;
|
||||
g->cols[c] = !has ? K : mod4 ? rad_param_geti(p, n_p, kq[c], K) : Ko;
|
||||
}
|
||||
g->x_cols = g->y_cols = 0;
|
||||
for (c = 0; c < EXL3_MAX_CLS; ++c) {
|
||||
if (g->cols[c] <= 0 || g->cols[c] % EXL3_HAD ||
|
||||
(!prep && (g->rows[c] <= 0 || g->rows[c] % rows_mult)))
|
||||
return RAD_E_SHAPE;
|
||||
if (g->cols[c] > g->x_cols) g->x_cols = g->cols[c];
|
||||
if (g->rows[c] > g->y_cols) g->y_cols = g->rows[c];
|
||||
}
|
||||
g->y_cols = prep ? 2 * g->x_cols : gd ? g->x_cols : g->y_cols / (gate_up ? 2 : 1);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ===================================================================== moe_exl3_gate_up_down AS ITS TWO HALVES
|
||||
*
|
||||
* The fused op read as the pair it is defined by, so every implementation reuses its gate_up and down: the
|
||||
* gate_up view (a_rot = 0, h_rot = 1, gate_up's operands, output h) and the down view (h_rot = 1, down's
|
||||
* geometry [K, N / 2], operands h, dn_codes, dn_suh, dn_svh, routing, output y). `h` is the caller's buffer (a
|
||||
* [T, max(N, N_odd) / 2] f16 tensor). The parameter arrays are the caller's: gate_up at most 11, down 10. */
|
||||
static inline void exl3_gd_params(const RadParam* p, int n_p, RadParam* pg, int* n_pg, RadParam* pd, int* n_pd) {
|
||||
static const RadParam h1 = { "h_rot", RAD_P_INT, 1, 0, 0, 0.0 }, a0 = { "a_rot", RAD_P_INT, 0, 0, 0, 0.0 };
|
||||
const int64_t N = rad_param_geti(p, n_p, "N", 0), K = rad_param_geti(p, n_p, "K", 0);
|
||||
const int two = exl3_geom_two_classes(p, n_p);
|
||||
const int64_t No = rad_param_geti(p, n_p, "N_odd", N), Ko = rad_param_geti(p, n_p, "K_odd", K);
|
||||
int ng = 0, nd = 0;
|
||||
for (int i = 0; i < n_p; ++i) {
|
||||
const char* k = p[i].key;
|
||||
if (!strcmp(k, "h_rot") || !strcmp(k, "a_rot")) continue;
|
||||
if (ng < 9) pg[ng++] = p[i];
|
||||
if (!strcmp(k, "N") || !strcmp(k, "K") || !strcmp(k, "N_odd") || !strcmp(k, "K_odd")) continue;
|
||||
if (nd < 6) pd[nd++] = p[i]; /* M, n_expert, top_k, dtype, codebook */
|
||||
}
|
||||
pg[ng++] = h1;
|
||||
pg[ng++] = a0;
|
||||
pd[nd] = p[0]; pd[nd].key = "N"; pd[nd].kind = RAD_P_INT; pd[nd].ival = K; pd[nd].ihi = 0; ++nd;
|
||||
pd[nd] = pd[nd - 1]; pd[nd].key = "K"; pd[nd].ival = N / 2; ++nd;
|
||||
if (two) {
|
||||
pd[nd] = pd[nd - 1]; pd[nd].key = "N_odd"; pd[nd].ival = Ko; ++nd;
|
||||
pd[nd] = pd[nd - 1]; pd[nd].key = "K_odd"; pd[nd].ival = No / 2; ++nd;
|
||||
}
|
||||
pd[nd++] = h1;
|
||||
*n_pg = ng;
|
||||
*n_pd = nd;
|
||||
}
|
||||
|
||||
/* The operand views over the fused op's operands `t` (18): gate_up's 14 (output h) and down's 10 (input h, output
|
||||
* t[17]). */
|
||||
static inline void exl3_gd_operands(const RadTensor* t, const RadTensor* h, RadTensor* tg, RadTensor* td) {
|
||||
const Exl3Positions* gd = exl3_positions(EXL3_GU_DN);
|
||||
const Exl3Positions* gu = exl3_positions(EXL3_GATE_UP);
|
||||
const Exl3Positions* dn = exl3_positions(EXL3_DOWN);
|
||||
for (int c = 0; c < 2; ++c) {
|
||||
for (int q = EXL3_P_CODES; q <= EXL3_P_DN_SUH; ++q) tg[gu->plane[c][q]] = t[gd->plane[c][q]];
|
||||
td[dn->plane[c][EXL3_P_CODES]] = t[gd->plane[c][EXL3_P_DN_CODES]];
|
||||
td[dn->plane[c][EXL3_P_SUH]] = t[gd->plane[c][EXL3_P_DN_SUH]];
|
||||
td[dn->plane[c][EXL3_P_SVH]] = t[gd->plane[c][EXL3_P_DN_SVH]];
|
||||
}
|
||||
tg[gu->x] = t[gd->x];
|
||||
tg[gu->sorted] = td[dn->sorted] = t[gd->sorted];
|
||||
tg[gu->offset] = td[dn->offset] = t[gd->offset];
|
||||
tg[gu->y] = td[dn->x] = *h;
|
||||
td[dn->y] = t[gd->y];
|
||||
}
|
||||
|
||||
/* ...and version 7's four-class op the same way: the gate_up_mod4 view (a_rot = 0, h_rot = 1) and the down_mod4 view
|
||||
* (class q at [K_q, N_q / 2]). Parameter arrays: gate_up at most 15, down 14. Operands `t` (32): gate_up_mod4's 24
|
||||
* (output h) and down_mod4's 16 (input h, output t[31]). */
|
||||
static inline void exl3_gd4_params(const RadParam* p, int n_p, RadParam* pg, int* n_pg, RadParam* pd, int* n_pd) {
|
||||
static const RadParam h1 = { "h_rot", RAD_P_INT, 1, 0, 0, 0.0 }, a0 = { "a_rot", RAD_P_INT, 0, 0, 0, 0.0 };
|
||||
static const char* const nq[EXL3_MAX_CLS] = { "N", "N_1", "N_2", "N_3" };
|
||||
static const char* const kq[EXL3_MAX_CLS] = { "K", "K_1", "K_2", "K_3" };
|
||||
const int64_t N = rad_param_geti(p, n_p, "N", 0), K = rad_param_geti(p, n_p, "K", 0);
|
||||
int ng = 0, nd = 0;
|
||||
for (int i = 0; i < n_p; ++i) {
|
||||
const char* k = p[i].key;
|
||||
int shape = 0;
|
||||
if (!strcmp(k, "h_rot") || !strcmp(k, "a_rot")) continue;
|
||||
if (ng < 13) pg[ng++] = p[i];
|
||||
for (int c = 0; c < EXL3_MAX_CLS; ++c) shape |= !strcmp(k, nq[c]) || !strcmp(k, kq[c]);
|
||||
if (!shape && nd < 5) pd[nd++] = p[i]; /* M, n_expert, top_k, dtype, codebook */
|
||||
}
|
||||
pg[ng++] = h1;
|
||||
pg[ng++] = a0;
|
||||
for (int c = 0; c < EXL3_MAX_CLS; ++c) {
|
||||
pd[nd] = p[0]; pd[nd].key = nq[c]; pd[nd].kind = RAD_P_INT; pd[nd].ihi = 0;
|
||||
pd[nd].ival = rad_param_geti(p, n_p, kq[c], K); ++nd;
|
||||
pd[nd] = pd[nd - 1]; pd[nd].key = kq[c]; pd[nd].ival = rad_param_geti(p, n_p, nq[c], N) / 2; ++nd;
|
||||
}
|
||||
pd[nd++] = h1;
|
||||
*n_pg = ng;
|
||||
*n_pd = nd;
|
||||
}
|
||||
static inline void exl3_gd4_operands(const RadTensor* t, const RadTensor* h, RadTensor* tg, RadTensor* td) {
|
||||
const Exl3Positions* gd = exl3_positions(EXL3_GU_DN4);
|
||||
const Exl3Positions* gu = exl3_positions(EXL3_GATE_UP4);
|
||||
const Exl3Positions* dn = exl3_positions(EXL3_DOWN4);
|
||||
for (int c = 0; c < EXL3_MAX_CLS; ++c) {
|
||||
for (int q = EXL3_P_CODES; q <= EXL3_P_DN_SUH; ++q) tg[gu->plane[c][q]] = t[gd->plane[c][q]];
|
||||
td[dn->plane[c][EXL3_P_CODES]] = t[gd->plane[c][EXL3_P_DN_CODES]];
|
||||
td[dn->plane[c][EXL3_P_SUH]] = t[gd->plane[c][EXL3_P_DN_SUH]];
|
||||
td[dn->plane[c][EXL3_P_SVH]] = t[gd->plane[c][EXL3_P_DN_SVH]];
|
||||
}
|
||||
tg[gu->x] = t[gd->x];
|
||||
tg[gu->sorted] = td[dn->sorted] = t[gd->sorted];
|
||||
tg[gu->offset] = td[dn->offset] = t[gd->offset];
|
||||
tg[gu->y] = td[dn->x] = *h;
|
||||
td[dn->y] = t[gd->y];
|
||||
}
|
||||
|
||||
/* Expert e's class and its entry in that class's tables. */
|
||||
static inline int exl3_class_of(const Exl3Geom* g, int64_t e) { return (int)(e % g->n_class); }
|
||||
static inline int64_t exl3_entry_of(const Exl3Geom* g, int64_t e) { return e / g->n_class; }
|
||||
/* How many entries class c's tables must hold: ceil((n_expert - c) / n_class). */
|
||||
static inline int64_t exl3_class_entries(const Exl3Geom* g, int c) {
|
||||
return (g->n_expert - c + g->n_class - 1) / g->n_class;
|
||||
}
|
||||
|
||||
#ifdef __cplusplus
|
||||
} /* extern "C" */
|
||||
#endif
|
||||
|
||||
#endif /* EXL3_ABI_H */
|
||||
@@ -0,0 +1,208 @@
|
||||
/* exl3_decode.h -- THE ORACLE: what an EXL3 weight's numbers are, in plain C99, no dependencies.
|
||||
*
|
||||
* Everything another library checks itself against goes through here: the host reference kernels
|
||||
* (kernels/exl3ref), the quantiser's decode hook (quantizers/exl3) and the property tests. It is a
|
||||
* transcription of exllamav3's host-side decode and is checked bit for bit against a golden decode
|
||||
* made by an independent host implementation (common/tests/data/exl3_golden.npz). Slow and readable
|
||||
* on purpose.
|
||||
*
|
||||
* ============================================================ THE FORMAT (one linear, y = x @ W)
|
||||
*
|
||||
* exllamav3 stores a weight W of shape [k, n] (k = in_features, n = out_features) as
|
||||
*
|
||||
* W = diag(suh) . Hb . W_hat . Hb . diag(svh)
|
||||
*
|
||||
* Hb the block-diagonal natural-order Sylvester Hadamard of block 128, scaled 1/sqrt(128); suh f16 [k]
|
||||
* and svh f16 [n] per-channel scales; W_hat [k, n] the trellis-coded values, cut into 16x16 tiles.
|
||||
* Tile (tk, tn) is 16*K int16 = 8*K little-endian u32 words, read as ONE MSB-first stream of 256*K
|
||||
* bits. Position p (0..255) owns stream bits [p*K, (p+1)*K) -- its K-bit SYMBOL -- and its 16-bit
|
||||
* STATE is the 16-bit window ending at bit (p+1)*K, circular within the tile. A codebook maps the
|
||||
* state to an fp16 value. Position p = 8*L + j (L 0..31, j 0..7) sits at tile row (k axis)
|
||||
* 2*(L%4) + {0,1,8,9}[j%4] and tile column (n axis) L/4 + 8*(j/4).
|
||||
*
|
||||
* ============================================================ RADIANCE'S VIEW (the canonical planes)
|
||||
*
|
||||
* radiance stores a weight as [rows, cols] = [n, k]: row i is OUTPUT feature n = i, column j is
|
||||
* INPUT feature k = j (the transpose of exllamav3's [k, n]). The canonical EXL3 encoding
|
||||
* (include/exl3_encoding.h) holds, at codes-plane element (i, j), the K-bit SYMBOL of
|
||||
* the trellis position that decodes weight element W_hat[k = j][n = i]: tile (tk = j/16, tn = i/16),
|
||||
* position exl3_tile_to_pos(j % 16, i % 16). The plane is uK, row-major, each row a bit stream
|
||||
* lowest bits first and starting on a byte (rad_encoding.h), so element (i, j) is bits
|
||||
* [j*K, (j+1)*K) of row i and its VALUE is the symbol. Every symbol sequence is a valid trellis, so
|
||||
* this is a lossless permutation of the tile streams (exl3_layout.h converts both ways), and any
|
||||
* cut on 16 rows / 16 columns keeps tiles whole.
|
||||
*
|
||||
* "Decode one expert's weight to f32" is exl3_decode_rows(view, 0, view->rows, out): out is
|
||||
* f32 [n][k] -- radiance's [rows, cols], i.e. out[n*k_total + k] = W[k][n] in exllamav3's terms.
|
||||
*
|
||||
* ============================================================ NUMERICS
|
||||
*
|
||||
* Codebook values are exact fp16 (one rounding, as exllamav3's __hfma / __hadd). The Hadamard is the
|
||||
* butterfly in f32 then one multiply by (float)(1/sqrt(128)); W is formed in exllamav3's order
|
||||
* (had over k, x suh, had over n, x svh) in f32. Bit-exact claims are made for W_hat only; W agrees
|
||||
* with an f32 transcription to rounding (the tests state the bound). Build with -ffp-contract=off.
|
||||
*
|
||||
* Thread safety: every function is reentrant (no static state; scratch is malloc'd per call).
|
||||
*/
|
||||
#ifndef EXL3_DECODE_H
|
||||
#define EXL3_DECODE_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* Bumped on any change to a declaration below; consumers check it at compile time.
|
||||
* 2: half-integer K (exllamav3 >= 1.6), carried as a TAGGED `bits` (below). */
|
||||
#define EXL3_DECODE_API_VERSION 2
|
||||
|
||||
enum {
|
||||
EXL3_TILE = 16, /* a tile is 16 x 16 weights */
|
||||
EXL3_TILE_POS = 256, /* positions a tile */
|
||||
EXL3_HAD = 128, /* rotation block; both feature counts are multiples of it */
|
||||
EXL3_BITS_MIN = 1, /* integer K, bits a weight, that the DECODER reads (exllamav3 1.4.4: 1..8) */
|
||||
EXL3_BITS_MAX = 8
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ half-integer K (exllamav3 >= 1.6)
|
||||
*
|
||||
* exllamav3 1.6 adds K = KA + 0.5 (1.5, 2.5, 3.5; mul1 codebook only): the tile's positions alternate KA and KA + 1
|
||||
* bits, the ODD positions carrying the extra bit (exl3_lib/quantize.py frac_k: mask 0xAAAA), so a tile is a ring of
|
||||
* 128 * (2 KA + 1) bits = 16 * K uint16 (40 at K = 2.5). Position p's symbol is stream bits [S(p - 1), S(p)) and its
|
||||
* state the 16-bit window ending at S(p), circular in the ring, with S(p) = floor((p + 1) * K2 / 2) and K2 = 2 K --
|
||||
* which is (p + 1) * K at integer K, so ONE formula covers both (exllamav3 frac.cu frac_s / frac_window).
|
||||
*
|
||||
* Everything here that takes `int bits` takes K TAGGED: an integer K is itself (1..8), a half-integer K is
|
||||
* EXL3_HALF(KA) = 16 + 2 KA + 1 (1.5 -> 19, 2.5 -> 21, 3.5 -> 23). exl3_k2(bits) is 2 K either way.
|
||||
*
|
||||
* The canonical codes plane keeps the same rule along a row: element j (k = j) is bits [off(j), off(j + 1)) with
|
||||
* off(j) = floor(j * K2 / 2), LSB-first. Positions 2m and 2m + 1 of a tile are adjacent k (tile rows r, r + 1, r even)
|
||||
* in one n column, so in radiance's [n, k] view the even column holds KA bits and the odd column KA + 1: a row is
|
||||
* cols / 2 PAIR symbols of 2 KA + 1 bits (value = even | odd << KA), which is exactly a TILED u(2KA+1) plane of block
|
||||
* [1 x 2] (include/exl3_encoding.h). At integer K it is the uK [1 x 1] plane, bit for bit as before. */
|
||||
enum { EXL3_HALF_TAG = 16 };
|
||||
#define EXL3_HALF(ka) (EXL3_HALF_TAG + 2 * (ka) + 1)
|
||||
|
||||
static inline int exl3_bits_half(int bits) {
|
||||
return bits == EXL3_HALF(1) || bits == EXL3_HALF(2) || bits == EXL3_HALF(3);
|
||||
}
|
||||
static inline int exl3_bits_valid(int bits) {
|
||||
return (bits >= EXL3_BITS_MIN && bits <= EXL3_BITS_MAX) || exl3_bits_half(bits);
|
||||
}
|
||||
/* 2 K: half-bit units (K = 2.5 -> 5). 0 for a `bits` that is not valid. */
|
||||
static inline int exl3_k2(int bits) {
|
||||
return exl3_bits_half(bits) ? bits - EXL3_HALF_TAG : exl3_bits_valid(bits) ? 2 * bits : 0;
|
||||
}
|
||||
/* Bit offset of symbol j along a tile stream or a canonical row, and its width (K, or KA / KA + 1 by parity). */
|
||||
static inline int64_t exl3_sym_off(int bits, int64_t j) { return j * exl3_k2(bits) / 2; }
|
||||
static inline int exl3_sym_width(int bits, int64_t j) {
|
||||
return (int)(exl3_sym_off(bits, j + 1) - exl3_sym_off(bits, j));
|
||||
}
|
||||
|
||||
/* Codebooks, numbered as exllamav3 numbers them (cb template argument, codebook.cuh). */
|
||||
enum { EXL3_CB_3INST = 0, EXL3_CB_MCG = 1, EXL3_CB_MUL1 = 2 };
|
||||
|
||||
/* The scalar a checkpoint stores beside the trellis to name its codebook: `<name>.mul1` or
|
||||
* `<name>.mcg`, I32 [] holding these bits; neither present means 3inst. */
|
||||
#define EXL3_MUL1_MARKER 0x83DCD12Du
|
||||
#define EXL3_MCG_MARKER 0xCBAC1FEDu
|
||||
|
||||
/* Return codes. Negative is failure; consumers map them to their own (RAD_E_*). */
|
||||
enum { EXL3_OK = 0, EXL3_E_ARG = -1, EXL3_E_SHAPE = -2, EXL3_E_NOMEM = -3 };
|
||||
|
||||
/* "3inst", "mcg", "mul1"; null for anything else. Inline so header-only consumers
|
||||
* (include/exl3_encoding.h) need nothing linked. */
|
||||
static inline const char* exl3_codebook_name(int codebook) {
|
||||
return codebook == EXL3_CB_3INST ? "3inst"
|
||||
: codebook == EXL3_CB_MCG ? "mcg"
|
||||
: codebook == EXL3_CB_MUL1 ? "mul1" : 0;
|
||||
}
|
||||
/* The inverse; -1 for a name that is not one of the three. */
|
||||
static inline int exl3_codebook_from_name(const char* name) {
|
||||
int cb;
|
||||
for (cb = EXL3_CB_3INST; cb <= EXL3_CB_MUL1 && name; ++cb) {
|
||||
const char* a = exl3_codebook_name(cb);
|
||||
const char* b = name;
|
||||
while (*a && *a == *b) { ++a; ++b; }
|
||||
if (!*a && !*b) return cb;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ fp16 */
|
||||
float exl3_half_to_float(uint16_t h);
|
||||
/* Round to nearest even, ONE rounding of the exact double; overflow to inf, nan to 0x7E00. */
|
||||
uint16_t exl3_half_from_double(double x);
|
||||
|
||||
/* ------------------------------------------------------------------ codebook */
|
||||
/* A 16-bit trellis state (higher bits ignored) to its fp16 value, as fp16 bits. */
|
||||
uint16_t exl3_codebook_value(uint32_t state, int codebook);
|
||||
|
||||
/* ------------------------------------------------------------------ the tile */
|
||||
/* Position p (0..255) -> tile row r (k axis, 0..15) and tile column c (n axis, 0..15). */
|
||||
void exl3_pos_to_tile(int p, int* r, int* c);
|
||||
/* Tile (r, c) -> position. */
|
||||
int exl3_tile_to_pos(int r, int c);
|
||||
|
||||
/* One tile's stream (16*K uint16, i.e. 8*K little-endian u32 words, MSB-first) -> its 256 symbols,
|
||||
* symbol p being stream bits [off(p), off(p+1)) read MSB first (p*K .. (p+1)*K at integer K). */
|
||||
void exl3_tile_symbols(const uint16_t* tile, int bits, uint8_t sym[EXL3_TILE_POS]);
|
||||
/* The inverse: 256 symbols (low K bits used) -> the tile stream. Any symbols are a valid trellis. */
|
||||
void exl3_tile_pack(const uint8_t sym[EXL3_TILE_POS], int bits, uint16_t* tile);
|
||||
/* The 16-bit state of every position: the window of the symbol stream ending at symbol p's last
|
||||
* bit, circular within the tile (tail-biting). */
|
||||
void exl3_tile_states(const uint8_t sym[EXL3_TILE_POS], int bits, uint16_t state[EXL3_TILE_POS]);
|
||||
|
||||
/* A whole trellis tensor as exllamav3 stores it -- int16 [kt][nt][16*K] (K2 = 2K: 8*K2), tile (tk, tn) at
|
||||
* (tk*nt + tn)*16*K -- to W_hat [16*kt][16*nt] as fp16 bits (exllamav3's [k, n] order: the golden's).
|
||||
* EXL3_E_ARG for bits or codebook out of range. */
|
||||
int exl3_trellis_decode(const uint16_t* trellis, int64_t kt, int64_t nt, int bits, int codebook,
|
||||
uint16_t* w_hat);
|
||||
|
||||
/* ------------------------------------------------------------------ the codes plane */
|
||||
/* Element (i, j) of a codes plane, rows `row_bytes` apart, LSB-first along the row: the K-bit symbol of column j
|
||||
* (half-integer K: bits [off(j), off(j+1)), KA or KA + 1 wide by j's parity). */
|
||||
uint32_t exl3_codes_get(const uint8_t* codes, int64_t row_bytes, int bits, int64_t i, int64_t j);
|
||||
void exl3_codes_set(uint8_t* codes, int64_t row_bytes, int bits, int64_t i, int64_t j,
|
||||
uint32_t value);
|
||||
/* Bytes of one dense row of `cols` symbols: ceil(off(cols)/8) = ceil(cols*K/8). */
|
||||
int64_t exl3_codes_row_bytes(int64_t cols, int bits);
|
||||
|
||||
/* ------------------------------------------------------------------ the rotation */
|
||||
/* The normalised natural-order Sylvester Hadamard over each block of 128 of v[0..n), in place:
|
||||
* butterfly (a+b low, a-b high) in f32, then x (float)(1/sqrt(128)). EXL3_E_SHAPE unless n % 128 == 0. */
|
||||
int exl3_had128(float* v, int64_t n);
|
||||
|
||||
/* ------------------------------------------------------------------ one weight from its planes */
|
||||
/* One weight -- a projection, or a TP slice of one -- in radiance's [rows = n, cols = k] view, as
|
||||
* the canonical planes hold it. A STACKED gate_up (gate rows then up rows) has the up
|
||||
* half's input scales in `suh1`: rows [0, rows/2) are read with `suh`, rows [rows/2, rows) with
|
||||
* `suh1`. A TP slice of a stacked weight takes the same span of each half, so the rule holds for
|
||||
* the slice. */
|
||||
typedef struct Exl3View {
|
||||
int64_t rows, cols; /* n, k */
|
||||
int bits; /* K */
|
||||
int codebook; /* EXL3_CB_* */
|
||||
const uint8_t* codes; /* uK [rows][cols], row-major, LSB-first */
|
||||
int64_t codes_row_bytes; /* the stride; 0 = dense, exl3_codes_row_bytes(cols, bits) */
|
||||
const uint16_t* suh; /* f16 [cols] */
|
||||
const uint16_t* suh1; /* f16 [cols] for the second half of a stacked weight, or null */
|
||||
const uint16_t* svh; /* f16 [rows] */
|
||||
} Exl3View;
|
||||
|
||||
/* W_hat (the rotated basis, the values a kernel multiplies by) of rows [row0, row0+n) as f32
|
||||
* [n][cols], each an exact fp16 value. Needs only codes, bits, codebook, rows, cols; rows and cols
|
||||
* multiples of 16. EXL3_E_ARG / EXL3_E_SHAPE (a range outside the view) / EXL3_E_NOMEM. */
|
||||
int exl3_decode_what_rows(const Exl3View* v, int64_t row0, int64_t n, float* out);
|
||||
|
||||
/* The weight itself, rows [row0, row0+n) as f32 [n][cols] = W[k][n] transposed (see the header).
|
||||
* rows and cols multiples of 128 (both rotations), and of 256 rows when suh1 is set. Any row range
|
||||
* inside the view; the enclosing 128-row blocks are decoded. */
|
||||
int exl3_decode_rows(const Exl3View* v, int64_t row0, int64_t n, float* out);
|
||||
|
||||
#ifdef __cplusplus
|
||||
} /* extern "C" */
|
||||
#endif
|
||||
|
||||
#endif /* EXL3_DECODE_H */
|
||||
@@ -0,0 +1,159 @@
|
||||
/* exl3_encoding.h -- THE canonical EXL3 encoding, as radiance encoding data, and the
|
||||
* GEMM dtype strings the architecture and kernels name it by. Header-only.
|
||||
*
|
||||
* include/exl3_abi.h includes this file; nothing else defines the encoding. A weight in it:
|
||||
*
|
||||
* scheme "exl3" a quantiser's own scheme: the core checks plane 0 and
|
||||
* role uniqueness only (rad_enc_valid) and decodes it
|
||||
* through the exl3 quantiser's decode hook
|
||||
* transform "<codebook>/h128" "mul1/h128", "mcg/h128" or "3inst/h128": the trellis
|
||||
* codebook, and the rotation (normalised Hadamard,
|
||||
* block 128) on BOTH sides of the weight
|
||||
* plane 0 codes uK TILED [1x1] element (i, j) = the K-bit trellis symbol of W_hat at
|
||||
* (k = j, n = i), position-major (common/exl3_decode.h)
|
||||
* half-integer K = KA + 0.5: u(2KA+1) TILED [1x2]: element (i, m) = the PAIR symbol of
|
||||
* columns 2m (KA bits, low) and 2m + 1 (KA + 1 bits, high) --
|
||||
* the same bits as reading column j at off(j) = floor(j K2 / 2)
|
||||
* plane 1 suh f16 TILED [0x1] input scales, one a column (k); cut with the columns
|
||||
* plane 2 svh f16 TILED [1x0] output scales, one a row (n); cut with the rows
|
||||
* plane 3 suh.1 f16 TILED [0x1] STACKED gate_up only: the up half's input scales;
|
||||
* rows [rows/2, rows) read suh.1, the first half suh
|
||||
*
|
||||
* so a stacked 4-bit gate_up spells `exl3:codes=u4[1x1],suh=f16[*x1],svh=f16[1x*],suh.1=f16[*x1]/mul1/h128`.
|
||||
* The plane ORDER is fixed (the indices below) so down and gate_up share planes 0..2; read by role
|
||||
* where a role is enough. Encodings are identical byte for byte (rad_enc_equal) or different:
|
||||
* exl3_encoding_read() refuses anything exl3_encoding_make() would not have written.
|
||||
*
|
||||
* K is per weight and per encoding: two weights of different K are two encodings. A recipe's bits
|
||||
* option, the trellis tensor's last dimension (16*K) and the codes dtype must all agree.
|
||||
*/
|
||||
#ifndef EXL3_ENCODING_H
|
||||
#define EXL3_ENCODING_H
|
||||
|
||||
#include "rad_encoding.h"
|
||||
#include "exl3_decode.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* Bumped on any change to the encoding or a declaration below. 2: half-integer K (the [1x2] pair plane). */
|
||||
#define EXL3_ENCODING_VERSION 2
|
||||
|
||||
#define EXL3_SCHEME "exl3"
|
||||
#define EXL3_ROTATION "h128" /* the second half of the transform string */
|
||||
|
||||
enum { EXL3_PLANE_CODES = 0, EXL3_PLANE_SUH = 1, EXL3_PLANE_SVH = 2, EXL3_PLANE_SUH1 = 3 };
|
||||
|
||||
/* The K a GEMM dtype string exists for: "exl3k2" .. "exl3k8", and the half-integer "exl3k1h" (1.5), "exl3k2h"
|
||||
* (2.5), "exl3k3h" (3.5). The DECODER reads K 1..8 and the three half-integer K (exl3_decode.h: a TAGGED `bits`);
|
||||
* K=1 has no dtype string, so no kernel can be named for it and the quantiser refuses it. The loops below walk
|
||||
* EXL3_GEMM_BITS_MIN..MAX, the integer K; the half-integer K are listed apart. */
|
||||
enum { EXL3_GEMM_BITS_MIN = 2, EXL3_GEMM_BITS_MAX = 8 };
|
||||
|
||||
/* The core dtype of a codes plane: RAD_U1..RAD_U8 for integer K (one symbol an element); for half-integer K the
|
||||
* pair symbol's 2 KA + 1 bits (RAD_U3 / RAD_U5 / RAD_U7, block [1x2]); RAD_DT_INVALID otherwise. */
|
||||
static inline uint32_t exl3_codes_dtype(int bits) {
|
||||
static const uint32_t dt[9] = { RAD_DT_INVALID, RAD_U1, RAD_U2, RAD_U3, RAD_U4,
|
||||
RAD_U5, RAD_U6, RAD_U7, RAD_U8 };
|
||||
if (exl3_bits_half(bits)) return dt[exl3_k2(bits)];
|
||||
return bits >= EXL3_BITS_MIN && bits <= EXL3_BITS_MAX ? dt[bits] : (uint32_t)RAD_DT_INVALID;
|
||||
}
|
||||
|
||||
/* Columns of the codes plane's element grid over a weight of `cols` columns: cols, or cols / 2 pairs. */
|
||||
static inline int64_t exl3_codes_plane_cols(int64_t cols, int bits) {
|
||||
return exl3_bits_half(bits) ? cols / 2 : cols;
|
||||
}
|
||||
|
||||
/* The inverse of exl3_codes_dtype for a [1x1] codes plane (integer K): K, or -1. */
|
||||
static inline int exl3_bits_of_dtype(uint32_t dtype) {
|
||||
int k;
|
||||
for (k = EXL3_BITS_MIN; k <= EXL3_BITS_MAX; ++k)
|
||||
if (exl3_codes_dtype(k) == dtype) return k;
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* The (tagged) K of a codes plane by its dtype AND block: [1x1] integer K, [1x2] half-integer K; -1 otherwise. */
|
||||
static inline int exl3_bits_of_plane(uint32_t dtype, int64_t block_cols) {
|
||||
int ka;
|
||||
if (block_cols == 1) return exl3_bits_of_dtype(dtype);
|
||||
if (block_cols != 2) return -1;
|
||||
for (ka = 1; ka <= 3; ++ka)
|
||||
if (exl3_codes_dtype(EXL3_HALF(ka)) == dtype) return EXL3_HALF(ka);
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* The GEMM dtype string an op constraint names for K-bit EXL3 weights; null when K has none. It
|
||||
* names K only: the codebook is in the encoding, and a kernel's layout hook refuses a codebook it
|
||||
* does not decode (RAD_E_DTYPE) -- the gfx1201 rows decode mul1 alone. */
|
||||
static inline const char* exl3_gemm_dtype(int bits) {
|
||||
static const char* const s[9] = { 0, 0, "exl3k2", "exl3k3", "exl3k4",
|
||||
"exl3k5", "exl3k6", "exl3k7", "exl3k8" };
|
||||
static const char* const h[4] = { 0, "exl3k1h", "exl3k2h", "exl3k3h" };
|
||||
if (exl3_bits_half(bits)) return h[exl3_k2(bits) / 2];
|
||||
return bits >= EXL3_GEMM_BITS_MIN && bits <= EXL3_GEMM_BITS_MAX ? s[bits] : 0;
|
||||
}
|
||||
|
||||
/* K of a GEMM dtype string (tagged for half-integer K), or -1. */
|
||||
static inline int exl3_gemm_bits(const char* dtype) {
|
||||
int k;
|
||||
for (k = EXL3_GEMM_BITS_MIN; k <= EXL3_GEMM_BITS_MAX && dtype; ++k)
|
||||
if (strcmp(dtype, exl3_gemm_dtype(k)) == 0) return k;
|
||||
for (k = 1; k <= 3 && dtype; ++k)
|
||||
if (strcmp(dtype, exl3_gemm_dtype(EXL3_HALF(k))) == 0) return EXL3_HALF(k);
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* The encoding of a K-bit weight in `codebook`; `stacked` nonzero for a gate_up (adds suh.1).
|
||||
* RAD_OK, or RAD_E_INVAL for K outside 1..8 and the half-integer three, an unknown codebook, or a
|
||||
* half-integer K in another codebook than mul1. */
|
||||
static inline int exl3_encoding_make(int bits, int codebook, int stacked, RadEncoding* out) {
|
||||
char t[RAD_ENC_STR];
|
||||
const char* cb = exl3_codebook_name(codebook);
|
||||
const uint32_t dt = exl3_codes_dtype(bits);
|
||||
if (!out || !cb || dt == RAD_DT_INVALID) return RAD_E_INVAL;
|
||||
if (exl3_bits_half(bits) && codebook != EXL3_CB_MUL1) return RAD_E_INVAL;
|
||||
rad_enc_clear(out);
|
||||
rad_enc_copy_str(out->scheme, EXL3_SCHEME);
|
||||
snprintf(t, sizeof t, "%s/%s", cb, EXL3_ROTATION);
|
||||
rad_enc_copy_str(out->transform, t);
|
||||
rad_enc_add_plane(out, "codes", dt, 1, exl3_bits_half(bits) ? 2 : 1);
|
||||
rad_enc_add_plane(out, "suh", RAD_F16, 0, 1);
|
||||
rad_enc_add_plane(out, "svh", RAD_F16, 1, 0);
|
||||
if (stacked) rad_enc_add_plane(out, "suh.1", RAD_F16, 0, 1);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Read an encoding back. RAD_E_UNSUPPORTED when the scheme is not "exl3" (not ours: a decoder
|
||||
* answers that and the core asks the next one); RAD_E_FORMAT when it says "exl3" but is not exactly
|
||||
* what exl3_encoding_make writes for some K, codebook and stacking; RAD_OK otherwise, with the
|
||||
* three filled in (any pointer may be null). */
|
||||
static inline int exl3_encoding_read(const RadEncoding* e, int* bits, int* codebook, int* stacked) {
|
||||
RadEncoding want;
|
||||
char cb[RAD_ENC_STR];
|
||||
const char* slash;
|
||||
size_t n;
|
||||
int k, c, s;
|
||||
if (!e || !rad_enc_is(e, EXL3_SCHEME)) return RAD_E_UNSUPPORTED;
|
||||
if (e->n_planes < 3 || e->n_planes > 4) return RAD_E_FORMAT;
|
||||
slash = (const char*)memchr(e->transform, '/', RAD_ENC_STR);
|
||||
if (!slash) return RAD_E_FORMAT;
|
||||
n = (size_t)(slash - e->transform);
|
||||
memcpy(cb, e->transform, n);
|
||||
cb[n] = 0;
|
||||
k = exl3_bits_of_plane(e->plane[EXL3_PLANE_CODES].dtype, e->plane[EXL3_PLANE_CODES].block[1]);
|
||||
c = exl3_codebook_from_name(cb);
|
||||
s = e->n_planes == 4;
|
||||
if (k < 0 || c < 0 || exl3_encoding_make(k, c, s, &want) != RAD_OK || !rad_enc_equal(e, &want))
|
||||
return RAD_E_FORMAT;
|
||||
if (bits) *bits = k;
|
||||
if (codebook) *codebook = c;
|
||||
if (stacked) *stacked = s;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
#ifdef __cplusplus
|
||||
} /* extern "C" */
|
||||
#endif
|
||||
|
||||
#endif /* EXL3_ENCODING_H */
|
||||
+460
-49
@@ -17,6 +17,7 @@
|
||||
#include "rad_yarn.h"
|
||||
#include "rad_abi_layout.h"
|
||||
|
||||
#include <cctype>
|
||||
#include <cstdarg>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
@@ -36,9 +37,12 @@ namespace rad {
|
||||
namespace arch {
|
||||
|
||||
/* One thread per tensor-parallel rank in one process (spec §1), and declare runs once per rank,
|
||||
* so declared handles are per-rank state; a single global would let rank 1 overwrite rank 0.
|
||||
* libr4d all-reduces over 2/4/8 ranks, hence eight. */
|
||||
enum { MAX_RANKS = 8 };
|
||||
* so declared handles are per-instance state; a single global would let rank 1 overwrite rank 0.
|
||||
* libr4d all-reduces over 2/4/8 ranks, hence eight ranks. Several engines may run in the process
|
||||
* (docs/MULTIMODEL.md), each with its own ranks, so state is indexed by the instance's slot
|
||||
* (rad_build_slot at declare, rad_slot in step), unique across all of them, never by the rank two
|
||||
* engines share. */
|
||||
enum { MAX_RANKS = 8, MAX_SLOTS = RAD_MAX_SLOTS };
|
||||
|
||||
/* ================================================================== a debug residual probe
|
||||
*
|
||||
@@ -123,6 +127,36 @@ inline const char* calib_dir() {
|
||||
return d && *d ? d : nullptr;
|
||||
}
|
||||
|
||||
/* Whether layer `layer` taps (RADIANCE_CALIB_LAYERS: comma-separated layers and "lo-hi" ranges;
|
||||
* unset, every layer). A model whose per-expert Hessians do not fit the host at once (Nemotron-3.5
|
||||
* Bolt's are 169 GiB) calibrates in several runs over disjoint ranges; each run writes only its
|
||||
* layers' files, so the runs share one directory. */
|
||||
inline bool calib_layer_on(int layer) {
|
||||
static const std::vector<std::pair<int, int>> ranges = [] {
|
||||
std::vector<std::pair<int, int>> r;
|
||||
const char* s = std::getenv("RADIANCE_CALIB_LAYERS");
|
||||
while (s && *s) {
|
||||
char* e = nullptr;
|
||||
const long lo = std::strtol(s, &e, 10);
|
||||
if (e == s) break;
|
||||
long hi = lo;
|
||||
if (*e == '-') {
|
||||
const char* h = e + 1;
|
||||
hi = std::strtol(h, &e, 10);
|
||||
if (e == h) break;
|
||||
}
|
||||
r.emplace_back((int)lo, (int)hi);
|
||||
s = *e == ',' ? e + 1 : e;
|
||||
if (*s && *s != ',' && !std::isdigit((unsigned char)*s)) break;
|
||||
}
|
||||
return r;
|
||||
}();
|
||||
if (!std::getenv("RADIANCE_CALIB_LAYERS")) return true;
|
||||
for (const auto& r : ranges)
|
||||
if (layer >= r.first && layer <= r.second) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Token count at which the tap dumps and switches itself off (RADIANCE_CALIB_TOKENS, default
|
||||
* 65536). Whether the tap runs at all is calib_dir()'s decision. */
|
||||
inline long long calib_target() {
|
||||
@@ -150,10 +184,9 @@ inline long long calib_target() {
|
||||
* from an exercised one: libquant reads a per-expert file only when it holds several times K
|
||||
* rows. `domain` is what the tap summed; a reader quantising in another domain converts the file
|
||||
* itself (libquant's calib_sum). */
|
||||
inline bool calib_write_host(const float* h, int64_t k, long long rows, const char* what,
|
||||
uint32_t domain, int rank) {
|
||||
const char* dir = calib_dir();
|
||||
if (!dir || !h || k <= 0) return false;
|
||||
inline bool calib_write_host_to(const char* dir, const float* h, int64_t k, long long rows,
|
||||
const char* what, uint32_t domain, int rank) {
|
||||
if (!dir || !*dir || !h || k <= 0) return false;
|
||||
char path[512];
|
||||
std::snprintf(path, sizeof path, "%s/gram.r%d.%s.bin", dir, rank, what);
|
||||
FILE* f = std::fopen(path, "wb");
|
||||
@@ -177,6 +210,11 @@ inline bool calib_write_host(const float* h, int64_t k, long long rows, const ch
|
||||
return okw;
|
||||
}
|
||||
|
||||
inline bool calib_write_host(const float* h, int64_t k, long long rows, const char* what,
|
||||
uint32_t domain, int rank) {
|
||||
return calib_write_host_to(calib_dir(), h, k, rows, what, domain, rank);
|
||||
}
|
||||
|
||||
/* The same file from a device accumulator: copied back on the block's stream, then written. */
|
||||
inline bool calib_write(RadCtx* c, rad_buf b, int64_t k, long long rows, const char* what,
|
||||
uint32_t domain) {
|
||||
@@ -189,13 +227,27 @@ inline bool calib_write(RadCtx* c, rad_buf b, int64_t k, long long rows, const c
|
||||
return calib_write_host(h.data(), k, rows, what, domain, rad_rank(c));
|
||||
}
|
||||
|
||||
/* A pinned host buffer of at least `bytes`, one per rank, held for the process lifetime, so a tap
|
||||
* that copies a scratch back every pass runs at link speed. Null (and logged) on failure. */
|
||||
/* A selected architecture tap may use the build context's directory directly, rather than the
|
||||
* process environment helper above. */
|
||||
inline bool calib_write_to(RadCtx* c, rad_buf b, int64_t k, long long rows, const char* what,
|
||||
uint32_t domain, const char* dir) {
|
||||
if (!dir || !*dir || !b || k <= 0) return false;
|
||||
void* p = rad_buf_ptr(c, b);
|
||||
if (!p) return false;
|
||||
std::vector<float> h((size_t)(k * k));
|
||||
if (rad_memcpy_async(h.data(), p, (int64_t)h.size() * 4, rad_stream(c)) < 0) return false;
|
||||
if (rad_stream_sync(rad_stream(c)) < 0) return false;
|
||||
return calib_write_host_to(dir, h.data(), k, rows, what, domain, rad_rank(c));
|
||||
}
|
||||
|
||||
/* A pinned host buffer of at least `bytes`, one per instance (slot), held for the process
|
||||
* lifetime, so a tap that copies a scratch back every pass runs at link speed. Null (and logged)
|
||||
* on failure. */
|
||||
inline float* calib_staging(RadCtx* c, int64_t bytes) {
|
||||
static std::mutex mu;
|
||||
static std::map<int, std::pair<void*, int64_t>> per_rank;
|
||||
static std::map<int, std::pair<void*, int64_t>> per_slot;
|
||||
std::lock_guard<std::mutex> lk(mu);
|
||||
std::pair<void*, int64_t>& s = per_rank[rad_rank(c)];
|
||||
std::pair<void*, int64_t>& s = per_slot[rad_slot(c)];
|
||||
if (s.second >= bytes) return (float*)s.first;
|
||||
if (s.first) rad_dev_free(s.first, RAD_MEM_HOST_PINNED);
|
||||
s.first = rad_dev_alloc(bytes, RAD_MEM_HOST_PINNED);
|
||||
@@ -309,8 +361,36 @@ private:
|
||||
std::string scope_;
|
||||
};
|
||||
|
||||
/* Returns the first negative status from a declare step. */
|
||||
#define RAD_ARCH_TRY(expr) do { int _s = (expr); if (_s < 0) return _s; } while (0)
|
||||
/* Returns the first negative status from a declare step, and says where the status crossed. A
|
||||
* step can return a status with no message of its own, and a failed declare would then report
|
||||
* the status alone. Every level the status passes prints one line, innermost first, so the lines
|
||||
* read as the path from the step that failed up to the plugin's declare. */
|
||||
#ifdef __FILE_NAME__
|
||||
#define RAD_ARCH_FILE __FILE_NAME__
|
||||
#else
|
||||
#define RAD_ARCH_FILE __FILE__
|
||||
#endif
|
||||
#define RAD_ARCH_TRY(expr) \
|
||||
do { \
|
||||
int _s = (expr); \
|
||||
if (_s < 0) { \
|
||||
fprintf(stderr, "radiance: declare: %s, from %s:%d\n", rad_strerror(_s), \
|
||||
RAD_ARCH_FILE, __LINE__); \
|
||||
return _s; \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
/* The status of a block whose declaration got no handle for the names in `what` (an op that
|
||||
* resolves to no kernel is recorded and handed back null, an error only if the block issues it, so
|
||||
* without this a missing kernel surfaces as a bare "invalid argument" at startup). The builder
|
||||
* has said why in its own words; this names which handle did not come back, so that message reads
|
||||
* against a line of the block. */
|
||||
inline int declare_refused(const char* block, std::initializer_list<const char*> what) {
|
||||
std::string list;
|
||||
for (const char* w : what) { if (!list.empty()) list += ", "; list += w; }
|
||||
std::fprintf(stderr, "%s: the builder gave no handle for %s\n", block, list.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* ================================================================== C++-side decl helpers */
|
||||
/* C++ forms of rad_group_layer() and friends, which are C compound literals (a GNU extension in
|
||||
@@ -484,6 +564,16 @@ inline int map_tap(RadBuilder* b, const char* declared, const char* src, int dim
|
||||
return rad_decl_name_map(b, &m);
|
||||
}
|
||||
|
||||
/* The elementwise product of two checkpoint tensors of one shape (RAD_MAP_MUL): a gain shipped as
|
||||
* two factors. */
|
||||
inline int map_mul(RadBuilder* b, const char* declared, const char* a, const char* c) {
|
||||
RadNameMap m = map_base(declared, RAD_MAP_MUL);
|
||||
m.n_src = 2;
|
||||
m.src[0] = a;
|
||||
m.src[1] = c;
|
||||
return rad_decl_name_map(b, &m);
|
||||
}
|
||||
|
||||
/* An EMA codebook: the embedding sums over max(cluster usage, 1e-5), row by row (RAD_MAP_EMA). */
|
||||
inline int map_ema(RadBuilder* b, const char* declared, const char* sums, const char* usage) {
|
||||
RadNameMap m = map_base(declared, RAD_MAP_EMA);
|
||||
@@ -501,6 +591,14 @@ inline int map_copy(RadBuilder* b, const char* declared, const char* src) {
|
||||
return rad_decl_name_map(b, &m);
|
||||
}
|
||||
|
||||
/* A checkpoint tensor copied through unchanged and declared replicated on every rank, in the
|
||||
* movement group of layer `group`. Null when the copy or the declaration is refused. */
|
||||
inline rad_weight wcopy(RadBuilder* b, const char* dn, const char* src, uint32_t dtype,
|
||||
std::initializer_list<int64_t> shape, int access, int group) {
|
||||
if (map_copy(b, dn, src) < 0) return 0;
|
||||
return decl_w(b, dn, dtype, shape, access, RAD_SHARD_NONE, grp_layer(group));
|
||||
}
|
||||
|
||||
/* A copy with an alternative source; the first one the container holds wins. Expresses a tied
|
||||
* lm_head: Qwen3 0.6B and 1.7B ship no output.weight and reuse the embedding, 8B and up ship
|
||||
* one. */
|
||||
@@ -609,6 +707,89 @@ inline rad_op rw(RadBuilder* b, rad_op h,
|
||||
return h;
|
||||
}
|
||||
|
||||
/* y = a + c over `rows` rows of `n`, at `dtype`. */
|
||||
inline rad_op add_op(RadBuilder* b, int64_t rows, int64_t n, const char* dtype, rad_buf a,
|
||||
rad_buf c, rad_buf y) {
|
||||
return rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_STR("dtype", dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ a, c }, { y });
|
||||
}
|
||||
inline rad_op add_op(RadBuilder* b, int64_t rows, int64_t n, rad_buf a, rad_buf c, rad_buf y) {
|
||||
return add_op(b, rows, n, "bf16", a, c, y);
|
||||
}
|
||||
|
||||
/* An elementwise op `op` (silu, gelu, ...) of one input over `rows` rows of `n`, at `dtype`. */
|
||||
inline rad_op unary(RadBuilder* b, const char* op, int64_t rows, int64_t n, const char* dtype,
|
||||
rad_buf in, rad_buf out) {
|
||||
return rw(b, RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_STR("dtype", dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ in }, { out });
|
||||
}
|
||||
inline rad_op unary(RadBuilder* b, const char* op, int64_t rows, int64_t n, rad_buf in,
|
||||
rad_buf out) {
|
||||
return unary(b, op, rows, n, "bf16", in, out);
|
||||
}
|
||||
|
||||
/* A dtype conversion (also a plain copy, from == to) of `rows` rows of `n`. */
|
||||
inline rad_op cast_op(RadBuilder* b, int64_t rows, int64_t n, const char* from, const char* to,
|
||||
rad_buf x, rad_buf y) {
|
||||
return rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_STR("from", from), RAD_STR("to", to)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ x }, { y });
|
||||
}
|
||||
|
||||
/* The same op over several operands, bf16. */
|
||||
inline rad_op rows_op(RadBuilder* b, const char* op, int64_t rows, int64_t n,
|
||||
std::initializer_list<rad_buf> in, std::initializer_list<rad_buf> out) {
|
||||
return rw(b, RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
in, out);
|
||||
}
|
||||
|
||||
/* y = x * w (a per-channel weight of `n`) over `rows` rows, bf16. */
|
||||
inline rad_op mulw_op(RadBuilder* b, int64_t rows, int64_t n, rad_weight w, rad_buf x,
|
||||
rad_buf y) {
|
||||
return rw(b, RAD_OP(b, "mul_weight",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w)),
|
||||
{ x }, { y });
|
||||
}
|
||||
|
||||
/* y = x * w^T over `rows` rows, bf16: `gemm_nt` of an [N, K] weight, and `gemm_nt_bias` with a
|
||||
* bias vector added in the epilogue. */
|
||||
inline rad_op gemm_op(RadBuilder* b, int64_t rows, int64_t N, int64_t K, rad_weight w, rad_buf x,
|
||||
rad_buf y) {
|
||||
return rw(b, 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)),
|
||||
{ x }, { y });
|
||||
}
|
||||
inline rad_op gemm_bias_op(RadBuilder* b, int64_t rows, int64_t N, int64_t K, rad_weight w,
|
||||
rad_weight bias, rad_buf x, rad_buf y) {
|
||||
return rw(b, 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_WEIGHTS(w, bias)),
|
||||
{ x }, { y });
|
||||
}
|
||||
|
||||
/* y[i] = start + i * step over `rows` rows. */
|
||||
inline rad_op iota_op(RadBuilder* b, int64_t rows, int64_t start, int64_t step, rad_buf y) {
|
||||
return rw(b, RAD_OP(b, "iota",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("start", start),
|
||||
RAD_INT("step", step)),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, { y });
|
||||
}
|
||||
|
||||
/* ---- A weight read into the on-die cache beside a collective (libr4d `prefetch`, docs/OPS.md).
|
||||
* At decode heights a GEMM streams its weight once from memory, and a collective in front of it
|
||||
* leaves the card's memory idle for its round trip. prefetch_beside issues `op`, a `prefetch` of
|
||||
@@ -641,8 +822,14 @@ inline void prefetch_beside(RadCtx* c, rad_op op, rad_weight w, int64_t T) {
|
||||
}
|
||||
/* The `prefetch` of `w`'s first `bytes` where a library serves it; 0 otherwise. A plugin declares
|
||||
* none where the deployment turns the reads off (RadBuildCtx::weight_prefetch_off). */
|
||||
inline rad_op decl_prefetch(RadBuilder* b, rad_weight w, int64_t bytes) {
|
||||
inline rad_op decl_prefetch(RadBuilder* b, rad_weight w, int64_t bytes, int64_t blocks = 0) {
|
||||
if (!w || bytes <= 0 || !rad_op_declared(b, "prefetch")) return 0;
|
||||
/* `blocks`: the workgroups reading, where the architecture measured its own count
|
||||
* (docs/OPS.md); 0 leaves the kernel's. Stated only when asked, so a declaration without it
|
||||
* is what it was. */
|
||||
if (blocks > 0)
|
||||
return RAD_OP(b, "prefetch", RAD_PARAMS(RAD_INT("bytes", bytes), RAD_INT("blocks", blocks)),
|
||||
RAD_WEIGHTS(w));
|
||||
return RAD_OP(b, "prefetch", RAD_PARAMS(RAD_INT("bytes", bytes)), RAD_WEIGHTS(w));
|
||||
}
|
||||
|
||||
@@ -668,7 +855,7 @@ struct Geom {
|
||||
int64_t n_head_all = 0;
|
||||
int64_t n_head_kv_all = 0;
|
||||
/* This rank's first row in the checkpoint's unsharded k/v projection, in container rows (the
|
||||
* unit of a LinearFP8 span, passed as `span_lo`). Nonzero when KV heads are replicated over
|
||||
* unit of a LinearQ span, passed as `span_lo`). Nonzero when KV heads are replicated over
|
||||
* ranks (world > n_head_kv_all) or under a smaller attention world; zero on a plain split. */
|
||||
int64_t kv_off = 0;
|
||||
/* The attention world. When world neither divides nor is a multiple of the KV head count
|
||||
@@ -702,9 +889,6 @@ struct Geom {
|
||||
/* Messages below this many bytes use the exact all-reduce even with a lossy wire. Passed as
|
||||
* `all_reduce`'s `min_bytes`; 0 leaves the default to the kernel plugin. */
|
||||
int64_t wire_min_bytes = 0;
|
||||
/* RAD_ATTN_FP8_* bits: the attention products accepted in e4m3 (RadBuildCtx describes it).
|
||||
* decl_attn passes it on as `attn_paged`'s `prefill_fp8`. */
|
||||
int attn_prefill_fp8 = 0;
|
||||
float eps = 1e-6f;
|
||||
/* GemmaRMSNorm's `1 +`. Qwen3.5, Qwen3-Next and Gemma normalise with `x_hat * (1 + w)` and
|
||||
* store `w` near 0.1, so reading it as a plain gain shrinks every normed activation 5-10x. An
|
||||
@@ -735,11 +919,17 @@ struct Geom {
|
||||
* kv_store rows band on it verbatim. */
|
||||
const char* kv_dtype = "bf16";
|
||||
/* The linears are plain bf16 weights read by `gemm_nt`, in a model built from the fp8 blocks
|
||||
* (rad_fp8.h): a dense bf16 checkpoint converted without a quantising recipe. Producers in
|
||||
* front of a linear then quantise nothing, so an `ActFP8` is its bf16 plane alone. A model-wide
|
||||
* (rad_linear.h): a dense bf16 checkpoint converted without a quantising recipe. Producers in
|
||||
* front of a linear then quantise nothing, so an `ActQ` is its bf16 plane alone. A model-wide
|
||||
* setting because producers and consumers must agree; the plugin reads it off a trunk weight's
|
||||
* encoding and every linear checks its own against it. */
|
||||
bool w_bf16 = false;
|
||||
/* The linears are rotated int8 (rad_linear.h's linear_is_w8h: IQ8R, or the 128-group form) with
|
||||
* one activation scale per `w_i8_group` columns, for a plugin whose producers are declared away
|
||||
* from its probe: each then declares an int8 code pair (ActQ::declare_pair). Model-wide as
|
||||
* w_bf16 is. */
|
||||
bool w_i8h = false;
|
||||
int64_t w_i8_group = 128;
|
||||
|
||||
int64_t q_dim() const { return n_head * head_dim; }
|
||||
int64_t kv_dim() const { return n_head_kv * head_dim; }
|
||||
@@ -747,6 +937,125 @@ struct Geom {
|
||||
int64_t gqa() const { return n_head_kv ? n_head / n_head_kv : 0; }
|
||||
};
|
||||
|
||||
/* gemm_nt of a plain weight at the step height (`M` ranging 1..g.max_tok), read at g.dtype. */
|
||||
inline rad_op decl_gemm_nt(RadBuilder* b, const Geom& g, int64_t N, int64_t K, rad_weight w,
|
||||
rad_buf a, rad_buf y) {
|
||||
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)),
|
||||
{ a }, { y });
|
||||
}
|
||||
|
||||
/* An int8 activation quantiser: bf16 `a` of `rows` rows of `K` into the codes `q8` and the f32
|
||||
* scales `s8`. `op` is quant_act_i8 (one scale a row), quant_act_i8g (one a `group` columns) or
|
||||
* had_quant_act_i8g (the same after a Hadamard rotation of each group). */
|
||||
inline rad_op decl_quant_act(RadBuilder* b, const char* op, int64_t rows, int64_t K, int group,
|
||||
rad_buf a, rad_buf q8, rad_buf s8) {
|
||||
return rw(b, RAD_OP(b, op,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", K),
|
||||
RAD_INT("group", group), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ a }, { q8, s8 });
|
||||
}
|
||||
|
||||
/* gemm_nt_q of the weight planes (w, ws) against `in`, the activation operands (an int8 pair,
|
||||
* or an f16 copy); `dtype` names the operand combination (w4a8, i8a8, w4a16_asym, ...) and
|
||||
* `group` the columns a scale covers. */
|
||||
inline rad_op decl_gemm_q(RadBuilder* b, int64_t rows, int64_t N, int64_t K, int group,
|
||||
const char* dtype, rad_weight w, rad_weight ws,
|
||||
std::initializer_list<rad_buf> in, rad_buf y) {
|
||||
return rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_INT("group", group), RAD_STR("dtype", dtype)),
|
||||
RAD_WEIGHTS(w, ws)),
|
||||
in, { y });
|
||||
}
|
||||
|
||||
|
||||
/* A linear of the bf16 blocks (rad_block_mlp.h, rad_block_attn_gated.h, rad_block_gdn.h): its
|
||||
* weight, declared at what the model holds, and the `gemm_nt` dtype that reads it. A `bf16x12`
|
||||
* weight, libquant's lossless packing of a bf16 one in 12.25 bits a value (docs/TOOLS.md), is
|
||||
* declared over every plane at its codes' dtype and read at "bf16x12" (docs/OPS.md), whose rows
|
||||
* give bf16's bytes. Any other weight is declared bf16 and read at `g.dtype`, so a container with
|
||||
* no bf16x12 weight declares the graph it did before. */
|
||||
struct LinearBF16 {
|
||||
rad_weight w = 0;
|
||||
const char* dtype = nullptr; /* gemm_nt's */
|
||||
};
|
||||
|
||||
inline LinearBF16 decl_linear_bf16(RadBuilder* b, const Geom& g, const char* name,
|
||||
std::initializer_list<int64_t> shape, int shard,
|
||||
RadWeightGroup group,
|
||||
std::initializer_list<int64_t> row_parts = {}) {
|
||||
RadEncoding e{};
|
||||
const bool x12 = weight_enc(b, name, &e) && rad_enc_is(&e, "bf16x12") && e.n_planes > 0;
|
||||
LinearBF16 l;
|
||||
l.w = decl_w(b, name, x12 ? e.plane[0].dtype : (uint32_t)RAD_BF16, shape,
|
||||
RAD_ACCESS_PER_TOKEN, shard, group, 0, row_parts);
|
||||
l.dtype = x12 ? "bf16x12" : g.dtype;
|
||||
return l;
|
||||
}
|
||||
|
||||
/* ================================================================== all-reduce declarations */
|
||||
/* An in-place all-reduce of `x`, `rows` rows of `n` at `dtype`, over g.world ranks; `numel` ranges
|
||||
* n .. rows * n. The wire is the serve's (--tp-wire): exact or lossy as g.wire_exact says, and
|
||||
* g.wire_min_bytes the size below which a lossy wire is not used. The caller declares it only
|
||||
* where the graph has a collective (world > 1). */
|
||||
inline rad_op decl_all_reduce(RadBuilder* b, const Geom& g, rad_buf x, int64_t n, int64_t rows,
|
||||
const char* dtype) {
|
||||
return rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", n, rows * n),
|
||||
RAD_STR("dtype", dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ x }, { x });
|
||||
}
|
||||
|
||||
/* ... a block's residual stream at the full step height, in the geometry's dtype. */
|
||||
inline rad_op decl_all_reduce(RadBuilder* b, const Geom& g, rad_buf x) {
|
||||
return decl_all_reduce(b, g, x, g.n_embd, g.max_tok, g.dtype);
|
||||
}
|
||||
|
||||
/* The same collective for a caller that issues it beside other work: at `overlap` 1 it gets the
|
||||
* launch that holds fewer CUs while waiting on the link. */
|
||||
inline rad_op decl_all_reduce_overlap(RadBuilder* b, const Geom& g, rad_buf x, int64_t n,
|
||||
int64_t rows, const char* dtype, int overlap) {
|
||||
return rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", n, rows * n),
|
||||
RAD_STR("dtype", dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes),
|
||||
RAD_INT("overlap", overlap)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ x }, { x });
|
||||
}
|
||||
inline rad_op decl_all_reduce_overlap(RadBuilder* b, const Geom& g, rad_buf x, int overlap) {
|
||||
return decl_all_reduce_overlap(b, g, x, g.n_embd, g.max_tok, g.dtype, overlap);
|
||||
}
|
||||
|
||||
/* The collective after a tensor-parallel block of a bf16 model: no op (0) at one rank. */
|
||||
inline rad_op decl_all_reduce_tp(RadBuilder* b, const Geom& g, rad_buf x, int64_t rows) {
|
||||
if (g.world <= 1) return 0;
|
||||
return decl_all_reduce(b, g, x, g.n_embd, rows, "bf16");
|
||||
}
|
||||
|
||||
/* A collective that is always exact, with no size threshold: the sum of disjoint rows (each
|
||||
* token's row from one rank, zeros from the others), where a lossy wire would only add error. */
|
||||
inline rad_op decl_all_reduce_exact(RadBuilder* b, const Geom& g, rad_buf x, int64_t n,
|
||||
int64_t rows, const char* dtype) {
|
||||
return rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", n, rows * n),
|
||||
RAD_STR("dtype", dtype), RAD_INT("exact", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ x }, { x });
|
||||
}
|
||||
inline rad_op decl_all_reduce_exact(RadBuilder* b, const Geom& g, rad_buf x) {
|
||||
return decl_all_reduce_exact(b, g, x, g.n_embd, g.max_tok, g.dtype);
|
||||
}
|
||||
|
||||
/* The KV cache dtype: RadBuildCtx::kv_dtype (--kv-cache-dtype), or `dflt` when it is
|
||||
* RAD_DT_INVALID (not given). Every architecture in this tree passes RAD_BF16 as the default. */
|
||||
static inline uint32_t rad_kv_cache_dtype(const RadBuildCtx* c, uint32_t dflt) {
|
||||
@@ -769,7 +1078,7 @@ inline int divide_or_fail(int64_t v, int world, const char* what, int64_t* out)
|
||||
* §13), so a ragged shard is free, while padding would need a fake token id masked everywhere.
|
||||
*
|
||||
* A vocabulary world divides keeps the even share. Otherwise each rank takes ceil(total / world)
|
||||
* rounded up to a 128-row block (RAD_FP8_BLOCK), the last rank short: a block-scaled fp8 lm_head
|
||||
* rounded up to a 128-row block (RAD_SCALE_GROUP), the last rank short: a block-scaled fp8 lm_head
|
||||
* is stored in 128x128 tiles and a row span that cuts a tile is refused (rad_weight_shard_span).
|
||||
* Example: 248320 over 3 ranks gives 82816, 82816, 82688. core/engine.cpp restates this rule and
|
||||
* checks it against the declared width; keep the two in step. */
|
||||
@@ -790,6 +1099,24 @@ inline int64_t shard_begin(int64_t total, int world, int rank) {
|
||||
return beg < total ? beg : total;
|
||||
}
|
||||
|
||||
/* A rank's contiguous slice of `n` units over `parts` ranks, the remainder going to the first
|
||||
* ranks one unit each: [first, first + count). */
|
||||
struct Span {
|
||||
int64_t first = 0, count = 0;
|
||||
};
|
||||
inline Span split_span(int64_t n, int parts, int rank) {
|
||||
const int64_t base = n / parts, rem = n % parts;
|
||||
return {base * rank + std::min<int64_t>(rank, rem), base + (rank < rem ? 1 : 0)};
|
||||
}
|
||||
|
||||
/* The same split of a width, in whole 128-column scale groups (RAD_SCALE_GROUP): rank's columns
|
||||
* [*lo, *hi). */
|
||||
inline void block_slice_128(int64_t width, int world, int rank, int64_t* lo, int64_t* hi) {
|
||||
const Span s = split_span(width / 128, world, rank);
|
||||
*lo = s.first * 128;
|
||||
*hi = (s.first + s.count) * 128;
|
||||
}
|
||||
|
||||
/* A container-header integer under its GGUF (`qwen35.ssm.state_size`) or HuggingFace
|
||||
* (`linear_key_head_dim`) spelling, so one plugin serves a .rad converted from either. `found`
|
||||
* reports whether the value was read or defaulted, so a caller can refuse a silent default. */
|
||||
@@ -826,6 +1153,17 @@ inline const char* meta_text_gets(const RadModelMeta* m, const char* key, const
|
||||
char k[192];
|
||||
return rad_meta_gets(m, meta_text_key(m, key, pre, k), dflt);
|
||||
}
|
||||
/* A boolean: a JSON boolean reaches the meta as 1/0 or as true/false, depending on the
|
||||
* converter's path. */
|
||||
inline bool meta_text_getb(const RadModelMeta* m, const char* key, bool dflt,
|
||||
const char* pre = "") {
|
||||
const char* s = meta_text_gets(m, key, nullptr, pre);
|
||||
if (!s) return dflt;
|
||||
if (!std::strcmp(s, "true") || !std::strcmp(s, "True")) return true;
|
||||
if (!std::strcmp(s, "false") || !std::strcmp(s, "False") || !std::strcmp(s, "null"))
|
||||
return false;
|
||||
return std::atoll(s) != 0;
|
||||
}
|
||||
|
||||
/* ================================================================== config arrays */
|
||||
/* Calls fn(token, length) for each token of a flattened config array until fn returns false.
|
||||
@@ -834,7 +1172,9 @@ inline const char* meta_text_gets(const RadModelMeta* m, const char* key, const
|
||||
template <class F>
|
||||
inline void for_each_token(const char* s, F&& fn) {
|
||||
if (!s) return;
|
||||
auto sep = [](char ch) { return ch == ' ' || ch == ',' || ch == '[' || ch == ']' || ch == '"'; };
|
||||
auto sep = [](char ch) {
|
||||
return ch == ' ' || ch == ',' || ch == '[' || ch == ']' || ch == '"';
|
||||
};
|
||||
for (const char* p = s; *p;) {
|
||||
while (*p && sep(*p)) ++p;
|
||||
if (!*p) return;
|
||||
@@ -844,6 +1184,21 @@ inline void for_each_token(const char* s, F&& fn) {
|
||||
}
|
||||
}
|
||||
|
||||
/* A numeric config array as doubles: the numbers of the flattened value (see for_each_token), any
|
||||
* other character skipped. */
|
||||
inline std::vector<double> meta_list(const RadModelMeta* m, const char* key) {
|
||||
std::vector<double> v;
|
||||
const char* s = rad_meta_gets(m, key, nullptr);
|
||||
while (s && *s) {
|
||||
char* e = nullptr;
|
||||
const double x = std::strtod(s, &e);
|
||||
if (e == s) { ++s; continue; }
|
||||
v.push_back(x);
|
||||
s = e;
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
inline bool token_is(const char* t, size_t n, const char* word) {
|
||||
return std::strlen(word) == n && std::strncmp(t, word, n) == 0;
|
||||
}
|
||||
@@ -866,8 +1221,9 @@ inline int parse_layer_ids(const char* s, int64_t n_layer, int* out, int max) {
|
||||
|
||||
/* A `layer_types` array as one flag per entry: 1 for any name in `one`, 0 for `zero`. Any other
|
||||
* name is refused, naming `arch`. */
|
||||
inline int parse_layer_kinds(const char* arch, const char* s, std::initializer_list<const char*> one,
|
||||
const char* zero, std::vector<int>* out) {
|
||||
inline int parse_layer_kinds(const char* arch, const char* s,
|
||||
std::initializer_list<const char*> one, const char* zero,
|
||||
std::vector<int>* out) {
|
||||
out->clear();
|
||||
int rc = RAD_OK;
|
||||
for_each_token(s, [&](const char* t, size_t n) {
|
||||
@@ -921,7 +1277,7 @@ inline int check_layer_schedule(const char* arch, const char* s, int64_t n_layer
|
||||
|
||||
/* A rank's place in the remainder-first order. Head-sized work that does not divide evenly (the
|
||||
* extra delta-net head) goes first to attention-zero ranks, which pay only a fill for attention
|
||||
* (rad_block_attn_gated_fp8.h) and keep no attention cache, so the slowest rank is not also given
|
||||
* (rad_block_attn_gated_q.h) and keep no attention cache, so the slowest rank is not also given
|
||||
* the extra head. An expert's extra block is not head-sized and stays on the rotation
|
||||
* (qwen4exp_fp8.cpp). Attention-zero ranks take places 0..n-1 regardless of `parity`; attention
|
||||
* ranks follow, rotated by `parity`. With no attention-zero rank the place is
|
||||
@@ -941,7 +1297,7 @@ inline int64_t remainder_place(const Geom& g, int rank, int parity) {
|
||||
*
|
||||
* `attn_world_ok`: the plugin's attention block supports a smaller attention world
|
||||
* (Geom::attn_world): it declares the attention-zero fill and zero KV group and spans projections
|
||||
* by `attn_rank`. Only rad_block_attn_gated_fp8.h does. Otherwise a world the KV head count
|
||||
* by `attn_rank`. Only rad_block_attn_gated_q.h does. Otherwise a world the KV head count
|
||||
* neither divides nor is a multiple of is refused. */
|
||||
inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c,
|
||||
const char* dtype, uint32_t act_dtype, bool arch_splits_ff = false,
|
||||
@@ -976,16 +1332,15 @@ inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c,
|
||||
g.world = c->world_size ? c->world_size : 1;
|
||||
g.wire_exact= c->tp_wire_lossy ? 0 : 1;
|
||||
g.wire_min_bytes = c->tp_wire_min_bytes;
|
||||
g.attn_prefill_fp8 = c->attn_prefill_fp8;
|
||||
g.eps = m->rms_eps;
|
||||
g.theta = m->rope_theta;
|
||||
g.rope_scale= 1.0f; /* yarn_from reads the model's rotary scaling */
|
||||
g.dtype = dtype;
|
||||
g.act_dtype = act_dtype;
|
||||
{
|
||||
const char* sec = rad_meta_gets(m, "rope_parameters.mrope_section",
|
||||
rad_meta_gets(m, "text_config.rope_parameters.mrope_section",
|
||||
""));
|
||||
const char* sec = rad_meta_gets(
|
||||
m, "rope_parameters.mrope_section",
|
||||
rad_meta_gets(m, "text_config.rope_parameters.mrope_section", ""));
|
||||
if (sec && *sec) {
|
||||
const bool inter =
|
||||
rad_meta_geti(m, "rope_parameters.mrope_interleaved",
|
||||
@@ -1293,16 +1648,6 @@ inline rad_op decl_rotary(RadBuilder* b, const Geom& g, const char* name,
|
||||
return rad_decl_op(b, name, p.data(), (int)p.size(), weights, nw);
|
||||
}
|
||||
|
||||
/* An `attn_paged` op with the deployment's `prefill_fp8` appended (docs/OPS.md). At 0 the
|
||||
* parameters are passed unchanged, so op identities and tune keys do not change. */
|
||||
inline rad_op decl_attn(RadBuilder* b, const Geom& g, const char* name,
|
||||
const RadParam* params, int n, const rad_weight* weights, int nw) {
|
||||
if (g.attn_prefill_fp8 == 0) return rad_decl_op(b, name, params, n, weights, nw);
|
||||
std::vector<RadParam> p(params, params + n);
|
||||
p.push_back(RAD_INT("prefill_fp8", g.attn_prefill_fp8));
|
||||
return rad_decl_op(b, name, p.data(), (int)p.size(), weights, nw);
|
||||
}
|
||||
|
||||
/* Reads a model's rotary scaling into `g.rope_scale` and `g.yarn`. Every architecture calls it
|
||||
* after geom_from, for the target ("") and for a drafter with its own config ("draft."). Only the
|
||||
* free-form keys are read; RadModelMeta::rope_scale is not, since a factor without its type would
|
||||
@@ -1371,15 +1716,19 @@ inline int yarn_from(Geom& g, const RadModelMeta* meta, const char* prefix, int6
|
||||
/* `truncate` is a JSON boolean; the converter writes 1 or 0, and true/false are accepted. */
|
||||
double truncate = 1.0;
|
||||
if (const char* t = rad_meta_gets(meta, (home + "truncate").c_str(), nullptr))
|
||||
truncate = !std::strcmp(t, "true") ? 1.0 : !std::strcmp(t, "false") ? 0.0 : get("truncate", 1.0);
|
||||
const double factor = get("factor", 0.0), original = get("original_max_position_embeddings", 0.0);
|
||||
truncate = !std::strcmp(t, "true") ? 1.0
|
||||
: !std::strcmp(t, "false") ? 0.0
|
||||
: get("truncate", 1.0);
|
||||
const double factor = get("factor", 0.0);
|
||||
const double original = get("original_max_position_embeddings", 0.0);
|
||||
const double fast = get("beta_fast", 32.0), slow = get("beta_slow", 1.0);
|
||||
const double magnitude = get("attention_factor", factor > 1.0 ? 1.0 + 0.1 * std::log(factor) : 1.0);
|
||||
const double magnitude =
|
||||
get("attention_factor", factor > 1.0 ? 1.0 + 0.1 * std::log(factor) : 1.0);
|
||||
if (!std::isfinite(factor) || factor < 1.0 || !std::isfinite(original) || original < 1.0 ||
|
||||
original != std::floor(original) || (truncate != 0.0 && truncate != 1.0) ||
|
||||
!std::isfinite(fast) || !std::isfinite(slow) || slow <= 0.0 || fast < slow ||
|
||||
!std::isfinite(magnitude) || magnitude <= 0.0 || !std::isfinite(g.theta) || g.theta <= 1.0f ||
|
||||
rot < 2 || (rot & 1)) {
|
||||
!std::isfinite(magnitude) || magnitude <= 0.0 || !std::isfinite(g.theta) ||
|
||||
g.theta <= 1.0f || rot < 2 || (rot & 1)) {
|
||||
fprintf(stderr, "radiance: %s YaRN (%s) needs a finite factor >= 1, an integral "
|
||||
"original_max_position_embeddings > 0, beta_fast >= beta_slow > 0, "
|
||||
"attention_factor > 0 and truncate true or false\n", who, home.c_str());
|
||||
@@ -1439,6 +1788,46 @@ inline void batch_split(const RadBatch* b, int64_t* n_seq_dec, int64_t* n_tok_de
|
||||
}
|
||||
}
|
||||
|
||||
/* What a step's attention reads of the QSA selection (AttnGatedQ::qsa_use), which decides what
|
||||
* the indexer issues for the layer (QsaIndexer::step, docs/QSA.md "Below the bound"):
|
||||
*
|
||||
* kQsaSelect score and select, per layer: a step past the exactness bound, a streamed group,
|
||||
* and every step of a block that did not ask for the forms below;
|
||||
* kQsaUnread nothing reads the selection: the step is entirely at or below the bound and its
|
||||
* attention is the dense one, or the sparse row over the sequence's own block table
|
||||
* (one row a sequence), which is what the selection would be. The indexer stores its
|
||||
* keys and tail and issues no query, score or select;
|
||||
* kQsaOnce the attention reads a selection (the sparse row a query) on a step entirely at or
|
||||
* below the bound: every complete block is taken whatever it scores, so the
|
||||
* selection depends on the positions and the block table alone and is the same
|
||||
* bytes at every layer. The first full-attention layer of the pass issues it;
|
||||
* no later layer issues a query, a score or a select. */
|
||||
enum QsaUse : int { kQsaSelect = 0, kQsaUnread = 1, kQsaOnce = 2 };
|
||||
|
||||
/* Ops of a chain that is independent of a block's own, for the block to issue behind its ordered
|
||||
* launches. A recorded pass lets a launch start beside the last ordered one when it touches
|
||||
* nothing in flight (Ctx::haz_mark). A dependent chain issued in one piece is therefore a row of
|
||||
* ordered launches, each paid in turn; issued one op behind each of the block's own ordered
|
||||
* launches, every op of it is unordered behind the block's launch in front of it, and still
|
||||
* behind its own predecessor, which that launch already waited for. The block calls `at(k)` for
|
||||
* k = 0, 1, 2, ... behind its ordered launches in turn, and the owner issues what is left once
|
||||
* the block returns. The chain must read nothing the block writes and write nothing the block
|
||||
* touches, and its buffers must be excluded from sharing (rad_buf_concurrent): they are in use at
|
||||
* launches the linear order puts after their last declared use. */
|
||||
struct SideOps {
|
||||
void (*fn)(void* u, int stage) = nullptr;
|
||||
void* u = nullptr;
|
||||
void at(int stage) const { if (fn) fn(u, stage); }
|
||||
};
|
||||
|
||||
/* RADIANCE_DEBUG_QSA_EAGER: every step is kQsaSelect, each layer issuing its own selection. An
|
||||
* instrument for comparing that sequence with the forms above (the text must not move); read
|
||||
* once. */
|
||||
inline bool qsa_eager() {
|
||||
static const bool on = std::getenv("RADIANCE_DEBUG_QSA_EAGER") != nullptr;
|
||||
return on;
|
||||
}
|
||||
|
||||
/* The step batch's entry for one declared KV group (built once per step by the core, spec §8). */
|
||||
inline const RadKVGroupBatch* kv_batch(const RadBatch* b, rad_kvgroup group) {
|
||||
for (int i = 0; i < b->n_kv_groups; ++i)
|
||||
@@ -1484,11 +1873,19 @@ inline const char* drafter_layer_prefix(const RadModelMeta* meta) {
|
||||
return "draft.transformer_layer_config.";
|
||||
return "draft.";
|
||||
}
|
||||
inline int drafter_geom(Geom& dg, const Geom& target, const RadModelMeta* meta, const char* what) {
|
||||
/* `kv_repl_ok`: the drafter block reads its k and v at Geom::kv_off (rad_block_dflash2.h does), so
|
||||
* fewer KV heads than ranks are replicated as geom_from replicates the target's: world a multiple
|
||||
* of the head count, one KV head a rank, `kv_off` its first row in the unsharded k/v projection.
|
||||
* Otherwise such a world is refused, as before. */
|
||||
inline int drafter_geom(Geom& dg, const Geom& target, const RadModelMeta* meta, const char* what,
|
||||
bool kv_repl_ok = false) {
|
||||
dg = target;
|
||||
const char* pre = drafter_layer_prefix(meta);
|
||||
char key[160];
|
||||
auto k = [&](const char* name) { std::snprintf(key, sizeof key, "%s%s", pre, name); return key; };
|
||||
auto k = [&](const char* name) {
|
||||
std::snprintf(key, sizeof key, "%s%s", pre, name);
|
||||
return key;
|
||||
};
|
||||
dg.n_layer = rad_meta_geti(meta, k("num_hidden_layers"), 0);
|
||||
dg.head_dim = rad_meta_geti(meta, k("head_dim"), 0);
|
||||
dg.n_head_all = rad_meta_geti(meta, k("num_attention_heads"), 0);
|
||||
@@ -1508,8 +1905,17 @@ inline int drafter_geom(Geom& dg, const Geom& target, const RadModelMeta* meta,
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RAD_ARCH_TRY(yarn_from(dg, meta, pre, dg.head_dim));
|
||||
RAD_ARCH_TRY(divide_or_fail(dg.n_head_all, dg.world, "draft num_attention_heads", &dg.n_head));
|
||||
RAD_ARCH_TRY(divide_or_fail(dg.n_head_kv_all, dg.world, "draft num_key_value_heads", &dg.n_head_kv));
|
||||
RAD_ARCH_TRY(divide_or_fail(dg.n_head_all, dg.world, "draft num_attention_heads",
|
||||
&dg.n_head));
|
||||
/* The target's kv_off is the target's; the drafter's is set here or zero. */
|
||||
dg.kv_off = 0;
|
||||
if (kv_repl_ok && dg.world > dg.n_head_kv_all && dg.world % dg.n_head_kv_all == 0) {
|
||||
dg.n_head_kv = 1; /* world / n_head_kv_all ranks share each KV head */
|
||||
dg.kv_off = (dg.rank / (dg.world / dg.n_head_kv_all)) * dg.head_dim;
|
||||
} else {
|
||||
RAD_ARCH_TRY(divide_or_fail(dg.n_head_kv_all, dg.world, "draft num_key_value_heads",
|
||||
&dg.n_head_kv));
|
||||
}
|
||||
RAD_ARCH_TRY(divide_or_fail(dg.n_ff_all, dg.world, "draft intermediate_size", &dg.n_ff));
|
||||
const long long dvocab = rad_meta_geti(meta, k("vocab_size"), dg.n_vocab_all);
|
||||
if (dvocab != dg.n_vocab_all) {
|
||||
@@ -1594,6 +2000,11 @@ inline int drafter_kv_group(RadBuilder* b, Names& nm, const RadBuildCtx* ctx, Ge
|
||||
#define RAD_ARCH_SERVES_IMPORTS(V) \
|
||||
extern "C" int rad_arch_serves_imports(void) { return V; }
|
||||
|
||||
/* RAD_ARCH_MULTI_INSTANCE() states that the plugin keeps all per-instance state by slot, so several
|
||||
* engines in one process may run it at once (rad_builder.h, rad_arch_multi_instance). */
|
||||
#define RAD_ARCH_MULTI_INSTANCE() \
|
||||
extern "C" int rad_arch_multi_instance(void) { return 1; }
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
|
||||
@@ -139,7 +139,7 @@ inline int AttnBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
|
||||
/* 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, decl_attn(b, g, "attn_paged",
|
||||
op_attn = rw(b, rad_decl_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),
|
||||
@@ -158,13 +158,7 @@ inline int AttnBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
|
||||
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_ar = decl_all_reduce(b, g, 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)),
|
||||
|
||||
@@ -26,6 +26,7 @@
|
||||
#define RAD_BLOCK_ATTN_GATED_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
#include "rad_norm_bf16.h"
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
@@ -69,15 +70,28 @@ struct AttnGatedBF16 {
|
||||
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;
|
||||
/* The fold (rad_norm_bf16.h): the norm may take the previous block's delta and all-reduce,
|
||||
* and this block may leave its own to the next block's norm (`ar_out`, NormBF16::takes_ar). */
|
||||
NormBF16 nq{};
|
||||
bool ar_out = false;
|
||||
/* Set by the architecture after declare: a `prefetch` of the next GEMM's leading weight bytes
|
||||
* (decl_prefetch, rad_arch.h), issued after o and before this block's own all-reduce where it
|
||||
* issues one, so it is beside the reduction whether this block or the next norm runs it
|
||||
* (prefetch_beside). 0 where none is declared. */
|
||||
rad_op op_pf = 0;
|
||||
rad_weight pf_w = 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);
|
||||
int64_t rotary_dim, const Wire& wire, const Src& src, bool fold = false, bool add_out = true,
|
||||
bool ar_in = false, bool ar_out_ = false);
|
||||
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) {
|
||||
const Src& src, bool fold, bool add_out, bool ar_in,
|
||||
bool ar_out_) {
|
||||
ar_out = ar_out_;
|
||||
g = geom; w = wire; layer = l; kv = group; n_rot = rotary_dim;
|
||||
|
||||
const int64_t q_dim = g.q_dim();
|
||||
@@ -93,7 +107,7 @@ inline int AttnGatedBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, in
|
||||
/* 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. */
|
||||
* passed in rad_block_attn_gated_q.h. */
|
||||
if (g.world > g.n_head_kv_all) {
|
||||
fprintf(stderr, "radiance: %s declares no KV row span and cannot serve world_size = %d "
|
||||
"with n_head_kv = %lld; the KV-head replication in geom_from needs the "
|
||||
@@ -118,41 +132,40 @@ inline int AttnGatedBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, in
|
||||
|
||||
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));
|
||||
const LinearBF16 qg = decl_linear_bf16(b, g, nm.f("blk.%d.attn_qg.weight", l),
|
||||
{qg_dim, g.n_embd}, RAD_SHARD_ROW, grp_layer(l));
|
||||
const LinearBF16 kp = decl_linear_bf16(b, g, nm.f("blk.%d.attn_k.weight", l),
|
||||
{kv_dim, g.n_embd}, RAD_SHARD_ROW, grp_layer(l));
|
||||
const LinearBF16 vp = decl_linear_bf16(b, g, nm.f("blk.%d.attn_v.weight", l),
|
||||
{kv_dim, g.n_embd}, RAD_SHARD_ROW, grp_layer(l));
|
||||
w_qg = qg.w; w_k = kp.w; w_v = vp.w;
|
||||
/* 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));
|
||||
const LinearBF16 out = decl_linear_bf16(b, g, nm.f("blk.%d.attn_output.weight", l),
|
||||
{g.n_embd, q_dim}, RAD_SHARD_COL, grp_layer(l));
|
||||
w_o = out.w;
|
||||
|
||||
/* ---- 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});
|
||||
RAD_ARCH_TRY(nq.declare(b, g, w_norm, w.x, w.h, fold, ar_in));
|
||||
op_norm = nq.op_norm;
|
||||
|
||||
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_INT("K", g.n_embd), RAD_STR("dtype", qg.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_INT("K", g.n_embd), RAD_STR("dtype", kp.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_INT("K", g.n_embd), RAD_STR("dtype", vp.dtype)),
|
||||
RAD_WEIGHTS(w_v)),
|
||||
{w.h}, {w.v});
|
||||
|
||||
@@ -195,7 +208,7 @@ inline int AttnGatedBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, in
|
||||
*
|
||||
* 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, decl_attn(b, g, "attn_paged",
|
||||
op_attn = rw(b, rad_decl_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),
|
||||
@@ -234,7 +247,7 @@ inline int AttnGatedBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, in
|
||||
|
||||
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_INT("K", q_dim), RAD_STR("dtype", out.dtype)),
|
||||
RAD_WEIGHTS(w_o)),
|
||||
{w.attn}, {w.h});
|
||||
|
||||
@@ -243,19 +256,14 @@ inline int AttnGatedBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, in
|
||||
* 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_ar = decl_all_reduce(b, g, 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});
|
||||
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}, {w.x});
|
||||
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -270,7 +278,7 @@ inline void AttnGatedBF16::step(RadCtx* c, const RadBatch* batch) const {
|
||||
|
||||
const int64_t T = batch->n_tok;
|
||||
|
||||
RAD_ISSUE(c, op_norm, brows(w.x, T), RAD_W(w_norm), brows(w.h, T));
|
||||
nq.step(c, 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));
|
||||
@@ -303,8 +311,11 @@ inline void AttnGatedBF16::step(RadCtx* c, const RadBatch* batch) const {
|
||||
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));
|
||||
/* Decode steps only: a prompt's rows never take the reads (rad_arch.h, kPrefetchRows). */
|
||||
prefetch_beside(c, op_pf, pf_w, batch->phase == RAD_PHASE_DECODE ? T : INT64_MAX);
|
||||
if (op_ar && !(ar_out && ar_wire_is_exact(g, T)))
|
||||
RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
|
||||
if (op_add) RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h, T), brows(w.x, T));
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
|
||||
@@ -1,43 +1,35 @@
|
||||
/* rad_block_attn_gated_fp8.h -- gated GQA attention with block-scaled FP8 projections.
|
||||
/* rad_block_attn_gated_q.h -- gated GQA attention over LinearQ 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,
|
||||
* - q|gate, k, v and o are LinearQ: 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.
|
||||
* the attention family's cache rows. 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.
|
||||
* a multiple of 128; LinearQ checks this.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_ATTN_GATED_FP8_H
|
||||
#define RAD_BLOCK_ATTN_GATED_FP8_H
|
||||
#ifndef RAD_BLOCK_ATTN_GATED_Q_H
|
||||
#define RAD_BLOCK_ATTN_GATED_Q_H
|
||||
|
||||
#include "rad_fp8.h"
|
||||
#include "rad_linear.h"
|
||||
|
||||
#include <cstring>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
/* Whether the streamed store has a row for this cache layout: libr4d's are E4M3 and bf16 only. A
|
||||
* packed cache (fp8_v4, k6_v4) must not declare it, since a weightless op with no row is a hole
|
||||
* that refuses startup even with --kv-resident off; kvstream_configure then names the layout. */
|
||||
inline bool kv_store_streamed_dtype(const char* kv_dtype) {
|
||||
return kv_dtype && (std::strcmp(kv_dtype, "fp8_e4m3") == 0 ||
|
||||
std::strcmp(kv_dtype, "bf16") == 0);
|
||||
}
|
||||
|
||||
struct AttnGatedFP8 {
|
||||
struct AttnGatedQ {
|
||||
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 */
|
||||
ActQ 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] */
|
||||
@@ -45,7 +37,7 @@ struct AttnGatedFP8 {
|
||||
/* [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 */
|
||||
ActQ 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. */
|
||||
@@ -87,6 +79,21 @@ struct AttnGatedFP8 {
|
||||
/* `sel`'s row pitch is `topk + 1`; the extra slot is the partial page
|
||||
* (r4d_qsa_select_bf16.hip). */
|
||||
int64_t qsa_topk = 0;
|
||||
/* The architecture's word that a sequence with one row in the step has that row at its
|
||||
* context's last position (`seqused - 1`: a plain decode row, a serial head's round), so at or
|
||||
* below `qsa_exact_to` such a row's selection is the head of the sequence's block table and its
|
||||
* `seqused` the sequence's (qsa_select: every complete block in block order, then the partial
|
||||
* page, and `pos + 1`). The sparse row is then issued over the table and the indexer selects
|
||||
* nothing (qsa_use). Off: such a step keeps the selection. */
|
||||
bool qsa_table_rows = false;
|
||||
/* The architecture's pass key carries whether this group's exact host bound
|
||||
* (RadBatch::kv_used_max_h, the furthest context any row of the step can read) is within
|
||||
* `qsa_exact_to`, so that bound may say whether the step needs scores (qsa_within) in place of
|
||||
* the rounded `max_ctx_len + max_q_len`, which a 4-row step leaves at 1025 tokens. It never
|
||||
* moves the choice between the dense and the sparse kernel, which stays the rounded bound's:
|
||||
* the two agree on the keys, not on the last bit of the sum. Off: the rounded bound, which the
|
||||
* core's key holds. */
|
||||
bool qsa_exact_host = false;
|
||||
/* 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
|
||||
@@ -114,8 +121,20 @@ struct AttnGatedFP8 {
|
||||
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{};
|
||||
LinearQ qg{}, kp{}, vp{}, o{};
|
||||
/* Set by the architecture after declare: a `prefetch` of the out projection's leading bytes
|
||||
* (decl_prefetch, rad_arch.h), issued behind the q, k and v projections on decode steps
|
||||
* (prefetch_beside). 0 where none is declared. */
|
||||
rad_op op_pf_o = 0;
|
||||
/* The same read as a second op for steps of at least pf_o_v_rows rows, where the
|
||||
* architecture measured another workgroup count for them (decl_prefetch's `blocks`); 0 where
|
||||
* every step takes op_pf_o. */
|
||||
rad_op op_pf_o_v = 0;
|
||||
int64_t pf_o_v_rows = 0;
|
||||
/* The most rows of a decode step whose k and v projections are issued in front of the q|gate
|
||||
* projection (step()); 0, the default, keeps the declared order on every step. */
|
||||
int64_t kv_first_rows = 0;
|
||||
NormQuant 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 */
|
||||
@@ -125,7 +144,12 @@ struct AttnGatedFP8 {
|
||||
int64_t fused_rows = 0; /* widest T the fused ops take */
|
||||
rad_op op_q_norm = 0, op_k_norm = 0, op_rope_q = 0, op_rope_k = 0;
|
||||
rad_op op_attn = 0, op_kv_store = 0, op_gq = 0;
|
||||
rad_op op_attn_gq = 0; /* attn_paged + gate_quant_fp8 */
|
||||
rad_op op_attn_gq = 0; /* attn_paged + gate_quant_fp8 or gate_had_quant_i8g */
|
||||
/* Tree verification (rad_drafter_tree): `attn_paged_tree` over a step's decode rows, which
|
||||
* honours RadBatch::spec_parent. Declared only when `tree` is set before declare; 0 where no
|
||||
* library serves it, which the architecture reads as "no trees". */
|
||||
bool tree = false;
|
||||
rad_op op_attn_tree = 0;
|
||||
/* kv_store_streamed: the host mirror always, the ring slot when `res` says the block is resident
|
||||
* (docs/OPS.md). Zero when no row serves it; a streamed group then fails the step. */
|
||||
rad_op op_kv_stream = 0;
|
||||
@@ -138,7 +162,7 @@ struct AttnGatedFP8 {
|
||||
* quantiser (no op with bf16 linears). */
|
||||
rad_op op_sig = 0, op_mul = 0;
|
||||
rad_buf gate = 0;
|
||||
QuantFP8 q_gate{};
|
||||
QuantAct 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.
|
||||
@@ -146,13 +170,13 @@ struct AttnGatedFP8 {
|
||||
* 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
|
||||
/* Which wires that consumer takes (ArOut, rad_linear.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. */
|
||||
* next block will not add, so this one issues the trailing add. See rad_linear.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,
|
||||
@@ -171,9 +195,13 @@ struct AttnGatedFP8 {
|
||||
|
||||
/* 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). */
|
||||
/* `own_ar` false: the caller issues the all-reduce itself (GdnQ::step says when). */
|
||||
/* `side`: an independent chain's ops, issued behind this block's ordered launches (SideOps,
|
||||
* rad_arch.h): one behind the prologue and the store, one behind the attention, one behind
|
||||
* the gate where the gate is a launch of its own. Null, and on the paths that return early,
|
||||
* nothing is asked of it. */
|
||||
void step(RadCtx* c, const RadBatch* batch, bool own_ar = true,
|
||||
ArPieces* pieces = nullptr) const;
|
||||
ArPieces* pieces = nullptr, const SideOps* side = 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,
|
||||
@@ -189,6 +217,41 @@ struct AttnGatedFP8 {
|
||||
* components agree, so plane 0 of an M-RoPE batch's positions is each token's position) and
|
||||
* the gate quantised by gate_quant_fp8. A streamed group never takes it: the pieces path's
|
||||
* plain store never writes the host mirror. */
|
||||
/* The rounded host bound of the furthest context a row of the step reads; by it a step of
|
||||
* several rows a sequence takes the dense or the sparse kernel (step(), `sparse`). */
|
||||
int64_t qsa_reach(const RadBatch* batch) const {
|
||||
return (int64_t)batch->max_ctx_len + batch->max_q_len;
|
||||
}
|
||||
/* Whether every row of the step is at or below the exactness bound, by the tightest host
|
||||
* ceiling there is: the group's exact one where the pass key holds its side of the bound
|
||||
* (qsa_exact_host), else the rounded one. Every row's position + 1 is at most either. */
|
||||
bool qsa_within(const RadBatch* batch, const RadKVGroupBatch* kvb) const {
|
||||
if (qsa_exact_to <= 0) return false;
|
||||
int64_t reach = qsa_reach(batch);
|
||||
if (qsa_exact_host && kvb && batch->kv && batch->kv_used_max_h) {
|
||||
const int64_t tight = batch->kv_used_max_h[kvb - batch->kv];
|
||||
if (tight > 0 && tight < reach) reach = tight;
|
||||
}
|
||||
return reach <= qsa_exact_to;
|
||||
}
|
||||
/* What this step's attention reads of the selection (QsaUse, rad_arch.h); the architecture
|
||||
* hands it to the indexer, which runs first, and step() takes its path by the same call. */
|
||||
int qsa_use(const RadBatch* batch) const {
|
||||
if (!qsa_sel || !qsa_sequ || op_fill || qsa_eager()) return kQsaSelect;
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
/* A streamed group may be ring-bound, where every pass is sparse and the resolve rewrites
|
||||
* the selection; it keeps the selection at every context. */
|
||||
if (!kvb || kvb->stream || !kvb->block_table || !kvb->seqused) return kQsaSelect;
|
||||
if (!qsa_within(batch, kvb)) return kQsaSelect;
|
||||
/* One row a sequence is the sparse row at every context: over the table where the
|
||||
* architecture vouches for it, else over a selection. */
|
||||
if (batch->n_tok == batch->n_seq)
|
||||
return (qsa_table_rows && batch->max_q_len == 1) ? kQsaUnread : kQsaOnce;
|
||||
/* Several rows a sequence: the dense attention, which reads the table, where the rounded
|
||||
* bound is within the budget too, else the sparse row a query over a selection. */
|
||||
return qsa_reach(batch) <= qsa_exact_to ? kQsaUnread : kQsaOnce;
|
||||
}
|
||||
|
||||
bool takes_pieces(const RadBatch* batch, const ArPieces* pieces) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
@@ -200,7 +263,7 @@ struct AttnGatedFP8 {
|
||||
}
|
||||
};
|
||||
|
||||
inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
inline int AttnGatedQ::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_) {
|
||||
@@ -238,7 +301,7 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
}
|
||||
|
||||
/* `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
|
||||
* (rad_linear.h's NormQuant: 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.
|
||||
*
|
||||
@@ -260,7 +323,7 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
w_k_norm = decl_w(b, nm.f("blk.%d.attn_k_norm.weight", l), RAD_F32, {g.head_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
|
||||
/* One norm+quantise op feeds all three input projections (rad_fp8.h: NormQuantFP8). */
|
||||
/* One norm+quantise op feeds all three input projections (rad_linear.h: NormQuant). */
|
||||
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));
|
||||
@@ -334,7 +397,7 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
|
||||
/* Declared before kv_store, which reads back the resolved `block_size`
|
||||
* (rad_block_attn_gated.h). */
|
||||
op_attn = decl_attn(b, g, "attn_paged",
|
||||
op_attn = rad_decl_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),
|
||||
@@ -358,6 +421,26 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
rad_op_writes(b, op_attn, &w.attn.x, 1);
|
||||
}
|
||||
|
||||
/* The tree form over the decode rows: a verify block of 1 + max_spec rows a sequence. Dense
|
||||
* attention only; a layer with a QSA selection keeps the chain. */
|
||||
if (tree && op_attn && !(qsa_sel && qsa_sequ) && rad_op_declared(b, "attn_paged_tree")) {
|
||||
const int64_t thi = std::min<int64_t>(g.max_tok, std::max<int64_t>(1, g.max_spec + 1));
|
||||
op_attn_tree = rad_decl_op(b, "attn_paged_tree",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, thi), 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),
|
||||
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);
|
||||
if (op_attn_tree) {
|
||||
rad_op_reads(b, op_attn_tree, &w.q, 1);
|
||||
rad_op_writes(b, op_attn_tree, &w.attn.x, 1);
|
||||
}
|
||||
}
|
||||
|
||||
/* The resolve belongs here rather than in the indexer: it must follow this layer's store,
|
||||
* since a block copied in from the mirror has to carry this step's tokens. Its band is the
|
||||
* step's widest launch and its row `qsa_topk + 1` wide, as the attention declares. */
|
||||
@@ -374,8 +457,8 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
|
||||
/* The streamed store: kv_store's operands and parameters plus the residency map and the layer's
|
||||
* mirror row, which the batch carries (store_cache). `block_size` does not bind the group;
|
||||
* `attn_paged` already has. Only for a layout with a row (kv_store_streamed_dtype). */
|
||||
if (kv_store_streamed_dtype(g.kv_dtype) && rad_op_declared(b, "kv_store_streamed"))
|
||||
* `attn_paged` already has. */
|
||||
if (rad_op_declared(b, "kv_store_streamed"))
|
||||
op_kv_stream = rw(b, RAD_OP(b, "kv_store_streamed",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
|
||||
RAD_INT("head_dim", g.head_dim),
|
||||
@@ -388,7 +471,7 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
/* 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. */
|
||||
* Resolves for either cache. */
|
||||
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),
|
||||
@@ -402,9 +485,8 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
{w.qg, w.k, w.cos_sin, w.v}, {w.q, w.k});
|
||||
|
||||
/* The fold for a streamed group: also writes the mirror and consults the residency map, whose
|
||||
* operands are added at issue. Gated on the same layouts. */
|
||||
if (op_fused && kv_store_streamed_dtype(g.kv_dtype) &&
|
||||
rad_op_declared(b, "qk_norm_rope_gate_kv_store_streamed"))
|
||||
* operands are added at issue. */
|
||||
if (op_fused && rad_op_declared(b, "qk_norm_rope_gate_kv_store_streamed"))
|
||||
op_fused_stream = rw(b, RAD_OP(b, "qk_norm_rope_gate_kv_store_streamed",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, fused_rows),
|
||||
RAD_INT("head_dim", g.head_dim), RAD_INT("n_head", g.n_head),
|
||||
@@ -424,7 +506,7 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
*
|
||||
* 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
|
||||
* the out projection is fed int8 (ActQ::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.
|
||||
@@ -450,14 +532,16 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
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",
|
||||
/* Rotated int8 codes (ActQ::q8_rot): gate_had_quant_i8g, had_quant_act_i8g's codes. */
|
||||
const char* gq = w.attn.q8_rot ? "gate_had_quant_i8g" : "gate_quant_fp8";
|
||||
if (rad_op_declared(b, gq))
|
||||
op_gq = rw(b, RAD_OP(b, gq,
|
||||
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_INT("n", g.head_dim), RAD_INT("group", w.attn.cg()),
|
||||
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) {
|
||||
if (!op_gq && g.head_dim % RAD_SCALE_GROUP == 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));
|
||||
@@ -469,10 +553,12 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
* 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",
|
||||
* has no merge. Rotated int8 codes (ActQ::q8_rot) take attn_paged_gate_had_quant, the merge
|
||||
* with gate_had_quant_i8g's quantiser. */
|
||||
const char* attn_gq = w.attn.q8_rot ? "attn_paged_gate_had_quant" : "attn_paged_gate_quant";
|
||||
if (op_attn && qsa_sel && qsa_sequ && !g.w_bf16 && w.attn.cg() == RAD_SCALE_GROUP &&
|
||||
rad_op_declared(b, attn_gq)) {
|
||||
op_attn_gq = RAD_OP(b, attn_gq,
|
||||
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),
|
||||
@@ -481,7 +567,7 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
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_INT("group", RAD_SCALE_GROUP),
|
||||
RAD_STR("act", "sigmoid")),
|
||||
RAD_NOWEIGHTS);
|
||||
if (op_attn_gq) {
|
||||
@@ -492,34 +578,28 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
}
|
||||
}
|
||||
|
||||
/* qwen4exp_lora: self_attn.o_proj is a LoRA module kind. Over a rotated int8 container
|
||||
* it runs as a plain bf16 GEMM over the kernel-relaid weight view (LinearQ::plain_bf16_view)
|
||||
* only when a runtime adapter targets this source. With none it keeps gemm_nt_q i8a8h: the
|
||||
* view's plain gemm_nt has no layout in the default libraries, so declaring it for every
|
||||
* container stops startup (#587). Every other encoding, and the drafter's same-leaf siblings,
|
||||
* declare exactly what the tree declares. */
|
||||
o.plain_bf16_view = src.o && rad_lora_source_targeted(b, src.o);
|
||||
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) {
|
||||
inline int AttnGatedQ::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});
|
||||
op_ar = decl_all_reduce(b, g, 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});
|
||||
op_ar_ov = decl_all_reduce_overlap(b, g, w.h.x, ar_overlap);
|
||||
|
||||
/* Only when the next block's norm will not add (rad_fp8.h: NormQuantFP8). */
|
||||
/* Only when the next block's norm will not add (rad_linear.h: NormQuant). */
|
||||
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),
|
||||
@@ -530,12 +610,12 @@ inline int AttnGatedFP8::declare_out(RadBuilder* b, bool add_out) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
inline void AttnGatedFP8::store_stage_identity(RadCtx* c, const int32_t* slot, int64_t T) const {
|
||||
inline void AttnGatedQ::store_stage_identity(RadCtx* c, const int32_t* slot, int64_t T) const {
|
||||
RAD_ISSUE_N(c, op_kv_store, T, brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T),
|
||||
kv_cache(kv, layer));
|
||||
}
|
||||
|
||||
inline void AttnGatedFP8::store_cache(RadCtx* c, const RadKVGroupBatch* kvb,
|
||||
inline void AttnGatedQ::store_cache(RadCtx* c, const RadKVGroupBatch* kvb,
|
||||
const int32_t* slot, int64_t T) const {
|
||||
if (!kvb || !kvb->stream) {
|
||||
RAD_ISSUE(c, op_kv_store,
|
||||
@@ -558,7 +638,7 @@ inline void AttnGatedFP8::store_cache(RadCtx* c, const RadKVGroupBatch* kvb,
|
||||
if (staged) store_stage_identity(c, slot, T);
|
||||
}
|
||||
|
||||
inline void AttnGatedFP8::store_kv(RadCtx* c, const RadBatch* batch) const {
|
||||
inline void AttnGatedQ::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 */
|
||||
@@ -571,8 +651,8 @@ inline void AttnGatedFP8::store_kv(RadCtx* c, const RadBatch* batch) const {
|
||||
store_cache(c, kvb, slot, T);
|
||||
}
|
||||
|
||||
inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
ArPieces* pieces) const {
|
||||
inline void AttnGatedQ::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
ArPieces* pieces, const SideOps* side) 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;
|
||||
@@ -617,7 +697,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
RAD_ISSUE_N(c, op_gq, n * g.n_head,
|
||||
bcol_at(w.qg, r0, qgw, hd, hd, n), brow_slice(w.attn.x, r0, n, qw),
|
||||
brow_slice(w.attn.cq(), r0, n, qw),
|
||||
brow_slice(w.attn.cs(), r0, n, fp8_blocks(qw)),
|
||||
brow_slice(w.attn.cs(), r0, n, qw / w.attn.cg()),
|
||||
brow_slice(w.attn.x, r0, n, qw));
|
||||
o.step(c, w.attn, w.h.x, T, r0, n);
|
||||
if (p == 0) pieces->hand(r0, n);
|
||||
@@ -634,9 +714,23 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
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);
|
||||
/* The three projections read the same input and none reads another's output, so a recorded
|
||||
* pass starts them together (Ctx::haz_mark) whatever their order; the order decides which
|
||||
* the card launches first. On a decode step of up to `kv_first_rows` rows the two small ones
|
||||
* go first: behind the wide q|gate projection their launches wait until its blocks are all
|
||||
* on the card, and the prologue then waits for them. Qwen3.8-Flash-Next at tp 2, chain 3
|
||||
* with coupling (twelve trunk layers and the head's): -0.66% a step. */
|
||||
if (T <= kv_first_rows && batch->phase == RAD_PHASE_DECODE) {
|
||||
kp.step(c, w.h, w.k, T);
|
||||
vp.step(c, w.h, w.v, T);
|
||||
qg.step(c, w.h, w.qg, T);
|
||||
} else {
|
||||
qg.step(c, w.h, w.qg, T);
|
||||
kp.step(c, w.h, w.k, T);
|
||||
vp.step(c, w.h, w.v, T);
|
||||
}
|
||||
/* The out projection's weight, read beside the prologue and the attention (op_pf_o). */
|
||||
prefetch_beside(c, op_pf_o_v && T >= pf_o_v_rows ? op_pf_o_v : op_pf_o, o.w, 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
|
||||
@@ -681,6 +775,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
}
|
||||
|
||||
if (!fused_kv && !folded_stream) store_cache(c, kvb, slot, T);
|
||||
if (side) side->at(0);
|
||||
|
||||
/* 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
|
||||
@@ -693,7 +788,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
* 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 int64_t reach = qsa_reach(batch);
|
||||
/* A pass on a streamed group's ring (a ring smaller than the id space, and not staged) must
|
||||
* take the sparse path: on the ring a block id is not a pool address, so the dense path would
|
||||
* read ring slots as pages. `T == n_seq` alone misses a verify pass, whose T is
|
||||
@@ -707,6 +802,19 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
const bool sparse = qsa_sel && qsa_sequ &&
|
||||
(ring_bound || T == batch->n_seq || qsa_exact_to <= 0 ||
|
||||
reach > qsa_exact_to);
|
||||
/* At or below the bound a step of one row a sequence has no selection (qsa_use): the sparse
|
||||
* row reads the sequence's own block table and length, which is what qsa_select would have
|
||||
* written for it (the field says why), so the launch, its kernel and its bytes are the sparse
|
||||
* row's. */
|
||||
const bool by_table = sparse && T == batch->n_seq && qsa_use(batch) == kQsaUnread;
|
||||
const int64_t tpitch = kvb ? kvb->block_table_pitch : 0;
|
||||
auto sel_rows = [&](int64_t off, int64_t rows) {
|
||||
return by_table ? praw2(table + off * tpitch, RAD_I32, rows, tpitch)
|
||||
: brow_slice(qsa_sel, off, rows, qsa_topk + 1);
|
||||
};
|
||||
auto sequ_rows = [&](int64_t off, int64_t rows) {
|
||||
return by_table ? praw(used + off, RAD_I32, rows) : brow_slice(qsa_sequ, off, rows, 1);
|
||||
};
|
||||
const bool gated = sparse && op_attn_gq;
|
||||
/* A streamed group's selection, per launch: make the rows' blocks resident and rewrite `sel`
|
||||
* as ring slots, after this layer's store (a block copied in from the mirror must carry this
|
||||
@@ -714,6 +822,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
* and never resolves, so a prefill cannot overflow the ring. */
|
||||
const KVStreamLayer res_l = op_resolve ? kv_stream_layer(c, kv, layer, kvb) : KVStreamLayer{};
|
||||
auto resolve_sel = [&](int64_t off, int64_t rows) {
|
||||
if (by_table) return; /* never a streamed group (qsa_use) */
|
||||
if (kv_stage_layer(c, kv, kvb, layer)) return;
|
||||
if (!res_l.host || res_l.blocks <= 0 || res_l.slots <= 0 || rows <= 0) return;
|
||||
kv_resolve_issue(c, op_resolve, res_l, brow_slice(qsa_sel, off, rows, qsa_topk + 1),
|
||||
@@ -735,13 +844,12 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
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),
|
||||
sel_rows(off, rows), sequ_rows(off, rows),
|
||||
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)));
|
||||
brow_slice(w.attn.cs(), off, rows, qw / w.attn.cg()));
|
||||
}
|
||||
o.step(c, w.attn, w.h.x, T, p0, pn);
|
||||
if (p0 + pn < T) pieces->hand(p0, pn);
|
||||
@@ -759,13 +867,12 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
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),
|
||||
sel_rows(off, rows), sequ_rows(off, rows),
|
||||
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)));
|
||||
brow_slice(w.attn.cs(), off, rows, qw / w.attn.cg()));
|
||||
}
|
||||
} else if (sparse) {
|
||||
const int64_t chunk = qsa_rows();
|
||||
@@ -776,8 +883,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
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),
|
||||
sel_rows(off, rows), sequ_rows(off, rows),
|
||||
RAD_NONE, RAD_NONE, RAD_NONE,
|
||||
brow_slice(w.attn.x, off, rows, qw));
|
||||
}
|
||||
@@ -809,9 +915,28 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
const int64_t pitch = kvb ? kvb->block_table_pitch : 0;
|
||||
const int32_t qp = batch->max_q_len_prefill > 0 ? batch->max_q_len_prefill
|
||||
: batch->max_q_len;
|
||||
if (batch->phase == RAD_PHASE_MIXED && D > 0 && D < batch->n_seq &&
|
||||
/* A tree step (rad_drafter_tree): the decode rows' verify blocks see, inside the block,
|
||||
* only their ancestors (RadBatch::spec_parent), so those rows go through the tree form.
|
||||
* Where one launch serves the whole step beside a short chunk, the ordinary form runs
|
||||
* over every row first and the tree form rewrites the decode rows, which come first. */
|
||||
const bool tree_step = op_attn_tree && batch->spec_parent && batch->draft_pass == 0 &&
|
||||
D > 0;
|
||||
const int32_t qd = batch->phase == RAD_PHASE_MIXED && batch->max_q_len_decode > 0
|
||||
? batch->max_q_len_decode : batch->max_q_len;
|
||||
auto tree_rows = [&]() {
|
||||
RAD_ISSUE_N(c, op_attn_tree, qd,
|
||||
brows(w.q, DT), kv_cache(kv, layer),
|
||||
praw2(table, RAD_I32, D, pitch), praw(used, RAD_I32, D),
|
||||
RAD_NONE, RAD_NONE, praw(batch->cu_seqlens, RAD_I32, D + 1),
|
||||
brows(w.attn.x, DT), praw(batch->spec_parent, RAD_I32, DT));
|
||||
};
|
||||
if (tree_step && D == batch->n_seq) {
|
||||
tree_rows();
|
||||
} else if (batch->phase == RAD_PHASE_MIXED && D > 0 && D < batch->n_seq &&
|
||||
batch->max_q_len_decode > 0 && qp > batch->max_q_len_decode) {
|
||||
const int64_t P = batch->n_seq - D;
|
||||
if (tree_step) tree_rows();
|
||||
else
|
||||
RAD_ISSUE_N(c, op_attn, batch->max_q_len_decode,
|
||||
brows(w.q, DT), kv_cache(kv, layer),
|
||||
praw2(table, RAD_I32, D, pitch), praw(used, RAD_I32, D),
|
||||
@@ -832,12 +957,14 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
/* cu_seqlens: verify rows may be of different lengths. */
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
|
||||
brows(w.attn.x, T));
|
||||
if (tree_step) tree_rows();
|
||||
}
|
||||
}
|
||||
|
||||
/* Every attention launch of this layer is issued: start the next layer's stage copy, which
|
||||
* crosses the link under the out projection and the next layer's projections. */
|
||||
if (kvb && kvb->stream) kv_stage_next(c, kv, layer);
|
||||
if (side) side->at(1);
|
||||
if (gated) {
|
||||
/* the sparse attention gated and quantised in its merge */
|
||||
} else if (op_sig) {
|
||||
@@ -851,6 +978,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
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));
|
||||
}
|
||||
if (side && !gated) side->at(2);
|
||||
|
||||
o.step(c, w.attn, w.h.x, T);
|
||||
if (own_ar && op_ar && !ar_taken(g, T, ar_out, ar_out_take))
|
||||
@@ -861,4 +989,4 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_ATTN_GATED_FP8_H */
|
||||
#endif /* RAD_BLOCK_ATTN_GATED_Q_H */
|
||||
@@ -1,41 +1,44 @@
|
||||
/* rad_block_attn_fp8.h -- plain GQA attention with block-scaled FP8 projections.
|
||||
/* rad_block_attn_q.h -- plain GQA attention over LinearQ 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:
|
||||
* rad_block_attn_gated_q.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.
|
||||
*
|
||||
* `rotary_dim` 0 is attention without positions (NoPE, Nemotron-H's attention layers): no `rope`
|
||||
* is declared, and position reaches the model through its recurrent layers alone.
|
||||
*
|
||||
* 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
|
||||
* not a contiguous slice of the stack. LinearQ 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.
|
||||
* The fused front op, the KV dtype and the fold flags are documented in rad_linear.h and
|
||||
* rad_block_attn_gated_q.h.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_ATTN_FP8_H
|
||||
#define RAD_BLOCK_ATTN_FP8_H
|
||||
#ifndef RAD_BLOCK_ATTN_Q_H
|
||||
#define RAD_BLOCK_ATTN_Q_H
|
||||
|
||||
#include "rad_fp8.h"
|
||||
#include "rad_linear.h"
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct AttnFP8 {
|
||||
struct AttnQ {
|
||||
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 */
|
||||
ActQ 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 */
|
||||
ActQ attn{}; /* [max_tok, q_dim] attention output */
|
||||
};
|
||||
|
||||
/* Checkpoint tensor names; the declaration is the same whether they hold block fp8 or a dense
|
||||
@@ -58,9 +61,9 @@ struct AttnFP8 {
|
||||
const char* mode = "neox";
|
||||
|
||||
rad_weight w_norm = 0;
|
||||
LinearFP8 qkv{}, o{};
|
||||
NormQuantFP8 nq_h{};
|
||||
QuantFP8 q_attn{};
|
||||
LinearQ qkv{}, o{};
|
||||
NormQuant nq_h{};
|
||||
QuantAct 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;
|
||||
@@ -72,7 +75,7 @@ struct AttnFP8 {
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
};
|
||||
|
||||
inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup group,
|
||||
inline int AttnQ::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;
|
||||
@@ -81,19 +84,21 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
|
||||
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)) {
|
||||
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);
|
||||
/* Above the KV head count geom_from replicates KV heads (rad_arch.h): each of the fused row's
|
||||
* three parts takes its own span (as gemma4's q|k|v does), q this rank's heads and k and v the
|
||||
* shared head at `kv_off`, where the even shard would hand a rank part of a head. A smaller
|
||||
* attention world (Geom::attn_world) is not served here. */
|
||||
const bool kv_repl = g.world > g.n_head_kv_all;
|
||||
if (kv_repl && g.attn_world != g.world) {
|
||||
fprintf(stderr, "radiance: %s replicates KV heads but declares no attention-zero ranks; "
|
||||
"world_size = %d must be a multiple of n_head_kv = %lld.\n", __func__,
|
||||
g.world, (long long)g.n_head_kv_all);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
@@ -101,30 +106,34 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
|
||||
w_norm = decl_w(b, nm.f("blk.%d.attn_norm.weight", l), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
|
||||
/* Norm and quantise in one op (rad_fp8.h: NormQuantFP8). */
|
||||
/* Norm and quantise in one op (rad_linear.h: NormQuant). */
|
||||
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 }));
|
||||
if (kv_repl) {
|
||||
const int64_t lo[3] = { g.rank * q_dim, g.kv_off, g.kv_off };
|
||||
const int64_t hi[3] = { lo[0] + q_dim, lo[1] + kv_dim, lo[2] + kv_dim };
|
||||
const int64_t tot[3] = { g.n_head_all * g.head_dim, g.n_head_kv_all * g.head_dim,
|
||||
g.n_head_kv_all * g.head_dim };
|
||||
RAD_ARCH_TRY(qkv.span_parts(b, lo, hi, tot, 3));
|
||||
}
|
||||
|
||||
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});
|
||||
if (n_rot > 0)
|
||||
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});
|
||||
op_qlift = cast_op(b, g.max_tok, q_dim, g.dtype, g.dtype, 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, decl_attn(b, g, "attn_paged",
|
||||
op_attn = rw(b, rad_decl_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),
|
||||
@@ -143,19 +152,14 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
|
||||
{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));
|
||||
* fold it into. Declared where the activation carries a code pair its producer writes: an int8
|
||||
* trunk that leaves each linear to quantise its own input declares none (nemotronh). */
|
||||
if (w.attn.cq()) 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});
|
||||
op_ar = decl_all_reduce(b, g, w.h.x);
|
||||
|
||||
if (add_out)
|
||||
op_add = rw(b, RAD_OP(b, "add",
|
||||
@@ -166,7 +170,7 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
inline void AttnFP8::step(RadCtx* c, const RadBatch* batch) const {
|
||||
inline void AttnQ::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;
|
||||
@@ -179,7 +183,7 @@ inline void AttnFP8::step(RadCtx* c, const RadBatch* batch) const {
|
||||
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));
|
||||
if (op_rope) 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,
|
||||
@@ -206,4 +210,4 @@ inline void AttnFP8::step(RadCtx* c, const RadBatch* batch) const {
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_ATTN_FP8_H */
|
||||
#endif /* RAD_BLOCK_ATTN_Q_H */
|
||||
@@ -153,7 +153,8 @@ inline int ClefHead::declare(RadBuilder* b, const RadModelMeta* meta, const RadB
|
||||
if (bs <= 0) return RAD_E_STATE;
|
||||
/* Rows a request may hold: the context, or the head's own bound where that is less (the
|
||||
* server refuses a longer prompt before it is admitted). */
|
||||
const int64_t rows = g.max_ctx < RAD_CLEF_MAX_PROMPT ? g.max_ctx : RAD_CLEF_MAX_PROMPT;
|
||||
const int64_t rows = g.max_ctx < (int64_t)RAD_CLEF_MAX_PROMPT ? g.max_ctx
|
||||
: (int64_t)RAD_CLEF_MAX_PROMPT;
|
||||
nblk = (rows + bs - 1) / bs;
|
||||
NM = nblk * bs;
|
||||
n_vocab = g.n_vocab;
|
||||
@@ -501,11 +502,7 @@ inline int ClefHead::declare(RadBuilder* b, const RadModelMeta* meta, const RadB
|
||||
op_cp_abs = rw(b, copy(), { b_abs }, { b_feat });
|
||||
op_rs1 = rw(b, gemmb(OM, W, 4 * W, "gelu", rs1_w, rs1_b), { b_feat }, { b_r });
|
||||
op_rs2 = rw(b, gemmb(OM, 1, W, "none", rs2_w, rs2_b), { b_r }, { b_out3 });
|
||||
op_cast = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", 3 * OM),
|
||||
RAD_STR("from", "bf16"), RAD_STR("to", "f32")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_out3 }, { b_logits });
|
||||
op_cast = cast_op(b, 1, 3 * OM, "bf16", "f32", b_out3, b_logits);
|
||||
|
||||
rad_note(b, "clef's joint schema head on the card: width %lld, %lld heads of %lld, "
|
||||
"feedforward %lld, %lld routing + %lld decoder layers; hn cached as a FULL group "
|
||||
|
||||
+394
-146
@@ -1,7 +1,7 @@
|
||||
/* 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):
|
||||
* the MTP head (rad_block_mtp_q.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
|
||||
@@ -47,16 +47,27 @@
|
||||
* hp = hidden_projection(x) the selector's query, rank 256
|
||||
* tokens = dflash_select(cand, unary, hp, anchor, predecessor, successor)
|
||||
*
|
||||
* ============================== LILICORR ==============================
|
||||
*
|
||||
* Config::lili is NVIDIA's LiLiCorr backbone (Nemotron-3.5-Bolt's drafter): the same layers with a
|
||||
* learned sink logit a query head in the attention (attn_paged_sink, `attention_sink_bias`), and no
|
||||
* selector or draft head here. The query pass ends with the gather into `sel_h`; the plugin then
|
||||
* runs rad_block_lilicorr.h's correlator over those rows, which reads the target's own head.
|
||||
*
|
||||
* ============================== 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.
|
||||
* separate mask embedding. A table embed_lookup cannot read (qwen35_exl3's exl3i trellis) is
|
||||
* gathered by the plugin's own op (op_embed_ext), the rows the target's own embedding gives.
|
||||
*
|
||||
* The head reads the 2-bit copy of the lm_head, as the MTP head does (rad_block_mtp_fp8.h,
|
||||
* The head reads the 2-bit copy of the lm_head, as the MTP head does (rad_block_mtp_q.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.
|
||||
* is fp8 or int8 (op_drerank), or by a plugin's own op over a head logit_rerank cannot read
|
||||
* (op_rr_ext), so coarseness affects only which candidates are proposed. Where the target's head
|
||||
* is already narrow (Inkling 2's int8 head) the block reads that head itself (w_thead) and keeps
|
||||
* no copy.
|
||||
*
|
||||
* ============================== PLAIN NORMS ==============================
|
||||
*
|
||||
@@ -68,6 +79,8 @@
|
||||
*
|
||||
* 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.
|
||||
* Fewer KV heads than ranks are replicated (drafter_geom's `kv_repl_ok`): each rank reads its
|
||||
* head's k/v rows at `kv_off` and keeps that head in its cache.
|
||||
*
|
||||
* fc [n_embd, n_taps*n_embd], 262 MiB in fp8 at Qwen3.8's width, read whole by the
|
||||
* context pass every step. Split by rows over the ranks and all-gathered, and
|
||||
@@ -75,7 +88,7 @@
|
||||
* (n_embd / world) and computes the fewest whole 128-row scale blocks that cover
|
||||
* it (the 31B at tp 4: 1344 columns a rank inside 11 blocks, 1408 rows, against
|
||||
* 42 blocks whole), a row span of the one stored weight
|
||||
* (DenseFP8::declare_slice), so no reconvert. The GEMM takes its K split from
|
||||
* (DenseQ::declare_slice), so no reconvert. The GEMM takes its K split from
|
||||
* the whole width (OPS.md's `split_n`), so each output is summed as the unsplit
|
||||
* fc sums it, and the all-gather reads each rank's window out of its wider rows
|
||||
* (an input pitch) and writes c whole. A GEMM cannot write a column slice (the
|
||||
@@ -97,7 +110,7 @@
|
||||
#define RAD_BLOCK_DFLASH2_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
#include "rad_fp8.h"
|
||||
#include "rad_linear.h"
|
||||
#include "rad_spechub.h" /* RAD_MTP_COUPLE_*: the coupling wire (--draft-coupling) */
|
||||
|
||||
namespace rad {
|
||||
@@ -138,6 +151,19 @@ struct Dflash2 {
|
||||
/* The target's embedding scale, applied to the query block as the drafter was trained
|
||||
* (dflash_config.input_embedding_scale): 1 for Qwen, sqrt(hidden) in bf16 for Gemma. */
|
||||
double escale = 1.0;
|
||||
/* The drafter's logit transform: `omul` multiplies the final norm's output, `scap` > 0 is
|
||||
* a tanh soft cap on the draft logits. 1 and 0 leave the logits as the head gives them. */
|
||||
double omul = 1.0;
|
||||
double scap = 0.0;
|
||||
/* `scap` taken after the selector adds its edge score to the unary logit rather than over
|
||||
* the draft logits (dflash_config.selector_softcap_mode "after_correction"). The greedy
|
||||
* walk takes each position's argmax of that sum, which an increasing cap leaves where it
|
||||
* is, so the unary logits stay uncapped and no cap op is declared; a tree and the coupled
|
||||
* walk weigh the scores themselves and are refused. */
|
||||
bool cap_after = false;
|
||||
/* Candidates only from ids below this (the target's unpadded vocabulary): the head's rows
|
||||
* past it are filled with -1e30 before the top-K. 0: every row of the head. */
|
||||
int64_t vocab_real = 0;
|
||||
/* Bytes of the next GEMM's weight read into the cache beside each all-reduce of the query
|
||||
* pass (prefetch_beside, rad_arch.h); 0 reads none. */
|
||||
int64_t prefetch = 0;
|
||||
@@ -152,6 +178,17 @@ struct Dflash2 {
|
||||
* acceptance, sum min(P, Q). */
|
||||
double q_temp = 1.0;
|
||||
int64_t short_rows = 0;
|
||||
/* The drafter's linears are served at i8a8h (DenseQ::w8h: IQ8R, or a rotated int8 or
|
||||
* narrower form at group 128), learned by the plugin from `probe_i8` before it declares the
|
||||
* activation pairs: they are then int8 codes with one f32 scale per (row, act_g8), written
|
||||
* by had_quant_act_i8g. Every linear must agree. `fc_mapped`: probe_i8 made
|
||||
* `dflash.fc.weight`'s name map. */
|
||||
bool act_i8 = false;
|
||||
int64_t act_g8 = RAD_SCALE_GROUP;
|
||||
bool fc_mapped = false;
|
||||
/* LiLiCorr's backbone (the LILICORR section above): sinks, and the head left to the
|
||||
* plugin. sel_rank and sel_topk are then unused. */
|
||||
int lili = 0;
|
||||
int64_t steps() const { return block - 1; }
|
||||
int64_t nodes() const { return tree && tree_nodes > 0 ? tree_nodes : steps(); }
|
||||
int64_t ng(int64_t n_embd) const { return group ? n_embd / group : 0; }
|
||||
@@ -186,7 +223,9 @@ struct Dflash2 {
|
||||
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 read only by the `gemm_nt_q` linears (int8 codes with a scale per Config::act_g8,
|
||||
* written by `had_quant_act_i8g`, when the drafter's linears are rotated int8:
|
||||
* Config::act_i8). 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 */
|
||||
@@ -200,7 +239,7 @@ struct Dflash2 {
|
||||
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 dlog = 0; /* [srows, head_rows(g)] bf16 the coarse logits; f32 from w_thead */
|
||||
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
|
||||
@@ -232,11 +271,11 @@ struct Dflash2 {
|
||||
|
||||
/* model-scope weights.
|
||||
*
|
||||
* The linears are block fp8 or OCP-MXFP4 (rad_fp8.h: DenseFP8, per the recipe) although the
|
||||
* The linears are block fp8 or OCP-MXFP4 (rad_linear.h: DenseQ, 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{};
|
||||
DenseQ w_fc{};
|
||||
/* fc split by rows (see SHARDING): w_fc is this rank's fc_rows block-aligned rows, holding its
|
||||
* fc_share output columns at row fc_off. fc_rows 0: w_fc is the whole fc, replicated. */
|
||||
int64_t fc_share = 0, fc_rows = 0, fc_off = 0;
|
||||
@@ -248,15 +287,19 @@ struct Dflash2 {
|
||||
* 31B's: the head read at w8a8, so the selector sees the candidates an 8-bit head ranks), and
|
||||
* the 2-bit grid otherwise. Set by declare from the copy's encoding. */
|
||||
bool head_i8 = false;
|
||||
/* The copy is plain bf16 where the container holds it so, read by gemm_nt: the form for a
|
||||
* vocabulary that is not a multiple of the int8 and 2-bit head kernels' 128-row tile (Muse
|
||||
* Glimmer's 202048 tokens). */
|
||||
bool head_bf16 = false;
|
||||
|
||||
/* 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]{};
|
||||
DenseQ 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]{};
|
||||
DenseQ 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] = {};
|
||||
|
||||
@@ -294,6 +337,9 @@ struct Dflash2 {
|
||||
int64_t block_lo = 0;
|
||||
int64_t sel_lo_nodes = 0; /* a tree's nodes at the short block (op_sel_lo) */
|
||||
rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn = 0;
|
||||
/* LiLiCorr: the attention with each layer's sinks, a weight, so one op a layer. */
|
||||
rad_weight w_sink[MAX_LAYERS] = {};
|
||||
rad_op op_attn_sink[MAX_LAYERS] = {};
|
||||
rad_op op_act = 0, op_ar = 0, op_add = 0, op_final = 0;
|
||||
/* The residual add folded into the norm after it (add_rmsnorm), issued in place of op_add and
|
||||
* that norm where it resolves: op_afn[i] after layer i's attention (its feed-forward norm),
|
||||
@@ -309,12 +355,43 @@ struct Dflash2 {
|
||||
rad_weight pfa_w[MAX_LAYERS][2] = {}, pff_w[MAX_LAYERS][2] = {}, pfo_w[MAX_LAYERS] = {};
|
||||
|
||||
/* head and selector */
|
||||
rad_op op_gather = 0, op_dquant = 0, op_dlogits = 0, op_dtopk = 0;
|
||||
rad_op op_gather = 0, op_dquant = 0, op_dlogits = 0, op_dcap = 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;
|
||||
/* A rescoring op the plugin declares itself, for a head logit_rerank cannot read (qwen35_exl3's exl3i trellis head:
|
||||
* exl3i_rerank). Its operands are logit_rerank's with the head as up to three weights, rr_w[0..]: x, head..., idx_in,
|
||||
* idx, val, pairs. The plugin declares it over this block's buffers (sel_h, cand -> cand, unary[, dpair]) with its
|
||||
* reads and writes, leaves w_lm 0 and sets op_rr_ext before declare; the block issues it where it would issue
|
||||
* logit_rerank. 0: none. */
|
||||
rad_op op_rr_ext = 0;
|
||||
rad_weight rr_w[3] = {};
|
||||
/* An embedding op the plugin declares itself, for a token table embed_lookup cannot read (qwen35_exl3's exl3i trellis
|
||||
* table: embed_exl3i). Its operands are embed_lookup's with the table as up to three weights, emb_w[0..]: token ids,
|
||||
* table..., x. The plugin declares it over this block's x (M up to the query rows) with its writes, reading whole rows
|
||||
* on every rank (no all-reduce), for an unscaled embedding, and sets op_embed_ext before declare; the block issues it
|
||||
* where it would issue embed_lookup. 0: embed_lookup on w_tok. */
|
||||
rad_op op_embed_ext = 0;
|
||||
rad_weight emb_w[3] = {};
|
||||
/* An op the plugin declares itself over x in place (M up to the query rows), issued after the
|
||||
* embedding and its all-reduce, with `post_embed_w` its one weight: operands x, the weight, x.
|
||||
* For a target whose input embedding is more than the table lookup (Inkling 2 norms the
|
||||
* looked-up row, embed_norm), so the query block embeds as the target embeds its own tokens.
|
||||
* 0: none. */
|
||||
rad_op op_post_embed = 0;
|
||||
rad_weight post_embed_w = 0;
|
||||
/* The target's own head, set by the plugin before declare: logits_gemm reads it over `sel_h`
|
||||
* into an f32 `dlog` (the plugin declares it so), in place of a draft-head copy, so there is
|
||||
* no `dflash.draft_head` tensor and no rerank (the scores are already the target head's). Its
|
||||
* rows are this rank's vocabulary slice, so above one rank the head must be vocab-sharded
|
||||
* (head_sharded). 0: the copy. */
|
||||
rad_weight w_thead = 0;
|
||||
/* Config::vocab_real's fill over this rank's padded columns of `dlog`, [pad_lo, pad_lo +
|
||||
* pad_n); 0 when this rank holds none. */
|
||||
rad_op op_dpad = 0;
|
||||
int64_t pad_lo = 0, pad_n = 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;
|
||||
@@ -327,6 +404,18 @@ struct Dflash2 {
|
||||
* the drafter's own block is longer (rad_drafter_short_block). */
|
||||
static constexpr int64_t kShortBlock = 4;
|
||||
|
||||
/* Whether the container's drafter is served at i8a8h and at which scale group, from its `fc`,
|
||||
* whose name map this makes (set Config::fc_mapped). Asked before the activation pairs are
|
||||
* declared, since it decides their dtype and scale grid. */
|
||||
static int probe_i8(RadBuilder* b, Names& nm, const char* ck, bool* i8, int64_t* g8) {
|
||||
const char* fwn = nm.f("dflash.fc.weight");
|
||||
RAD_ARCH_TRY(map_linear(b, fwn, { nm.ckpt("%s.fc.weight", ck) }));
|
||||
RadEncoding fe{};
|
||||
*i8 = weight_enc(b, fwn, &fe) && linear_is_w8h(fe);
|
||||
*g8 = *i8 ? linear_w8h_group(fe) : (int64_t)RAD_SCALE_GROUP;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
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);
|
||||
@@ -347,14 +436,26 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
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 (!ck || (!ck_lm && !w_thead) || !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)
|
||||
if (cfg.block < 2 || cfg.n_taps <= 0 || (!cfg.lili && (cfg.sel_rank <= 0 || cfg.sel_topk <= 0)))
|
||||
return RAD_E_INVAL;
|
||||
if (cfg.cap_after && (cfg.tree || wire.couple_draws || wire.couple_state)) {
|
||||
fprintf(stderr, "radiance: dflash2: this drafter's softcap is taken after the selector's "
|
||||
"edge score, which only the greedy walk serves (no draft tree, no "
|
||||
"--draft-coupling)\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (w_thead && g.world > 1 && !head_sharded(g)) {
|
||||
fprintf(stderr, "radiance: dflash2: the target's head is read in place of a draft-head "
|
||||
"copy, and at %d ranks its %lld rows do not shard evenly by vocabulary\n",
|
||||
g.world, (long long)g.n_vocab_all);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
const int64_t NG = cfg.ng(g.n_embd);
|
||||
const int64_t CD = cfg.coef_dim(g.n_embd);
|
||||
@@ -366,24 +467,31 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
srows = g.max_seqs * cfg.steps();
|
||||
if (qrows <= 0 || srows <= 0) return RAD_E_INVAL;
|
||||
|
||||
/* The linears read the activation pairs the plugin declared: int8 ones take rotated int8
|
||||
* weights (cfg.act_i8), E4M3 ones block fp8 or MXFP4. */
|
||||
w_fc.w8h_ok = cfg.act_i8;
|
||||
for (int i = 0; i < MAX_LAYERS; ++i)
|
||||
w_q[i].w8h_ok = w_k[i].w8h_ok = w_v[i].w8h_ok = w_o[i].w8h_ok = w_gu[i].w8h_ok =
|
||||
w_dn[i].w8h_ok = cfg.act_i8;
|
||||
|
||||
/* ---------------------------------------------------------------- model-scope weights */
|
||||
{
|
||||
const int64_t K = cfg.n_taps * g.n_embd;
|
||||
const char* fwn = nm.f("dflash.fc.weight");
|
||||
RAD_ARCH_TRY(map_linear(b, fwn, { nm.ckpt("%s.fc.weight", ck) }));
|
||||
if (!cfg.fc_mapped) RAD_ARCH_TRY(map_linear(b, fwn, { nm.ckpt("%s.fc.weight", ck) }));
|
||||
/* Split only block fp8 (an MXFP4 GEMM's K split is its own), into equal shares of whole
|
||||
* 16-byte words (the gather's unit). */
|
||||
RadEncoding fe{};
|
||||
const RadEncPlane* fsc = nullptr;
|
||||
const bool fp8 = weight_enc(b, fwn, &fe) && rad_enc_is(&fe, "affine") && fe.n_planes == 2 &&
|
||||
!fe.transform[0] && fe.plane[0].dtype == RAD_F8E4M3 &&
|
||||
(fsc = rad_enc_plane(&fe, "scale")) && fsc->block[0] == RAD_FP8_BLOCK &&
|
||||
fsc->block[1] == RAD_FP8_BLOCK;
|
||||
const int64_t share = (g.world > 1 && g.n_embd % RAD_FP8_BLOCK == 0 &&
|
||||
(fsc = rad_enc_plane(&fe, "scale")) && fsc->block[0] == RAD_SCALE_GROUP &&
|
||||
fsc->block[1] == RAD_SCALE_GROUP;
|
||||
const int64_t share = (g.world > 1 && g.n_embd % RAD_SCALE_GROUP == 0 &&
|
||||
g.n_embd % g.world == 0 && (g.n_embd / g.world) % 8 == 0)
|
||||
? g.n_embd / g.world : 0;
|
||||
if (fp8 && share > 0) {
|
||||
const int64_t B = RAD_FP8_BLOCK;
|
||||
const int64_t B = RAD_SCALE_GROUP;
|
||||
const int64_t lo = share * g.rank / B * B;
|
||||
const int64_t hi = (share * (g.rank + 1) + B - 1) / B * B;
|
||||
fc_share = share;
|
||||
@@ -401,25 +509,12 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
}
|
||||
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):
|
||||
/* The 2-bit draft head, declared as the MTP head's is (rad_block_mtp_q.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.
|
||||
@@ -427,35 +522,61 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
* 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). */
|
||||
* the replicated codebooks. The all_gather is `world * R` pairs a row (2 KiB at R = 16).
|
||||
*
|
||||
* LiLiCorr has neither the selector nor this head (its correlator reads the target's). */
|
||||
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));
|
||||
/* The 8-bit form: int8 codes, one f16 scale per (row, 128 of K), symmetric, which gemm_nt_q
|
||||
* reads at w8a8 against the same quant_act_i8 activation (without its asum). */
|
||||
{
|
||||
RadEncoding e{};
|
||||
const RadEncPlane* sc = nullptr;
|
||||
head_i8 = weight_enc(b, dhn, &e) && rad_enc_is(&e, "affine") && e.n_planes == 2 &&
|
||||
!e.transform[0] && e.plane[0].dtype == RAD_I8 && e.plane[0].block[1] == 1 &&
|
||||
(sc = rad_enc_plane(&e, "scale")) && sc->dtype == RAD_F16 &&
|
||||
sc->block[0] == 1 && sc->block[1] == DF_W2_GROUP;
|
||||
if (!cfg.lili) {
|
||||
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_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());
|
||||
}
|
||||
if (head_i8) {
|
||||
w_dh = decl_view(b, dhn, nullptr, "codes", RAD_I8, {head_rows(g), g.n_embd},
|
||||
/* The target's own head (w_thead) is declared by the plugin; the copy is this block's. */
|
||||
if (!cfg.lili && !w_thead) {
|
||||
const char* dhn = nm.f("dflash.draft_head.weight");
|
||||
RAD_ARCH_TRY(map_copy(b, dhn, ck_lm));
|
||||
/* The 8-bit form: int8 codes, one f16 scale per (row, 128 of K), symmetric, which
|
||||
* gemm_nt_q reads at w8a8 against the same quant_act_i8 activation (without its asum). */
|
||||
RadEncoding dhe{};
|
||||
const bool head_known = weight_enc(b, dhn, &dhe);
|
||||
{
|
||||
const RadEncPlane* sc = nullptr;
|
||||
head_i8 = head_known && rad_enc_is(&dhe, "affine") && dhe.n_planes == 2 &&
|
||||
!dhe.transform[0] && dhe.plane[0].dtype == RAD_I8 && dhe.plane[0].block[1] == 1 &&
|
||||
(sc = rad_enc_plane(&dhe, "scale")) && sc->dtype == RAD_F16 &&
|
||||
sc->block[0] == 1 && sc->block[1] == DF_W2_GROUP;
|
||||
}
|
||||
if (head_i8) {
|
||||
w_dh = decl_view(b, dhn, nullptr, "codes", RAD_I8, {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", RAD_F16,
|
||||
{head_rows(g), g.n_embd / DF_W2_GROUP}, RAD_ACCESS_PER_TOKEN,
|
||||
dh_split, grp_model());
|
||||
} else if (head_known && rad_enc_is(&dhe, "plain") && dhe.n_planes == 1 &&
|
||||
dhe.plane[0].dtype == RAD_BF16) {
|
||||
head_bf16 = true;
|
||||
w_dh = decl_w(b, dhn, RAD_BF16, {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", RAD_F16,
|
||||
{head_rows(g), g.n_embd / DF_W2_GROUP}, RAD_ACCESS_PER_TOKEN, dh_split,
|
||||
grp_model());
|
||||
} else {
|
||||
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());
|
||||
} else {
|
||||
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 || (!head_bf16 && !w_dhs)) return RAD_E_INVAL;
|
||||
}
|
||||
if (!w_dh || !w_dhs) return RAD_E_INVAL;
|
||||
|
||||
/* ---------------------------------------------------------------- per-layer weights */
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
@@ -492,6 +613,13 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
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) }));
|
||||
/* Fewer KV heads than ranks (drafter_geom's `kv_repl_ok`): k and v are this rank's
|
||||
* replicated head, rows [kv_off, kv_off + kv_dim) of the unsharded projection, where the
|
||||
* even shard would hand a rank part of a head. q stays an even share of the heads. */
|
||||
if (g.world > g.n_head_kv_all) {
|
||||
RAD_ARCH_TRY(w_k[i].span(b, g.kv_off, g.kv_off + kvd));
|
||||
RAD_ARCH_TRY(w_v[i].span(b, g.kv_off, g.kv_off + kvd));
|
||||
}
|
||||
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},
|
||||
@@ -520,6 +648,14 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
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));
|
||||
/* LiLiCorr's sink logit a query head, split with the heads. */
|
||||
if (cfg.lili) {
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_sinks", i),
|
||||
nm.ckpt("%s.layers.%d.self_attn.attention_sink_bias", ck, i)));
|
||||
w_sink[i] = decl_w(b, nm.f("dflash.blk.%d.attn_sinks", i), RAD_F32, {g.n_head},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(first_layer + i));
|
||||
if (!w_sink[i]) return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -529,38 +665,81 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
*
|
||||
* 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});
|
||||
if (!cfg.lili) {
|
||||
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});
|
||||
} else {
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
op_attn_sink[i] = rw(b, RAD_OP(b, "attn_paged_sink",
|
||||
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_WEIGHTS(w_sink[i])),
|
||||
{w.q}, {w.attn});
|
||||
if (!op_attn_sink[i]) return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- the context pass */
|
||||
/* Every linear is `fp8a8` (or `mxfp4a8` for a 4-bit recipe; DenseFP8 reads which from the
|
||||
/* Every linear is `fp8a8` (or `mxfp4a8` for a 4-bit recipe; DenseQ 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",
|
||||
/* A rotated int8 drafter (cfg.act_i8): the same five quantisers as had_quant_act_i8g at its
|
||||
* scale group, and no fp8a8 fold. Its linears read one activation pair, so they are all
|
||||
* i8a8h forms at one group or none is. */
|
||||
const char* const qop = cfg.act_i8 ? "had_quant_act_i8g" : "quant_act_fp8";
|
||||
const int64_t qgr = cfg.act_i8 ? cfg.act_g8 : (int64_t)RAD_SCALE_GROUP;
|
||||
{
|
||||
auto fits = [&](const DenseQ& d) {
|
||||
return d.w8h == cfg.act_i8 && (!d.w8h || d.g8 == cfg.act_g8);
|
||||
};
|
||||
bool same = fits(w_fc);
|
||||
for (int64_t l = 0; l < g.n_layer; ++l)
|
||||
same = same && fits(w_q[l]) && fits(w_k[l]) && fits(w_v[l]) && fits(w_o[l]) &&
|
||||
fits(w_gu[l]) && fits(w_dn[l]);
|
||||
if (!same) {
|
||||
fprintf(stderr, "radiance: the drafter's linears are not all rotated int8 at one scale "
|
||||
"group or all block fp8 / MXFP4; they read one activation pair, so the "
|
||||
"recipe must give them one format\n");
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
}
|
||||
op_qsrc = rw(b, RAD_OP(b, qop,
|
||||
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_INT("group", qgr), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.src}, {w.srcq, w.srcs});
|
||||
if (fc_rows) {
|
||||
/* The split (SHARDING above): this rank's block-aligned rows into `cpart`, its window of
|
||||
* them gathered into `c`. The GEMM takes its K split from the whole width. The gather
|
||||
* rides the trunk's all-reduce instance (the same numel bound, so the same instance). */
|
||||
* rides the trunk's all-reduce instance (the same numel bound, so the same instance).
|
||||
* The message is a range, as the all-reduce's: a fixed numel follows max_tok, and the
|
||||
* arena's sizing declare (RadBuildCtx::shape_probe) refuses a fixed parameter that
|
||||
* changes with the step size. */
|
||||
op_cfc = w_fc.gemm(b, crows, fc_rows, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.cpart},
|
||||
g.n_embd);
|
||||
op_cgath = rw(b, RAD_OP(b, "all_gather",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_INT("numel", crows * g.n_embd),
|
||||
RAD_RANGE("numel", g.n_embd, crows * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("row", fc_share)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.cpart}, {w.c});
|
||||
@@ -576,9 +755,9 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
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",
|
||||
op_qc = rw(b, RAD_OP(b, qop,
|
||||
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_INT("group", qgr), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.c}, {w.cq, w.cs});
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
@@ -617,7 +796,13 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
/* ---------------------------------------------------------------- the query pass */
|
||||
/* An unscaled lookup is declared exactly as before the scale existed, so a Qwen container
|
||||
* resolves the same op. */
|
||||
if (cfg.escale != 1.0)
|
||||
if (op_embed_ext) {
|
||||
if (cfg.escale != 1.0) {
|
||||
fprintf(stderr, "radiance: dflash2: a plugin embedding op takes no input_embedding_scale\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
op_embed = op_embed_ext;
|
||||
} else if (cfg.escale != 1.0)
|
||||
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),
|
||||
@@ -633,28 +818,23 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
{}, {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});
|
||||
if (g.world > 1 && !op_embed_ext)
|
||||
op_embed_ar = decl_all_reduce_exact(b, g, w.x, g.n_embd, qrows, g.dtype);
|
||||
/* 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",
|
||||
op_qh2 = rw(b, RAD_OP(b, qop,
|
||||
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_INT("group", qgr), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h2}, {w.h2q, w.h2s});
|
||||
op_qat = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
op_qat = rw(b, RAD_OP(b, qop,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", qd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.attn}, {w.atq, w.ats});
|
||||
op_qff = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
op_qff = rw(b, RAD_OP(b, qop,
|
||||
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_INT("group", qgr), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.ffn}, {w.ffq, w.ffs});
|
||||
|
||||
@@ -700,8 +880,8 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
{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 or M2XFP4 gate_up takes the pair. */
|
||||
if (!w_gu[i].mx && !w_gu[i].m2x)
|
||||
* fp8a8 tile, so an MXFP4 gate_up takes the pair. */
|
||||
if (!w_gu[i].mx && !w_gu[i].w8h)
|
||||
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});
|
||||
@@ -774,12 +954,10 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
/* Only for a shape a library serves: an op declared for one that resolves to no device
|
||||
* kernel is a hole that refuses startup (Program::device_holes), whether or not it is
|
||||
* issued, so the block asks within libr4d's span for the fold (head_dim 256 to 512 in
|
||||
* steps of 256, bf16 rows, an fp8 or bf16 cache). Qwen3.8's DFlash2 drafter (head_dim
|
||||
* 128) keeps the chain. */
|
||||
* steps of 256, bf16 rows, either cache). Qwen3.8's DFlash2 drafter (head_dim 128) keeps
|
||||
* the chain. */
|
||||
const bool fold_shape = g.head_dim >= 256 && g.head_dim <= 512 && g.head_dim % 256 == 0 &&
|
||||
!std::strcmp(g.dtype, "bf16") &&
|
||||
(!std::strcmp(g.kv_dtype, "fp8_e4m3") ||
|
||||
!std::strcmp(g.kv_dtype, "bf16"));
|
||||
!std::strcmp(g.dtype, "bf16");
|
||||
if (fold_shape && g.yarn.factor == 0.0f &&
|
||||
rad_op_declared(b, "qkv_norm_rope_kv_store")) {
|
||||
const int64_t bsz = rad_kv_block_size(b, kv);
|
||||
@@ -828,24 +1006,25 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
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_ar = decl_all_reduce(b, g, w.h, g.n_embd, qrows, g.dtype);
|
||||
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});
|
||||
op_final = cfg.omul != 1.0
|
||||
? 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_F64("mult", cfg.omul), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_norm)),
|
||||
{w.x}, {w.h})
|
||||
: 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});
|
||||
/* Each residual add and the norm after it as one launch where a library serves add_rmsnorm
|
||||
* (byte-identical to the pair: the norm is taken over the bf16 sum it stores), taken only
|
||||
* where every handle resolves (rad_op_resolved), all or none; the pairs declared beside it run
|
||||
@@ -869,6 +1048,9 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
op_afinal = all ? an(w_norm) : 0;
|
||||
if (!op_afinal)
|
||||
for (int i = 0; i < MAX_LAYERS; ++i) op_afn[i] = op_aan[i] = 0;
|
||||
/* The output multiplier is declared on the plain final rmsnorm only: a drafter with one
|
||||
* takes the unfused add and norm. */
|
||||
if (cfg.omul != 1.0) op_afinal = 0;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- the head and the selector
|
||||
@@ -884,39 +1066,72 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
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 = head_i8
|
||||
? rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
/* LiLiCorr's head is the plugin's (rad_block_lilicorr.h), over sel_h. */
|
||||
if (cfg.lili) return RAD_OK;
|
||||
if (!head_bf16 && !w_thead)
|
||||
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});
|
||||
/* The target's head writes f32 logits (logits_gemm); the copies write the activation dtype. */
|
||||
const char* const dlt = w_thead ? "f32" : g.dtype;
|
||||
op_dlogits = w_thead
|
||||
? rw(b, RAD_OP(b, "logits_gemm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n_vocab", head_rows(g)),
|
||||
RAD_INT("n_embd", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_thead)),
|
||||
{w.sel_h}, {w.dlog})
|
||||
: head_bf16
|
||||
? rw(b, RAD_OP(b, "gemm_nt",
|
||||
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", "w8a8")),
|
||||
RAD_WEIGHTS(w_dh, w_dhs)),
|
||||
{w.dq, w.ds}, {w.dlog})
|
||||
: 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});
|
||||
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_dh)),
|
||||
{w.sel_h}, {w.dlog})
|
||||
: head_i8
|
||||
? decl_gemm_q(b, srows, head_rows(g), g.n_embd, DF_W2_GROUP, "w8a8", w_dh, w_dhs,
|
||||
{ w.dq, w.ds }, w.dlog)
|
||||
: decl_gemm_q(b, srows, head_rows(g), g.n_embd, DF_W2_GROUP, "w2a8", w_dh, w_dhs,
|
||||
{ w.dq, w.ds, w.dsum }, w.dlog);
|
||||
if (w_thead && !op_dlogits) return RAD_E_INVAL;
|
||||
if (cfg.vocab_real > 0) {
|
||||
const int64_t off = head_sharded(g) ? g.vocab_off : 0;
|
||||
const int64_t lo = std::max<int64_t>(cfg.vocab_real, off);
|
||||
const int64_t hi = std::min<int64_t>(g.n_vocab_all, off + head_rows(g));
|
||||
pad_lo = hi > lo ? lo - off : 0;
|
||||
pad_n = hi > lo ? hi - lo : 0;
|
||||
if (pad_n > 0) {
|
||||
op_dpad = rw(b, RAD_OP(b, "fill",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", pad_n),
|
||||
RAD_STR("dtype", dlt), RAD_F64("value", -1e30)),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, {w.dlog});
|
||||
if (!op_dpad) return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
if (cfg.scap > 0.0 && !cfg.cap_after) {
|
||||
op_dcap = rw(b, RAD_OP(b, "logit_softcap",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", head_rows(g)),
|
||||
RAD_F64("cap", cfg.scap), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.dlog}, {w.dlog});
|
||||
if (!op_dcap) return RAD_E_INVAL;
|
||||
}
|
||||
/* 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 */
|
||||
const bool rerank = (w_lm || op_rr_ext) && (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_STR("dtype", dlt)),
|
||||
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_INT("R", top_w), RAD_STR("dtype", dlt)),
|
||||
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
|
||||
@@ -927,7 +1142,9 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
*
|
||||
* 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) {
|
||||
if (rerank && op_rr_ext) {
|
||||
op_drerank = op_rr_ext; /* the plugin's own (op_rr_ext above), declared with its reads and writes */
|
||||
} else 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),
|
||||
@@ -1064,7 +1281,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
const int i = (int)l;
|
||||
pfa_w[i][0] = w_fcp[i];
|
||||
pfa_w[i][1] = w_gu[i].w;
|
||||
pff_w[i][0] = l + 1 < g.n_layer ? w_acp[i + 1] : w_dh;
|
||||
pff_w[i][0] = l + 1 < g.n_layer ? w_acp[i + 1] : w_thead ? w_thead : w_dh;
|
||||
pff_w[i][1] = l + 1 < g.n_layer ? w_q[i + 1].w : 0;
|
||||
for (int j = 0; j < 2; ++j) {
|
||||
op_pfa[i][j] = decl_prefetch(b, pfa_w[i][j], cfg.prefetch);
|
||||
@@ -1090,7 +1307,8 @@ inline void Dflash2::context(RadCtx* c, const RadBatch* batch) const {
|
||||
if (fc_rows) {
|
||||
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.cpart, T), RAD_NONE, w_fc.bref());
|
||||
RAD_ISSUE_N(c, op_cgath, T, bcol(w.cpart, fc_off, fc_share, T), brows(w.c, T));
|
||||
RAD_ISSUE_N(c, op_cgath, T * g.n_embd, bcol(w.cpart, fc_off, fc_share, T),
|
||||
brows(w.c, T));
|
||||
} else {
|
||||
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());
|
||||
@@ -1142,9 +1360,15 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const rad_op* aconv = lo ? op_aconv_lo : op_aconv;
|
||||
const rad_op* fconv = lo ? op_fconv_lo : op_fconv;
|
||||
|
||||
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_ext)
|
||||
RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(emb_w[0]), RAD_W(emb_w[1]),
|
||||
RAD_W(emb_w[2]), brows(w.x, T));
|
||||
else
|
||||
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);
|
||||
if (op_post_embed)
|
||||
RAD_ISSUE_N(c, op_post_embed, T, brows(w.x, T), RAD_W(post_embed_w), brows(w.x, T));
|
||||
|
||||
/* x += h2 waits for the norm after it, which takes it in (add_rmsnorm) where declared */
|
||||
bool add_pending = false;
|
||||
@@ -1188,13 +1412,22 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
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));
|
||||
if (cfg.lili)
|
||||
RAD_ISSUE_N(c, op_attn_sink[i], 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),
|
||||
RAD_W(w_sink[i]), brows(w.attn, T));
|
||||
else
|
||||
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());
|
||||
@@ -1238,21 +1471,33 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
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 (cfg.lili) return; /* the plugin's correlator takes sel_h from here */
|
||||
|
||||
/* `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. The 8-bit head is symmetric and
|
||||
* takes no asum. */
|
||||
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), head_i8 ? RAD_NONE : RAD_B(w.dsum), RAD_NONE);
|
||||
if (w_thead) {
|
||||
RAD_ISSUE_N(c, op_dlogits, S, brows(w.sel_h, S), RAD_W(w_thead), brows(w.dlog, S));
|
||||
} else if (head_bf16) {
|
||||
RAD_ISSUE_N(c, op_dlogits, S, brows(w.sel_h, S), RAD_W(w_dh), brows(w.dlog, S));
|
||||
} else {
|
||||
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. The 8-bit head is symmetric
|
||||
* and takes no asum. */
|
||||
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), head_i8 ? RAD_NONE : RAD_B(w.dsum), RAD_NONE);
|
||||
}
|
||||
if (op_dpad) RAD_ISSUE_N(c, op_dpad, S, bcol(w.dlog, pad_lo, pad_n, S));
|
||||
if (op_dcap) RAD_ISSUE_N(c, op_dcap, S, brows(w.dlog, S), brows(w.dlog, S));
|
||||
/* 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)
|
||||
if (op_drerank && op_rr_ext)
|
||||
RAD_ISSUE_N(c, op_drerank, S, brows(w.sel_h, S), RAD_W(rr_w[0]), RAD_W(rr_w[1]), RAD_W(rr_w[2]),
|
||||
brows(w.cand, S), brows(w.cand, S), brows(w.unary, S), brows(w.dpair, S));
|
||||
else 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));
|
||||
@@ -1260,7 +1505,10 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
} 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)
|
||||
if (op_drerank && op_rr_ext)
|
||||
RAD_ISSUE_N(c, op_drerank, S, brows(w.sel_h, S), RAD_W(rr_w[0]), RAD_W(rr_w[1]), RAD_W(rr_w[2]),
|
||||
brows(w.cand, S), brows(w.cand, S), brows(w.unary, S), RAD_NONE);
|
||||
else 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);
|
||||
}
|
||||
|
||||
+111
-115
@@ -93,12 +93,15 @@
|
||||
*
|
||||
* ============================== PRECISION ==============================
|
||||
*
|
||||
* E4M3 + a bf16 [N/128][K/128] plane fc, q/k/v/o, gate_up, down -- every linear
|
||||
* what the recipe made them 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
|
||||
* The checkpoint is dense bf16; the linears are rad_linear.h's DenseQ 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.
|
||||
* bf16, 324 MB at eight bits). DenseQ reads block fp8 or MXFP4 against E4M3 activations, or a
|
||||
* rotated int8 form (IQ8R and the narrower grids under the same rotation) against int8 ones
|
||||
* (Config::act_i8); one format for all of them, since they share the activation pairs. 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.
|
||||
@@ -107,7 +110,7 @@
|
||||
*
|
||||
* 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.
|
||||
* slice store and a contiguous q copy, as in rad_block_attn_q.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
|
||||
@@ -117,7 +120,7 @@
|
||||
#define RAD_BLOCK_DSPARK_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
#include "rad_fp8.h"
|
||||
#include "rad_linear.h"
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
@@ -135,6 +138,14 @@ struct Dspark {
|
||||
int64_t top_k = 0; /* candidates the Markov walk re-ranks */
|
||||
int64_t window = 0; /* sliding attention width, 0 for none */
|
||||
int causal = 0;
|
||||
/* The drafter's linears are served at i8a8h (DenseQ::w8h: IQ8R, or a rotated int8 or
|
||||
* narrower form at group 128), learned by the plugin from `probe_i8` before it declares the
|
||||
* activation pairs: they are then int8 codes with one f32 scale per (row, act_g8), written
|
||||
* by had_quant_act_i8g and the rotating norm. Every linear must agree. `fc_mapped`:
|
||||
* probe_i8 made `dspark.fc.weight`'s name map. */
|
||||
bool act_i8 = false;
|
||||
int64_t act_g8 = RAD_SCALE_GROUP;
|
||||
bool fc_mapped = false;
|
||||
/* Every row predicts, so `block`, not `block - 1` (see ROW ALIGNMENT). */
|
||||
int64_t steps() const { return block; }
|
||||
};
|
||||
@@ -149,21 +160,24 @@ struct Dspark {
|
||||
* 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] */
|
||||
/* The codes and scales the linears read: e4m3 | f32 [.., /128], or with Config::act_i8
|
||||
* i8 | f32 [.., /act_g8]. The same holds for the three ActQ pairs below, whose `q` and
|
||||
* `s` are then the int8 pair. */
|
||||
rad_buf srcq = 0, srcs = 0;
|
||||
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
|
||||
* (rad_block_attn_q.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] */
|
||||
ActQ 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] */
|
||||
ActQ attn{}; /* [qrows, q_dim] */
|
||||
rad_buf gate_up = 0; /* [qrows, 2 * n_ff] */
|
||||
ActFP8 ffn{}; /* [qrows, n_ff] */
|
||||
ActQ 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 */
|
||||
@@ -194,7 +208,7 @@ struct Dspark {
|
||||
rad_kvgroup kv = 0;
|
||||
|
||||
/* ---- model-scope weights */
|
||||
DenseFP8 w_fc{};
|
||||
DenseQ 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 */
|
||||
@@ -204,9 +218,9 @@ struct Dspark {
|
||||
* 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]{};
|
||||
DenseQ 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]{};
|
||||
DenseQ 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;
|
||||
@@ -216,8 +230,8 @@ struct Dspark {
|
||||
* 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
|
||||
/* The fused norm / residual add / quantise, declared directly rather than via rad_linear.h's
|
||||
* NormQuant: 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;
|
||||
@@ -235,6 +249,18 @@ struct Dspark {
|
||||
rad_op op_dgather = 0, op_dmerge = 0; /* the vocab-parallel pair; 0 when the head is whole */
|
||||
rad_op op_sel = 0;
|
||||
|
||||
/* Whether the container's drafter is served at i8a8h and at which scale group, from its `fc`,
|
||||
* whose name map this makes (set Config::fc_mapped). Asked before the activation pairs are
|
||||
* declared, since it decides their dtype and scale grid. */
|
||||
static int probe_i8(RadBuilder* b, Names& nm, const char* ck, bool* i8, int64_t* g8) {
|
||||
const char* fwn = nm.f("dspark.fc.weight");
|
||||
RAD_ARCH_TRY(map_linear(b, fwn, { nm.ckpt("%s.fc.weight", ck) }));
|
||||
RadEncoding fe{};
|
||||
*i8 = weight_enc(b, fwn, &fe) && linear_is_w8h(fe);
|
||||
*g8 = *i8 ? linear_w8h_group(fe) : (int64_t)RAD_SCALE_GROUP;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
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);
|
||||
@@ -274,10 +300,17 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
srows = g.max_seqs * cfg.steps();
|
||||
if (qrows <= 0 || srows <= 0) return RAD_E_INVAL;
|
||||
|
||||
/* The linears read the activation pairs the plugin declared: int8 ones take rotated int8
|
||||
* weights (cfg.act_i8), E4M3 ones block fp8 or MXFP4. */
|
||||
w_fc.w8h_ok = cfg.act_i8;
|
||||
for (int i = 0; i < MAX_LAYERS; ++i)
|
||||
w_q[i].w8h_ok = w_k[i].w8h_ok = w_v[i].w8h_ok = w_o[i].w8h_ok = w_gu[i].w8h_ok =
|
||||
w_dn[i].w8h_ok = cfg.act_i8;
|
||||
|
||||
/* ---------------------------------------------------------------- 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) }));
|
||||
{ nm.ckpt("%s.fc.weight", ck) }, {}, cfg.fc_mapped));
|
||||
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)));
|
||||
@@ -301,7 +334,7 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
w_mk2 = decl_w(b, nm.f("dspark.markov_w2"), RAD_BF16, {g.n_vocab_all, cfg.rank},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
|
||||
/* The 2-bit draft head over the target's lm_head (as in rad_block_mtp_fp8.h):
|
||||
/* The 2-bit draft head over the target's lm_head (as in rad_block_mtp_q.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.
|
||||
*
|
||||
@@ -379,19 +412,34 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
|
||||
/* ---------------------------------------------------------------- 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",
|
||||
* Every linear is a DenseQ GEMM over the pair its quantiser writes: `quant_act_fp8` codes
|
||||
* for block fp8 or MXFP4, had_quant_act_i8g's at the weights' scale group for a rotated int8
|
||||
* drafter (cfg.act_i8). The linears read one activation pair, so they are all i8a8h forms at
|
||||
* one group or none is. There is no `fp8a16` band: that kernel is M <= 1, and neither pass
|
||||
* runs at one row. */
|
||||
const char* const qop = cfg.act_i8 ? "had_quant_act_i8g" : "quant_act_fp8";
|
||||
const int64_t qgr = cfg.act_i8 ? cfg.act_g8 : (int64_t)RAD_SCALE_GROUP;
|
||||
{
|
||||
auto fits = [&](const DenseQ& d) {
|
||||
return d.w8h == cfg.act_i8 && (!d.w8h || d.g8 == cfg.act_g8);
|
||||
};
|
||||
bool same = fits(w_fc);
|
||||
for (int64_t l = 0; l < g.n_layer; ++l)
|
||||
same = same && fits(w_q[l]) && fits(w_k[l]) && fits(w_v[l]) && fits(w_o[l]) &&
|
||||
fits(w_gu[l]) && fits(w_dn[l]);
|
||||
if (!same) {
|
||||
fprintf(stderr, "radiance: the drafter's linears are not all rotated int8 at one scale "
|
||||
"group or all block fp8 / MXFP4; they read one activation pair, so the "
|
||||
"recipe must give them one format\n");
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
}
|
||||
op_qsrc = rw(b, RAD_OP(b, qop,
|
||||
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_INT("group", qgr), 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});
|
||||
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",
|
||||
@@ -401,27 +449,17 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
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",
|
||||
op_qc = rw(b, RAD_OP(b, qop,
|
||||
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_INT("group", qgr), 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_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),
|
||||
@@ -460,15 +498,11 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
* 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});
|
||||
op_embed_ar = decl_all_reduce_exact(b, g, w.x, g.n_embd, qrows, g.dtype);
|
||||
|
||||
/* 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
|
||||
/* Norm, residual add and quantise are one op, `rmsnorm_quant_fp8` (what rad_linear.h's
|
||||
* NormQuant wraps), or its rotating int8 twin `rmsnorm_had_quant_i8g` for a rotated int8
|
||||
* drafter, which takes the same operands. 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.
|
||||
@@ -478,9 +512,9 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
* 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_op h = RAD_OP(b, cfg.act_i8 ? "rmsnorm_had_quant_i8g" : "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_F64("eps", g.eps), RAD_INT("group", qgr),
|
||||
RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd)),
|
||||
RAD_WEIGHTS(gain));
|
||||
if (!h) return 0;
|
||||
@@ -490,9 +524,9 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
rad_op_writes(b, h, wr, fold ? 4 : 3);
|
||||
return h;
|
||||
};
|
||||
op_qat = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
op_qat = rw(b, RAD_OP(b, qop,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", qd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.attn.x}, {w.attn.q, w.attn.s});
|
||||
if (!op_qat) return RAD_E_INVAL;
|
||||
@@ -508,24 +542,9 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
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_qp[i] = w_q[i].gemm(b, qrows, qd, g.n_embd, {w.h.q, w.h.s}, {w.q});
|
||||
op_kp[i] = w_k[i].gemm(b, qrows, kvd, g.n_embd, {w.h.q, w.h.s}, {w.k});
|
||||
op_vp[i] = w_v[i].gemm(b, qrows, kvd, g.n_embd, {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),
|
||||
@@ -538,28 +557,15 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
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_op[i] = w_o[i].gemm(b, qrows, g.n_embd, qd, {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_gu[i] = w_gu[i].gemm(b, qrows, 2 * g.n_ff, g.n_embd, {w.h.q, w.h.s}, {w.gate_up});
|
||||
/* The fold is an fp8a8 tile, so any other gate_up takes the pair. */
|
||||
if (!w_gu[i].mx && !w_gu[i].w8h)
|
||||
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] = w_dn[i].gemm(b, qrows, g.n_embd, g.n_ff, {w.ffn.q, w.ffn.s}, {w.h.x});
|
||||
}
|
||||
|
||||
op_qrope = rw(b, decl_rotary(b, g, "rope",
|
||||
@@ -588,21 +594,15 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.gate_up}, {w.ffn.x});
|
||||
op_qff = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
op_qff = rw(b, RAD_OP(b, qop,
|
||||
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_INT("group", qgr), 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_ar = decl_all_reduce(b, g, w.h.x, g.n_embd, qrows, g.dtype);
|
||||
op_outnorm = decl_norm(w_norm, true);
|
||||
if (!op_outnorm) return RAD_E_INVAL;
|
||||
|
||||
@@ -621,12 +621,8 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
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});
|
||||
op_dlogits = decl_gemm_q(b, srows, head_rows(g), g.n_embd, DS_W2_GROUP, "w2a8", 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. */
|
||||
@@ -687,16 +683,16 @@ inline void Dspark::context(RadCtx* c, const RadBatch* batch) const {
|
||||
|
||||
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);
|
||||
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, RAD_NONE);
|
||||
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, RAD_NONE);
|
||||
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));
|
||||
@@ -735,11 +731,11 @@ inline void Dspark::step(RadCtx* c, const RadBatch* batch) const {
|
||||
* 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_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.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_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.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_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));
|
||||
@@ -757,7 +753,7 @@ inline void Dspark::step(RadCtx* c, const RadBatch* batch) const {
|
||||
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);
|
||||
RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h.x, T), RAD_NONE, w_o[i].bref());
|
||||
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 */
|
||||
@@ -769,12 +765,12 @@ inline void Dspark::step(RadCtx* c, const RadBatch* batch) const {
|
||||
} 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);
|
||||
w_gu[i].bref());
|
||||
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);
|
||||
RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h.x, T), RAD_NONE, w_dn[i].bref());
|
||||
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h.x, T), RAD_NONE);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,936 @@
|
||||
/* rad_block_dspark_bf16.h -- the DSpark drafter over bf16 weights, at the widths a Spark layer
|
||||
* uses: a few plain attention layers that denoise a whole block of masked positions in one pass,
|
||||
* conditioned on the trunk's residual stream at a handful of layers, with a rank-N Markov head
|
||||
* over the target's own output table.
|
||||
*
|
||||
* ============================== WHY A SECOND DSPARK BLOCK ==============================
|
||||
*
|
||||
* rad_block_dspark.h is the same drafter shape for a block-fp8 release: its linears are DenseQ
|
||||
* behind `quant_act_fp8`, its feed-forward is `silu_mul`, its norms carry q/k gains, and its draft
|
||||
* head is a 2-bit copy of the target's. The published Spark drafts (`dflash` GGUFs, and the HF
|
||||
* Spark drafter releases behind them) ship the other way: bf16 linears, no q/k norms, one sigmoid
|
||||
* gate a head on the attention output, exact-erf GELU, one RMS gain per tap, and a sliding window.
|
||||
* Those are different ops, not different parameters, so this block declares its own graph and
|
||||
* uses an explicit anchor-window attention op and a full-vocabulary Markov selector so neither
|
||||
* semantic distinction is silently folded into the generic per-row window or candidate-lattice ops.
|
||||
*
|
||||
* Nothing here is quantised. The drafter is 624M parameters read whole a draft pass, so bf16 costs
|
||||
* 1.2 GiB of residency and one extra weight pass a step; quantising it is a separate measurement
|
||||
* (it can only move acceptance, since every draft is verified by the target).
|
||||
*
|
||||
* ============================== THE FORWARD PASS ==============================
|
||||
*
|
||||
* The reference is llama.cpp's `llama_model_dflash::graph<false>` (XHToken/llama.cpp
|
||||
* 22c0ae1871b, the branch the Spark draft cards name), which mirrors the HF export:
|
||||
*
|
||||
* tap(l) = rmsnorm(residual after trunk layer l) * fc_norm[l] one gain row per tap
|
||||
* ctx = rmsnorm(fc(concat_l tap(l))) hidden_norm
|
||||
* per draft layer (x5):
|
||||
* h_n = input_layernorm(h)
|
||||
* q,k,v = q_proj/k_proj/v_proj(h_n); k_ctx, v_ctx = k_proj/v_proj(ctx)
|
||||
* rope(q, k); attention over [the layer's context K/V, this block] non-causally,
|
||||
* inside a `window` positions
|
||||
* h += o_proj(sigmoid(g_proj(h)) * attn) one gate a head, no q/k norms
|
||||
* h += mlp(post_attention_layernorm(h)) gelu(gate) * up, then down
|
||||
* logits = target.lm_head(output_norm(h)) + markov_w2 @ markov_w1[prev]
|
||||
*
|
||||
* The two projections of `ctx` are the drafter's own k_proj and v_proj, one pair per layer, and
|
||||
* they run over every committed token; the drafter's layers never see the context rows. That is
|
||||
* the context pass below, and the block above is the query pass -- the same split
|
||||
* rad_block_dspark.h makes, and the same `RAD_DRAFT_BLOCK` drive.
|
||||
*
|
||||
* ============================== THE TAPS ARE NORMED, NOT JUST READ ==================
|
||||
*
|
||||
* `fc_norm` is [n_taps, n_embd]: the residual entering each tap layer is normed with its own gain
|
||||
* before the concatenation, so `fc` sees n_taps unit-scaled streams instead of one sum whose
|
||||
* magnitudes the trunk happens to have. One `rmsnorm` per tap over that tap's column slice of the
|
||||
* tap buffer, into the same slice layout of a normed copy; `fc` then reads one contiguous
|
||||
* [n_taps * n_embd] row.
|
||||
*
|
||||
* ============================== THE SHARED ANCHOR WINDOW ==========================
|
||||
*
|
||||
* The pinned llama.cpp oracle increments the configured history from 512 to 513 and repeats the
|
||||
* anchor row's mask for every row in the denoising block. `attn_paged_anchor_window` implements
|
||||
* that exact predicate: every row sees keys through the end of the staged context whose absolute
|
||||
* position is less than 513 behind the anchor. The query row does not move the lower cutoff. The
|
||||
* same 513-token width is passed to the KV group and scheduler, so rollback, cache recycling and
|
||||
* block staging all retain the exact history the drafter reads.
|
||||
*
|
||||
* ============================== ROW ALIGNMENT ==============================
|
||||
*
|
||||
* Every row predicts, the anchor included (`dflash.sample_from_anchor`, which the GGUF import
|
||||
* refuses when false): row j of [anchor, MASK x (block-1)] proposes the token at the anchor's
|
||||
* position plus j + 1, so `steps()` is `block` and the head runs over all the block's rows. The
|
||||
* core stages the block against `RadDrafterDecl::block` and runs the head over the last `depth`
|
||||
* rows, which covers this and Dflash2's shift-by-one convention (abi/rad_builder.h).
|
||||
*
|
||||
* ============================== THE MARKOV HEAD ==============================
|
||||
*
|
||||
* The draft logits get a learned bigram bias
|
||||
*
|
||||
* score[l, token] = logits[l, token] + markov_w2[token] . markov_w1[prev(l)]
|
||||
* prev(0) = the anchor; prev(l) = the greedy token chosen at l - 1
|
||||
*
|
||||
* `dflash_markov_greedy` scans the full vocabulary at every position and greedily chooses the
|
||||
* largest biased score, following the structure of the pinned reference's serial Markov walk.
|
||||
* Base logits are F32; reduction order and tie behavior can still differ from the reference. It
|
||||
* does not prune to the base head's top K, use a joint-path heap, or apply confidence to logits.
|
||||
*
|
||||
* The confidence head (`conf_proj`, one sigmoid a position predicting acceptance) is imported and
|
||||
* ignored: it exists to let a serving loop cut the block short, this engine's depth is fixed at
|
||||
* declare, and it changes nothing the drafter proposes.
|
||||
*
|
||||
* ============================== PRECISION ==============================
|
||||
*
|
||||
* bf16 for every weight and activation except the residual stream, which is f32 exactly as the
|
||||
* Spark trunk keeps it (rad_block_dspark.h's fp8 graphs fold the residual into the norm; here the
|
||||
* norms read the f32 stream and write bf16, and `add` keeps the sum in f32). The reference runs
|
||||
* bf16 weights against an f32 residual, so rounding the drafter's stream to bf16 would be a third
|
||||
* opinion on every layer's output for no saved bytes worth having at `block` rows.
|
||||
*
|
||||
* ============================== NOT DONE ==============================
|
||||
*
|
||||
* The head and full-vocabulary Markov scan are read replicated, so a vocab-sharded deployment
|
||||
* cannot draft with them. The plugin refuses `world > 1` rather than scoring only one rank's
|
||||
* slice of the vocabulary.
|
||||
*
|
||||
* The drafter's linears are four GEMMs and one attention a layer with no folding: the norms are
|
||||
* plain `rmsnorm`, not a fused norm-add-quantise, because nothing here quantises. At seven rows
|
||||
* a pass the launches, not the bytes, are the cost.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_DSPARK_BF16_H
|
||||
#define RAD_BLOCK_DSPARK_BF16_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
#define DS_REFUSED(...) ::rad::arch::declare_refused("DSpark drafter", { __VA_ARGS__ })
|
||||
|
||||
struct DsparkBF16 {
|
||||
enum { MAX_LAYERS = 8 };
|
||||
|
||||
/* The drafter's config beyond its geometry. Everything here comes from the container's
|
||||
* `draft.` keys; nothing is defaulted quietly, because a silently ignored gate or window only
|
||||
* moves acceptance, which is the one number the user cannot see. */
|
||||
struct Config {
|
||||
int64_t n_taps = 0; /* how many trunk layers `fc` concatenates */
|
||||
int64_t block = 0; /* noise rows a sequence, and drafts (one per row) */
|
||||
int64_t rank = 0; /* markov_rank: the codebooks' width */
|
||||
int64_t window = 0; /* reference's anchor-aligned n_swa (configured history + 1) */
|
||||
int64_t rot = 0; /* rotary dimensions a head; 0 for all of head_dim */
|
||||
int causal = 0;
|
||||
int tap_norm = 0; /* `fc_norm`: one RMS gain a tap before the concatenation */
|
||||
int qk_norm = 0; /* per-head q/k gains, and no output gate */
|
||||
int gate = 0; /* one sigmoid gate a head on the attention output */
|
||||
const char* act = "gelu"; /* the feed-forward's activation */
|
||||
int64_t steps() const { return block; } /* every row predicts */
|
||||
};
|
||||
|
||||
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 srcn = 0; /* [max_tok, n_taps * n_embd] each tap normed, same layout */
|
||||
rad_buf c = 0, cn = 0; /* [max_tok, n_embd] fc output and separately normed context */
|
||||
rad_buf ck = 0, ckn = 0; /* [max_tok, kv_dim] projected and optionally normed K */
|
||||
rad_buf cv = 0; /* [max_tok, kv_dim] and its V */
|
||||
|
||||
/* ---- the query pass, `block` rows per sequence */
|
||||
rad_buf x = 0; /* [qrows, n_embd] f32 the drafter's residual stream */
|
||||
rad_buf delta = 0; /* [qrows, n_embd] f32 the block a projection just wrote */
|
||||
rad_buf h = 0; /* [qrows, n_embd] bf16 the normed stream, and every linear's output */
|
||||
rad_buf q = 0, k = 0, v = 0, qn = 0, kn = 0;
|
||||
rad_buf gate = 0, gaten = 0; /* [qrows, n_head] projection and sigmoid */
|
||||
rad_buf attn = 0, attng = 0; /* [qrows, q_dim] attention and gated attention */
|
||||
rad_buf gate_up = 0; rad_buf ff = 0;
|
||||
|
||||
/* ---- the head and the walk, one row per draft position */
|
||||
rad_buf dlog = 0; /* [srows, n_vocab] f32 full-vocabulary draft logits */
|
||||
rad_buf best_score = 0; /* [max_seqs, ceil(n_vocab/64)] f32 partial argmax scores */
|
||||
rad_buf best_token = 0; /* [max_seqs, ceil(n_vocab/64)] i32 partial argmax ids */
|
||||
rad_buf tokens = 0; /* [max_seqs, steps] i32 the draft; the engine reads it by name */
|
||||
};
|
||||
|
||||
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;
|
||||
rad_kvgroup kv = 0;
|
||||
|
||||
/* ---- model-scope weights */
|
||||
rad_weight w_fc = 0, w_hnorm = 0, w_norm = 0;
|
||||
rad_weight w_fcnorm[MAX_LAYERS] = {}; /* one row of `fc_norm` a tap */
|
||||
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_head = 0; /* the target's output table */
|
||||
|
||||
/* ---- per-layer weights */
|
||||
rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {};
|
||||
rad_weight 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] = {}, w_gate[MAX_LAYERS] = {};
|
||||
rad_weight w_gu[MAX_LAYERS] = {}, w_dn[MAX_LAYERS] = {};
|
||||
|
||||
/* ---- the context pass */
|
||||
rad_op op_tapn[MAX_LAYERS] = {}; /* one per tap, not per layer */
|
||||
rad_op op_cfc = 0, op_cnorm = 0;
|
||||
rad_op op_ck[MAX_LAYERS] = {}, op_cv[MAX_LAYERS] = {}, op_cknorm[MAX_LAYERS] = {};
|
||||
rad_op op_crope = 0, op_cstore = 0;
|
||||
|
||||
/* ---- the query pass. The weightless ops are declared once and issued per layer; the ones
|
||||
* with weights are per layer, since a weight's prefetch interval and residency class come
|
||||
* from the op that declares it. */
|
||||
rad_op op_embed = 0, op_widen = 0, op_add = 0;
|
||||
rad_op op_anorm[MAX_LAYERS] = {}, op_fnorm[MAX_LAYERS] = {}, op_outnorm = 0;
|
||||
rad_op op_qp[MAX_LAYERS] = {}, op_kp[MAX_LAYERS] = {}, op_vp[MAX_LAYERS] = {};
|
||||
rad_op op_qn[MAX_LAYERS] = {}, op_kn[MAX_LAYERS] = {}, op_gp[MAX_LAYERS] = {};
|
||||
rad_op op_op[MAX_LAYERS] = {}, op_gu[MAX_LAYERS] = {}, op_dn[MAX_LAYERS] = {};
|
||||
rad_op op_widen2 = 0;
|
||||
rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn = 0;
|
||||
rad_op op_sig = 0, op_gate_heads = 0, op_act = 0;
|
||||
|
||||
/* ---- the head and the walk */
|
||||
rad_op op_dlogits = 0, op_markov = 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, const char* ck_head,
|
||||
const Wire& wire);
|
||||
/* The context pass, one row per committed token. */
|
||||
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 DsparkBF16::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_head, const Wire& wire) {
|
||||
g = geom; cfg = c; w = wire; first_layer = base_layer; kv = group; w_tok = tok_embd;
|
||||
if (!ck || !ck_head || !w_tok) return DS_REFUSED("ck", "ck_head", "w_tok");
|
||||
if (g.n_layer <= 0 || g.n_layer > MAX_LAYERS) {
|
||||
fprintf(stderr, "radiance: the bf16 DSpark drafter has %lld layers; this block carries at "
|
||||
"most %d\n", (long long)g.n_layer, MAX_LAYERS);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (cfg.n_taps <= 0 || cfg.n_taps > MAX_LAYERS || cfg.block < 2 || cfg.rank <= 0)
|
||||
return RAD_E_INVAL;
|
||||
if (cfg.qk_norm && cfg.gate) {
|
||||
fprintf(stderr, "radiance: the drafter declares both per-head q/k norms and a per-head "
|
||||
"output gate; no published drafter ships both, and this block would have "
|
||||
"to guess which one the checkpoint trained with\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* The full-vocabulary head and Markov scan are read replicated; partial-vocabulary drafting
|
||||
* would need an exact distributed argmax and replicated codebook access. */
|
||||
if (g.world > 1) {
|
||||
fprintf(stderr, "radiance: the bf16 DSpark drafter reads the target's whole output table "
|
||||
"and cannot draft at tp %d; run it at tp 1\n", g.world);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
const int64_t qd = q_dim(), kvd = kv_dim(), E = g.n_embd;
|
||||
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(); /* every row predicts */
|
||||
if (qrows <= 0 || srows <= 0 || cfg.rot < 0 || cfg.rot > g.head_dim || cfg.rot % 2)
|
||||
return RAD_E_INVAL;
|
||||
const int64_t rot = cfg.rot ? cfg.rot : g.head_dim;
|
||||
|
||||
/* One op declaration per kernel shape, shared by the layers: `rmsnorm`'s and `gemm_nt`'s
|
||||
* parameters are geometry, and only the weights differ per layer. */
|
||||
auto gemm = [&](int64_t rows, int64_t n, int64_t k, rad_weight wt, rad_buf x, rad_buf y) {
|
||||
return rw(b, 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(wt)),
|
||||
{x}, {y});
|
||||
};
|
||||
|
||||
/* ---------------------------------------------------------------- model-scope weights */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.fc.weight"), nm.ckpt("%s.fc.weight", ck)));
|
||||
w_fc = decl_w(b, nm.f("dspark.fc.weight"), RAD_BF16, {E, cfg.n_taps * E},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.hidden_norm.weight"),
|
||||
nm.ckpt("%s.hidden_norm.weight", ck)));
|
||||
w_hnorm = decl_w(b, nm.f("dspark.hidden_norm.weight"), RAD_BF16, {E},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.norm.weight"), nm.ckpt("%s.norm.weight", ck)));
|
||||
w_norm = decl_w(b, nm.f("dspark.norm.weight"), RAD_BF16, {E},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
if (!w_fc || !w_hnorm || !w_norm) return DS_REFUSED("w_fc", "w_hnorm", "w_norm");
|
||||
|
||||
/* `fc_norm` is [n_taps, n_embd]: one gain row a tap, read as that tap's slice. */
|
||||
if (cfg.tap_norm) {
|
||||
const char* src = nm.ckpt("%s.fc_norm.weight", ck);
|
||||
for (int64_t t = 0; t < cfg.n_taps; ++t) {
|
||||
const int i = (int)t;
|
||||
RAD_ARCH_TRY(map_rows(b, nm.f("dspark.fc_norm.%d.weight", i),
|
||||
{ { src, (int)t, 1 } }));
|
||||
w_fcnorm[i] = decl_w(b, nm.f("dspark.fc_norm.%d.weight", i), RAD_BF16, {E},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
if (!w_fcnorm[i]) return DS_REFUSED("w_fcnorm[i]");
|
||||
}
|
||||
}
|
||||
|
||||
/* The Markov codebooks, bf16, replicated over the whole vocabulary: both are [vocab, rank], so
|
||||
* `w2 @ w1[prev]` is `<w1[prev], w2[token]>`. RAD_ACCESS_VOCAB: each walk position reads one
|
||||
* predecessor row and scans every successor row. */
|
||||
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());
|
||||
if (!w_mk1 || !w_mk2) return DS_REFUSED("w_mk1", "w_mk2");
|
||||
|
||||
/* The target's output table under the drafter's own name: one stored tensor, two arch weights,
|
||||
* as rad_block_dspark.h does for its 2-bit copy. bf16 and replicated here, since the drafter
|
||||
* reads it as the head its full-vocabulary walk scores (see NOT DONE for sharding). */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.head.weight"), ck_head));
|
||||
w_head = decl_w(b, nm.f("dspark.head.weight"), RAD_BF16, {g.n_vocab_all, E},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
if (!w_head) return DS_REFUSED("w_head");
|
||||
|
||||
/* ---------------------------------------------------------------- per-layer weights
|
||||
*
|
||||
* One name map and one declaration a weight, spelled out: the list is the readable form of
|
||||
* which checkpoint tensor feeds which matmul, and a drafter has few enough of them that a
|
||||
* table would only hide it. */
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
const RadWeightGroup grp = grp_layer(first_layer + i);
|
||||
|
||||
/* A norm gain: f32, read whole, never sharded. */
|
||||
auto norm_w = [&](rad_weight* out, const char* suffix, const char* from,
|
||||
std::initializer_list<int64_t> shape) -> int {
|
||||
const char* name = nm.f("dspark.blk.%d.%s", i, suffix);
|
||||
RAD_ARCH_TRY(map_copy(b, name, nm.ckpt("%s.layers.%d.%s", ck, i, from)));
|
||||
*out = decl_w(b, name, RAD_BF16, shape, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp);
|
||||
return *out ? RAD_OK : RAD_E_INVAL;
|
||||
};
|
||||
/* A linear: bf16. More than one source is a concatenation, whose row parts say where each
|
||||
* piece begins (RadWeightDecl::row_parts), so `act_mul` can read [gate | up] as one
|
||||
* weight. */
|
||||
auto lin_w = [&](rad_weight* out, const char* suffix,
|
||||
std::initializer_list<const char*> srcs,
|
||||
std::initializer_list<int64_t> shape,
|
||||
std::initializer_list<int64_t> parts = {}) -> int {
|
||||
const char* name = nm.f("dspark.blk.%d.%s", i, suffix);
|
||||
if (srcs.size() > 1) RAD_ARCH_TRY(map_concat(b, name, srcs));
|
||||
else RAD_ARCH_TRY(map_copy(b, name, *srcs.begin()));
|
||||
*out = decl_w(b, name, RAD_BF16, shape, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp, 0,
|
||||
parts);
|
||||
return *out ? RAD_OK : RAD_E_INVAL;
|
||||
};
|
||||
|
||||
#define SRC(path) nm.ckpt("%s.layers.%d." path, ck, i)
|
||||
RAD_ARCH_TRY(norm_w(&w_anorm[i], "attn_norm.weight", "input_layernorm.weight", {E}));
|
||||
RAD_ARCH_TRY(norm_w(&w_fnorm[i], "ffn_norm.weight", "post_attention_layernorm.weight", {E}));
|
||||
RAD_ARCH_TRY(lin_w(&w_q[i], "attn_q", { SRC("self_attn.q_proj.weight") }, {qd, E}));
|
||||
RAD_ARCH_TRY(lin_w(&w_k[i], "attn_k", { SRC("self_attn.k_proj.weight") }, {kvd, E}));
|
||||
RAD_ARCH_TRY(lin_w(&w_v[i], "attn_v", { SRC("self_attn.v_proj.weight") }, {kvd, E}));
|
||||
RAD_ARCH_TRY(lin_w(&w_o[i], "attn_output", { SRC("self_attn.o_proj.weight") }, {E, qd}));
|
||||
RAD_ARCH_TRY(lin_w(&w_gu[i], "ffn_gate_up",
|
||||
{ SRC("mlp.gate_proj.weight"), SRC("mlp.up_proj.weight") },
|
||||
{2 * g.n_ff, E}, { g.n_ff, g.n_ff }));
|
||||
RAD_ARCH_TRY(lin_w(&w_dn[i], "ffn_down", { SRC("mlp.down_proj.weight") },
|
||||
{E, g.n_ff}));
|
||||
if (cfg.gate)
|
||||
RAD_ARCH_TRY(lin_w(&w_gate[i], "attn_gate", { SRC("self_attn.g_proj.weight") },
|
||||
{g.n_head, E}));
|
||||
if (cfg.qk_norm) {
|
||||
RAD_ARCH_TRY(norm_w(&w_qn[i], "attn_q_norm.weight", "self_attn.q_norm.weight",
|
||||
{g.head_dim}));
|
||||
RAD_ARCH_TRY(norm_w(&w_kn[i], "attn_k_norm.weight", "self_attn.k_norm.weight",
|
||||
{g.head_dim}));
|
||||
}
|
||||
#undef SRC
|
||||
}
|
||||
|
||||
/* Non-causal: every query row sees its whole block and the context the trunk committed
|
||||
* (`causal` comes from `draft.is_causal`). Declared before both kv_stores, which read the
|
||||
* resolved `block_size` back with rad_kv_block_size(); before it, that returns zero. */
|
||||
op_attn = rw(b, RAD_OP(b, cfg.window > 0 ? "attn_paged_anchor_window" : "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", "bf16"), RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{cfg.qk_norm ? w.qn : w.q}, {w.attn});
|
||||
if (!op_attn) return DS_REFUSED("op_attn");
|
||||
|
||||
/* ---------------------------------------------------------------- the context pass
|
||||
*
|
||||
* One row per committed token, run once per trunk step: the taps become the drafter's own K
|
||||
* and V. Nothing here is per query row, so its cost follows the trunk's token count, not the
|
||||
* block's. */
|
||||
for (int64_t t = 0; t < cfg.n_taps; ++t) {
|
||||
const int i = (int)t;
|
||||
op_tapn[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", E),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_fcnorm[i])),
|
||||
{w.src}, {w.srcn});
|
||||
if (!op_tapn[i]) return DS_REFUSED("op_tapn[i]");
|
||||
}
|
||||
op_cfc = gemm(crows, E, cfg.n_taps * E, w_fc, w.srcn, w.c);
|
||||
op_cnorm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", E),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_hnorm)),
|
||||
{w.c}, {w.cn});
|
||||
if (!op_cfc || !op_cnorm) return DS_REFUSED("op_cfc", "op_cnorm");
|
||||
|
||||
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] = gemm(crows, kvd, E, w_k[i], w.cn, w.ck);
|
||||
op_cv[i] = gemm(crows, kvd, E, w_v[i], w.cn, w.cv);
|
||||
if (!op_ck[i] || !op_cv[i]) return DS_REFUSED("op_ck[i]", "op_cv[i]");
|
||||
if (cfg.qk_norm) {
|
||||
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", "bf16")),
|
||||
RAD_WEIGHTS(w_kn[i])),
|
||||
{w.ck}, {w.ckn});
|
||||
if (!op_cknorm[i]) return DS_REFUSED("op_cknorm[i]");
|
||||
}
|
||||
}
|
||||
|
||||
/* 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 the reference's single concatenated rope
|
||||
* does. */
|
||||
op_crope = rw(b, decl_rope(b, g, crows, g.head_dim, g.n_head_kv, 0, rot, "neox"),
|
||||
{cfg.qk_norm ? w.ckn : w.ck}, {cfg.qk_norm ? w.ckn : 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),
|
||||
{cfg.qk_norm ? w.ckn : w.ck, w.cv}, {});
|
||||
if (!op_crope || !op_cstore) return DS_REFUSED("op_crope", "op_cstore");
|
||||
|
||||
/* ---------------------------------------------------------------- the query pass
|
||||
*
|
||||
* `block` rows per sequence, through the drafter's layers. The residual stream is f32 and the
|
||||
* linears read bf16, exactly as the trunk keeps them: `rmsnorm` reads the stream and writes the
|
||||
* activations, `cast` widens a projection's output, and `add` keeps the sum in f32. */
|
||||
op_embed = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n_embd", E),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
|
||||
RAD_INT("vocab_offset", g.vocab_off)),
|
||||
RAD_WEIGHTS(w_tok)),
|
||||
{}, {w.h});
|
||||
op_widen = cast_op(b, qrows, E, "bf16", "f32", w.h, w.x);
|
||||
/* One widen and one add serve both residual sites a layer: same shapes, same buffers. */
|
||||
op_widen2 = cast_op(b, qrows, E, "bf16", "f32", w.h, w.delta);
|
||||
op_add = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
|
||||
RAD_STR("dtype", "f32")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.x, w.delta}, {w.x});
|
||||
if (!op_embed || !op_widen || !op_widen2 || !op_add)
|
||||
return DS_REFUSED("op_embed", "op_widen", "op_widen2", "op_add");
|
||||
|
||||
/* Invariant: the norms are declared where step() issues them. Declaration order is the buffer
|
||||
* planner's liveness (core/build/rad_bufplan.cpp), and the stream `x` lives over the ops that
|
||||
* touch it: each layer's two norms in the loop, the final one after everything the layers
|
||||
* issue. 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] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_anorm[i])),
|
||||
{w.x}, {w.h});
|
||||
op_qp[i] = gemm(qrows, qd, E, w_q[i], w.h, w.q);
|
||||
op_kp[i] = gemm(qrows, kvd, E, w_k[i], w.h, w.k);
|
||||
op_vp[i] = gemm(qrows, kvd, E, w_v[i], w.h, w.v);
|
||||
op_op[i] = gemm(qrows, E, qd, w_o[i], cfg.gate ? w.attng : w.attn, w.h);
|
||||
op_fnorm[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_fnorm[i])),
|
||||
{w.x}, {w.h});
|
||||
op_gu[i] = gemm(qrows, 2 * g.n_ff, E, w_gu[i], w.h, w.gate_up);
|
||||
op_dn[i] = gemm(qrows, E, g.n_ff, w_dn[i], w.ff, w.h);
|
||||
if (!op_anorm[i] || !op_qp[i] || !op_kp[i] || !op_vp[i] || !op_op[i] || !op_fnorm[i] ||
|
||||
!op_gu[i] || !op_dn[i])
|
||||
return RAD_E_INVAL;
|
||||
if (cfg.qk_norm) {
|
||||
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", "bf16")),
|
||||
RAD_WEIGHTS(w_qn[i])),
|
||||
{w.q}, {w.qn});
|
||||
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", "bf16")),
|
||||
RAD_WEIGHTS(w_kn[i])),
|
||||
{w.k}, {w.kn});
|
||||
if (!op_qn[i] || !op_kn[i]) return DS_REFUSED("op_qn[i]", "op_kn[i]");
|
||||
}
|
||||
if (cfg.gate) {
|
||||
op_gp[i] = gemm(qrows, g.n_head, E, w_gate[i], w.h, w.gate);
|
||||
if (!op_gp[i]) return DS_REFUSED("op_gp[i]");
|
||||
}
|
||||
}
|
||||
|
||||
op_qrope = rw(b, decl_rope(b, g, qrows, g.head_dim, g.n_head, 0, rot, "neox"),
|
||||
{cfg.qk_norm ? w.qn : w.q}, {cfg.qk_norm ? w.qn : w.q});
|
||||
op_krope = rw(b, decl_rope(b, g, qrows, g.head_dim, g.n_head_kv, 0, rot, "neox"),
|
||||
{cfg.qk_norm ? w.kn : w.k}, {cfg.qk_norm ? w.kn : 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),
|
||||
{cfg.qk_norm ? w.kn : w.k, w.v}, {});
|
||||
/* The gate the trunk uses too: one sigmoid a head, then one scale a head's whole row. */
|
||||
if (cfg.gate) {
|
||||
op_sig = rw(b, RAD_OP(b, "sigmoid",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_head),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.gate}, {w.gaten});
|
||||
op_gate_heads = rw(b, RAD_OP(b, "scale_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head),
|
||||
RAD_INT("n", g.head_dim), RAD_STR("act", "none"),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.attn, w.gaten}, {w.attng});
|
||||
if (!op_sig || !op_gate_heads) return DS_REFUSED("op_sig", "op_gate_heads");
|
||||
}
|
||||
/* `act_mul` with the activation the drafter was trained with: exact-erf gelu for the Spark
|
||||
* drafts (`hidden_activation: gelu`), silu for a Qwen3-shaped one. `gelu_mul` is the tanh
|
||||
* approximation and is not what the reference runs. */
|
||||
op_act = rw(b, RAD_OP(b, "act_mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff),
|
||||
RAD_STR("act", cfg.act), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.gate_up}, {w.ff});
|
||||
op_outnorm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_norm)),
|
||||
{w.x}, {w.h});
|
||||
if (!op_qrope || !op_krope || !op_store || !op_act || !op_outnorm)
|
||||
return DS_REFUSED("op_qrope", "op_krope", "op_store", "op_act", "op_outnorm");
|
||||
|
||||
/* ---------------------------------------------------------------- the head and full-vocabulary walk
|
||||
*
|
||||
* Every row predicts, so the head scores all `steps` rows, anchor included. The row order is
|
||||
* sequence-major, which is the selector's [sequence, position, vocabulary] contract. The
|
||||
* greedy Markov op scans all vocabulary entries at every position and feeds each winning id
|
||||
* into the next position's bigram bias.
|
||||
*/
|
||||
op_dlogits = rw(b, RAD_OP(b, "logits_gemm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n_vocab", g.n_vocab),
|
||||
RAD_INT("n_embd", E), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_head)),
|
||||
{w.h}, {w.dlog});
|
||||
op_markov = rw(b, RAD_OP(b, "dflash_markov_greedy_f32",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs),
|
||||
RAD_INT("steps", cfg.steps()), RAD_INT("rank", cfg.rank),
|
||||
RAD_INT("n_vocab", g.n_vocab_all),
|
||||
RAD_INT("anchor_stride", cfg.block),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_mk1, w_mk2)),
|
||||
{w.dlog}, {w.best_score, w.best_token, w.tokens});
|
||||
if (!op_dlogits || !op_markov) return DS_REFUSED("op_dlogits", "op_markov");
|
||||
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------------ the context pass */
|
||||
|
||||
inline void DsparkBF16::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;
|
||||
const int64_t E = g.n_embd;
|
||||
|
||||
/* Each tap's slice of the residual the trunk just tapped, normed with its own gain into the
|
||||
* same slice layout of one row-per-token buffer. */
|
||||
for (int64_t t = 0; t < cfg.n_taps; ++t) {
|
||||
const int i = (int)t;
|
||||
if (!cfg.tap_norm) continue;
|
||||
RAD_ISSUE_N(c, op_tapn[i], T, bcol(w.src, t * E, E, T), RAD_W(w_fcnorm[i]),
|
||||
bcol(w.srcn, t * E, E, T));
|
||||
}
|
||||
RAD_ISSUE_N(c, op_cfc, T, cfg.tap_norm ? brows(w.srcn, T) : brows(w.src, T), RAD_W(w_fc),
|
||||
brows(w.c, T));
|
||||
RAD_ISSUE_N(c, op_cnorm, T, brows(w.c, T), RAD_W(w_hnorm), brows(w.cn, 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.cn, T), RAD_W(w_k[i]), brows(w.ck, T));
|
||||
RAD_ISSUE_N(c, op_cv[i], T, brows(w.cn, T), RAD_W(w_v[i]), brows(w.cv, T));
|
||||
if (cfg.qk_norm)
|
||||
RAD_ISSUE_N(c, op_cknorm[i], T * g.n_head_kv, brows(w.ck, T), RAD_W(w_kn[i]),
|
||||
brows(w.ckn, T));
|
||||
RAD_ISSUE_N(c, op_crope, T, brows(cfg.qk_norm ? w.ckn : w.ck, T), praw(batch->positions, RAD_I32, T));
|
||||
RAD_ISSUE_N(c, op_cstore, T, brows(cfg.qk_norm ? w.ckn : w.ck, T), brows(w.cv, T),
|
||||
praw(slot, RAD_I32, T), kv_cache(kv, first_layer + i));
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------------ the query pass */
|
||||
|
||||
inline void DsparkBF16::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 RadOperand pos = praw(batch->positions, RAD_I32, T);
|
||||
|
||||
/* The block the core staged: the token the sampler just chose, then the mask token in every
|
||||
* unfilled slot. */
|
||||
RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w_tok), brows(w.h, T));
|
||||
RAD_ISSUE_N(c, op_widen, T, brows(w.h, T), brows(w.x, T));
|
||||
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
|
||||
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_qp[i], T, brows(w.h, T), RAD_W(w_q[i]), brows(w.q, T));
|
||||
RAD_ISSUE_N(c, op_kp[i], T, brows(w.h, T), RAD_W(w_k[i]), brows(w.k, T));
|
||||
RAD_ISSUE_N(c, op_vp[i], T, brows(w.h, T), RAD_W(w_v[i]), brows(w.v, T));
|
||||
if (cfg.qk_norm) {
|
||||
RAD_ISSUE_N(c, op_qn[i], T * g.n_head, brows(w.q, T), RAD_W(w_qn[i]), brows(w.qn, T));
|
||||
RAD_ISSUE_N(c, op_kn[i], T * g.n_head_kv, brows(w.k, T), RAD_W(w_kn[i]),
|
||||
brows(w.kn, T));
|
||||
}
|
||||
RAD_ISSUE_N(c, op_qrope, T, brows(cfg.qk_norm ? w.qn : w.q, T), pos);
|
||||
RAD_ISSUE_N(c, op_krope, T, brows(cfg.qk_norm ? w.kn : w.k, T), pos);
|
||||
/* The block's own K and V go into the cache past `seqused`, which is how every row of the
|
||||
* block attends to every other; the next context pass overwrites them, which is the
|
||||
* reference's `crop(start)`. */
|
||||
RAD_ISSUE_N(c, op_store, T, brows(cfg.qk_norm ? w.kn : 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(cfg.qk_norm ? w.qn : 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));
|
||||
if (cfg.gate) {
|
||||
/* One gate a head, applied to that head's whole row of the attention output, before
|
||||
* o_proj. View [rows, heads * dim] and [rows, heads] as one row a head. */
|
||||
RAD_ISSUE_N(c, op_gp[i], T, brows(w.h, T), RAD_W(w_gate[i]), brows(w.gate, T));
|
||||
RAD_ISSUE_N(c, op_sig, T, brows(w.gate, T), brows(w.gaten, T));
|
||||
const RadOperand heads = RAD_P_T2(rad_buf_ptr(c, w.attn), RAD_BF16, T * g.n_head,
|
||||
g.head_dim);
|
||||
const RadOperand gates = RAD_P_T2(rad_buf_ptr(c, w.gaten), RAD_BF16, T * g.n_head, 1);
|
||||
const RadOperand gated = RAD_P_T2(rad_buf_ptr(c, w.attng), RAD_BF16, T * g.n_head,
|
||||
g.head_dim);
|
||||
RAD_ISSUE_N(c, op_gate_heads, T * g.n_head, heads, gates, RAD_NONE, gated);
|
||||
}
|
||||
RAD_ISSUE_N(c, op_op[i], T, brows(cfg.gate ? w.attng : w.attn, T), RAD_W(w_o[i]), brows(w.h, T));
|
||||
RAD_ISSUE_N(c, op_widen2, T, brows(w.h, T), brows(w.delta, T));
|
||||
RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.delta, 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_gu[i], T, brows(w.h, T), RAD_W(w_gu[i]), brows(w.gate_up, T));
|
||||
RAD_ISSUE_N(c, op_act, T, bcol(w.gate_up, 0, g.n_ff, T),
|
||||
bcol(w.gate_up, g.n_ff, g.n_ff, T), brows(w.ff, T));
|
||||
RAD_ISSUE_N(c, op_dn[i], T, brows(w.ff, T), RAD_W(w_dn[i]), brows(w.h, T));
|
||||
RAD_ISSUE_N(c, op_widen2, T, brows(w.h, T), brows(w.delta, T));
|
||||
RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.delta, T), brows(w.x, T));
|
||||
}
|
||||
|
||||
RAD_ISSUE_N(c, op_outnorm, T, brows(w.x, T), RAD_W(w_norm), brows(w.h, T));
|
||||
|
||||
/* The predicting rows, named by the scheduler through `out_ids`. */
|
||||
const int64_t S = batch->n_out;
|
||||
if (S <= 0) return;
|
||||
RAD_ISSUE_N(c, op_dlogits, S, brows(w.h, S), RAD_W(w_head), brows(w.dlog, S));
|
||||
RAD_ISSUE_N(c, op_markov, batch->n_seq, brows(w.dlog, S),
|
||||
praw(batch->token_ids, RAD_I32, T), RAD_W(w_mk1), RAD_W(w_mk2),
|
||||
brows(w.best_score, batch->n_seq), brows(w.best_token, batch->n_seq),
|
||||
brows(w.tokens, batch->n_seq));
|
||||
}
|
||||
|
||||
/* ================================================================== the trunk's side of it
|
||||
*
|
||||
* The taps, and one call a target plugin makes to put a drafter on. Both live here because both
|
||||
* are the drafter's contract with the trunk: which residual streams it reads, where its blocks
|
||||
* live, and how deep a proposal it makes. */
|
||||
|
||||
/* The residual streams a drafter reads, captured as the trunk passes them. */
|
||||
struct DsparkTaps {
|
||||
enum { MAX_TAPS = DsparkBF16::MAX_LAYERS };
|
||||
|
||||
int n = 0;
|
||||
int layer[MAX_TAPS] = {}; /* the trunk layer whose OUTPUT is tapped */
|
||||
rad_buf src = 0; /* [rows, n * n_embd] f32, one column slice a tap */
|
||||
rad_op op = 0; /* the residual stream, copied into that slice */
|
||||
|
||||
/* Read `draft.target_layer_ids`, which names the layers whose output is tapped. Zero taps when
|
||||
* the container carries no drafter, or one that reads no trunk stream. Out-of-range ids are
|
||||
* dropped, not clamped: a drafter naming a layer this model lacks belongs to another target. */
|
||||
int read(const RadModelMeta* meta, int64_t n_layer) {
|
||||
n = 0;
|
||||
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);
|
||||
if (!ids) ids = rad_meta_gets(meta, "draft.gguf_target_layers", nullptr);
|
||||
n = parse_layer_ids(ids, n_layer, layer, MAX_TAPS);
|
||||
return n;
|
||||
}
|
||||
|
||||
/* The copy that saves a tap. A drafter reads the trunk's own residual stream, which is f32
|
||||
* here and stays f32: the widening the fp8 graphs do is theirs, not this one's. */
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& g, int64_t rows, rad_buf residual) {
|
||||
if (n <= 0) return RAD_OK;
|
||||
src = decl_b(b, nm.f("draft_src"), RAD_F32, {rows, (int64_t)n * g.n_embd});
|
||||
if (!src) return DS_REFUSED("src");
|
||||
/* Declared over the trunk's own residual buffer: the op's operand pair is the stream and a
|
||||
* tap's slice, and every issue site passes the slice it is writing. */
|
||||
op = cast_op(b, rows, g.n_embd, "f32", "f32", residual, src);
|
||||
return op ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* The tap that follows trunk layer `l`, if any. Issued on prefill and decode alike: the
|
||||
* drafter conditions on every committed token's residual stream. */
|
||||
void step(RadCtx* c, rad_buf residual, int64_t rows, int64_t l, int64_t n_embd) const {
|
||||
if (!op) return;
|
||||
for (int t = 0; t < n; ++t)
|
||||
if (layer[t] == l)
|
||||
RAD_ISSUE(c, op, brows(residual, rows),
|
||||
bcol(src, (int64_t)t * n_embd, n_embd, rows));
|
||||
}
|
||||
};
|
||||
|
||||
/* Put a DSpark drafter on a trunk: its config from the container's `draft.` keys, its own KV
|
||||
* group, its graph, and the drafter declaration the core drives. `base_layer` is the absolute
|
||||
* layer its first block takes, one past the trunk's last.
|
||||
*
|
||||
* Nothing is defaulted quietly. A `draft.` key that describes a drafter this file does not
|
||||
* implement is refused by name, because a silently ignored gate, window or block length only moves
|
||||
* acceptance -- the one number a user cannot see in the output.
|
||||
*
|
||||
* The plugin calls it last, after its own head and logits: a drafter's passes run after the whole
|
||||
* trunk, and the buffer planner lays an op's lifetimes out in declaration order, so declaring it
|
||||
* earlier would let a trunk temporary land on the stream the drafter is still reading. */
|
||||
inline int declare_dspark(DsparkBF16* ds, DsparkBF16::Wire* w, rad_kvgroup* kv, RadBuilder* b,
|
||||
Names& nm, const RadModelMeta* meta, const RadBuildCtx* ctx,
|
||||
const Geom& target, const DsparkTaps& taps, int base_layer,
|
||||
rad_weight tok_embd, const char* ck_head) {
|
||||
Geom dg{};
|
||||
RAD_ARCH_TRY(drafter_geom(dg, target, meta, "DSpark"));
|
||||
/* The width the drafter concatenates and projects is the trunk's, and `drafter_geom` keeps the
|
||||
* target's -- so a draft that disagrees is a draft for another model, and its `fc` would be
|
||||
* read at a shape it was not trained at. */
|
||||
const int64_t want_embd = rad_meta_geti(meta, "draft.hidden_size",
|
||||
rad_meta_geti(meta, "draft.dflash_config.hidden_size",
|
||||
dg.n_embd));
|
||||
if (want_embd != dg.n_embd) {
|
||||
fprintf(stderr, "radiance: the drafter reads a %lld-wide trunk and this target is %lld "
|
||||
"wide; they are not the same model\n", (long long)want_embd,
|
||||
(long long)dg.n_embd);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
DsparkBF16::Config c{};
|
||||
c.n_taps = taps.n;
|
||||
c.rank = rad_meta_geti(meta, "draft.markov_rank", 0);
|
||||
c.causal = rad_meta_geti(meta, "draft.is_causal", 0) ? 1 : 0;
|
||||
c.tap_norm = rad_meta_geti(meta, "draft.fc_norm", 0) ? 1 : 0;
|
||||
c.qk_norm = rad_meta_geti(meta, "draft.qk_norm", 0) ? 1 : 0;
|
||||
c.gate = rad_meta_geti(meta, "draft.headwise_attn_output_gate", 0) ? 1 : 0;
|
||||
const char* act = rad_meta_gets(meta, "draft.hidden_act", "silu");
|
||||
c.act = (!std::strcmp(act, "gelu") || !std::strcmp(act, "none")) ? "gelu"
|
||||
: (!std::strcmp(act, "silu")) ? "silu" : nullptr;
|
||||
if (!c.act) {
|
||||
fprintf(stderr, "radiance: the drafter's feed-forward is '%s'; this block runs exact-erf "
|
||||
"gelu (what the Spark drafts train with) or silu, and the two are not the "
|
||||
"same function\n", act);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const char* gate_mode = rad_meta_gets(meta, "draft.gate_attn_act_mode", "sigmoid");
|
||||
if (c.gate && std::strcmp(gate_mode, "sigmoid")) {
|
||||
fprintf(stderr, "radiance: the drafter gates its attention output with '%s'; this block "
|
||||
"applies a sigmoid\n", gate_mode);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* Every row predicts, the anchor included. Without it a block row's worth of proposals is
|
||||
* missing and the head reads rows the drafter never filled. */
|
||||
if (!rad_meta_geti(meta, "draft.sample_from_anchor", 1)) {
|
||||
fprintf(stderr, "radiance: the drafter declares sample_from_anchor false, whose bonus "
|
||||
"anchor slot this block has no rows for\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* The reference applies the bigram bias to the full vocabulary before each greedy choice. */
|
||||
if (c.rank <= 0 || c.rank % 32 || c.rank > 512) {
|
||||
fprintf(stderr, "radiance: the drafter's Markov head has rank %lld; the walk that applies "
|
||||
"the bigram bias takes a multiple of 32 up to 512\n", (long long)c.rank);
|
||||
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` rather than the
|
||||
* `block_size - 1` a DFlash2 container's is. A block-diffusion drafter is trained for one
|
||||
* block length and has no partial block, so any other depth is refused. */
|
||||
const int64_t trained = rad_meta_geti(meta, "draft.block_size", 0);
|
||||
if (trained < 2) {
|
||||
fprintf(stderr, "radiance: this drafter 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 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",
|
||||
(long long)trained, (long long)trained, ctx->max_spec, (long long)trained);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
c.block = trained;
|
||||
|
||||
/* The reference gives every row of the block the anchor's history. `window` is the configured
|
||||
* number of preceding positions; llama.cpp sets n_swa to window + 1 and masks when
|
||||
* anchor - key >= n_swa. Keep that exact width in attention, the KV group and scheduler. */
|
||||
int64_t window = 0;
|
||||
if (rad_meta_geti(meta, "draft.use_sliding_window", 0))
|
||||
window = rad_meta_geti(meta, "draft.sliding_window", 0);
|
||||
if (window < 0 || (window && window < c.block)) {
|
||||
fprintf(stderr, "radiance: the drafter's %lld-token window does not cover the %lld-token "
|
||||
"block it denoises\n", (long long)window, (long long)c.block);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (window > 0 && window == INT64_MAX) return RAD_E_INVAL;
|
||||
c.window = window > 0 ? window + 1 : 0; /* llama.cpp dflash: n_swa += 1 */
|
||||
const double prf = rad_meta_getf(meta, "draft.partial_rotary_factor",
|
||||
rad_meta_getf(meta,
|
||||
"draft.rope_parameters.partial_rotary_factor", 1.0));
|
||||
const double rot = (double)dg.head_dim * prf;
|
||||
if (!(prf > 0.0) && prf != 0.0) {
|
||||
fprintf(stderr, "radiance: the drafter's partial_rotary_factor is %g\n", prf);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (std::floor(rot) != rot || (int64_t)rot % 2 || rot > (double)dg.head_dim) {
|
||||
fprintf(stderr, "radiance: the drafter rotates %g of %lld head dimensions\n", rot,
|
||||
(long long)dg.head_dim);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
c.rot = (int64_t)rot ? (int64_t)rot : dg.head_dim;
|
||||
|
||||
RAD_ARCH_TRY(drafter_kv_group(b, nm, ctx, dg, c.window, base_layer, kv));
|
||||
|
||||
/* Activations: one row per committed token for the context pass, one row per block position
|
||||
* for the query pass. Both are small; the drafter's cost is its weights. */
|
||||
const int64_t qd = dg.n_head * dg.head_dim, kvd = dg.n_head_kv * dg.head_dim;
|
||||
int64_t qr = dg.max_seqs * c.block;
|
||||
if (qr > dg.max_tok) qr = dg.max_tok;
|
||||
const int64_t sr = dg.max_seqs * c.steps();
|
||||
DsparkBF16::Wire& dw = *w;
|
||||
dw.src = taps.src;
|
||||
dw.srcn = decl_b(b, nm.f("ds_srcn"), RAD_BF16, {dg.max_tok, c.n_taps * dg.n_embd});
|
||||
dw.c = decl_b(b, nm.f("ds_c"), RAD_BF16, {dg.max_tok, dg.n_embd});
|
||||
dw.cn = decl_b(b, nm.f("ds_cn"), RAD_BF16, {dg.max_tok, dg.n_embd});
|
||||
dw.ck = decl_b(b, nm.f("ds_ck"), RAD_BF16, {dg.max_tok, kvd});
|
||||
dw.cv = decl_b(b, nm.f("ds_cv"), RAD_BF16, {dg.max_tok, kvd});
|
||||
if (c.qk_norm) dw.ckn = decl_b(b, nm.f("ds_ckn"), RAD_BF16, {dg.max_tok, kvd});
|
||||
dw.x = decl_b(b, nm.f("ds_x"), RAD_F32, {qr, dg.n_embd});
|
||||
dw.delta = decl_b(b, nm.f("ds_delta"), RAD_F32, {qr, dg.n_embd});
|
||||
dw.h = decl_b(b, nm.f("ds_h"), RAD_BF16, {qr, dg.n_embd});
|
||||
dw.q = decl_b(b, nm.f("ds_q"), RAD_BF16, {qr, qd});
|
||||
dw.k = decl_b(b, nm.f("ds_k"), RAD_BF16, {qr, kvd});
|
||||
dw.v = decl_b(b, nm.f("ds_v"), RAD_BF16, {qr, kvd});
|
||||
if (c.qk_norm) {
|
||||
dw.qn = decl_b(b, nm.f("ds_qn"), RAD_BF16, {qr, qd});
|
||||
dw.kn = decl_b(b, nm.f("ds_kn"), RAD_BF16, {qr, kvd});
|
||||
}
|
||||
dw.gate = decl_b(b, nm.f("ds_gate"), RAD_BF16, {qr, dg.n_head});
|
||||
dw.attn = decl_b(b, nm.f("ds_attn"), RAD_BF16, {qr, qd});
|
||||
if (c.gate) {
|
||||
dw.gaten = decl_b(b, nm.f("ds_gaten"), RAD_BF16, {qr, dg.n_head});
|
||||
dw.attng = decl_b(b, nm.f("ds_attng"), RAD_BF16, {qr, qd});
|
||||
}
|
||||
dw.gate_up = decl_b(b, nm.f("ds_gate_up"), RAD_BF16, {qr, 2 * dg.n_ff});
|
||||
dw.ff = decl_b(b, nm.f("ds_ff"), RAD_BF16, {qr, dg.n_ff});
|
||||
dw.dlog = decl_b(b, nm.f("ds_dlog"), RAD_F32, {sr, dg.n_vocab});
|
||||
const int64_t n_markov_tiles = (dg.n_vocab_all + 63) / 64;
|
||||
dw.best_score = decl_b(b, nm.f("ds_markov_score"), RAD_F32,
|
||||
{dg.max_seqs, n_markov_tiles});
|
||||
dw.best_token = decl_b(b, nm.f("ds_markov_token"), RAD_I32,
|
||||
{dg.max_seqs, n_markov_tiles});
|
||||
/* 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("ds_tokens"), RAD_I32, {dg.max_seqs, c.steps()});
|
||||
if (!dw.srcn || !dw.c || !dw.cn || !dw.ck || !dw.cv ||
|
||||
(c.qk_norm && (!dw.ckn || !dw.qn || !dw.kn)) ||
|
||||
(c.gate && (!dw.gaten || !dw.attng)) || !dw.x || !dw.delta || !dw.h || !dw.q || !dw.k ||
|
||||
!dw.v || !dw.gate || !dw.attn || !dw.gate_up || !dw.ff || !dw.dlog ||
|
||||
!dw.best_score || !dw.best_token || !dw.tokens)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
RAD_ARCH_TRY(ds->declare(b, nm, dg, c, base_layer, *kv, tok_embd, "draft", ck_head, dw));
|
||||
|
||||
RadDrafterDecl drf{};
|
||||
drf.name = "dspark";
|
||||
drf.kind = RAD_DRAFT_BLOCK;
|
||||
drf.depth = ctx->max_spec;
|
||||
drf.block = c.block;
|
||||
drf.proposal = dw.tokens;
|
||||
drf.proposal_pitch = c.steps();
|
||||
drf.window = c.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 drafter 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 anchor-aligned window (%lld configured "
|
||||
"history + 1), %lld of %lld rotary dimensions, %s, %s a head, %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, c.causal ? "causal" : "non-causal", (long long)c.window,
|
||||
(long long)window, (long long)c.rot, (long long)dg.head_dim, c.act,
|
||||
c.gate ? "sigmoid gate" : "no gate", (int)c.n_taps, (long long)c.block,
|
||||
(long long)c.steps());
|
||||
rad_note(b, "the rank-%lld Markov bigram head greedily scans all %lld vocabulary tokens at "
|
||||
"each draft position; confidence is not applied to logits%s",
|
||||
(long long)c.rank, (long long)dg.n_vocab_all,
|
||||
rad_meta_geti(meta, "draft.has_confidence_head", 0)
|
||||
? " (its reference role is adaptive depth, which this fixed-depth graph does not use)"
|
||||
: "");
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_DSPARK_BF16_H */
|
||||
+76
-38
@@ -3,9 +3,10 @@
|
||||
* 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)
|
||||
* rmsnorm -> in gemm ([q|k|v|a|b])
|
||||
* prefill: z gemm -> gdn_conv_prep -> gdn_kkt_solve -> gdn_chunk_scan -> gdn_gated_rmsnorm
|
||||
* decode: gdn_conv_update -> z gemm -> gdn_recurrent_update (which folds the gated norm)
|
||||
* (z after the convolution in a pure decode step; a mixed step issues it first, as prefill)
|
||||
* -> out gemm -> [all_reduce] -> residual add
|
||||
*
|
||||
* The two paths branch on phase, which spec §10 allows: both sequences are declared, resolved
|
||||
@@ -42,6 +43,7 @@
|
||||
#define RAD_BLOCK_GDN_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
#include "rad_norm_bf16.h"
|
||||
|
||||
#include <cmath>
|
||||
|
||||
@@ -105,14 +107,34 @@ struct GdnBF16 {
|
||||
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;
|
||||
/* The fold (rad_norm_bf16.h): the norm may take the previous block's delta and all-reduce,
|
||||
* and this block may leave its own to the next block's norm (`ar_out`, NormBF16::takes_ar). */
|
||||
NormBF16 nq{};
|
||||
bool ar_out = false;
|
||||
/* Set by the architecture after declare, `prefetch`es (decl_prefetch, rad_arch.h); 0 where
|
||||
* none is declared:
|
||||
* op_pf / pf_w of the next GEMM's leading weight bytes, issued after out and before this
|
||||
* block's own all-reduce where it issues one, so it is beside the reduction
|
||||
* whether this block or the next norm runs it (prefetch_beside);
|
||||
* op_pf_out of the out-projection's leading bytes beside the decode recurrent update (as
|
||||
* GdnQ::op_pf_out), issued right before it in a pure decode step of at most
|
||||
* pf_out_seqs sequences. */
|
||||
rad_op op_pf = 0;
|
||||
rad_weight pf_w = 0;
|
||||
rad_op op_pf_out = 0;
|
||||
int64_t pf_out_seqs = 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);
|
||||
rad_kvgroup state, rad_kvgroup conv, const Wire& wire, const Src& s,
|
||||
bool fold = false, bool add_out = true,
|
||||
bool ar_in = false, bool ar_out_ = false);
|
||||
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) {
|
||||
rad_kvgroup state, rad_kvgroup conv, const Wire& wire, const Src& s,
|
||||
bool fold, bool add_out, bool ar_in, bool ar_out_) {
|
||||
ar_out = ar_out_;
|
||||
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)
|
||||
@@ -155,11 +177,13 @@ inline int GdnBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
|
||||
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));
|
||||
const LinearBF16 in = decl_linear_bf16(b, g, nm.f("blk.%d.ssm_in.weight", l),
|
||||
{in_dim, g.n_embd}, RAD_SHARD_ROW, grp_layer(l),
|
||||
{cfg.k_dim(), cfg.k_dim(), cfg.v_dim(), cfg.n_head_v,
|
||||
cfg.n_head_v});
|
||||
const LinearBF16 z = decl_linear_bf16(b, g, nm.f("blk.%d.ssm_z.weight", l),
|
||||
{v_dim, g.n_embd}, RAD_SHARD_ROW, grp_layer(l));
|
||||
w_in = in.w; w_z = z.w;
|
||||
/* 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. */
|
||||
@@ -174,20 +198,19 @@ inline int GdnBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
/* 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));
|
||||
const LinearBF16 out = decl_linear_bf16(b, g, nm.f("blk.%d.ssm_out.weight", l),
|
||||
{g.n_embd, v_dim}, RAD_SHARD_COL, grp_layer(l));
|
||||
w_out = out.w;
|
||||
|
||||
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});
|
||||
RAD_ARCH_TRY(nq.declare(b, g, w_norm, w.x, w.h, fold, ar_in));
|
||||
op_norm = nq.op_norm;
|
||||
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_INT("K", g.n_embd), RAD_STR("dtype", in.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_INT("K", g.n_embd), RAD_STR("dtype", z.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
|
||||
@@ -245,22 +268,17 @@ inline int GdnBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
|
||||
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_INT("K", v_dim), RAD_STR("dtype", out.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});
|
||||
op_ar = decl_all_reduce(b, g, w.h);
|
||||
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}, {w.x});
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -278,17 +296,28 @@ inline void GdnBF16::step(RadCtx* c, const RadBatch* batch) const {
|
||||
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
|
||||
/* Each path runs over its own run of sequences (details in rad_block_gdn_q.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);
|
||||
|
||||
/* In a pure decode step z goes after the convolution. in and z read only the normed input, so
|
||||
* the engine runs z beside in when it follows in, and at decode heights the two then share
|
||||
* the memory and both stretch: on two R9700s at Qwen3.8-27B's verify shape, ~145 us each
|
||||
* against ~72 and ~43 apart. The convolution reads only in's output, so z behind it runs
|
||||
* beside that small kernel instead, and the recurrent update, which reads z, waits for it.
|
||||
* Only the order of two independent launches changes, so the bytes do not: measured
|
||||
* 166 -> 142 us from in to the recurrent update, and 1.6 ms off a 47 ms step, with the same
|
||||
* greedy text. A prefill or mixed step keeps z beside in: there it is a large GEMM, and the
|
||||
* order was measured at decode only. */
|
||||
const bool z_late = D > 0 && D == S;
|
||||
|
||||
nq.step(c, T);
|
||||
RAD_ISSUE(c, op_in, brows(w.h, T), RAD_W(w_in), brows(w.in, T));
|
||||
if (!z_late) RAD_ISSUE(c, op_z, brows(w.h, T), RAD_W(w_z), brows(w.z, T));
|
||||
/* 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;
|
||||
@@ -302,6 +331,12 @@ inline void GdnBF16::step(RadCtx* c, const RadBatch* batch) const {
|
||||
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));
|
||||
if (z_late) RAD_ISSUE(c, op_z, brows(w.h, T), RAD_W(w_z), brows(w.z, T));
|
||||
/* The recurrent update runs one workgroup per (sequence, head) and leaves the card's
|
||||
* memory mostly idle, so the out-projection's leading bytes are read beside it
|
||||
* (prefetch_beside: on the second lane, behind a join from lane 0). The join follows z,
|
||||
* which the update reads, so it orders nothing the update did not wait for. */
|
||||
if (op_pf_out && z_late && D <= pf_out_seqs) prefetch_beside(c, op_pf_out, w_out, T);
|
||||
/* 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,
|
||||
@@ -349,8 +384,11 @@ inline void GdnBF16::step(RadCtx* c, const RadBatch* batch) const {
|
||||
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));
|
||||
/* Decode steps only: a prompt's rows never take the reads (rad_arch.h, kPrefetchRows). */
|
||||
prefetch_beside(c, op_pf, pf_w, batch->phase == RAD_PHASE_DECODE ? T : INT64_MAX);
|
||||
if (op_ar && !(ar_out && ar_wire_is_exact(g, T)))
|
||||
RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
|
||||
if (op_add) RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h, T), brows(w.x, T));
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/* rad_block_gdn_fp8.h -- the gated-delta-net block with block-scaled FP8 projections.
|
||||
/* rad_block_gdn_q.h -- the gated-delta-net block over LinearQ 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.
|
||||
@@ -31,10 +31,10 @@
|
||||
* 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
|
||||
#ifndef RAD_BLOCK_GDN_Q_H
|
||||
#define RAD_BLOCK_GDN_Q_H
|
||||
|
||||
#include "rad_fp8.h"
|
||||
#include "rad_linear.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
@@ -42,7 +42,7 @@
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct GdnFP8 {
|
||||
struct GdnQ {
|
||||
/* 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 {
|
||||
@@ -73,10 +73,10 @@ struct GdnFP8 {
|
||||
|
||||
struct Wire {
|
||||
rad_buf x = 0; /* [max_tok, n_embd] the residual stream */
|
||||
ActFP8 h{}; /* [max_tok, n_embd] normed input, then the out projection */
|
||||
ActQ 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 */
|
||||
ActQ 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] */
|
||||
@@ -84,7 +84,7 @@ struct GdnFP8 {
|
||||
rad_buf gdec = 0; /* [max_tok, n_head_v] */
|
||||
rad_buf beta = 0; /* [max_tok, n_head_v] */
|
||||
rad_buf kkt = 0; /* [max_tok, n_head_v, chunk] */
|
||||
ActFP8 o{}; /* [max_tok, n_head_v, head_v] rank 3, see the header */
|
||||
ActQ o{}; /* [max_tok, n_head_v, head_v] rank 3, see the header */
|
||||
};
|
||||
|
||||
struct Src {
|
||||
@@ -115,9 +115,9 @@ struct GdnFP8 {
|
||||
* MiB arena and +33 MiB queues a card) for about +1 % at one stream. */
|
||||
bool ab_lane = false;
|
||||
rad_weight w_a_log = 0, w_dt_bias = 0, w_out_norm = 0;
|
||||
LinearFP8 in{}, out{};
|
||||
NormQuantFP8 nq_h{};
|
||||
QuantFP8 q_o{};
|
||||
LinearQ in{}, out{};
|
||||
NormQuant nq_h{};
|
||||
QuantAct q_o{};
|
||||
|
||||
rad_op op_ab = 0;
|
||||
rad_op op_conv_prep = 0, op_kkt = 0, op_scan = 0, op_gnorm = 0; /* prefill */
|
||||
@@ -126,20 +126,34 @@ struct GdnFP8 {
|
||||
* 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;
|
||||
/* Whether op_cr writes the out projection's codes; otherwise q_o follows it. */
|
||||
bool cr_codes = false;
|
||||
int64_t cr_rows = 0;
|
||||
/* Tree verification (rad_drafter_tree): the fold's `_tree` form over a step's decode rows,
|
||||
* which honours RadBatch::spec_parent (a row continues from its parent's state and
|
||||
* convolution window). Declared only when `tree` is set before declare; 0 where no library
|
||||
* serves it, which the architecture reads as "no trees". */
|
||||
bool tree = false;
|
||||
rad_op op_cr_tree = 0;
|
||||
int64_t cr_tree_rows = 0;
|
||||
/* Set by the architecture after declare: a `prefetch` of the out-projection's leading bytes
|
||||
* (decl_prefetch, rad_arch.h), issued on the second lane beside the decode recurrent update on
|
||||
* steps of up to pf_out_rows rows and pf_out_seqs sequences. 0 where none is declared. */
|
||||
* (decl_prefetch, rad_arch.h), issued beside the decode recurrent update on steps of up to
|
||||
* pf_out_rows rows and pf_out_seqs sequences. 0 where none is declared. */
|
||||
rad_op op_pf_out = 0;
|
||||
int64_t pf_out_rows = 0, pf_out_seqs = 0;
|
||||
/* The same read as a second op for steps of at least pf_out_v_rows rows, where the
|
||||
* architecture measured another workgroup count for them (decl_prefetch's `blocks`); 0 where
|
||||
* every step takes op_pf_out. */
|
||||
rad_op op_pf_out_v = 0;
|
||||
int64_t pf_out_v_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). */
|
||||
/* The next block absorbs this block's closing all-reduce (see rad_block_attn_gated_q.h). */
|
||||
bool ar_out = false;
|
||||
/* Which wires that consumer takes (ArOut, rad_fp8.h); set before declare. */
|
||||
/* Which wires that consumer takes (ArOut, rad_linear.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. */
|
||||
* next block will not add, so this one issues the trailing add. See rad_linear.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,
|
||||
@@ -168,7 +182,7 @@ struct GdnFP8 {
|
||||
rad_op op_ar_ov = 0;
|
||||
};
|
||||
|
||||
inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int l,
|
||||
inline int GdnQ::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_) {
|
||||
@@ -199,7 +213,7 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
/* `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. */
|
||||
* rad_block_attn_gated_q.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;
|
||||
@@ -232,7 +246,7 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
w_out_norm = decl_w(b, nm.f("blk.%d.ssm_norm.weight", l), RAD_F32, {cfg.head_v},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
|
||||
/* Norm and quantise in one op (rad_fp8.h: NormQuantFP8); the qkv|z and a|b projections read
|
||||
/* Norm and quantise in one op (rad_linear.h: NormQuant); 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,
|
||||
@@ -246,9 +260,7 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
* 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() }));
|
||||
{ cfg.k_dim(), cfg.k_dim(), cfg.v_dim(), cfg.v_dim() }, 0, 0));
|
||||
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). */
|
||||
@@ -327,9 +339,11 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
g.max_spec > 0 ? "anchor" : "per_candidate")),
|
||||
RAD_WEIGHTS(w_a_log, w_dt_bias, w_out_norm)),
|
||||
{w.q, w.k, w.v, w.ab, w.in.x}, {w.o.x});
|
||||
/* The epilogue's codes for an fp8 or int8 out-projection (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()) {
|
||||
/* The epilogue's codes for an fp8 or int8 out-projection (int8 when ActQ::q8_fed; the codes
|
||||
* dtype picks the quantiser). A bf16 out-projection reads only `o.x` and these stay absent.
|
||||
* Rotated int8 codes (ActQ::q8_rot) only the conv fold writes (gdn_conv_recurrent_update_had);
|
||||
* rows this update serves are quantised by q_o. */
|
||||
if (op_recur && w.o.cq() && !w.o.q8_rot) {
|
||||
const rad_buf oq[2] = { w.o.cq(), w.o.cs() };
|
||||
RAD_ARCH_TRY(rad_op_writes(b, op_recur, oq, 2));
|
||||
}
|
||||
@@ -337,49 +351,75 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
* 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)),
|
||||
/* The fold's rotated epilogue writes one scale per (row, 128), or per 256 for an IQ8R
|
||||
* trunk's codes (ActQ::g8; `group`, stated to that form alone: last, and cut off
|
||||
* otherwise), where this rank's value heads pair up. */
|
||||
const bool cr_wide = w.o.q8_rot && w.o.g8 == RAD_I8_GROUP_WIDE && cfg.n_head_v % 2 == 0;
|
||||
cr_codes = w.o.cq() && (!w.o.q8_rot || w.o.g8 == RAD_SCALE_GROUP || cr_wide);
|
||||
const RadParam cp[] = { 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_INT("group", RAD_I8_GROUP_WIDE) };
|
||||
const rad_weight cw[] = { w_conv, w_a_log, w_dt_bias, w_out_norm };
|
||||
op_cr = rw(b, rad_decl_op(b, w.o.q8_rot && cr_codes ? "gdn_conv_recurrent_update_had"
|
||||
: "gdn_conv_recurrent_update",
|
||||
cp, (int)(sizeof cp / sizeof *cp) - (cr_wide && cr_codes ? 0 : 1),
|
||||
cw, 4),
|
||||
{w.in.x, w.ab}, {w.o.x});
|
||||
if (op_cr && w.o.cq()) {
|
||||
if (op_cr && cr_codes) {
|
||||
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;
|
||||
/* The fold's window is the conv cache's depth, conv_width - 2 + 1 + max_spec, which
|
||||
* its kernel holds in registers: a deployment drafting deeper keeps the pair. */
|
||||
if (op_cr && g.max_spec + 1 <= hi) cr_rows = hi;
|
||||
}
|
||||
if (tree && g.max_spec > 0) {
|
||||
/* The chain fold's codes and `group` (cr_codes above): the rotated form where the chain's
|
||||
* is, `group` 256 where the chain's pairs value heads. */
|
||||
const bool had = w.o.q8_rot && cr_codes;
|
||||
const bool wide = had && w.o.g8 == RAD_I8_GROUP_WIDE && cfg.n_head_v % 2 == 0;
|
||||
const char* name = had ? "gdn_conv_recurrent_update_had_tree"
|
||||
: "gdn_conv_recurrent_update_tree";
|
||||
const int64_t hi = g.max_tok < 16 ? g.max_tok : 16;
|
||||
const RadParam tp[] = { 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", "anchor"),
|
||||
RAD_INT("group", RAD_I8_GROUP_WIDE) };
|
||||
const rad_weight tw[] = { w_conv, w_a_log, w_dt_bias, w_out_norm };
|
||||
if (rad_op_declared(b, name) && g.max_spec + 1 <= hi)
|
||||
op_cr_tree = rw(b, rad_decl_op(b, name, tp,
|
||||
(int)(sizeof tp / sizeof *tp) - (wide ? 0 : 1), tw, 4),
|
||||
{w.in.x, w.ab}, {w.o.x});
|
||||
if (op_cr_tree && cr_codes) {
|
||||
const rad_buf oq[2] = { w.o.cq(), w.o.cs() };
|
||||
RAD_ARCH_TRY(rad_op_writes(b, op_cr_tree, oq, 2));
|
||||
}
|
||||
if (op_cr_tree) cr_tree_rows = hi;
|
||||
}
|
||||
|
||||
RAD_ARCH_TRY(q_o.declare(b, g, w.o, v_dim));
|
||||
/* qwen4exp_lora: linear_attn.out_proj is a LoRA module kind. The plain bf16 view is
|
||||
* taken only when a runtime adapter targets this source (see the gated attn block). */
|
||||
out.plain_bf16_view = s.out && rad_lora_source_targeted(b, s.out);
|
||||
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});
|
||||
op_ar = decl_all_reduce(b, g, 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). */
|
||||
op_ar_ov = decl_all_reduce_overlap(b, g, w.h.x, ar_overlap);
|
||||
/* Only when the next block's norm will not add (rad_linear.h: NormQuant). */
|
||||
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),
|
||||
@@ -389,7 +429,7 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
inline void GdnQ::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);
|
||||
@@ -453,8 +493,12 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
/* At decode and verify sizes the a|b projection is nearly all launch cost and reads only the
|
||||
* norm's output, as the in-projection does, so it runs beside it on lane 1 and is joined before
|
||||
* the convolution reads `ab`. A prefill chunk keeps one lane, where the two would share
|
||||
* bandwidth. */
|
||||
if (ab_lane && T <= 64 && rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK) {
|
||||
* bandwidth. Where launches chain it stays on lane 0: its chained form starts beside the
|
||||
* in-projection without the two lane joins, each of which holds a launch back until the host
|
||||
* has seen the other lane finish (Qwen3.8-27B on two cards: the projection started 55 us late
|
||||
* and the update behind it another 20 to 40 us). */
|
||||
if (ab_lane && !rad_chain_on() && T <= 64 && rad_lane_join(c, 0, 1) == RAD_OK &&
|
||||
rad_lane(c, 1) == RAD_OK) {
|
||||
RAD_ISSUE_N(c, op_ab, T, brows(w.h.x, T), RAD_W(w_ab), brows(w.ab, T));
|
||||
rad_lane(c, 0);
|
||||
in.step(c, w.h, w.in.x, T);
|
||||
@@ -488,13 +532,35 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
|
||||
/* The recurrent update at decode heights runs one workgroup per (sequence, head) and leaves the
|
||||
* card's memory mostly idle, so the out-projection's weight is read into the on-die cache
|
||||
* beside it, on the second lane behind a join from lane 0 (as prefetch_beside). */
|
||||
* beside it: in front of the update on lane 0 where launches chain (the read's chained form
|
||||
* holds nothing behind it), else on the second lane behind a join from lane 0 (as
|
||||
* prefetch_beside). */
|
||||
if (op_pf_out && D > 0 && D <= pf_out_seqs && P == 0 && T <= pf_out_rows) {
|
||||
if (rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK)
|
||||
RAD_ISSUE(c, op_pf_out, RAD_W(out.w));
|
||||
rad_lane(c, 0);
|
||||
const rad_op pf = op_pf_out_v && T >= pf_out_v_rows ? op_pf_out_v : op_pf_out;
|
||||
if (prefetch_lane0()) {
|
||||
RAD_ISSUE(c, pf, RAD_W(out.w));
|
||||
} else {
|
||||
if (rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK)
|
||||
RAD_ISSUE(c, pf, RAD_W(out.w));
|
||||
rad_lane(c, 0);
|
||||
}
|
||||
}
|
||||
if (D > 0 && op_cr && qd <= cr_rows) {
|
||||
/* A tree step (rad_drafter_tree): the decode rows' verify blocks are trees. */
|
||||
if (D > 0 && op_cr_tree && batch->spec_parent && batch->draft_pass == 0 &&
|
||||
qd <= cr_tree_rows) {
|
||||
RAD_ISSUE_N(c, op_cr_tree, 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),
|
||||
cr_codes ? brows(w.o.cq(), DT) : RAD_NONE,
|
||||
cr_codes ? brows(w.o.cs(), DT) : RAD_NONE,
|
||||
praw(batch->spec_parent, RAD_I32, DT));
|
||||
if (w.o.cq() && !cr_codes) q_o.step(c, T, 0, DT);
|
||||
} else 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),
|
||||
@@ -503,8 +569,9 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
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);
|
||||
cr_codes ? brows(w.o.cq(), DT) : RAD_NONE,
|
||||
cr_codes ? brows(w.o.cs(), DT) : RAD_NONE);
|
||||
if (w.o.cq() && !cr_codes) q_o.step(c, T, 0, DT);
|
||||
} 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),
|
||||
@@ -518,15 +585,53 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
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);
|
||||
w.o.cq() && !w.o.q8_rot ? brows(w.o.cq(), DT) : RAD_NONE,
|
||||
w.o.cq() && !w.o.q8_rot ? brows(w.o.cs(), DT) : RAD_NONE);
|
||||
/* Rotated codes come only from the fold; here the decode rows take the quantiser. */
|
||||
if (w.o.q8_rot) q_o.step(c, T, 0, DT);
|
||||
}
|
||||
|
||||
/* 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;
|
||||
/* A checkpoint inside the step (RadBatch::ckpt_cut): the convolution, solve and scan run over
|
||||
* [0, cut) and [cut, T) as two pieces, each the chunk of those rows (the state handed on
|
||||
* through the cache, the second piece's context its first row's position, as ArPieces' pieces
|
||||
* do), and the state and convolution slots go to the checkpoint stage between them. The first
|
||||
* piece is issued at the band a chunk of its rows takes, so the snapshot holds the bytes a
|
||||
* step ending at the checkpoint leaves. */
|
||||
const int64_t ck = batch->ckpt_cut;
|
||||
const bool ck_split = P == 1 && D == 0 && ck > 0 && ck < T && batch->ckpt_cu;
|
||||
if (ck_split) {
|
||||
for (int64_t p = 0; p < 2; ++p) {
|
||||
const int64_t n = p == 0 ? ck : T - ck;
|
||||
const int32_t* cu = batch->ckpt_cu + p;
|
||||
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(p == 0 ? batch->ctx_lens : batch->positions + ck, 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));
|
||||
if (p == 0) {
|
||||
rad_ckpt_snap(c, kv_state, layer);
|
||||
rad_ckpt_snap(c, kv_conv, layer);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (P > 0) {
|
||||
if (!ck_split) {
|
||||
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),
|
||||
@@ -544,6 +649,7 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
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;
|
||||
@@ -578,4 +684,4 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_GDN_FP8_H */
|
||||
#endif /* RAD_BLOCK_GDN_Q_H */
|
||||
@@ -0,0 +1,263 @@
|
||||
/* rad_block_gemma4_unified.h -- the media embedders of Gemma 4 12B ("unified", transformers'
|
||||
* Gemma4UnifiedVisionEmbedder and the audio Gemma4UnifiedMultimodalEmbedder), served by gemma4_bf16.
|
||||
* Neither has an encoder: the language model sees each patch or audio frame after a few norms and
|
||||
* linears.
|
||||
*
|
||||
* image: a patch is 48 x 48 x 3 (3 x 3 of the processor's 16-pixel patches), staged by the core's
|
||||
* Gemma 4 processor as u / 255 in bf16, (y, x, channel); a LayerNorm over the patch, a linear with
|
||||
* a bias, a LayerNorm, plus a learned row for the patch's column and one for its row (the
|
||||
* checkpoint's [npos, 2, width] table, read as its two taps of dimension 1), a LayerNorm, then the
|
||||
* multimodal embedder: an RMS norm with no gain and a width -> n_embd linear. The LayerNorms are
|
||||
* nn.LayerNorm's default eps 1e-5, which no config states. One patch is one row.
|
||||
* audio: a frame is 640 samples at 16 kHz as they are, the last zero-padded, in bf16; an RMS norm
|
||||
* with no gain and a 640 -> n_embd linear. One frame is one row.
|
||||
*
|
||||
* Their rows replace the placeholders' embeddings unscaled, as the vision tower's do. Every rank
|
||||
* runs them whole (RAD_SHARD_NONE). */
|
||||
#ifndef RAD_BLOCK_GEMMA4_UNIFIED_H
|
||||
#define RAD_BLOCK_GEMMA4_UNIFIED_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct Gemma4UnifiedVision {
|
||||
bool on = false;
|
||||
/* The language model reads a picture's rows both ways (RadEncoderDecl::bidirectional); the
|
||||
* plugin sets it before declare. */
|
||||
bool bidirectional = false;
|
||||
int64_t P = 0, width = 0, patch_dim = 0, npos = 0, n_embd = 0;
|
||||
rad_weight w_ln1 = 0, w_ln1b = 0, w_in = 0, w_inb = 0, w_ln2 = 0, w_ln2b = 0, w_px = 0, w_py = 0;
|
||||
rad_weight w_pn = 0, w_pnb = 0, w_proj = 0;
|
||||
rad_op op_ln1 = 0, op_in = 0, op_ln2 = 0, op_px = 0, op_py = 0, op_padd = 0, op_add = 0;
|
||||
rad_op op_pn = 0, op_norm = 0, op_out = 0;
|
||||
rad_buf b_n = 0, b_x = 0, b_h = 0, b_px = 0, b_py = 0, b_out = 0;
|
||||
|
||||
static bool present(const RadModelMeta* m) {
|
||||
const char* t = rad_meta_gets(m, "vision_config.model_type", "");
|
||||
return t && !std::strcmp(t, "gemma4_unified_vision");
|
||||
}
|
||||
|
||||
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
|
||||
int64_t model_embd, const char* who) {
|
||||
on = false;
|
||||
if (!present(m) || ctx->max_enc_patches <= 0) return RAD_OK;
|
||||
width = rad_meta_geti(m, "vision_config.mm_embed_dim", 0);
|
||||
npos = rad_meta_geti(m, "vision_config.mm_posemb_size", 0);
|
||||
const int64_t side = rad_meta_geti(m, "vision_config.model_patch_size", 0);
|
||||
const int64_t outd = rad_meta_geti(m, "vision_config.output_proj_dims", width);
|
||||
const double eps = rad_meta_getf(m, "vision_config.rms_norm_eps", 1e-6);
|
||||
if (width <= 0 || npos <= 0 || side <= 0 || outd != width) {
|
||||
fprintf(stderr, "radiance: %s: the container's vision_config is incomplete or not the "
|
||||
"embedder this plugin serves (mm_embed_dim %lld, mm_posemb_size %lld, "
|
||||
"model_patch_size %lld, output_proj_dims %lld)\n", who,
|
||||
(long long)width, (long long)npos, (long long)side, (long long)outd);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
n_embd = model_embd;
|
||||
patch_dim = 3 * side * side;
|
||||
P = ctx->max_enc_patches;
|
||||
const int A = RAD_ACCESS_PER_REQUEST, N = RAD_SHARD_NONE;
|
||||
const char* V = "model.vision_embedder";
|
||||
struct { const char* to; const char* from; } cp[] = {
|
||||
{ "v.ln1.weight", "patch_ln1.weight" }, { "v.ln1.bias", "patch_ln1.bias" },
|
||||
{ "v.in.weight", "patch_dense.weight" }, { "v.in.bias", "patch_dense.bias" },
|
||||
{ "v.ln2.weight", "patch_ln2.weight" }, { "v.ln2.bias", "patch_ln2.bias" },
|
||||
{ "v.pn.weight", "pos_norm.weight" }, { "v.pn.bias", "pos_norm.bias" } };
|
||||
for (const auto& e : cp)
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("%s", e.to), nm.ckpt("%s.%s", V, e.from)));
|
||||
RAD_ARCH_TRY(map_tap(b, nm.f("v.pos_x.weight"), nm.ckpt("%s.pos_embedding", V), 1, 0));
|
||||
RAD_ARCH_TRY(map_tap(b, nm.f("v.pos_y.weight"), nm.ckpt("%s.pos_embedding", V), 1, 1));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("v.embed.weight"), nm.ckpt("model.embed_vision.embedding_projection.weight")));
|
||||
w_ln1 = decl_w(b, nm.f("v.ln1.weight"), RAD_BF16, {patch_dim}, A, N, grp_model());
|
||||
w_ln1b = decl_w(b, nm.f("v.ln1.bias"), RAD_BF16, {patch_dim}, A, N, grp_model());
|
||||
w_in = decl_w(b, nm.f("v.in.weight"), RAD_BF16, {width, patch_dim}, A, N, grp_model());
|
||||
w_inb = decl_w(b, nm.f("v.in.bias"), RAD_BF16, {width}, A, N, grp_model());
|
||||
w_ln2 = decl_w(b, nm.f("v.ln2.weight"), RAD_BF16, {width}, A, N, grp_model());
|
||||
w_ln2b = decl_w(b, nm.f("v.ln2.bias"), RAD_BF16, {width}, 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_pn = decl_w(b, nm.f("v.pn.weight"), RAD_BF16, {width}, A, N, grp_model());
|
||||
w_pnb = decl_w(b, nm.f("v.pn.bias"), RAD_BF16, {width}, A, N, grp_model());
|
||||
w_proj = decl_w(b, nm.f("v.embed.weight"), RAD_BF16, {n_embd, width}, A, N, grp_model());
|
||||
|
||||
b_n = decl_b(b, nm.f("v.n"), RAD_BF16, {P, patch_dim});
|
||||
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_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_out = decl_b(b, nm.f("v.out"), RAD_BF16, {P, n_embd});
|
||||
|
||||
auto ln = [&](int64_t n, rad_weight w, rad_weight bias) {
|
||||
return RAD_OP(b, "layernorm", RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", n),
|
||||
RAD_F64("eps", 1e-5), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w, bias));
|
||||
};
|
||||
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 add = [&]() {
|
||||
return RAD_OP(b, "add", RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
op_ln1 = rw(b, ln(patch_dim, w_ln1, w_ln1b), {}, {b_n});
|
||||
op_in = rw(b, RAD_OP(b, "gemm_nt_bias",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", width),
|
||||
RAD_INT("K", patch_dim), RAD_STR("dtype", "bf16"),
|
||||
RAD_STR("act", "none")),
|
||||
RAD_WEIGHTS(w_in, w_inb)),
|
||||
{b_n}, {b_x});
|
||||
op_ln2 = rw(b, ln(width, w_ln2, w_ln2b), {b_x}, {b_h});
|
||||
op_px = rw(b, lookup(w_px), {}, {b_px});
|
||||
op_py = rw(b, lookup(w_py), {}, {b_py});
|
||||
op_padd = rw(b, add(), {b_px, b_py}, {b_px});
|
||||
op_add = rw(b, add(), {b_h, b_px}, {b_h});
|
||||
op_pn = rw(b, ln(width, w_pn, w_pnb), {b_h}, {b_x});
|
||||
op_norm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
|
||||
RAD_F64("eps", eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{b_x}, {b_h});
|
||||
op_out = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", n_embd),
|
||||
RAD_INT("K", width), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_proj)),
|
||||
{b_h}, {b_out});
|
||||
|
||||
RadEncoderDecl e{};
|
||||
e.name = "vision";
|
||||
e.modalities = RAD_MM_IMAGE | RAD_MM_VIDEO;
|
||||
e.patch_dim = patch_dim;
|
||||
e.merge = 1;
|
||||
e.max_patches = P;
|
||||
e.n_embd = n_embd;
|
||||
e.out = b_out;
|
||||
e.bidirectional = bidirectional ? 1 : 0;
|
||||
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
|
||||
rad_note(b, "vision embedder (no tower): %lldx%lld patches of %lld values -> %lld, "
|
||||
"positions %lld a side; %lld patches a pass -> %lld rows of %lld",
|
||||
(long long)side, (long long)side, (long long)patch_dim, (long long)width,
|
||||
(long long)npos, (long long)P, (long long)P, (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;
|
||||
if (!on || Pn <= 0 || Pn > P || batch->enc_n_seg <= 0) {
|
||||
rad_step_fail(c, "an encoder pass this program's vision embedder cannot serve: none "
|
||||
"declared, or more patches than it was declared for");
|
||||
return;
|
||||
}
|
||||
const int32_t* crd = batch->enc_coord;
|
||||
RAD_ISSUE_N(c, op_ln1, Pn, praw2(batch->enc_pixels, RAD_BF16, Pn, patch_dim), RAD_W(w_ln1),
|
||||
RAD_W(w_ln1b), brows(b_n, Pn));
|
||||
RAD_ISSUE_N(c, op_in, Pn, brows(b_n, Pn), RAD_W(w_in), RAD_W(w_inb), RAD_NONE, brows(b_x, Pn));
|
||||
RAD_ISSUE_N(c, op_ln2, Pn, brows(b_x, Pn), RAD_W(w_ln2), RAD_W(w_ln2b), brows(b_h, 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_h, Pn), brows(b_px, Pn), brows(b_h, Pn));
|
||||
RAD_ISSUE_N(c, op_pn, Pn, brows(b_h, Pn), RAD_W(w_pn), RAD_W(w_pnb), brows(b_x, Pn));
|
||||
RAD_ISSUE_N(c, op_norm, Pn, brows(b_x, Pn), RAD_NONE, brows(b_h, Pn));
|
||||
RAD_ISSUE_N(c, op_out, Pn, brows(b_h, Pn), RAD_W(w_proj), brows(b_out, Pn));
|
||||
}
|
||||
};
|
||||
|
||||
struct Gemma4UnifiedAudio {
|
||||
bool on = false;
|
||||
int64_t P = 0, frame = 0, n_embd = 0;
|
||||
rad_weight w_proj = 0;
|
||||
rad_op op_norm = 0, op_out = 0;
|
||||
rad_buf b_n = 0, b_out = 0;
|
||||
|
||||
static bool present(const RadModelMeta* m) {
|
||||
const char* t = rad_meta_gets(m, "audio_config.model_type", "");
|
||||
return t && !std::strcmp(t, "gemma4_unified_audio");
|
||||
}
|
||||
/* Samples a frame: the extractor's audio_samples_per_token, else the embedder's input width. */
|
||||
static int64_t frame_for(const RadModelMeta* m) {
|
||||
return rad_meta_geti(m, "processor.feature_extractor.audio_samples_per_token",
|
||||
rad_meta_geti(m, "audio_config.audio_embed_dim", 0));
|
||||
}
|
||||
/* The longest clip in frames: processor_config.json's audio_seq_length, else 30 s. */
|
||||
static int64_t frames_for(const RadModelMeta* m) {
|
||||
const int64_t f = frame_for(m);
|
||||
const int64_t rate = rad_meta_geti(m, "processor.feature_extractor.sampling_rate", 16000);
|
||||
if (f <= 0 || rate <= 0) return 0;
|
||||
return rad_meta_geti(m, "processor.audio_seq_length", (30 * rate + f - 1) / f);
|
||||
}
|
||||
|
||||
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
|
||||
int64_t model_embd, const char* who) {
|
||||
on = false;
|
||||
if (!present(m) || ctx->max_audio_frames <= 0) return RAD_OK;
|
||||
frame = frame_for(m);
|
||||
const int64_t width = rad_meta_geti(m, "audio_config.audio_embed_dim", 0);
|
||||
const double eps = rad_meta_getf(m, "audio_config.rms_norm_eps", 1e-6);
|
||||
if (frame <= 0 || width != frame) {
|
||||
fprintf(stderr, "radiance: %s: the container's audio frame (%lld samples) is not the "
|
||||
"embedder's input (audio_embed_dim %lld)\n", who, (long long)frame,
|
||||
(long long)width);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
n_embd = model_embd;
|
||||
P = ctx->max_audio_frames;
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("a.embed.weight"), nm.ckpt("model.embed_audio.embedding_projection.weight")));
|
||||
w_proj = decl_w(b, nm.f("a.embed.weight"), RAD_BF16, {n_embd, frame}, RAD_ACCESS_PER_REQUEST,
|
||||
RAD_SHARD_NONE, grp_model());
|
||||
b_n = decl_b(b, nm.f("a.n"), RAD_BF16, {P, frame});
|
||||
b_out = decl_b(b, nm.f("a.out"), RAD_BF16, {P, n_embd});
|
||||
op_norm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", frame),
|
||||
RAD_F64("eps", eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, {b_n});
|
||||
op_out = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", n_embd),
|
||||
RAD_INT("K", frame), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_proj)),
|
||||
{b_n}, {b_out});
|
||||
RadEncoderDecl e{};
|
||||
e.name = "audio";
|
||||
e.modalities = RAD_MM_AUDIO;
|
||||
e.patch_dim = frame;
|
||||
e.merge = 1;
|
||||
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 embedder (no encoder): frames of %lld samples -> %lld; %lld frames a pass",
|
||||
(long long)frame, (long long)n_embd, (long long)P);
|
||||
on = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t Pn = batch->enc_n_patch;
|
||||
if (!on || Pn <= 0 || Pn > P || batch->enc_n_seg <= 0) {
|
||||
rad_step_fail(c, "an audio pass this program's audio embedder cannot serve: none "
|
||||
"declared, or more frames than it was declared for");
|
||||
return;
|
||||
}
|
||||
RAD_ISSUE_N(c, op_norm, Pn, praw2(batch->enc_pixels, RAD_BF16, Pn, frame), RAD_NONE,
|
||||
brows(b_n, Pn));
|
||||
RAD_ISSUE_N(c, op_out, Pn, brows(b_n, Pn), RAD_W(w_proj), brows(b_out, Pn));
|
||||
}
|
||||
};
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_GEMMA4_UNIFIED_H */
|
||||
@@ -56,6 +56,9 @@ struct Gemma4Vision {
|
||||
rad_op op_c[C_N] = {};
|
||||
};
|
||||
bool on = false, standardize = false, clip = false;
|
||||
/* The language model reads a picture's rows both ways (RadEncoderDecl::bidirectional); the
|
||||
* plugin sets it before declare. */
|
||||
bool bidirectional = 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;
|
||||
@@ -321,6 +324,7 @@ struct Gemma4Vision {
|
||||
e.max_patches = P;
|
||||
e.n_embd = n_embd;
|
||||
e.out = b_out;
|
||||
e.bidirectional = bidirectional ? 1 : 0;
|
||||
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%s; %lld patches a pass -> %lld rows of %lld",
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
* on this rank's run of rows only, since no other rank reads them. */
|
||||
#ifndef RAD_BLOCK_GLM_INDEXER_H
|
||||
#define RAD_BLOCK_GLM_INDEXER_H
|
||||
#include "rad_fp8.h"
|
||||
#include "rad_linear.h"
|
||||
#include "rad_glm_tp.h"
|
||||
|
||||
namespace rad {
|
||||
@@ -27,6 +27,9 @@ struct DsaCache {
|
||||
rad_buf query = 0, codes = 0, scales = 0, gate = 0, kg = 0;
|
||||
rad_buf stage = 0, page = 0, bpos = 0, nc = 0, pooled = 0, pool_scale = 0;
|
||||
rad_buf score = 0, selected = 0, nsel = 0, length = 0;
|
||||
/* A taking-all step's zero scores, [max_tok, topk + 1]: such a step does not split, and
|
||||
* the score plane holds only a run of rows when the step may. */
|
||||
rad_buf unscored = 0;
|
||||
/* TP only: a rank's rebased bounds, page tables and lengths before the gathers. */
|
||||
rad_buf cu_part = 0, sel_part = 0, len_part = 0;
|
||||
};
|
||||
@@ -44,6 +47,7 @@ struct DsaCache {
|
||||
rad_kvgroup index = 0, tail = 0, attention = 0;
|
||||
rad_weight ape = 0;
|
||||
rad_op op_query = 0, op_work = 0, op_pool = 0, op_tail = 0, op_score = 0, op_select = 0;
|
||||
rad_op op_unscored = 0, op_select_all = 0;
|
||||
rad_op op_score_part = 0, op_select_part = 0, op_gather_sel = 0, op_gather_len = 0;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Config& cfg,
|
||||
@@ -112,6 +116,15 @@ struct DsaCache {
|
||||
RAD_INT("seqs", g.max_seqs), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.kg }, {});
|
||||
/* A step whose every row reaches topk or fewer blocks selects them all (takes_all), and
|
||||
* qsa_select takes any finite scores in block order then: zeros serve as well as the
|
||||
* scorer's. The fill spans topk + 1 columns, at least the live reach of such a step. */
|
||||
op_unscored = rw(b,
|
||||
RAD_OP(b, "fill",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
|
||||
RAD_INT("n", unscored_cols()), RAD_STR("dtype", "f32")),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, { w.unscored });
|
||||
op_score = rw(b,
|
||||
RAD_OP(b, "dsa_score",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 128),
|
||||
@@ -139,6 +152,14 @@ struct DsaCache {
|
||||
RAD_INT("seqs", g.max_seqs), RAD_INT("signed", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.score, w.nc }, { w.selected, w.nsel, w.length });
|
||||
op_select_all = rw(b,
|
||||
RAD_OP(b, "qsa_select",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
|
||||
RAD_INT("blocks", unscored_cols()),
|
||||
RAD_INT("topk", 512), RAD_INT("ratio", 4),
|
||||
RAD_INT("seqs", g.max_seqs), RAD_INT("signed", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.unscored, w.nc }, { w.selected, w.nsel, w.length });
|
||||
if (split) {
|
||||
op_select_part = rw(
|
||||
b,
|
||||
@@ -165,8 +186,12 @@ struct DsaCache {
|
||||
if (!op_score_part || !op_select_part || !op_gather_sel || !op_gather_len)
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
return op_query && op_work && op_tail && op_score && op_select ? RAD_OK : RAD_E_INVAL;
|
||||
return op_query && op_work && op_tail && op_unscored && op_score && op_select &&
|
||||
op_select_all
|
||||
? RAD_OK
|
||||
: RAD_E_INVAL;
|
||||
}
|
||||
int64_t unscored_cols() const { return c.topk + 1 < c.blocks ? c.topk + 1 : c.blocks; }
|
||||
/* The columns a step scores: the live reach the batch bounds on the host. */
|
||||
int64_t live_blocks(const RadBatch* batch) const {
|
||||
const auto* ib = kv_batch(batch, index);
|
||||
@@ -179,13 +204,19 @@ struct DsaCache {
|
||||
}
|
||||
/* The decision reads the same host bound as the score plane's width (max_ctx_len, rounded by
|
||||
* the core), so every rank takes the same path and a recorded decode pass changes it only when
|
||||
* that bound moves. */
|
||||
* that bound moves. A step that takes all its blocks never splits: with nothing to score, every
|
||||
* rank selects the whole step itself, and the gathers have nothing to save. */
|
||||
bool splits(const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
return op_score_part && (GlmTp::splits(T, g.world) ||
|
||||
(T >= GlmTp::kSplitWorkRows &&
|
||||
T * live_blocks(batch) >= GlmTp::kSplitWork));
|
||||
return op_score_part && live_blocks(batch) > c.topk &&
|
||||
(GlmTp::splits(T, g.world) ||
|
||||
(T >= GlmTp::kSplitWorkRows && T * live_blocks(batch) >= GlmTp::kSplitWork));
|
||||
}
|
||||
/* Every row's history fits the selection, so the query side (projection, head gates,
|
||||
* quantiser, scorer) has nothing to decide: the selected table is every live block in order,
|
||||
* bit for bit what scoring would select. Read from the same host bound as splits(), so every
|
||||
* rank agrees. */
|
||||
bool takes_all(const RadBatch* batch) const { return live_blocks(batch) <= c.topk; }
|
||||
/* The query rows this rank runs: the whole step, or its run of a split step (GlmTp::run_of).
|
||||
* A rank whose run lies wholly past a small step runs the step's first R rows instead: no
|
||||
* sequence holds its run, so its scores are -inf, and its answers land past T. The caller's
|
||||
@@ -210,11 +241,13 @@ struct DsaCache {
|
||||
const int64_t T = batch->n_tok, S = batch->n_seq;
|
||||
const int64_t work = (T + 3) / 4 + S,
|
||||
pitch = tb->state_index_pitch > 0 ? tb->state_index_pitch : 1;
|
||||
const bool all = takes_all(batch);
|
||||
int64_t q0 = 0, qn = T;
|
||||
query_rows(batch, &q0, &qn);
|
||||
RAD_ISSUE_N(ctx, op_query, qn * 32, brow_slice(w.query, q0 * 32, qn * 32, 128),
|
||||
brow_slice(w.codes, q0 * 32, qn * 32, 128),
|
||||
brow_slice(w.scales, q0 * 32, qn * 32, 1));
|
||||
if (!all)
|
||||
RAD_ISSUE_N(ctx, op_query, qn * 32, brow_slice(w.query, q0 * 32, qn * 32, 128),
|
||||
brow_slice(w.codes, q0 * 32, qn * 32, 128),
|
||||
brow_slice(w.scales, q0 * 32, qn * 32, 1));
|
||||
RAD_ISSUE_N(ctx, op_work, T, brows(w.kg, T), praw(batch->positions, RAD_I32, T),
|
||||
praw(batch->cu_seqlens, RAD_I32, S + 1), kv_cache(tail, layer),
|
||||
praw2(tb->state_index, RAD_I32, S, pitch),
|
||||
@@ -232,6 +265,16 @@ struct DsaCache {
|
||||
step_split(ctx, batch, live);
|
||||
return;
|
||||
}
|
||||
if (all) {
|
||||
const int64_t U = unscored_cols();
|
||||
RAD_ISSUE_N(ctx, op_unscored, T, brows(w.unscored, T));
|
||||
RAD_ISSUE_N(ctx, op_select_all, T, bcol_at(w.unscored, 0, U, 0, live, T),
|
||||
praw2(ab->block_table, RAD_I32, S, ab->block_table_pitch),
|
||||
brows(w.nc, S), praw(batch->positions, RAD_I32, T),
|
||||
praw(batch->cu_seqlens, RAD_I32, S + 1), brows(w.selected, T),
|
||||
brows(w.nsel, T), brows(w.length, T));
|
||||
return;
|
||||
}
|
||||
// dsa_score declares ten operands, cu_part the optional tenth; the engine counts them.
|
||||
RAD_ISSUE_N(ctx, op_score, T, brows(w.codes, T * 32), brows(w.scales, T * 32),
|
||||
brows(w.gate, T), kv_cache(index, layer), RAD_NONE,
|
||||
@@ -275,7 +318,7 @@ struct GlmIndexer {
|
||||
};
|
||||
Geom g{};
|
||||
Wire w{};
|
||||
LinearFP8 query{}, key_gate{};
|
||||
LinearQ query{}, key_gate{};
|
||||
DsaCache cache{};
|
||||
rad_weight gain = 0, bias = 0, head_weight = 0;
|
||||
rad_op op_norm = 0, op_query_copy = 0, op_gate_copy = 0, op_head = 0;
|
||||
@@ -289,7 +332,7 @@ struct GlmIndexer {
|
||||
Geom bg = g;
|
||||
bg.w_bf16 = true;
|
||||
auto act = [](rad_buf x) {
|
||||
ActFP8 a{};
|
||||
ActQ a{};
|
||||
a.x = x;
|
||||
return a;
|
||||
};
|
||||
@@ -317,18 +360,8 @@ struct GlmIndexer {
|
||||
RAD_F64("eps", 1e-6), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(gain, bias)),
|
||||
{ w.kg_raw }, { w.cache.kg });
|
||||
op_query_copy = rw(b,
|
||||
RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * 32), RAD_INT("n", 128),
|
||||
RAD_STR("from", "bf16"), RAD_STR("to", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.q_wide }, { w.cache.query });
|
||||
op_gate_copy = rw(b,
|
||||
RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 128),
|
||||
RAD_STR("from", "bf16"), RAD_STR("to", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.kg_raw }, { w.cache.kg });
|
||||
op_query_copy = cast_op(b, g.max_tok * 32, 128, "bf16", "bf16", w.q_wide, w.cache.query);
|
||||
op_gate_copy = cast_op(b, g.max_tok, 128, "bf16", "bf16", w.kg_raw, w.cache.kg);
|
||||
op_head = rw(b,
|
||||
RAD_OP(b, "gemm_nt_f32",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", 32),
|
||||
@@ -342,29 +375,35 @@ struct GlmIndexer {
|
||||
void step(RadCtx* ctx, const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
auto act = [](rad_buf x) {
|
||||
ActFP8 a{};
|
||||
ActQ a{};
|
||||
a.x = x;
|
||||
return a;
|
||||
};
|
||||
int64_t r0 = 0, rows = T;
|
||||
cache.query_rows(batch, &r0, &rows);
|
||||
/* The key side runs on every step, since the index cache must stay current; the query
|
||||
* side only where the selection is a choice (DsaCache::takes_all). */
|
||||
const bool all = cache.takes_all(batch);
|
||||
/* Every output row of these ops is independent of the others and of how many there are,
|
||||
* except the bf16 projection's at 64 rows and under, a band whose split count a tuned
|
||||
* configuration may set: it stays on the step's rows unless every run is wider. */
|
||||
const bool runs = cache.splits(batch);
|
||||
if (runs && T - (g.world - 1) * DsaCache::part_rows(T, g.world) > 64)
|
||||
query.step(ctx, act(w.q_low), w.q_wide, T, r0, rows);
|
||||
else
|
||||
query.step(ctx, act(w.q_low), w.q_wide, T);
|
||||
RAD_ISSUE_N(ctx, op_query_copy, rows * 32, brow_slice(w.q_wide, r0, rows, 4096),
|
||||
brow_slice(w.cache.query, r0 * 32, rows * 32, 128));
|
||||
if (!all) {
|
||||
if (runs && T - (g.world - 1) * DsaCache::part_rows(T, g.world) > 64)
|
||||
query.step(ctx, act(w.q_low), w.q_wide, T, r0, rows);
|
||||
else
|
||||
query.step(ctx, act(w.q_low), w.q_wide, T);
|
||||
RAD_ISSUE_N(ctx, op_query_copy, rows * 32, brow_slice(w.q_wide, r0, rows, 4096),
|
||||
brow_slice(w.cache.query, r0 * 32, rows * 32, 128));
|
||||
}
|
||||
key_gate.step(ctx, act(w.input), w.kg_raw, T);
|
||||
RAD_ISSUE_N(ctx, op_norm, T, bcol(w.kg_raw, 0, 128, T), RAD_W(gain), RAD_W(bias),
|
||||
bcol(w.cache.kg, 0, 128, T));
|
||||
RAD_ISSUE_N(ctx, op_gate_copy, T, bcol(w.kg_raw, 128, 128, T),
|
||||
bcol(w.cache.kg, 128, 128, T));
|
||||
RAD_ISSUE_N(ctx, op_head, rows, brow_slice(w.input, r0, rows, 4096), RAD_W(head_weight),
|
||||
brow_slice(w.cache.gate, r0, rows, 32));
|
||||
if (!all)
|
||||
RAD_ISSUE_N(ctx, op_head, rows, brow_slice(w.input, r0, rows, 4096),
|
||||
RAD_W(head_weight), brow_slice(w.cache.gate, r0, rows, 32));
|
||||
cache.step(ctx, batch);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
* into the gates are replicated. The block's all_reduce sums the output. */
|
||||
#ifndef RAD_BLOCK_GLM_KDA_H
|
||||
#define RAD_BLOCK_GLM_KDA_H
|
||||
#include "rad_fp8.h"
|
||||
#include "rad_linear.h"
|
||||
#include "rad_glm_tp.h"
|
||||
#include <cmath>
|
||||
|
||||
@@ -140,7 +140,7 @@ struct GlmKda {
|
||||
Geom g{};
|
||||
Wire w{};
|
||||
KdaState core{};
|
||||
LinearFP8 qkv{}, beta{}, forget_a{}, forget_b{}, gate_a{}, gate_b{}, output{};
|
||||
LinearQ qkv{}, beta{}, forget_a{}, forget_b{}, gate_a{}, gate_b{}, output{};
|
||||
rad_op op_ar = 0;
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int layer, const Wire& wire,
|
||||
const char* prefix, const KdaState::Src& src, rad_kvgroup state,
|
||||
@@ -152,13 +152,13 @@ struct GlmKda {
|
||||
w.forget_low == w.gate_low)
|
||||
return RAD_E_INVAL;
|
||||
// All seven projections are plain bf16 in the pinned checkpoint; under w_bf16,
|
||||
// LinearFP8::declare refuses a quantised one by name.
|
||||
// LinearQ::declare refuses a quantised one by name.
|
||||
Geom bg = g;
|
||||
bg.w_bf16 = true;
|
||||
const int64_t width = GlmTp::kda_width(g.world), heads = GlmTp::heads(g.world);
|
||||
const auto group = grp_layer(layer);
|
||||
auto act = [](rad_buf x) {
|
||||
ActFP8 a{};
|
||||
ActQ a{};
|
||||
a.x = x;
|
||||
return a;
|
||||
};
|
||||
@@ -200,7 +200,7 @@ struct GlmKda {
|
||||
void step(RadCtx* ctx, const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
auto act = [](rad_buf x) {
|
||||
ActFP8 a{};
|
||||
ActQ a{};
|
||||
a.x = x;
|
||||
return a;
|
||||
};
|
||||
|
||||
@@ -15,10 +15,11 @@
|
||||
* unset declares neither them nor the form. */
|
||||
#ifndef RAD_BLOCK_GLM_MLA_H
|
||||
#define RAD_BLOCK_GLM_MLA_H
|
||||
#include "rad_fp8.h"
|
||||
#include "rad_linear.h"
|
||||
#include "rad_glm_tp.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
@@ -27,6 +28,25 @@ struct MlaLatent {
|
||||
struct Config {
|
||||
int64_t heads = 16, head_dim = 256, latent_dim = 512, blocks = 513;
|
||||
};
|
||||
/* The attention over the latent cache, `rows` rows of `heads` heads. The cache is Geom::kv_dtype
|
||||
* (bf16, fp8_e4m3 under --kv-cache-dtype fp8, or i8); `kv_dtype` is stated only for a cache that
|
||||
* is not bf16, so a bf16 build declares the op it always did. */
|
||||
static rad_op attn_op(RadBuilder* b, const Geom& g, int64_t rows, int64_t heads,
|
||||
int64_t blocks, double scale) {
|
||||
if (g.kv_dtype && std::strcmp(g.kv_dtype, "bf16"))
|
||||
return RAD_OP(b, "mla_attn",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("latent_dim", 512),
|
||||
RAD_INT("heads", heads), RAD_INT("blocks", blocks),
|
||||
RAD_INT("block_size", 4), RAD_F64("scale", scale),
|
||||
RAD_STR("dtype", "bf16"), RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS);
|
||||
return RAD_OP(b, "mla_attn",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("latent_dim", 512),
|
||||
RAD_INT("heads", heads), RAD_INT("blocks", blocks),
|
||||
RAD_INT("block_size", 4), RAD_F64("scale", scale),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
}
|
||||
struct Wire {
|
||||
rad_buf q = 0, q_latent = 0, attn_latent = 0, out = 0, selected = 0, length = 0;
|
||||
/* qsa_select's entry count (selected_count), one int a row: the streamed resolve's `nsel`.
|
||||
@@ -68,16 +88,10 @@ struct MlaLatent {
|
||||
RAD_STR("mode", "absorb"), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(projection)),
|
||||
{ w.q }, { w.q_latent });
|
||||
op_attn =
|
||||
rw(b,
|
||||
RAD_OP(b, "mla_attn",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("latent_dim", c.latent_dim),
|
||||
RAD_INT("heads", c.heads), RAD_INT("blocks", c.blocks),
|
||||
RAD_INT("block_size", 4),
|
||||
RAD_F64("scale", 1.0 / std::sqrt((double)c.head_dim)),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.q_latent, w.selected, w.length }, { w.attn_latent });
|
||||
op_attn = rw(b,
|
||||
attn_op(b, g, g.max_tok, c.heads, c.blocks,
|
||||
1.0 / std::sqrt((double)c.head_dim)),
|
||||
{ w.q_latent, w.selected, w.length }, { w.attn_latent });
|
||||
if (!op_attn || rad_kv_block_size(b, group) != 4) return RAD_E_INVAL;
|
||||
op_expand = rw(
|
||||
b,
|
||||
@@ -109,10 +123,10 @@ struct GlmMla {
|
||||
* world * rows_for(T) rows, since every rank's run is gathered at full length. */
|
||||
struct RowsWire {
|
||||
rad_buf q = 0, q_latent = 0, attn_latent = 0, out = 0;
|
||||
ActFP8 attn{};
|
||||
ActQ attn{};
|
||||
};
|
||||
struct Wire {
|
||||
ActFP8 input{}, q_low{}, attn{};
|
||||
ActQ input{}, q_low{}, attn{};
|
||||
rad_buf q_raw = 0, kv_raw = 0, latent = 0, out = 0;
|
||||
MlaLatent::Wire core{};
|
||||
RowsWire rows{};
|
||||
@@ -126,14 +140,14 @@ struct GlmMla {
|
||||
Wire w{};
|
||||
int layer = 0;
|
||||
rad_kvgroup kv = 0;
|
||||
LinearFP8 q_a{}, kv_a{}, q_b{}, output{};
|
||||
NormQuantFP8 q_norm{};
|
||||
QuantFP8 attn_quant{};
|
||||
LinearQ q_a{}, kv_a{}, q_b{}, output{};
|
||||
NormQuant q_norm{};
|
||||
QuantAct attn_quant{};
|
||||
MlaLatent core{};
|
||||
rad_weight q_gain = 0, kv_gain = 0;
|
||||
rad_op op_kv_norm = 0, op_store = 0, op_store_stream = 0, op_resolve = 0, op_ar = 0;
|
||||
LinearFP8 rows_q_b{}, rows_output{};
|
||||
QuantFP8 rows_quant{};
|
||||
LinearQ rows_q_b{}, rows_output{};
|
||||
QuantAct rows_quant{};
|
||||
rad_weight rows_kv_b = 0;
|
||||
rad_op op_rows_absorb = 0, op_rows_attn = 0, op_rows_expand = 0, op_rows_gather = 0;
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
|
||||
@@ -172,12 +186,13 @@ struct GlmMla {
|
||||
RAD_ARCH_TRY(q_b.declare(b, nm, g, nm.f("blk.%d.attn_q_b", l), GlmTp::mla_width(g.world),
|
||||
1536, RAD_SHARD_ROW, wg, { nm.ckpt("%s.q_b_proj.weight", prefix) },
|
||||
w.q_low, w.core.q));
|
||||
// Cache stores contiguous halves of the normalized latent, with no duplicated K/V.
|
||||
/* Cache stores contiguous halves of the normalized latent, with no duplicated K/V. An E4M3
|
||||
* cache (Geom::kv_dtype) stores at kv_store's default descale of 1, which mla_attn reads. */
|
||||
op_store = rw(b,
|
||||
RAD_OP(b, "kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", 256),
|
||||
RAD_INT("n_head_kv", 1), RAD_INT("block_size", 4),
|
||||
RAD_STR("kv_dtype", "bf16")),
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.latent }, {});
|
||||
if (!op_store) return RAD_E_INVAL;
|
||||
@@ -200,7 +215,7 @@ struct GlmMla {
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
|
||||
RAD_INT("head_dim", 256), RAD_INT("n_head_kv", 1),
|
||||
RAD_INT("block_size", 4),
|
||||
RAD_STR("kv_dtype", "bf16")),
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.latent }, {});
|
||||
/* Issued in finish, after this layer's indexer selects and before the attention reads
|
||||
@@ -239,15 +254,8 @@ struct GlmMla {
|
||||
{ in }, { out });
|
||||
};
|
||||
op_rows_absorb = project("absorb", r.q, r.q_latent);
|
||||
op_rows_attn =
|
||||
rw(b,
|
||||
RAD_OP(b, "mla_attn",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("latent_dim", 512),
|
||||
RAD_INT("heads", 64), RAD_INT("blocks", core.c.blocks),
|
||||
RAD_INT("block_size", 4), RAD_F64("scale", 1.0 / std::sqrt(256.0)),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ r.q_latent, w.core.selected, w.core.length }, { r.attn_latent });
|
||||
op_rows_attn = rw(b, MlaLatent::attn_op(b, g, R, 64, core.c.blocks, 1.0 / std::sqrt(256.0)),
|
||||
{ r.q_latent, w.core.selected, w.core.length }, { r.attn_latent });
|
||||
op_rows_expand = project("expand", r.attn_latent, r.attn.x);
|
||||
RAD_ARCH_TRY(rows_quant.declare(b, g, r.attn, 16384));
|
||||
rows_output.stored = nm.f("blk.%d.attn_output.weight", layer);
|
||||
|
||||
@@ -16,7 +16,11 @@
|
||||
* before the layer's attention, `join` (the residual add and the proposal rows' selection) between
|
||||
* its attention and its feed-forward, `head` after it. The embedding and lm_head are the trunk's.
|
||||
* Its names live under the `mtp.` scope (Names), its weights in layer 45's group. eh_proj
|
||||
* (4096 x 8192 bf16, 64 MiB) is replicated and read whole in every draft pass. */
|
||||
* (4096 x 8192 bf16, 64 MiB) is replicated and read whole in every draft pass.
|
||||
*
|
||||
* The same head serves another DeepSeek-style drafter by its checkpoint layout, set before
|
||||
* declare_inputs: the residual width, the layer's checkpoint prefix and index, and the name of the
|
||||
* head's final norm (Ling-3.0: 2560, `model.layers.42`, 42, `final_layernorm.weight`). */
|
||||
#ifndef RAD_BLOCK_GLM_MTP_H
|
||||
#define RAD_BLOCK_GLM_MTP_H
|
||||
#include "rad_glm_tp.h"
|
||||
@@ -31,6 +35,10 @@ struct GlmMtp {
|
||||
rad_weight token = 0, head = 0;
|
||||
};
|
||||
static constexpr int kDepth = 3; /* --num-speculative-tokens auto */
|
||||
int64_t width = 4096;
|
||||
const char* prefix = "model.language_model.layers.45";
|
||||
int layer = 45;
|
||||
const char* norm_src = "shared_head.norm.weight";
|
||||
Names nm{ "mtp" };
|
||||
Geom g{};
|
||||
Wire w{};
|
||||
@@ -50,47 +58,48 @@ struct GlmMtp {
|
||||
w = wire;
|
||||
if (!b || !w.final_hidden || !w.logits || !w.token || !w.head || g.max_spec < 1)
|
||||
return RAD_E_INVAL;
|
||||
x = decl_b(b, nm.f("x"), RAD_BF16, { g.max_tok, 4096 });
|
||||
hidden = decl_b(b, nm.f("hidden"), RAD_BF16, { g.max_tok, 4096 }, RAD_BUF_PERSIST);
|
||||
embedding = decl_b(b, nm.f("embedding"), RAD_BF16, { g.max_tok, 4096 });
|
||||
concat = decl_b(b, nm.f("concat"), RAD_BF16, { g.max_tok, 8192 });
|
||||
out = decl_b(b, nm.f("final"), RAD_BF16, { g.max_tok, 4096 });
|
||||
const char* pre = "model.language_model.layers.45";
|
||||
const int64_t E = width;
|
||||
x = decl_b(b, nm.f("x"), RAD_BF16, { g.max_tok, E });
|
||||
hidden = decl_b(b, nm.f("hidden"), RAD_BF16, { g.max_tok, E }, RAD_BUF_PERSIST);
|
||||
embedding = decl_b(b, nm.f("embedding"), RAD_BF16, { g.max_tok, E });
|
||||
concat = decl_b(b, nm.f("concat"), RAD_BF16, { g.max_tok, 2 * E });
|
||||
out = decl_b(b, nm.f("final"), RAD_BF16, { g.max_tok, E });
|
||||
const char* pre = prefix;
|
||||
auto gain = [&](const char* n, const char* src) {
|
||||
const char* name = nm.f("%s", n);
|
||||
if (map_copy(b, name, nm.ckpt("%s.%s", pre, src)) < 0) return (rad_weight)0;
|
||||
return decl_w(b, name, RAD_F32, { 4096 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp_layer(45));
|
||||
return decl_w(b, name, RAD_F32, { E }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp_layer(layer));
|
||||
};
|
||||
en = gain("enorm.weight", "enorm.weight");
|
||||
hn = gain("hnorm.weight", "hnorm.weight");
|
||||
norm = gain("output_norm.weight", "shared_head.norm.weight");
|
||||
norm = gain("output_norm.weight", norm_src);
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("eh_proj.weight"), nm.ckpt("%s.eh_proj.weight", pre)));
|
||||
eh = decl_w(b, nm.f("eh_proj.weight"), RAD_BF16, { 4096, 8192 }, RAD_ACCESS_PER_TOKEN,
|
||||
RAD_SHARD_NONE, grp_layer(45));
|
||||
eh = decl_w(b, nm.f("eh_proj.weight"), RAD_BF16, { E, 2 * E }, RAD_ACCESS_PER_TOKEN,
|
||||
RAD_SHARD_NONE, grp_layer(layer));
|
||||
if (!x || !hidden || !embedding || !concat || !out || !en || !hn || !norm || !eh)
|
||||
return RAD_E_INVAL;
|
||||
op_prev = rw(b,
|
||||
RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096),
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", E),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.final_hidden }, { hidden });
|
||||
op_embed = rw(b,
|
||||
RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", 4096),
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", E),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
|
||||
RAD_INT("vocab_offset", g.vocab_off)),
|
||||
RAD_WEIGHTS(w.token)),
|
||||
{}, { embedding });
|
||||
if (media) RAD_ARCH_TRY(mrows.declare(b, g.max_tok, 4096, embedding));
|
||||
if (media) RAD_ARCH_TRY(mrows.declare(b, g.max_tok, E, embedding));
|
||||
op_embed_ar = GlmTp::reduce(b, g, embedding, true);
|
||||
op_en = rmsnorm(b, en, embedding, concat);
|
||||
op_hn = rmsnorm(b, hn, hidden, concat);
|
||||
op_eh = rw(b,
|
||||
RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", 4096),
|
||||
RAD_INT("K", 8192), RAD_STR("dtype", "bf16")),
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", E),
|
||||
RAD_INT("K", 2 * E), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(eh)),
|
||||
{ concat }, { x });
|
||||
return op_prev && op_embed && op_en && op_hn && op_eh && (g.world == 1 || op_embed_ar)
|
||||
@@ -102,14 +111,14 @@ struct GlmMtp {
|
||||
int declare_join(RadBuilder* b, rad_buf y) {
|
||||
op_residual = rw(b,
|
||||
RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096),
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", width),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ x, y }, { x });
|
||||
// All history rows fill the draft cache; only proposal rows need its FFN.
|
||||
op_select = rw(b,
|
||||
RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", 4096),
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", width),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ x }, { hidden });
|
||||
@@ -124,7 +133,7 @@ struct GlmMtp {
|
||||
op_head = 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", 4096),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", width),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w.head)),
|
||||
{ hidden }, { w.logits });
|
||||
@@ -150,9 +159,9 @@ struct GlmMtp {
|
||||
RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w.token),
|
||||
brows(embedding, T));
|
||||
mrows.step(c, batch, embedding, T);
|
||||
if (op_embed_ar) RAD_ISSUE_N(c, op_embed_ar, T * 4096, brows(embedding, T), RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_en, T, brows(embedding, T), RAD_W(en), bcol(concat, 0, 4096, T));
|
||||
RAD_ISSUE_N(c, op_hn, T, brows(hidden, T), RAD_W(hn), bcol(concat, 4096, 4096, T));
|
||||
if (op_embed_ar) RAD_ISSUE_N(c, op_embed_ar, T * width, brows(embedding, T), RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_en, T, brows(embedding, T), RAD_W(en), bcol(concat, 0, width, T));
|
||||
RAD_ISSUE_N(c, op_hn, T, brows(hidden, T), RAD_W(hn), bcol(concat, width, width, T));
|
||||
RAD_ISSUE_N(c, op_eh, T, brows(concat, T), RAD_W(eh), brows(x, T));
|
||||
}
|
||||
void step_join(RadCtx* c, const RadBatch* batch, rad_buf y) const {
|
||||
@@ -175,18 +184,13 @@ private:
|
||||
rad_op rmsnorm(RadBuilder* b, rad_weight gain, rad_buf in, rad_buf out) const {
|
||||
return rw(b,
|
||||
RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096),
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", width),
|
||||
RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(gain)),
|
||||
{ in }, { out });
|
||||
}
|
||||
rad_op cast(RadBuilder* b, rad_buf in, rad_buf out) const {
|
||||
return rw(b,
|
||||
RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096),
|
||||
RAD_STR("from", "bf16"), RAD_STR("to", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ in }, { out });
|
||||
return cast_op(b, g.max_tok, width, "bf16", "bf16", in, out);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
/* GLM noaux_tc router. Correction bias changes selection only; mixture weights
|
||||
* come from the uncorrected sigmoid probabilities. All routing arithmetic is F32. */
|
||||
* come from the uncorrected probabilities -- sigmoid, or the score Config::score names
|
||||
* (DeepSeek-V4's sqrt(softplus)). All routing arithmetic is F32. With `groups`
|
||||
* above 1 the selection is group-limited (router_sigmoid_group_topk, Ling-3.0's 8 groups, 4 kept). */
|
||||
#ifndef RAD_BLOCK_GLM_ROUTER_H
|
||||
#define RAD_BLOCK_GLM_ROUTER_H
|
||||
#include "rad_glm_tp.h"
|
||||
@@ -9,12 +11,20 @@ namespace rad {
|
||||
namespace arch {
|
||||
struct GlmRouter {
|
||||
struct Config {
|
||||
int64_t experts = 288, top_k = 8, rows = 32;
|
||||
int64_t experts = 288, top_k = 8, rows = 32, groups = 1, topk_groups = 1;
|
||||
int norm = 1;
|
||||
double route_scale = 2.5;
|
||||
/* The score function by name (router_scored_topk: "sqrtsoftplus" for DeepSeek-V4); null is
|
||||
* GLM's sigmoid (router_sigmoid_topk). */
|
||||
const char* score = nullptr;
|
||||
/* Image-span routing: with `vl` set, `Src::correction_vl` (bias_vl) is the correction on
|
||||
* rows whose mask (RadBatch::vl_mask) is 1 and `correction` on the rest
|
||||
* (router_scored_topk_vl). Selection only, weights as on the text rows. */
|
||||
int vl = 0;
|
||||
};
|
||||
struct Src {
|
||||
const char *weight = nullptr, *correction = nullptr;
|
||||
const char *correction_vl = nullptr;
|
||||
};
|
||||
struct Wire {
|
||||
rad_buf input = 0, logits = 0, ids = 0, weights = 0;
|
||||
@@ -22,8 +32,8 @@ struct GlmRouter {
|
||||
Geom g{};
|
||||
Config c{};
|
||||
Wire w{};
|
||||
rad_weight projection = 0, correction = 0;
|
||||
rad_op op_project = 0, op_select = 0;
|
||||
rad_weight projection = 0, correction = 0, correction_vl_w = 0;
|
||||
rad_op op_project = 0, op_select = 0, op_select_vl = 0;
|
||||
SplitF32Proj split{};
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int layer, const char* name,
|
||||
@@ -33,8 +43,9 @@ struct GlmRouter {
|
||||
w = wire;
|
||||
if (!b || !name || !src.weight || !src.correction || g.n_embd < 1 || c.experts < 1 ||
|
||||
c.experts > 512 || c.top_k < 1 || c.top_k > c.experts || c.rows < 1 ||
|
||||
c.rows > g.max_tok || !std::isfinite(c.route_scale) || c.route_scale <= 0 || !w.input ||
|
||||
!w.logits || !w.ids || !w.weights || w.logits == w.weights)
|
||||
c.rows > g.max_tok || !std::isfinite(c.route_scale) || c.route_scale <= 0 ||
|
||||
c.groups < 1 || c.experts % c.groups || c.topk_groups < 1 || c.topk_groups > c.groups ||
|
||||
!w.input || !w.logits || !w.ids || !w.weights || w.logits == w.weights)
|
||||
return RAD_E_INVAL;
|
||||
const char *pn = nm.f("%s.weight", name), *cn = nm.f("%s.correction", name);
|
||||
RAD_ARCH_TRY(map_copy(b, pn, src.weight));
|
||||
@@ -52,16 +63,66 @@ struct GlmRouter {
|
||||
{ w.input }, { w.logits });
|
||||
RAD_ARCH_TRY(split.declare(b, nm, g, name, c.rows, c.experts, g.n_embd, projection, w.input,
|
||||
w.logits));
|
||||
op_select =
|
||||
rw(b,
|
||||
RAD_OP(b, "router_sigmoid_topk",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n_expert", c.experts),
|
||||
RAD_INT("top_k", c.top_k), RAD_INT("norm", c.norm),
|
||||
RAD_F64("route_scale", c.route_scale), RAD_STR("dtype", "f32")),
|
||||
RAD_WEIGHTS(correction)),
|
||||
{ w.logits }, { w.ids, w.weights });
|
||||
if (c.score)
|
||||
op_select =
|
||||
rw(b,
|
||||
RAD_OP(b, "router_scored_topk",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n_expert", c.experts),
|
||||
RAD_INT("top_k", c.top_k), RAD_INT("norm", c.norm),
|
||||
RAD_F64("route_scale", c.route_scale),
|
||||
RAD_STR("score", c.score), RAD_STR("dtype", "f32")),
|
||||
RAD_WEIGHTS(correction)),
|
||||
{ w.logits }, { w.ids, w.weights });
|
||||
else if (c.groups > 1)
|
||||
op_select =
|
||||
rw(b,
|
||||
RAD_OP(b, "router_sigmoid_group_topk",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n_expert", c.experts),
|
||||
RAD_INT("top_k", c.top_k), RAD_INT("n_group", c.groups),
|
||||
RAD_INT("topk_group", c.topk_groups), RAD_INT("norm", c.norm),
|
||||
RAD_F64("route_scale", c.route_scale), RAD_STR("dtype", "f32")),
|
||||
RAD_WEIGHTS(correction)),
|
||||
{ w.logits }, { w.ids, w.weights });
|
||||
else
|
||||
op_select =
|
||||
rw(b,
|
||||
RAD_OP(b, "router_sigmoid_topk",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n_expert", c.experts),
|
||||
RAD_INT("top_k", c.top_k), RAD_INT("norm", c.norm),
|
||||
RAD_F64("route_scale", c.route_scale), RAD_STR("dtype", "f32")),
|
||||
RAD_WEIGHTS(correction)),
|
||||
{ w.logits }, { w.ids, w.weights });
|
||||
if (c.vl) {
|
||||
if (!src.correction_vl || !c.score) return RAD_E_INVAL;
|
||||
const char* vn = nm.f("%s.correction_vl", name);
|
||||
RAD_ARCH_TRY(map_copy(b, vn, src.correction_vl));
|
||||
correction_vl_w = decl_w(b, vn, RAD_F32, { c.experts }, RAD_ACCESS_PER_TOKEN,
|
||||
RAD_SHARD_NONE, grp_layer(layer));
|
||||
if (!correction_vl_w) return RAD_E_INVAL;
|
||||
op_select_vl =
|
||||
rw(b,
|
||||
RAD_OP(b, "router_scored_topk_vl",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n_expert", c.experts),
|
||||
RAD_INT("top_k", c.top_k), RAD_INT("norm", c.norm),
|
||||
RAD_F64("route_scale", c.route_scale),
|
||||
RAD_STR("score", c.score), RAD_STR("dtype", "f32")),
|
||||
RAD_WEIGHTS(correction, correction_vl_w)),
|
||||
{ w.logits }, { w.ids, w.weights });
|
||||
if (!op_select_vl) return RAD_E_INVAL;
|
||||
}
|
||||
return op_project && op_select ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
bool masked() const { return op_select_vl != 0; }
|
||||
/* The masked select: same projection, then the vl op with the row mask (RadBatch::vl_mask;
|
||||
* 1 inside an image span). */
|
||||
void step_masked(RadCtx* ctx, int64_t first, int64_t rows, int64_t output_first,
|
||||
RadOperand mask) const {
|
||||
project(ctx, first, rows, output_first);
|
||||
RAD_ISSUE_N(ctx, op_select_vl, rows, brow_slice(w.logits, output_first, rows, c.experts),
|
||||
RAD_W(correction), RAD_W(correction_vl_w), mask,
|
||||
brow_slice(w.ids, output_first, rows, c.top_k),
|
||||
brow_slice(w.weights, output_first, rows, c.top_k));
|
||||
}
|
||||
void project(RadCtx* ctx, int64_t first, int64_t rows, int64_t output_first = 0) const {
|
||||
if (split.takes(rows))
|
||||
split.step(ctx, rows, brow_slice(w.input, first, rows, g.n_embd), projection,
|
||||
|
||||
+57
-18
@@ -33,7 +33,7 @@
|
||||
#ifndef RAD_BLOCK_HC_H
|
||||
#define RAD_BLOCK_HC_H
|
||||
|
||||
#include "rad_fp8.h"
|
||||
#include "rad_linear.h"
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
@@ -77,12 +77,13 @@ struct HyperConn {
|
||||
* 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. */
|
||||
/* Whether the read also emits Hadamard-rotated codes of the block input, for a consumer
|
||||
* whose weight carries the rotation (MoeQ'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. */
|
||||
* (LinearQ::i8). The rotated codes take the same dtype (had_quant_act_i8g's beside int8,
|
||||
* had_quant_act_fp8's beside E4M3), so `Wire::rq` is declared to match. */
|
||||
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
|
||||
@@ -93,7 +94,7 @@ struct HyperConn {
|
||||
|
||||
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 */
|
||||
ActQ 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 */
|
||||
@@ -115,6 +116,11 @@ struct HyperConn {
|
||||
* `mix`), read from their encoding at declare. */
|
||||
bool mix_e4m3 = false;
|
||||
rad_op op_read = 0, op_write = 0;
|
||||
/* The block input's own int8 pair is the rotated one (ActQ::q8_rot, a trunk stored rotated):
|
||||
* the read writes its rotated codes there and its plain ones into `pq` / `ps`, a pair of this
|
||||
* connection's that nothing reads. */
|
||||
bool xrot = false;
|
||||
rad_buf pq = 0, ps = 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
|
||||
@@ -164,10 +170,21 @@ struct HyperConn {
|
||||
* (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 {
|
||||
void read_pieces(RadCtx* c_, int64_t T) const { read_span(c_, T, 0, T); }
|
||||
/* The same with a boundary at `cut` (a checkpoint inside the step, RadBatch::ckpt_cut): rows
|
||||
* [0, cut) are read as a chunk of `cut` rows reads them, then [cut, T) on their own; 0 is
|
||||
* none. */
|
||||
void read_pieces(RadCtx* c_, int64_t T, int64_t cut) const {
|
||||
if (cut <= 0 || cut >= T) { read_span(c_, T, 0, T); return; }
|
||||
read_span(c_, T, 0, cut);
|
||||
read_span(c_, T, cut, T);
|
||||
}
|
||||
/* Rows [a, b) in pieces of Config::read_rows from `a`; one read where they fit in one. */
|
||||
void read_span(RadCtx* c_, int64_t T, int64_t a, int64_t b) 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);
|
||||
auto one = [&](int64_t r0, int64_t n) { read(c_, T, r0, n); };
|
||||
if (piece <= 0 || b - a <= piece) { one(a, b - a); return; }
|
||||
for (int64_t r0 = a; r0 < b; r0 += piece) one(r0, b - r0 < piece ? b - r0 : piece);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -193,6 +210,17 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
|
||||
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;
|
||||
/* A trunk whose int8 linears are stored rotated reads the rotated codes alone: `x`'s int8 pair
|
||||
* is then that pair (ActQ::q8_rot), and every reader of the block input -- the trunk's
|
||||
* projections and the rotated experts -- takes it. The read derives the rotated codes in its
|
||||
* plain codes' finisher, so the plain ones still have somewhere to go: a pair of this
|
||||
* connection's own that nothing reads. */
|
||||
xrot = c.quant && c.codes_i8 && w.x.q8_rot;
|
||||
if (xrot && c.rotate) {
|
||||
fprintf(stderr, "radiance: %s: the block input's own codes are the rotated ones "
|
||||
"(ActQ::q8_rot), so there is no second rotated pair to ask for\n", name);
|
||||
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);
|
||||
@@ -248,8 +276,16 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
|
||||
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; }
|
||||
if (xrot) {
|
||||
pq = decl_b(b, nm.f("%s.plain.q8", name), RAD_I8, { g.max_tok, g.n_embd });
|
||||
ps = decl_b(b, nm.f("%s.plain.s8", name), RAD_F32, { g.max_tok, scale_groups(g.n_embd) });
|
||||
if (!pq || !ps || w.x.g8 != RAD_SCALE_GROUP) return RAD_E_INVAL;
|
||||
wr[n_wr++] = pq; wr[n_wr++] = ps;
|
||||
wr[n_wr++] = w.x.q8; wr[n_wr++] = w.x.s8;
|
||||
} else {
|
||||
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
|
||||
@@ -258,8 +294,8 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
|
||||
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_INT("group", c.quant ? RAD_SCALE_GROUP : 0),
|
||||
RAD_INT("rotate", (c.rotate || xrot) ? 1 : 0),
|
||||
RAD_STR("mix", mix_e4m3 ? "e4m3" : "bf16")),
|
||||
wts, n_wts);
|
||||
if (!op_read) return RAD_E_INVAL;
|
||||
@@ -358,11 +394,14 @@ inline void HyperConn::read(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) con
|
||||
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);
|
||||
c.quant ? brow_slice(xrot ? pq : c.codes_i8 ? w.x.q8 : w.x.q, r0, rows,
|
||||
g.n_embd) : RAD_NONE,
|
||||
c.quant ? brow_slice(xrot ? ps : c.codes_i8 ? w.x.s8 : w.x.s, r0, rows,
|
||||
scale_groups(g.n_embd)) : RAD_NONE,
|
||||
(c.rotate || xrot) ? brow_slice(xrot ? w.x.q8 : w.rq, r0, rows, g.n_embd)
|
||||
: RAD_NONE,
|
||||
(c.rotate || xrot) ? brow_slice(xrot ? w.x.s8 : w.rs, r0, rows,
|
||||
scale_groups(g.n_embd)) : RAD_NONE);
|
||||
}
|
||||
|
||||
/* ================================================================== the control-vector projection
|
||||
|
||||
@@ -0,0 +1,452 @@
|
||||
/* rad_block_inkling2_tower.h -- Inkling 2's vision tower as the engine serves it: declared beside
|
||||
* the text backbone (arch/inkling2), run on an encoder pass (RadBatch::enc), its rows read by the
|
||||
* core and scattered over the placeholders of a later step. rad_block_inkling2_vision.h is the same
|
||||
* tower over host f32 buffers (the golden's test); this one reads the container's bf16 weights and
|
||||
* the pass the core stages.
|
||||
*
|
||||
* Per pass, the processor (core/mm, Family::Inkling2) gives each picture one zero row at
|
||||
* coordinate (-1, -1) ahead of its patches, which are (y, x, channel) in merge-block order:
|
||||
*
|
||||
* x = rows @ Wp^T the patch embedding, bias-less; the class row
|
||||
* stays zero
|
||||
* x += pos(table, row, col), or cls grid_embed_hw: the 32 x 32 table resampled per
|
||||
* axis onto the picture's patch grid (torch's
|
||||
* bilinear, align_corners=False, clamped); the class
|
||||
* row takes class_embedding as its prefix row
|
||||
* x[class rows] += cls_pos table_add, one row a picture
|
||||
* x = LN_pre(x)
|
||||
* depth times (pre-norm, layer scale):
|
||||
* x += ls1 * proj(attn(rope(qkv(LN1(x))))) full attention within a picture, class row
|
||||
* included; rope's axial at theta 1e4, (column + 1,
|
||||
* row + 1), the class row (0, 0)
|
||||
* x += ls2 * c_proj(gelu(c_fc(LN2(x)))) exact GELU
|
||||
* g = each picture's patch rows gather_rows: the class row dropped; a merge cell's
|
||||
* four patches are consecutive, so g read as
|
||||
* [P / 4, 4 width] is the reference's 2 x 2 merge,
|
||||
* columns (dy, dx, channel)
|
||||
* out = proj_out(gelu(proj_in(g))) both bias-less (projector_bias false)
|
||||
*
|
||||
* The reference's rotary turns the adjacent pairs (2j, 2j + 1) of each half of a head, the first
|
||||
* half by the column and the second by the row, at theta^(-j / (head_dim / 4)) (vLLM's
|
||||
* inkling2/nvidia/ops/vision.py, llama.cpp's build_rope_2d). rope's `axial` pairs (i, i + head_dim
|
||||
* / 2) instead, so q and k are stored with their rows permuted within each head (row-piece maps,
|
||||
* done at convert: the container holds the permuted rows), which turns the same angles onto the
|
||||
* same pairs. Every q . k is unchanged; v is not permuted. rad_block_inkling2_vision.h's rope_perm
|
||||
* is the permutation.
|
||||
*
|
||||
* Weights are replicated per-request bf16 (RAD_ACCESS_PER_REQUEST), the blocks one group each from
|
||||
* `first_group`, as the other towers in arch/ do. Activations are pass-sized (RadBuildCtx::
|
||||
* max_enc_patches rows), except in a sizing declare (shape_probe), where they follow the probe's
|
||||
* step and the attention's longest segment stays at the real pass.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_INKLING2_TOWER_H
|
||||
#define RAD_BLOCK_INKLING2_TOWER_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
#include "rad_block_inkling2_vision.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct Inkling2Tower {
|
||||
int64_t depth = 0, width = 0, heads = 0, head_dim = 0, ff = 0, patch = 0, merge = 0;
|
||||
int64_t side = 0, proj = 0, n_embd = 0, patch_dim = 0, P = 0, R = 0;
|
||||
double eps = 1e-5;
|
||||
double theta = 1e4;
|
||||
bool on = false;
|
||||
char sec[48] = {};
|
||||
|
||||
struct Layer {
|
||||
rad_weight n1w = 0, n1b = 0, n2w = 0, n2b = 0, ls1 = 0, ls2 = 0;
|
||||
rad_weight qkv_w = 0, qkv_b = 0, o_w = 0, o_b = 0, fc_w = 0, fc_b = 0, pr_w = 0, pr_b = 0;
|
||||
rad_op ln1 = 0, qkv = 0, rope = 0, attn = 0, o = 0, ls1_op = 0, add1 = 0;
|
||||
rad_op ln2 = 0, fc = 0, pr = 0, ls2_op = 0, add2 = 0;
|
||||
};
|
||||
std::vector<Layer> L;
|
||||
rad_weight w_patch = 0, w_pos = 0, w_cls = 0, w_clspos = 0, w_pre = 0, w_preb = 0;
|
||||
rad_weight w_in = 0, w_out = 0;
|
||||
rad_op op_patch = 0, op_pos = 0, op_clspos = 0, op_lpre = 0, op_order = 0, op_seq = 0;
|
||||
rad_op op_gather = 0, op_in = 0, op_gelu = 0, op_out = 0;
|
||||
rad_buf b_x = 0, b_s = 0, b_h = 0, b_qkv = 0, b_att = 0, b_t = 0, b_ff = 0;
|
||||
rad_buf b_idx = 0, b_inv = 0, b_pos = 0, b_cuw = 0, b_seq = 0;
|
||||
rad_buf b_g = 0, b_m1 = 0, b_m2 = 0, b_out = 0;
|
||||
|
||||
/* The container's vision_config names this tower. */
|
||||
static bool present(const RadModelMeta* m) {
|
||||
return !std::strcmp(rad_meta_gets(m, "vision_config.model_type", ""), "inkling2_vision") &&
|
||||
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 Inkling2Tower::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 = (int64_t)std::llround(rad_meta_getf(m, "vision_config.mlp_ratio", 0.0) * (double)width);
|
||||
patch = rad_meta_geti(m, "vision_config.native_patch_size", 0);
|
||||
merge = rad_meta_geti(m, "vision_config.adapter_merge_size", 0);
|
||||
side = rad_meta_geti(m, "vision_config.posemb_grid_size", 0);
|
||||
proj = rad_meta_geti(m, "vision_config.projection_hidden_dim", 0);
|
||||
eps = rad_meta_getf(m, "vision_config.layer_norm_eps", 1e-5);
|
||||
n_embd = model_embd;
|
||||
const int64_t text = rad_meta_geti(m, "vision_config.text_hidden_size", model_embd);
|
||||
if (depth <= 0 || depth > 128 || width <= 0 || heads <= 0 || width % heads || ff <= 0 ||
|
||||
patch <= 0 || merge <= 0 || side <= 0 || side > 512 || proj <= 0 || text != model_embd) {
|
||||
fprintf(stderr, "radiance: inkling2: the container's vision_config is incomplete or "
|
||||
"inconsistent (layers %lld, hidden %lld, heads %lld, ff %lld, patch %lld, "
|
||||
"merge %lld, position grid %lld, projector %lld, text width %lld against "
|
||||
"the model's %lld)\n", (long long)depth, (long long)width,
|
||||
(long long)heads, (long long)ff, (long long)patch, (long long)merge,
|
||||
(long long)side, (long long)proj, (long long)text, (long long)model_embd);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* What is served of the config: the 2 x 2 merge (a cell is four consecutive rows) and the
|
||||
* bias-less projector the release states. */
|
||||
if (merge != 2 || rad_meta_geti(m, "vision_config.projector_bias", 0) != 0) {
|
||||
fprintf(stderr, "radiance: inkling2: this vision tower states merge %lld and projector_bias "
|
||||
"%lld; the 2 x 2 merge and a bias-less projector are served\n",
|
||||
(long long)merge, (long long)rad_meta_geti(m, "vision_config.projector_bias", 0));
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
head_dim = width / heads;
|
||||
if (head_dim % 4) return RAD_E_SHAPE;
|
||||
patch_dim = 3 * patch * patch;
|
||||
const int64_t mm = merge * merge, mw = mm * width;
|
||||
std::snprintf(sec, sizeof sec, "%lld %lld", (long long)(head_dim / 4),
|
||||
(long long)(head_dim / 4));
|
||||
|
||||
/* A pass's rows, class rows included; its output rows are at most a quarter of them. */
|
||||
P = ctx->max_enc_patches;
|
||||
const int64_t max_seg = P;
|
||||
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);
|
||||
}
|
||||
R = P / mm;
|
||||
if (R <= 0) return RAD_E_SHAPE;
|
||||
const int ACC = RAD_ACCESS_PER_REQUEST;
|
||||
|
||||
const char* vb = "model.visual.backbone";
|
||||
if (map_copy(b, nm.f("v.patch.weight"), nm.ckpt("%s.embeddings.patch_embedding.weight", vb)) < 0)
|
||||
return RAD_E_INVAL;
|
||||
/* Whether the tower is here at all: its stem's encoding, which convert answers from the
|
||||
* checkpoint and load from the container alike. A container converted without it (the text
|
||||
* recipe's) serves text; the maps left behind are inert. */
|
||||
{
|
||||
RadEncoding enc;
|
||||
if (rad_weight_encoding(b, nm.f("v.patch.weight"), &enc, nullptr, nullptr) != RAD_OK) {
|
||||
rad_note(b, "inkling2: vision_config names a tower its weights are not here for; "
|
||||
"serving text");
|
||||
return RAD_OK;
|
||||
}
|
||||
}
|
||||
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;
|
||||
RadEncoding e{};
|
||||
if (weight_enc(b, dn, &e) &&
|
||||
!(rad_enc_is(&e, "plain") && e.n_planes == 1 && e.plane[0].dtype == RAD_BF16)) {
|
||||
fprintf(stderr, "radiance: inkling2 vision: '%s' must be bf16\n", dn);
|
||||
return 0;
|
||||
}
|
||||
return decl_w(b, dn, RAD_BF16, shp, ACC, RAD_SHARD_NONE, g);
|
||||
};
|
||||
w_patch = decl_w(b, nm.f("v.patch.weight"), RAD_BF16, { width, patch_dim }, ACC,
|
||||
RAD_SHARD_NONE, grp_model());
|
||||
w_pos = bw(nm.f("v.pos.weight"), nm.ckpt("%s.embeddings.position_embedding", vb),
|
||||
{ side * side, width }, grp_model());
|
||||
w_cls = bw(nm.f("v.cls.weight"), nm.ckpt("%s.embeddings.class_embedding", vb), { width },
|
||||
grp_model());
|
||||
w_clspos = bw(nm.f("v.cls_pos.weight"), nm.ckpt("%s.embeddings.cls_position_embedding", vb),
|
||||
{ width }, grp_model());
|
||||
w_pre = bw(nm.f("v.ln_pre.weight"), nm.ckpt("%s.ln_pre.weight", vb), { width }, grp_model());
|
||||
w_preb = bw(nm.f("v.ln_pre.bias"), nm.ckpt("%s.ln_pre.bias", vb), { width }, grp_model());
|
||||
|
||||
/* q | k | v joined into one projection, q's and k's rows permuted within each head onto
|
||||
* rope's axial pairing (see the header), one row piece a row; v whole. */
|
||||
std::vector<int64_t> src_row((size_t)width);
|
||||
for (int64_t r = 0; r < width; ++r) {
|
||||
const int64_t h = r / head_dim, d = r % head_dim;
|
||||
src_row[(size_t)(h * head_dim + inkling2v::rope_perm(d, head_dim))] = r;
|
||||
}
|
||||
auto qkv_map = [&](const char* dn, const char* qn, const char* kn, const char* vn) -> int {
|
||||
for (const char* srcn : { qn, kn }) {
|
||||
for (int64_t r = 0; r < width; r += 8) {
|
||||
RadNameMap mp = map_base(dn, RAD_MAP_ROWS);
|
||||
for (int64_t k = r; k < std::min<int64_t>(r + 8, width); ++k) {
|
||||
mp.src[mp.n_src] = srcn;
|
||||
mp.src_index[mp.n_src] = (int)src_row[(size_t)k];
|
||||
mp.src_rows[mp.n_src] = 1;
|
||||
++mp.n_src;
|
||||
}
|
||||
if (rad_decl_name_map(b, &mp) < 0) return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
return map_rows(b, dn, { { vn, 0, width } });
|
||||
};
|
||||
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;
|
||||
auto src = [&](const char* s) { return nm.ckpt("%s.layers.%d.%s", vb, li, s); };
|
||||
auto dn = [&](const char* s) { return nm.f("v.blk.%d.%s", li, s); };
|
||||
l.n1w = bw(dn("ln_1.weight"), src("ln_1.weight"), { width }, g);
|
||||
l.n1b = bw(dn("ln_1.bias"), src("ln_1.bias"), { width }, g);
|
||||
l.n2w = bw(dn("ln_2.weight"), src("ln_2.weight"), { width }, g);
|
||||
l.n2b = bw(dn("ln_2.bias"), src("ln_2.bias"), { width }, g);
|
||||
l.ls1 = bw(dn("ls_1.gamma"), src("ls_1.gamma"), { width }, g);
|
||||
l.ls2 = bw(dn("ls_2.gamma"), src("ls_2.gamma"), { width }, g);
|
||||
{
|
||||
/* nm.ckpt returns a scratch string per call: keep the three names apart. */
|
||||
const std::string q = src("self_attn.q_proj.weight"), k = src("self_attn.k_proj.weight"),
|
||||
v = src("self_attn.v_proj.weight");
|
||||
const std::string qb = src("self_attn.q_proj.bias"), kb = src("self_attn.k_proj.bias"),
|
||||
vbn = src("self_attn.v_proj.bias");
|
||||
const std::string wn = dn("qkv.weight"), bn = dn("qkv.bias");
|
||||
RAD_ARCH_TRY(qkv_map(wn.c_str(), q.c_str(), k.c_str(), v.c_str()));
|
||||
RAD_ARCH_TRY(qkv_map(bn.c_str(), qb.c_str(), kb.c_str(), vbn.c_str()));
|
||||
l.qkv_w = decl_w(b, wn.c_str(), RAD_BF16, { 3 * width, width }, ACC, RAD_SHARD_NONE, g);
|
||||
l.qkv_b = decl_w(b, bn.c_str(), RAD_BF16, { 3 * width }, ACC, RAD_SHARD_NONE, g);
|
||||
}
|
||||
l.o_w = bw(dn("out_proj.weight"), src("self_attn.out_proj.weight"), { width, width }, g);
|
||||
l.o_b = bw(dn("out_proj.bias"), src("self_attn.out_proj.bias"), { width }, g);
|
||||
l.fc_w = bw(dn("c_fc.weight"), src("mlp.c_fc.weight"), { ff, width }, g);
|
||||
l.fc_b = bw(dn("c_fc.bias"), src("mlp.c_fc.bias"), { ff }, g);
|
||||
l.pr_w = bw(dn("c_proj.weight"), src("mlp.c_proj.weight"), { width, ff }, g);
|
||||
l.pr_b = bw(dn("c_proj.bias"), src("mlp.c_proj.bias"), { width }, g);
|
||||
if (!l.n1w || !l.n1b || !l.n2w || !l.n2b || !l.ls1 || !l.ls2 || !l.qkv_w || !l.qkv_b ||
|
||||
!l.o_w || !l.o_b || !l.fc_w || !l.fc_b || !l.pr_w || !l.pr_b)
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
w_in = bw(nm.f("v.proj_in.weight"), nm.ckpt("model.visual.proj_in.weight"), { proj, mw },
|
||||
grp_model());
|
||||
w_out = bw(nm.f("v.proj_out.weight"), nm.ckpt("model.visual.proj_out.weight"),
|
||||
{ n_embd, proj }, grp_model());
|
||||
if (!w_patch || !w_pos || !w_cls || !w_clspos || !w_pre || !w_preb || !w_in || !w_out)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
/* ---- activations. `g` holds the gathered patch rows at `width`, read by proj_in as R rows
|
||||
* of mm * width (the merge's view, no copy). */
|
||||
b_x = decl_b(b, nm.f("v.x"), RAD_BF16, { P, width });
|
||||
b_s = decl_b(b, nm.f("v.s"), 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_t = decl_b(b, nm.f("v.t"), RAD_BF16, { P, width });
|
||||
b_ff = decl_b(b, nm.f("v.ff"), RAD_BF16, { P, ff });
|
||||
b_idx = decl_b(b, nm.f("v.idx"), RAD_I32, { P });
|
||||
b_inv = decl_b(b, nm.f("v.inv"), RAD_I32, { P });
|
||||
b_pos = decl_b(b, nm.f("v.pos"), RAD_I32, { 2, P });
|
||||
b_cuw = decl_b(b, nm.f("v.cuw"), RAD_I32, { P + 1 });
|
||||
b_seq = decl_b(b, nm.f("v.seq"), RAD_I32, { P });
|
||||
b_g = decl_b(b, nm.f("v.g"), RAD_BF16, { R, mw });
|
||||
b_m1 = decl_b(b, nm.f("v.m1"), RAD_BF16, { R, proj });
|
||||
b_m2 = decl_b(b, nm.f("v.m2"), RAD_BF16, { R, proj });
|
||||
b_out = decl_b(b, nm.f("v.out"), RAD_BF16, { R, n_embd });
|
||||
if (!b_x || !b_s || !b_h || !b_qkv || !b_att || !b_t || !b_ff || !b_idx || !b_inv || !b_pos ||
|
||||
!b_cuw || !b_seq || !b_g || !b_m1 || !b_m2 || !b_out)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
auto gemm_b = [&](int64_t N, int64_t K, const char* a, rad_weight w, rad_weight bias) {
|
||||
return RAD_OP(b, "gemm_nt_bias",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_STR("dtype", "bf16"), RAD_STR("act", a)),
|
||||
RAD_WEIGHTS(w, bias));
|
||||
};
|
||||
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 lnorm = [&](rad_weight w, rad_weight bias) {
|
||||
return RAD_OP(b, "layernorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width), RAD_F64("eps", eps),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w, bias));
|
||||
};
|
||||
auto ew = [&](const char* op, rad_weight w) {
|
||||
return w ? RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w))
|
||||
: RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
|
||||
op_patch = rw(b, gemm(P, width, patch_dim, w_patch), {}, { b_x });
|
||||
op_pos = rw(b, RAD_OP(b, "grid_embed_hw",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
|
||||
RAD_INT("side", side), RAD_INT("n_prefix", 1),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_pos, w_cls)),
|
||||
{ b_x }, { b_x });
|
||||
op_clspos = rw(b, RAD_OP(b, "table_add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width), RAD_INT("L", 1),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_clspos)),
|
||||
{ b_x }, { b_x });
|
||||
op_lpre = rw(b, lnorm(w_pre, w_preb), { b_x }, { b_s });
|
||||
/* window 0: the identity order, whose positions are (column + 1, row + 1) -- the class row's
|
||||
* (-1, -1) coordinate gives it the reference's (0, 0). */
|
||||
op_order = rw(b, RAD_OP(b, "window_order",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("window", 0)),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, { b_idx, b_inv, b_pos, b_cuw });
|
||||
op_seq = rw(b, RAD_OP(b, "iota",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("start", 0), RAD_INT("step", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, { b_seq });
|
||||
for (Layer& l : L) {
|
||||
l.ln1 = rw(b, lnorm(l.n1w, l.n1b), { b_s }, { b_h });
|
||||
l.qkv = rw(b, gemm_b(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_pos }, { 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.o = rw(b, gemm_b(width, width, "none", l.o_w, l.o_b), { b_att }, { b_t });
|
||||
l.ls1_op = rw(b, ew("mul_weight", l.ls1), { b_t }, { b_att });
|
||||
l.add1 = rw(b, ew("add", 0), { b_s, b_att }, { b_s });
|
||||
l.ln2 = rw(b, lnorm(l.n2w, l.n2b), { b_s }, { b_h });
|
||||
l.fc = rw(b, gemm_b(ff, width, "gelu", l.fc_w, l.fc_b), { b_h }, { b_ff });
|
||||
l.pr = rw(b, gemm_b(width, ff, "none", l.pr_w, l.pr_b), { b_ff }, { b_t });
|
||||
l.ls2_op = rw(b, ew("mul_weight", l.ls2), { b_t }, { b_att });
|
||||
l.add2 = rw(b, ew("add", 0), { b_s, b_att }, { b_s });
|
||||
}
|
||||
op_gather = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_s, b_seq }, { b_g });
|
||||
op_in = rw(b, gemm(R, proj, mw, w_in), { b_g }, { b_m1 });
|
||||
op_gelu = rw(b, RAD_OP(b, "gelu",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", proj),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_m1 }, { b_m2 });
|
||||
op_out = rw(b, gemm(R, n_embd, proj, w_out), { b_m2 }, { 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 = ctx->max_enc_patches;
|
||||
e.n_embd = n_embd;
|
||||
e.out = b_out;
|
||||
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
|
||||
rad_note(b, "inkling2 vision tower: %lld blocks of %lld (%lld heads x %lld), ff %lld, patch "
|
||||
"%lld, %lld x %lld position table, one class row a picture, merge %lld; "
|
||||
"projector %lld -> %lld -> %lld; %lld rows a pass",
|
||||
(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)merge, (long long)mw, (long long)proj, (long long)n_embd,
|
||||
(long long)P);
|
||||
}
|
||||
on = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
inline void Inkling2Tower::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;
|
||||
/* Each picture is its class row and h x w patches, whole merge cells. */
|
||||
int64_t rows = 0, out_rows = 0;
|
||||
bool whole = on && Pn > 0 && Pn <= P && S > 0 && batch->enc_seg_h && batch->enc_seg_w &&
|
||||
batch->enc_pixels && batch->enc_coord && batch->enc_cu;
|
||||
for (int64_t s = 0; whole && s < S; ++s) {
|
||||
const int64_t hw = (int64_t)batch->enc_seg_h[s] * batch->enc_seg_w[s];
|
||||
whole = hw > 0 && hw % mm == 0;
|
||||
rows += 1 + hw;
|
||||
out_rows += hw / mm;
|
||||
}
|
||||
if (!whole || rows != Pn || out_rows > R) {
|
||||
rad_step_fail(c, "inkling2: an encoder pass this program's vision tower cannot serve: no "
|
||||
"tower, more rows than it was declared for, or pictures that are not a "
|
||||
"class row and whole merge cells");
|
||||
return;
|
||||
}
|
||||
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);
|
||||
RadOperand pos = RAD_B(b_pos);
|
||||
pos.rows = 2;
|
||||
pos.cols = Pn;
|
||||
RadOperand cuw = RAD_B(b_cuw);
|
||||
cuw.rows = S + 1;
|
||||
|
||||
RAD_ISSUE_N(c, op_patch, Pn, pix, RAD_W(w_patch), brows(b_x, Pn));
|
||||
RAD_ISSUE_N(c, op_pos, Pn, brows(b_x, Pn), RAD_W(w_pos), crd, RAD_W(w_cls));
|
||||
for (int64_t s = 0, r0 = 0; s < S; ++s) {
|
||||
RAD_ISSUE_N(c, op_clspos, 1, brow_slice(b_x, r0, 1, width), RAD_W(w_clspos),
|
||||
brow_slice(b_x, r0, 1, width));
|
||||
r0 += 1 + (int64_t)batch->enc_seg_h[s] * batch->enc_seg_w[s];
|
||||
}
|
||||
RAD_ISSUE_N(c, op_lpre, Pn, brows(b_x, Pn), RAD_W(w_pre), RAD_W(w_preb), brows(b_s, Pn));
|
||||
RAD_ISSUE_N(c, op_order, Pn, crd, cu, brows(b_idx, Pn), brows(b_inv, Pn), pos, cuw);
|
||||
RAD_ISSUE_N(c, op_seq, Pn, brows(b_seq, Pn));
|
||||
for (const Layer& l : L) {
|
||||
RAD_ISSUE_N(c, l.ln1, Pn, brows(b_s, 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), pos);
|
||||
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.o, Pn, brows(b_att, Pn), RAD_W(l.o_w), RAD_W(l.o_b), RAD_NONE,
|
||||
brows(b_t, Pn));
|
||||
RAD_ISSUE_N(c, l.ls1_op, Pn, brows(b_t, Pn), RAD_W(l.ls1), brows(b_att, Pn));
|
||||
RAD_ISSUE_N(c, l.add1, Pn, brows(b_s, Pn), brows(b_att, Pn), brows(b_s, Pn));
|
||||
RAD_ISSUE_N(c, l.ln2, Pn, brows(b_s, Pn), RAD_W(l.n2w), RAD_W(l.n2b), brows(b_h, Pn));
|
||||
RAD_ISSUE_N(c, l.fc, Pn, brows(b_h, Pn), RAD_W(l.fc_w), RAD_W(l.fc_b), RAD_NONE,
|
||||
brows(b_ff, Pn));
|
||||
RAD_ISSUE_N(c, l.pr, Pn, brows(b_ff, Pn), RAD_W(l.pr_w), RAD_W(l.pr_b), RAD_NONE,
|
||||
brows(b_t, Pn));
|
||||
RAD_ISSUE_N(c, l.ls2_op, Pn, brows(b_t, Pn), RAD_W(l.ls2), brows(b_att, Pn));
|
||||
RAD_ISSUE_N(c, l.add2, Pn, brows(b_s, Pn), brows(b_att, Pn), brows(b_s, Pn));
|
||||
}
|
||||
/* Each picture's patch rows, behind its class row, into `g` at width: picture s's rows
|
||||
* [r0 + 1, r0 + 1 + hw) of the stream, named by a slice of the identity index. */
|
||||
for (int64_t s = 0, r0 = 0, o0 = 0; s < S; ++s) {
|
||||
const int64_t hw = (int64_t)batch->enc_seg_h[s] * batch->enc_seg_w[s];
|
||||
RAD_ISSUE_N(c, op_gather, hw, brows(b_s, Pn), brow_slice(b_seq, r0 + 1, hw, 1),
|
||||
brow_slice(b_g, o0, hw / mm, mm * width));
|
||||
r0 += 1 + hw;
|
||||
o0 += hw / mm;
|
||||
}
|
||||
RAD_ISSUE_N(c, op_in, out_rows, brows(b_g, out_rows), RAD_W(w_in), brows(b_m1, out_rows));
|
||||
RAD_ISSUE_N(c, op_gelu, out_rows, brows(b_m1, out_rows), brows(b_m2, out_rows));
|
||||
RAD_ISSUE_N(c, op_out, out_rows, brows(b_m2, out_rows), RAD_W(w_out), brows(b_out, out_rows));
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_INKLING2_TOWER_H */
|
||||
@@ -0,0 +1,494 @@
|
||||
/* rad_block_inkling2_vision.h -- Inkling 2 Mini's vision tower: the patch embedding, the CLS
|
||||
* token, a pre-norm ViT with layer scale and a 2-D rotary, the 2 x 2 patch merge, and the two-layer
|
||||
* projector into the text width. Llama.cpp's inkling2v graph is the reference (its build_vit,
|
||||
* build_rope_2d and build_patch_merge_permute in mtmd-graph.cpp); tests/mkinkling2vision.py is the
|
||||
* float32 reference this block is checked against.
|
||||
*
|
||||
* WHAT IT COMPUTES, for a grid of gh x gw patches (n = gh * gw, M = n + 1 with the CLS row):
|
||||
*
|
||||
* p = pix_patch(image) [n, 3 p p], channel-major, (ph, pw) inside
|
||||
* x = p @ Wp^T gemm_nt, no bias
|
||||
* x += pos the learned side x side table on this grid
|
||||
* seq = [cls + cls_pos ; x] the CLS row first
|
||||
* seq = LN_pre(seq)
|
||||
* per block: seq += ls1 * proj(attn(rope(qkv(LN1(seq))))) full attention over all M rows
|
||||
* seq += ls2 * fc2(gelu(fc1(LN2(seq)))) exact erf GELU
|
||||
* cells = pixtral_merge(seq[1:], merge 2) [n / 4, 4 width], (channel, dy, dx) columns
|
||||
* out = proj_out(gelu(proj_in(cells))) no bias, projection hidden -> text width
|
||||
*
|
||||
* The rotary is llama's build_rope_2d: each head's first half turns by the row position and its
|
||||
* second half by the column position, each over adjacent pairs (2j, 2j + 1) at theta^(-j / (head_dim
|
||||
* / 4)). rope's axial mode pairs across the halves instead, so q and k are stored with their head
|
||||
* dimensions permuted (see the layout note), and the same rotation is then rope's axial with
|
||||
* sections (head_dim / 4, head_dim / 4) and components (row, column). The CLS row is at (0, 0) and
|
||||
* patch (y, x) at (y + 1, x + 1) (mtmd's encoder fills them).
|
||||
*
|
||||
* LAYOUT FIXES, done once when the weights are packed, not per call. The checkpoint's patch weight
|
||||
* is HWC-flattened and proj_in's columns are ordered (dy, dx, channel) (the converter does not
|
||||
* permute either, and llama's graph reads them so). The existing ops produce channel-major
|
||||
* features, pix_patch's `hw` order and pixtral_merge's (channel, dy, dx), so the packed weights are
|
||||
* column-permuted to match. The rotary's pairs are adjacent inside each half of a head, and rope's
|
||||
* axial pairs (i, i + head_dim / 2), so q and k rows are permuted within each head: dimension 2j
|
||||
* goes to j, 2j + 1 to j + head_dim / 2, and the second half's 2j to head_dim / 4 + j and 2j + 1 to
|
||||
* 3 head_dim / 4 + j. Applied to both, that leaves every q . k unchanged; v is not permuted.
|
||||
*
|
||||
* A GRID OTHER THAN THE TABLE'S. The learned table is side x side. An image whose grid differs from
|
||||
* it gets the table resampled to its grid first, by posemb_resample (align_corners off, edge taps
|
||||
* clamped: llama's bilinear, vLLM's kernel), into a buffer of the workspace's own. A grid equal to
|
||||
* the table reads the table itself, so the checkpoint's grid is unchanged bit for bit. The CLS row
|
||||
* takes no table position: its position is (0, 0) in the rotary and it is not on the grid.
|
||||
* The grid is the workspace's: Workspace::init fixes it, and forward refuses an image of another.
|
||||
*
|
||||
* HOW IT RUNS. `forward` issues ops through a launch callback (the engine's issue, or a host
|
||||
* kernel table in a test), so the same sequence is the one the engine declares. The tensors are
|
||||
* f32 throughout, with each op's rounding as libref's. Buffers are sized once by Workspace::init,
|
||||
* so the step path allocates nothing.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_INKLING2_VISION_H
|
||||
#define RAD_BLOCK_INKLING2_VISION_H
|
||||
|
||||
#include "rad_types.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
namespace inkling2v {
|
||||
|
||||
struct Geometry {
|
||||
int64_t depth = 0; /* ViT blocks */
|
||||
int64_t width = 0; /* the ViT width; head_dim = width / heads */
|
||||
int64_t heads = 0;
|
||||
int64_t patch = 0; /* native patch side */
|
||||
int64_t side = 0; /* the position table's grid side: the image is side * patch px square */
|
||||
int64_t merge = 2; /* the spatial merge */
|
||||
int64_t proj = 0; /* the projector's hidden width (4096 released) */
|
||||
int64_t text = 0; /* the text width the projector writes */
|
||||
float eps = 1e-5f; /* every LayerNorm */
|
||||
float theta = 1e4f;
|
||||
|
||||
int64_t head_dim() const { return heads > 0 ? width / heads : 0; }
|
||||
int64_t ff() const { return 4 * width; }
|
||||
int64_t n() const { return side * side; } /* the table's rows */
|
||||
};
|
||||
|
||||
/* The checkpoint's tensors, f32, in checkpoint layout. Non-owning: the reader keeps them alive. */
|
||||
struct LayerIn {
|
||||
const float *ln1_w, *ln1_b, *ln2_w, *ln2_b, *ls1, *ls2;
|
||||
const float *q_w, *q_b, *k_w, *k_b, *v_w, *v_b, *o_w, *o_b;
|
||||
const float *fc_w, *fc_b, *pr_w, *pr_b;
|
||||
};
|
||||
struct TowerIn {
|
||||
const float *cls, *cls_pos; /* [width] each */
|
||||
const float *patch_w; /* [width, 3 p p], HWC-flattened */
|
||||
const float *pos; /* [side^2, width] */
|
||||
const float *pre_w, *pre_b; /* ln_pre */
|
||||
std::vector<LayerIn> layers;
|
||||
const float *in_w; /* proj_in [proj, 4 width], (dy, dx, channel) columns */
|
||||
const float *out_w; /* proj_out [text, proj] */
|
||||
};
|
||||
|
||||
/* The weights in the layout the ops read, owned. */
|
||||
struct Packed {
|
||||
Geometry g;
|
||||
std::vector<float> cls, patch_w, pos, pre_w, pre_b, in_w, out_w;
|
||||
struct Layer {
|
||||
std::vector<float> ln1_w, ln1_b, ln2_w, ln2_b, ls1, ls2;
|
||||
std::vector<float> qkv_w, qkv_b; /* q, k, v stacked on rows: [3 width, width] */
|
||||
std::vector<float> o_w, o_b, fc_w, fc_b, pr_w, pr_b;
|
||||
};
|
||||
std::vector<Layer> layers;
|
||||
};
|
||||
|
||||
/* The within-head permutation of q and k: where head dimension d goes. The first half's pairs
|
||||
* (2j, 2j + 1) become axial's pairs (j, j + head_dim / 2), the second half's become (head_dim / 4 + j,
|
||||
* 3 head_dim / 4 + j), so axial turns each section's j-th pair at the section's ladder. */
|
||||
inline int64_t rope_perm(int64_t d, int64_t hd) {
|
||||
const int64_t half = hd / 2, quarter = hd / 4;
|
||||
if (d < half) return d % 2 == 0 ? d / 2 : d / 2 + half;
|
||||
const int64_t e = d - half;
|
||||
return e % 2 == 0 ? quarter + e / 2 : quarter + half + e / 2;
|
||||
}
|
||||
|
||||
/* Packs the checkpoint into the op layout. Done at declare; the step path only reads Packed. */
|
||||
inline int pack(const Geometry& g, const TowerIn& in, Packed* out) {
|
||||
if (g.depth <= 0 || g.width <= 0 || g.heads <= 0 || g.width % g.heads || g.head_dim() % 4 ||
|
||||
g.patch <= 0 || g.side <= 0 || g.merge != 2 || g.side % g.merge || g.proj <= 0 ||
|
||||
g.text <= 0 || (int64_t)in.layers.size() != g.depth)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t W = g.width, P = g.patch, pp = P * P, cpp = 3 * pp, PH = g.proj;
|
||||
out->g = g;
|
||||
out->cls.resize(W);
|
||||
for (int64_t i = 0; i < W; ++i) out->cls[i] = in.cls[i] + in.cls_pos[i];
|
||||
/* The patch weight is HWC inside each patch; pix_patch's `hw` order is channel-major. */
|
||||
out->patch_w.resize(W * cpp);
|
||||
for (int64_t o = 0; o < W; ++o)
|
||||
for (int64_t c = 0; c < 3; ++c)
|
||||
for (int64_t ph = 0; ph < P; ++ph)
|
||||
for (int64_t pw = 0; pw < P; ++pw)
|
||||
out->patch_w[o * cpp + c * pp + ph * P + pw] =
|
||||
in.patch_w[o * cpp + (ph * P + pw) * 3 + c];
|
||||
out->pos.assign(in.pos, in.pos + g.n() * W);
|
||||
out->pre_w.assign(in.pre_w, in.pre_w + W);
|
||||
out->pre_b.assign(in.pre_b, in.pre_b + W);
|
||||
/* pixtral_merge emits (channel, dy, dx) columns; the checkpoint has (dy, dx, channel). */
|
||||
out->in_w.resize(PH * 4 * W);
|
||||
for (int64_t o = 0; o < PH; ++o)
|
||||
for (int64_t q = 0; q < 4; ++q)
|
||||
for (int64_t c = 0; c < W; ++c)
|
||||
out->in_w[o * 4 * W + c * 4 + q] = in.in_w[o * 4 * W + q * W + c];
|
||||
out->out_w.assign(in.out_w, in.out_w + g.text * PH);
|
||||
|
||||
out->layers.assign(g.depth, Packed::Layer{});
|
||||
for (int64_t l = 0; l < g.depth; ++l) {
|
||||
const LayerIn& s = in.layers[l];
|
||||
Packed::Layer& d = out->layers[l];
|
||||
d.ln1_w.assign(s.ln1_w, s.ln1_w + W); d.ln1_b.assign(s.ln1_b, s.ln1_b + W);
|
||||
d.ln2_w.assign(s.ln2_w, s.ln2_w + W); d.ln2_b.assign(s.ln2_b, s.ln2_b + W);
|
||||
d.ls1.assign(s.ls1, s.ls1 + W); d.ls2.assign(s.ls2, s.ls2 + W);
|
||||
/* q and k take the rope's within-head permutation (see the layout note); v is stored as is. */
|
||||
const int64_t hd = g.head_dim();
|
||||
d.qkv_w.resize(3 * W * W);
|
||||
d.qkv_b.resize(3 * W);
|
||||
for (int64_t r = 0; r < W; ++r) {
|
||||
const int64_t dst = (r / hd) * hd + rope_perm(r % hd, hd);
|
||||
std::memcpy(&d.qkv_w[(0 * W + dst) * W], s.q_w + r * W, sizeof(float) * W);
|
||||
std::memcpy(&d.qkv_w[(1 * W + dst) * W], s.k_w + r * W, sizeof(float) * W);
|
||||
d.qkv_b[0 * W + dst] = s.q_b[r];
|
||||
d.qkv_b[1 * W + dst] = s.k_b[r];
|
||||
}
|
||||
std::memcpy(&d.qkv_w[2 * W * W], s.v_w, sizeof(float) * W * W);
|
||||
std::memcpy(&d.qkv_b[2 * W], s.v_b, sizeof(float) * W);
|
||||
d.o_w.assign(s.o_w, s.o_w + W * W); d.o_b.assign(s.o_b, s.o_b + W);
|
||||
d.fc_w.assign(s.fc_w, s.fc_w + g.ff() * W); d.fc_b.assign(s.fc_b, s.fc_b + g.ff());
|
||||
d.pr_w.assign(s.pr_w, s.pr_w + W * g.ff()); d.pr_b.assign(s.pr_b, s.pr_b + W);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The buffers one forward writes, sized once at declare for the grid. */
|
||||
struct Workspace {
|
||||
int64_t gh = 0, gw = 0; /* the grid this workspace is sized for */
|
||||
int64_t n = 0, M = 0, W = 0, ff = 0, cells = 0, PH = 0, text = 0, cpp = 0;
|
||||
std::vector<float> stream[2], h, qkv, att, t1, t2, ffn, emb, patches, merged, hid, hid2, ptab;
|
||||
std::vector<int32_t> pos, coord, cu;
|
||||
|
||||
/* The grid is gh x gw patches; both sides must be whole merges. */
|
||||
int init(const Geometry& g, int64_t grid_h, int64_t grid_w) {
|
||||
if (g.side <= 0 || g.width <= 0 || g.patch <= 0 || g.merge <= 0 || grid_h <= 0 ||
|
||||
grid_w <= 0 || grid_h % g.merge || grid_w % g.merge)
|
||||
return RAD_E_SHAPE;
|
||||
gh = grid_h; gw = grid_w;
|
||||
n = gh * gw; M = n + 1; W = g.width; ff = g.ff(); PH = g.proj;
|
||||
cells = n / (g.merge * g.merge);
|
||||
text = g.text; cpp = 3 * g.patch * g.patch;
|
||||
stream[0].assign(M * W, 0.0f); stream[1].assign(M * W, 0.0f);
|
||||
h.assign(M * W, 0.0f); qkv.assign(M * 3 * W, 0.0f); att.assign(M * W, 0.0f);
|
||||
t1.assign(M * W, 0.0f); t2.assign(M * W, 0.0f); ffn.assign(M * ff, 0.0f);
|
||||
emb.assign(n * W, 0.0f); patches.assign(n * cpp, 0.0f); ptab.assign(n * W, 0.0f);
|
||||
merged.assign(cells * 4 * W, 0.0f); hid.assign(cells * PH, 0.0f); hid2.assign(cells * PH, 0.0f);
|
||||
pos.assign(2 * M, 0); coord.assign(4 * n, 0); cu.assign(2, 0);
|
||||
return RAD_OK;
|
||||
}
|
||||
};
|
||||
|
||||
/* The op launch: the engine's issue or a host kernel table. */
|
||||
using Issue = int (*)(void* ctx, const char* op, const RadTensor* t, int nt, const RadParam* p, int np);
|
||||
|
||||
namespace detail {
|
||||
|
||||
inline RadTensor mat(void* d, uint32_t dt, int64_t rows, int64_t cols, int64_t row_stride) {
|
||||
RadTensor r{};
|
||||
r.data = d;
|
||||
r.dtype = dt;
|
||||
r.rank = 2;
|
||||
r.shape[0] = rows;
|
||||
r.shape[1] = cols;
|
||||
r.stride[0] = row_stride;
|
||||
r.stride[1] = 1;
|
||||
return r;
|
||||
}
|
||||
|
||||
/* One op launch's operands and parameters, built on the stack. */
|
||||
struct Call {
|
||||
RadTensor t[6];
|
||||
int nt = 0;
|
||||
RadParam p[10];
|
||||
int np = 0;
|
||||
Call& in(const RadTensor& x) { t[nt++] = x; return *this; }
|
||||
Call& i(const char* k, int64_t v) { p[np++] = RAD_INT(k, v); return *this; }
|
||||
Call& f(const char* k, double v) { p[np++] = RAD_F64(k, v); return *this; }
|
||||
Call& s(const char* k, const char* v) { p[np++] = RAD_STR(k, v); return *this; }
|
||||
int run(Issue issue, void* ctx, const char* op) const { return issue(ctx, op, t, nt, p, np); }
|
||||
};
|
||||
|
||||
} // namespace detail
|
||||
|
||||
/* One image: `img` is [gh * patch, gw * patch * 3] f32, normalised, on the workspace's grid.
|
||||
* `tokens` (n x width) and `out` ((n / merge^2) x text) are written; `tokens` may be null. */
|
||||
inline int forward(const Packed& P, Workspace& ws, Issue issue, void* ctx, const float* img,
|
||||
int64_t img_h, int64_t img_w, float* tokens, float* out) {
|
||||
using detail::Call;
|
||||
using detail::mat;
|
||||
const Geometry& g = P.g;
|
||||
if (!issue || !img || !out) return RAD_E_INVAL;
|
||||
const int64_t gh = ws.gh, gw = ws.gw;
|
||||
if (img_h != gh * g.patch || img_w != gw * g.patch) return RAD_E_SHAPE;
|
||||
const int64_t n = ws.n, M = ws.M, W = ws.W, ff = ws.ff, cells = ws.cells, PH = ws.PH;
|
||||
const int64_t hd = g.head_dim(), pp = g.patch * g.patch, cpp = 3 * pp;
|
||||
const int64_t side = g.side;
|
||||
const uint32_t F32 = RAD_F32, I32 = RAD_I32;
|
||||
const float* const pos_tab = P.pos.data();
|
||||
int rc = RAD_OK;
|
||||
|
||||
/* Positions and merge coordinates: CLS at (0, 0), patch (y, x) at (y + 1, x + 1) for the rotary;
|
||||
* raster grid coordinates for the merge. */
|
||||
ws.pos[0] = 0;
|
||||
ws.pos[M] = 0;
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
ws.pos[1 + i] = (int32_t)(i % gw + 1);
|
||||
ws.pos[M + 1 + i] = (int32_t)(i / gw + 1);
|
||||
ws.coord[0 * n + i] = (int32_t)(i / gw);
|
||||
ws.coord[1 * n + i] = (int32_t)(i % gw);
|
||||
ws.coord[2 * n + i] = (int32_t)gh;
|
||||
ws.coord[3 * n + i] = (int32_t)gw;
|
||||
}
|
||||
ws.cu[0] = 0;
|
||||
ws.cu[1] = (int32_t)M;
|
||||
|
||||
/* Patch embedding: pix_patch's rows [gh, gw * cpp] are the patches in raster order. */
|
||||
{
|
||||
Call c;
|
||||
c.in(mat(const_cast<float*>(img), F32, img_h, img_w * 3, img_w * 3))
|
||||
.in(mat(ws.patches.data(), F32, gh, gw * cpp, gw * cpp))
|
||||
.i("M", img_h).i("p", g.patch).i("C", 3).s("order", "hw").s("dtype", "f32");
|
||||
rc = c.run(issue, ctx, "pix_patch");
|
||||
if (rc) return rc;
|
||||
}
|
||||
{
|
||||
Call c;
|
||||
c.in(mat(ws.patches.data(), F32, n, cpp, cpp))
|
||||
.in(mat(const_cast<float*>(P.patch_w.data()), F32, W, cpp, cpp))
|
||||
.in(mat(ws.emb.data(), F32, n, W, W))
|
||||
.i("M", n).i("N", W).i("K", cpp).s("dtype", "f32");
|
||||
rc = c.run(issue, ctx, "gemm_nt");
|
||||
if (rc) return rc;
|
||||
}
|
||||
|
||||
/* The table on this grid: the checkpoint's own grid reads the table, any other gets it resampled
|
||||
* (posemb_resample, align_corners off), once per call into the workspace. */
|
||||
const float* pos_grid = pos_tab;
|
||||
if (gh != side || gw != side) {
|
||||
Call c;
|
||||
c.in(mat(const_cast<float*>(pos_tab), F32, side * side, W, W))
|
||||
.in(mat(ws.ptab.data(), F32, n, W, W))
|
||||
.i("S_h", side).i("S_w", side).i("T_h", gh).i("T_w", gw).i("n", W).s("dtype", "f32");
|
||||
rc = c.run(issue, ctx, "posemb_resample");
|
||||
if (rc) return rc;
|
||||
pos_grid = ws.ptab.data();
|
||||
}
|
||||
|
||||
/* Stream: row 0 is the CLS, rows 1.. are the patches plus the position table. */
|
||||
float* cur = ws.stream[0].data();
|
||||
float* alt = ws.stream[1].data();
|
||||
std::memcpy(cur, P.cls.data(), sizeof(float) * W);
|
||||
{
|
||||
Call c;
|
||||
c.in(mat(ws.emb.data(), F32, n, W, W))
|
||||
.in(mat(const_cast<float*>(pos_grid), F32, n, W, W))
|
||||
.in(mat(cur + W, F32, n, W, W))
|
||||
.i("M", n).i("n", W).s("dtype", "f32");
|
||||
rc = c.run(issue, ctx, "add");
|
||||
if (rc) return rc;
|
||||
}
|
||||
{
|
||||
Call c;
|
||||
c.in(mat(cur, F32, M, W, W))
|
||||
.in(mat(const_cast<float*>(P.pre_w.data()), F32, 1, W, W))
|
||||
.in(mat(const_cast<float*>(P.pre_b.data()), F32, 1, W, W))
|
||||
.in(mat(alt, F32, M, W, W))
|
||||
.i("M", M).i("n", W).f("eps", g.eps).s("dtype", "f32");
|
||||
rc = c.run(issue, ctx, "layernorm");
|
||||
if (rc) return rc;
|
||||
std::swap(cur, alt);
|
||||
}
|
||||
|
||||
for (int64_t l = 0; l < g.depth; ++l) {
|
||||
const Packed::Layer& L = P.layers[l];
|
||||
{
|
||||
Call c;
|
||||
c.in(mat(cur, F32, M, W, W))
|
||||
.in(mat(const_cast<float*>(L.ln1_w.data()), F32, 1, W, W))
|
||||
.in(mat(const_cast<float*>(L.ln1_b.data()), F32, 1, W, W))
|
||||
.in(mat(ws.h.data(), F32, M, W, W))
|
||||
.i("M", M).i("n", W).f("eps", g.eps).s("dtype", "f32");
|
||||
rc = c.run(issue, ctx, "layernorm");
|
||||
if (rc) return rc;
|
||||
}
|
||||
{
|
||||
Call c;
|
||||
c.in(mat(ws.h.data(), F32, M, W, W))
|
||||
.in(mat(const_cast<float*>(L.qkv_w.data()), F32, 3 * W, W, W))
|
||||
.in(mat(const_cast<float*>(L.qkv_b.data()), F32, 1, 3 * W, 3 * W))
|
||||
.in(RadTensor{}) /* res: the optional residual, absent */
|
||||
.in(mat(ws.qkv.data(), F32, M, 3 * W, 3 * W))
|
||||
.i("M", M).i("N", 3 * W).i("K", W).s("dtype", "f32");
|
||||
rc = c.run(issue, ctx, "gemm_nt_bias");
|
||||
if (rc) return rc;
|
||||
}
|
||||
{
|
||||
/* Two sections of head_dim / 4 pairs: the row then the column, each at theta^(-j /
|
||||
* (head_dim / 4)), paired across the halves on the permuted q and k. */
|
||||
char sec[48];
|
||||
std::snprintf(sec, sizeof sec, "%lld %lld", (long long)(hd / 4), (long long)(hd / 4));
|
||||
Call c;
|
||||
c.in(mat(ws.qkv.data(), F32, M, 3 * W, 3 * W))
|
||||
.in(mat(ws.pos.data(), I32, 2, M, M))
|
||||
.i("M", M).i("head_dim", hd).i("n_head", g.heads).i("n_head_kv", g.heads)
|
||||
.f("theta", g.theta).f("scale", 1.0).s("mode", "axial").s("sections", sec);
|
||||
rc = c.run(issue, ctx, "rope");
|
||||
if (rc) return rc;
|
||||
}
|
||||
{
|
||||
RadTensor q = mat(ws.qkv.data(), F32, M, W, 3 * W);
|
||||
RadTensor k = mat(ws.qkv.data() + W, F32, M, W, 3 * W);
|
||||
RadTensor v = mat(ws.qkv.data() + 2 * W, F32, M, W, 3 * W);
|
||||
Call c;
|
||||
c.in(q).in(k).in(v)
|
||||
.in(RadTensor{ ws.cu.data(), I32, 1, {2}, {1} })
|
||||
.in(mat(ws.att.data(), F32, M, W, W))
|
||||
.i("M", M).i("head_dim", hd).i("gqa", 1).i("causal", 0).s("dtype", "f32")
|
||||
.f("scale", 1.0 / std::sqrt((double)hd));
|
||||
rc = c.run(issue, ctx, "attn_dense");
|
||||
if (rc) return rc;
|
||||
}
|
||||
{
|
||||
Call c;
|
||||
c.in(mat(ws.att.data(), F32, M, W, W))
|
||||
.in(mat(const_cast<float*>(L.o_w.data()), F32, W, W, W))
|
||||
.in(mat(const_cast<float*>(L.o_b.data()), F32, 1, W, W))
|
||||
.in(RadTensor{}) /* res: the optional residual, absent */
|
||||
.in(mat(ws.t1.data(), F32, M, W, W))
|
||||
.i("M", M).i("N", W).i("K", W).s("dtype", "f32");
|
||||
rc = c.run(issue, ctx, "gemm_nt_bias");
|
||||
if (rc) return rc;
|
||||
}
|
||||
{
|
||||
Call c;
|
||||
c.in(mat(ws.t1.data(), F32, M, W, W))
|
||||
.in(mat(const_cast<float*>(L.ls1.data()), F32, 1, W, W))
|
||||
.in(mat(ws.t2.data(), F32, M, W, W))
|
||||
.i("M", M).i("n", W).s("dtype", "f32");
|
||||
rc = c.run(issue, ctx, "mul_weight");
|
||||
if (rc) return rc;
|
||||
}
|
||||
{
|
||||
Call c;
|
||||
c.in(mat(cur, F32, M, W, W)).in(mat(ws.t2.data(), F32, M, W, W))
|
||||
.in(mat(alt, F32, M, W, W))
|
||||
.i("M", M).i("n", W).s("dtype", "f32");
|
||||
rc = c.run(issue, ctx, "add");
|
||||
if (rc) return rc;
|
||||
std::swap(cur, alt);
|
||||
}
|
||||
{
|
||||
Call c;
|
||||
c.in(mat(cur, F32, M, W, W))
|
||||
.in(mat(const_cast<float*>(L.ln2_w.data()), F32, 1, W, W))
|
||||
.in(mat(const_cast<float*>(L.ln2_b.data()), F32, 1, W, W))
|
||||
.in(mat(ws.h.data(), F32, M, W, W))
|
||||
.i("M", M).i("n", W).f("eps", g.eps).s("dtype", "f32");
|
||||
rc = c.run(issue, ctx, "layernorm");
|
||||
if (rc) return rc;
|
||||
}
|
||||
{
|
||||
Call c;
|
||||
c.in(mat(ws.h.data(), F32, M, W, W))
|
||||
.in(mat(const_cast<float*>(L.fc_w.data()), F32, ff, W, W))
|
||||
.in(mat(const_cast<float*>(L.fc_b.data()), F32, 1, ff, ff))
|
||||
.in(RadTensor{}) /* res: the optional residual, absent */
|
||||
.in(mat(ws.ffn.data(), F32, M, ff, ff))
|
||||
.i("M", M).i("N", ff).i("K", W).s("dtype", "f32").s("act", "gelu");
|
||||
rc = c.run(issue, ctx, "gemm_nt_bias");
|
||||
if (rc) return rc;
|
||||
}
|
||||
{
|
||||
Call c;
|
||||
c.in(mat(ws.ffn.data(), F32, M, ff, ff))
|
||||
.in(mat(const_cast<float*>(L.pr_w.data()), F32, W, ff, ff))
|
||||
.in(mat(const_cast<float*>(L.pr_b.data()), F32, 1, W, W))
|
||||
.in(RadTensor{}) /* res: the optional residual, absent */
|
||||
.in(mat(ws.t1.data(), F32, M, W, W))
|
||||
.i("M", M).i("N", W).i("K", ff).s("dtype", "f32");
|
||||
rc = c.run(issue, ctx, "gemm_nt_bias");
|
||||
if (rc) return rc;
|
||||
}
|
||||
{
|
||||
Call c;
|
||||
c.in(mat(ws.t1.data(), F32, M, W, W))
|
||||
.in(mat(const_cast<float*>(L.ls2.data()), F32, 1, W, W))
|
||||
.in(mat(ws.t2.data(), F32, M, W, W))
|
||||
.i("M", M).i("n", W).s("dtype", "f32");
|
||||
rc = c.run(issue, ctx, "mul_weight");
|
||||
if (rc) return rc;
|
||||
}
|
||||
{
|
||||
Call c;
|
||||
c.in(mat(cur, F32, M, W, W)).in(mat(ws.t2.data(), F32, M, W, W))
|
||||
.in(mat(alt, F32, M, W, W))
|
||||
.i("M", M).i("n", W).s("dtype", "f32");
|
||||
rc = c.run(issue, ctx, "add");
|
||||
if (rc) return rc;
|
||||
std::swap(cur, alt);
|
||||
}
|
||||
}
|
||||
|
||||
/* The CLS row leaves; the patch rows merge 2 x 2 into the projector's cells. */
|
||||
if (tokens) std::memcpy(tokens, cur + W, sizeof(float) * n * W);
|
||||
{
|
||||
Call c;
|
||||
c.in(mat(cur + W, F32, n, W, W))
|
||||
.in(mat(ws.coord.data(), I32, 4, n, n))
|
||||
.in(mat(ws.merged.data(), F32, cells, 4 * W, 4 * W))
|
||||
.i("M", n).i("n", W).i("merge", g.merge).s("dtype", "f32");
|
||||
rc = c.run(issue, ctx, "pixtral_merge");
|
||||
if (rc) return rc;
|
||||
}
|
||||
{
|
||||
Call c;
|
||||
c.in(mat(ws.merged.data(), F32, cells, 4 * W, 4 * W))
|
||||
.in(mat(const_cast<float*>(P.in_w.data()), F32, PH, 4 * W, 4 * W))
|
||||
.in(mat(ws.hid.data(), F32, cells, PH, PH))
|
||||
.i("M", cells).i("N", PH).i("K", 4 * W).s("dtype", "f32");
|
||||
rc = c.run(issue, ctx, "gemm_nt");
|
||||
if (rc) return rc;
|
||||
}
|
||||
{
|
||||
Call c;
|
||||
c.in(mat(ws.hid.data(), F32, cells, PH, PH)).in(mat(ws.hid2.data(), F32, cells, PH, PH))
|
||||
.i("M", cells).i("n", PH).s("dtype", "f32");
|
||||
rc = c.run(issue, ctx, "gelu");
|
||||
if (rc) return rc;
|
||||
}
|
||||
{
|
||||
Call c;
|
||||
c.in(mat(ws.hid2.data(), F32, cells, PH, PH))
|
||||
.in(mat(const_cast<float*>(P.out_w.data()), F32, g.text, PH, PH))
|
||||
.in(mat(out, F32, cells, g.text, g.text))
|
||||
.i("M", cells).i("N", g.text).i("K", PH).s("dtype", "f32");
|
||||
rc = c.run(issue, ctx, "gemm_nt");
|
||||
if (rc) return rc;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} // namespace inkling2v
|
||||
} // namespace arch
|
||||
} // namespace rad
|
||||
|
||||
#endif /* RAD_BLOCK_INKLING2_VISION_H */
|
||||
@@ -0,0 +1,401 @@
|
||||
/* rad_block_lilicorr.h -- LiLiCorr's head: the candidate correlator after a DFlash2 backbone.
|
||||
*
|
||||
* NVIDIA's drafter for Nemotron-3.5-Bolt (vLLM's model_executor/models/lilicorr.py). The backbone is
|
||||
* rad_block_dflash2.h's, with attention sinks (Dflash2::Config::lili). Its final hidden states at
|
||||
* the block's draft rows go here instead of to DFlash2's selector:
|
||||
*
|
||||
* candidates each draft position's top-k from the target's own lm_head (log-softmax values,
|
||||
* vocab-parallel: each rank's shard, all-gathered, merged)
|
||||
* lattice steps x k rows a sequence, row s * k + j:
|
||||
* token_proj(embed(cand)) + pass_hidden_proj(h_s)
|
||||
* + feature_mlp(layernorm(five rank features)) + slot[s] + rank[j]
|
||||
* 2 layers rmsnorm, attention over the lattice with a learned slot bias (lili_attn), the
|
||||
* in/out projections; rmsnorm, silu MLP with biases; residuals
|
||||
* factor x = output_norm(lattice), a = anchor_norm(context_proj(the anchor's context row))
|
||||
* f = silu(W [x | a | x * a] + b), [out | in] = edge heads of f
|
||||
* walk normalised dot products, start from the anchor's own outgoing head, greedy
|
||||
* (lili_walk)
|
||||
*
|
||||
* The anchor's context row is hidden_norm(fc(taps)) at the last committed position, which the
|
||||
* context pass left in Dflash2's `c` (RadBatch::anchor_rows names the row). The head reads the
|
||||
* target's embedding and lm_head, and its own 25 linears are bf16: ModelOpt ships them NVFP4,
|
||||
* which no kernel serves, and the recipe decodes them (`cast dtype=bf16`).
|
||||
*
|
||||
* Every rank computes the whole lattice (vLLM: "candidate IDs and embeddings are replicated across
|
||||
* TP ranks"); only the head's logits and the embedding lookup are per rank, with the merge in
|
||||
* lili_cand and an exact all-reduce after the lookup.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_LILICORR_H
|
||||
#define RAD_BLOCK_LILICORR_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct LiliCorr {
|
||||
enum { MAX_LAYERS = 4 };
|
||||
|
||||
struct Config {
|
||||
int64_t steps = 0; /* draft positions a sequence: the block less the anchor */
|
||||
int64_t k = 8; /* candidates a position (lilicorr_candidate_topk) */
|
||||
int64_t hs = 1024; /* the lattice's width (lilicorr_hidden_size) */
|
||||
int64_t n_head = 8;
|
||||
int64_t mlp = 2048; /* hs * lilicorr_mlp_ratio */
|
||||
int64_t fdim = 1024; /* lilicorr_factor_dim */
|
||||
int64_t n_layer = 2;
|
||||
double eps = 1e-6; /* rms_norm_eps, the lattice's RMS norms */
|
||||
double vec_eps = 1e-4; /* lilicorr_vector_eps, F.normalize's floor */
|
||||
double scale = 8.0; /* lilicorr_logit_scale */
|
||||
};
|
||||
|
||||
/* row_k: the pairs a rank's logprob row carries, k rounded up so 2 + 2 row_k floats are whole
|
||||
* 16-byte words (the all-gather's unit): 9 for k = 8. */
|
||||
static int64_t row_k(int64_t k) { return (k % 2) ? k : k + 1; }
|
||||
|
||||
struct Wire {
|
||||
/* Dflash2's */
|
||||
rad_buf sel_h = 0; /* [srows, n_embd] the drafter's final hidden states, draft rows */
|
||||
rad_buf c = 0; /* [max_tok, n_embd] hidden_norm(fc(taps)), the context pass's rows */
|
||||
rad_buf tokens = 0; /* [max_seqs, steps] i32, the proposal */
|
||||
/* the head's own */
|
||||
rad_buf logits = 0; /* [srows, n_vocab] f32, this rank's shard */
|
||||
rad_buf stats = 0; /* [srows, 2 + 2 row_k] f32 */
|
||||
rad_buf sgath = 0; /* [srows, world * (2 + 2 row_k)] f32, world > 1 */
|
||||
rad_buf pas = 0; /* [srows, hs] */
|
||||
rad_buf cand = 0; /* [srows * k] i32 */
|
||||
rad_buf feat = 0; /* [lrows, hs] */
|
||||
rad_buf hh = 0; /* [lrows, hs] the lattice's residual stream; starts as lili_cand's base */
|
||||
rad_buf emb = 0; /* [lrows, n_embd] the candidates' embeddings */
|
||||
rad_buf y = 0; /* [lrows, hs] */
|
||||
rad_buf qkv = 0; /* [lrows, 3 hs] */
|
||||
rad_buf att = 0; /* [lrows, hs] */
|
||||
rad_buf up = 0; /* [lrows, mlp] */
|
||||
rad_buf ups = 0; /* [lrows, mlp] */
|
||||
rad_buf cat = 0; /* [lrows, 3 hs] */
|
||||
rad_buf fh = 0; /* [lrows, hs] */
|
||||
rad_buf fhs = 0; /* [lrows, hs] */
|
||||
rad_buf edges = 0; /* [lrows, 2 fdim] */
|
||||
rad_buf anc = 0; /* [max_seqs, n_embd] */
|
||||
rad_buf ast = 0; /* [max_seqs, hs] */
|
||||
rad_buf an = 0; /* [max_seqs, hs] */
|
||||
rad_buf aout = 0; /* [max_seqs, fdim] */
|
||||
};
|
||||
|
||||
Geom g{};
|
||||
Config cfg{};
|
||||
Wire w{};
|
||||
int64_t srows = 0, lrows = 0, rk = 0;
|
||||
|
||||
rad_weight w_lm = 0, w_tok = 0; /* the target's */
|
||||
rad_weight w_tokp = 0, b_tokp = 0, w_pass = 0, b_pass = 0, w_ctx = 0, b_ctx = 0;
|
||||
rad_weight w_fdn = 0, b_fdn = 0, ln_w = 0, ln_b = 0, up_w = 0, up_b = 0, w_slot = 0, w_rank = 0;
|
||||
rad_weight w_anorm[MAX_LAYERS] = {}, w_in[MAX_LAYERS] = {}, b_in[MAX_LAYERS] = {};
|
||||
rad_weight w_out[MAX_LAYERS] = {}, b_out[MAX_LAYERS] = {}, w_mnorm[MAX_LAYERS] = {};
|
||||
rad_weight w_up[MAX_LAYERS] = {}, b_up[MAX_LAYERS] = {}, w_dn[MAX_LAYERS] = {};
|
||||
rad_weight b_dn[MAX_LAYERS] = {};
|
||||
rad_weight w_rel = 0, w_same = 0, w_onorm = 0, w_annorm = 0;
|
||||
rad_weight w_fac = 0, b_fac = 0, w_edge = 0, b_edge = 0, w_aout = 0, b_aout = 0;
|
||||
|
||||
rad_op op_logits = 0, op_stats = 0, op_sgath = 0, op_pas = 0, op_cand = 0;
|
||||
rad_op op_emb = 0, op_emb_ar = 0, op_tokp = 0, op_fdn = 0;
|
||||
rad_op op_anorm[MAX_LAYERS] = {}, op_in[MAX_LAYERS] = {}, op_attn = 0;
|
||||
rad_op op_out[MAX_LAYERS] = {}, op_mnorm[MAX_LAYERS] = {}, op_up[MAX_LAYERS] = {};
|
||||
rad_op op_dn[MAX_LAYERS] = {}, op_silu_up = 0;
|
||||
rad_op op_onorm = 0, op_anc = 0, op_ctx = 0, op_annorm = 0, op_factor = 0, op_fac = 0;
|
||||
rad_op op_silu_f = 0, op_edge = 0, op_aout = 0, op_walk = 0;
|
||||
|
||||
/* `lm_head_type`: the llama.cpp block type the target stores its head as (rad_ggml.h), whose
|
||||
* logits then come from logits_gemm_ggml as the target's own do; null for a plain bf16 head. */
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, rad_weight lm_head,
|
||||
rad_weight tok_embd, const char* ck, const Wire& wire,
|
||||
const char* lm_head_type = nullptr);
|
||||
/* After Dflash2::step, on the same query batch: `sel_h` holds the draft rows. */
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
};
|
||||
|
||||
inline int LiliCorr::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c,
|
||||
rad_weight lm_head, rad_weight tok_embd, const char* ck,
|
||||
const Wire& wire, const char* lm_head_type) {
|
||||
g = geom; cfg = c; w = wire; w_lm = lm_head; w_tok = tok_embd;
|
||||
if (!w_lm || !w_tok || !ck || cfg.steps < 1 || cfg.k < 2 || cfg.n_layer < 1 ||
|
||||
cfg.n_layer > MAX_LAYERS || cfg.hs % cfg.n_head)
|
||||
return RAD_E_INVAL;
|
||||
const int64_t K = cfg.k, S = cfg.steps, hs = cfg.hs, fd = cfg.fdim, E = g.n_embd;
|
||||
srows = g.max_seqs * S;
|
||||
lrows = srows * K;
|
||||
rk = row_k(K);
|
||||
const int ACC = RAD_ACCESS_PER_TOKEN;
|
||||
const RadWeightGroup grp = grp_model();
|
||||
|
||||
/* The head's weights, all replicated. Linears and tables bf16, biases, norms and the
|
||||
* feature layer f32. */
|
||||
auto wt = [&](const char* dn, const char* src, uint32_t dt,
|
||||
std::initializer_list<int64_t> shp) -> rad_weight {
|
||||
if (map_copy(b, dn, src) < 0) return 0;
|
||||
return decl_w(b, dn, dt, shp, ACC, RAD_SHARD_NONE, grp);
|
||||
};
|
||||
const char* L = nm.ckpt("%s.lilicorr", ck);
|
||||
auto src = [&](const char* tail) { return nm.ckpt("%s.%s", L, tail); };
|
||||
w_tokp = wt(nm.f("dflash.lili.token_proj.weight"), src("token_proj.weight"), RAD_BF16, { hs, E });
|
||||
b_tokp = wt(nm.f("dflash.lili.token_proj.bias"), src("token_proj.bias"), RAD_F32, { hs });
|
||||
w_pass = wt(nm.f("dflash.lili.pass_proj.weight"), src("pass_hidden_proj.weight"), RAD_BF16,
|
||||
{ hs, E });
|
||||
b_pass = wt(nm.f("dflash.lili.pass_proj.bias"), src("pass_hidden_proj.bias"), RAD_F32, { hs });
|
||||
w_ctx = wt(nm.f("dflash.lili.context_proj.weight"), src("context_proj.weight"), RAD_BF16,
|
||||
{ hs, E });
|
||||
b_ctx = wt(nm.f("dflash.lili.context_proj.bias"), src("context_proj.bias"), RAD_F32, { hs });
|
||||
ln_w = wt(nm.f("dflash.lili.feature_norm.weight"), src("feature_norm.weight"), RAD_F32, { 5 });
|
||||
ln_b = wt(nm.f("dflash.lili.feature_norm.bias"), src("feature_norm.bias"), RAD_F32, { 5 });
|
||||
up_w = wt(nm.f("dflash.lili.feature_up.weight"), src("feature_mlp.up_proj.weight"), RAD_F32,
|
||||
{ hs, 5 });
|
||||
up_b = wt(nm.f("dflash.lili.feature_up.bias"), src("feature_mlp.up_proj.bias"), RAD_F32,
|
||||
{ hs });
|
||||
w_fdn = wt(nm.f("dflash.lili.feature_down.weight"), src("feature_mlp.down_proj.weight"),
|
||||
RAD_BF16, { hs, hs });
|
||||
b_fdn = wt(nm.f("dflash.lili.feature_down.bias"), src("feature_mlp.down_proj.bias"), RAD_F32,
|
||||
{ hs });
|
||||
/* [1, 1, steps, 1, hs] and [1, 1, 1, k, hs], read as tables (a reshape of one whole plane). */
|
||||
w_slot = wt(nm.f("dflash.lili.slot_embedding"), src("slot_embedding"), RAD_BF16, { S, hs });
|
||||
w_rank = wt(nm.f("dflash.lili.rank_embedding"), src("rank_embedding"), RAD_BF16, { K, hs });
|
||||
w_rel = wt(nm.f("dflash.lili.relative_slot_bias"), src("relative_slot_bias"), RAD_F32,
|
||||
{ cfg.n_head, 2 * (S + 1) - 1 });
|
||||
w_same = wt(nm.f("dflash.lili.same_slot_bias"), src("same_slot_bias"), RAD_F32, { cfg.n_head });
|
||||
for (int64_t l = 0; l < cfg.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
auto ls = [&](const char* tail) { return nm.ckpt("%s.layers.%d.%s", L, i, tail); };
|
||||
w_anorm[i] = wt(nm.f("dflash.lili.blk.%d.attn_norm.weight", i), ls("attn_norm.weight"),
|
||||
RAD_F32, { hs });
|
||||
w_in[i] = wt(nm.f("dflash.lili.blk.%d.attn_in.weight", i), ls("attn.in_proj_weight"),
|
||||
RAD_BF16, { 3 * hs, hs });
|
||||
b_in[i] = wt(nm.f("dflash.lili.blk.%d.attn_in.bias", i), ls("attn.in_proj_bias"), RAD_F32,
|
||||
{ 3 * hs });
|
||||
w_out[i] = wt(nm.f("dflash.lili.blk.%d.attn_out.weight", i), ls("attn.out_proj.weight"),
|
||||
RAD_BF16, { hs, hs });
|
||||
b_out[i] = wt(nm.f("dflash.lili.blk.%d.attn_out.bias", i), ls("attn.out_proj.bias"),
|
||||
RAD_F32, { hs });
|
||||
w_mnorm[i] = wt(nm.f("dflash.lili.blk.%d.mlp_norm.weight", i), ls("mlp_norm.weight"),
|
||||
RAD_F32, { hs });
|
||||
w_up[i] = wt(nm.f("dflash.lili.blk.%d.mlp_up.weight", i), ls("mlp.up_proj.weight"),
|
||||
RAD_BF16, { cfg.mlp, hs });
|
||||
b_up[i] = wt(nm.f("dflash.lili.blk.%d.mlp_up.bias", i), ls("mlp.up_proj.bias"), RAD_F32,
|
||||
{ cfg.mlp });
|
||||
w_dn[i] = wt(nm.f("dflash.lili.blk.%d.mlp_down.weight", i), ls("mlp.down_proj.weight"),
|
||||
RAD_BF16, { hs, cfg.mlp });
|
||||
b_dn[i] = wt(nm.f("dflash.lili.blk.%d.mlp_down.bias", i), ls("mlp.down_proj.bias"),
|
||||
RAD_F32, { hs });
|
||||
if (!w_anorm[i] || !w_in[i] || !b_in[i] || !w_out[i] || !b_out[i] || !w_mnorm[i] ||
|
||||
!w_up[i] || !b_up[i] || !w_dn[i] || !b_dn[i])
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
w_onorm = wt(nm.f("dflash.lili.output_norm.weight"), src("output_norm.weight"), RAD_F32, { hs });
|
||||
w_annorm = wt(nm.f("dflash.lili.anchor_norm.weight"), src("anchor_norm.weight"), RAD_F32, { hs });
|
||||
w_fac = wt(nm.f("dflash.lili.factor_proj.weight"), src("factor_input_proj.weight"), RAD_BF16,
|
||||
{ hs, 3 * hs });
|
||||
b_fac = wt(nm.f("dflash.lili.factor_proj.bias"), src("factor_input_proj.bias"), RAD_F32,
|
||||
{ hs });
|
||||
/* [out_head | in_head] as one linear, as vLLM fuses them (`_fused_edge_weight`). */
|
||||
RAD_ARCH_TRY(map_concat(b, nm.f("dflash.lili.edge.weight"),
|
||||
{ src("out_head.weight"), src("in_head.weight") }, 0));
|
||||
RAD_ARCH_TRY(map_concat(b, nm.f("dflash.lili.edge.bias"),
|
||||
{ src("out_head.bias"), src("in_head.bias") }, 0));
|
||||
w_edge = decl_w(b, nm.f("dflash.lili.edge.weight"), RAD_BF16, { 2 * fd, hs }, ACC,
|
||||
RAD_SHARD_NONE, grp);
|
||||
b_edge = decl_w(b, nm.f("dflash.lili.edge.bias"), RAD_F32, { 2 * fd }, ACC, RAD_SHARD_NONE,
|
||||
grp);
|
||||
w_aout = wt(nm.f("dflash.lili.anchor_out.weight"), src("anchor_out_head.weight"), RAD_BF16,
|
||||
{ fd, hs });
|
||||
b_aout = wt(nm.f("dflash.lili.anchor_out.bias"), src("anchor_out_head.bias"), RAD_F32, { fd });
|
||||
if (!w_tokp || !b_tokp || !w_pass || !b_pass || !w_ctx || !b_ctx || !ln_w || !ln_b || !up_w ||
|
||||
!up_b || !w_fdn || !b_fdn || !w_slot || !w_rank || !w_rel || !w_same || !w_onorm ||
|
||||
!w_annorm || !w_fac || !b_fac || !w_edge || !b_edge || !w_aout || !b_aout)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
/* ---------------------------------------------------------------- ops */
|
||||
auto gemm_b = [&](int64_t rows, int64_t N, int64_t Kd, rad_weight wgt, 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", Kd),
|
||||
RAD_STR("dtype", "bf16"), RAD_STR("act", "none")),
|
||||
RAD_WEIGHTS(wgt, bias));
|
||||
};
|
||||
auto rms = [&](int64_t rows, int64_t n, rad_weight gain) -> rad_op {
|
||||
return RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", cfg.eps),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(gain));
|
||||
};
|
||||
auto silu = [&](int64_t rows, int64_t n) -> rad_op {
|
||||
return RAD_OP(b, "silu",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
const int64_t sw = 2 + 2 * rk;
|
||||
|
||||
/* The candidates: this rank's shard of the target's logits, its logprob row, the exchange. */
|
||||
if (lm_head_type)
|
||||
op_logits = rw(b, RAD_OP(b, "logits_gemm_ggml",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n_vocab", g.n_vocab),
|
||||
RAD_INT("n_embd", E), RAD_STR("type", lm_head_type),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_lm)),
|
||||
{ w.sel_h }, { w.logits });
|
||||
else
|
||||
op_logits = rw(b, RAD_OP(b, "logits_gemm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n_vocab", g.n_vocab),
|
||||
RAD_INT("n_embd", E), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_lm)),
|
||||
{ w.sel_h }, { w.logits });
|
||||
/* Replicated, `vocab_off` is omitted: an optional parameter present at 0 is a different
|
||||
* declaration from an absent one. */
|
||||
op_stats = g.world > 1
|
||||
? rw(b, RAD_OP(b, "sample_logprobs",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n_vocab", g.n_vocab),
|
||||
RAD_INT("k", rk), RAD_INT("vocab_off", g.vocab_off)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.logits }, { w.stats })
|
||||
: rw(b, RAD_OP(b, "sample_logprobs",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n_vocab", g.n_vocab),
|
||||
RAD_INT("k", rk)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.logits }, { w.stats });
|
||||
if (g.world > 1)
|
||||
op_sgath = rw(b, RAD_OP(b, "all_gather",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_INT("numel", srows * sw), RAD_STR("dtype", "f32"),
|
||||
RAD_INT("row", sw)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.stats }, { w.sgath });
|
||||
op_pas = rw(b, gemm_b(srows, hs, E, w_pass, b_pass), { w.sel_h }, { w.pas });
|
||||
op_cand = rw(b, RAD_OP(b, "lili_cand",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("k", K),
|
||||
RAD_INT("world", g.world), RAD_INT("steps", S),
|
||||
RAD_INT("n", hs), RAD_STR("dtype", "bf16"),
|
||||
RAD_F64("eps", 1e-5), RAD_INT("row_k", rk)),
|
||||
RAD_WEIGHTS(ln_w, ln_b, up_w, up_b, w_slot, w_rank)),
|
||||
{ g.world > 1 ? w.sgath : w.stats, w.pas }, { w.cand, w.feat, w.hh });
|
||||
/* The lattice: candidates' embeddings (the trunk's vocab-sharded table, exact reduce), the
|
||||
* token and feature projections added onto lili_cand's base in their GEMMs' residual. */
|
||||
op_emb = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, lrows), RAD_INT("n_embd", E),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
|
||||
RAD_INT("vocab_offset", g.vocab_off)),
|
||||
RAD_WEIGHTS(w_tok)),
|
||||
{ w.cand }, { w.emb });
|
||||
if (g.world > 1)
|
||||
op_emb_ar = decl_all_reduce_exact(b, g, w.emb, E, lrows, "bf16");
|
||||
op_tokp = rw(b, gemm_b(lrows, hs, E, w_tokp, b_tokp), { w.emb, w.hh }, { w.hh });
|
||||
op_fdn = rw(b, gemm_b(lrows, hs, hs, w_fdn, b_fdn), { w.feat, w.hh }, { w.hh });
|
||||
for (int64_t l = 0; l < cfg.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
op_anorm[i] = rw(b, rms(lrows, hs, w_anorm[i]), { w.hh }, { w.y });
|
||||
op_in[i] = rw(b, gemm_b(lrows, 3 * hs, hs, w_in[i], b_in[i]), { w.y }, { w.qkv });
|
||||
op_out[i] = rw(b, gemm_b(lrows, hs, hs, w_out[i], b_out[i]), { w.att, w.hh }, { w.hh });
|
||||
op_mnorm[i] = rw(b, rms(lrows, hs, w_mnorm[i]), { w.hh }, { w.y });
|
||||
op_up[i] = rw(b, gemm_b(lrows, cfg.mlp, hs, w_up[i], b_up[i]), { w.y }, { w.up });
|
||||
op_dn[i] = rw(b, gemm_b(lrows, hs, cfg.mlp, w_dn[i], b_dn[i]), { w.ups, w.hh }, { w.hh });
|
||||
}
|
||||
op_attn = rw(b, RAD_OP(b, "lili_attn",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, lrows), RAD_INT("steps", S), RAD_INT("k", K),
|
||||
RAD_INT("n_head", cfg.n_head),
|
||||
RAD_INT("head_dim", hs / cfg.n_head),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_rel, w_same)),
|
||||
{ w.qkv }, { w.att });
|
||||
op_silu_up = rw(b, silu(lrows, cfg.mlp), { w.up }, { w.ups });
|
||||
op_onorm = rw(b, rms(lrows, hs, w_onorm), { w.hh }, { w.y });
|
||||
/* The anchor: the context pass's row at each drafting sequence's last committed position. */
|
||||
op_anc = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("n", E),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.c }, { w.anc });
|
||||
op_ctx = rw(b, gemm_b(g.max_seqs, hs, E, w_ctx, b_ctx), { w.anc }, { w.ast });
|
||||
op_annorm = rw(b, rms(g.max_seqs, hs, w_annorm), { w.ast }, { w.an });
|
||||
op_factor = rw(b, RAD_OP(b, "lili_factor",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, lrows), RAD_INT("L", S * K),
|
||||
RAD_INT("n", hs), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.y, w.an }, { w.cat });
|
||||
op_fac = rw(b, gemm_b(lrows, hs, 3 * hs, w_fac, b_fac), { w.cat }, { w.fh });
|
||||
op_silu_f = rw(b, silu(lrows, hs), { w.fh }, { w.fhs });
|
||||
op_edge = rw(b, gemm_b(lrows, 2 * fd, hs, w_edge, b_edge), { w.fhs }, { w.edges });
|
||||
op_aout = rw(b, gemm_b(g.max_seqs, fd, hs, w_aout, b_aout), { w.an }, { w.aout });
|
||||
op_walk = rw(b, RAD_OP(b, "lili_walk",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("steps", S),
|
||||
RAD_INT("k", K), RAD_INT("n", fd), RAD_STR("dtype", "bf16"),
|
||||
RAD_F64("eps", cfg.vec_eps), RAD_F64("scale", cfg.scale)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.edges, w.aout, w.cand }, { w.tokens });
|
||||
if (!op_logits || !op_stats || (g.world > 1 && (!op_sgath || !op_emb_ar)) || !op_pas ||
|
||||
!op_cand || !op_emb || !op_tokp || !op_fdn || !op_attn || !op_silu_up || !op_onorm ||
|
||||
!op_anc || !op_ctx || !op_annorm || !op_factor || !op_fac || !op_silu_f || !op_edge ||
|
||||
!op_aout || !op_walk)
|
||||
return RAD_E_INVAL;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
inline void LiliCorr::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t n = batch->n_seq, S = n * cfg.steps, Lr = S * cfg.k;
|
||||
if (n <= 0) return;
|
||||
if (!batch->anchor_rows) {
|
||||
rad_step_fail(c, "lilicorr: the query pass carries no anchor rows (RadBatch::anchor_rows): "
|
||||
"this engine does not position a block drafter's anchor");
|
||||
return;
|
||||
}
|
||||
const int64_t E = g.n_embd, hs = cfg.hs, fd = cfg.fdim;
|
||||
const int64_t sw = 2 + 2 * rk;
|
||||
|
||||
RAD_ISSUE_N(c, op_logits, S, brows(w.sel_h, S), RAD_W(w_lm), brows(w.logits, S));
|
||||
RAD_ISSUE_N(c, op_stats, S, brows(w.logits, S), RAD_NONE, brows(w.stats, S));
|
||||
if (op_sgath) RAD_ISSUE(c, op_sgath, brows(w.stats, S), brows(w.sgath, S));
|
||||
RAD_ISSUE_N(c, op_pas, S, brows(w.sel_h, S), RAD_W(w_pass), RAD_W(b_pass), RAD_NONE,
|
||||
brows(w.pas, S));
|
||||
RAD_ISSUE_N(c, op_cand, S, op_sgath ? brows(w.sgath, S) : brows(w.stats, S), brows(w.pas, S),
|
||||
RAD_W(ln_w), RAD_W(ln_b), RAD_W(up_w), RAD_W(up_b), RAD_W(w_slot), RAD_W(w_rank),
|
||||
brow_slice(w.cand, 0, Lr, 1), brows(w.feat, Lr), brows(w.hh, Lr));
|
||||
(void)sw;
|
||||
|
||||
RAD_ISSUE_N(c, op_emb, Lr, brow_slice(w.cand, 0, Lr, 1), RAD_W(w_tok), brows(w.emb, Lr));
|
||||
if (op_emb_ar) RAD_ISSUE_N(c, op_emb_ar, Lr * E, brows(w.emb, Lr), RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_tokp, Lr, brows(w.emb, Lr), RAD_W(w_tokp), RAD_W(b_tokp), brows(w.hh, Lr),
|
||||
brows(w.hh, Lr));
|
||||
RAD_ISSUE_N(c, op_fdn, Lr, brows(w.feat, Lr), RAD_W(w_fdn), RAD_W(b_fdn), brows(w.hh, Lr),
|
||||
brows(w.hh, Lr));
|
||||
for (int64_t l = 0; l < cfg.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
RAD_ISSUE_N(c, op_anorm[i], Lr, brows(w.hh, Lr), RAD_W(w_anorm[i]), brows(w.y, Lr));
|
||||
RAD_ISSUE_N(c, op_in[i], Lr, brows(w.y, Lr), RAD_W(w_in[i]), RAD_W(b_in[i]), RAD_NONE,
|
||||
brows(w.qkv, Lr));
|
||||
RAD_ISSUE_N(c, op_attn, Lr, brows(w.qkv, Lr), RAD_W(w_rel), RAD_W(w_same), brows(w.att, Lr));
|
||||
RAD_ISSUE_N(c, op_out[i], Lr, brows(w.att, Lr), RAD_W(w_out[i]), RAD_W(b_out[i]),
|
||||
brows(w.hh, Lr), brows(w.hh, Lr));
|
||||
RAD_ISSUE_N(c, op_mnorm[i], Lr, brows(w.hh, Lr), RAD_W(w_mnorm[i]), brows(w.y, Lr));
|
||||
RAD_ISSUE_N(c, op_up[i], Lr, brows(w.y, Lr), RAD_W(w_up[i]), RAD_W(b_up[i]), RAD_NONE,
|
||||
brows(w.up, Lr));
|
||||
RAD_ISSUE_N(c, op_silu_up, Lr, brows(w.up, Lr), brows(w.ups, Lr));
|
||||
RAD_ISSUE_N(c, op_dn[i], Lr, brows(w.ups, Lr), RAD_W(w_dn[i]), RAD_W(b_dn[i]),
|
||||
brows(w.hh, Lr), brows(w.hh, Lr));
|
||||
}
|
||||
RAD_ISSUE_N(c, op_onorm, Lr, brows(w.hh, Lr), RAD_W(w_onorm), brows(w.y, Lr));
|
||||
|
||||
RAD_ISSUE_N(c, op_anc, n, RAD_B(w.c), praw(batch->anchor_rows, RAD_I32, n), brows(w.anc, n));
|
||||
RAD_ISSUE_N(c, op_ctx, n, brows(w.anc, n), RAD_W(w_ctx), RAD_W(b_ctx), RAD_NONE, brows(w.ast, n));
|
||||
RAD_ISSUE_N(c, op_annorm, n, brows(w.ast, n), RAD_W(w_annorm), brows(w.an, n));
|
||||
RAD_ISSUE_N(c, op_factor, Lr, brows(w.y, Lr), brows(w.an, n), brows(w.cat, Lr));
|
||||
RAD_ISSUE_N(c, op_fac, Lr, brows(w.cat, Lr), RAD_W(w_fac), RAD_W(b_fac), RAD_NONE,
|
||||
brows(w.fh, Lr));
|
||||
RAD_ISSUE_N(c, op_silu_f, Lr, brows(w.fh, Lr), brows(w.fhs, Lr));
|
||||
RAD_ISSUE_N(c, op_edge, Lr, brows(w.fhs, Lr), RAD_W(w_edge), RAD_W(b_edge), RAD_NONE,
|
||||
brows(w.edges, Lr));
|
||||
RAD_ISSUE_N(c, op_aout, n, brows(w.an, n), RAD_W(w_aout), RAD_W(b_aout), RAD_NONE,
|
||||
brows(w.aout, n));
|
||||
RAD_ISSUE_N(c, op_walk, n, brows(w.edges, Lr), brows(w.aout, n),
|
||||
brow_slice(w.cand, 0, Lr, 1), brows(w.tokens, n), RAD_NONE);
|
||||
(void)E; (void)hs; (void)fd;
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_LILICORR_H */
|
||||
+44
-29
@@ -5,11 +5,16 @@
|
||||
* 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.
|
||||
*
|
||||
* With a fold (rad_norm_bf16.h) the norm takes the previous block's delta and all-reduce, and
|
||||
* `add_out` / `ar_out` leave this block's own to the next block's norm. The defaults are the
|
||||
* block as above.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_MLP_H
|
||||
#define RAD_BLOCK_MLP_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
#include "rad_norm_bf16.h"
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
@@ -38,15 +43,27 @@ struct MlpBF16 {
|
||||
|
||||
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;
|
||||
NormBF16 nq{};
|
||||
/* The next block's norm takes this block's all-reduce where it can (NormBF16::takes_ar). */
|
||||
bool ar_out = false;
|
||||
/* Set by the architecture after declare: a `prefetch` of the next GEMM's leading weight bytes
|
||||
* (decl_prefetch, rad_arch.h), issued after down and before this block's own all-reduce where
|
||||
* it issues one, so it is beside the reduction whether this block or the next norm runs it
|
||||
* (prefetch_beside). 0 where none is declared. */
|
||||
rad_op op_pf = 0;
|
||||
rad_weight pf_w = 0;
|
||||
|
||||
/* `fold` / `ar_in`: the norm takes the previous block's delta / and its all-reduce.
|
||||
* `add_out`: issue this block's add here. `ar_out_`: leave the all-reduce to the next norm. */
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
|
||||
const Src& src);
|
||||
const Src& src, bool fold = false, bool add_out = true, bool ar_in = false,
|
||||
bool ar_out_ = false);
|
||||
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;
|
||||
const Src& src, bool fold, bool add_out, bool 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));
|
||||
RAD_ARCH_TRY(map_concat(b, nm.f("blk.%d.ffn_gate_up.weight", l), { src.gate, src.up }, 0));
|
||||
@@ -54,20 +71,20 @@ inline int MlpBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, c
|
||||
|
||||
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));
|
||||
const LinearBF16 gu = decl_linear_bf16(b, g, nm.f("blk.%d.ffn_gate_up.weight", l),
|
||||
{2 * g.n_ff, g.n_embd}, RAD_SHARD_ROW, grp_layer(l),
|
||||
{g.n_ff, g.n_ff});
|
||||
const LinearBF16 dn = decl_linear_bf16(b, g, nm.f("blk.%d.ffn_down.weight", l),
|
||||
{g.n_embd, g.n_ff}, RAD_SHARD_COL, grp_layer(l));
|
||||
w_gate_up = gu.w;
|
||||
w_down = dn.w;
|
||||
|
||||
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});
|
||||
RAD_ARCH_TRY(nq.declare(b, g, w_norm, w.x, w.h, fold, ar_in));
|
||||
op_norm = nq.op_norm;
|
||||
|
||||
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_INT("K", g.n_embd), RAD_STR("dtype", gu.dtype)),
|
||||
RAD_WEIGHTS(w_gate_up)),
|
||||
{w.h}, {w.gate_up});
|
||||
|
||||
@@ -79,26 +96,21 @@ inline int MlpBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, c
|
||||
|
||||
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_INT("K", g.n_ff), RAD_STR("dtype", dn.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_ar = decl_all_reduce(b, g, 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});
|
||||
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}, {w.x});
|
||||
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -107,12 +119,15 @@ 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));
|
||||
nq.step(c, 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));
|
||||
/* Decode steps only: a prompt's rows never take the reads (rad_arch.h, kPrefetchRows). */
|
||||
prefetch_beside(c, op_pf, pf_w, batch->phase == RAD_PHASE_DECODE ? T : INT64_MAX);
|
||||
if (op_ar && !(ar_out && ar_wire_is_exact(g, T)))
|
||||
RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
|
||||
if (op_add) RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h, T), brows(w.x, T));
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
/* rad_block_mlp_fp8.h -- the SwiGLU feed-forward block with block-scaled FP8 linears.
|
||||
/* rad_block_mlp_q.h -- the SwiGLU feed-forward block over LinearQ 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]
|
||||
* - Both projections are LinearQ (rad_linear.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).
|
||||
@@ -16,20 +16,20 @@
|
||||
* 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
|
||||
#ifndef RAD_BLOCK_MLP_Q_H
|
||||
#define RAD_BLOCK_MLP_Q_H
|
||||
|
||||
#include "rad_fp8.h"
|
||||
#include "rad_linear.h"
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct MlpFP8 {
|
||||
struct MlpQ {
|
||||
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 */
|
||||
ActQ h{}; /* [max_tok, n_embd] normed input, then the down output */
|
||||
rad_buf gate_up = 0; /* [max_tok, 2 * n_ff] */
|
||||
ActFP8 ffn{}; /* [max_tok, n_ff] */
|
||||
ActQ ffn{}; /* [max_tok, n_ff] */
|
||||
};
|
||||
|
||||
/* Checkpoint names. `gate`, `up` and `down` name the `.weight` tensors; the checkpoint reader
|
||||
@@ -46,9 +46,9 @@ struct MlpFP8 {
|
||||
int layer = 0;
|
||||
|
||||
rad_weight w_norm = 0;
|
||||
LinearFP8 gate_up{}, down{};
|
||||
NormQuantFP8 nq_h{};
|
||||
GateQuantFP8 gq_ffn{};
|
||||
LinearQ gate_up{}, down{};
|
||||
NormQuant nq_h{};
|
||||
GateQuant 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).
|
||||
@@ -61,12 +61,12 @@ struct MlpFP8 {
|
||||
* Counterpart of `ar_in`; both sides ask ar_fused_ok(g, T), so they agree. */
|
||||
bool ar_out = false;
|
||||
/* Set before declare: a clamped product (`swiglu_limit`) and its quantiser as one launch
|
||||
* (GateQuantFP8::fuse_clamped). */
|
||||
* (GateQuant::fuse_clamped). */
|
||||
bool swiglu_quant = 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. */
|
||||
* rad_linear.h. */
|
||||
/* `wide_fold`: declare the gated fold over the whole prompt (gemm_nt_q_gated_wide, whose row
|
||||
* serves every M) rather than the narrow row's 64-row band. Set by a model that runs whole
|
||||
* prompts through the fold; every other caller keeps the band and the pair past it. */
|
||||
@@ -75,7 +75,7 @@ struct MlpFP8 {
|
||||
int ar_in = kArNone, bool ar_out_ = false, double swiglu_limit = 0,
|
||||
bool wide_fold = false);
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
/* The block over the first `T` rows of its buffers (see MoeFP8::step_rows). */
|
||||
/* The block over the first `T` rows of its buffers (see MoeQ::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;
|
||||
@@ -95,7 +95,7 @@ struct MlpFP8 {
|
||||
rad_op op_ar_ov = 0;
|
||||
};
|
||||
|
||||
inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
|
||||
inline int MlpQ::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_, double swiglu_limit, bool wide_fold) {
|
||||
g = geom; w = wire; layer = l;
|
||||
@@ -105,7 +105,7 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
|
||||
w_norm = decl_w(b, nm.f("blk.%d.ffn_norm.weight", l), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
|
||||
/* Norm, quantise and residual add in one op (rad_fp8.h: NormQuantFP8). Folded, it adds the
|
||||
/* Norm, quantise and residual add in one op (rad_linear.h: NormQuant). 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));
|
||||
@@ -114,8 +114,8 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
|
||||
{ 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, and so does an
|
||||
* int8 one fed its codes (ActFP8::q8_fed). */
|
||||
* (LinearQ::reads_x); a block-fp8 down_proj reads only codes and scales, and so does an
|
||||
* int8 one fed its codes (ActQ::q8_fed). */
|
||||
const char* down_base = nm.f("blk.%d.ffn_down", l);
|
||||
RAD_ARCH_TRY(down.probe(b, nm, g, down_base, { src.down }));
|
||||
gq_ffn.fuse_clamped = swiglu_quant;
|
||||
@@ -123,52 +123,37 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
|
||||
down.reads_x && !(w.ffn.q8_fed && down.probed_i8), false,
|
||||
swiglu_limit));
|
||||
|
||||
/* The fold: decl_gated_fold (an fp8a8 tile) for block-fp8 weights, decl_gated_fold_mx for plain
|
||||
* MXFP4 at one to 16 rows (eight where K is short). Other gate_up encodings (M2XFP4 included),
|
||||
* and a clamped (swiglu_limit) product, take the pair. Over int8 codes only a host kernel would
|
||||
* take it, which would pin the layer's weights to the host. */
|
||||
/* The fold: decl_gated_fold (an fp8a8 tile) for block-fp8 weights, decl_gated_fold_iqr for an
|
||||
* IQR weight whose input and output are the rotated int8 trunk's fed pairs, to 16 rows. Other
|
||||
* gate_up encodings, and a clamped (swiglu_limit) product, take the pair. */
|
||||
const bool fold_ok = swiglu_limit <= 0 && !gate_up.f32_scale;
|
||||
if (fold_ok && !gate_up.bf16 && !gate_up.mx && !gate_up.m2x && !gate_up.paro5 && !gate_up.w4 &&
|
||||
!gate_up.i8)
|
||||
if (fold_ok && !gate_up.bf16 && !gate_up.w4 && !gate_up.i8)
|
||||
op_gated = decl_gated_fold(b, g.max_tok, gate_up.N, gate_up.K, gate_up.w, gate_up.ws,
|
||||
{ w.h.q, w.h.s },
|
||||
gq_ffn.want_x
|
||||
? std::initializer_list<rad_buf>{ w.ffn.q, w.ffn.s, w.ffn.x }
|
||||
: std::initializer_list<rad_buf>{ w.ffn.q, w.ffn.s },
|
||||
&gated_rows, wide_fold);
|
||||
else if (fold_ok && gate_up.mx && !gate_up.paro)
|
||||
op_gated = decl_gated_fold_mx(b, g.max_tok, gate_up.N, gate_up.K, gate_up.w, gate_up.ws,
|
||||
gate_up.wref, { w.h.q, w.h.s },
|
||||
gq_ffn.want_x
|
||||
? std::initializer_list<rad_buf>{ w.ffn.q, w.ffn.s,
|
||||
w.ffn.x }
|
||||
: std::initializer_list<rad_buf>{ w.ffn.q, w.ffn.s },
|
||||
&gated_rows);
|
||||
else if (fold_ok && gate_up.iqr && w.h.q8_fed && w.h.q8_rot && w.ffn.q8_fed && w.ffn.q8_rot)
|
||||
op_gated = decl_gated_fold_iqr(b, g.max_tok, gate_up.N, gate_up.K, gate_up.w, gate_up.ws,
|
||||
{ w.h.q8, w.h.s8 },
|
||||
gq_ffn.want_x
|
||||
? std::initializer_list<rad_buf>{ w.ffn.q8, w.ffn.s8,
|
||||
w.ffn.x }
|
||||
: std::initializer_list<rad_buf>{ w.ffn.q8, w.ffn.s8 },
|
||||
&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});
|
||||
op_ar = decl_all_reduce(b, g, w.h.x);
|
||||
/* The same collective for a caller that runs it beside other work (issue_ar): 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});
|
||||
op_ar_ov = decl_all_reduce_overlap(b, g, w.h.x, ar_overlap);
|
||||
|
||||
/* Only when the next block's norm will not add (rad_fp8.h: NormQuantFP8). */
|
||||
/* Only when the next block's norm will not add (rad_linear.h: NormQuant). */
|
||||
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),
|
||||
@@ -184,25 +169,20 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
|
||||
* 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 {
|
||||
inline void MlpQ::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);
|
||||
body(c, T, r0, rows);
|
||||
tail(c, r0, rows);
|
||||
}
|
||||
|
||||
inline void MlpFP8::body(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const {
|
||||
if (op_gated && rows <= gated_rows && gate_up.mx) {
|
||||
RAD_ISSUE_N(c, op_gated, rows, brow_slice(w.h.q, r0, rows, g.n_embd),
|
||||
brow_slice(w.h.s, r0, rows, g.n_embd / RAD_FP8_BLOCK), RAD_W(gate_up.w),
|
||||
RAD_W(gate_up.ws), RAD_W(gate_up.wref), brow_slice(w.ffn.q, r0, rows, g.n_ff),
|
||||
brow_slice(w.ffn.s, r0, rows, g.n_ff / RAD_FP8_BLOCK),
|
||||
gq_ffn.want_x ? brow_slice(w.ffn.x, r0, rows, g.n_ff) : RAD_NONE);
|
||||
} else if (op_gated && rows <= gated_rows) {
|
||||
RAD_ISSUE_N(c, op_gated, rows, brow_slice(w.h.q, r0, rows, g.n_embd),
|
||||
brow_slice(w.h.s, r0, rows, g.n_embd / RAD_FP8_BLOCK), RAD_W(gate_up.w),
|
||||
RAD_W(gate_up.ws), brow_slice(w.ffn.q, r0, rows, g.n_ff),
|
||||
brow_slice(w.ffn.s, r0, rows, g.n_ff / RAD_FP8_BLOCK),
|
||||
inline void MlpQ::body(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const {
|
||||
if (op_gated && rows <= gated_rows) {
|
||||
/* The fp8a8 fold's E4M3 pairs, or the IQR fold's int8 ones (cq / cs: the fed pair). */
|
||||
RAD_ISSUE_N(c, op_gated, rows, brow_slice(w.h.cq(), r0, rows, g.n_embd),
|
||||
brow_slice(w.h.cs(), r0, rows, g.n_embd / RAD_SCALE_GROUP), RAD_W(gate_up.w),
|
||||
RAD_W(gate_up.ws), brow_slice(w.ffn.cq(), r0, rows, g.n_ff),
|
||||
brow_slice(w.ffn.cs(), r0, rows, g.n_ff / RAD_SCALE_GROUP),
|
||||
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);
|
||||
@@ -211,7 +191,7 @@ inline void MlpFP8::body(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const {
|
||||
down.step(c, w.ffn, w.h.x, T, r0, rows);
|
||||
}
|
||||
|
||||
inline void MlpFP8::tail(RadCtx* c, int64_t r0, int64_t rows) const {
|
||||
inline void MlpQ::tail(RadCtx* c, int64_t r0, int64_t rows) const {
|
||||
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)
|
||||
@@ -220,7 +200,7 @@ inline void MlpFP8::tail(RadCtx* c, int64_t r0, int64_t rows) const {
|
||||
brow_slice(w.x, r0, rows, g.n_embd));
|
||||
}
|
||||
|
||||
inline void MlpFP8::step(RadCtx* c, const RadBatch* batch) const {
|
||||
inline void MlpQ::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
slice(c, T, 0, T);
|
||||
}
|
||||
@@ -228,4 +208,4 @@ inline void MlpFP8::step(RadCtx* c, const RadBatch* batch) const {
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_MLP_FP8_H */
|
||||
#endif /* RAD_BLOCK_MLP_Q_H */
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,7 +1,7 @@
|
||||
/* 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 ==============================
|
||||
* ============================== DIFFERENCES FROM rad_block_mtp_q.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
|
||||
@@ -32,7 +32,7 @@
|
||||
*
|
||||
* ============================== THE TWO KINDS OF PASS ==============================
|
||||
*
|
||||
* By the sign of `RadBatch::draft_pass` (details in rad_block_mtp_fp8.h):
|
||||
* By the sign of `RadBatch::draft_pass` (details in rad_block_mtp_q.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
|
||||
@@ -53,7 +53,7 @@
|
||||
*
|
||||
* 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
|
||||
* overwritten by the next step's token at the same address (see rad_block_mtp_q.h). The group's
|
||||
* page grows from 12 layers to 13 (8% more attention KV), only when speculation is declared.
|
||||
*
|
||||
* ============================== BUFFERS ==============================
|
||||
@@ -69,10 +69,10 @@
|
||||
#ifndef RAD_BLOCK_MTP_HC_H
|
||||
#define RAD_BLOCK_MTP_HC_H
|
||||
|
||||
#include "rad_block_attn_gated_fp8.h"
|
||||
#include "rad_block_attn_gated_q.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_block_moe_q.h"
|
||||
#include "rad_block_mtp_q.h" /* mtp_draft_head_q2(): one reading of the 2-bit head */
|
||||
#include "rad_spechub.h" /* RAD_MTP_COUPLE_*: the coupling wire */
|
||||
#include "rad_qsa.h"
|
||||
#include "rad_block_vit.h"
|
||||
@@ -102,7 +102,7 @@ struct MtpHcBlock {
|
||||
rad_buf inj = 0; /* [max_tok, hc] both connections' write gains */
|
||||
rad_buf hout = 0; /* [max_logit_rows, n_embd] the mixer's output, the lm_head's input */
|
||||
rad_buf logits = 0; /* [max_logit_rows, n_vocab] the trunk's, shared */
|
||||
ActFP8 x{}; /* the narrow block input, the trunk's */
|
||||
ActQ 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;
|
||||
@@ -112,8 +112,8 @@ struct MtpHcBlock {
|
||||
/* --draft-coupling: [max_seqs] draws and [depth, max_seqs] states, both PERSIST across
|
||||
* the serial passes (round 1 resets the logical stream, not the plane). */
|
||||
rad_buf couple_draws = 0, couple_state = 0;
|
||||
AttnGatedFP8::Wire attn{};
|
||||
MoeFP8::Wire mlp{};
|
||||
AttnGatedQ::Wire attn{};
|
||||
MoeQ::Wire mlp{};
|
||||
QsaIndexer::Wire qsa{};
|
||||
};
|
||||
|
||||
@@ -123,8 +123,8 @@ struct MtpHcBlock {
|
||||
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{};
|
||||
AttnGatedQ::Src attn{};
|
||||
MoeQ::Src mlp{};
|
||||
/* The indexer's names and geometry; `qk_proj` null declares no indexer at all. */
|
||||
QsaIndexer::Config qsa{};
|
||||
};
|
||||
@@ -144,16 +144,23 @@ struct MtpHcBlock {
|
||||
rad_weight w_dh = 0, w_dhs = 0;
|
||||
|
||||
HyperConn hc_attn{}, hc_mlp{}, mixer{};
|
||||
AttnGatedFP8 attn{};
|
||||
AttnGatedQ 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{};
|
||||
MoeQ mlp{};
|
||||
|
||||
rad_op op_gather = 0, op_embed = 0, op_embed_ar = 0, op_enter = 0, op_carry = 0;
|
||||
/* The selected draft calibration also records the bf16 attention input shared by
|
||||
* qg/k/v, independently of the expert gate's later input. */
|
||||
rad_buf b_attn_gram = 0;
|
||||
rad_op op_attn_gram = 0;
|
||||
const char* attn_gram_stem = nullptr;
|
||||
mutable int64_t attn_gram_rows = 0;
|
||||
mutable bool attn_gram_done = false;
|
||||
|
||||
/* Media rows over the head's embedding (see MtpBlockFP8::media). Set before declare when the
|
||||
/* Media rows over the head's embedding (see MtpBlockQ::media). Set before declare when the
|
||||
* program has an encoder. */
|
||||
|
||||
bool media = false;
|
||||
@@ -236,12 +243,7 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
/* 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_embed_ar = decl_all_reduce_exact(b, g, w.e, g.n_embd, rows, g.dtype);
|
||||
|
||||
op_enter = rw(b, RAD_OP(b, "mtp_enter",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", g.n_embd),
|
||||
@@ -258,6 +260,21 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
* 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));
|
||||
if (src.mlp.cfg.calib) {
|
||||
/* Only a BF16 source supplies domain-0 inputs for this calibration. The input
|
||||
* is replicated, so each TP rank records the same width and GPTQ sums them. */
|
||||
if (!src.mlp.cfg.expert_bf16 || !w.attn.h.x) return RAD_E_UNSUPPORTED;
|
||||
attn_gram_stem = nm.f("blk.%d.attn_qg", l);
|
||||
b_attn_gram = decl_b(b, nm.f("blk.%d.mtp_attn_gram", l), RAD_F32,
|
||||
{g.n_embd, g.n_embd}, RAD_BUF_PERSIST);
|
||||
op_attn_gram = rw(b, RAD_OP(b, "gram_accum",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("group", RAD_SCALE_GROUP),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.attn.h.x, b_attn_gram}, {b_attn_gram});
|
||||
if (!b_attn_gram || !op_attn_gram) return RAD_E_INVAL;
|
||||
}
|
||||
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,
|
||||
@@ -272,17 +289,17 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
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});
|
||||
op_dback = cast_op(b, g.max_logit_rows, HN, g.dtype, g.dtype, 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; }
|
||||
if (src.mlp.cfg.expert_rot && !w.x.q8_rot) {
|
||||
mcfg.rotate = 1;
|
||||
mwire.rq = w.mlp.hr.cq();
|
||||
mwire.rs = w.mlp.hr.cs();
|
||||
}
|
||||
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;
|
||||
@@ -303,11 +320,7 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
}
|
||||
|
||||
/* ---- 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});
|
||||
op_carry = cast_op(b, rows, HN, g.dtype, g.dtype, 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. */
|
||||
@@ -330,7 +343,7 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
{w.hout}, {w.logits});
|
||||
if (!op_carry || !op_logits) return RAD_E_INVAL;
|
||||
|
||||
/* ---- The 2-bit draft head (rationale in rad_block_mtp_fp8.h): fewer bytes per draft round,
|
||||
/* ---- The 2-bit draft head (rationale in rad_block_mtp_q.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
|
||||
@@ -359,12 +372,8 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
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});
|
||||
op_dlogits = decl_gemm_q(b, g.max_logit_rows, hrows, g.n_embd, MTP_W2_GROUP, "w2a8", 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. */
|
||||
@@ -402,8 +411,8 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_lm));
|
||||
if (!op_drerank) return RAD_E_INVAL;
|
||||
/* Arrays rather than rw(): the write set is conditional (see rad_fp8.h:
|
||||
* NormQuantFP8). */
|
||||
/* Arrays rather than rw(): the write set is conditional (see rad_linear.h:
|
||||
* NormQuant). */
|
||||
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);
|
||||
@@ -467,6 +476,17 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
const int r = batch->draft_pass;
|
||||
/* Expert calibration needs real draft-layer inputs, not the trunk's Hessian. In a
|
||||
* selected calibration layer, run the history's teacher-forced rows through the full
|
||||
* draft block before selecting the rows needed by the drafter. Normal inference and
|
||||
* a tap that has reached its target retain the ordinary history-only fast path. */
|
||||
const bool tap_history = r < 0 && mlp.c.calib && !mlp.calib_done;
|
||||
/* serial_batch names one trunk hidden row per history token. Refuse an incomplete
|
||||
* gather instead of silently calibrating stale hin rows if that contract changes. */
|
||||
if (tap_history && (batch->n_out != T || !batch->out_ids)) {
|
||||
rad_step_fail(c, "MTP calibration needs one trunk hidden row per history token");
|
||||
return;
|
||||
}
|
||||
|
||||
/* The history pass continues from the trunk's wide stream; later rounds from the head's,
|
||||
* which the carry left in the same buffer. */
|
||||
@@ -489,11 +509,26 @@ inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
|
||||
RAD_W(w_fc_h), RAD_W(w_fc_e), brows(w.hw, T));
|
||||
|
||||
hc_attn.read_pieces(c, T);
|
||||
if (tap_history && op_attn_gram && !attn_gram_done) {
|
||||
if (attn_gram_rows == 0)
|
||||
rad_memset_async(rad_buf_ptr(c, b_attn_gram), 0,
|
||||
g.n_embd * g.n_embd * 4, rad_stream(c));
|
||||
RAD_ISSUE_N(c, op_attn_gram, T, brows(w.attn.h.x, T), RAD_NONE,
|
||||
brows(b_attn_gram, g.n_embd));
|
||||
attn_gram_rows += T;
|
||||
if (attn_gram_rows >= calib_target()) {
|
||||
if (!calib_write(c, b_attn_gram, g.n_embd, attn_gram_rows, attn_gram_stem, 0)) {
|
||||
rad_step_fail(c, "MTP calibration could not write its attention input Gram");
|
||||
return;
|
||||
}
|
||||
attn_gram_done = true;
|
||||
}
|
||||
}
|
||||
|
||||
/* 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) {
|
||||
if (r < 0 && batch->n_draft_out <= 0 && !tap_history) {
|
||||
qsa.store(c, attn.w.h, batch);
|
||||
attn.store_kv(c, batch);
|
||||
return;
|
||||
@@ -501,7 +536,7 @@ inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
|
||||
|
||||
/* 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);
|
||||
qsa.step(c, attn.w.h, batch, qsa_win_cu, attn.qsa_use(batch));
|
||||
attn.step(c, batch);
|
||||
|
||||
hc_attn.write(c, T, 0, T);
|
||||
@@ -509,7 +544,7 @@ inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
|
||||
/* 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) {
|
||||
if (r < 0 && !tap_history) {
|
||||
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));
|
||||
@@ -520,6 +555,16 @@ inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
|
||||
mlp.step_rows(c, L);
|
||||
hc_mlp.write(c, L, 0, L);
|
||||
|
||||
if (tap_history) {
|
||||
/* History-only chunks have no proposal. For the last chunk, select the same
|
||||
* round-1 rows the ordinary path would have selected before its feed-forward. */
|
||||
L = batch->n_draft_out;
|
||||
if (L <= 0) return;
|
||||
RAD_ISSUE_N(c, op_dsel, L, RAD_B(w.hw), praw(batch->draft_out_ids, RAD_I32, L),
|
||||
brows(w.hin, L));
|
||||
RAD_ISSUE_N(c, op_dback, L, brows(w.hin, L), brows(w.hw, L));
|
||||
}
|
||||
|
||||
/* 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)
|
||||
@@ -532,7 +577,7 @@ inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
|
||||
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_linear.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) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/* rad_block_mtp_fp8.h -- the multi-token-prediction head, with block-scaled FP8 projections.
|
||||
/* rad_block_mtp_q.h -- the multi-token-prediction head over LinearQ projections.
|
||||
*
|
||||
* ============================== WHAT IT IS ==============================
|
||||
*
|
||||
@@ -21,7 +21,7 @@
|
||||
* 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
|
||||
* x = one gated-GQA layer + one SwiGLU feed-forward, over x <- AttnGatedQ, MlpQ
|
||||
* h'= mtp.norm(x)
|
||||
* logits = the trunk's lm_head over h'
|
||||
*
|
||||
@@ -86,12 +86,13 @@
|
||||
* 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
|
||||
#ifndef RAD_BLOCK_MTP_Q_H
|
||||
#define RAD_BLOCK_MTP_Q_H
|
||||
|
||||
#include "rad_block_attn_gated_fp8.h"
|
||||
#include "rad_block_mlp_fp8.h"
|
||||
#include "rad_block_attn_gated_q.h"
|
||||
#include "rad_block_mlp_q.h"
|
||||
#include "rad_block_vit.h"
|
||||
#include "rad_spechub.h"
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
@@ -112,10 +113,13 @@ inline bool mtp_draft_head_q2(RadBuilder* b, const char* head, const char* lm) {
|
||||
|
||||
/* 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). */
|
||||
* `Ffn` is MlpQ or MoeQ; both have the same declare() signature over their own Wire and Src
|
||||
* (MoeQ's Config travels inside its Src for this reason). */
|
||||
template <class Ffn>
|
||||
struct MtpBlockFP8 {
|
||||
struct MtpBlockQ {
|
||||
/* spechub consumes a top-eight law; otherwise only the greedy token is needed. */
|
||||
static constexpr int proposal_pitch(bool coupled) { return coupled ? 8 : 1; }
|
||||
|
||||
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. */
|
||||
@@ -128,17 +132,22 @@ struct MtpBlockFP8 {
|
||||
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 2-bit projection's scratch: at most one proposal per sequence, including the
|
||||
* selected final history rows. The unselected history rows need only K/V. */
|
||||
rad_buf dq = 0; /* [max_seqs, n_embd] int8 codes */
|
||||
rad_buf ds = 0; /* [max_seqs, 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_seqs, n_vocab_all] bf16, the coarse logits */
|
||||
rad_buf didx = 0; /* [max_seqs, proposal_pitch] i32, proposal in column zero */
|
||||
rad_buf dval = 0; /* [max_seqs, proposal_pitch] f32, shortlist logits */
|
||||
bool coupled = false;
|
||||
/* A targeted calib-corpus run may select the virtual MTP layer (n_main) and record the
|
||||
* draft head's actual input. The trunk's CalibFull is intentionally not involved. */
|
||||
const char* calib_dir = nullptr;
|
||||
int64_t calib_tokens = 0;
|
||||
/* 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{};
|
||||
AttnGatedQ::Wire attn{};
|
||||
typename Ffn::Wire mlp{};
|
||||
};
|
||||
|
||||
@@ -147,10 +156,7 @@ struct MtpBlockFP8 {
|
||||
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{};
|
||||
AttnGatedQ::Src attn{};
|
||||
typename Ffn::Src mlp{};
|
||||
};
|
||||
|
||||
@@ -162,7 +168,7 @@ struct MtpBlockFP8 {
|
||||
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{};
|
||||
AttnGatedQ 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
|
||||
@@ -172,6 +178,11 @@ struct MtpBlockFP8 {
|
||||
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;
|
||||
rad_buf couple_draws = 0, couple_state = 0;
|
||||
rad_op op_couple[RAD_MTP_COUPLE_MAX_ROUNDS] = {};
|
||||
CalibTap draft_head_calib{};
|
||||
bool draft_head_calib_on = false;
|
||||
mutable int64_t draft_head_calib_rows = 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,
|
||||
@@ -180,13 +191,31 @@ struct MtpBlockFP8 {
|
||||
};
|
||||
|
||||
template <class Ffn>
|
||||
inline int MtpBlockFP8<Ffn>::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
inline int MtpBlockQ<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;
|
||||
q2 = w.dq != 0;
|
||||
draft_head_calib_on = w.calib_dir && *w.calib_dir;
|
||||
if (draft_head_calib_on && (w.calib_tokens <= 0 || g.max_spec != 0 || q2 || w.coupled)) {
|
||||
std::fprintf(stderr, "radiance: MTP draft-head calibration requires a non-empty corpus "
|
||||
"and a history-only head (speculation off)\n");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (w.coupled && (!q2 || g.max_spec < 1 || g.max_spec > RAD_MTP_COUPLE_MAX_ROUNDS)) {
|
||||
std::fprintf(stderr, "radiance: Qwen35 native MTP coupling requires the U2 draft head and "
|
||||
"a draft depth in 1..%d\n", RAD_MTP_COUPLE_MAX_ROUNDS);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (w.coupled && !rad_op_declared(b, "mtp_couple_propose")) {
|
||||
std::fprintf(stderr, "radiance: load the spechub kernels for Qwen35 MTP draft coupling\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (rows <= 0 || !w_tok || (!draft_head_calib_on &&
|
||||
(q2 ? (!w.ds || !w.dsum || !w.dlog || !w.didx || !w.dval) : (!w_lm || !w.logits))))
|
||||
return RAD_E_INVAL;
|
||||
|
||||
/* The normed embedding first, then the normed hidden state (see the header). */
|
||||
off_e = 0;
|
||||
@@ -225,12 +254,7 @@ inline int MtpBlockFP8<Ffn>::declare(RadBuilder* b, Names& nm, const Geom& geom,
|
||||
/* 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_embed_ar = decl_all_reduce_exact(b, g, w.e, g.n_embd, rows, g.dtype);
|
||||
|
||||
op_pre_h = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", g.n_embd),
|
||||
@@ -257,17 +281,15 @@ inline int MtpBlockFP8<Ffn>::declare(RadBuilder* b, Names& nm, const Geom& geom,
|
||||
* 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;
|
||||
if (!draft_head_calib_on) {
|
||||
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 = cast_op(b, g.max_logit_rows, g.n_embd, g.dtype, g.dtype, 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));
|
||||
|
||||
@@ -277,15 +299,22 @@ inline int MtpBlockFP8<Ffn>::declare(RadBuilder* b, Names& nm, const Geom& geom,
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_norm)),
|
||||
{w.x}, {w.hout});
|
||||
if (!op_norm) return RAD_E_INVAL;
|
||||
if (draft_head_calib_on)
|
||||
return g.rank == 0 ? draft_head_calib.declare(b, nm, rows, nm.f("mtp.draft_head"),
|
||||
w.hout, g.n_embd) : RAD_OK;
|
||||
|
||||
/* 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});
|
||||
/* Only the fallback projects through the target's single lm_head. In particular do not
|
||||
* declare an unused logits_gemm with a null weight when the target uses width classes. */
|
||||
if (!q2) {
|
||||
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_logits) return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* ---- The 2-bit draft head.
|
||||
*
|
||||
@@ -299,20 +328,26 @@ inline int MtpBlockFP8<Ffn>::declare(RadBuilder* b, Names& nm, const Geom& geom,
|
||||
* 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.
|
||||
* The head bypasses the sampler's f32 logits. row_topk takes the argmax, or the shortlist
|
||||
* when coupling is on; the engine reads the proposal from column zero of didx. The target'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");
|
||||
RadEncoding enc{}, expected = rad_enc_affine(RAD_U2, RAD_F16, 1, MTP_W2_GROUP);
|
||||
rad_enc_add_plane(&expected, "zero", RAD_U8, 1, MTP_W2_GROUP);
|
||||
if (!weight_enc(b, dhn, &enc) || !rad_enc_equal(&enc, &expected)) {
|
||||
std::fprintf(stderr, "radiance: %s requires unrotated U2 codes with an F16 scale and "
|
||||
"U8 zero per group of 128\n", dhn);
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
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,
|
||||
@@ -321,32 +356,45 @@ inline int MtpBlockFP8<Ffn>::declare(RadBuilder* b, Names& nm, const Geom& geom,
|
||||
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_PARAMS(RAD_RANGE("M", 1, g.max_seqs),
|
||||
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_dlogits = decl_gemm_q(b, g.max_seqs, g.n_vocab_all, g.n_embd, MTP_W2_GROUP, "w2a8",
|
||||
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_PARAMS(RAD_RANGE("M", 1, g.max_seqs),
|
||||
RAD_INT("N", g.n_vocab_all), RAD_INT("R", proposal_pitch(w.coupled)),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.dlog}, {w.didx, w.dval});
|
||||
if (!op_dquant || !op_dlogits || !op_dtopk) return RAD_E_INVAL;
|
||||
if (w.coupled) {
|
||||
/* The engine binds these persistent planes by name. The U2 projection is
|
||||
* replicated over the full vocabulary, so its shortlist already holds global ids. */
|
||||
couple_draws = decl_b(b, nm.f("mtp_couple_draws"), RAD_U32,
|
||||
{g.max_seqs, RAD_MTP_COUPLE_DRAW_WORDS}, RAD_BUF_PERSIST);
|
||||
couple_state = decl_b(b, nm.f("mtp_couple_state"), RAD_U32,
|
||||
{g.max_spec, g.max_seqs, RAD_MTP_COUPLE_STATE_WORDS}, RAD_BUF_PERSIST);
|
||||
if (!couple_draws || !couple_state) return RAD_E_INVAL;
|
||||
for (int rd = 1; rd <= g.max_spec; ++rd) {
|
||||
op_couple[rd - 1] = rw(b, RAD_OP(b, "mtp_couple_propose",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("n_vocab", g.n_vocab_all),
|
||||
RAD_INT("round", rd), RAD_INT("max_rounds", g.max_spec)),
|
||||
RAD_NOWEIGHTS), {w.didx, w.dval, couple_draws}, {w.didx, couple_state});
|
||||
if (!op_couple[rd - 1]) return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* 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;
|
||||
const rad_op last = w.coupled ? op_couple[g.max_spec - 1] : q2 ? op_dtopk : op_logits;
|
||||
if (rad_op_reads(b, last, &w.hout, 1) < 0) return RAD_E_INVAL;
|
||||
}
|
||||
return RAD_OK;
|
||||
@@ -356,9 +404,14 @@ inline int MtpBlockFP8<Ffn>::declare(RadBuilder* b, Names& nm, const Geom& geom,
|
||||
* 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 {
|
||||
inline void MtpBlockQ<Ffn>::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
const int r = batch->draft_pass;
|
||||
const bool tap_history = draft_head_calib_on;
|
||||
if (tap_history && (r >= 0 || batch->n_out != T || batch->n_draft_out != 0)) {
|
||||
rad_step_fail(c, "MTP draft-head calibration requires every history row and no proposals");
|
||||
return;
|
||||
}
|
||||
|
||||
/* The history pass gathers; later rounds read the previous pass's output from the same
|
||||
* buffer. */
|
||||
@@ -367,6 +420,10 @@ inline void MtpBlockFP8<Ffn>::step(RadCtx* c, const RadBatch* batch) const {
|
||||
"the history pass (RadBatch::draft_out_ids) and has no pass of its own");
|
||||
return;
|
||||
}
|
||||
if (w.coupled && (r == 0 || r > g.max_spec)) {
|
||||
rad_step_fail(c, "Qwen35 MTP coupled round outside the declared draft depth");
|
||||
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),
|
||||
@@ -381,18 +438,19 @@ inline void MtpBlockFP8<Ffn>::step(RadCtx* c, const RadBatch* batch) const {
|
||||
|
||||
RAD_ISSUE(c, op_fc, brows(w.c, T), RAD_W(w_fc), brows(w.x, T));
|
||||
|
||||
/* A history pass 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) {
|
||||
/* The ordinary history fast path only stores K/V. A selected MTP calibration layer instead
|
||||
* runs every prompt row through the block so the U2 draft head gets a real, full-rank Gram. */
|
||||
if (r < 0 && batch->n_draft_out <= 0 && !tap_history) {
|
||||
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. */
|
||||
* to the front of `x` and the rest of the head runs over them. Calibration uses all prompt
|
||||
* rows and returns before the proposal path. */
|
||||
int64_t L = T; /* the rows the stream goes on with */
|
||||
if (r < 0) {
|
||||
if (r < 0 && !tap_history) {
|
||||
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));
|
||||
@@ -402,27 +460,49 @@ inline void MtpBlockFP8<Ffn>::step(RadCtx* c, const RadBatch* batch) const {
|
||||
mlp.step_rows(c, L);
|
||||
|
||||
RAD_ISSUE(c, op_norm, brows(w.x, L), RAD_W(w_norm), brows(w.hout, L));
|
||||
if (tap_history) {
|
||||
/* Only the owner counts and writes. Followers can replay this pass without a host tap. */
|
||||
if (g.rank == 0) {
|
||||
if (L > w.calib_tokens - draft_head_calib_rows) {
|
||||
rad_step_fail(c, "MTP draft-head calibration would count more rows than the corpus holds");
|
||||
return;
|
||||
}
|
||||
draft_head_calib.step(c, w.hout, L, true);
|
||||
draft_head_calib_rows += L;
|
||||
if (draft_head_calib_rows == w.calib_tokens &&
|
||||
!calib_write_to(c, draft_head_calib.h, draft_head_calib.K, draft_head_calib_rows,
|
||||
"mtp.draft_head", 0, w.calib_dir))
|
||||
rad_step_fail(c, "failed to write the MTP draft-head RADGRAM2 calibration");
|
||||
}
|
||||
return; /* calib-corpus needs the head input, not a speculative proposal */
|
||||
}
|
||||
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_linear.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 */
|
||||
if (w.coupled) {
|
||||
const int rd = r < 0 ? 1 : r; /* history already supplied round one's rows */
|
||||
RAD_ISSUE_N(c, op_couple[rd - 1], L, brows(w.didx, L), brows(w.dval, L),
|
||||
praw(batch->seq_ids, RAD_I32, batch->n_seq), brows(couple_draws, L),
|
||||
RAD_B(couple_state));
|
||||
}
|
||||
} 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>;
|
||||
/* The dense head (SwiGLU feed-forward). The routed one is MtpBlockQ<MoeQ>, named by the
|
||||
* plugin that needs it; this header does not include rad_block_moe_q.h. */
|
||||
using MtpQ = MtpBlockQ<MlpQ>;
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_MTP_FP8_H */
|
||||
#endif /* RAD_BLOCK_MTP_Q_H */
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,739 @@
|
||||
/* rad_block_museglimmer_vision.h -- Muse Glimmer's vision tower (transformers'
|
||||
* MuseGlimmerVisionModel, an InternVit-shaped stack), its adapter and the perception norm, served
|
||||
* by museglimmer.
|
||||
*
|
||||
* What it computes, per encoder pass (RadBatch::enc), in the reference's order:
|
||||
*
|
||||
* x = patches @ Wp^T the patch embedding as a linear layer, bias-less;
|
||||
* a patch row is (temporal, channel, y, x)
|
||||
* x += position table resampled to the grid `grid_embed_pad`, bilinear at half-pixel
|
||||
* centres, align_corners=False, out-of-range taps
|
||||
* zero-weighted (grid_sample padding zeros)
|
||||
* x = LN_pre(x) LayerNorm, eps `layer_norm_eps`
|
||||
* x = x[window order] `window_order`: the 32x32-patch window permutation
|
||||
* (per frame, ragged edges smaller windows), its
|
||||
* inverse, per-slot rotary positions and the
|
||||
* per-window cumulative boundaries
|
||||
* depth times:
|
||||
* h = LN1(x) LayerNorm, eps 1e-5 (the blocks hard-code it)
|
||||
* q|k|v = qkv(h) the reference's three biased projections, joined
|
||||
* q first into one GEMM as the reference's fused
|
||||
* tensors would read
|
||||
* rope(q, k) `rope` axial, the whole head, sections
|
||||
* head_dim/4 a side on theta^(-j/(head_dim/4)),
|
||||
* positions (column + 1, row + 1) -- HF's
|
||||
* position_ids.flip(-1) + 1
|
||||
* x += proj(attn(q, k, v)) non-causal, scale 1/sqrt(head_dim). A
|
||||
* window_attention layer attends within one window
|
||||
* (cu = the per-window boundaries in permuted
|
||||
* order); a full_attention layer attends within
|
||||
* its frame (cu = the frame boundaries). The
|
||||
* window permutation never moves a patch across
|
||||
* frames, so the frame boundaries among permuted
|
||||
* rows are the boundaries among natural rows:
|
||||
* `enc_cu` is passed unchanged, exactly what the
|
||||
* reference passes (modeling_muse_glimmer.py maps
|
||||
* full_attention to the frame cu_seqlens while the
|
||||
* rows stay permuted).
|
||||
* x += fc2(gelu(fc1(LN2(x)))) both biased; `gelu` the exact erf form the
|
||||
* config's hidden_act names, in gemm_nt_bias's
|
||||
* epilogue
|
||||
* x = x[inv] the window order undone (gather_rows)
|
||||
* x = LN_post(x) LayerNorm, eps `layer_norm_eps`
|
||||
* y = pixel_shuffle(x) the merge (`pixtral_merge`): each 2x2 block's
|
||||
* four patches fold into one row of merge^2 *
|
||||
* width, channels interleaved -- the reference's
|
||||
* [block, merge^2, dim].permute(0, 2, 1)
|
||||
* y = gelu(fc2(gelu(fc1(y)))) the adapter: both linears bias-less, TWO
|
||||
* activations (projector_hidden_act)
|
||||
* y = y @ Wproj^T the projection, bias-less, the model's width
|
||||
* out = rms(y) `perception_emb_norm`, a weightless RMS norm at
|
||||
* the TEXT model's rms_norm_eps
|
||||
*
|
||||
* The reference permutes AFTER ln_pre, so the tower works in window order and un-permutes before
|
||||
* ln_post, exactly as above. The processor stages patches in the reference's raster order; the
|
||||
* merge is a real fold (not a view: the reference interleaves the four patches' channels, which
|
||||
* four consecutive rows do not spell), and its output is what the adapter reads.
|
||||
*
|
||||
* A linear is BF16, or int8 with a bf16 scale per (row, 128 of K). The int8 form is what replaced
|
||||
* block FP8: quant_act_i8g, then gemm_i8a8_row, which reads the container's own bytes so a tower
|
||||
* placed in RAM is read in place. The patch stem, position table, norms and biases stay BF16.
|
||||
*
|
||||
* Every rank runs the whole tower with replicated weights, as rad_block_vit.h's does, and the
|
||||
* weights are RAD_ACCESS_PER_REQUEST. Activations are sized by the pass (RadBuildCtx::
|
||||
* max_enc_patches rows), except in a sizing declare (shape_probe), where rows follow the probe's
|
||||
* step; the attention's longest segment stays at the real pass so the kernel rows do not move.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_MUSEGLIMMER_VISION_H
|
||||
#define RAD_BLOCK_MUSEGLIMMER_VISION_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
#include "rad_linear.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
/* A vision linear is BF16, or int8 codes with a bf16 scale per (row, 128 of K): the form that
|
||||
* replaced block FP8. The int8 path quantises the BF16 input with quant_act_i8g and reads it with
|
||||
* gemm_i8a8_row (`w_rb` 1), whose weights stay the container's bytes so a tower on the mapped
|
||||
* tier is read in place. Bias, the exact-erf GELU and the residual are separate BF16 ops, so the
|
||||
* int8 path rounds once before the bias (the BF16 gemm_nt_bias fuses that epilogue). The patch
|
||||
* stem, position table, norms and biases stay BF16; a linear whose K or N is not a whole 128 is
|
||||
* refused rather than served by a fragment-order tile that the mapped tier cannot read. */
|
||||
struct MuseVisionAct {
|
||||
rad_buf q = 0, s = 0;
|
||||
int declare(RadBuilder* b, Names& nm, const char* name, int64_t rows, int64_t n) {
|
||||
if (n % RAD_SCALE_GROUP) return RAD_E_SHAPE;
|
||||
q = decl_b(b, nm.f("%s.q", name), RAD_I8, { rows, n });
|
||||
s = decl_b(b, nm.f("%s.s", name), RAD_F32, { rows, n / RAD_SCALE_GROUP });
|
||||
return q && s ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
};
|
||||
|
||||
struct MuseVisionLinear {
|
||||
rad_weight w = 0, ws = 0, bias = 0;
|
||||
rad_op op = 0, op_q = 0, op_bias = 0, op_gelu = 0, op_add = 0;
|
||||
rad_buf x = 0, y = 0, tmp = 0, residual = 0;
|
||||
MuseVisionAct a{};
|
||||
int64_t N = 0, K = 0;
|
||||
bool quant = false;
|
||||
|
||||
int weights(RadBuilder* b, Names& nm, const char* base, int64_t n, int64_t k,
|
||||
RadWeightGroup group, std::initializer_list<const char*> src,
|
||||
std::initializer_list<int64_t> parts = {}) {
|
||||
N = n; K = k;
|
||||
const char* wn = nm.f("%s.weight", base);
|
||||
if (src.size() == 1) {
|
||||
if (map_copy(b, wn, *src.begin()) < 0) return RAD_E_INVAL;
|
||||
} else if (map_concat(b, wn, src) < 0) {
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RadEncoding enc{};
|
||||
const bool known = weight_enc(b, wn, &enc);
|
||||
const bool plain = !known || (rad_enc_is(&enc, "plain") && enc.n_planes == 1 &&
|
||||
enc.plane[0].dtype == RAD_BF16);
|
||||
const int64_t part_n = (int64_t)parts.size();
|
||||
int64_t part_w[8] = {};
|
||||
int pi = 0;
|
||||
for (int64_t p : parts) {
|
||||
if (pi >= 8) return RAD_E_INVAL;
|
||||
part_w[pi++] = p;
|
||||
}
|
||||
if (plain) {
|
||||
w = decl_w(b, wn, RAD_BF16, { N, K }, RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE,
|
||||
group, 0, parts);
|
||||
return w ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
if (const char* gone = known ? linear_retired(enc) : nullptr)
|
||||
return linear_refuse_retired(wn, gone);
|
||||
if (!known || !linear_is_w8(enc)) {
|
||||
char fmt[256];
|
||||
if (known) rad_enc_format(&enc, fmt, sizeof fmt);
|
||||
else std::snprintf(fmt, sizeof fmt, "an unknown encoding");
|
||||
fprintf(stderr, "radiance: museglimmer vision: '%s' is %s; linears serve BF16 or "
|
||||
"int8 with a bf16 scale per (row, 128 of K)\n", wn, fmt);
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
if (N % RAD_SCALE_GROUP || K % RAD_SCALE_GROUP) {
|
||||
fprintf(stderr, "radiance: museglimmer vision: '%s' is %lldx%lld; an int8 linear "
|
||||
"needs N and K in whole 128s\n", wn, (long long)N, (long long)K);
|
||||
return RAD_E_SHAPE;
|
||||
}
|
||||
quant = true;
|
||||
w = decl_view(b, wn, nullptr, "codes", RAD_I8, { N, K }, RAD_ACCESS_PER_REQUEST,
|
||||
RAD_SHARD_NONE, group, part_n ? part_w : nullptr, (int)part_n);
|
||||
ws = decl_view(b, nm.f("%s.scale", base), wn, "scale", RAD_BF16,
|
||||
{ N, K / RAD_SCALE_GROUP }, RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, group,
|
||||
part_n ? part_w : nullptr, (int)part_n);
|
||||
return w && ws ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
int ops(RadBuilder* b, int64_t rows, rad_buf in, rad_buf out, const MuseVisionAct& act,
|
||||
rad_buf res = 0, rad_buf scratch = 0, const char* activation = "none") {
|
||||
x = in; y = out; residual = res; tmp = res ? scratch : out; a = act;
|
||||
if (!x || !y || !w || (res && !tmp)) return RAD_E_INVAL;
|
||||
if (!quant) {
|
||||
if (bias) {
|
||||
op = res ? rw(b, 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", activation)),
|
||||
RAD_WEIGHTS(w, bias)), { x, res }, { y })
|
||||
: rw(b, 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", activation)),
|
||||
RAD_WEIGHTS(w, bias)), { x }, { y });
|
||||
} else {
|
||||
op = rw(b, 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)), { x }, { y });
|
||||
if (std::strcmp(activation, "none")) return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
return op ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
if (!a.q || !a.s) return RAD_E_INVAL;
|
||||
op_q = decl_quant_act(b, "quant_act_i8g", rows, K, RAD_SCALE_GROUP, x, a.q, a.s);
|
||||
op = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_INT("group", RAD_SCALE_GROUP), RAD_STR("dtype", "i8a8"),
|
||||
RAD_INT("w_rb", 1)),
|
||||
RAD_WEIGHTS(w, ws)),
|
||||
{ a.q, a.s }, { tmp });
|
||||
if (bias)
|
||||
op_bias = rw(b, RAD_OP(b, "table_add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", N), RAD_INT("L", 1),
|
||||
RAD_STR("dtype", "bf16")), RAD_WEIGHTS(bias)),
|
||||
{ tmp }, { tmp });
|
||||
if (!std::strcmp(activation, "gelu"))
|
||||
op_gelu = rw(b, RAD_OP(b, "gelu",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", N),
|
||||
RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS),
|
||||
{ tmp }, { tmp });
|
||||
else if (std::strcmp(activation, "none")) return RAD_E_UNSUPPORTED;
|
||||
if (res)
|
||||
op_add = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", N),
|
||||
RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS),
|
||||
{ tmp, res }, { y });
|
||||
return op_q && op && (!bias || op_bias) &&
|
||||
(std::strcmp(activation, "gelu") || op_gelu) && (!res || op_add)
|
||||
? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
void step(RadCtx* c, int64_t rows) const {
|
||||
if (!quant) {
|
||||
if (bias)
|
||||
RAD_ISSUE_N(c, op, rows, brows(x, rows), RAD_W(w), RAD_W(bias),
|
||||
residual ? brows(residual, rows) : RAD_NONE, brows(y, rows));
|
||||
else
|
||||
RAD_ISSUE_N(c, op, rows, brows(x, rows), RAD_W(w), brows(y, rows));
|
||||
return;
|
||||
}
|
||||
RAD_ISSUE_N(c, op_q, rows, brows(x, rows), brows(a.q, rows), brows(a.s, rows));
|
||||
/* a_sum and b_ref are the schema's optional tail; this grid reads neither. */
|
||||
RAD_ISSUE_N(c, op, rows, brows(a.q, rows), brows(a.s, rows), RAD_W(w), RAD_W(ws),
|
||||
brows(tmp, rows), RAD_NONE, RAD_NONE);
|
||||
if (op_bias) RAD_ISSUE_N(c, op_bias, rows, brows(tmp, rows), RAD_W(bias), brows(tmp, rows));
|
||||
if (op_gelu) RAD_ISSUE_N(c, op_gelu, rows, brows(tmp, rows), brows(tmp, rows));
|
||||
if (op_add) RAD_ISSUE_N(c, op_add, rows, brows(tmp, rows), brows(residual, rows),
|
||||
brows(y, rows));
|
||||
}
|
||||
};
|
||||
|
||||
struct MuseTower {
|
||||
/* Geometry, from the container's vision_config (never aliased: only the full prefix). The
|
||||
* adapter's widths are top-level keys of the family config. */
|
||||
int64_t depth = 0, width = 0, heads = 0, head_dim = 0, ff = 0, patch = 0, temporal = 0;
|
||||
int64_t merge = 0, side = 0, npos = 0, proj_ff = 0, out_hidden = 0, n_embd = 0;
|
||||
int64_t patch_dim = 0, P = 0;
|
||||
double eps = 1e-5; /* ln_pre / ln_post; the blocks hard-code 1e-5 */
|
||||
float theta = 10000.0f;
|
||||
bool on = false;
|
||||
|
||||
struct Layer {
|
||||
bool full = false; /* full_attention: frame-wide attention, NoPE-free (rotary runs
|
||||
* on every layer of this tower, full or window) */
|
||||
rad_weight n1w = 0, n1b = 0, n2w = 0, n2b = 0;
|
||||
MuseVisionLinear qkv, proj, up, down;
|
||||
rad_op ln1 = 0, rope = 0, attn = 0, ln2 = 0;
|
||||
int64_t max_seg = 0; /* the kernel band's longest segment */
|
||||
};
|
||||
std::vector<Layer> L;
|
||||
rad_weight w_patch = 0, w_pos = 0, lw_pre = 0, lb_pre = 0, lw_post = 0, lb_post = 0;
|
||||
MuseVisionLinear a1, a2, proj;
|
||||
MuseVisionAct a_width, a_ff, a_merged, a_projector;
|
||||
rad_op op_patch = 0, op_pos = 0, op_lpre = 0, op_wo = 0, op_gidx = 0, op_ginv = 0;
|
||||
rad_op op_lpost = 0, op_merge = 0, op_g1 = 0, op_g2 = 0, op_perc = 0;
|
||||
rad_buf b_x = 0, b_h = 0, b_p = 0, b_qkv = 0, b_att = 0, b_ff = 0;
|
||||
rad_buf b_idx = 0, b_inv = 0, b_pos = 0, b_cuw = 0;
|
||||
rad_buf b_mh = 0, b_m1 = 0, b_m2 = 0, b_out = 0;
|
||||
char sec[48] = {};
|
||||
|
||||
/* Whether the container carries this family's tower. */
|
||||
static bool present(const RadModelMeta* m) {
|
||||
return 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 MuseTower::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);
|
||||
temporal = rad_meta_geti(m, "vision_config.patch_temporal", 2);
|
||||
merge = rad_meta_geti(m, "vision_config.merge_size", 2);
|
||||
side = rad_meta_geti(m, "vision_config.pos_emb_height", 0);
|
||||
npos = rad_meta_geti(m, "vision_config.pos_emb_height", 0) *
|
||||
rad_meta_geti(m, "vision_config.pos_emb_width", 0);
|
||||
eps = rad_meta_getf(m, "vision_config.layer_norm_eps", 1e-5);
|
||||
theta = (float)rad_meta_getf(m, "vision_config.rope_parameters.rope_theta", 10000.0);
|
||||
proj_ff = rad_meta_geti(m, "projector_hidden_size", 4096);
|
||||
out_hidden = rad_meta_geti(m, "out_hidden_size", 6144);
|
||||
n_embd = model_embd;
|
||||
/* Bounds the walk and the host allocations below take at face value, set against published
|
||||
* maxima rather than round numbers: the deepest vision encoder ever shipped is 48 layers
|
||||
* (ViT-22B, InternViT-6B; this family's towers are SigLIP-class, tens), and the largest
|
||||
* stored position table a side of 92 (SigLIP at 1292 px over patch 14; CLIP 16, SAM 64 --
|
||||
* native-resolution towers store no side x side table at all). The caps sit ~2.6x and
|
||||
* ~5.5x past those maxima, so they never bite an honest container, and at the cap the
|
||||
* guarded shapes are harmless: the depth vectors cost KiB and the grid products reach 2^18
|
||||
* at most. Past the caps the container is not describing a model but a vector size
|
||||
* (full.assign(depth) and L.assign(depth) would throw past max_size, and the grid products
|
||||
* below overflow signed 64 before any comparison could notice). Refuse like every other
|
||||
* bad config: say so and RAD_E_INVAL. */
|
||||
if (depth <= 0 || depth > 128 || width <= 0 || heads <= 0 || ff <= 0 || patch <= 0 ||
|
||||
temporal <= 0 || merge <= 0 || side <= 0 || side > 512 || proj_ff <= 0 ||
|
||||
out_hidden <= 0 || width % heads ||
|
||||
rad_meta_geti(m, "vision_config.pos_emb_width", 0) != side) {
|
||||
fprintf(stderr, "radiance: museglimmer: the container's vision_config is incomplete, "
|
||||
"inconsistent, or past what this tower walks (depth %lld, hidden %lld, "
|
||||
"heads %lld, ff %lld, patch %lld, "
|
||||
"temporal %lld, merge %lld, position grid %lld x %lld, projector %lld, "
|
||||
"merged %lld)\n", (long long)depth, (long long)width, (long long)heads,
|
||||
(long long)ff, (long long)patch, (long long)temporal, (long long)merge,
|
||||
(long long)side, (long long)rad_meta_geti(m, "vision_config.pos_emb_width", 0),
|
||||
(long long)proj_ff, (long long)out_hidden);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* The merge is `pixtral_merge`, whose kernels fold a 2x2 block: the only factor Muse Glimmer
|
||||
* ships and the only one the op serves. */
|
||||
if (merge != 2) {
|
||||
fprintf(stderr, "radiance: museglimmer: this vision tower states merge_size %lld; the "
|
||||
"merge op folds a 2x2 block\n", (long long)merge);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* The exact-erf GELU is what this tower and its adapter state; another activation is another
|
||||
* tower (the reference would compute a different function). */
|
||||
const char* act = rad_meta_gets(m, "vision_config.hidden_act", "gelu");
|
||||
const char* pact = rad_meta_gets(m, "projector_hidden_act", "gelu");
|
||||
const char* rt = rad_meta_gets(m, "vision_config.rope_parameters.rope_type", "axial");
|
||||
if (std::strcmp(act, "gelu") || std::strcmp(pact, "gelu")) {
|
||||
fprintf(stderr, "radiance: museglimmer: this vision tower has hidden_act '%s' and "
|
||||
"projector_hidden_act '%s'; it serves the exact gelu both call for\n",
|
||||
act, pact);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* `axial` is Meta's spelling and `default` NVIDIA's ModelOpt export of the same tower: the
|
||||
* reference's vision embedder has one rotary (axial), so both name it. Anything else is
|
||||
* another tower. */
|
||||
if (std::strcmp(rt, "axial") && std::strcmp(rt, "default")) {
|
||||
fprintf(stderr, "radiance: museglimmer: this vision tower states rope_type '%s'; it "
|
||||
"serves the axial 2-D rotary the tower's rotary embedder raises on "
|
||||
"leaving\n", rt);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* The tower's full layers: every fourth, counted from the start, plus the last (the config's
|
||||
* own rule, MuseGlimmerVisionConfig.__post_init__). The shipped array must say the same
|
||||
* thing; a window layer where the rule puts a full one changes what the model saw. */
|
||||
std::vector<int> full;
|
||||
const char* kinds = rad_meta_gets(m, "vision_config.layer_types", "");
|
||||
if (kinds && *kinds) {
|
||||
RAD_ARCH_TRY(parse_layer_kinds("museglimmer vision", kinds, {"full_attention"},
|
||||
"window_attention", &full));
|
||||
if ((int64_t)full.size() != depth) {
|
||||
fprintf(stderr, "radiance: museglimmer: vision_config.layer_types names %zu layers "
|
||||
"and the tower has %lld\n", full.size(), (long long)depth);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
for (int64_t l = 0; l < depth; ++l) {
|
||||
const bool rule = is_full_attention(l, 4) || l == depth - 1;
|
||||
if ((full[(size_t)l] != 0) != rule) {
|
||||
fprintf(stderr, "radiance: museglimmer: vision_config.layer_types makes tower "
|
||||
"layer %lld %s and the family rule (every fourth from the first, "
|
||||
"plus the last) makes it %s\n", (long long)l,
|
||||
full[(size_t)l] ? "full" : "window", rule ? "full" : "window");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
full.assign((size_t)depth, 0);
|
||||
for (int64_t l = 0; l < depth; ++l)
|
||||
full[(size_t)l] = is_full_attention(l, 4) || l == depth - 1;
|
||||
}
|
||||
|
||||
head_dim = width / heads;
|
||||
patch_dim = 3 * temporal * patch * patch;
|
||||
/* The 2-D rotary: half the head a side, each on its own ladder (arange(0, head_dim/2, 2)
|
||||
* frequencies, sections head_dim/4 a side). */
|
||||
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));
|
||||
/* The merger's rows replace token embeddings, so they must be the model's width. */
|
||||
if (out_hidden != merge * merge * width) {
|
||||
fprintf(stderr, "radiance: museglimmer: out_hidden_size %lld is not merge %lld squared "
|
||||
"times the tower's width %lld, whose view the adapter's first layer "
|
||||
"reads\n", (long long)out_hidden, (long long)merge, (long long)width);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* The tower emits merged rows the width of the model's tokens: the caller passes the model's
|
||||
* width and the projection is declared at it, so no separate check exists. */
|
||||
|
||||
const int64_t mm = merge * merge;
|
||||
P = ctx->max_enc_patches;
|
||||
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. The kernel bands stay at the
|
||||
* real pass: the engine runs the real declare's kernels at every level. */
|
||||
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 int64_t ACC = RAD_ACCESS_PER_REQUEST;
|
||||
/* The window side in patches (the reference states it in pixels and divides by patch_size).
|
||||
* A window_attention layer's longest segment is one window. */
|
||||
const int64_t win_seg = side * side;
|
||||
|
||||
/* ---- weights, replicated. Model-level groups for the stem and the adapter; one group per
|
||||
* block from `first_group` on, so a tower block is its own movement unit. */
|
||||
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;
|
||||
RadEncoding e{};
|
||||
if (weight_enc(b, dn, &e) &&
|
||||
!(rad_enc_is(&e, "plain") && e.n_planes == 1 && e.plane[0].dtype == RAD_BF16)) {
|
||||
fprintf(stderr, "radiance: museglimmer vision: '%s' must remain BF16\n", dn);
|
||||
return 0;
|
||||
}
|
||||
return decl_w(b, dn, RAD_BF16, shp, ACC, RAD_SHARD_NONE, g);
|
||||
};
|
||||
w_patch = bw(nm.f("v.patch.weight"),
|
||||
nm.ckpt("model.vision_tower.patch_embedder.patch_embedding.weight"),
|
||||
{ width, patch_dim }, grp_model());
|
||||
w_pos = bw(nm.f("v.pos.weight"),
|
||||
nm.ckpt("model.vision_tower.patch_embedder.position_embedding_table.weight"),
|
||||
{ npos, width }, grp_model());
|
||||
lw_pre = bw(nm.f("v.lnpre.weight"), nm.ckpt("model.vision_tower.ln_pre.weight"), { width },
|
||||
grp_model());
|
||||
lb_pre = bw(nm.f("v.lnpre.bias"), nm.ckpt("model.vision_tower.ln_pre.bias"), { 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;
|
||||
auto src = [&](const char* s) { return nm.ckpt("model.vision_tower.layers.%d.%s", li, s); };
|
||||
auto dn = [&](const char* s) { return nm.f("v.blk.%d.%s", li, s); };
|
||||
l.n1w = bw(dn("norm1.weight"), src("norm1.weight"), { width }, g);
|
||||
l.n1b = bw(dn("norm1.bias"), src("norm1.bias"), { width }, g);
|
||||
/* The reference's three biased projections, joined q | k | v into one GEMM. */
|
||||
RAD_ARCH_TRY(l.qkv.weights(b, nm, dn("qkv"), 3 * width, width, g,
|
||||
{ src("attn.q_proj.weight"), src("attn.k_proj.weight"),
|
||||
src("attn.v_proj.weight") }, { width, width, width }));
|
||||
if (map_concat(b, dn("qkv.bias"),
|
||||
{ src("attn.q_proj.bias"), src("attn.k_proj.bias"),
|
||||
src("attn.v_proj.bias") }) < 0)
|
||||
return RAD_E_INVAL;
|
||||
{
|
||||
const char* qbn = dn("qkv.bias");
|
||||
RadEncoding qb{};
|
||||
if (weight_enc(b, qbn, &qb) &&
|
||||
!(rad_enc_is(&qb, "plain") && qb.n_planes == 1 && qb.plane[0].dtype == RAD_BF16))
|
||||
return RAD_E_DTYPE;
|
||||
l.qkv.bias = decl_w(b, qbn, RAD_BF16, { 3 * width }, ACC, RAD_SHARD_NONE, g, 0,
|
||||
{ width, width, width });
|
||||
}
|
||||
RAD_ARCH_TRY(l.proj.weights(b, nm, dn("proj"), width, width, g,
|
||||
{ src("attn.proj.weight") }));
|
||||
l.proj.bias = bw(dn("proj.bias"), src("attn.proj.bias"), { width }, g);
|
||||
l.n2w = bw(dn("norm2.weight"), src("norm2.weight"), { width }, g);
|
||||
l.n2b = bw(dn("norm2.bias"), src("norm2.bias"), { width }, g);
|
||||
RAD_ARCH_TRY(l.up.weights(b, nm, dn("fc1"), ff, width, g, { src("mlp.fc1.weight") }));
|
||||
l.up.bias = bw(dn("fc1.bias"), src("mlp.fc1.bias"), { ff }, g);
|
||||
RAD_ARCH_TRY(l.down.weights(b, nm, dn("fc2"), width, ff, g, { src("mlp.fc2.weight") }));
|
||||
l.down.bias = bw(dn("fc2.bias"), src("mlp.fc2.bias"), { width }, g);
|
||||
if (!l.n1w || !l.n1b || !l.qkv.bias || !l.proj.bias || !l.n2w || !l.n2b ||
|
||||
!l.up.bias || !l.down.bias)
|
||||
return RAD_E_INVAL;
|
||||
l.full = full[(size_t)i] != 0;
|
||||
l.max_seg = l.full ? ctx->max_enc_patches : win_seg;
|
||||
}
|
||||
lw_post = bw(nm.f("v.lnpost.weight"), nm.ckpt("model.vision_tower.ln_post.weight"), { width },
|
||||
grp_model());
|
||||
lb_post = bw(nm.f("v.lnpost.bias"), nm.ckpt("model.vision_tower.ln_post.bias"), { width },
|
||||
grp_model());
|
||||
RAD_ARCH_TRY(a1.weights(b, nm, "v.mlp.fc1", proj_ff, out_hidden, grp_model(),
|
||||
{ nm.ckpt("model.vision_adapter.fc1.weight") }));
|
||||
RAD_ARCH_TRY(a2.weights(b, nm, "v.mlp.fc2", proj_ff, proj_ff, grp_model(),
|
||||
{ nm.ckpt("model.vision_adapter.fc2.weight") }));
|
||||
RAD_ARCH_TRY(proj.weights(b, nm, "v.proj", n_embd, proj_ff, grp_model(),
|
||||
{ nm.ckpt("model.vision_projection.weight") }));
|
||||
if (!w_patch || !w_pos || !lw_pre || !lb_pre || !lw_post || !lb_post) return RAD_E_INVAL;
|
||||
|
||||
/* ---- activations. `mh` holds the merged rows: `pixtral_merge` folds each 2x2 block's four
|
||||
* patch rows into one row of mm * width in the reference's pixel_shuffle layout, and the
|
||||
* adapter's first layer reads it. */
|
||||
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_p = decl_b(b, nm.f("v.p"), 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_idx = decl_b(b, nm.f("v.idx"), RAD_I32, { P });
|
||||
b_inv = decl_b(b, nm.f("v.inv"), RAD_I32, { P });
|
||||
b_pos = decl_b(b, nm.f("v.pos"), RAD_I32, { 2, P });
|
||||
b_cuw = decl_b(b, nm.f("v.cuw"), RAD_I32, { P + 1 });
|
||||
b_mh = decl_b(b, nm.f("v.mh"), RAD_BF16, { R, mm * width });
|
||||
b_m1 = decl_b(b, nm.f("v.m1"), RAD_BF16, { R, proj_ff });
|
||||
b_m2 = decl_b(b, nm.f("v.m2"), RAD_BF16, { R, proj_ff });
|
||||
b_out = decl_b(b, nm.f("v.out"), RAD_BF16, { R, n_embd });
|
||||
if (!b_x || !b_h || !b_p || !b_qkv || !b_att || !b_ff || !b_idx || !b_inv || !b_pos || !b_cuw ||
|
||||
!b_mh || !b_m1 || !b_m2 || !b_out)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
bool width_i8 = false, ff_i8 = false;
|
||||
for (const Layer& l : L) {
|
||||
width_i8 |= l.qkv.quant || l.proj.quant || l.up.quant;
|
||||
ff_i8 |= l.down.quant;
|
||||
}
|
||||
if (width_i8) RAD_ARCH_TRY(a_width.declare(b, nm, "v.i8_width", P, width));
|
||||
if (ff_i8) RAD_ARCH_TRY(a_ff.declare(b, nm, "v.i8_ff", P, ff));
|
||||
if (a1.quant) RAD_ARCH_TRY(a_merged.declare(b, nm, "v.i8_merged", R, mm * width));
|
||||
if (a2.quant || proj.quant)
|
||||
RAD_ARCH_TRY(a_projector.declare(b, nm, "v.i8_projector", R, proj_ff));
|
||||
|
||||
auto lnorm = [&](int64_t rows, int64_t n, double e, 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", e),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w, bias));
|
||||
};
|
||||
auto attn_op = [&](int64_t max_seg) -> rad_op {
|
||||
return 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);
|
||||
};
|
||||
|
||||
/* The stem is bias-less (the reference's patch_embedding states no bias). */
|
||||
op_patch = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", width),
|
||||
RAD_INT("K", patch_dim), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_patch)),
|
||||
{}, { b_x });
|
||||
op_pos = rw(b, RAD_OP(b, "grid_embed_pad",
|
||||
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 });
|
||||
op_lpre = rw(b, lnorm(P, width, eps, lw_pre, lb_pre), { b_x }, { b_h });
|
||||
op_wo = rw(b, RAD_OP(b, "window_order",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("window", side)),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, { b_idx, b_inv, b_pos, b_cuw });
|
||||
op_gidx = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_h, b_idx }, { b_p });
|
||||
for (Layer& l : L) {
|
||||
l.ln1 = rw(b, lnorm(P, width, 1e-5, l.n1w, l.n1b), { b_p }, { b_h });
|
||||
RAD_ARCH_TRY(l.qkv.ops(b, P, b_h, b_qkv, a_width));
|
||||
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_pos }, { b_qkv });
|
||||
/* A window layer's segment bounds are the order op's per-window cu; a full layer's are
|
||||
* the pass's frame bounds, raw (the permutation is within frames, so they read the same
|
||||
* values in permuted order). */
|
||||
l.attn = rw(b, attn_op(l.max_seg),
|
||||
l.full ? std::initializer_list<rad_buf>{ b_qkv }
|
||||
: std::initializer_list<rad_buf>{ b_qkv, b_cuw },
|
||||
{ b_att });
|
||||
/* b_h is the norm output qkv already consumed, so the residual GEMM may stage there. */
|
||||
RAD_ARCH_TRY(l.proj.ops(b, P, b_att, b_p, a_width, b_p, b_h));
|
||||
l.ln2 = rw(b, lnorm(P, width, 1e-5, l.n2w, l.n2b), { b_p }, { b_h });
|
||||
RAD_ARCH_TRY(l.up.ops(b, P, b_h, b_ff, a_width, 0, 0, "gelu"));
|
||||
RAD_ARCH_TRY(l.down.ops(b, P, b_ff, b_p, a_ff, b_p, b_h));
|
||||
}
|
||||
op_ginv = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_p, b_inv }, { b_x });
|
||||
op_lpost = rw(b, lnorm(P, width, eps, lw_post, lb_post), { b_x }, { b_x });
|
||||
/* The reference's pixel_shuffle: each 2x2 block's four patches fold into one row with the
|
||||
* channels interleaved (block, channel, sub-patch), which is `pixtral_merge`'s layout. A view
|
||||
* over four consecutive rows cannot produce it: the concatenated form is a different tensor. */
|
||||
op_merge = rw(b, RAD_OP(b, "pixtral_merge",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
|
||||
RAD_INT("merge", merge), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_x }, { b_mh });
|
||||
/* The adapter: both linears bias-less, gelu between and after (the reference's
|
||||
* act(fc2(act(fc1(x))))). The GELU stays its own op, as it was on the BF16 path. */
|
||||
RAD_ARCH_TRY(a1.ops(b, R, b_mh, b_m1, a_merged));
|
||||
op_g1 = rw(b, RAD_OP(b, "gelu",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", proj_ff),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_m1 }, { b_m2 });
|
||||
RAD_ARCH_TRY(a2.ops(b, R, b_m2, b_m1, a_projector));
|
||||
op_g2 = rw(b, RAD_OP(b, "gelu",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", proj_ff),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_m1 }, { b_m2 });
|
||||
RAD_ARCH_TRY(proj.ops(b, R, b_m2, b_out, a_projector));
|
||||
/* perception_emb_norm: MuseGlimmerRMSNorm(eps = the TEXT model's rms_norm_eps, with_scale
|
||||
* False) -- no gain operand, no centered 1+. */
|
||||
op_perc = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", n_embd),
|
||||
RAD_F64("eps", m->rms_eps), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_out }, { b_out });
|
||||
|
||||
if (!ctx->shape_probe) {
|
||||
RadEncoderDecl e{};
|
||||
e.name = "vision";
|
||||
e.modalities = RAD_MM_IMAGE | RAD_MM_VIDEO;
|
||||
e.patch_dim = patch_dim;
|
||||
e.merge = mm;
|
||||
e.max_patches = ctx->max_enc_patches;
|
||||
e.n_embd = n_embd;
|
||||
e.out = b_out;
|
||||
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
|
||||
int64_t nfull = 0;
|
||||
for (int64_t l = 0; l < depth; ++l) nfull += full[(size_t)l];
|
||||
rad_note(b, "vision tower: %lld blocks of %lld (%lld heads x %lld), ff %lld, patch %lld x "
|
||||
"%lld x %lld, merge %lld, windows of %lld patches (%lld full attention); "
|
||||
"%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)side, (long long)nfull, (long long)P, (long long)R,
|
||||
(long long)n_embd);
|
||||
}
|
||||
on = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Stage taps, the same protocol as rad_block_sam.h's: RADIANCE_DEBUG_MM_BUFFERS names stages
|
||||
* (comma separated, matched as substrings) and RADIANCE_DEBUG_MM_DUMP's directory receives
|
||||
* tap.<tag>.bf16 -- raw bf16 rows, one file a stage. The copy is issued on the pass's stream
|
||||
* behind the producing op and synced, so it reads that op's output rather than whatever writes
|
||||
* the buffer later (the after-pass dump in core/engine_mm.cpp cannot see intermediates). */
|
||||
inline void muse_tap(RadCtx* c, const char* tag, rad_buf b, int64_t rows, int64_t cols) {
|
||||
static const char* const dir = std::getenv("RADIANCE_DEBUG_MM_DUMP");
|
||||
static const char* const env = std::getenv("RADIANCE_DEBUG_MM_BUFFERS");
|
||||
if (!dir || !*dir || !env || !*env || rows <= 0 || cols <= 0 || rad_rank(c) != 0) return;
|
||||
bool want = false;
|
||||
const size_t tl = std::strlen(tag);
|
||||
for (const char* s = env; *s && !want;) {
|
||||
const char* e = s;
|
||||
while (*e && *e != ',') ++e;
|
||||
const size_t l = (size_t)(e - s);
|
||||
for (size_t i = 0; l && i + l <= tl && !want; ++i)
|
||||
want = std::strncmp(tag + i, s, l) == 0;
|
||||
s = *e ? e + 1 : e;
|
||||
}
|
||||
if (!want) return;
|
||||
void* p = rad_buf_ptr(c, b);
|
||||
if (!p) return;
|
||||
std::vector<uint16_t> h((size_t)(rows * cols));
|
||||
if (rad_memcpy_async(h.data(), p, (size_t)(rows * cols * 2), rad_stream(c)) < 0) return;
|
||||
rad_stream_sync(rad_stream(c));
|
||||
char path[512];
|
||||
std::snprintf(path, sizeof path, "%s/tap.%s.bf16", dir, tag);
|
||||
if (FILE* f = std::fopen(path, "wb")) {
|
||||
std::fwrite(h.data(), sizeof(uint16_t), h.size(), f);
|
||||
std::fclose(f);
|
||||
}
|
||||
}
|
||||
|
||||
inline void MuseTower::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 || !batch->enc_coord || !batch->enc_cu ||
|
||||
!batch->enc_seg_h || !batch->enc_seg_w || !batch->enc_pixels) {
|
||||
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;
|
||||
}
|
||||
/* Windows per frame, from the pass's host grids: the window layers' cu is the per-window
|
||||
* boundaries among permuted rows, `n_win + 1` entries of the order op's output. */
|
||||
int64_t n_win = 0;
|
||||
for (int64_t s = 0; s < S; ++s)
|
||||
n_win += (batch->enc_seg_h[s] + side - 1) / side * ((batch->enc_seg_w[s] + side - 1) / side);
|
||||
if (n_win > P) {
|
||||
rad_step_fail(c, "an encoder pass whose window count exceeds the tower's declared rows");
|
||||
return;
|
||||
}
|
||||
/* Patches, coordinates (planes 0-3: row, column, segment height, segment width, in patches)
|
||||
* and the frame boundaries, staged by the core. The full layers read the frame boundaries
|
||||
* unchanged: the window permutation is within frames, so the boundaries among permuted rows
|
||||
* are these values (the reference passes its cu_seqlens the same way). */
|
||||
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);
|
||||
RadOperand cuw = RAD_B(b_cuw);
|
||||
cuw.rows = n_win + 1;
|
||||
RadOperand pos = RAD_B(b_pos);
|
||||
pos.rows = 2;
|
||||
pos.cols = Pn;
|
||||
|
||||
RAD_ISSUE_N(c, op_patch, Pn, pix, RAD_W(w_patch), brows(b_x, Pn));
|
||||
RAD_ISSUE_N(c, op_pos, Pn, brows(b_x, Pn), RAD_W(w_pos), crd);
|
||||
muse_tap(c, "v.patchpos", b_x, Pn, width);
|
||||
RAD_ISSUE_N(c, op_lpre, Pn, brows(b_x, Pn), RAD_W(lw_pre), RAD_W(lb_pre), brows(b_h, Pn));
|
||||
muse_tap(c, "v.lnpre", b_h, Pn, width);
|
||||
RAD_ISSUE_N(c, op_wo, Pn, crd, cu, brows(b_idx, Pn), brows(b_inv, Pn), pos, cuw);
|
||||
RAD_ISSUE_N(c, op_gidx, Pn, brows(b_h, Pn), brows(b_idx, Pn), brows(b_p, Pn));
|
||||
for (size_t li = 0; li < L.size(); ++li) {
|
||||
const Layer& l = L[li];
|
||||
RAD_ISSUE_N(c, l.ln1, Pn, brows(b_p, Pn), RAD_W(l.n1w), RAD_W(l.n1b), brows(b_h, Pn));
|
||||
l.qkv.step(c, Pn);
|
||||
RAD_ISSUE_N(c, l.rope, Pn, brows(b_qkv, Pn), pos);
|
||||
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),
|
||||
l.full ? cu : cuw, brows(b_att, Pn));
|
||||
l.proj.step(c, Pn);
|
||||
RAD_ISSUE_N(c, l.ln2, Pn, brows(b_p, Pn), RAD_W(l.n2w), RAD_W(l.n2b), brows(b_h, Pn));
|
||||
l.up.step(c, Pn);
|
||||
l.down.step(c, Pn);
|
||||
if (li == 0) muse_tap(c, "v.blk0", b_p, Pn, width);
|
||||
if (li + 1 == L.size()) muse_tap(c, "v.blkL", b_p, Pn, width);
|
||||
}
|
||||
RAD_ISSUE_N(c, op_ginv, Pn, brows(b_p, Pn), brows(b_inv, Pn), brows(b_x, Pn));
|
||||
muse_tap(c, "v.ginv", b_x, Pn, width);
|
||||
/* ln_post over the P patches, then the reference's pixel_shuffle into merged rows. */
|
||||
RAD_ISSUE_N(c, op_lpost, Pn, brows(b_x, Pn), RAD_W(lw_post), RAD_W(lb_post), brows(b_x, Pn));
|
||||
muse_tap(c, "v.lnpost", b_x, Pn, width);
|
||||
RAD_ISSUE_N(c, op_merge, Pn, brows(b_x, Pn), crd, brows(b_mh, Rn));
|
||||
muse_tap(c, "v.merge", b_mh, Rn, mm * width);
|
||||
a1.step(c, Rn);
|
||||
muse_tap(c, "v.fc1", b_m1, Rn, proj_ff);
|
||||
RAD_ISSUE_N(c, op_g1, Rn, brows(b_m1, Rn), brows(b_m2, Rn));
|
||||
a2.step(c, Rn);
|
||||
RAD_ISSUE_N(c, op_g2, Rn, brows(b_m1, Rn), brows(b_m2, Rn));
|
||||
proj.step(c, Rn);
|
||||
muse_tap(c, "v.proj", b_out, Rn, n_embd);
|
||||
RAD_ISSUE_N(c, op_perc, Rn, brows(b_out, Rn), RAD_NONE, brows(b_out, Rn));
|
||||
muse_tap(c, "v.out", b_out, Rn, n_embd);
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_MUSEGLIMMER_VISION_H */
|
||||
+167
-33
@@ -45,13 +45,13 @@
|
||||
* 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.
|
||||
* once per half of the batch, as rad_block_gdn_q.h does.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_PLE_H
|
||||
#define RAD_BLOCK_PLE_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
#include "rad_fp8.h"
|
||||
#include "rad_linear.h"
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
@@ -98,12 +98,24 @@ struct PleLayer {
|
||||
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_weight w_nk = 0, w_nq = 0, w_nc = 0, w_conv = 0;
|
||||
/* The two projections of the gathered embedding, each in the encoding its container stores:
|
||||
* plain bf16 as the checkpoint ships them, or rotated int8 (or a narrower rotated form), which
|
||||
* halves the bytes a pass waits for once the rows are on the card. `a_embd` is their input and
|
||||
* `a_fed` the same planes for the second projection, whose codes the first one's quantiser
|
||||
* wrote. */
|
||||
LinearQ key{}, value{};
|
||||
ActQ a_embd{}, a_fed{};
|
||||
|
||||
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_ids = 0, op_gather = 0, op_embd = 0;
|
||||
rad_op op_gate = 0, op_conv = 0, op_add = 0;
|
||||
/* The draft passes' hint (hint_ids, hint_fetch), where a drafter and `ngram_hint` exist: the
|
||||
* per-slot tails the hash continues from, the hinted ids (host domain, as `ple_ids`) and the
|
||||
* rows fetched for them, which nothing reads. */
|
||||
rad_buf b_tail = 0, b_hint_ids = 0, b_hint_emb = 0;
|
||||
rad_op op_hint_hist = 0, op_hint_round = 0, op_hint_gather = 0;
|
||||
|
||||
int64_t hn() const { return c.hc * g.n_embd; }
|
||||
/* The read-ahead queue's depth in steps: batch.cpp's k_ahead_chunks steps of the following
|
||||
@@ -123,6 +135,14 @@ struct PleLayer {
|
||||
/* 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;
|
||||
/* On a draft head's pass: the ids of each sequence's newest token, first in the pass, and
|
||||
* the fetch of their rows, last in it (see hint_ids()). */
|
||||
void hint_ids(RadCtx* c_, const RadBatch* batch) const;
|
||||
void hint_fetch(RadCtx* c_, const RadBatch* batch) const;
|
||||
bool hints(const RadBatch* batch) const {
|
||||
return op_hint_gather != 0 &&
|
||||
(batch->draft_pass > 1 || (batch->draft_pass < 0 && batch->n_draft_out > 0));
|
||||
}
|
||||
};
|
||||
|
||||
inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& cfg,
|
||||
@@ -178,7 +198,7 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
|
||||
/* 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) or read as that release ships it (its shards under
|
||||
* recipe (data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe) or read as that release ships it (its shards under
|
||||
* one `weight_scale`); 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. */
|
||||
@@ -212,13 +232,12 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
|
||||
/* ---- the projections and the three gains ------------------------------------------------ */
|
||||
/* bf16: the FP8 checkpoint's `modules_to_not_convert` names both projections. */
|
||||
/* bf16 as shipped (the FP8 checkpoint's `modules_to_not_convert` names both projections); a
|
||||
* recipe may store them rotated int8. The name maps come first: the encodings, looked up
|
||||
* through them, say whether the input needs its int8 pair. They are declared below, with the
|
||||
* buffers they read and write. */
|
||||
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},
|
||||
@@ -236,7 +255,7 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
|
||||
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 ||
|
||||
if (!w_table || (!table_bf16 && !w_scale) || !w_mult || !w_vsz || !w_off ||
|
||||
!w_nk || !w_nq || !w_nc || !w_conv) return RAD_E_INVAL;
|
||||
|
||||
/* ---- the two rolling windows ------------------------------------------------------------ */
|
||||
@@ -315,7 +334,7 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
|
||||
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.
|
||||
* rad_block_gdn_q.h; the core's `conv_state_index` is not used.
|
||||
*
|
||||
* ---- the ops, in the order step() issues them ------------------------------------------- */
|
||||
layer_ = layer;
|
||||
@@ -337,22 +356,79 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
|
||||
{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});
|
||||
/* ---- the draft passes' hint. A verify step's rows are the token the last verify chose and
|
||||
* the drafter's proposals, each known a draft pass or more before the verify hashes it,
|
||||
* except the last. Each draft pass hashes its sequences' newest token (`ngram_hint`) and
|
||||
* gathers those rows through the same row source, which for a table on a drive reads them
|
||||
* into its row cache; the verify step's gather then waits for the last proposal's rows
|
||||
* only. All three ops or none: without a drafter, or where no library hashes the hint,
|
||||
* nothing is declared and the verify step reads every row itself, as before. */
|
||||
if (g.max_spec > 0 && rad_op_declared(b, "ngram_hint")) {
|
||||
const int64_t ctx = c.ngram - 1;
|
||||
b_tail = decl_b(b, nm.f("ple_hint_tail"), RAD_I32, {g.max_seqs, 2 * ctx}, RAD_BUF_PERSIST);
|
||||
RadBufDecl hi{};
|
||||
hi.dtype = RAD_I32; hi.rank = 2;
|
||||
hi.shape[0] = g.max_seqs; hi.shape[1] = c.heads;
|
||||
hi.kind = RAD_BUF_PERSIST; hi.domain = RAD_DOMAIN_HOST;
|
||||
b_hint_ids = rad_decl_buffer(b, nm.f("ple_hint_ids"), &hi);
|
||||
/* PERSIST although nothing reads it: a transient's bytes are shared by declared op
|
||||
* order, and the fetch runs on the host while the draft pass's other buffers are live. */
|
||||
RadBufDecl he{};
|
||||
he.dtype = g.act_dtype; he.rank = 2;
|
||||
he.shape[0] = g.max_seqs; he.shape[1] = c.embed_dim;
|
||||
he.kind = RAD_BUF_PERSIST; he.domain = RAD_DOMAIN_HOST;
|
||||
b_hint_emb = rad_decl_buffer(b, nm.f("ple_hint_emb"), &he);
|
||||
if (!b_tail || !b_hint_ids || !b_hint_emb) return RAD_E_INVAL;
|
||||
for (const int hist : { 1, 0 })
|
||||
(hist ? op_hint_hist : op_hint_round) =
|
||||
rw(b, RAD_OP(b, "ngram_hint",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("heads", c.heads),
|
||||
RAD_INT("ngram", c.ngram), RAD_INT("eos", c.eos),
|
||||
RAD_INT("hist", hist)),
|
||||
RAD_WEIGHTS(w_mult, w_vsz, w_off)),
|
||||
{b_tail}, {b_tail, b_hint_ids});
|
||||
const rad_weight wt[2] = { w_table, w_scale };
|
||||
op_hint_gather = rw(b, RAD_OP(b, "embed_lookup_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs * c.heads),
|
||||
RAD_INT("n_embd", HD), RAD_INT("n_vocab", c.rows),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
wt, table_bf16 ? 1 : 2),
|
||||
{b_hint_ids}, {b_hint_emb});
|
||||
if (!op_hint_hist || !op_hint_round || !op_hint_gather)
|
||||
op_hint_hist = op_hint_round = op_hint_gather = 0;
|
||||
}
|
||||
|
||||
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});
|
||||
op_embd = cast_op(b, g.max_tok, c.embed_dim, g.dtype, g.dtype, b_emb, b_embd);
|
||||
|
||||
/* The projections. An int8 one reads the embedding's int8 codes at its own scale group; the
|
||||
* first such quantises the bf16 plane and a second reads those codes, so two int8 projections
|
||||
* must agree in rotation and group (LinearQ refuses the pair otherwise). */
|
||||
{
|
||||
const char* kb = nm.f("blk.%d.ple_key", layer);
|
||||
const char* vb = nm.f("blk.%d.ple_value", layer);
|
||||
RadEncoding ke{}, ve{};
|
||||
const bool kk = weight_enc(b, nm.f("%s.weight", kb), &ke);
|
||||
const bool vk = weight_enc(b, nm.f("%s.weight", vb), &ve);
|
||||
const bool k8 = !g.w_bf16 && kk && (linear_is_w8(ke) || linear_is_w8h(ke));
|
||||
const bool v8 = !g.w_bf16 && vk && (linear_is_w8(ve) || linear_is_w8h(ve));
|
||||
a_embd.x = b_embd;
|
||||
if (k8 || v8)
|
||||
RAD_ARCH_TRY(a_embd.declare_qs(b, nm, g, "ple_emb_dev", c.embed_dim, 0, true, false,
|
||||
linear_w8h_group(k8 ? ke : ve)));
|
||||
a_fed = a_embd;
|
||||
if (k8 && v8) {
|
||||
a_fed.q8_fed = true;
|
||||
a_fed.q8_rot = linear_is_w8h(ke);
|
||||
}
|
||||
key.mapped = value.mapped = true;
|
||||
/* Anything but an int8 form is the plain bf16 GEMM, in a quantised model too. */
|
||||
Geom gb = g;
|
||||
gb.w_bf16 = true;
|
||||
RAD_ARCH_TRY(key.declare(b, nm, k8 ? g : gb, kb, HN, c.embed_dim, RAD_SHARD_NONE,
|
||||
grp_model(), { src.key_proj }, a_embd, b_k));
|
||||
RAD_ARCH_TRY(value.declare(b, nm, v8 ? g : gb, vb, g.n_embd, c.embed_dim, RAD_SHARD_NONE,
|
||||
grp_model(), { src.value_proj }, a_fed, b_v));
|
||||
}
|
||||
|
||||
/* `q` is the incoming stream, un-normed; the op applies all three norms because the third is
|
||||
* over bytes it writes. */
|
||||
@@ -378,14 +454,14 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h, b_out}, {w.h});
|
||||
|
||||
if (!op_ids || !op_gather || !op_embd || !op_key || !op_value || !op_gate || !op_conv ||
|
||||
if (!op_ids || !op_gather || !op_embd || !key.op || !value.op || !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.
|
||||
* rad_block_gdn_q.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
|
||||
@@ -421,7 +497,24 @@ inline void PleLayer::ids(RadCtx* c_, const RadBatch* batch) const {
|
||||
* 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)
|
||||
/* A checkpoint inside the step (RadBatch::ckpt_cut): the rows before it, the window's
|
||||
* snapshot, then the rest with the ahead rows, each as a chunk of those rows hashes them. */
|
||||
const int64_t ck = batch->ckpt_cut;
|
||||
if (P == 1 && D == 0 && ck > 0 && ck < T && batch->ckpt_cu) {
|
||||
for (int64_t p = 0; p < 2; ++p) {
|
||||
const int64_t r0 = p == 0 ? 0 : ck, n = p == 0 ? ck : T - ck;
|
||||
RAD_ISSUE_N(c_, op_ids, n,
|
||||
praw(batch->token_ids, RAD_I32, T + A), kv_cache(kv_tok, layer_),
|
||||
praw(batch->ckpt_cu + p, RAD_I32, 2),
|
||||
RAD_W(w_mult), RAD_W(w_vsz), RAD_W(w_off),
|
||||
praw(tk_idx, RAD_I32, 1),
|
||||
praw(p == 0 ? batch->ctx_lens : batch->positions + r0, RAD_I32, 1),
|
||||
RAD_NONE,
|
||||
brows(b_ids, T),
|
||||
p == 1 && A > 0 ? brow_slice(b_ids, T, A, c.heads) : RAD_NONE);
|
||||
if (p == 0) rad_ckpt_snap(c_, kv_tok, layer_);
|
||||
}
|
||||
} else 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),
|
||||
@@ -433,6 +526,33 @@ inline void PleLayer::ids(RadCtx* c_, const RadBatch* batch) const {
|
||||
A > 0 ? brow_slice(b_ids, T, A, c.heads) : RAD_NONE);
|
||||
}
|
||||
|
||||
/* The hint of a draft head's pass. The history pass ends at the token the verify chose and each
|
||||
* later round reads the proposal before it (RadBatch::draft_pass), so the pass's newest token per
|
||||
* sequence is one the next verify step runs. hint_ids() hashes it first in the pass, so the ids
|
||||
* are in host memory as the pass starts; hint_fetch() goes last, where the host has issued the
|
||||
* whole pass and only waits for that one kernel, and the rows it reads arrive while the card
|
||||
* drafts. A history pass that drafts nothing gets neither. */
|
||||
inline void PleLayer::hint_ids(RadCtx* c_, const RadBatch* batch) const {
|
||||
if (!hints(batch)) return;
|
||||
const int64_t T = batch->n_tok, S = batch->n_seq;
|
||||
const RadKVGroupBatch* tk = kv_batch(batch, kv_tok);
|
||||
const int32_t* tk_idx = tk ? tk->state_index : nullptr;
|
||||
RAD_ISSUE_N(c_, batch->draft_pass < 0 ? op_hint_hist : op_hint_round, S,
|
||||
praw(batch->token_ids, RAD_I32, T), praw(batch->positions, RAD_I32, T),
|
||||
praw(batch->cu_seqlens, RAD_I32, S + 1),
|
||||
RAD_W(w_mult), RAD_W(w_vsz), RAD_W(w_off),
|
||||
tk_idx ? praw(tk_idx, RAD_I32, S) : RAD_NONE,
|
||||
RAD_B(b_tail), brows(b_hint_ids, S));
|
||||
}
|
||||
|
||||
inline void PleLayer::hint_fetch(RadCtx* c_, const RadBatch* batch) const {
|
||||
if (!hints(batch)) return;
|
||||
const int64_t S = batch->n_seq;
|
||||
RAD_ISSUE_N(c_, op_hint_gather, S * c.heads,
|
||||
brows(b_hint_ids, S), RAD_W(w_table), table_bf16 ? RAD_NONE : RAD_W(w_scale),
|
||||
brows(b_hint_emb, S), 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;
|
||||
@@ -454,8 +574,8 @@ inline void PleLayer::step(RadCtx* c_, const RadBatch* batch) const {
|
||||
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));
|
||||
key.step(c_, a_embd, b_k, T, 0, T);
|
||||
value.step(c_, a_fed, b_v, T, 0, T);
|
||||
|
||||
RAD_ISSUE_N(c_, op_gate, T,
|
||||
brows(b_k, T), brows(w.h, T), brows(b_v, T),
|
||||
@@ -470,7 +590,21 @@ inline void PleLayer::step(RadCtx* c_, const RadBatch* batch) const {
|
||||
praw(batch->ctx_lens, RAD_I32, D),
|
||||
praw(batch->num_accepted, RAD_I32, D),
|
||||
brows(b_out, DT));
|
||||
if (P > 0)
|
||||
const int64_t ck = batch->ckpt_cut;
|
||||
if (P == 1 && D == 0 && ck > 0 && ck < T && batch->ckpt_cu) {
|
||||
/* A checkpoint inside the step: the window over the rows before it, its snapshot, then
|
||||
* the rest (as ids()). */
|
||||
for (int64_t p = 0; p < 2; ++p) {
|
||||
RAD_ISSUE_N(c_, op_conv, p == 0 ? ck : T - ck,
|
||||
brows(b_gvn, T), RAD_W(w_conv), kv_cache(kv_conv, layer_),
|
||||
praw(batch->ckpt_cu + p, RAD_I32, 2), brows(b_gv, T),
|
||||
praw(cv_idx, RAD_I32, 1),
|
||||
praw(p == 0 ? batch->ctx_lens : batch->positions + ck, RAD_I32, 1),
|
||||
RAD_NONE,
|
||||
brows(b_out, T));
|
||||
if (p == 0) rad_ckpt_snap(c_, kv_conv, layer_);
|
||||
}
|
||||
} else 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),
|
||||
|
||||
+30
-31
@@ -82,20 +82,20 @@ struct VisionTower {
|
||||
* and leaves `on` false, for a model whose config names a tower its weights may not have. */
|
||||
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
|
||||
int64_t model_embd, int first_group, bool deepstack = false,
|
||||
bool gate_weights = false);
|
||||
bool gate_weights = false, const char* prefix = "model.visual");
|
||||
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,
|
||||
bool gate_weights) {
|
||||
bool gate_weights, const char* prefix) {
|
||||
on = false;
|
||||
if (!present(m) || ctx->max_enc_patches <= 0) return RAD_OK;
|
||||
|
||||
/* Whether the stem is there: its map first, then its encoding, which convert answers from the
|
||||
* checkpoint and load from the container alike. A map left behind is inert. */
|
||||
if (gate_weights) {
|
||||
if (map_copy(b, nm.f("v.patch.weight"), nm.ckpt("model.visual.patch_embed.proj.weight")) < 0)
|
||||
if (map_copy(b, nm.f("v.patch.weight"), nm.ckpt("%s.patch_embed.proj.weight", prefix)) < 0)
|
||||
return RAD_E_INVAL;
|
||||
RadEncoding enc;
|
||||
if (rad_weight_encoding(b, nm.f("v.patch.weight"), &enc, nullptr, nullptr) != RAD_OK) {
|
||||
@@ -194,46 +194,45 @@ inline int VisionTower::declare(RadBuilder* b, const RadModelMeta* m, const RadB
|
||||
w_patch = gate_weights
|
||||
? decl_w(b, nm.f("v.patch.weight"), RAD_BF16, { width, patch_dim },
|
||||
RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, grp_model())
|
||||
: bw(nm.f("v.patch.weight"), nm.ckpt("model.visual.patch_embed.proj.weight"),
|
||||
: bw(nm.f("v.patch.weight"), nm.ckpt("%s.patch_embed.proj.weight", prefix),
|
||||
RAD_BF16, { width, patch_dim }, grp_model());
|
||||
b_patch = bw(nm.f("v.patch.bias"), nm.ckpt("model.visual.patch_embed.proj.bias"),
|
||||
b_patch = bw(nm.f("v.patch.bias"), nm.ckpt("%s.patch_embed.proj.bias", prefix),
|
||||
RAD_BF16, { width }, grp_model());
|
||||
w_pos = bw(nm.f("v.pos.weight"), nm.ckpt("model.visual.pos_embed.weight"),
|
||||
w_pos = bw(nm.f("v.pos.weight"), nm.ckpt("%s.pos_embed.weight", prefix),
|
||||
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);
|
||||
l.n1w = bw(nm.f("v.blk.%d.norm1.weight", li), nm.ckpt("%s.blocks.%d.norm1.weight", prefix, li), RAD_BF16, { width }, g);
|
||||
l.n1b = bw(nm.f("v.blk.%d.norm1.bias", li), nm.ckpt("%s.blocks.%d.norm1.bias", prefix, li), RAD_BF16, { width }, g);
|
||||
l.qkv_w = bw(nm.f("v.blk.%d.qkv.weight", li), nm.ckpt("%s.blocks.%d.attn.qkv.weight", prefix, li), RAD_BF16, { 3 * width, width }, g);
|
||||
l.qkv_b = bw(nm.f("v.blk.%d.qkv.bias", li), nm.ckpt("%s.blocks.%d.attn.qkv.bias", prefix, li), RAD_BF16, { 3 * width }, g);
|
||||
l.out_w = bw(nm.f("v.blk.%d.proj.weight", li), nm.ckpt("%s.blocks.%d.attn.proj.weight", prefix, li), RAD_BF16, { width, width }, g);
|
||||
l.out_b = bw(nm.f("v.blk.%d.proj.bias", li), nm.ckpt("%s.blocks.%d.attn.proj.bias", prefix, li), RAD_BF16, { width }, g);
|
||||
l.n2w = bw(nm.f("v.blk.%d.norm2.weight", li), nm.ckpt("%s.blocks.%d.norm2.weight", prefix, li), RAD_BF16, { width }, g);
|
||||
l.n2b = bw(nm.f("v.blk.%d.norm2.bias", li), nm.ckpt("%s.blocks.%d.norm2.bias", prefix, li), RAD_BF16, { width }, g);
|
||||
l.up_w = bw(nm.f("v.blk.%d.fc1.weight", li), nm.ckpt("%s.blocks.%d.mlp.linear_fc1.weight", prefix, li), RAD_BF16, { ff, width }, g);
|
||||
l.up_b = bw(nm.f("v.blk.%d.fc1.bias", li), nm.ckpt("%s.blocks.%d.mlp.linear_fc1.bias", prefix, li), RAD_BF16, { ff }, g);
|
||||
l.down_w = bw(nm.f("v.blk.%d.fc2.weight", li), nm.ckpt("%s.blocks.%d.mlp.linear_fc2.weight", prefix, li), RAD_BF16, { width, ff }, g);
|
||||
l.down_b = bw(nm.f("v.blk.%d.fc2.bias", li), nm.ckpt("%s.blocks.%d.mlp.linear_fc2.bias", prefix, 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());
|
||||
mn_w = bw(nm.f("v.merger.norm.weight"), nm.ckpt("%s.merger.norm.weight", prefix), RAD_BF16, { width }, grp_model());
|
||||
mn_b = bw(nm.f("v.merger.norm.bias"), nm.ckpt("%s.merger.norm.bias", prefix), RAD_BF16, { width }, grp_model());
|
||||
m1_w = bw(nm.f("v.merger.fc1.weight"), nm.ckpt("%s.merger.linear_fc1.weight", prefix), RAD_BF16, { mm * width, mm * width }, grp_model());
|
||||
m1_b = bw(nm.f("v.merger.fc1.bias"), nm.ckpt("%s.merger.linear_fc1.bias", prefix), RAD_BF16, { mm * width }, grp_model());
|
||||
m2_w = bw(nm.f("v.merger.fc2.weight"), nm.ckpt("%s.merger.linear_fc2.weight", prefix), RAD_BF16, { n_embd, mm * width }, grp_model());
|
||||
m2_b = bw(nm.f("v.merger.fc2.bias"), nm.ckpt("%s.merger.linear_fc2.bias", prefix), 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());
|
||||
ds_nw[t] = bw(nm.f("v.ds.%d.norm.weight", t), nm.ckpt("%s.deepstack_merger_list.%d.norm.weight", prefix, t), RAD_BF16, { mm * width }, grp_model());
|
||||
ds_nb[t] = bw(nm.f("v.ds.%d.norm.bias", t), nm.ckpt("%s.deepstack_merger_list.%d.norm.bias", prefix, t), RAD_BF16, { mm * width }, grp_model());
|
||||
ds_1w[t] = bw(nm.f("v.ds.%d.fc1.weight", t), nm.ckpt("%s.deepstack_merger_list.%d.linear_fc1.weight", prefix, t), RAD_BF16, { mm * width, mm * width }, grp_model());
|
||||
ds_1b[t] = bw(nm.f("v.ds.%d.fc1.bias", t), nm.ckpt("%s.deepstack_merger_list.%d.linear_fc1.bias", prefix, t), RAD_BF16, { mm * width }, grp_model());
|
||||
ds_2w[t] = bw(nm.f("v.ds.%d.fc2.weight", t), nm.ckpt("%s.deepstack_merger_list.%d.linear_fc2.weight", prefix, t), RAD_BF16, { n_embd, mm * width }, grp_model());
|
||||
ds_2b[t] = bw(nm.f("v.ds.%d.fc2.bias", t), nm.ckpt("%s.deepstack_merger_list.%d.linear_fc2.bias", prefix, 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;
|
||||
}
|
||||
|
||||
@@ -25,7 +25,13 @@
|
||||
* safetensors file per input, <dir>/<stem>.safetensors, holding `hessian_upper`, f32
|
||||
* [k * (k + 1) / 2], row i's entries k2 = i .. k-1 after row i-1's, and metadata naming `k`, the
|
||||
* rows summed and the checkpoint linears that read the input. H is the raw sum; divide by `rows`
|
||||
* for the mean second moment. */
|
||||
* for the mean second moment.
|
||||
*
|
||||
* An int8 trunk (site_i8, one rank only) is recorded from the codes and scales its GEMMs actually
|
||||
* read, so H includes what the model's own quantisation did to the input -- the input a quantised
|
||||
* model feeds each layer, for GPTQ against the error it inherits. Codes a rotating producer wrote
|
||||
* are in the rotated domain; the file's metadata then names it (`domain`: the Hadamard width), as
|
||||
* RADGRAM2's header does, and the reader converts. */
|
||||
#pragma once
|
||||
|
||||
#include <arch/rad_arch.h>
|
||||
@@ -52,6 +58,8 @@ struct CalibFull {
|
||||
rad_op op_gather = 0; /* the columns of every rank into `gathered`; 0 when replicated */
|
||||
rad_op op_gram = 0; /* declared on the owner only */
|
||||
bool owner = false;
|
||||
rad_buf q8 = 0, s8 = 0; /* site_i8: the int8 codes and their f32 (row, 128) scales */
|
||||
uint32_t domain = 0; /* site_i8: the codes' rotation width, 0 for none */
|
||||
std::vector<float> tri; /* the owner's accumulator, upper triangle packed */
|
||||
};
|
||||
|
||||
@@ -156,6 +164,32 @@ struct CalibFull {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* One input of layer `layer` from an int8 trunk's codes `q8` and scales `s8` (see the file
|
||||
* comment): the whole input on one rank, `domain` the Hadamard width the codes were rotated by
|
||||
* (0 for none). */
|
||||
int site_i8(RadBuilder* b, const Geom& g, int64_t layer, std::string stem, std::string linears,
|
||||
rad_buf q8, rad_buf s8, int64_t K, uint32_t domain) {
|
||||
if (world > 1 || !q8 || !s8 || K > kmax) return RAD_E_INVAL;
|
||||
Site s;
|
||||
s.stem = std::move(stem);
|
||||
s.linears = std::move(linears);
|
||||
s.K = s.k_local = K;
|
||||
s.owner = true;
|
||||
s.q8 = q8;
|
||||
s.s8 = s8;
|
||||
s.domain = domain;
|
||||
(void)layer;
|
||||
s.op_gram = rw(b, RAD_OP(b, "gram_accum",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", K),
|
||||
RAD_INT("group", 128), RAD_STR("dtype", "i8a8"),
|
||||
RAD_INT("upper", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ q8, s8, scratch }, { scratch });
|
||||
if (!s.op_gram) return RAD_E_INVAL;
|
||||
sites.push_back(std::move(s));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Site `i` over a step's T rows: gather (every rank), then on the owner the Gram into the
|
||||
* scratch, copied to a free square, the scratch zeroed, and the square handed to the worker. */
|
||||
void tap(RadCtx* c, size_t i, int64_t T) {
|
||||
@@ -186,7 +220,10 @@ struct CalibFull {
|
||||
}
|
||||
}
|
||||
const int64_t K = s.K;
|
||||
RAD_ISSUE_N(c, s.op_gram, T, a, RAD_NONE, praw2(dev, RAD_F32, K, K));
|
||||
if (s.q8)
|
||||
RAD_ISSUE_N(c, s.op_gram, T, brows(s.q8, T), brows(s.s8, T), praw2(dev, RAD_F32, K, K));
|
||||
else
|
||||
RAD_ISSUE_N(c, s.op_gram, T, a, RAD_NONE, praw2(dev, RAD_F32, K, K));
|
||||
/* `upper` 1 writes no entry below the diagonal, so only the upper triangle comes back:
|
||||
* band by band of kBand rows, each from its first row's diagonal on, about half the
|
||||
* square's bytes. The link is what a step's taps wait on, 25 GB a step on each rank of
|
||||
@@ -317,7 +354,9 @@ private:
|
||||
const uint64_t bytes = (uint64_t)s.tri.size() * 4;
|
||||
std::string hdr = "{\"__metadata__\":{\"k\":\"" + std::to_string(s.K) + "\",\"rows\":\"" +
|
||||
std::to_string(seen) + "\",\"layout\":\"upper triangle, row-major, packed\","
|
||||
"\"linears\":\"" + s.linears + "\"},\"hessian_upper\":{\"dtype\":\"F32\","
|
||||
"\"linears\":\"" + s.linears + "\"" +
|
||||
(s.domain ? ",\"domain\":\"" + std::to_string(s.domain) + "\"" : std::string()) +
|
||||
"},\"hessian_upper\":{\"dtype\":\"F32\","
|
||||
"\"shape\":[" + std::to_string(s.tri.size()) + "],\"data_offsets\":[0," +
|
||||
std::to_string(bytes) + "]}}";
|
||||
while (hdr.size() % 8) hdr += ' ';
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
/* rad_expert_split.h -- how many routed experts each rank holds, for a model that gives each rank
|
||||
* whole experts (expert parallelism: MoeQ::Config::n_expert and expert_base).
|
||||
*
|
||||
* By default every rank holds n_expert / world. `list` (RadBuildCtx::expert_split, the
|
||||
* `expert-split` setting) gives every rank's count instead, comma-separated in rank order
|
||||
* ("108,84,108,84"): whole experts, in steps of `step` (2 where the block's quantised GEMM takes two
|
||||
* tables by parity, which is what MoeQ does), summing to the model's. The router is replicated
|
||||
* and each rank sorts only the slots in its own range, so the ranks need not hold equal runs.
|
||||
*
|
||||
* It is for a machine whose cards are not on equal links: a rank given few enough experts holds
|
||||
* all of them in VRAM, so none is streamed to it over its link, and the ranks on the faster links
|
||||
* take the rest. What the counts should be depends on the links and on what a card holds, so the
|
||||
* deployment states them.
|
||||
*
|
||||
* A list that does not fit the model or the world is refused, not ignored: the function returns
|
||||
* false with *given true, and the caller stops the start, naming the list. A rank at or past
|
||||
* `world` (a shape probe) takes rank 0's run. */
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <vector>
|
||||
|
||||
inline bool rad_expert_split(int64_t n_expert, int world, int rank, int step, const char* list,
|
||||
int64_t* n, int64_t* base, bool* given) {
|
||||
*given = false;
|
||||
if (step < 1) step = 1;
|
||||
if (rank < 0 || rank >= world) rank = 0;
|
||||
if (!list || !*list || world <= 1) {
|
||||
*n = world > 0 ? n_expert / world : n_expert;
|
||||
*base = rank * *n;
|
||||
return world <= 1 || (n_expert % world == 0 && *n % step == 0);
|
||||
}
|
||||
*given = true;
|
||||
std::vector<int64_t> v;
|
||||
for (const char* p = list; *p;) {
|
||||
char* end = nullptr;
|
||||
const long long x = std::strtoll(p, &end, 10);
|
||||
if (end == p) return false;
|
||||
v.push_back(x);
|
||||
if (*end && *end != ',') return false;
|
||||
p = *end == ',' ? end + 1 : end;
|
||||
}
|
||||
int64_t sum = 0;
|
||||
for (int64_t x : v) {
|
||||
if (x < step || x % step) return false;
|
||||
sum += x;
|
||||
}
|
||||
if ((int)v.size() != world || sum != n_expert) return false;
|
||||
*n = v[(size_t)rank];
|
||||
*base = 0;
|
||||
for (int r = 0; r < rank; ++r) *base += v[(size_t)r];
|
||||
return true;
|
||||
}
|
||||
@@ -30,8 +30,8 @@
|
||||
*
|
||||
* ============================== 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.
|
||||
* 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, 73.5 at 5376), and the drafter was trained through the target's embedding
|
||||
@@ -90,7 +90,7 @@
|
||||
#define RAD_GEMMA4_DFLASH_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
#include "rad_fp8.h"
|
||||
#include "rad_linear.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
@@ -133,17 +133,17 @@ 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;
|
||||
sc->block[0] == RAD_SCALE_GROUP && sc->block[1] == RAD_SCALE_GROUP;
|
||||
}
|
||||
|
||||
/* Int8 on the w8a8 grid: i8 codes and an f16 scale per [1 x 128], no transform (a recipe's `rtn
|
||||
* codes=i8 group=128 scale=f16 clamp=sym`), what gemm_nt_q reads at w8a8. Not rad_fp8.h's
|
||||
* codes=i8 group=128 scale=f16 clamp=sym`), what gemm_nt_q reads at w8a8. Not rad_linear.h's
|
||||
* linear_is_w8, which is the i8a8 grid's bf16 scale over a per-(row, 128) activation. */
|
||||
inline bool linear_w8a8(const RadEncoding& e) {
|
||||
if (!rad_enc_is(&e, "affine") || e.n_planes != 2 || e.transform[0]) return false;
|
||||
const RadEncPlane* sc = rad_enc_plane(&e, "scale");
|
||||
return e.plane[0].dtype == RAD_I8 && e.plane[0].block[1] == 1 && sc && sc->dtype == RAD_F16 &&
|
||||
sc->block[0] == 1 && sc->block[1] == RAD_FP8_BLOCK;
|
||||
sc->block[0] == 1 && sc->block[1] == RAD_SCALE_GROUP;
|
||||
}
|
||||
|
||||
/* Which drafter the container carries under `draft.`: 1 for DFlash (v1), 2 for DFlash2 (which is
|
||||
@@ -204,7 +204,7 @@ inline bool dflash2_probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
* 58. Id 0 would be the embedding, which no layer outputs, and is refused. */
|
||||
inline int dflash2_taps(const RadModelMeta* meta, const RadBuildCtx* ctx, int64_t n_layer, int* out,
|
||||
int max) {
|
||||
if (ctx->max_spec <= 0 || dflash_kind(meta) != 2) return 0;
|
||||
if (!rad_ctx_draft_head(ctx) || dflash_kind(meta) != 2) return 0;
|
||||
const char* aux = rad_meta_gets(meta, "draft.aux_hidden_state_layer_ids", nullptr);
|
||||
int n = 0;
|
||||
if (aux) {
|
||||
@@ -317,13 +317,13 @@ struct Dflash1 {
|
||||
};
|
||||
|
||||
/* One of the drafter's linears, in the grid the container holds it (see the file header): block
|
||||
* fp8 or MXFP4 through DenseFP8, or int8 at w8a8 -- codes and an f16 scale per [1 x 128] as two
|
||||
* fp8 or MXFP4 through DenseQ, or int8 at w8a8 -- codes and an f16 scale per [1 x 128] as two
|
||||
* views of one stored weight, the w4a8 grid's layout at twice the radix. `w` and `s` are the
|
||||
* GEMM's two weight operands either way, and `bref()` its trailing one. */
|
||||
struct Lin {
|
||||
rad_weight w = 0, s = 0;
|
||||
bool i8 = false;
|
||||
DenseFP8 f{};
|
||||
DenseQ f{};
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const char* base, int64_t N, int64_t K, int access,
|
||||
int shard, RadWeightGroup grp, std::initializer_list<const char*> src,
|
||||
@@ -334,7 +334,7 @@ struct Dflash1 {
|
||||
if (!i8) return f.gemm(b, hi, N, K, reads, writes);
|
||||
return rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "w8a8")),
|
||||
RAD_INT("group", RAD_SCALE_GROUP), RAD_STR("dtype", "w8a8")),
|
||||
RAD_WEIGHTS(w, s)),
|
||||
reads, writes);
|
||||
}
|
||||
@@ -419,7 +419,7 @@ private:
|
||||
void decl_pair(RadBuilder* b, Names& nm, const char* q, const char* s, int64_t rows, int64_t n,
|
||||
rad_buf* qb, rad_buf* sb) const {
|
||||
*qb = decl_b(b, nm.f("%s", q), i8 ? RAD_I8 : RAD_F8E4M3, {rows, n});
|
||||
*sb = decl_b(b, nm.f("%s", s), RAD_F32, {rows, i8 ? 1 : fp8_blocks(n)});
|
||||
*sb = decl_b(b, nm.f("%s", s), RAD_F32, {rows, i8 ? 1 : scale_groups(n)});
|
||||
}
|
||||
/* The standalone quantiser of an n-wide activation, in the grid: `quant_act_fp8` with a scale
|
||||
* per 128 columns, or `quant_act_i8` with one per row, whose `group` only sizes the optional
|
||||
@@ -428,7 +428,7 @@ private:
|
||||
rad_buf s) const {
|
||||
return rw(b, RAD_OP(b, i8 ? "quant_act_i8" : "quant_act_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_INT("group", RAD_SCALE_GROUP), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{x}, {q, s});
|
||||
}
|
||||
@@ -500,7 +500,7 @@ inline int Dflash1::Lin::declare(RadBuilder* b, Names& nm, const char* base, int
|
||||
std::initializer_list<const char*> src,
|
||||
std::initializer_list<int64_t> row_parts) {
|
||||
/* The name map once, before the question it answers: a COPY map declared twice is refused and
|
||||
* a CONCAT one extended (rad_builder.cpp), so DenseFP8 is told the map is made. */
|
||||
* a CONCAT one extended (rad_builder.cpp), so DenseQ is told the map is made. */
|
||||
const char* wn = nm.f("%s.weight", base);
|
||||
RAD_ARCH_TRY(map_linear(b, wn, src));
|
||||
RadEncoding enc{};
|
||||
@@ -513,10 +513,10 @@ inline int Dflash1::Lin::declare(RadBuilder* b, Names& nm, const char* base, int
|
||||
}
|
||||
/* w8a8: rows in 16s (the fragment's tile) and K in whole 128-column scale groups. The scale
|
||||
* plane has the weight's rows, so it takes the weight's row parts as they are. */
|
||||
if (N % 16 || K % RAD_FP8_BLOCK) {
|
||||
if (N % 16 || K % RAD_SCALE_GROUP) {
|
||||
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an int8 weight takes rows in 16s "
|
||||
"and K in whole %d-column scale groups.\n",
|
||||
base, (long long)N, (long long)K, RAD_FP8_BLOCK);
|
||||
base, (long long)N, (long long)K, RAD_SCALE_GROUP);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
int64_t p[RAD_MAX_ROW_PARTS] = {0};
|
||||
@@ -531,7 +531,7 @@ inline int Dflash1::Lin::declare(RadBuilder* b, Names& nm, const char* base, int
|
||||
p[np++] = q;
|
||||
}
|
||||
w = decl_view(b, wn, nullptr, "codes", RAD_I8, { N, K }, access, shard, grp, p, np);
|
||||
s = decl_view(b, nm.f("%s.scale", base), wn, "scale", RAD_F16, { N, K / RAD_FP8_BLOCK },
|
||||
s = decl_view(b, nm.f("%s.scale", base), wn, "scale", RAD_F16, { N, K / RAD_SCALE_GROUP },
|
||||
access, shard, grp, p, np);
|
||||
return w && s ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
@@ -540,7 +540,7 @@ inline int Dflash1::Lin::declare(RadBuilder* b, Names& nm, const char* base, int
|
||||
|
||||
inline int Dflash1::taps(const RadModelMeta* meta, const RadBuildCtx* ctx, int64_t n_layer,
|
||||
int* out, int max) {
|
||||
if (ctx->max_spec <= 0) return 0;
|
||||
if (!rad_ctx_draft_head(ctx)) return 0;
|
||||
const int kind = dflash_kind(meta);
|
||||
if (kind == 0) return 0;
|
||||
if (kind == 2) {
|
||||
@@ -875,11 +875,7 @@ inline int Dflash1::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
* buffer planner's liveness, and declared after the layers the copies' buffers would look born
|
||||
* after the last layer's input and free to share its bytes. */
|
||||
auto rep_op = [&](int64_t rows, rad_buf src, rad_buf dst) {
|
||||
return rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", g.head_dim),
|
||||
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{src}, {dst});
|
||||
return cast_op(b, rows, g.head_dim, g.dtype, g.dtype, src, dst);
|
||||
};
|
||||
|
||||
/* ---------------------------------------------------------------- the context pass */
|
||||
@@ -930,12 +926,7 @@ inline int Dflash1::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
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_embed_ar = decl_all_reduce_exact(b, g, w.x, g.n_embd, qrows, g.dtype);
|
||||
op_qh = decl_quant(b, qrows, g.n_embd, w.h, w.hq, w.hs);
|
||||
op_qat = decl_quant(b, qrows, qd, w.attn, w.atq, w.ats);
|
||||
op_qff = decl_quant(b, qrows, g.n_ff, w.ffn, w.ffq, w.ffs);
|
||||
@@ -956,7 +947,7 @@ inline int Dflash1::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
RAD_WEIGHTS(gain))
|
||||
: 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_F64("eps", g.eps), RAD_INT("group", RAD_SCALE_GROUP),
|
||||
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});
|
||||
@@ -1003,11 +994,11 @@ inline int Dflash1::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
* rule, band included). E4M3 grid only: libr4d's fold is fp8a8. */
|
||||
{
|
||||
const int64_t hi = qrows < 64 ? qrows : 64;
|
||||
if (hi > 0 && !i8 && !w_gu[i].f.mx) {
|
||||
if (hi > 0 && !i8) {
|
||||
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_INT("group", RAD_SCALE_GROUP),
|
||||
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});
|
||||
@@ -1043,13 +1034,7 @@ inline int Dflash1::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
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_ar = decl_all_reduce(b, g, w.h, g.n_embd, qrows, g.dtype);
|
||||
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)),
|
||||
@@ -1086,10 +1071,10 @@ inline int Dflash1::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
const bool head_i8 = known && linear_w8a8(he);
|
||||
q_head = head_fp8 || head_i8;
|
||||
if (q_head) {
|
||||
if (g.n_vocab % RAD_FP8_BLOCK || g.n_embd % RAD_FP8_BLOCK) {
|
||||
if (g.n_vocab % RAD_SCALE_GROUP || g.n_embd % RAD_SCALE_GROUP) {
|
||||
fprintf(stderr, "radiance: gemma4: the 8-bit 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);
|
||||
(long long)g.n_vocab, (long long)g.n_embd, RAD_SCALE_GROUP);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const int shard = g.world > 1 ? RAD_SHARD_ROW : RAD_SHARD_NONE;
|
||||
@@ -1098,20 +1083,20 @@ inline int Dflash1::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
{ g.n_vocab, g.n_embd }, RAD_ACCESS_PER_TOKEN, shard, grp_model());
|
||||
w_dh.s = head_i8
|
||||
? decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale", RAD_F16,
|
||||
{ g.n_vocab, g.n_embd / RAD_FP8_BLOCK }, RAD_ACCESS_PER_TOKEN, shard,
|
||||
{ g.n_vocab, g.n_embd / RAD_SCALE_GROUP }, RAD_ACCESS_PER_TOKEN, shard,
|
||||
grp_model())
|
||||
: 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,
|
||||
{ scale_groups(g.n_vocab), scale_groups(g.n_embd) }, RAD_ACCESS_PER_TOKEN,
|
||||
shard, grp_model());
|
||||
w_dh.f.w = w_dh.w;
|
||||
w_dh.f.s = w_dh.s;
|
||||
if (!w_dh.w || !w_dh.s) return RAD_E_INVAL;
|
||||
w.selq = decl_b(b, nm.f("df_selq"), head_i8 ? RAD_I8 : RAD_F8E4M3, {srows, g.n_embd});
|
||||
w.sels = decl_b(b, nm.f("df_sels"), RAD_F32,
|
||||
{srows, head_i8 ? 1 : fp8_blocks(g.n_embd)});
|
||||
{srows, head_i8 ? 1 : scale_groups(g.n_embd)});
|
||||
op_qsel = rw(b, RAD_OP(b, head_i8 ? "quant_act_i8" : "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_INT("group", RAD_SCALE_GROUP), 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});
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
/* rad_ggml.h -- which GGUF block type a stored weight is, for a plugin that serves llama.cpp's own
|
||||
* blocks (gemm_nt_ggml, moe_gemm_ggml; docs/OPS.md).
|
||||
*
|
||||
* A GGUF tensor is imported as the affine planes of its type (libquant/lq_ggml_planes.h), so the
|
||||
* only thing a plugin sees is that encoding (rad_weight_encoding). ggml_type_of names the type back
|
||||
* by comparing it with libquant's one definition of each type's encoding, compiled into the plugin
|
||||
* from its sources the way libref compiles them (nothing is linked, so abi/ stays the whole
|
||||
* contract). Each type's encoding is its own (checkpoint_test: ggml_encodings_are_distinct), so
|
||||
* the answer is unambiguous. A plugin built without those sources (RAD_ARCH_HAVE_GGML unset)
|
||||
* names no type, and serves such a weight however it served it before.
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_encoding.h"
|
||||
|
||||
#ifdef RAD_ARCH_HAVE_GGML
|
||||
#include "lq_ggml_planes.h"
|
||||
#endif
|
||||
|
||||
namespace rad::arch {
|
||||
|
||||
/* llama.cpp's spelling of the GGUF type whose encoding `e` is exactly ("iq1_s", "q6_K"), the
|
||||
* spelling the ggml ops' `type` parameter takes, and in `block` the values one of its blocks
|
||||
* covers along K; null for any other encoding. Only types whose native blocks the loader can
|
||||
* rebuild from the planes (pack_of) are named. */
|
||||
inline const char* ggml_type_of(const RadEncoding& e, int64_t* block = nullptr) {
|
||||
#ifdef RAD_ARCH_HAVE_GGML
|
||||
for (uint32_t t = 0; t < 64; ++t) {
|
||||
const lq::ggml::PlaneKind* k = lq::ggml::plane_kind(t);
|
||||
if (!k || !lq::ggml::pack_of(t)) continue;
|
||||
const RadEncoding want = lq::ggml::encoding_of(k->type);
|
||||
if (rad_enc_equal(&e, &want)) {
|
||||
if (block) *block = k->block;
|
||||
return k->name;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
(void)e;
|
||||
(void)block;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
/* The dtype a weight stored as `e`'s planes is declared at: its codes plane's
|
||||
* (rad_builder.h: RadWeightDecl, several planes selected). */
|
||||
inline uint32_t ggml_codes_dtype(const RadEncoding& e) {
|
||||
const RadEncPlane* p = rad_enc_plane(&e, "codes");
|
||||
return p ? p->dtype : (uint32_t)RAD_DT_INVALID;
|
||||
}
|
||||
|
||||
} // namespace rad::arch
|
||||
@@ -0,0 +1,55 @@
|
||||
/* Inkling 2's reply format, as its chat template writes a turn.
|
||||
*
|
||||
* Every message is <|message_ROLE|><|content_KIND|>...<|end_message|>, and the model's turn is its
|
||||
* messages then <|content_model_end_sampling|> (the eos, which ends generation and is not read).
|
||||
* A reply that reasons, then answers, reads
|
||||
*
|
||||
* <|message_model|><|content_thinking|>REASONING<|end_message|>
|
||||
* <|message_model|><|content_text|>ANSWER<|end_message|>
|
||||
*
|
||||
* and one that calls tools writes each call as a message of its own whose header is followed by
|
||||
* the function's name rather than a content kind, its arguments in a JSON envelope that names it
|
||||
* again (the template sorts the arguments' keys and writes them compactly):
|
||||
*
|
||||
* <|message_model|>get_weather<|content_invoke_tool_json|>
|
||||
* {"name":"get_weather","args":{"city":"Lehi, Utah","units":"f"}}<|end_message|>
|
||||
*
|
||||
* So <|message_model|> is message_open: before <|content_thinking|> it is part of the reasoning
|
||||
* opener, before <|content_text|> (content_open) the answer's header, and both are dropped there;
|
||||
* before anything else it opens a call, so it is also name_prefix. The envelope is
|
||||
* object_args_key "args". With reasoning_anywhere a block the template interleaves later is
|
||||
* reasoning too, and the answer's own <|end_message|>, a close with no block open, is not part of
|
||||
* the answer.
|
||||
*
|
||||
* No grammar triggers. Every message opens with the same header, so a trigger word on it would
|
||||
* arm the call grammar on the reasoning and the answer as well (llama.cpp triggers on a pattern,
|
||||
* the header followed by something other than `<`, which trigger words cannot say). Calls are read
|
||||
* as the model writes them, unconstrained.
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_builder.h"
|
||||
|
||||
namespace inkling2 {
|
||||
|
||||
inline const RadChatFormat* inkling2_chat_format() {
|
||||
static const RadChatFormat f = [] {
|
||||
RadChatFormat c{};
|
||||
c.struct_size = (uint32_t)sizeof(RadChatFormat);
|
||||
c.name = "plugin:inkling2";
|
||||
c.reasoning_open = "<|content_thinking|>";
|
||||
c.reasoning_close = "<|end_message|>";
|
||||
c.reasoning_in_prompt = RAD_CHAT_THINK_FROM_PROMPT;
|
||||
c.reasoning_anywhere = 1;
|
||||
c.content_open = "<|content_text|>";
|
||||
c.message_open = "<|message_model|>";
|
||||
c.name_prefix = "<|message_model|>";
|
||||
c.name_suffix = "<|content_invoke_tool_json|>";
|
||||
c.call_end = "<|end_message|>";
|
||||
c.args_form = RAD_CHAT_ARGS_OBJECT;
|
||||
c.object_args_key = "args";
|
||||
return c;
|
||||
}();
|
||||
return &f;
|
||||
}
|
||||
|
||||
} /* namespace inkling2 */
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,71 @@
|
||||
/* Muse Glimmer's reply format: the ATEM channel protocol its chat template renders.
|
||||
*
|
||||
* The template's generation prompt ends at `<|start|>assistant`, so the model opens its own
|
||||
* channels: `<to=self>` reasoning first, then the answer:
|
||||
*
|
||||
* to=self<|message|> ...reasoning... <|eom|><|start|>assistant to=user<|message|> ...answer...
|
||||
*
|
||||
* `reasoning_close` carries the whole channel transition, so the answer's own header is consumed
|
||||
* with the reasoning block's close and the content begins at the answer's first byte. A reply
|
||||
* that skips the reasoning opens on the answer's channel directly (`to=user<|message|> ...`);
|
||||
* `content_open` names that header so it is dropped there too.
|
||||
*
|
||||
* Tool calls are the template's ATEM dialect, emitted as their own assistant turn whose channel
|
||||
* names the tool (chat_template.jinja, render_atem):
|
||||
*
|
||||
* to=self<|message|> ...reasoning... <|eom|><|start|>assistant to=NAME<|message|>
|
||||
* <atem:function_calls>
|
||||
* <atem:invoke name="NAME">
|
||||
* <atem:parameter name="k">value</atem:parameter>
|
||||
* </atem:invoke>
|
||||
* </atem:function_calls>
|
||||
*
|
||||
* String parameters are written raw, everything else as JSON (the template's `tojson`); the
|
||||
* section opener is the constrained-decoding trigger, and it is also the reasoning break: a call
|
||||
* turn's channel header names the tool rather than `user`, so the answer's `reasoning_close`
|
||||
* does not match there and the reasoning block runs to the section, swallowing the `<|eom|>` and
|
||||
* the header.
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_builder.h"
|
||||
|
||||
namespace museglimmer {
|
||||
|
||||
inline const RadChatFormat* muse_chat_format() {
|
||||
static const RadChatFormat f = [] {
|
||||
RadChatFormat x{};
|
||||
x.struct_size = sizeof(x);
|
||||
x.name = "plugin:museglimmer";
|
||||
x.reasoning_open = "to=self<|message|>";
|
||||
x.reasoning_close = "<|eom|><|start|>assistant to=user<|message|>";
|
||||
static const char* const kBreaks[] = {"<atem:function_calls>"};
|
||||
x.reasoning_breaks = kBreaks;
|
||||
x.n_reasoning_breaks = 1;
|
||||
/* The model opens its own channel; the prompt carries none. */
|
||||
x.reasoning_in_prompt = RAD_CHAT_THINK_NEVER;
|
||||
x.content_open = "to=user<|message|>";
|
||||
x.section_open = "<atem:function_calls>";
|
||||
x.section_close = "</atem:function_calls>";
|
||||
x.call_open = "<atem:invoke ";
|
||||
x.name_prefix = "name=\"";
|
||||
x.name_suffix = "\">";
|
||||
x.call_end = "</atem:invoke>";
|
||||
x.arg_prefix = "<atem:parameter name=\"";
|
||||
x.arg_name_suffix = "\">";
|
||||
x.arg_value_suffix = "</atem:parameter>";
|
||||
x.string_value = RAD_CHAT_VALUE_RAW; /* the template writes string arguments raw */
|
||||
x.other_value = RAD_CHAT_VALUE_JSON; /* booleans, numbers, arrays, objects as tojson */
|
||||
x.value_newlines = 1;
|
||||
/* No grammar triggers: the reference deployment (vLLM's --tool-call-parser muse) runs
|
||||
* unconstrained and parses whatever the model writes. A trigger arms the lazy tool-call
|
||||
* grammar, and with the DFlash drafter the trigger fires mid-verify -- inside drafted
|
||||
* text -- at the reasoning-to-call boundary, which spins the sampler and loops the
|
||||
* channel header (measured: drafter on = the header repeats 3-4x and the reply stalls;
|
||||
* drafter off = one header, clean call). The streaming parser reads natural ATEM as
|
||||
* it is. */
|
||||
return x;
|
||||
}();
|
||||
return &f;
|
||||
}
|
||||
|
||||
} /* namespace museglimmer */
|
||||
@@ -0,0 +1,85 @@
|
||||
/* rad_norm_bf16.h -- a bf16 block's input norm, which can take the previous block's delta with it.
|
||||
*
|
||||
* The bf16 blocks (rad_block_attn_gated.h, rad_block_gdn.h, rad_block_mlp.h) each end with
|
||||
* `all_reduce(h)` and `add(x, h)` and start with `rmsnorm(x) -> h`. With a fold, the previous block
|
||||
* leaves its delta in `h` and issues neither. This norm then issues, at two ranks where the step's
|
||||
* all-reduce goes out on the exact wire, `ar_rmsnorm`: the reduce in place, `x += h` and
|
||||
* `rmsnorm(x) -> h` in one launch, the three ops' bytes (its replaces chain, libr4d/r4d_fuse.cpp).
|
||||
* Elsewhere the previous block issues its own `all_reduce` and this norm issues `add` then
|
||||
* `rmsnorm`: the three ops as before.
|
||||
*
|
||||
* The bf16 counterpart of rad_linear.h's NormQuant fold. The previous block asks takes_ar() on the
|
||||
* same rows before skipping its collective (its `ar_out`), so both decide on ar_wire_is_exact.
|
||||
* Where the folds go is layer_fold()'s rule, as for the fp8 trunk.
|
||||
*/
|
||||
#ifndef RAD_NORM_BF16_H
|
||||
#define RAD_NORM_BF16_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
#include "rad_linear.h" /* ar_wire_is_exact */
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct NormBF16 {
|
||||
Geom g{};
|
||||
rad_weight w = 0;
|
||||
rad_buf x = 0, h = 0;
|
||||
rad_op op_norm = 0; /* rmsnorm(x) -> h */
|
||||
rad_op op_add = 0; /* with a fold, unfused: x += h first */
|
||||
rad_op op_arn = 0; /* with a fold at two ranks: ar_rmsnorm(h, x) -> h */
|
||||
|
||||
/* `fold`: take the previous block's delta from `h` into `x`. `fuse_ar`: and its all-reduce,
|
||||
* on steps whose wire is exact (two ranks only). */
|
||||
int declare(RadBuilder* b, const Geom& geom, rad_weight gain, rad_buf x_, rad_buf h_,
|
||||
bool fold = false, bool fuse_ar = false);
|
||||
/* Asked by the previous block before issuing its own all-reduce. */
|
||||
bool takes_ar(int64_t T) const { return op_arn && ar_wire_is_exact(g, T); }
|
||||
void step(RadCtx* c, int64_t T) const;
|
||||
};
|
||||
|
||||
inline int NormBF16::declare(RadBuilder* b, const Geom& geom, rad_weight gain, rad_buf x_,
|
||||
rad_buf h_, bool fold, bool fuse_ar) {
|
||||
g = geom; w = gain; x = x_; h = h_;
|
||||
op_add = op_arn = 0;
|
||||
if (fold) {
|
||||
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),
|
||||
{x, h}, {x});
|
||||
if (!op_add) return RAD_E_INVAL;
|
||||
}
|
||||
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)),
|
||||
{x}, {h});
|
||||
if (!op_norm) return RAD_E_INVAL;
|
||||
if (fold && fuse_ar && g.world == 2) {
|
||||
/* `h` is the message and the output, `x` the residual: both read and written. */
|
||||
op_arn = rw(b, RAD_OP(b, "ar_rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_INT("world_size", g.world),
|
||||
RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd)),
|
||||
RAD_WEIGHTS(w)),
|
||||
{h, x}, {h, x});
|
||||
if (!op_arn) return RAD_E_INVAL;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
inline void NormBF16::step(RadCtx* c, int64_t T) const {
|
||||
if (takes_ar(T)) {
|
||||
RAD_ISSUE_N(c, op_arn, T, brows(h, T), brows(x, T), RAD_W(w), brows(h, T));
|
||||
return;
|
||||
}
|
||||
if (op_add) RAD_ISSUE(c, op_add, brows(x, T), brows(h, T), brows(x, T));
|
||||
RAD_ISSUE(c, op_norm, brows(x, T), RAD_W(w), brows(h, T));
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_NORM_BF16_H */
|
||||
+111
-37
@@ -9,13 +9,14 @@
|
||||
* 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.
|
||||
* change here. A step entirely at or below that bound therefore needs no selection at all, and
|
||||
* step() issues only the block-key path for it (its `use`; docs/QSA.md, "Below the bound").
|
||||
*/
|
||||
#ifndef RAD_QSA_H
|
||||
#define RAD_QSA_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
#include "rad_fp8.h"
|
||||
#include "rad_linear.h"
|
||||
|
||||
#include <atomic>
|
||||
|
||||
@@ -105,7 +106,7 @@ struct QsaIndexer {
|
||||
Wire w{};
|
||||
int layer = 0;
|
||||
rad_weight w_qn = 0, w_kn = 0;
|
||||
LinearFP8 proj{};
|
||||
LinearQ 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
|
||||
@@ -119,19 +120,49 @@ struct QsaIndexer {
|
||||
* 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);
|
||||
const Wire& wire, const ActQ& 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;
|
||||
* score plane (Config::plane_rows); null where no step is.
|
||||
*
|
||||
* `use` is what the layer's attention reads of the selection this step (QsaUse, rad_arch.h;
|
||||
* AttnGatedQ::qsa_use): the default issues the query, the scores and the selection as every
|
||||
* step did before. `first` is whether this is the first full-attention layer the pass issues:
|
||||
* at or below the bound the selection is made there once and read by every layer after it (the
|
||||
* buffers are the model's, live across its layers, and nothing else writes them). The default
|
||||
* makes it at every layer. */
|
||||
void step(RadCtx* c, const ActQ& in, const RadBatch* batch,
|
||||
const int32_t* win_cu = nullptr, int use = kQsaSelect, bool first = true) 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;
|
||||
* selection (see AttnGatedQ::store_kv). */
|
||||
void store(RadCtx* c, const ActQ& in, const RadBatch* batch) const;
|
||||
/* `part` 0 issues all of it; 1, 2 and 3 its three stages apart and in that order (the work
|
||||
* list, the block keys, the tail store), for a caller that issues them behind another block's
|
||||
* launches (deferrable, below). */
|
||||
bool store_keys(RadCtx* c, const RadBatch* batch, int part = 0) const;
|
||||
/* Whether this step's keys and tail may be issued behind the attention block's launches
|
||||
* instead of in front of them (SideOps, rad_arch.h): nothing reads a selection of this
|
||||
* layer's (`use` as step() resolves it), so the attention reads nothing the three ops write.
|
||||
* The caller answers for the buffers (Wire: qk, stage, page, bpos, nc excluded from
|
||||
* sharing). */
|
||||
bool deferrable(const RadBatch* batch, int use, bool first) const {
|
||||
if (!on() || qsa_eager()) return false;
|
||||
/* step() stores no keys for a batch without the attention's group; leave that to it. */
|
||||
if (!kv_batch(batch, c.kv_attn)) return false;
|
||||
if (use == kQsaOnce) use = first ? kQsaSelect : kQsaUnread;
|
||||
return use == kQsaUnread;
|
||||
}
|
||||
/* What step() issues on a deferrable step, a piece at a time: the projection, then
|
||||
* store_keys's stages 1..3. */
|
||||
void step_proj(RadCtx* c, const ActQ& in, const RadBatch* batch) const {
|
||||
proj.step(c, in, w.qk, batch->n_tok);
|
||||
}
|
||||
void step_part(RadCtx* c, const RadBatch* batch, int part) const {
|
||||
(void)store_keys(c, batch, part);
|
||||
}
|
||||
};
|
||||
|
||||
inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
const Config& cfg, const Wire& wire, const ActFP8& in,
|
||||
const Config& cfg, const Wire& wire, const ActQ& 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 */
|
||||
@@ -260,14 +291,14 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
{w.score, w.nc}, {w.sel, w.nsel, w.sequ});
|
||||
|
||||
/* When the attention group streams, the attention block resolves `sel` to ring slots after its
|
||||
* layer's store (AttnGatedFP8::step); prefill runs on the stage and never resolves. */
|
||||
* layer's store (AttnGatedQ::step); prefill runs on the stage and never resolves. */
|
||||
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 {
|
||||
inline bool QsaIndexer::store_keys(RadCtx* c_, const RadBatch* batch, int part) 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 */
|
||||
@@ -289,43 +320,80 @@ inline bool QsaIndexer::store_keys(RadCtx* c_, const RadBatch* batch) const {
|
||||
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));
|
||||
if (part <= 1)
|
||||
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));
|
||||
if (part == 1) return true;
|
||||
if (part == 0 || part == 2)
|
||||
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));
|
||||
if (part == 2) return true;
|
||||
if (S == 1 && batch->ckpt_cut > 0 && batch->ckpt_cut < T && batch->ckpt_cu) {
|
||||
/* A checkpoint inside the step (RadBatch::ckpt_cut): the ring over the rows before it,
|
||||
* the snapshot, then the rest -- the ring a chunk ending there leaves, and after both
|
||||
* the ring the whole step leaves (a row writes its own position's slot). */
|
||||
const int64_t ck = batch->ckpt_cut;
|
||||
for (int64_t p = 0; p < 2; ++p) {
|
||||
RAD_ISSUE_N(c_, op_tail, p == 0 ? ck : T - ck,
|
||||
bcol_at(w.qk, 0, nw, koff, c.head_dim, T),
|
||||
praw(batch->positions, RAD_I32, T),
|
||||
praw(batch->ckpt_cu + p, RAD_I32, 2),
|
||||
kv_cache(c.kv_tail, layer),
|
||||
praw2(tlb->state_index, RAD_I32, S, tw));
|
||||
if (p == 0) rad_ckpt_snap(c_, c.kv_tail, layer);
|
||||
}
|
||||
} else
|
||||
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 {
|
||||
inline void QsaIndexer::store(RadCtx* c_, const ActQ& 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 {
|
||||
inline void QsaIndexer::step(RadCtx* c_, const ActQ& in, const RadBatch* batch,
|
||||
const int32_t* win_cu, int use, bool first) 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;
|
||||
|
||||
/* What the attention reads this step (QsaUse); anything asked of a step that cannot give it is
|
||||
* the full issue, which every reader accepts.
|
||||
*
|
||||
* kQsaOnce: the attention reads a selection on a step entirely at or below the exactness
|
||||
* bound. A row there has at most `topk` complete blocks, so qsa_select takes every one whose
|
||||
* key is not 0 -- every block with a page and a score that is a number, whatever the number --
|
||||
* and what it writes (the pages in block order, the partial page, their count, seqused) is a
|
||||
* function of the positions and the block table: the same bytes from every layer's scores. So
|
||||
* the pass's first full-attention layer issues the selection in full, and
|
||||
* every later layer reads that one and issues none of its own: no query, no score. */
|
||||
if (use == kQsaOnce) use = first ? kQsaSelect : kQsaUnread;
|
||||
if (use != kQsaUnread) use = kQsaSelect;
|
||||
/* RADIANCE_DEBUG_QSA_EAGER: every layer issues its own query, score and select. */
|
||||
if (qsa_eager()) use = kQsaSelect;
|
||||
|
||||
/* The projection always: its raw-key head is the block keys' and the tail's. */
|
||||
proj.step(c_, in, w.qk, T);
|
||||
/* The query heads are read by the score alone. */
|
||||
if (use == kQsaSelect) {
|
||||
/* 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
|
||||
@@ -342,8 +410,10 @@ inline void QsaIndexer::step(RadCtx* c_, const ActFP8& in, const RadBatch* batch
|
||||
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. */
|
||||
/* The keys first: the selection below reads the blocks they complete. The stateful half runs
|
||||
* whatever the attention reads: later steps score the block keys and build on the tail. */
|
||||
const RadKVGroupBatch* bkb = kv_batch(batch, kv_bk);
|
||||
const RadKVGroupBatch* atb = kv_batch(batch, c.kv_attn);
|
||||
if (!atb || !store_keys(c_, batch)) return;
|
||||
@@ -352,6 +422,10 @@ inline void QsaIndexer::step(RadCtx* c_, const ActFP8& in, const RadBatch* batch
|
||||
* 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;
|
||||
/* Nothing reads a selection of this layer's: the step is at or below the exactness bound and
|
||||
* its attention reads the block table, or the selection the pass's first full-attention layer
|
||||
* made (AttnGatedQ::qsa_use). */
|
||||
if (use == kQsaUnread) 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
|
||||
|
||||
+15
-13
@@ -70,6 +70,7 @@ struct Vae {
|
||||
int64_t halo = 0;
|
||||
std::vector<rad_buf> whole;
|
||||
VaeConvForm form = VAE_CONV_2D;
|
||||
bool round_norm_length = false;
|
||||
/* group_norm's statistics scratch, one for every GroupNorm op (they run one after another). */
|
||||
rad_buf gn_stats = 0;
|
||||
|
||||
@@ -92,9 +93,10 @@ struct Vae {
|
||||
grp_layer(first_group));
|
||||
}
|
||||
|
||||
/* y = conv(x): k x k, stride, `up` 2 reads x upsampled, `pad` same or down. */
|
||||
/* y = conv(x): k x k, stride, `up` 2 reads x upsampled, `pad` same or down.
|
||||
* A spatial weight has no time dimension, even in a causal VAE. */
|
||||
VImg conv(const VImg& x, int64_t cout, int k, int stride, int up, const char* pad,
|
||||
const char* ckpt) {
|
||||
const char* ckpt, bool spatial_weight = false) {
|
||||
VOp o;
|
||||
o.kind = VOp::CONV;
|
||||
o.x = x;
|
||||
@@ -106,7 +108,7 @@ struct Vae {
|
||||
o.y = img(cout, lvl);
|
||||
o.k = k;
|
||||
o.w = wt(nm->f("%s.weight", ckpt), nm->ckpt("%s.weight", ckpt), { cout, x.ch, k, k },
|
||||
form == VAE_CONV_CAUSAL);
|
||||
form == VAE_CONV_CAUSAL && !spatial_weight);
|
||||
o.b = wt(nm->f("%s.bias", ckpt), nm->ckpt("%s.bias", ckpt), { cout });
|
||||
o.op = RAD_OP(b, "conv2d_nhwc",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, px_at(lvl)), RAD_INT("cin", x.ch),
|
||||
@@ -134,7 +136,7 @@ struct Vae {
|
||||
o.op = rw(b, RAD_OP(b, "l2norm_chan",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("n", x.ch),
|
||||
RAD_STR("act", silu ? "silu" : "none"),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_INT("round_length", round_norm_length), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(o.w)),
|
||||
{ x.buf }, { o.y.buf });
|
||||
ops.push_back(o);
|
||||
@@ -172,18 +174,18 @@ struct Vae {
|
||||
/* A residual block, in -> out channels. */
|
||||
VImg resblock(const VImg& x, int64_t out, const char* ckpt) {
|
||||
VImg h = x;
|
||||
if (x.ch != out) h = conv(x, out, 1, 1, 1, "same", nm->f("%s.conv_shortcut", ckpt));
|
||||
VImg t = norm(x, true, nm->f("%s.norm1", ckpt), 4);
|
||||
t = conv(t, out, 3, 1, 1, "same", nm->f("%s.conv1", ckpt));
|
||||
t = norm(t, true, nm->f("%s.norm2", ckpt), 4);
|
||||
t = conv(t, out, 3, 1, 1, "same", nm->f("%s.conv2", ckpt));
|
||||
if (x.ch != out) h = conv(x, out, 1, 1, 1, "same", nm->ckpt("%s.conv_shortcut", ckpt));
|
||||
VImg t = norm(x, true, nm->ckpt("%s.norm1", ckpt), 4);
|
||||
t = conv(t, out, 3, 1, 1, "same", nm->ckpt("%s.conv1", ckpt));
|
||||
t = norm(t, true, nm->ckpt("%s.norm2", ckpt), 4);
|
||||
t = conv(t, out, 3, 1, 1, "same", nm->ckpt("%s.conv2", ckpt));
|
||||
return add(t, h);
|
||||
}
|
||||
/* The mid-block's single-head attention over every pixel. */
|
||||
VImg attention(const VImg& x, const char* ckpt) {
|
||||
VImg attention(const VImg& x, const char* ckpt, bool spatial_weights = false) {
|
||||
const int64_t C = x.ch;
|
||||
VImg t = norm(x, false, nm->f("%s.norm", ckpt), 3);
|
||||
VImg qkv = conv(t, 3 * C, 1, 1, 1, "same", nm->f("%s.to_qkv", ckpt));
|
||||
VImg t = norm(x, false, nm->ckpt("%s.norm", ckpt), 3);
|
||||
VImg qkv = conv(t, 3 * C, 1, 1, 1, "same", nm->ckpt("%s.to_qkv", ckpt), spatial_weights);
|
||||
VOp o;
|
||||
o.kind = VOp::ATTN;
|
||||
o.x = qkv;
|
||||
@@ -197,7 +199,7 @@ struct Vae {
|
||||
RAD_NOWEIGHTS),
|
||||
{ qkv.buf }, { o.y.buf });
|
||||
ops.push_back(o);
|
||||
VImg p = conv(o.y, C, 1, 1, 1, "same", nm->f("%s.proj", ckpt));
|
||||
VImg p = conv(o.y, C, 1, 1, 1, "same", nm->ckpt("%s.proj", ckpt), spatial_weights);
|
||||
return add(p, x);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(deepseek41 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
# A GGUF's weights in llama.cpp's blocks (arch/common/rad_ggml.h): the plugin names a weight's type
|
||||
# through libquant's one definition of each type's encoding, compiled from its sources as libref
|
||||
# compiles them (nothing is linked, so abi/ stays the whole contract). Out of tree, without those
|
||||
# sources, no weight is read as blocks.
|
||||
set(DS41_SRC ${CMAKE_CURRENT_SOURCE_DIR}/deepseek41.cpp)
|
||||
set(DS41_GGML_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../libquant)
|
||||
if(EXISTS ${DS41_GGML_DIR}/lq_ggml_planes.cpp)
|
||||
list(APPEND DS41_SRC ${DS41_GGML_DIR}/lq_ggml_planes.cpp ${DS41_GGML_DIR}/lq_ggml_tables.cpp)
|
||||
set(DS41_HAVE_GGML ON)
|
||||
endif()
|
||||
rad_add_plugin(deepseek41 architectures SOURCES ${DS41_SRC})
|
||||
if(DS41_HAVE_GGML)
|
||||
target_compile_definitions(deepseek41 PRIVATE RAD_ARCH_HAVE_GGML=1)
|
||||
target_include_directories(deepseek41 PRIVATE ${DS41_GGML_DIR})
|
||||
endif()
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,328 @@
|
||||
/* DeepSeek-V4.1's vision tower: the ViT over one image and the aligner that maps its 3x3 cells
|
||||
* into the language model's width, BF16 at TP1 (the tower is ~0.9 GiB; it is replicated, not
|
||||
* sharded). The reference is `inference/vision.py` (DeepSeek ViT: full bidirectional attention
|
||||
* over one image with 2D RoPE) and `model.py` 1218-1242 for the span.
|
||||
*
|
||||
* Geometry is fixed by config.json: 32 blocks, width 1024 = 16 heads x 64, SwiGLU 2816, patch
|
||||
* 14, theta 10000, RMSNorm eps 1e-6 with an F32 gain, 3x3 aligner into 5120. Nothing here
|
||||
* hard-codes those numbers: P (patches a pass), depth and widths all come from vision_config.
|
||||
*
|
||||
* Unlike the text path, no kernel normalises the weightless RMS with a separate gain: the tower
|
||||
* weight is F32, so `rmsnorm` carries the gain itself (it reads the gain in f32 and rounds the
|
||||
* row once, which is the reference's float32 arithmetic narrowed to the activation dtype).
|
||||
* The 2-D rotary is `ds41_vit_rope2d` -- both axes on ONE ladder, not Pixtral's interleaved
|
||||
* pair -- and the 3x3 pack is `ds41_pack3x3`, zero-padded over the raster grid, not a
|
||||
* channel-major merger. */
|
||||
#pragma once
|
||||
#include <arch/rad_arch.h>
|
||||
|
||||
namespace deepseek41 {
|
||||
using namespace rad::arch;
|
||||
|
||||
struct Ds41Vision {
|
||||
struct Norm {
|
||||
rad_weight w = 0;
|
||||
rad_op op = 0;
|
||||
};
|
||||
struct Layer {
|
||||
Norm n1, n2;
|
||||
rad_weight qkv_w = 0, qkv_b = 0, out_w = 0, out_b = 0, gu = 0, down = 0;
|
||||
rad_op project = 0, rope = 0, attn = 0, output = 0, add1 = 0;
|
||||
rad_op gate = 0, act = 0, gate_mul = 0, ffn = 0, add2 = 0;
|
||||
};
|
||||
bool on = false;
|
||||
int64_t P = 0, width = 0, heads = 0, hd = 0, ff = 0, depth = 0, patch_dim = 0;
|
||||
int64_t merge = 0, embd = 0, max_grid = 0;
|
||||
float eps = 1e-6f, theta = 10000.0f;
|
||||
rad_buf x = 0, h = 0, qkv = 0, att = 0, o = 0, gu = 0, ffn = 0, packed = 0, proj = 0,
|
||||
out = 0;
|
||||
rad_weight patch = 0, patch_b = 0, merger1 = 0, merger1_b = 0, merger2 = 0, merger2_b = 0;
|
||||
/* The span's learned rows (image_start / image_end / image_newline) copied into `span_rows`
|
||||
* [4, n_embd]: 0, 3, 2; slot 1 is unused (the encoder's own rows). */
|
||||
rad_weight start_w = 0, end_w = 0, nl_w = 0;
|
||||
rad_buf span_rows = 0;
|
||||
rad_op op_start = 0;
|
||||
rad_op stem = 0, pack = 0, project1 = 0, gelu = 0, project2 = 0;
|
||||
Norm post;
|
||||
std::vector<Layer> layers;
|
||||
|
||||
int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx, Names& nm,
|
||||
int64_t model_embd, int first_group) {
|
||||
on = false;
|
||||
if (ctx->max_enc_patches <= 0) return RAD_OK;
|
||||
auto vi = [&](const char* k) {
|
||||
return rad_meta_geti(meta, (std::string("vision_config.") + k).c_str(), 0);
|
||||
};
|
||||
width = vi("hidden_size");
|
||||
heads = vi("num_attention_heads");
|
||||
ff = vi("intermediate_size");
|
||||
depth = vi("num_hidden_layers");
|
||||
const int64_t ps = vi("patch_size");
|
||||
/* config.json: `downsample_ratio` 3, no per-tower eps or image_size; the reference fixes
|
||||
* RMSNorm eps at 1e-6 (vision.py's norm), temporal patch 1 and RGB. */
|
||||
merge = vi("downsample_ratio");
|
||||
embd = model_embd;
|
||||
const double theta_m = rad_meta_getf(meta, "vision_config.rope_theta", 0);
|
||||
const double eps_m = rad_meta_getf(meta, "vision_config.rms_norm_eps", 1e-6);
|
||||
if (width <= 0 || heads <= 0 || width % heads || (width / heads) % 4 || ff <= 0 ||
|
||||
depth <= 0 || ps <= 0 || merge < 2 || embd <= 0 || !(theta_m > 0) ||
|
||||
!std::isfinite(theta_m) || !(eps_m > 0) || !std::isfinite(eps_m))
|
||||
return RAD_E_INVAL;
|
||||
hd = width / heads;
|
||||
patch_dim = 3 * 1 * ps * ps; /* temporal_patch_size 1: an image is one plane */
|
||||
/* gemm_nt_bias's device kernel stages 8-wide; 588 is not a multiple of 8, and the host
|
||||
* fallback reads the device pixel pointer and faults. Four zero columns make K legal. */
|
||||
patch_dim = (patch_dim + 7) & ~7;
|
||||
theta = (float)theta_m;
|
||||
eps = (float)eps_m;
|
||||
const int64_t mm = merge * merge, max_seg = ctx->max_enc_patches;
|
||||
P = max_seg;
|
||||
if (P % mm) return RAD_E_SHAPE;
|
||||
if (ctx->shape_probe) P = std::max(mm, std::min(P, ctx->max_tok) / mm * mm);
|
||||
if (P < mm) return RAD_E_INVAL;
|
||||
const int64_t R = P / mm;
|
||||
max_grid = ctx->max_enc_patches;
|
||||
|
||||
auto buf = [&](const char* name, int64_t rows, int64_t cols, uint32_t flags = 0) {
|
||||
return decl_b(b, nm.f("v.%s", name), RAD_BF16, {rows, cols}, flags);
|
||||
};
|
||||
x = buf("x", P, width);
|
||||
h = buf("h", P, width);
|
||||
qkv = buf("qkv", P, 3 * width);
|
||||
att = buf("attn", P, width);
|
||||
o = buf("o", P, width);
|
||||
gu = buf("gate_up", P, 2 * ff);
|
||||
ffn = buf("ff", P, ff);
|
||||
packed = buf("packed", R, mm * width);
|
||||
proj = buf("proj", R, embd);
|
||||
out = buf("out", R, embd, RAD_BUF_PERSIST);
|
||||
if (!x || !h || !qkv || !att || !o || !gu || !ffn || !packed || !proj || !out)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
auto weight = [&](const char* dest, const char* src, uint32_t dt,
|
||||
std::initializer_list<int64_t> shape, RadWeightGroup group) {
|
||||
if (map_copy(b, dest, src) < 0) return rad_weight(0);
|
||||
return decl_w(b, dest, dt, shape, RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, group);
|
||||
};
|
||||
auto gemm = [&](int64_t rows, int64_t N, int64_t K, const char* act, rad_weight w,
|
||||
rad_weight bias) -> rad_op {
|
||||
if (bias)
|
||||
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", act)),
|
||||
RAD_WEIGHTS(w, bias));
|
||||
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 norm = [&](Norm& n, const char* dest, const char* src, RadWeightGroup group,
|
||||
rad_buf from, rad_buf to) {
|
||||
n.w = weight(dest, src, RAD_F32, {width}, group);
|
||||
n.op = rw(b,
|
||||
RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
|
||||
RAD_F64("eps", eps), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(n.w)),
|
||||
{from}, {to});
|
||||
};
|
||||
|
||||
patch = weight(nm.f("v.patch.weight"), nm.ckpt("vision.patch_embed.proj.weight"), RAD_BF16,
|
||||
{width, patch_dim}, grp_model());
|
||||
patch_b = weight(nm.f("v.patch.bias"), nm.ckpt("vision.patch_embed.proj.bias"), RAD_BF16,
|
||||
{width}, grp_model());
|
||||
stem = rw(b, gemm(P, width, patch_dim, "none", patch, patch_b), {}, {x});
|
||||
|
||||
layers.resize((size_t)depth);
|
||||
for (int64_t i = 0; i < depth; ++i) {
|
||||
auto& l = layers[(size_t)i];
|
||||
const long long li = i;
|
||||
const auto group = grp_layer(first_group + (int)i);
|
||||
norm(l.n1, nm.f("v.blk.%lld.n1.weight", li),
|
||||
nm.ckpt("vision.blocks.%lld.norm1.weight", li), group, x, h);
|
||||
norm(l.n2, nm.f("v.blk.%lld.n2.weight", li),
|
||||
nm.ckpt("vision.blocks.%lld.norm2.weight", li), group, x, h);
|
||||
l.qkv_w = weight(nm.f("v.blk.%lld.qkv.weight", li),
|
||||
nm.ckpt("vision.blocks.%lld.attn.wqkv.weight", li), RAD_BF16,
|
||||
{3 * width, width}, group);
|
||||
l.qkv_b = weight(nm.f("v.blk.%lld.qkv.bias", li),
|
||||
nm.ckpt("vision.blocks.%lld.attn.wqkv.bias", li), RAD_BF16,
|
||||
{3 * width}, group);
|
||||
l.out_w = weight(nm.f("v.blk.%lld.out.weight", li),
|
||||
nm.ckpt("vision.blocks.%lld.attn.wo.weight", li), RAD_BF16,
|
||||
{width, width}, group);
|
||||
l.out_b = weight(nm.f("v.blk.%lld.out.bias", li),
|
||||
nm.ckpt("vision.blocks.%lld.attn.wo.bias", li), RAD_BF16, {width},
|
||||
group);
|
||||
l.gu = weight(nm.f("v.blk.%lld.gate_up.weight", li),
|
||||
nm.ckpt("vision.blocks.%lld.mlp.w1.weight", li), RAD_BF16,
|
||||
{2 * ff, width}, group);
|
||||
l.down = weight(nm.f("v.blk.%lld.down.weight", li),
|
||||
nm.ckpt("vision.blocks.%lld.mlp.w2.weight", li), RAD_BF16,
|
||||
{width, ff}, group);
|
||||
if (!l.n1.w || !l.n2.w || !l.qkv_w || !l.qkv_b || !l.out_w || !l.out_b || !l.gu ||
|
||||
!l.down)
|
||||
return RAD_E_INVAL;
|
||||
l.project = rw(b, gemm(P, 3 * width, width, "none", l.qkv_w, l.qkv_b), {h}, {qkv});
|
||||
l.rope = rw(b,
|
||||
RAD_OP(b, "ds41_vit_rope2d",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", hd),
|
||||
RAD_INT("n_head", heads), RAD_F64("theta", theta),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{qkv}, {qkv});
|
||||
l.attn = rw(b,
|
||||
RAD_OP(b, "embed_attn",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", hd),
|
||||
RAD_INT("gqa", 1), RAD_INT("causal", 0),
|
||||
RAD_INT("max_seqlen", max_seg),
|
||||
RAD_F64("scale", 1.0 / std::sqrt((double)hd)),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{qkv}, {att});
|
||||
l.output = rw(b, gemm(P, width, width, "none", l.out_w, l.out_b), {att}, {o});
|
||||
l.add1 = rw(b,
|
||||
RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{x, o}, {x});
|
||||
l.gate = rw(b, gemm(P, 2 * ff, width, "none", l.gu, 0), {h}, {gu});
|
||||
l.act = rw(b,
|
||||
RAD_OP(b, "silu",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", ff),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{gu}, {gu});
|
||||
l.gate_mul = rw(b,
|
||||
RAD_OP(b, "mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", ff),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{gu}, {ffn});
|
||||
l.ffn = rw(b, gemm(P, width, ff, "none", l.down, 0), {ffn}, {o});
|
||||
l.add2 = rw(b,
|
||||
RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{x, o}, {x});
|
||||
}
|
||||
norm(post, nm.f("v.post.weight"), nm.ckpt("vision.norm.weight"), grp_model(), x, h);
|
||||
merger1 = weight(nm.f("v.merger1.weight"), nm.ckpt("aligner.w1.weight"), RAD_BF16,
|
||||
{embd, mm * width}, grp_model());
|
||||
merger1_b = weight(nm.f("v.merger1.bias"), nm.ckpt("aligner.w1.bias"), RAD_BF16, {embd},
|
||||
grp_model());
|
||||
merger2 = weight(nm.f("v.merger2.weight"), nm.ckpt("aligner.w2.weight"), RAD_BF16,
|
||||
{embd, embd}, grp_model());
|
||||
merger2_b = weight(nm.f("v.merger2.bias"), nm.ckpt("aligner.w2.bias"), RAD_BF16, {embd},
|
||||
grp_model());
|
||||
if (!patch || !patch_b || !post.w || !merger1 || !merger1_b || !merger2 ||
|
||||
!merger2_b)
|
||||
return RAD_E_INVAL;
|
||||
start_w = weight(nm.f("v.image_start"), nm.ckpt("image_start"), RAD_BF16, {embd},
|
||||
grp_model());
|
||||
end_w = weight(nm.f("v.image_end"), nm.ckpt("image_end"), RAD_BF16, {embd}, grp_model());
|
||||
nl_w = weight(nm.f("v.image_newline"), nm.ckpt("image_newline"), RAD_BF16, {embd},
|
||||
grp_model());
|
||||
span_rows = decl_b(b, nm.f("v.span_rows"), RAD_BF16, {4, embd}, RAD_BUF_PERSIST);
|
||||
if (!start_w || !end_w || !nl_w || !span_rows) return RAD_E_INVAL;
|
||||
op_start = rw(b,
|
||||
RAD_OP(b, "ds41_span_rows",
|
||||
RAD_PARAMS(RAD_INT("n", embd), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(start_w, nl_w, end_w)),
|
||||
{}, {span_rows});
|
||||
if (!op_start) return RAD_E_INVAL;
|
||||
pack = rw(b,
|
||||
RAD_OP(b, "ds41_pack3x3",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
|
||||
RAD_INT("merge", merge), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{h}, {packed});
|
||||
project1 = rw(b, gemm(R, embd, mm * width, "none", merger1, merger1_b), {packed}, {proj});
|
||||
gelu = rw(b,
|
||||
RAD_OP(b, "gelu",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", embd),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{proj}, {proj});
|
||||
project2 = rw(b, gemm(R, embd, embd, "none", merger2, merger2_b), {proj}, {out});
|
||||
if (!ctx->shape_probe) {
|
||||
RadEncoderDecl e{};
|
||||
e.name = "vision";
|
||||
e.modalities = RAD_MM_IMAGE;
|
||||
e.patch_dim = patch_dim;
|
||||
e.merge = (int)mm;
|
||||
e.max_patches = P;
|
||||
e.n_embd = embd;
|
||||
e.out = out;
|
||||
e.span_rows = span_rows;
|
||||
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
|
||||
rad_note(b, "DeepSeek-V4.1 vision tower: %lld blocks of %lld (%lld heads x %lld), "
|
||||
"ff %lld, patch %lld, merge %lld; %lld patches a pass -> %lld rows of %lld",
|
||||
(long long)depth, (long long)width, (long long)heads, (long long)hd,
|
||||
(long long)ff, (long long)ps, (long long)merge, (long long)P, (long long)R,
|
||||
(long long)embd);
|
||||
}
|
||||
on = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t n = batch->enc_n_patch, s = batch->enc_n_seg, mm = merge * merge;
|
||||
if (!on || batch->enc != RAD_MM_IMAGE || n <= 0 || n > P || s <= 0 || !batch->enc_pixels ||
|
||||
!batch->enc_coord || !batch->enc_cu || !batch->enc_seg_h || !batch->enc_seg_w) {
|
||||
rad_step_fail(c, "deepseek41: invalid vision encoder pass");
|
||||
return;
|
||||
}
|
||||
int64_t total = 0, rows = 0;
|
||||
for (int64_t i = 0; i < s; ++i) {
|
||||
const int64_t hh = batch->enc_seg_h[i], ww = batch->enc_seg_w[i];
|
||||
if (hh <= 0 || ww <= 0 || hh * ww > n - total) {
|
||||
rad_step_fail(c, "deepseek41: vision expects complete raster grids");
|
||||
return;
|
||||
}
|
||||
total += hh * ww;
|
||||
rows += ((hh + merge - 1) / merge) * ((ww + merge - 1) / merge);
|
||||
}
|
||||
if (total != n || rows > P / mm) {
|
||||
rad_step_fail(c, "deepseek41: vision grid sizes disagree with patches");
|
||||
return;
|
||||
}
|
||||
const auto coord = praw2(batch->enc_coord, RAD_I32, 2, n),
|
||||
crd4 = praw2(batch->enc_coord, RAD_I32, 4, n),
|
||||
cu = praw(batch->enc_cu, RAD_I32, s + 1);
|
||||
auto norm = [&](const Norm& nrm, rad_buf from, rad_buf to) {
|
||||
RAD_ISSUE_N(c, nrm.op, n, brows(from, n), RAD_W(nrm.w), brows(to, n));
|
||||
};
|
||||
RAD_ISSUE_N(c, stem, n, praw2(batch->enc_pixels, RAD_BF16, n, patch_dim), RAD_W(patch),
|
||||
RAD_W(patch_b), RAD_NONE, brows(x, n));
|
||||
RAD_ISSUE_N(c, op_start, embd, RAD_W(start_w), RAD_W(nl_w), RAD_W(end_w),
|
||||
brows(span_rows, 4));
|
||||
for (const auto& l : layers) {
|
||||
norm(l.n1, x, h);
|
||||
RAD_ISSUE_N(c, l.project, n, brows(h, n), RAD_W(l.qkv_w), RAD_W(l.qkv_b), RAD_NONE,
|
||||
brows(qkv, n));
|
||||
RAD_ISSUE_N(c, l.rope, n, brows(qkv, n), coord);
|
||||
RAD_ISSUE_N(c, l.attn, n, bcol(qkv, 0, width, n), bcol(qkv, width, width, n),
|
||||
bcol(qkv, 2 * width, width, n), cu, brows(att, n));
|
||||
RAD_ISSUE_N(c, l.output, n, brows(att, n), RAD_W(l.out_w), RAD_W(l.out_b), RAD_NONE,
|
||||
brows(o, n));
|
||||
RAD_ISSUE_N(c, l.add1, n, brows(x, n), brows(o, n), brows(x, n));
|
||||
norm(l.n2, x, h);
|
||||
RAD_ISSUE_N(c, l.gate, n, brows(h, n), RAD_W(l.gu), brows(gu, n));
|
||||
RAD_ISSUE_N(c, l.act, n, bcol(gu, 0, ff, n), bcol(gu, 0, ff, n));
|
||||
RAD_ISSUE_N(c, l.gate_mul, n, bcol(gu, 0, ff, n), bcol(gu, ff, ff, n), brows(ffn, n));
|
||||
RAD_ISSUE_N(c, l.ffn, n, brows(ffn, n), RAD_W(l.down), brows(o, n));
|
||||
RAD_ISSUE_N(c, l.add2, n, brows(x, n), brows(o, n), brows(x, n));
|
||||
}
|
||||
norm(post, x, h);
|
||||
RAD_ISSUE_N(c, pack, n, brows(h, n), crd4, brows(packed, (int64_t)rows));
|
||||
RAD_ISSUE_N(c, project1, (int64_t)rows, brows(packed, (int64_t)rows), RAD_W(merger1),
|
||||
RAD_W(merger1_b), RAD_NONE, brows(proj, (int64_t)rows));
|
||||
RAD_ISSUE_N(c, gelu, (int64_t)rows, brows(proj, (int64_t)rows), brows(proj, (int64_t)rows));
|
||||
RAD_ISSUE_N(c, project2, (int64_t)rows, brows(proj, (int64_t)rows), RAD_W(merger2),
|
||||
RAD_W(merger2_b), RAD_NONE, brows(out, (int64_t)rows));
|
||||
}
|
||||
};
|
||||
} // namespace deepseek41
|
||||
@@ -0,0 +1,30 @@
|
||||
/* ds41_walk_geom.h -- the planes and gather of deepseek41's full-vocabulary DSpark walk (dspark-walk;
|
||||
* dsp_declare / dsp_query), one definition the plugin and its test share (tests/r4d_emu/test_ds41walk.cpp
|
||||
* holds the issued gather to libr4d's all-gather admission, r4d_ar_gather_admit.h, at every sequence count
|
||||
* and step).
|
||||
*
|
||||
* A step's key is a u64 in a 16-byte slot (kSlot f32: the key, then 8 bytes nobody reads), because libr4d's
|
||||
* all-gather moves whole 16-byte words a row: ar_gather_4rank refuses an 8-byte row (the key alone, f32 row 2) at
|
||||
* the first full-vocabulary query pass. The planes, `wseqs` sequences a step, `block` steps:
|
||||
* keys [block * wseqs, kSlot] f32, zeroed once a pass; step l's rows [l * wseqs, l * wseqs + S)
|
||||
* gath [block * wseqs, world * kSlot] f32, all_gather(keys rows of step l, row kSlot) -> the same rows
|
||||
* The gather is declared with numel wseqs * kSlot (its bound) and issued over S rows. */
|
||||
#ifndef DS41_WALK_GEOM_H
|
||||
#define DS41_WALK_GEOM_H
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace ds41walk {
|
||||
|
||||
constexpr int64_t kSlot = 4;
|
||||
inline int64_t keys_cols() { return kSlot; }
|
||||
inline int64_t gath_cols(int world) { return (int64_t)world * kSlot; }
|
||||
inline int64_t plane_rows(int64_t block, int64_t wseqs) { return block * wseqs; }
|
||||
inline int64_t gather_numel(int64_t wseqs) { return wseqs * kSlot; }
|
||||
inline int64_t gather_row() { return kSlot; }
|
||||
/* step l's first row in keys and in gath */
|
||||
inline int64_t step_row(int64_t l, int64_t wseqs) { return l * wseqs; }
|
||||
|
||||
} // namespace ds41walk
|
||||
|
||||
#endif
|
||||
@@ -86,7 +86,7 @@ struct Model {
|
||||
Gemma4Audio aud;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* 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
|
||||
@@ -123,7 +123,8 @@ static int read_schedule(const RadModelMeta* meta, int64_t n_layer, std::vector<
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
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) {
|
||||
@@ -132,7 +133,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
Model& m = g_model[ctx->rank];
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
|
||||
@@ -265,10 +266,6 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
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) ||
|
||||
@@ -278,6 +275,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_x}, {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. */
|
||||
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});
|
||||
@@ -381,11 +382,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
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});
|
||||
m.op_cast = cast_op(b, g.max_seqs, m.n_out, "bf16", "f32", 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(), "",
|
||||
@@ -417,7 +414,7 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
const Geom& g = m.g;
|
||||
const int64_t T = batch->n_tok, S = batch->n_seq, E = g.n_embd;
|
||||
if (batch->enc) {
|
||||
@@ -480,6 +477,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
} /* namespace embgemma2 */
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
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")
|
||||
|
||||
+75
-127
@@ -8,9 +8,10 @@
|
||||
* Backbone: the language model of Qwen3.5-35B-A3B, unchanged -- 40 layers of 2048, three gated
|
||||
* delta-net layers to one gated attention layer (16 query heads over 2 KV heads of 256, NeoX
|
||||
* rotary on 64 dims at theta 1e7), a routed feed-forward in every layer (256 experts of 512, 8 a
|
||||
* token, and a gated shared expert of 512), (1 + w) norms. Only the routed experts are fp8
|
||||
* (`quant_method: bsgemm-moe`, E4M3 with an f32 scale a 128 x 128 block); everything else is
|
||||
* bf16. A prompt row is a token; an audio row is one frame of the codec's ten codes, embedded as
|
||||
* token, and a gated shared expert of 512), (1 + w) norms. Only the routed experts use fp8 in
|
||||
* the source checkpoint (`quant_method: bsgemm-moe`, E4M3 with one f32 scale per 128 x 128
|
||||
* block). The int8 recipe converts these experts and keeps the rest of the backbone in bf16.
|
||||
* A prompt row is a token; an audio row is one frame of the codec's ten codes, embedded as
|
||||
* (E_lm[248099 + c0] + E_cb[4096 + c1]) / sqrt 2: the first code through its semantic token,
|
||||
* the second through section 1 of the codebook table.
|
||||
*
|
||||
@@ -62,9 +63,9 @@
|
||||
* samples.
|
||||
*/
|
||||
#include <arch/rad_arch.h>
|
||||
#include <arch/rad_block_attn_gated_fp8.h>
|
||||
#include <arch/rad_block_gdn_fp8.h>
|
||||
#include <arch/rad_block_moe_fp8.h>
|
||||
#include <arch/rad_block_attn_gated_q.h>
|
||||
#include <arch/rad_block_gdn_q.h>
|
||||
#include <arch/rad_block_moe_q.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
@@ -100,7 +101,8 @@ constexpr int kShared = 4, kTower = kShared + (int)kCodes - 1;
|
||||
* token and every head; the main token uncapped (256, cfg_topk_sample's widest) and each head at
|
||||
* top-k 30, as SGLang-Omni draws them. fish-speech's server defaults (0.7, 0.7, 30 for both) make
|
||||
* the model fall silent after a tag or a speaker's line and never come back: over 40 takes of
|
||||
* four short scripts, 8 ran to their length in silence against none here (docs/ARCHITECTURES.md). */
|
||||
* four short scripts, 8 ran to their length in silence against none here
|
||||
* (docs/ARCHITECTURES.md). */
|
||||
constexpr int64_t kMainTopK = 256, kHeadTopK = 30;
|
||||
static const double kTemp = 1.0, kTopP = 0.9;
|
||||
/* The repetition-aware redraw, fixed by the training recipe (tower.py): when the first draw is
|
||||
@@ -156,9 +158,9 @@ enum : int { kGrpTower = 40, kGrpFrame = 53, kGrpCodec = 100 };
|
||||
/* ================================================================== the networks */
|
||||
struct Layer {
|
||||
int full = 0;
|
||||
AttnGatedFP8 attn;
|
||||
GdnFP8 gdn;
|
||||
MoeFP8 mlp;
|
||||
AttnGatedQ attn;
|
||||
GdnQ gdn;
|
||||
MoeQ mlp;
|
||||
};
|
||||
|
||||
/* A tower layer (tower.py's TowerLayer): the code embedding and the two norms into eh_proj, the
|
||||
@@ -237,23 +239,23 @@ struct Model {
|
||||
Names nm{""};
|
||||
Geom g{}; /* the backbone's */
|
||||
Geom gt{}; /* the tower's */
|
||||
GdnFP8::Config gcfg{};
|
||||
MoeFP8::Config moecfg{};
|
||||
GdnQ::Config gcfg{};
|
||||
MoeQ::Config moecfg{};
|
||||
int64_t n_rot = 0, n_rot_t = 0, n_main = 0, lanes = 0;
|
||||
rad_kvgroup kv_full = 0, kv_state = 0, kv_conv = 0;
|
||||
|
||||
/* ---- the backbone: the residual stream, its normed copy, and the blocks' working set */
|
||||
rad_buf b_x = 0;
|
||||
ActFP8 a_h{};
|
||||
ActQ a_h{};
|
||||
rad_buf b_qg = 0, b_k = 0, b_v = 0, b_q = 0, b_rope_cs = 0;
|
||||
ActFP8 a_attn{};
|
||||
ActFP8 a_in{}, a_go{};
|
||||
ActQ a_attn{};
|
||||
ActQ a_in{}, a_go{};
|
||||
rad_buf b_ab = 0, b_gq = 0, b_gk = 0, b_gv = 0, b_gdec = 0, b_beta = 0, b_kkt = 0;
|
||||
rad_buf b_rlogits = 0, b_eids = 0, b_ew = 0, b_sorted = 0, b_eoff = 0, b_ecnt = 0;
|
||||
rad_buf b_egu = 0, b_edn = 0, b_emoe = 0;
|
||||
ActFP8 a_eff{};
|
||||
ActQ a_eff{};
|
||||
rad_buf b_sgu = 0, b_sout = 0, b_sgate = 0;
|
||||
ActFP8 a_sff{};
|
||||
ActQ a_sff{};
|
||||
rad_weight w_tok = 0, w_out_norm = 0;
|
||||
rad_op op_embed = 0, op_embed_ar = 0, op_final_norm = 0, op_rope_cs = 0;
|
||||
std::vector<Layer> layers;
|
||||
@@ -261,9 +263,9 @@ struct Model {
|
||||
/* ---- a lane's state (PERSIST) */
|
||||
rad_buf b_hid = 0; /* [lanes, 2048] the last row's final-norm hidden state */
|
||||
rad_buf b_status = 0; /* [lanes] i32 */
|
||||
rad_buf b_hist = 0; /* [lanes * 10, kMaxFrames] i32: each lane's codes, codebook rows */
|
||||
rad_buf b_hist = 0; /* [lanes * 10, kMaxFrames] i32: each lane's codes, by codebook */
|
||||
rad_buf b_ras = 0; /* [lanes, 16] i32: the last 16 main picks (candidate indices) */
|
||||
rad_buf b_u = 0; /* [lanes, 2048] the last frame's codes 2..9, embedded and summed */
|
||||
rad_buf b_u = 0; /* [lanes, 2048] the last frame's codes 2..9, embedded, summed */
|
||||
|
||||
/* ---- the frame */
|
||||
rad_weight w_cand = 0; /* [4097, 2048] the lm_head's candidate rows */
|
||||
@@ -322,7 +324,7 @@ struct Model {
|
||||
* row's label). */
|
||||
constexpr int64_t kPcW = kMaxPrompt + 1;
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* ================================================================== declare helpers */
|
||||
static rad_op norm_op(RadBuilder* b, int64_t rows, int64_t n, double eps, double wadd,
|
||||
@@ -334,57 +336,6 @@ static rad_op norm_op(RadBuilder* b, int64_t rows, int64_t n, double eps, double
|
||||
x, { y });
|
||||
}
|
||||
|
||||
static rad_op add_op(RadBuilder* b, int64_t rows, int64_t n, rad_buf a, rad_buf c, rad_buf y) {
|
||||
return rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ a, c }, { y });
|
||||
}
|
||||
|
||||
static rad_op gemm_op(RadBuilder* b, int64_t rows, int64_t N, int64_t K, rad_weight w, rad_buf x,
|
||||
rad_buf y) {
|
||||
return rw(b, 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)),
|
||||
{ x }, { y });
|
||||
}
|
||||
|
||||
static rad_op gemm_bias_op(RadBuilder* b, int64_t rows, int64_t N, int64_t K, rad_weight w,
|
||||
rad_weight bias, rad_buf x, rad_buf y) {
|
||||
return rw(b, 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_WEIGHTS(w, bias)),
|
||||
{ x }, { y });
|
||||
}
|
||||
|
||||
static rad_op rows_op(RadBuilder* b, const char* op, int64_t rows, int64_t n,
|
||||
std::initializer_list<rad_buf> in, std::initializer_list<rad_buf> out) {
|
||||
return rw(b, RAD_OP(b, op,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
in, out);
|
||||
}
|
||||
|
||||
static rad_op mulw_op(RadBuilder* b, int64_t rows, int64_t n, rad_weight w, rad_buf x, rad_buf y) {
|
||||
return rw(b, RAD_OP(b, "mul_weight",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w)),
|
||||
{ x }, { y });
|
||||
}
|
||||
|
||||
static rad_op iota_op(RadBuilder* b, int64_t rows, int64_t start, int64_t step, rad_buf y) {
|
||||
return rw(b, RAD_OP(b, "iota",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("start", start),
|
||||
RAD_INT("step", step)),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, { y });
|
||||
}
|
||||
|
||||
static rad_op cu_op(RadBuilder* b, int64_t mult, rad_buf len, rad_buf y) {
|
||||
return rw(b, RAD_OP(b, "cu_repeat",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, 2), RAD_INT("mult", mult)),
|
||||
@@ -394,13 +345,7 @@ static rad_op cu_op(RadBuilder* b, int64_t mult, rad_buf len, rad_buf y) {
|
||||
|
||||
static rad_op ar_op(RadBuilder* b, const Geom& g, rad_buf x) {
|
||||
if (g.world <= 1) return 0;
|
||||
return 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),
|
||||
{ x }, { x });
|
||||
return decl_all_reduce(b, g, x);
|
||||
}
|
||||
|
||||
/* A frame draw: `k` largest, Fish's nucleus over the whole candidate set first (rad OPS.md,
|
||||
@@ -424,25 +369,27 @@ static rad_weight wcopy(RadBuilder* b, const char* dn, const char* src, uint32_t
|
||||
}
|
||||
|
||||
/* ================================================================== check_format */
|
||||
/* The container's statement of what it is. Every mismatch below would still make sound -- a
|
||||
* different template, another codebook layout, an fp8 format read as this one -- so each is a
|
||||
* refusal by name rather than a silent default. */
|
||||
/* The container's statement of what it is. The metadata describes Fish's source checkpoint,
|
||||
* which a conversion carries over unchanged; the converted experts' encoding is read from the
|
||||
* weights in declare_trunk. Every mismatch below would still make sound -- a different template,
|
||||
* another codebook layout, another release's experts read as this one -- so each is a refusal by
|
||||
* name rather than a silent default. */
|
||||
static int check_format(const RadModelMeta* meta) {
|
||||
const char* method = rad_meta_gets(meta, "quantization_config.quant_method", nullptr);
|
||||
const char* block = rad_meta_gets(meta, "quantization_config.weight_block_size", nullptr);
|
||||
if (!method || std::strcmp(method, "bsgemm-moe") != 0) {
|
||||
fprintf(stderr, "radiance: fishomni serves Fish Audio's released drama-3, whose routed "
|
||||
"experts are block-scaled fp8 (quant_method 'bsgemm-moe'); this container "
|
||||
fprintf(stderr, "radiance: fishomni serves Fish Audio's released drama-3, whose source "
|
||||
"experts use quant_method 'bsgemm-moe'; this checkpoint "
|
||||
"says '%s'\n", method ? method : "(none)");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (block) {
|
||||
long long b0 = 0, b1 = 0;
|
||||
if (std::sscanf(block, "%lld %lld", &b0, &b1) != 2) { b0 = 0; b1 = 0; }
|
||||
if (b0 != RAD_FP8_BLOCK || b1 != RAD_FP8_BLOCK) {
|
||||
fprintf(stderr, "radiance: fishomni refuses weight_block_size [%lld, %lld]: libr4d's "
|
||||
"block-scaled GEMMs are compiled at %d in both dimensions\n",
|
||||
b0, b1, RAD_FP8_BLOCK);
|
||||
if (b0 != RAD_SCALE_GROUP || b1 != RAD_SCALE_GROUP) {
|
||||
fprintf(stderr, "radiance: fishomni: source weight_block_size [%lld, %lld] differs "
|
||||
"from drama-3's %d in both dimensions\n",
|
||||
b0, b1, RAD_SCALE_GROUP);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
}
|
||||
@@ -482,9 +429,8 @@ static int check_format(const RadModelMeta* meta) {
|
||||
|
||||
/* ================================================================== the backbone */
|
||||
/* qwen35moe_fp8's trunk, written out (arch/qwen35_fp8/qwen35_fp8.cpp, QWEN35_MOE): the same
|
||||
* blocks, metadata and names, without its drafters, vision tower and int8 build. Its bf16 linears
|
||||
* (attention, delta net, shared expert) are served by LinearFP8's plain branch beside the fp8
|
||||
* experts. */
|
||||
* blocks, metadata and names. Its bf16 linears (attention, delta net and shared expert) read
|
||||
* the plain activations. Only the routed experts use the converted encoding. */
|
||||
static int declare_trunk(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx,
|
||||
Model& m) {
|
||||
Geom& g = m.g;
|
||||
@@ -502,7 +448,7 @@ static int declare_trunk(RadBuilder* b, const RadModelMeta* meta, const RadBuild
|
||||
g.n_layer, interval, {"full_attention"}));
|
||||
m.n_main = g.n_layer;
|
||||
|
||||
/* GemmaRMSNorm everywhere but the delta net's output norm (rad_block_gdn_fp8.h). */
|
||||
/* GemmaRMSNorm everywhere but the delta net's output norm (rad_block_gdn_q.h). */
|
||||
g.wadd = 1.0f;
|
||||
g.wadd_qk = 1.0f;
|
||||
|
||||
@@ -516,7 +462,7 @@ static int declare_trunk(RadBuilder* b, const RadModelMeta* meta, const RadBuild
|
||||
}
|
||||
RAD_ARCH_TRY(yarn_from(g, meta, "", m.n_rot));
|
||||
|
||||
GdnFP8::Config& gc = m.gcfg;
|
||||
GdnQ::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",
|
||||
@@ -590,7 +536,7 @@ static int declare_trunk(RadBuilder* b, const RadModelMeta* meta, const RadBuild
|
||||
|
||||
/* ---- the routing geometry; `n_ff` is already the per-rank expert width */
|
||||
{
|
||||
MoeFP8::Config& mc = m.moecfg;
|
||||
MoeQ::Config& mc = m.moecfg;
|
||||
mc.n_expert = meta->n_expert;
|
||||
mc.top_k = meta->n_expert_used > 0 ? meta->n_expert_used
|
||||
: meta_int2(meta, "qwen35.expert_used_count",
|
||||
@@ -618,15 +564,14 @@ static int declare_trunk(RadBuilder* b, const RadModelMeta* meta, const RadBuild
|
||||
m.b_ecnt = decl_b(b, nm.f("moe_cnt"), RAD_I32, {mc.n_expert}, RAD_BUF_PERSIST);
|
||||
m.b_egu = decl_b(b, nm.f("moe_gate_up"), g.act_dtype, {K, 2 * mc.n_ff_exp});
|
||||
m.a_eff.x = decl_b(b, nm.f("moe_ffn"), g.act_dtype, {K, mc.n_ff_exp});
|
||||
m.a_eff.q = decl_b(b, nm.f("moe_ffn.q"), RAD_F8E4M3, {K, mc.n_ff_exp});
|
||||
m.a_eff.s = decl_b(b, nm.f("moe_ffn.s"), RAD_F32, {K, fp8_blocks(mc.n_ff_exp)});
|
||||
m.b_edn = decl_b(b, nm.f("moe_down"), g.act_dtype, {K, g.n_embd});
|
||||
if (mc.n_ff_shared > 0) {
|
||||
m.b_emoe = decl_b(b, nm.f("moe_out"), g.act_dtype, {R, g.n_embd});
|
||||
m.b_sgu = decl_b(b, nm.f("shexp_gate_up"), g.act_dtype, {R, 2 * mc.n_ff_shared});
|
||||
m.a_sff.x = decl_b(b, nm.f("shexp_ffn"), g.act_dtype, {R, mc.n_ff_shared});
|
||||
m.a_sff.q = decl_b(b, nm.f("shexp_ffn.q"), RAD_F8E4M3, {R, mc.n_ff_shared});
|
||||
m.a_sff.s = decl_b(b, nm.f("shexp_ffn.s"), RAD_F32, {R, fp8_blocks(mc.n_ff_shared)});
|
||||
m.a_sff.s = decl_b(b, nm.f("shexp_ffn.s"), RAD_F32,
|
||||
{R, scale_groups(mc.n_ff_shared)});
|
||||
m.b_sout = decl_b(b, nm.f("shexp_out"), g.act_dtype, {R, g.n_embd});
|
||||
m.b_sgate = decl_b(b, nm.f("shexp_gate"), g.act_dtype, {R, 1});
|
||||
}
|
||||
@@ -652,12 +597,7 @@ static int declare_trunk(RadBuilder* b, const RadModelMeta* meta, const RadBuild
|
||||
* on every rank (replicated tables), and a reduction there would sum it world times. Exact:
|
||||
* it sums disjoint rows. */
|
||||
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});
|
||||
m.op_embed_ar = decl_all_reduce_exact(b, g, m.b_x);
|
||||
m.op_rope_cs = rw(b, decl_rotary(b, g, "rope_table",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qk_fuse_rows(g)), RAD_INT("rot", m.n_rot),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
@@ -665,17 +605,17 @@ static int declare_trunk(RadBuilder* b, const RadModelMeta* meta, const RadBuild
|
||||
RAD_NOWEIGHTS),
|
||||
{}, {m.b_rope_cs});
|
||||
|
||||
AttnGatedFP8::Wire aw{};
|
||||
AttnGatedQ::Wire aw{};
|
||||
aw.x = m.b_x; aw.h = m.a_h; aw.qg = m.b_qg; aw.k = m.b_k; aw.v = m.b_v;
|
||||
aw.q = m.b_q; aw.attn = m.a_attn;
|
||||
aw.cos_sin = m.op_rope_cs ? m.b_rope_cs : 0;
|
||||
|
||||
GdnFP8::Wire gw{};
|
||||
GdnQ::Wire gw{};
|
||||
gw.x = m.b_x; gw.h = m.a_h; gw.in = m.a_in; gw.ab = m.b_ab;
|
||||
gw.q = m.b_gq; gw.k = m.b_gk; gw.v = m.b_gv;
|
||||
gw.gdec = m.b_gdec; gw.beta = m.b_beta; gw.kkt = m.b_kkt; gw.o = m.a_go;
|
||||
|
||||
MoeFP8::Wire mw{};
|
||||
MoeQ::Wire mw{};
|
||||
mw.x = m.b_x; mw.h = m.a_h;
|
||||
mw.logits = m.b_rlogits; mw.ids = m.b_eids; mw.ew = m.b_ew;
|
||||
mw.sorted = m.b_sorted; mw.eoff = m.b_eoff; mw.ecnt = m.b_ecnt;
|
||||
@@ -690,7 +630,7 @@ static int declare_trunk(RadBuilder* b, const RadModelMeta* meta, const RadBuild
|
||||
const LayerFold f = layer_fold(g, l, m.n_main, nullptr, 0, false);
|
||||
const char* pre = "model.language_model.layers";
|
||||
if (lay.full) {
|
||||
AttnGatedFP8::Src as{};
|
||||
AttnGatedQ::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);
|
||||
@@ -702,7 +642,7 @@ static int declare_trunk(RadBuilder* b, const RadModelMeta* meta, const RadBuild
|
||||
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));
|
||||
} else {
|
||||
GdnFP8::Src gs{};
|
||||
GdnQ::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);
|
||||
@@ -718,7 +658,7 @@ static int declare_trunk(RadBuilder* b, const RadModelMeta* meta, const RadBuild
|
||||
RAD_ARCH_TRY(lay.gdn.declare(b, nm, g, gc, (int)l, m.kv_state, m.kv_conv, gw, gs,
|
||||
f.mix_fold, false, f.mix_ar_in, f.mix_ar_out));
|
||||
}
|
||||
MoeFP8::Src ms{};
|
||||
MoeQ::Src ms{};
|
||||
ms.cfg = m.moecfg;
|
||||
ms.norm = nm.ckpt("%s.%lld.post_attention_layernorm.weight", pre, (long long)l);
|
||||
ms.router = nm.ckpt("%s.%lld.mlp.gate.weight", pre, (long long)l);
|
||||
@@ -727,9 +667,19 @@ static int declare_trunk(RadBuilder* b, const RadModelMeta* meta, const RadBuild
|
||||
ms.shared = nm.ckpt("%s.%lld.mlp.shared_expert", pre, (long long)l);
|
||||
ms.shared_gate = nm.ckpt("%s.%lld.mlp.shared_expert_gate.weight", pre, (long long)l);
|
||||
}
|
||||
/* The experts' stored format, read from the layer's first: the release's scale planes are
|
||||
* f32 (fp8a8f32), not the bf16 Qwen3.6's are. */
|
||||
RAD_ARCH_TRY(MoeFP8::probe(b, nm, (int)l, ms, &ms.cfg));
|
||||
RAD_ARCH_TRY(MoeQ::probe(b, nm, (int)l, ms, &ms.cfg));
|
||||
/* Int8 gate/up needs a rotated copy of the bf16 norm output used by the shared expert.
|
||||
* The down projection needs one activation row per routed slot in this pass. */
|
||||
if (ms.cfg.expert_i8 && !mw.hr.q8) {
|
||||
RAD_ARCH_TRY(mw.hr.declare_qs(b, nm, g, "moe_hr", g.n_embd, g.max_tok, true, false));
|
||||
mw.hr.q8_fed = mw.hr.q8_rot = true;
|
||||
RAD_ARCH_TRY(mw.eff.declare_qs(b, nm, g, "moe_ffn", ms.cfg.n_ff_exp,
|
||||
ms.cfg.rows * ms.cfg.top_k, true, false));
|
||||
} else if (!ms.cfg.expert_i8 && !ms.cfg.expert_bf16 && !mw.eff.q) {
|
||||
RAD_ARCH_TRY(mw.eff.declare_qs(b, nm, g, "moe_ffn", ms.cfg.n_ff_exp,
|
||||
ms.cfg.rows * ms.cfg.top_k));
|
||||
}
|
||||
mw.eff.q8_fed = mw.eff.q8_rot = ms.cfg.expert_i8 != 0;
|
||||
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));
|
||||
}
|
||||
@@ -972,7 +922,8 @@ static int declare_tower(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
src("transformer_layer.feed_forward.w3.weight") }));
|
||||
L.w_gu = decl_w(b, dn("gate_up.weight"), RAD_BF16, { 2 * ff, D }, RAD_ACCESS_PER_TOKEN,
|
||||
RAD_SHARD_ROW, grp_layer(grp), 0, { ff, ff });
|
||||
RAD_ARCH_TRY(map_copy(b, dn("down.weight"), src("transformer_layer.feed_forward.w2.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, dn("down.weight"),
|
||||
src("transformer_layer.feed_forward.w2.weight")));
|
||||
L.w_down = decl_w(b, dn("down.weight"), RAD_BF16, { D, ff }, RAD_ACCESS_PER_TOKEN,
|
||||
RAD_SHARD_COL, grp_layer(grp));
|
||||
if (!L.w_emb || !L.w_en || !L.w_hn || !L.w_an || !L.w_fn || !L.w_fin || !L.w_qn ||
|
||||
@@ -1306,7 +1257,8 @@ static int declare_codec(RadBuilder* b, Model& m) {
|
||||
m.op_cnst = iota_op(b, 1, NC, 0, m.b_cconst);
|
||||
for (int s = 0; s < kRates; ++s) {
|
||||
m.b_ccu[s] = decl_b(b, nm.f("codec.cu%d", s), RAD_I32, { 2 });
|
||||
m.op_ccu[s] = s == 0 ? cu_op(b, 1, 0, m.b_ccu[0]) : cu_op(b, kRate[s], m.b_cconst, m.b_ccu[s]);
|
||||
m.op_ccu[s] = s == 0 ? cu_op(b, 1, 0, m.b_ccu[0])
|
||||
: cu_op(b, kRate[s], m.b_cconst, m.b_ccu[s]);
|
||||
if (!m.op_ccu[s]) return RAD_E_INVAL;
|
||||
}
|
||||
for (int k = 0; k < kCodes; ++k) {
|
||||
@@ -1490,12 +1442,7 @@ static int declare_codec(RadBuilder* b, Model& m) {
|
||||
rows[4], m.b_vt[4], 0, m.b_vout, m.b_ccu[7], "tanh"));
|
||||
m.b_audio = decl_b(b, nm.f("codec.audio"), RAD_F32, { kVocChunk * kSamplesPerFrame, 1 },
|
||||
RAD_BUF_PERSIST);
|
||||
m.op_fcast = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, kVocChunk * kSamplesPerFrame),
|
||||
RAD_INT("n", 1), RAD_STR("from", "bf16"),
|
||||
RAD_STR("to", "f32")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.b_vout }, { m.b_audio });
|
||||
m.op_fcast = cast_op(b, kVocChunk * kSamplesPerFrame, 1, "bf16", "f32", m.b_vout, m.b_audio);
|
||||
return m.w_cn && m.op_cn && m.w_fa && m.op_fs && m.op_fcast && m.op_cnst ? RAD_OK
|
||||
: RAD_E_INVAL;
|
||||
}
|
||||
@@ -1701,8 +1648,9 @@ static int declare_encoder(RadBuilder* b, Model& m) {
|
||||
/* ================================================================== declare */
|
||||
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];
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(check_format(meta));
|
||||
@@ -1909,8 +1857,7 @@ struct TowerAt {
|
||||
|
||||
static void step_tower(RadCtx* c, const Model& m, const TowerAt& at) {
|
||||
const Geom& g = m.gt;
|
||||
const int64_t R = at.R, D = g.n_embd, hd = g.head_dim, Sx = m.lanes;
|
||||
const int64_t qd = g.n_head * hd;
|
||||
const int64_t R = at.R, D = g.n_embd, Sx = m.lanes;
|
||||
/* Row k of the code-major [10, lanes] plane, narrowed to this pass's lanes. */
|
||||
auto code = [&](int k) {
|
||||
RadOperand o = brow_slice(m.b_codes, k, 1, Sx);
|
||||
@@ -1974,7 +1921,6 @@ static void step_tower(RadCtx* c, const Model& m, const TowerAt& at) {
|
||||
RAD_NONE, RAD_NONE, RAD_NONE);
|
||||
}
|
||||
}
|
||||
(void)qd;
|
||||
}
|
||||
|
||||
static void step_prompt(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
@@ -2184,7 +2130,7 @@ static void step_vocode(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
if (!batch->gen || !batch->agen_b) {
|
||||
rad_step_fail(c, "fishomni is an audio generator and runs generator passes only");
|
||||
return;
|
||||
@@ -2352,8 +2298,10 @@ RAD_ARCH_PROBE(fishomni)
|
||||
extern "C" int64_t rad_arch_text_prepare(int field, const char* in, char* out, int64_t cap) {
|
||||
return fishomni::text_prepare(field, in, out, cap);
|
||||
}
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(fishomni, "fishomni", "bsgemm-moe", "0.1.0",
|
||||
"Fish Audio drama-3: the Qwen3.5-35B-A3B backbone (block-scaled fp8 experts), a "
|
||||
"13-layer codebook tower over its full-attention cache, and Fish S2's modified "
|
||||
"Fish Audio drama-3: the Qwen3.5-35B-A3B backbone with converted routed experts, "
|
||||
"a 13-layer codebook tower over its full-attention cache, and Fish S2's modified "
|
||||
"DAC; 44.1 kHz mono speech")
|
||||
#endif
|
||||
@@ -0,0 +1,9 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(flint LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(flint architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/flint.cpp)
|
||||
@@ -0,0 +1,524 @@
|
||||
/* flint -- Recursive Flint (39.8B-A2.5B): two dense layers then 47 sigmoid-routed MoE layers,
|
||||
* grouped-query attention with per-head Q/K RMSNorm, a learned per-head softmax sink, and a
|
||||
* 513-token sliding window on 35 of the 49 layers (the other 14 are full attention and NoPE).
|
||||
*
|
||||
* 2 dense layers: rmsnorm -> q/k/v -> qk-norm -> [rope] -> paged attention + sink -> o
|
||||
* rmsnorm -> gate_up -> silu_mul -> down
|
||||
* 47 MoE layers: same attention; rmsnorm -> router -> top-6 of 256 (sigmoid)
|
||||
* -> grouped gate_up -> silu_mul -> down -> gather
|
||||
* + ungated shared expert (2 x 512)
|
||||
*
|
||||
* Weights come from a BF16 or recipe-quantized Flint checkpoint; the blocks probe the stored
|
||||
* encoding. Two trunk forms, read from layer 0's q projection:
|
||||
*
|
||||
* - a rotated int8 trunk (data/recipes/flint-iq8r.recipe: IQ8R linears, i8 codes rotated by a
|
||||
* 128-wide Hadamard): the norms, the gated products and the attention output write
|
||||
* had_quant_act_i8g's codes themselves, every linear reads them at i8a8h, and the routed
|
||||
* experts are rotated int8 (or another form with an int8 row) read by the grouped GEMM's int8
|
||||
* rows from the same codes (MoeQ::a8), as qwen35moe_w8a8 serves Qwen3.6-35B-A3B;
|
||||
* - any other (bf16, the four-bit attention of data/recipes/flint-bf16-q4.recipe, plain int8
|
||||
* linears): each linear reads the bf16 plane or quantises it itself, and four-bit experts read
|
||||
* the block input's E4M3 pair, as hyv3_bf16 serves its W4 and W8 recipes.
|
||||
*
|
||||
* No MTP head.
|
||||
*/
|
||||
#include <arch/rad_arch.h>
|
||||
#include "flint_attention.h"
|
||||
#include <arch/rad_block_mlp_q.h>
|
||||
#include <arch/rad_block_moe_q.h>
|
||||
#include "rad_abi_layout.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <climits>
|
||||
#include <cstdio>
|
||||
#include <vector>
|
||||
|
||||
namespace flint {
|
||||
using namespace rad::arch;
|
||||
|
||||
struct Layer {
|
||||
bool dense = false;
|
||||
bool sliding = false;
|
||||
FlintAttn attn{};
|
||||
MlpQ dense_mlp{};
|
||||
MoeQ moe{};
|
||||
};
|
||||
|
||||
struct Model {
|
||||
Names nm{};
|
||||
Geom g{};
|
||||
int64_t n_ff_expert = 0, n_ff_shared = 0;
|
||||
rad_kvgroup kv_full = 0, kv_win = 0;
|
||||
/* Whether layer 0's probe found a rotated-int8 trunk, and its activation scale group: see
|
||||
* rad_linear.h's trunk_rotation. */
|
||||
bool trunk_rot = false;
|
||||
int64_t trunk_g8 = RAD_SCALE_GROUP;
|
||||
|
||||
rad_buf x = 0, h_out = 0, logits = 0;
|
||||
ActQ h{};
|
||||
/* The routed experts' rotated int8 copy of the block input, where a rotated trunk's norms do
|
||||
* not write the codes themselves (MoeQ::Wire::hr). */
|
||||
ActQ hr{};
|
||||
rad_buf q = 0, k = 0, v = 0;
|
||||
ActQ attn{};
|
||||
rad_buf dense_gate_up = 0;
|
||||
ActQ dense_ffn{};
|
||||
MoeQ::Wire mw{};
|
||||
|
||||
rad_weight token = 0, final_norm = 0, lm_head = 0;
|
||||
rad_op embed = 0, embed_ar = 0, shared_one = 0, final_rms = 0, gather = 0, logits_op = 0;
|
||||
std::vector<Layer> layers;
|
||||
};
|
||||
|
||||
/* Every per-instance state is indexed by slot (rad_build_slot at declare, rad_slot in step). */
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* Flint's layer schedule: full attention (and NoPE) at 0, 1, 5, 9, ..., 45, 48; the other 35
|
||||
* layers are sliding (window 513) and carry RoPE. */
|
||||
static bool is_full(int64_t l) {
|
||||
return l == 0 || l == 1 || l == 48 || (l >= 5 && l <= 45 && (l - 5) % 4 == 0);
|
||||
}
|
||||
|
||||
static int64_t meta_i(const RadModelMeta* meta, const char* a, const char* b, int64_t def) {
|
||||
int64_t v = meta_text_geti(meta, a, INT64_MIN);
|
||||
if (v == INT64_MIN && b) v = meta_text_geti(meta, b, INT64_MIN);
|
||||
return v == INT64_MIN ? def : v;
|
||||
}
|
||||
|
||||
static int check_model(const RadModelMeta* meta, const Geom& g, Model& m) {
|
||||
const int64_t sliding = meta_i(meta, "sliding_window", "flint.attention.sliding_window", 513);
|
||||
const int64_t n_expert = meta_text_geti(meta, "num_experts", meta->n_expert);
|
||||
const int64_t top_k = meta_text_geti(meta, "num_experts_per_tok", meta->n_expert_used);
|
||||
const int64_t moe_ff = meta_i(meta, "moe_intermediate_size",
|
||||
"flint.expert_feed_forward_length", 512);
|
||||
const int64_t shared = meta_i(meta, "shared_expert_intermediate_size",
|
||||
"flint.expert_shared_feed_forward_length", 1024);
|
||||
const int64_t dense_ff = meta_i(meta, "intermediate_size",
|
||||
"flint.feed_forward_length", 6144);
|
||||
|
||||
if (g.n_layer != 49 || g.n_embd != 2048 || g.n_head_all != 32 || g.n_head_kv_all != 4 ||
|
||||
g.head_dim != 128 || g.n_vocab_all != 150144 || dense_ff != 6144 ||
|
||||
sliding != 513 || n_expert != 256 || top_k != 6 || moe_ff != 512 || shared != 1024) {
|
||||
fprintf(stderr, "radiance: flint: unsupported geometry (49 layers, 2048-wide, 32/4 "
|
||||
"heads x 128, vocab 150144, 256 experts top-6, expert width 512, shared "
|
||||
"1024, sliding 513); got %lld layers, %lld-wide, %lld/%lld heads, "
|
||||
"vocab %lld, %lld experts top-%lld, expert %lld, shared %lld, "
|
||||
"sliding %lld, dense %lld\n",
|
||||
(long long)g.n_layer, (long long)g.n_embd, (long long)g.n_head_all,
|
||||
(long long)g.n_head_kv_all, (long long)g.n_vocab_all, (long long)n_expert,
|
||||
(long long)top_k, (long long)moe_ff, (long long)shared, (long long)sliding,
|
||||
(long long)dense_ff);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (g.world != 1 && g.world != 2) {
|
||||
fprintf(stderr, "radiance: flint supports tensor-parallel world sizes 1 and 2\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
m.n_ff_expert = moe_ff;
|
||||
m.n_ff_shared = shared;
|
||||
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 ||
|
||||
rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
|
||||
int status = geom_from(m.g, meta, ctx, "bf16", RAD_BF16);
|
||||
if (status < 0) return status;
|
||||
Geom& g = m.g;
|
||||
Names& nm = m.nm;
|
||||
|
||||
status = check_model(meta, g, m);
|
||||
if (status < 0) return status;
|
||||
|
||||
if (ctx->kv_dtype != RAD_DT_INVALID && ctx->kv_dtype != RAD_BF16 && ctx->kv_dtype != RAD_I8) {
|
||||
fprintf(stderr, "radiance: flint serves a bf16 or an int8 KV cache, not %s\n",
|
||||
rad_dtype_name((uint32_t)ctx->kv_dtype));
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
status = yarn_from(g, meta, "", g.head_dim);
|
||||
if (status < 0) return status;
|
||||
|
||||
const int64_t sliding = meta_i(meta, "sliding_window", "flint.attention.sliding_window", 513);
|
||||
const int64_t n_expert_all = meta_text_geti(meta, "num_experts", meta->n_expert);
|
||||
const int64_t top_k = meta_text_geti(meta, "num_experts_per_tok", meta->n_expert_used);
|
||||
if (n_expert_all % g.world != 0) return RAD_E_SHAPE;
|
||||
const int64_t n_expert_local = n_expert_all / g.world;
|
||||
|
||||
/* Two paged groups: the 14 full layers grow with the context, the 35 sliding layers keep
|
||||
* only 513 tokens. That is what makes 262K affordable. Both take the deployment's cache
|
||||
* dtype: bf16, or with --kv-cache-dtype i8 the int8 cache (abi/rad_builder.h), K and V as
|
||||
* int8 codes with one f16 scale each per token and head. */
|
||||
RadKVGroupDecl kd{};
|
||||
kd.kind = RAD_KV_FULL;
|
||||
kd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16);
|
||||
kd.n_head_kv = g.n_head_kv;
|
||||
kd.head_dim = g.head_dim;
|
||||
m.kv_full = rad_decl_kv_group(b, nm.f("kv_full"), &kd);
|
||||
if (!m.kv_full) return RAD_E_INVAL;
|
||||
|
||||
RadKVGroupDecl kw = kd;
|
||||
kw.kind = RAD_KV_WINDOW;
|
||||
kw.window = sliding;
|
||||
m.kv_win = rad_decl_kv_group(b, nm.f("kv_win"), &kw);
|
||||
if (!m.kv_win) return RAD_E_INVAL;
|
||||
g.kv_dtype = rad_dtype_name(kd.dtype);
|
||||
|
||||
const int64_t T = g.max_tok, qd = g.q_dim(), kvd = g.kv_dim();
|
||||
|
||||
/* The trunk's stored form, probed from layer 0's q projection: rad_linear.h's trunk_rotation
|
||||
* answers whether it is rotated int8 and how wide the activation codes' scale group is. */
|
||||
m.layers.resize((size_t)g.n_layer);
|
||||
RAD_ARCH_TRY(m.layers[0].attn.q.probe(b, nm, g, nm.f("blk.0.attn_q"),
|
||||
{ nm.ckpt("model.layers.0.self_attn.q_proj.weight") }));
|
||||
{
|
||||
RadEncoding enc{};
|
||||
m.trunk_rot = weight_enc(b, nm.f("blk.0.attn_q.weight"), &enc) &&
|
||||
trunk_rotation(enc, &m.trunk_g8);
|
||||
}
|
||||
|
||||
MoeQ::Config mc{};
|
||||
mc.n_expert_all = n_expert_all;
|
||||
mc.n_expert = n_expert_local;
|
||||
mc.expert_base = n_expert_local * g.rank;
|
||||
mc.probed_expert = mc.expert_base;
|
||||
mc.top_k = top_k;
|
||||
mc.n_ff_exp = m.n_ff_expert;
|
||||
mc.norm_topk = 1;
|
||||
mc.sigmoid_router = 1;
|
||||
mc.route_scale = meta_text_getf(meta, "router_scaling_factor", 1.0);
|
||||
mc.shared_ungated = 1;
|
||||
/* One combine at the gather, not two separately reduced arms: TP2 then matches the TP1
|
||||
* arithmetic (the local routed+shared sum is rounded to bf16 once and the closing
|
||||
* all-reduce reduces it), and that single collective folds into the next block's norm. */
|
||||
mc.shared_fp32_combine = 0;
|
||||
mc.shared_one_external = g.world == 1;
|
||||
mc.router_fuse = 1;
|
||||
mc.rows = T < 2048 ? T : 2048;
|
||||
block_slice_128(m.n_ff_shared, g.world, g.rank, &mc.shared_lo, &mc.shared_hi);
|
||||
mc.n_ff_shared = mc.shared_hi - mc.shared_lo;
|
||||
|
||||
/* ---- the routed experts' stored form, read from the first routed layer's first owned
|
||||
* expert; every layer is declared with it (MoeQ::declare checks each layer's own). */
|
||||
const int64_t l_moe = 2;
|
||||
MoeQ::Src probe_src{};
|
||||
probe_src.experts = nm.ckpt("model.layers.%lld.mlp.experts", (long long)l_moe);
|
||||
RAD_ARCH_TRY(MoeQ::probe(b, nm, (int)l_moe, probe_src, &mc));
|
||||
if (m.trunk_rot && (mc.expert_bf16 || !mc.expert_rot)) {
|
||||
fprintf(stderr, "radiance: flint: the trunk is rotated int8 and the routed experts are "
|
||||
"%s; a rotated trunk's experts read its int8 codes and are stored rotated "
|
||||
"(data/recipes/flint-iq8r.recipe)\n",
|
||||
mc.expert_bf16 ? "plain bf16" : "unrotated");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (!m.trunk_rot && (mc.expert_i8 || mc.expert_iqr)) {
|
||||
fprintf(stderr, "radiance: flint: the routed experts are rotated int8 and the trunk is "
|
||||
"not; they read the trunk's rotated int8 codes, so convert the trunk with "
|
||||
"them (data/recipes/flint-iq8r.recipe)\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
/* ---- activation buffers. A rotated trunk's producers write had_quant_act_i8g's codes and
|
||||
* its linears declare no quantiser: the norms (rmsnorm_had_quant_i8g and, at two ranks, its
|
||||
* all-reduce form) where a loaded library serves them, the attention output (q_attn), and the
|
||||
* gated products (gated_had_quant_i8g). Where the norms are not served, each linear
|
||||
* quantises `h` itself and the experts read `hr`, written once a layer. Any other trunk keeps
|
||||
* both code pairs on `h`: E4M3 for four-bit experts, int8 for a plain int8 linear's own
|
||||
* quantiser. */
|
||||
const bool rot = m.trunk_rot;
|
||||
const int64_t g8 = m.trunk_g8;
|
||||
const bool h_fed = rot && rad_op_declared(b, "rmsnorm_had_quant_i8g") &&
|
||||
(g.world != 2 || rad_op_declared(b, "ar_rmsnorm_had_quant_i8g"));
|
||||
m.x = decl_b(b, nm.f("x"), RAD_BF16, {T, g.n_embd});
|
||||
m.h.x = decl_b(b, nm.f("h"), RAD_BF16, {T, g.n_embd});
|
||||
RAD_ARCH_TRY(m.h.declare_qs(b, nm, g, "h", g.n_embd, 0, true, !h_fed,
|
||||
rot ? g8 : (int64_t)RAD_SCALE_GROUP));
|
||||
m.h.q8_fed = m.h.q8_rot = h_fed;
|
||||
if (rot && !h_fed) {
|
||||
RAD_ARCH_TRY(m.hr.declare_qs(b, nm, g, "moe_hr", g.n_embd, 0, true, false,
|
||||
RAD_SCALE_GROUP));
|
||||
m.hr.q8_fed = m.hr.q8_rot = true;
|
||||
}
|
||||
m.q = decl_b(b, nm.f("attn_q"), RAD_BF16, {T, qd});
|
||||
m.k = decl_b(b, nm.f("attn_k"), RAD_BF16, {T, kvd});
|
||||
m.v = decl_b(b, nm.f("attn_v"), RAD_BF16, {T, kvd});
|
||||
m.attn.x = decl_b(b, nm.f("attn_out"), RAD_BF16, {T, qd});
|
||||
RAD_ARCH_TRY(m.attn.declare_qs(b, nm, g, "attn_out", qd, 0, true, false,
|
||||
rot ? g8 : (int64_t)RAD_SCALE_GROUP));
|
||||
m.attn.q8_fed = m.attn.q8_rot = rot;
|
||||
m.dense_gate_up = decl_b(b, nm.f("dense_gate_up"), RAD_BF16, {T, 2 * g.n_ff});
|
||||
m.dense_ffn.x = decl_b(b, nm.f("dense_ffn"), RAD_BF16, {T, g.n_ff});
|
||||
if (rot)
|
||||
RAD_ARCH_TRY(m.dense_ffn.declare_pair(b, nm, g, "dense_ffn", g.n_ff, 0, true, g8,
|
||||
"gated_had_quant_i8g"));
|
||||
else
|
||||
RAD_ARCH_TRY(m.dense_ffn.declare_qs(b, nm, g, "dense_ffn", g.n_ff, 0, true));
|
||||
m.h_out = decl_b(b, nm.f("h_out"), RAD_BF16, {g.max_logit_rows, g.n_embd});
|
||||
m.logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab});
|
||||
RAD_ARCH_TRY(rad_declare_logits(b, m.logits));
|
||||
|
||||
const int64_t R = T, S = mc.rows * top_k;
|
||||
m.mw.x = m.x;
|
||||
m.mw.h = m.h;
|
||||
m.mw.hr = m.hr;
|
||||
m.mw.logits = decl_b(b, nm.f("moe_logits"), RAD_F32, {R, n_expert_all});
|
||||
m.mw.ids = decl_b(b, nm.f("moe_ids"), RAD_I32, {R, top_k});
|
||||
m.mw.ew = decl_b(b, nm.f("moe_weights"), RAD_F32, {R, top_k});
|
||||
m.mw.eoff = decl_b(b, nm.f("moe_offsets"), RAD_I32, {n_expert_local + 1});
|
||||
m.mw.ecnt = decl_b(b, nm.f("moe_counts"), RAD_I32, {n_expert_local}, RAD_BUF_PERSIST);
|
||||
m.mw.sorted = decl_b(b, nm.f("moe_sorted"), RAD_I32, {S});
|
||||
m.mw.egu = decl_b(b, nm.f("moe_gate_up"), RAD_BF16, {S, 2 * mc.n_ff_exp});
|
||||
m.mw.eff.x = decl_b(b, nm.f("moe_ffn"), RAD_BF16, {S, mc.n_ff_exp});
|
||||
if (rot) {
|
||||
/* The routed arm of a rotated trunk is int8 throughout: the gated product's rotated codes
|
||||
* at one scale a 128 of K, which the grouped GEMM's int8 rows read (MoeQ::a8). */
|
||||
RAD_ARCH_TRY(m.mw.eff.declare_qs(b, nm, g, "moe_ffn", mc.n_ff_exp, S, true, false,
|
||||
RAD_SCALE_GROUP));
|
||||
m.mw.eff.q8_fed = m.mw.eff.q8_rot = true;
|
||||
} else {
|
||||
RAD_ARCH_TRY(m.mw.eff.declare_qs(b, nm, g, "moe_ffn", mc.n_ff_exp, S, true));
|
||||
}
|
||||
m.mw.edn = decl_b(b, nm.f("moe_down"), RAD_BF16, {S, g.n_embd});
|
||||
m.mw.sgu = decl_b(b, nm.f("shared_gate_up"), RAD_BF16, {T, 2 * mc.n_ff_shared});
|
||||
m.mw.sff.x = decl_b(b, nm.f("shared_ffn"), RAD_BF16, {T, mc.n_ff_shared});
|
||||
if (rot) {
|
||||
/* The shared expert's down projection is a trunk linear whose input codes take the group
|
||||
* its own weight is stored at, read from the first routed layer's through that layer's
|
||||
* own LinearQ (which then maps it once). */
|
||||
LinearQ& sd = m.layers[(size_t)l_moe].moe.sh_down;
|
||||
RAD_ARCH_TRY(sd.probe(b, nm, g, nm.f("blk.%lld.ffn_down_shexp", (long long)l_moe),
|
||||
{ nm.ckpt("model.layers.%lld.mlp.shared_expert.down_proj.weight",
|
||||
(long long)l_moe) }));
|
||||
const int64_t sg = sd.probed_i8 ? sd.probed_g8 : g8;
|
||||
RAD_ARCH_TRY(m.mw.sff.declare_pair(b, nm, g, "shared_ffn", mc.n_ff_shared, 0, true, sg,
|
||||
"gated_had_quant_i8g"));
|
||||
} else {
|
||||
RAD_ARCH_TRY(m.mw.sff.declare_qs(b, nm, g, "shared_ffn", mc.n_ff_shared, 0, true));
|
||||
}
|
||||
m.mw.sout = decl_b(b, nm.f("shared_out"), RAD_BF16, {T, g.n_embd});
|
||||
m.mw.sgate = decl_b(b, nm.f("shared_one"), RAD_BF16, {T, 1});
|
||||
if (mc.shared_one_external) {
|
||||
m.shared_one = rw(b, RAD_OP(b, "fill",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", 1),
|
||||
RAD_STR("dtype", g.dtype), RAD_F64("value", 1.0)),
|
||||
RAD_NOWEIGHTS), {}, {m.mw.sgate});
|
||||
if (!m.shared_one) return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
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.token = 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.final_norm = decl_w(b, nm.f("output_norm.weight"), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
m.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.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.token)),
|
||||
{}, {m.x});
|
||||
if (g.world > 1)
|
||||
m.embed_ar = decl_all_reduce_exact(b, g, m.x);
|
||||
|
||||
FlintAttn::Wire aw{};
|
||||
aw.x = m.x; aw.h = m.h; aw.q = m.q; aw.k = m.k; aw.v = m.v; aw.attn = m.attn;
|
||||
MlpQ::Wire dw{};
|
||||
dw.x = m.x; dw.h = m.h; dw.gate_up = m.dense_gate_up; dw.ffn = m.dense_ffn;
|
||||
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
Layer& lay = m.layers[(size_t)l];
|
||||
lay.dense = (l < 2);
|
||||
lay.sliding = !is_full(l);
|
||||
const char* pre = nm.ckpt("model.layers.%lld", (long long)l);
|
||||
|
||||
FlintAttn::Src as{};
|
||||
as.norm = nm.ckpt("%s.input_layernorm.weight", pre);
|
||||
as.q = nm.ckpt("%s.self_attn.q_proj.weight", pre);
|
||||
as.k = nm.ckpt("%s.self_attn.k_proj.weight", pre);
|
||||
as.v = nm.ckpt("%s.self_attn.v_proj.weight", pre);
|
||||
as.q_norm = nm.ckpt("%s.self_attn.q_norm.weight", pre);
|
||||
as.k_norm = nm.ckpt("%s.self_attn.k_norm.weight", pre);
|
||||
as.o = nm.ckpt("%s.self_attn.o_proj.weight", pre);
|
||||
as.sink = nm.ckpt("%s.self_attn.softmax_offset", pre);
|
||||
as.use_rope = lay.sliding;
|
||||
as.window = lay.sliding ? sliding : 0;
|
||||
|
||||
const rad_kvgroup grp = lay.sliding ? m.kv_win : m.kv_full;
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, grp));
|
||||
/* Every block after the first folds the previous block's delta and, at two ranks,
|
||||
* absorbs its all-reduce into its own norm; the last block keeps its add for the plain
|
||||
* final norm and issues its own collective. */
|
||||
const LayerFold f = layer_fold(g, l, g.n_layer, nullptr, 0, false);
|
||||
status = lay.attn.declare(b, nm, g, (int)l, grp, aw, as, f.mix_fold, false, f.mix_ar_in,
|
||||
f.mix_ar_out);
|
||||
if (status < 0) {
|
||||
fprintf(stderr, "radiance: flint: attention layer %lld declaration failed (%d)\n",
|
||||
(long long)l, status);
|
||||
return status;
|
||||
}
|
||||
|
||||
if (lay.dense) {
|
||||
MlpQ::Src ds{};
|
||||
const char* mlp = nm.ckpt("%s.mlp", pre);
|
||||
ds.norm = nm.ckpt("%s.post_attention_layernorm.weight", pre);
|
||||
ds.gate = nm.ckpt("%s.gate_proj.weight", mlp);
|
||||
ds.up = nm.ckpt("%s.up_proj.weight", mlp);
|
||||
ds.down = nm.ckpt("%s.down_proj.weight", mlp);
|
||||
status = lay.dense_mlp.declare(b, nm, g, (int)l, dw, ds, true, f.mlp_add,
|
||||
f.mlp_ar_in, f.mlp_ar_out);
|
||||
if (status < 0) {
|
||||
fprintf(stderr, "radiance: flint: dense layer %lld declaration failed (%d)\n",
|
||||
(long long)l, status);
|
||||
return status;
|
||||
}
|
||||
} else {
|
||||
MoeQ::Src ms{};
|
||||
ms.cfg = mc;
|
||||
const char* mlp = nm.ckpt("%s.mlp", pre);
|
||||
ms.norm = nm.ckpt("%s.post_attention_layernorm.weight", pre);
|
||||
ms.router = nm.ckpt("%s.gate.weight", mlp);
|
||||
/* Flint has no router correction bias. The sigmoid router's bias is
|
||||
* selection-only, so the converter merges a zero [n_expert] tensor under this
|
||||
* name (data/flint-zero-bias.safetensors, `rad-convert --add`). */
|
||||
ms.router_bias = nm.ckpt("%s.expert_bias", mlp);
|
||||
ms.experts = nm.ckpt("%s.experts", mlp);
|
||||
ms.shared = nm.ckpt("%s.shared_expert", mlp);
|
||||
status = lay.moe.declare(b, nm, g, (int)l, m.mw, ms, true, f.mlp_add, f.mlp_ar_in,
|
||||
f.mlp_ar_out);
|
||||
if (status < 0) {
|
||||
fprintf(stderr, "radiance: flint: MoE layer %lld declaration failed (%d)\n",
|
||||
(long long)l, status);
|
||||
return status;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
m.final_rms = 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.final_norm)),
|
||||
{m.x}, {m.h.x});
|
||||
m.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.h.x}, {m.h_out});
|
||||
m.logits_op = 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.lm_head)),
|
||||
{m.h_out}, {m.logits});
|
||||
|
||||
rad_note(b, "Flint: %lld layers (2 dense, 47 top-%lld/%lld sigmoid MoE), %lld/%lld "
|
||||
"attention/KV heads x %lld; expert width %lld, shared %lld, window %lld on %s; "
|
||||
"per-head sink on every layer; %s trunk, %s KV cache",
|
||||
(long long)g.n_layer, (long long)top_k, (long long)n_expert_all,
|
||||
(long long)g.n_head_all, (long long)g.n_head_kv_all, (long long)g.head_dim,
|
||||
(long long)m.n_ff_expert, (long long)mc.n_ff_shared, (long long)sliding,
|
||||
g.world == 2 ? "both cards" : "one card",
|
||||
rot ? (g8 == RAD_I8_GROUP_WIDE ? "IQ8R (rotated int8)" : "rotated int8") : "unrotated",
|
||||
g.kv_dtype);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = g_model[rad_slot(c)];
|
||||
RAD_ISSUE(c, m.embed,
|
||||
praw(batch->token_ids, RAD_I32, batch->n_tok), RAD_W(m.token),
|
||||
brows(m.x, batch->n_tok));
|
||||
if (m.embed_ar)
|
||||
RAD_ISSUE_N(c, m.embed_ar, (int64_t)batch->n_tok * m.g.n_embd,
|
||||
brows(m.x, batch->n_tok), RAD_NONE);
|
||||
|
||||
if (m.shared_one)
|
||||
RAD_ISSUE_N(c, m.shared_one, batch->n_tok, brows(m.mw.sgate, batch->n_tok));
|
||||
for (Layer& layer : m.layers) {
|
||||
layer.attn.step(c, batch);
|
||||
if (layer.dense) layer.dense_mlp.step(c, batch);
|
||||
else layer.moe.step(c, batch);
|
||||
}
|
||||
|
||||
RAD_ISSUE(c, m.final_rms, brows(m.x, batch->n_tok), RAD_W(m.final_norm),
|
||||
brows(m.h.x, batch->n_tok));
|
||||
if (batch->n_out > 0) {
|
||||
RAD_ISSUE_N(c, m.gather, batch->n_out,
|
||||
brows(m.h.x, batch->n_tok), praw(batch->out_ids, RAD_I32, batch->n_out),
|
||||
brows(m.h_out, batch->n_out));
|
||||
RAD_ISSUE_N(c, m.logits_op, batch->n_out,
|
||||
brows(m.h_out, batch->n_out), RAD_W(m.lm_head),
|
||||
brows(m.logits, batch->n_out));
|
||||
}
|
||||
}
|
||||
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
out->draft_depth = 0;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} // namespace flint
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(flint)
|
||||
static const char* const kFlintTriggers[] = { "<tool_call>" };
|
||||
static const RadChatFormat kFlintChatFormat = {
|
||||
.struct_size = sizeof(RadChatFormat),
|
||||
.name = "flint",
|
||||
.reasoning_open = "<think>",
|
||||
.reasoning_close = "</think>",
|
||||
.reasoning_breaks = kFlintTriggers,
|
||||
.n_reasoning_breaks = 1,
|
||||
.reasoning_in_prompt = RAD_CHAT_THINK_FROM_PROMPT,
|
||||
.section_open = nullptr,
|
||||
.section_close = nullptr,
|
||||
.call_separator = nullptr,
|
||||
.call_open = nullptr,
|
||||
.call_close = nullptr,
|
||||
.name_prefix = "<tool_call>",
|
||||
.name_suffix = "",
|
||||
.call_end = "</tool_call>",
|
||||
.arg_prefix = "<arg_key>",
|
||||
.arg_name_suffix = "</arg_key>",
|
||||
.arg_value_prefix = "<arg_value>",
|
||||
.arg_value_suffix = "</arg_value>",
|
||||
.string_value = RAD_CHAT_VALUE_RAW,
|
||||
.other_value = RAD_CHAT_VALUE_JSON,
|
||||
.value_newlines = 1,
|
||||
.triggers = kFlintTriggers,
|
||||
.n_triggers = 1,
|
||||
.args_form = RAD_CHAT_ARGS_TAGGED,
|
||||
};
|
||||
extern "C" const RadChatFormat* rad_arch_chat_format(const RadModelMeta*) {
|
||||
return &kFlintChatFormat;
|
||||
}
|
||||
extern "C" const char* rad_arch_id(void) { return "flint"; }
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
extern "C" const char* rad_arch_quant(void) { return ""; }
|
||||
extern "C" int rad_arch_declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* c) {
|
||||
return flint::declare(b, m, c);
|
||||
}
|
||||
extern "C" void rad_arch_step(struct RadCtx* c, const struct RadBatch* batch) {
|
||||
flint::step(c, batch);
|
||||
}
|
||||
extern "C" uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; }
|
||||
RAD_PLUGIN_ABI_LAYOUT_EXPORT
|
||||
extern "C" const RadPluginInfo* rad_plugin_info(void) {
|
||||
static const RadPluginInfo info = {
|
||||
RAD_PLUGIN_ARCH, "flint", "0.1.0",
|
||||
"Recursive Flint: 2 dense + 47 sigmoid MoE layers, sink attention, 513 window", ""
|
||||
};
|
||||
return &info;
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,264 @@
|
||||
/* flint_attention.h -- Flint's grouped-query attention: per-head Q/K RMSNorm, optional NeoX
|
||||
* RoPE (sliding layers) or no positional encoding (full layers), a learned per-head softmax
|
||||
* sink, a paged bf16 or int8 KV cache, and an optional sliding window.
|
||||
*
|
||||
* Derived from arch/hyv3_common/hyv3_attention.h (the same linears and activation plumbing); the
|
||||
* differences are Flint's:
|
||||
*
|
||||
* - every layer has `self_attn.softmax_offset` (GGUF `attn_sinks`), one learned logit a query
|
||||
* head added to the scaled scores before the softmax;
|
||||
* - the full-attention layers are NoPE, the sliding layers carry NeoX RoPE;
|
||||
* - the sliding layers bound the paged attention with `window` (513).
|
||||
*
|
||||
* The sink and the window ride in attn_paged_sink, which libr4d serves at h128/gqa8 on both
|
||||
* caches. The block's closing all-reduce may be taken by the next block's norm (ar_out).
|
||||
*/
|
||||
#ifndef FLINT_ATTENTION_H
|
||||
#define FLINT_ATTENTION_H
|
||||
|
||||
#include <arch/rad_linear.h>
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct FlintAttn {
|
||||
struct Wire {
|
||||
rad_buf x = 0; /* [max_tok, n_embd] residual stream */
|
||||
ActQ h{}; /* [max_tok, n_embd] normed input, then o output */
|
||||
rad_buf q = 0; /* [max_tok, q_dim], projected, normed and rotated */
|
||||
rad_buf k = 0; /* [max_tok, kv_dim] */
|
||||
rad_buf v = 0; /* [max_tok, kv_dim] */
|
||||
ActQ attn{}; /* [max_tok, q_dim] attention output */
|
||||
};
|
||||
|
||||
struct Src {
|
||||
const char* norm = nullptr;
|
||||
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;
|
||||
/* `self_attn.softmax_offset` (no `.weight` suffix). Null declares no sink. */
|
||||
const char* sink = nullptr;
|
||||
bool use_rope = true;
|
||||
int64_t window = 0; /* 0: full attention */
|
||||
};
|
||||
|
||||
Geom g{};
|
||||
Wire w{};
|
||||
int layer = 0;
|
||||
rad_kvgroup kv = 0;
|
||||
|
||||
rad_weight w_norm = 0, w_q_norm = 0, w_k_norm = 0, w_sink = 0;
|
||||
LinearQ q{}, k{}, v{}, o{};
|
||||
NormQuant nq_h{};
|
||||
QuantAct q_attn{};
|
||||
rad_op op_q_norm = 0, op_k_norm = 0;
|
||||
rad_op op_rope_q = 0, op_rope_k = 0, op_attn = 0, op_kv_store = 0;
|
||||
rad_op op_qkr_store = 0; /* Q/K norms, NeoX rotary (or none) and cache store, decode band */
|
||||
int64_t qkr_rows = 0;
|
||||
rad_op op_ar = 0, op_add = 0;
|
||||
/* The next block's norm absorbs this block's closing all-reduce (NormQuant::fuse_ar), so
|
||||
* this one must not issue it. Counterpart of `ar_in`; both sides ask ar_taken(g, T, ...) on
|
||||
* the same facts, so they agree. */
|
||||
bool ar_out = false;
|
||||
int ar_out_take = kArOutNorm;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup group,
|
||||
const Wire& wire, const Src& src, bool fold = false, bool add_out = true,
|
||||
int ar_in = kArNone, bool ar_out_ = false);
|
||||
bool issues_ar(int64_t T) const { return op_ar && !ar_taken(g, T, ar_out, ar_out_take); }
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
};
|
||||
|
||||
inline int FlintAttn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
rad_kvgroup group, const Wire& wire, const Src& src,
|
||||
bool fold, bool add_out, int ar_in, bool ar_out_) {
|
||||
g = geom;
|
||||
w = wire;
|
||||
layer = l;
|
||||
kv = group;
|
||||
ar_out = ar_out_;
|
||||
const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim();
|
||||
|
||||
if (g.world > g.n_head_kv_all) {
|
||||
fprintf(stderr, "radiance: flint declares no KV row span and cannot serve world_size = %d "
|
||||
"with n_head_kv = %lld\n", 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));
|
||||
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_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_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));
|
||||
if (!w_norm || !w_q_norm || !w_k_norm) return RAD_E_INVAL;
|
||||
|
||||
/* The learned softmax offset, one f32 a query head, sharded with the heads. */
|
||||
if (src.sink) {
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_sinks", l), src.sink));
|
||||
w_sink = decl_w(b, nm.f("blk.%d.attn_sinks", l), RAD_F32, {g.n_head},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
|
||||
if (!w_sink) return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
// As in the other pre-norm blocks, absorb a preceding delta into the residual stream.
|
||||
// The fused kernel normalizes the BF16-rounded sum, not an unrounded FP32 substitute.
|
||||
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(q.declare(b, nm, g, nm.f("blk.%d.attn_q", l), q_dim, g.n_embd,
|
||||
RAD_SHARD_ROW, grp_layer(l), {src.q}, w.h, w.q));
|
||||
RAD_ARCH_TRY(k.declare(b, nm, g, nm.f("blk.%d.attn_k", l), kv_dim, g.n_embd,
|
||||
RAD_SHARD_ROW, grp_layer(l), {src.k}, w.h, w.k));
|
||||
RAD_ARCH_TRY(v.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));
|
||||
|
||||
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_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});
|
||||
if (src.use_rope) {
|
||||
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});
|
||||
}
|
||||
|
||||
const rad_op attn = w_sink
|
||||
? rw(b, RAD_OP(b, "attn_paged_sink",
|
||||
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", src.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_WEIGHTS(w_sink)),
|
||||
{w.q}, {w.attn.x})
|
||||
: 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", src.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});
|
||||
op_attn = 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}, {});
|
||||
|
||||
/* The fused prologue serves the rope layers and, with `rotary_dim` 0, the NoPE ones: the
|
||||
* kernel then only copies the normed head through the rotary stage. Rows exist for the bf16
|
||||
* and the int8 cache (qkv_norm_rope_kv_store_h128_bf16, _i8); prefill heights and libraries
|
||||
* without the fold take the standalone norms, ropes and kv_store. */
|
||||
if (g.head_dim == 128 && !std::strcmp(g.dtype, "bf16") &&
|
||||
(!std::strcmp(g.kv_dtype, "bf16") || !std::strcmp(g.kv_dtype, "i8")) &&
|
||||
!g.rope_mc && g.yarn.factor == 0.0f &&
|
||||
rad_op_declared(b, "qkv_norm_rope_kv_store")) {
|
||||
qkr_rows = qk_fuse_rows(g);
|
||||
op_qkr_store = RAD_OP(b, "qkv_norm_rope_kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qkr_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_F64("theta", g.theta), RAD_F64("eps", g.eps),
|
||||
RAD_F64("scale", g.rope_scale), RAD_STR("mode", "neox"),
|
||||
RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype),
|
||||
RAD_INT("v_norm", 0),
|
||||
RAD_INT("rotary_dim", src.use_rope ? g.head_dim : 0),
|
||||
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));
|
||||
if (!op_qkr_store || !rad_op_resolved(b, op_qkr_store)) op_qkr_store = 0;
|
||||
if (op_qkr_store)
|
||||
op_qkr_store = rw(b, op_qkr_store, {w.q, w.k, w.v}, {w.q, w.k, w.v});
|
||||
}
|
||||
|
||||
/* The out projection's input codes: where the model feeds them (a rotated int8 trunk,
|
||||
* ActQ::q8_fed), q_attn writes had_quant_act_i8g's pair and the projection declares no
|
||||
* quantiser. Otherwise every form the out projection can take reads the bf16 plane or
|
||||
* quantises it itself (LinearQ refuses the E4M3-pair formats), so no quantiser runs here. */
|
||||
if (w.attn.q8_fed) 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 = decl_all_reduce(b, g, 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});
|
||||
/* A rope layer needs either the fused prologue or both standalone rope ops; without this,
|
||||
* step() would silently skip the rotation. */
|
||||
const bool rope_ok = !src.use_rope || op_qkr_store || (op_rope_q && op_rope_k);
|
||||
return op_attn && op_kv_store && rope_ok && (!add_out || op_add) &&
|
||||
(op_qkr_store || (op_q_norm && op_k_norm))
|
||||
? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
inline void FlintAttn::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;
|
||||
|
||||
nq_h.step(c, T);
|
||||
q.step(c, w.h, w.q, T);
|
||||
k.step(c, w.h, w.k, T);
|
||||
v.step(c, w.h, w.v, T);
|
||||
if (op_qkr_store && T <= qkr_rows) {
|
||||
RAD_ISSUE_N(c, op_qkr_store, T, brows(w.q, T), brows(w.k, T), brows(w.v, T),
|
||||
rope_posmc(g, batch, T), RAD_W(w_q_norm), RAD_W(w_k_norm),
|
||||
praw(slot, RAD_I32, T), kv_cache(kv, layer));
|
||||
} else {
|
||||
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));
|
||||
if (op_rope_q) {
|
||||
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));
|
||||
}
|
||||
if (w_sink)
|
||||
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),
|
||||
RAD_W(w_sink), brows(w.attn.x, T));
|
||||
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,
|
||||
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 (issues_ar(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 /* FLINT_ATTENTION_H */
|
||||
+73
-91
@@ -37,9 +37,13 @@
|
||||
*
|
||||
* ============================== WHAT IS QUANTISED ==============================
|
||||
*
|
||||
* Every linear of the language model and of the DiT's blocks is a LinearFP8 (rad_fp8.h), bf16
|
||||
* Every linear of the language model and of the DiT's blocks is a LinearQ (rad_linear.h), bf16
|
||||
* throughout when the first joint block's projection is plain; the embedders, the timestep MLPs,
|
||||
* the modulations, the output layer and the VAE stay bf16.
|
||||
* the modulations, the output layer and the VAE stay bf16. That projection also says whether the
|
||||
* linears are rotated int8 (IQ8R): the activations they read then carry int8 codes in place of the
|
||||
* E4M3 pair, which a block's modulated norm writes in its own pass where a library serves the
|
||||
* rotating twin (rms_mod_had_quant_i8g) and the rotating quantiser behind the plain norm
|
||||
* elsewhere.
|
||||
*
|
||||
* ============================== TENSOR PARALLEL ==============================
|
||||
*
|
||||
@@ -48,13 +52,12 @@
|
||||
* Everything else, the VAE included (its GroupNorm reads the whole picture), runs on every rank.
|
||||
*/
|
||||
#include <arch/rad_arch.h>
|
||||
#include <arch/rad_fp8.h>
|
||||
#include <arch/rad_linear.h>
|
||||
#include <arch/rad_vae2d.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
@@ -98,9 +101,9 @@ enum { kText = 0, kRefs = 1, kImage = 2 };
|
||||
/* ================================================================== the model */
|
||||
struct TeLayer {
|
||||
rad_weight w_n1 = 0, w_n2 = 0, w_qn = 0, w_kn = 0;
|
||||
LinearFP8 qkv{}, o{}, gate_up{}, down{};
|
||||
QuantFP8 q_h{}, q_attn{}, q_h2{};
|
||||
GateQuantFP8 gq{};
|
||||
LinearQ qkv{}, o{}, gate_up{}, down{};
|
||||
QuantAct q_h{}, q_attn{}, q_h2{};
|
||||
GateQuant gq{};
|
||||
rad_op op_n1 = 0, op_qkr = 0, op_attn = 0, op_ar1 = 0, op_add1 = 0;
|
||||
rad_op op_n2 = 0, op_ar2 = 0, op_add2 = 0, op_tap = 0;
|
||||
int tap = -1;
|
||||
@@ -110,9 +113,12 @@ struct TeLayer {
|
||||
* attention and the SwiGLU from the same normed rows, their outputs added. */
|
||||
struct Block {
|
||||
rad_weight w_qn = 0, w_kn = 0;
|
||||
LinearFP8 qkv{}, o{}, ff_in{}, ff_out{};
|
||||
GateQuantFP8 gq{};
|
||||
QuantFP8 q_attn{};
|
||||
LinearQ qkv{}, o{}, ff_in{}, ff_out{};
|
||||
GateQuant gq{};
|
||||
QuantAct q_attn{};
|
||||
/* The normed rows' quantiser for a rotated int8 model whose norm is the unquantised one
|
||||
* (Model::norm_i8 false). */
|
||||
QuantAct q_n{};
|
||||
rad_op op_n = 0, op_qkr = 0, op_attn = 0, op_sum = 0, op_ar = 0;
|
||||
};
|
||||
|
||||
@@ -137,7 +143,7 @@ struct Model {
|
||||
rad_weight w_tok = 0, w_ctx = 0;
|
||||
rad_op op_embed = 0, op_iota = 0, op_ctx = 0, op_store_t = 0;
|
||||
rad_buf b_tx = 0, b_tkv = 0, b_th2 = 0, b_tgu = 0, b_tidx = 0, b_taps = 0, b_ctx = 0;
|
||||
ActFP8 a_th{}, a_tattn{}, a_tffn{};
|
||||
ActQ a_th{}, a_tattn{}, a_tffn{};
|
||||
std::vector<TeLayer> te;
|
||||
|
||||
/* ---- the reference pictures: the encoder, the mode, 2 x 2 tokens, BatchNorm, the embedder */
|
||||
@@ -169,9 +175,17 @@ struct Model {
|
||||
op_gimg = 0, op_nout = 0, op_pout = 0, op_euler = 0;
|
||||
rad_buf b_lat = 0, b_xc = 0, b_h = 0, b_qkv = 0, b_o = 0, b_gu = 0, b_f = 0, b_sum = 0,
|
||||
b_hi = 0, b_fz = 0, b_v = 0;
|
||||
ActFP8 a_hm{}, a_attn{}, a_ffn{};
|
||||
ActQ a_hm{}, a_attn{}, a_ffn{};
|
||||
std::vector<Block> mode[3], single;
|
||||
LinearFP8 qkv0{};
|
||||
LinearQ qkv0{};
|
||||
/* The linears of both networks are rotated int8 (IQ8R, or the 128-group int8 before it), read
|
||||
* off qkv0's probe: the activations then carry int8 code pairs with one scale per (token, `g8`
|
||||
* columns) in place of the E4M3 pair. */
|
||||
bool i8 = false;
|
||||
int64_t g8 = RAD_SCALE_GROUP;
|
||||
/* A block's modulated norm writes those int8 codes in its own pass (rms_mod_had_quant_i8g),
|
||||
* where a library serves it. */
|
||||
bool norm_i8 = false;
|
||||
rad_weight w_pout = 0;
|
||||
|
||||
/* ---- per-image state and conditioning store (PERSIST) */
|
||||
@@ -184,26 +198,7 @@ struct Model {
|
||||
rad_buf b_dl = 0, b_decin = 0, b_cu4 = 0, b_img = 0;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
|
||||
static std::vector<double> meta_list(const RadModelMeta* m, const char* key) {
|
||||
std::vector<double> v;
|
||||
const char* s = rad_meta_gets(m, key, nullptr);
|
||||
while (s && *s) {
|
||||
char* e = nullptr;
|
||||
const double x = std::strtod(s, &e);
|
||||
if (e == s) { ++s; continue; }
|
||||
v.push_back(x);
|
||||
s = e;
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
static rad_weight wcopy(RadBuilder* b, const char* dn, const char* src, uint32_t dtype,
|
||||
std::initializer_list<int64_t> shape, int access, int group) {
|
||||
if (map_copy(b, dn, src) < 0) return 0;
|
||||
return decl_w(b, dn, dtype, shape, access, RAD_SHARD_NONE, grp_layer(group));
|
||||
}
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* A bf16 linear without a bias, read whole on every rank. */
|
||||
static rad_op dense(RadBuilder* b, Names& nm, const char* dn, const char* src, int64_t N, int64_t K,
|
||||
@@ -211,38 +206,7 @@ static rad_op dense(RadBuilder* b, Names& nm, const char* dn, const char* src, i
|
||||
*w = wcopy(b, nm.f("%s.weight", dn), nm.ckpt("%s.weight", src), RAD_BF16, { N, K }, access,
|
||||
group);
|
||||
if (!*w) return 0;
|
||||
return rw(b, 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)),
|
||||
{ in }, { out });
|
||||
}
|
||||
|
||||
static rad_op unary(RadBuilder* b, const char* op, int64_t rows, int64_t n, rad_buf in,
|
||||
rad_buf out) {
|
||||
return rw(b, RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ in }, { out });
|
||||
}
|
||||
|
||||
static rad_op add_op(RadBuilder* b, int64_t rows, int64_t n, rad_buf a, rad_buf c, rad_buf y) {
|
||||
return rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ a, c }, { y });
|
||||
}
|
||||
|
||||
static rad_op all_reduce(RadBuilder* b, const Geom& g, rad_buf x, int64_t rows) {
|
||||
if (g.world <= 1) return 0;
|
||||
return 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", "bf16"), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ x }, { x });
|
||||
return gemm_op(b, rows, N, K, *w, in, out);
|
||||
}
|
||||
|
||||
/* ================================================================== check_format */
|
||||
@@ -276,14 +240,16 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
m.b_tx = decl_b(b, nm.f("te.x"), RAD_BF16, { T, E });
|
||||
m.a_th.x = decl_b(b, nm.f("te.h"), RAD_BF16, { T, E });
|
||||
RAD_ARCH_TRY(m.a_th.declare_qs(b, nm, g, "te.h", E, T));
|
||||
RAD_ARCH_TRY(m.a_th.declare_pair(b, nm, g, "te.h", E, T, m.i8, m.g8, "had_quant_act_i8g"));
|
||||
m.b_tkv = decl_b(b, nm.f("te.qkv"), RAD_BF16, { T, q_dim + 2 * kv_dim });
|
||||
m.a_tattn.x = decl_b(b, nm.f("te.attn"), RAD_BF16, { T, q_dim });
|
||||
RAD_ARCH_TRY(m.a_tattn.declare_qs(b, nm, g, "te.attn", q_dim, T));
|
||||
RAD_ARCH_TRY(m.a_tattn.declare_pair(b, nm, g, "te.attn", q_dim, T, m.i8, m.g8,
|
||||
"had_quant_act_i8g"));
|
||||
m.b_th2 = decl_b(b, nm.f("te.h2"), RAD_BF16, { T, E });
|
||||
m.b_tgu = decl_b(b, nm.f("te.gate_up"), RAD_BF16, { T, 2 * g.n_ff });
|
||||
m.a_tffn.x = decl_b(b, nm.f("te.ffn"), RAD_BF16, { T, g.n_ff });
|
||||
RAD_ARCH_TRY(m.a_tffn.declare_qs(b, nm, g, "te.ffn", g.n_ff, T));
|
||||
RAD_ARCH_TRY(m.a_tffn.declare_pair(b, nm, g, "te.ffn", g.n_ff, T, m.i8, m.g8,
|
||||
"gated_had_quant_i8g"));
|
||||
m.b_taps = decl_b(b, nm.f("te.taps"), RAD_BF16, { T, kNTaps * E });
|
||||
m.b_tidx = decl_b(b, nm.f("te.rows"), RAD_I32, { T });
|
||||
|
||||
@@ -360,7 +326,7 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
RAD_SHARD_COL, grp_layer(l),
|
||||
{ nm.ckpt("%s.self_attn.o_proj.weight", lp) }, m.a_tattn, m.b_th2,
|
||||
T));
|
||||
L.op_ar1 = all_reduce(b, g, m.b_th2, T);
|
||||
L.op_ar1 = decl_all_reduce_tp(b, g, m.b_th2, T);
|
||||
L.op_add1 = add_op(b, T, E, m.b_tx, m.b_th2, m.b_tx);
|
||||
L.op_n2 = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E),
|
||||
@@ -378,7 +344,7 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
RAD_SHARD_COL, grp_layer(l),
|
||||
{ nm.ckpt("%s.mlp.down_proj.weight", lp) }, m.a_tffn, m.b_th2,
|
||||
T));
|
||||
L.op_ar2 = all_reduce(b, g, m.b_th2, T);
|
||||
L.op_ar2 = decl_all_reduce_tp(b, g, m.b_th2, T);
|
||||
L.op_add2 = add_op(b, T, E, m.b_tx, m.b_th2, m.b_tx);
|
||||
if (L.tap >= 0)
|
||||
L.op_tap = rw(b, RAD_OP(b, "gather_rows",
|
||||
@@ -530,11 +496,17 @@ static int declare_block(RadBuilder* b, Model& m, Block& B, const char* pre, con
|
||||
B.w_kn = wcopy(b, nm.f("%s.k_norm.weight", dn), nm.ckpt("%s.attn.norm_k.weight", pre), RAD_F32,
|
||||
{ hd }, RAD_ACCESS_PER_TOKEN, grp);
|
||||
if (!B.w_qn || !B.w_kn) return RAD_E_INVAL;
|
||||
const bool q = !g.w_bf16;
|
||||
/* The norm with the quantiser in it: E4M3 for block-fp8 linears, the rotating int8 twin for
|
||||
* rotated int8 ones where a library serves it. bf16 linears read its bf16 rows, and rotated
|
||||
* int8 ones without the twin quantise those with the rotating quantiser (q_n). */
|
||||
m.norm_i8 = m.i8 && m.a_hm.q8_fed && rad_op_declared(b, "rms_mod_had_quant_i8g") != 0;
|
||||
const bool q = (!g.w_bf16 && !m.i8) || m.norm_i8;
|
||||
auto norm = [&](bool gt) {
|
||||
rad_op op = q ? RAD_OP(b, "rms_mod_quant_fp8",
|
||||
rad_op op = q ? RAD_OP(b, m.norm_i8 ? "rms_mod_had_quant_i8g" : "rms_mod_quant_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", D),
|
||||
RAD_F64("eps", eps), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_F64("eps", eps),
|
||||
RAD_INT("group",
|
||||
m.norm_i8 ? m.g8 : (int64_t)RAD_SCALE_GROUP),
|
||||
RAD_INT("gated", gt ? 1 : 0), RAD_STR("dtype", "bf16"),
|
||||
RAD_STR("norm", "layer")),
|
||||
RAD_NOWEIGHTS)
|
||||
@@ -546,7 +518,7 @@ static int declare_block(RadBuilder* b, Model& m, Block& B, const char* pre, con
|
||||
if (!op) return op;
|
||||
/* The residual, the modulation table and, gated, the branch sum. */
|
||||
rad_buf rd[4] = { m.b_xc, m.b_h, mod, m.b_sum };
|
||||
rad_buf wq[3] = { m.a_hm.q, m.a_hm.s, m.b_h };
|
||||
rad_buf wq[3] = { m.a_hm.cq(), m.a_hm.cs(), m.b_h };
|
||||
rad_buf wb[2] = { m.a_hm.x, m.b_h };
|
||||
rad_op_reads(b, op, rd, gt ? 4 : 3);
|
||||
if (q) rad_op_writes(b, op, wq, 3);
|
||||
@@ -554,6 +526,7 @@ static int declare_block(RadBuilder* b, Model& m, Block& B, const char* pre, con
|
||||
return op;
|
||||
};
|
||||
B.op_n = norm(gated);
|
||||
if (m.i8 && m.a_hm.q8_fed && !m.norm_i8) RAD_ARCH_TRY(B.q_n.declare(b, g, m.a_hm, D));
|
||||
RAD_ARCH_TRY(B.qkv.declare(b, nm, g, nm.f("%s.attn_qkv", dn), 3 * qd, D, RAD_SHARD_ROW,
|
||||
grp_layer(grp),
|
||||
{ nm.ckpt("%s.attn.to_q.weight", pre),
|
||||
@@ -587,7 +560,7 @@ static int declare_block(RadBuilder* b, Model& m, Block& B, const char* pre, con
|
||||
grp_layer(grp), { nm.ckpt("%s.ff.linear_out.weight", pre) },
|
||||
m.a_ffn, m.b_f, rows));
|
||||
B.op_sum = add_op(b, rows, D, m.b_o, m.b_f, m.b_sum);
|
||||
B.op_ar = all_reduce(b, g, m.b_sum, rows);
|
||||
B.op_ar = decl_all_reduce_tp(b, g, m.b_sum, rows);
|
||||
return B.op_n && B.op_qkr && B.op_attn && B.op_sum ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
@@ -728,14 +701,16 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
/* ---- the blocks' buffers */
|
||||
const int64_t qd = g.q_dim();
|
||||
m.a_hm.x = decl_b(b, nm.f("dit.hm"), RAD_BF16, { T, D });
|
||||
RAD_ARCH_TRY(m.a_hm.declare_qs(b, nm, g, "dit.hm", D));
|
||||
RAD_ARCH_TRY(m.a_hm.declare_pair(b, nm, g, "dit.hm", D, 0, m.i8, m.g8, "had_quant_act_i8g"));
|
||||
m.b_qkv = decl_b(b, nm.f("dit.qkv"), RAD_BF16, { T, 3 * qd });
|
||||
m.a_attn.x = decl_b(b, nm.f("dit.attn"), RAD_BF16, { T, qd });
|
||||
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "dit.attn", qd));
|
||||
RAD_ARCH_TRY(m.a_attn.declare_pair(b, nm, g, "dit.attn", qd, 0, m.i8, m.g8,
|
||||
"had_quant_act_i8g"));
|
||||
m.b_o = decl_b(b, nm.f("dit.o"), RAD_BF16, { T, D });
|
||||
m.b_gu = decl_b(b, nm.f("dit.gate_up"), RAD_BF16, { T, 2 * g.n_ff });
|
||||
m.a_ffn.x = decl_b(b, nm.f("dit.ffn"), RAD_BF16, { T, g.n_ff });
|
||||
RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "dit.ffn", g.n_ff));
|
||||
RAD_ARCH_TRY(m.a_ffn.declare_pair(b, nm, g, "dit.ffn", g.n_ff, 0, m.i8, m.g8,
|
||||
"gated_had_quant_i8g"));
|
||||
m.b_f = decl_b(b, nm.f("dit.f"), RAD_BF16, { T, D });
|
||||
m.b_sum = decl_b(b, nm.f("dit.sum"), RAD_BF16, { T, D });
|
||||
|
||||
@@ -895,8 +870,9 @@ static int declare_decoder(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
|
||||
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];
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(check_format(meta));
|
||||
@@ -935,15 +911,19 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
}
|
||||
m.C = rad_meta_geti(meta, "transformer.in_channels", 128);
|
||||
{
|
||||
LinearFP8& probe = m.qkv0;
|
||||
LinearQ& probe = m.qkv0;
|
||||
RAD_ARCH_TRY(probe.probe(b, nm, gd, "dit.single.0.attn_qkv",
|
||||
{ "transformer.single_transformer_blocks.0.attn.to_q.weight",
|
||||
"transformer.single_transformer_blocks.0.attn.to_k.weight",
|
||||
"transformer.single_transformer_blocks.0.attn.to_v.weight" }));
|
||||
RadEncoding e{};
|
||||
const bool plain = weight_enc(b, nm.f("dit.single.0.attn_qkv.weight"), &e) &&
|
||||
rad_enc_is(&e, "plain");
|
||||
const bool known = weight_enc(b, nm.f("dit.single.0.attn_qkv.weight"), &e);
|
||||
const bool plain = known && rad_enc_is(&e, "plain");
|
||||
gd.w_bf16 = m.gt.w_bf16 = plain;
|
||||
/* Or rotated int8 (IQ8R): the activations then carry int8 codes at the weights' scale
|
||||
* group in place of the E4M3 pair (ActQ::declare_pair). */
|
||||
m.i8 = known && (linear_is_w8h(e) || linear_is_wnh(e));
|
||||
if (m.i8) m.g8 = linear_w8h_group(e);
|
||||
}
|
||||
|
||||
const int64_t lane_rows = m.lanes * m.max_img;
|
||||
@@ -1030,7 +1010,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
"+ %zu joint blocks (%lld heads a rank, ff %lld), %s linears",
|
||||
m.gt.rank, m.gt.world, m.flow_map ? " (flow map)" : " base", kTaps[kNTaps - 1],
|
||||
(long long)m.gt.n_layer, m.mode[0].size(), m.single.size(), (long long)gd.n_head,
|
||||
(long long)gd.n_ff, gd.w_bf16 ? "bf16" : "block-fp8");
|
||||
(long long)gd.n_ff, gd.w_bf16 ? "bf16" : m.i8 ? "rotated int8" : "block-fp8");
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -1124,18 +1104,20 @@ static void step_blocks(RadCtx* c, const Model& m, const std::vector<Block>& sta
|
||||
int64_t r0, int64_t R, const RadOperand& acu, const RadOperand& mcu,
|
||||
const RadOperand& s, const RadOperand& gt, const RadOperand& pos) {
|
||||
const Geom& g = m.gd;
|
||||
const int64_t D = g.n_embd, qd = g.q_dim(), nD = D / RAD_FP8_BLOCK;
|
||||
const bool q8 = !g.w_bf16;
|
||||
const int64_t D = g.n_embd, qd = g.q_dim();
|
||||
const bool q8 = (!g.w_bf16 && !m.i8) || m.norm_i8;
|
||||
const RadOperand xv = brow_slice(x, r0, R, D);
|
||||
for (size_t i = 0; i < stack.size(); ++i) {
|
||||
const Block& B = stack[i];
|
||||
const bool gated = i > 0;
|
||||
if (q8)
|
||||
RAD_ISSUE_N(c, B.op_n, R, gated ? brows(m.b_sum, R) : RAD_NONE, gated ? gt : RAD_NONE,
|
||||
s, RAD_NONE, mcu, xv, brows(m.a_hm.q, R), brows(m.a_hm.s, R), RAD_NONE);
|
||||
s, RAD_NONE, mcu, xv, brows(m.a_hm.cq(), R), brows(m.a_hm.cs(), R),
|
||||
RAD_NONE);
|
||||
else
|
||||
RAD_ISSUE_N(c, B.op_n, R, gated ? brows(m.b_sum, R) : RAD_NONE, gated ? gt : RAD_NONE,
|
||||
s, RAD_NONE, mcu, xv, brows(m.a_hm.x, R));
|
||||
B.q_n.step(c, R);
|
||||
B.qkv.step(c, m.a_hm, m.b_qkv, R);
|
||||
RAD_ISSUE_N(c, B.op_qkr, R, brows(m.b_qkv, R), pos, RAD_W(B.w_qn), RAD_W(B.w_kn));
|
||||
RAD_ISSUE_N(c, B.op_attn, R, bcol(m.b_qkv, 0, qd, R), bcol(m.b_qkv, qd, qd, R),
|
||||
@@ -1148,13 +1130,12 @@ static void step_blocks(RadCtx* c, const Model& m, const std::vector<Block>& sta
|
||||
RAD_ISSUE_N(c, B.op_sum, R, brows(m.b_o, R), brows(m.b_f, R), brows(m.b_sum, R));
|
||||
if (B.op_ar) RAD_ISSUE_N(c, B.op_ar, R * D, brows(m.b_sum, R), RAD_NONE);
|
||||
}
|
||||
(void)nD;
|
||||
}
|
||||
|
||||
static void step_denoise(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
const RadGenBatch* G = batch->gen_b;
|
||||
const Geom& g = m.gd;
|
||||
const int64_t N = batch->n_tok, S = batch->n_seq, NI = G->n_img, C = m.C, D = g.n_embd;
|
||||
const int64_t N = batch->n_tok, S = batch->n_seq, NI = G->n_img, D = g.n_embd;
|
||||
const int64_t nt = G->n_mode_h[kText], nr = G->n_mode_h[kRefs];
|
||||
const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, S + 1);
|
||||
const RadOperand icu = praw(G->img_cu, RAD_I32, S + 1);
|
||||
@@ -1233,7 +1214,6 @@ static void step_denoise(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
praw(G->pair, RAD_I32, S), lanes, praw(G->flags, RAD_I32, S),
|
||||
praw(G->seed, RAD_U32, 2 * S), icu, brows(m.b_inp, LR), brows(m.b_mask, LR),
|
||||
brows(m.b_state, LR), brows(m.b_prev, LR));
|
||||
(void)C;
|
||||
}
|
||||
|
||||
static void step_decode(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
@@ -1254,7 +1234,7 @@ static void step_decode(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
if (!batch->gen || !batch->gen_b) {
|
||||
rad_step_fail(c, "flux3 is an image generator and runs generator passes only");
|
||||
return;
|
||||
@@ -1283,6 +1263,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
/* One more level of expansion so `#NS` sees the expanded namespace. */
|
||||
#define FLUX3_PROBE_X(NS) RAD_ARCH_PROBE(NS)
|
||||
#define FLUX3_PLUGIN_X(NS, ...) RAD_ARCH_PLUGIN(NS, __VA_ARGS__)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
FLUX3_PROBE_X(FLUX3_NS)
|
||||
FLUX3_PLUGIN_X(FLUX3_NS, FLUX3_ID, "", "0.1.0",
|
||||
"FLUX.3 [klein] and its base: Qwen3-VL-4B's stacked layers, a 5.6B three-mode "
|
||||
|
||||
+81
-741
File diff suppressed because it is too large.
Load diff
Loaded 100 of 1562 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user