Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fe12b49a61 | ||
|
|
d32d8deccf | ||
|
|
d5b10559f0 | ||
|
|
595102bf7b | ||
|
|
dd344cf17c | ||
|
|
7e0985ef9d | ||
|
|
f66f75e9ea | ||
|
|
7e8e015dae | ||
|
|
ee6b9642bf | ||
|
|
adfca9234c | ||
|
|
02975e668b | ||
|
|
56b9791753 | ||
|
|
15fd4b5e10 | ||
|
|
855c1b0726 | ||
|
|
118dd45e4d | ||
|
|
513226567c | ||
|
|
f2dc8aeff7 | ||
|
|
a40249a894 | ||
|
|
1aaee32d0b | ||
|
|
a7f6d4482f | ||
|
|
987c59e8a7 | ||
|
|
28cfbd6974 | ||
|
|
19546db926 | ||
|
|
08589fcb1c | ||
|
|
a529b005c2 | ||
|
|
9f217df19e | ||
|
|
19e4ae57e0 | ||
|
|
a636686c16 | ||
|
|
e595da84bd | ||
|
|
5fb7c39267 | ||
|
|
4283e7b7d0 | ||
|
|
455b2874ad | ||
|
|
b303ac3faa | ||
|
|
6f85b375d9 | ||
|
|
f64eaa9962 | ||
|
|
cc0fefe624 | ||
|
|
e21e4a1d7e | ||
|
|
27c870b549 | ||
|
|
16893665cf | ||
|
|
06b90808f2 | ||
|
|
36cc0e749f | ||
|
|
a3b8fac5a1 | ||
|
|
684d6e13f1 | ||
|
|
7e52c2fa25 | ||
|
|
b37f6ec221 | ||
|
|
73ccefecbc | ||
|
|
d32e6286aa | ||
|
|
f85b5f3209 | ||
|
|
6e7fe0ce40 | ||
|
|
29e39e65ce | ||
|
|
12cc475c2a | ||
|
|
4ea33d5f24 | ||
|
|
81e0af07d5 | ||
|
|
256fe0a4bf | ||
|
|
c5bb8e006e | ||
|
|
67b6e043b8 | ||
|
|
1db7c36149 | ||
|
|
9ffda189a1 | ||
|
|
82ed9c8b38 | ||
|
|
1fc87db33e | ||
|
|
8784fcbc7a | ||
|
|
e06ad291de | ||
|
|
f002c80bb5 | ||
|
|
929b0963b4 | ||
|
|
477e03a1c6 | ||
|
|
5991ea27ef | ||
|
|
6e6279bf5b | ||
|
|
47219977dc | ||
|
|
dc9a6f42cb | ||
|
|
5eaf31a0e1 | ||
|
|
b787d6b35d | ||
|
|
b2300f280c | ||
|
|
ab63bf3fef | ||
|
|
c642e6fd51 | ||
|
|
678307c8d0 | ||
|
|
f08cd442e0 | ||
|
|
4a754ada7f | ||
|
|
fefede8393 | ||
|
|
379622714f | ||
|
|
966d8de89b | ||
|
|
43dc10921d | ||
|
|
2803ae4342 | ||
|
|
a15e78ede5 | ||
|
|
8dca69a982 | ||
|
|
1937f4169b | ||
|
|
d26714d672 | ||
|
|
4d4f9f2555 | ||
|
|
8cf592c230 | ||
|
|
55b005b5e2 | ||
|
|
978bc2edf5 | ||
|
|
fed876f725 | ||
|
|
4392c4f1a6 | ||
|
|
4d815b6972 | ||
|
|
5f08dfee72 | ||
|
|
6ffd1de942 | ||
|
|
95ba2c67bd | ||
|
|
e0a3257324 | ||
|
|
a09aa7ebf1 | ||
|
|
c2bc1faf40 | ||
|
|
32d67b6ae7 | ||
|
|
28d1ec0cbe | ||
|
|
0a8b9b6207 | ||
|
|
3ca81538d3 | ||
|
|
6e014a36e1 | ||
|
|
d8af833a54 | ||
|
|
9a14832c88 | ||
|
|
3b13fd3266 | ||
|
|
b16685e06b | ||
|
|
62b7f51c3b | ||
|
|
6b13b0624e | ||
|
|
be9bcf820d | ||
|
|
8c5b601ad1 | ||
|
|
3ade1e25fe | ||
|
|
74ed3ef8b4 | ||
|
|
a32d0dd71c | ||
|
|
1c104de400 | ||
|
|
17b556d9f5 | ||
|
|
5d4431b8a3 | ||
|
|
ff19013a3d | ||
|
|
267aed6a6c | ||
|
|
5e0cd1e29a | ||
|
|
db547d66d5 | ||
|
|
88b5a04acb | ||
|
|
aac92d7ac7 | ||
|
|
a8c8066d26 | ||
|
|
e4f2d2a6eb | ||
|
|
7a116d6538 | ||
|
|
4cc7ecf24e | ||
|
|
a08bf20d8d | ||
|
|
e476d8d6d0 | ||
|
|
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 |
No files matched your search
+26
-2
@@ -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 2.2.0 LANGUAGES C CXX)
|
||||
project(radiance VERSION 2.4.1 LANGUAGES C CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 20)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
@@ -199,8 +199,19 @@ endif()
|
||||
# License 1.0 (data/vectors/LICENSE.qwen-community-1.0.txt, NOTICE); radiance's Apache-2.0 grant
|
||||
# covers the code that reads them, never the file. It ships loaded only when the deployment asks
|
||||
# (--control-vector), and the request default is off, because what it removes is a safety behaviour.
|
||||
# Inkling2's vector ships the same way, and is the one measured in docs/GUIDE.md 4.10 for that
|
||||
# arch: grenforcer's published directions (huggingface.co/grenforcer/Kintsugi-Inkling-2-Mini-control-vector,
|
||||
# the `refusal-inkling2-late` pack), stored unit-normalised and remapped from their visit view
|
||||
# (direction.30..47 -> physical layers 6..23, which is what 2.3's loader validates against the
|
||||
# physical count). gguf sha256 9d83085565cffb9f..., json dc0cf696597f7636.... No license is stated
|
||||
# at the source as of shipping; the directions are derived from Kintsugi's Inkling-2-Mini, and
|
||||
# radiance's Apache-2.0 grant covers the reader, not the file. Measured greedy on the shipped
|
||||
# iq4r container, 50 harmful / 50 harmless, substitution counted as refusal: harmful delivered
|
||||
# 49/50 (stock 0/50), harmless 47/50 (stock 43/50); within-boot KL mean 0.42, median 0.007. It
|
||||
# ships loaded only when the deployment asks, and the request default is off.
|
||||
file(MAKE_DIRECTORY ${RAD_PLUGIN_OUT}/vectors)
|
||||
foreach(rrad_vector qwen4exp-control-vector.gguf qwen4exp-control-vector.json)
|
||||
foreach(rrad_vector qwen4exp-control-vector.gguf qwen4exp-control-vector.json
|
||||
inkling2-control-vector.gguf inkling2-control-vector.json)
|
||||
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/data/vectors/${rrad_vector}
|
||||
${RAD_PLUGIN_OUT}/vectors/${rrad_vector} COPYONLY)
|
||||
install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/data/vectors/${rrad_vector}
|
||||
@@ -325,6 +336,19 @@ 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()
|
||||
|
||||
+24
-12
@@ -46,7 +46,7 @@ ARG FFMPEG_VERSION=8.1.3
|
||||
ARG FFMPEG_SHA256=7138d28c96d9d3e3af4ee3d8cad72741f8ffb40da90c1112235dea3ecd3178a3
|
||||
|
||||
# ----------------------------------------------------------------------------------------- ffmpeg
|
||||
FROM ubuntu:${UBUNTU_VERSION} AS ffmpeg
|
||||
FROM docker.io/ubuntu:${UBUNTU_VERSION} AS ffmpeg
|
||||
ARG FFMPEG_VERSION
|
||||
ARG FFMPEG_SHA256
|
||||
ARG JOBS=
|
||||
@@ -86,7 +86,7 @@ RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
|
||||
> /opt/ffmpeg/share/doc/ffmpeg/SOURCE
|
||||
|
||||
# ------------------------------------------------------------------------------------------- llvm
|
||||
FROM rocm/dev-ubuntu-${UBUNTU_VERSION}:${ROCM_VERSION} AS llvm
|
||||
FROM docker.io/rocm/dev-ubuntu-${UBUNTU_VERSION}:${ROCM_VERSION} AS llvm
|
||||
ARG JOBS=
|
||||
# clang, lld and the offload tools all load lib/llvm/lib/libLLVM.so, so this stage rebuilds only
|
||||
# that file: ROCm's llvm-project at exactly the commit `clang --version` names (the stage stops if
|
||||
@@ -126,17 +126,13 @@ RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
|
||||
-DCMAKE_C_COMPILER=$L/bin/clang -DCMAKE_CXX_COMPILER=$L/bin/clang++ > /tmp/llvm-configure.log 2>&1 \
|
||||
|| { tail -40 /tmp/llvm-configure.log >&2; exit 1; }; \
|
||||
ninja -C /build-llvm ${JOBS:+-j${JOBS}} LLVM > /tmp/llvm-build.log 2>&1 \
|
||||
|| { grep -m20 -B2 -A8 'error' /tmp/llvm-build.log >&2; exit 1; }; \
|
||||
|| { tail -40 /tmp/llvm-build.log >&2; exit 1; }; \
|
||||
so=$(basename $(readlink -f $L/lib/libLLVM.so)); \
|
||||
mkdir -p /out; cp /build-llvm/lib/$so /out/; \
|
||||
rm -rf /build-llvm /llvm-project
|
||||
|
||||
# ------------------------------------------------------------------------------------------ build
|
||||
FROM rocm/dev-ubuntu-${UBUNTU_VERSION}:${ROCM_VERSION} AS build
|
||||
ARG GPU_TARGETS="gfx1201;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=
|
||||
FROM docker.io/rocm/dev-ubuntu-${UBUNTU_VERSION}:${ROCM_VERSION} AS build
|
||||
|
||||
# g++-14 rather than the default 13: hipcc compiles device-side translation units against its
|
||||
# libstdc++, which is also the runtime image's. gawk: tools/ops_doc_check.sh uses gensub, which
|
||||
@@ -147,7 +143,7 @@ ARG JOBS=
|
||||
RUN apt-get update \
|
||||
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
|
||||
cmake ninja-build pkg-config g++-14 gawk libdav1d7 libwebp7 libopenh264-7 busybox-static \
|
||||
libopenblas-dev \
|
||||
libopenblas-dev ccache \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY --from=ffmpeg /opt/ffmpeg /opt/ffmpeg
|
||||
@@ -188,18 +184,34 @@ RUN set -e; R=/opt/rocm; D=/opt/rocm-repeatable; L=lib/llvm; \
|
||||
WORKDIR /src
|
||||
COPY . .
|
||||
|
||||
# Declared after COPY so changing -t or -j keeps the layers above.
|
||||
ARG GPU_TARGETS="gfx1201;gfx12-generic;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=
|
||||
|
||||
# The prefix is fixed at configure time because the default $RADIANCE_HOME is compiled in as
|
||||
# <prefix>/share/radiance; DESTDIR stages the tree without moving that default.
|
||||
# oom_score_adj 1000: on a host that is also serving, the OOM killer takes the compiler first.
|
||||
RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
|
||||
cmake -S . -B /build -G Ninja \
|
||||
# ccache: /build starts empty in every build (any source change re-runs this layer), so only a
|
||||
# content-keyed cache keeps the compiles. The rebuilt libLLVM is part of the key, so a VOPD or ROCm
|
||||
# change starts clean.
|
||||
RUN --mount=type=cache,id=radiance-ccache,target=/ccache \
|
||||
echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
|
||||
export CCACHE_DIR=/ccache CCACHE_MAXSIZE=30G CCACHE_DEPEND=1 \
|
||||
CCACHE_EXTRAFILES=/opt/rocm-repeatable/lib/llvm/lib/$(basename $(readlink -f /opt/rocm/lib/llvm/lib/libLLVM.so)); \
|
||||
ccache -z > /dev/null \
|
||||
&& cmake -S . -B /build -G Ninja \
|
||||
-DCMAKE_INSTALL_PREFIX=/opt/radiance \
|
||||
-DRAD_WITH_HIP=ON -DRAD_WITH_FFMPEG=ON \
|
||||
"-DRAD_GPU_TARGETS=${GPU_TARGETS}" \
|
||||
-DCMAKE_HIP_COMPILER=/opt/rocm-repeatable/lib/llvm/bin/clang++ -DCMAKE_HIP_COMPILER_ROCM_ROOT=/opt/rocm \
|
||||
-DCMAKE_HIP_FLAGS=--rocm-path=/opt/rocm \
|
||||
-DRAD_HIP_VOPD_REPEATABLE=ON \
|
||||
-DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache \
|
||||
-DCMAKE_HIP_COMPILER_LAUNCHER=ccache \
|
||||
&& cmake --build /build ${JOBS:+-j${JOBS}} \
|
||||
&& ccache -s \
|
||||
&& DESTDIR=/stage cmake --install /build \
|
||||
&& mkdir -p /stage/opt/radiance/share/radiance/recipes \
|
||||
&& cp data/recipes/*.recipe /stage/opt/radiance/share/radiance/recipes/
|
||||
@@ -286,7 +298,7 @@ RUN set -e; R=/rootfs; L=$R/usr/lib/x86_64-linux-gnu; \
|
||||
|
||||
# ---------------------------------------------------------------------------------------- runtime
|
||||
FROM scratch AS runtime
|
||||
ARG GPU_TARGETS="gfx1201;gfx11-generic;gfx1151"
|
||||
ARG GPU_TARGETS="gfx1201;gfx12-generic;gfx11-generic;gfx1151"
|
||||
ARG VERSION=dev
|
||||
ARG REVISION=unknown
|
||||
|
||||
|
||||
@@ -35,7 +35,11 @@ Written by Deadcode, with contributions from:
|
||||
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
|
||||
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, and EXL3-V3 routed experts for Qwen3.5 MoE and Gemma 4 MoE
|
||||
(qwen35moe_exl3 with mad codebook, MTP head and vision tower; gemma4_exl3) and libr4d's 16-row
|
||||
paged MLA prefill attention row and bench mode
|
||||
- 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
|
||||
@@ -57,7 +61,7 @@ Written by Deadcode, with contributions from:
|
||||
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
|
||||
(--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
|
||||
@@ -75,7 +79,10 @@ Written by Deadcode, with contributions from:
|
||||
(--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 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
|
||||
@@ -90,14 +97,15 @@ Written by Deadcode, with contributions from:
|
||||
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
|
||||
short block under load, a block drafter's window carried in the window snapshot, window snapshots
|
||||
from short prompts, and calibration Gram tap scratch zeroing before the first sum
|
||||
- redxherring: --model taking a Hugging Face repo id
|
||||
- Smellyyyy: the idea behind --prefill-interleave
|
||||
- gearwave00001: /v1/messages as Claude Code sends it
|
||||
- devmilan: the NVFP4 and FP8 compressed-tensors imports
|
||||
- sfjes: Gemma 4 31B dense -- its plugin, its two attention classes and their kernels, and prefix
|
||||
reuse that leaves a windowed group alone -- and --host-headroom-mib
|
||||
reuse that leaves a windowed group alone -- and --host-headroom-mib, and fleet virtual IDs
|
||||
(models entry with pool: routing to a resident member)
|
||||
- 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
|
||||
@@ -124,9 +132,11 @@ Written by Deadcode, with contributions from:
|
||||
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
|
||||
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
|
||||
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
|
||||
@@ -144,11 +154,12 @@ Written by Deadcode, with contributions from:
|
||||
- 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
|
||||
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, and the mapped tier kept in the page
|
||||
cache across a load
|
||||
cache across a load, and Inkling 2's hc=1 control vector and shipped vector file
|
||||
- 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), and the
|
||||
diagnosis of the expert loan held at zero by leftover cache blocks
|
||||
@@ -165,9 +176,18 @@ Written by Deadcode, with contributions from:
|
||||
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)
|
||||
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, and ERNIE-5.5-Flash-Preview (arch/ernie55: trunk, MXFP4 experts,
|
||||
DSpark, TP3 EP, WMMA prefill and optional block-FP8 trunk) and keeping the heat engine swapping
|
||||
behind staged prefill passes
|
||||
- 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, and
|
||||
Meta Muse Glimmer 30B -- the museglimmer plugins, its windowed vision tower, its DFlash drafter,
|
||||
@@ -184,7 +204,9 @@ Written by Deadcode, with contributions from:
|
||||
- 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
|
||||
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, and deepseek41's image-span router bias declared only when images are served
|
||||
- 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
|
||||
@@ -199,7 +221,8 @@ Written by Deadcode, with contributions from:
|
||||
- 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
|
||||
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)
|
||||
@@ -211,13 +234,17 @@ Written by Deadcode, with contributions from:
|
||||
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
|
||||
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
|
||||
- Kezi: the decode tile arms of the int4 and int5 x int8 GEMM, draft trees for Qwen3.8-27B's
|
||||
DFlash2 drafts (the tree verify rows and the gdn fold), and sweeping unreachable KV cache entries
|
||||
(#653)
|
||||
- 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
|
||||
@@ -225,19 +252,71 @@ Written by Deadcode, with contributions from:
|
||||
- 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)
|
||||
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
|
||||
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, and live per-request control-vector slots
|
||||
(additive steering, Qwen3.5/Gemma 4 wiring and 2-slot stacking), Qwen3-VL dense W4A8 text and
|
||||
vision with request-owned DeepStack, and MiniMax-H3's rotated W4A8 denoiser projections and audio
|
||||
encoder fixes
|
||||
- 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
|
||||
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
|
||||
- jintakhan: gemma4_bf16's sliding-window attention ported to gemma4
|
||||
whitespace, and LTX-2's chunk ceiling raised to 40
|
||||
- jintakhan: gemma4_bf16's sliding-window attention ported to gemma4, Gemma 4 MoE's IQR trunk and
|
||||
full IQR expert arm, the IQ8R-V4 recipe, Google's assistant MTP drafter, and CMAKE_ARGS in
|
||||
build.sh
|
||||
- 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 multi-instance serving (rad_arch_multi_instance), the token
|
||||
table as a Lloyd codebook (embed_tq), gfx12-generic support for exl3i/exl3r4d and the Docker
|
||||
image, and Docker build job/logging/base-image hardening
|
||||
- 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
|
||||
- squarecylinder: libhalo serving the whole gfx11 family (RDNA 3 / 3.5 including gfx1100), IQR
|
||||
prefill 128-token tile, IQ8R 256-wide GDN decode fold and h256 mixed-step scratch fix; libr3d's
|
||||
mla_attn_paged prefill arm and radix sample_topk; and band tables built from winning plugins
|
||||
- HumbleTurtle: rotated 4-bit and 6-bit KV cache (i4r, i6r), --kv-host-tokens, and /v1/messages
|
||||
taking the chat path's priority
|
||||
- iwinux: MOSS-Image (arch/mossimage, FLUX.2 VAE decoder block, flow-matching schedule lower bound,
|
||||
odd-width group_norm, and bf16/IQ8R/LoRA recipes)
|
||||
- testeddoughnut: Inkling 2 Mini on Strix Halo in libhalo (attn_paged_rel with WMMA prefill and
|
||||
verify, attn_res_mix, sconv_res, l2_clip, situ_mul, grid_embed_hw, int8 embedding in place,
|
||||
pitched RoPE) and Inkling 2's content_close chat format
|
||||
- Tangenius: Inkling 2 relative-attention performance work in libr4d (compact long verify,
|
||||
direct-fragment variants, wider splits, mixed-pass WMMA keying, moe_gather_inv sort slot table)
|
||||
and Docker ccache cache mounts
|
||||
- Spizzerp: RADIANCE_REL_COMPACT_MIN for single-sequence long verify compact bands
|
||||
- AustinM731: GLM-5.3-Flash native serial MTP on IQ8R trunk with IQR experts, and scheduler
|
||||
history_end linear-state snapshots for chat prompts
|
||||
- posta: opt-in scheduler.swap-hold for busy models, and accurate prompt counts and preempted_ms
|
||||
in timings across preemptions
|
||||
- AmySkippy: Qwen3 BF16 retrieval support and experimental FFN IQ8R
|
||||
- DominBear: build and runtime fixes for AMD CDNA1 (gfx908, Instinct MI100)
|
||||
|
||||
This product includes software from the following projects, each under the MIT License. The
|
||||
license text is in the file named beside each.
|
||||
@@ -300,3 +379,24 @@ 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
|
||||
-------------
|
||||
|
||||
plugin/exl3i's routed-expert rows (moe_exl3_gate_up / moe_exl3_down) derive from radiance-exl3
|
||||
(Copyright 2026 Dylan Johnston, Apache-2.0, imported from mikoskinen/r9700-exact-serving; its EXL3
|
||||
decode is a transcription of exllamav3's, Copyright (c) 2025 Turboderp, MIT License): the op
|
||||
contract (plugin/exl3import/include/exl3i_moe_abi.h), the host reference (plugin/exl3i/moe_ref.c),
|
||||
the device rows (plugin/exl3i/exl3i_moe.hip.h and moe.c), and the routed block's exl3i wiring
|
||||
(arch/common/rad_block_moe_q.h's declare_exl3i / issue_exl3i).
|
||||
|
||||
|
||||
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.
|
||||
@@ -1,431 +1,167 @@
|
||||
# radiance
|
||||
|
||||
An inference server for AMD GPUs, in C++ and HIP: language models, and image, video, speech and
|
||||
music generation. Its HTTP API speaks OpenAI's chat, completions, Responses, images, audio and video
|
||||
APIs, Anthropic's Messages API and llama-server's native one, so their clients and SDKs work
|
||||
unchanged. Model architectures, kernel libraries and quantisers are `.so` plugins; the ones in this
|
||||
tree are built and loaded the same way a third party's are ([`docs/PLUGIN.md`](docs/PLUGIN.md)).
|
||||
An inference server for AMD GPUs written in C++20 and HIP. It serves language and vision-language models, embeddings, rerankers, speech recognition, text-to-speech, music, image, video and 3D generation behind one process and one port.
|
||||
|
||||
The bundled device kernels target AMD RDNA4 (`libr4d`: `gfx1200`, `gfx1201`), RDNA3 (`libr3d`:
|
||||
`gfx11xx`) and Strix Halo (`libhalo`: `gfx1151`). 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,
|
||||
Qwen3-ASR, the 0.8B-3B models) at interactive speed on a desktop CPU, the 27B and larger far more
|
||||
slowly than a card.
|
||||
Its HTTP and WebSocket API speaks OpenAI (`/v1/chat/completions`, `/v1/completions`, `/v1/responses`, `/v1/embeddings`, `/v1/images/*`, `/v1/audio/*`, `/v1/videos`, `/v1/realtime`), Anthropic (`/v1/messages`), vLLM (`/v1/rerank`, `/metrics`, `/tokenize`) and llama-server (`/completion`, `/infill`, `/props`). Architectures, kernel libraries and quantisers are `.so` plugins using a stable C ABI ([`docs/PLUGIN.md`](docs/PLUGIN.md)).
|
||||
|
||||
To support the development of radiance: [Patreon](https://patreon.com/StillDeadCode).
|
||||
**Hardware support:**
|
||||
- **AMD RDNA4** (`gfx1200`, `gfx1201`, `gfx12-generic`): `libr4d`, plus `plugin/exl3i` (EXL3-V3 trellis linears) and `plugin/glm`.
|
||||
- **AMD RDNA3 / 3.5** (`gfx11xx`, `gfx11-generic`, Strix Halo `gfx1151`): `libhalo` (WMMA) and `libr3d`.
|
||||
- **CPU (x86-64)**: `libavx` (AVX-512 / AVX2+FMA / AVX / scalar) serves every model without a GPU.
|
||||
|
||||
## Models
|
||||
Support development on [Patreon](https://patreon.com/StillDeadCode).
|
||||
|
||||
| model | container | get it | fleet file |
|
||||
|---|---|---|---|
|
||||
| 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` |
|
||||
| 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-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) |
|
||||
| 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-bf16.rad` (8.3 GiB) | [convert](#convert-a-checkpoint) | — |
|
||||
| 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` |
|
||||
| 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) | — |
|
||||
| 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) | — |
|
||||
| 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) | `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` |
|
||||
---
|
||||
|
||||
**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,
|
||||
NVIDIA-Nemotron-3.5-Bolt-74B-A9B, GLM-5.3-Flash, Ling-3.0-flash-Sante, Fish Audio drama-3 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) serves without the drafter
|
||||
under `num-speculative-tokens: 0`.
|
||||
## Quick Start (Docker)
|
||||
|
||||
A container holds everything the server needs: the weights, the tokeniser, the chat template and
|
||||
any drafter. Each download link's repository has the recipe and the exact command that made the
|
||||
file. Download one into your models directory (the transfer resumes if interrupted):
|
||||
The host needs Docker and an `amdgpu` kernel driver supporting ROCm 10.1 (no host ROCm install required). Enable **Above 4G Decoding** and **Resizable BAR** in firmware for full performance.
|
||||
|
||||
```sh
|
||||
mkdir -p /srv/models/rad && cd /srv/models/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
|
||||
repository has the recipe and the calibration step. To convert Google's bf16 checkpoint yourself,
|
||||
`data/recipes/gemma4-31b-dense-bf16-w4a8.recipe` quantises without calibration (round-to-nearest
|
||||
with a scale search, bf16 lm_head); see [Convert a checkpoint](#convert-a-checkpoint). On two R9700s
|
||||
that container decodes at 103 tok/s on prose and 141 on code, against 112 and 150 for keptn42's,
|
||||
and accepts 0.46 of its drafts on prose against 0.50.
|
||||
|
||||
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. 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
|
||||
about 68 s with FastH3 and 8.8 minutes at MiniMax-H3's 50 steps; both read about 39 GiB of pinned
|
||||
host memory. With LBH-123-AI's latent upscaler in the container, `"latent_upscale": 2` runs the first
|
||||
steps at half the size and refines at the full size: MiniMax-H3's clip then takes 3.4 minutes
|
||||
(docs/GUIDE.md §5.16). A ComfyUI node, `integrations/comfyui/ComfyUI-Radiance-MiniMax`, renders
|
||||
through `/v1/videos` from a ComfyUI graph as a client of the server. MiniMax-H3's license, which
|
||||
FastH3 carries, does not cover the EU, the UK, the Republic of Korea or the USA.
|
||||
|
||||
MiniMax-Music3 and Breeze-TTS-2 answer `/v1/audio/speech`, whole or streamed as they are made: a song
|
||||
from lyrics and a description, 44.1 kHz stereo, made at about the speed it plays on two cards; and
|
||||
speech in a voice the request describes, made in 0.6 of its playing time on one card, its first
|
||||
streamed audio 0.21 s after the request. Breeze-TTS-2 also speaks text while it is being written,
|
||||
over the `/v1/audio/speech/stream` WebSocket; it is licensed for research and non-commercial use
|
||||
only. Fish Audio's drama-3 speaks a script whose speakers and direction are written in it
|
||||
(`<|speaker:1|>`, `[laughs]`), each speaker in the model's voice or one cloned from a reference
|
||||
clip and its transcript, at 0.3 of its playing time on two cards, its first streamed audio
|
||||
0.23 s after the request; under the Fish Audio Community License a service that lets others
|
||||
generate speech with it needs a licence from Fish Audio, and imitating a real person's voice needs
|
||||
their consent.
|
||||
|
||||
## Run with Docker
|
||||
|
||||
The host needs Docker and an `amdgpu` driver that supports ROCm 10.1; it does not need ROCm. The
|
||||
card works best with Resizable BAR on (Above 4G Decoding and Resizable BAR in the firmware setup);
|
||||
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` (RDNA4), `gfx11-generic` (RDNA3) and `gfx1151` (Strix Halo). Pull it, clone
|
||||
this repository for its compose files, then start one of them:
|
||||
The [`stilldeadcode/radiance`](https://hub.docker.com/r/stilldeadcode/radiance) image bundles kernels for `gfx1201`, `gfx12-generic`, `gfx11-generic` and `gfx1151`:
|
||||
|
||||
```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 tp2.yaml up -d # two cards; tp1.yaml for one (RADIANCE_GPU)
|
||||
docker compose -f tp2.yaml logs -f
|
||||
docker compose -f tp2.yaml down
|
||||
cp .env.example .env # set RADIANCE_MODELS, RADIANCE_API_KEY, device GIDs
|
||||
docker compose -f tp2.yaml up -d # tp1.yaml for 1 card, tp2.yaml for 2, tp4.yaml for 4
|
||||
```
|
||||
|
||||
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` and `tp2.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).
|
||||
Each compose file serves multiple models behind one port, loading and swapping them on demand ([`docs/MULTIMODEL.md`](docs/MULTIMODEL.md)). Edit the matching `tp*.radiance.yaml` to keep only the models you have. See [`docs/DOCKER.md`](docs/DOCKER.md) for standalone `docker run` and custom `docker/build.sh` targets.
|
||||
|
||||
To build the image yourself, for example for other cards, run `docker/build.sh -t 'gfx1200;gfx1201'`
|
||||
in the clone (it needs `docker buildx` and tests the build as it goes). Then set
|
||||
`RADIANCE_IMAGE=radiance:latest` in `.env`.
|
||||
|
||||
## Build from source
|
||||
|
||||
You need Linux, git, a C++20 compiler, CMake 3.21+ and Ninja. For the device kernels you also need
|
||||
ROCm 10.1 or 7.2 (`hipcc`; set `ROCM_PATH` if it is not `/opt/rocm`). Clone the repository and
|
||||
build in it:
|
||||
|
||||
```sh
|
||||
git clone https://codeberg.org/StillDeadcode/radiance.git && cd radiance
|
||||
./build.sh # configure, build for the cards present, run the fast tests
|
||||
./build.sh --no-hip # host backend only
|
||||
cmake -S . -B build -G Ninja -DRAD_GPU_TARGETS='gfx1201' # build for cards this machine lacks
|
||||
```
|
||||
|
||||
To install, name the prefix when the build directory is first configured
|
||||
(`-DCMAKE_INSTALL_PREFIX=/opt/radiance`), build, then run `cmake --install build`. The default
|
||||
plugin path, `<prefix>/share/radiance`, is compiled in from that first configure, so
|
||||
`cmake --install build --prefix DIR` alone gives a tree that looks for its plugins elsewhere. The
|
||||
prefix gets `bin/`, `include/radiance/`, `lib/cmake/radiance/`, `libexec/radiance/`,
|
||||
`share/radiance/` and `share/doc/radiance/`.
|
||||
|
||||
With ROCm 10.1 the build turns the compiler's VOPD pairing (dual-issue instruction pairs) off: its
|
||||
LLVM 24 pairs in an order that follows heap addresses, so two builds of the same source can differ.
|
||||
The Docker image builds its compiler with the fix and keeps the pairing, which is 1.4-3.5% faster
|
||||
on 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
|
||||
|
||||
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
|
||||
```
|
||||
|
||||
```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,
|
||||
`server.download-dir` must name a writable mount, since the compose files mount `/models` read-only.
|
||||
|
||||
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.
|
||||
|
||||
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: 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` |
|
||||
| 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` |
|
||||
|
||||
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.
|
||||
|
||||
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` 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 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
|
||||
trusting it.
|
||||
|
||||
`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 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.
|
||||
|
||||
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:
|
||||
Send a request or open the web dashboard at `http://localhost:8000/`:
|
||||
|
||||
```sh
|
||||
curl -s localhost:8000/v1/chat/completions -H 'Content-Type: application/json' \
|
||||
-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:
|
||||
---
|
||||
|
||||
## Build from Source
|
||||
|
||||
Requires Linux, git, CMake 3.21+, Ninja, and C++20 (tested with the `clang` shipped in ROCm 10.1; ROCm 7.2 is also supported; set `ROCM_PATH` if not `/opt/rocm`).
|
||||
|
||||
```sh
|
||||
curl -s localhost:8000/v1/images/generations -H 'Content-Type: application/json' \
|
||||
-d '{"prompt":"a lighthouse on a cliff at sunset, oil painting","size":"1024x1024"}' \
|
||||
| python3 -c 'import sys,json,base64; open("out.png","wb").write(base64.b64decode(json.load(sys.stdin)["data"][0]["b64_json"]))'
|
||||
git clone https://codeberg.org/StillDeadcode/radiance.git && cd radiance
|
||||
./build.sh # build for attached GPUs + fast tests
|
||||
./build.sh --no-hip # host CPU backend only
|
||||
cmake -S . -B build -G Ninja -DRAD_GPU_TARGETS='gfx1201' # cross-compile for specific targets
|
||||
```
|
||||
|
||||
`http://localhost:8000/` is the dashboard. [`docs/GUIDE.md`](docs/GUIDE.md) covers the API, memory
|
||||
budgets, long context, speculative decoding and operating a server.
|
||||
To install, set `-DCMAKE_INSTALL_PREFIX=/opt/radiance` at initial configure time and run `cmake --install build`. (The compiled-in plugin search path comes from that prefix; from a build tree, set `RADIANCE_HOME=$PWD/build/radiance_home`.)
|
||||
|
||||
## Convert a checkpoint
|
||||
Create a `radiance.yaml` (see [`docs/GUIDE.md`](docs/GUIDE.md) and [`docs/MULTIMODEL.md`](docs/MULTIMODEL.md) for all keys):
|
||||
|
||||
`rad-convert` turns a Hugging Face checkpoint into a container, quantising what a recipe in
|
||||
`data/recipes/` names. Download checkpoints with `scripts/hfget.sh <org/repo> <dir>`.
|
||||
```yaml
|
||||
server:
|
||||
port: 8000
|
||||
models:
|
||||
minicpm5-2b-iq8r:
|
||||
model: StillDeadcode/minicpm5-2b-iq8r # local .rad, HF checkpoint dir, or HF repo id
|
||||
```
|
||||
|
||||
```sh
|
||||
# Spark X2.6 uses the checkpoint's BF16 weights, tokenizer and chat template; no recipe required.
|
||||
export RADIANCE_HOME=$PWD/build/radiance_home
|
||||
build/bin/radiance --config radiance.yaml --check
|
||||
build/bin/radiance --config radiance.yaml
|
||||
```
|
||||
|
||||
> Migrating from pre-2.0 CLI flags? Run `rad-yaml --model x.rad --tp 2 > radiance.yaml` to convert them.
|
||||
|
||||
---
|
||||
|
||||
## Supported Models
|
||||
|
||||
Radiance serves self-contained `.rad` containers (weights, tokenizer, chat template, and optional drafter/vision tower) as well as unquantised Hugging Face checkpoints directly. Ready-to-run containers and recipes are listed below; full architecture details live in [`docs/ARCHITECTURES.md`](docs/ARCHITECTURES.md).
|
||||
|
||||
### Text & Multimodal LLMs
|
||||
|
||||
| Family | Notable Models & Modalities | Pre-built Containers / Conversion |
|
||||
|---|---|---|
|
||||
| **Qwen3.5 / 3.6 / 3.8** | Qwen3.8-27B (vision, DFlash2), Qwen3.6-35B-A3B MoE (MTP), Qwen3.8-Flash-Next MoE (vision, MTP), Qwen3-VL 32B | [Flash-Next IQR-V4](https://huggingface.co/StillDeadcode/qwen3.8-next-flash-iqr-v4) · [27B IQ8R](https://huggingface.co/StillDeadcode/qwen3.8-27b-iq8r-dflash) · [27B IQR-V4](https://huggingface.co/StillDeadcode/qwen3.8-27b-iqr-v4) · [35B-A3B IQ8R](https://huggingface.co/StillDeadcode/qwen3.6-35b-a3b-iq8r) |
|
||||
| **Gemma 3 & 4** | Gemma 4 12B / 26B-A4B MoE / 31B (vision, audio on E2B/E4B, DFlash2/MTP), TranslateGemma 27B | [31B EXL3-V3](https://huggingface.co/keptn/gemma4-31b-exl3) · [12B EXL3-V3](https://huggingface.co/keptn/gemma4-12b-exl3) · [TranslateGemma 27B](https://huggingface.co/StillDeadcode/translategemma-27b-i8) |
|
||||
| **GLM-5.3 / DeepSeek-V4.1 / ERNIE-5.5** | GLM-5.3-Flash (vision, MTP), DeepSeek-V4.1-Flash (vision, DSpark), ERNIE-5.5-Flash-Preview (DSpark) | [GLM-5.3 IQR-V4](https://huggingface.co/animusnull/glm-5.3-flash-iqr-v4) · [DeepSeek-V4.1](https://huggingface.co/bakon3/DeepSeek-V4.1-Flash-1017-uncensored-rad) · `rad-convert` |
|
||||
| **Nemotron / Ling / Inkling / Flint** | Nemotron-3.5-Bolt 74B-A9B & E4B, Ling-3.0-tiny, Inkling 2 Mini (vision, DFlash2), Recursive Flint | [Inkling 2 Mini IQR-V4](https://huggingface.co/StillDeadcode/inkling-2-mini-iq4r-v4) · [Bolt-E4B EXL3](https://huggingface.co/keptn/nemotron-3.5-bolt-e4b-exl3) · [Flint IQ8R](https://huggingface.co/StillDeadcode/flint-iq8r) · [Ling-3.0-tiny](https://huggingface.co/StillDeadcode/ling-3.0-tiny-iq8r) |
|
||||
| **MiniCPM / Spark / Muse / LFM / Hy-Memory** | MiniCPM5-2B (DSpark), Spark X2.6 4B (DSpark), Meta Muse Glimmer 30B (vision/video, DFlash2), LFM2/LFM3, Hy-Memory-30B-A3B | [MiniCPM5-2B IQ8R](https://huggingface.co/StillDeadcode/minicpm5-2b-iq8r) · [Muse Glimmer IQ8R](https://huggingface.co/StillDeadcode/muse-glimmer-30b-iq8r-dflash) · [Spark X2.6](https://huggingface.co/gostar77/spark-x2.6-4b-radiance) · [Hy-Memory](https://huggingface.co/gostar77/hy-memory-30b-a3b-radiance) |
|
||||
| **OCR & Decision** | Unlimited-OCR, Cloudflare Clef, Convai Laya | [Unlimited-OCR](https://huggingface.co/Aijuus/unlimited-ocr-bf16) · `rad-convert` |
|
||||
|
||||
### Image, Video, Audio & 3D Generation
|
||||
|
||||
| Modality | Models | Pre-built Containers / Conversion |
|
||||
|---|---|---|
|
||||
| **Image** (`/v1/images/*`) | Qwen-Image 2.1 / Turbo, MOSS-Image, Krea 2 Raw / Turbo, FLUX.3 [klein], SDXL & finetunes, Anima | [Qwen-Image 2.1](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-iq8r) · [Turbo](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-turbo-iq8r) · [Krea 2 Turbo](https://huggingface.co/StillDeadcode/krea-2-turbo-radiance-iq8r) · [FLUX.3](https://huggingface.co/StillDeadcode/radiance-flux-3-klein-iq8r) |
|
||||
| **Video** (`/v1/videos`) | MiniMax-H3 / FastH3 (stereo audio), LTX-2.5 (stereo audio), Wan 2.2 TI2V-5B | [MiniMax-H3](https://huggingface.co/StillDeadcode/minimax-h3-i8) · [FastH3](https://huggingface.co/StillDeadcode/fasth3-8-step-v2-i8) · [LTX-2.5 Distilled](https://huggingface.co/StillDeadcode/radiance-ltx-2.5-distilled-iq8r) |
|
||||
| **Speech & Music** (`/v1/audio/speech`) | Breeze-TTS-2 (streaming + WS), Fish Audio drama-3, MiniMax-Music3 (44.1 kHz stereo) | [Breeze-TTS-2](https://huggingface.co/StillDeadcode/radiance-breeze-tts2-bf16) · [Music3](https://huggingface.co/StillDeadcode/minimax-music3-bf16) · `data/recipes/drama3-i8.recipe` |
|
||||
| **3D Shape** (`/generate`) | Hunyuan3D-2 | `rad-convert` |
|
||||
|
||||
### Embeddings, Rerankers & Speech Recognition
|
||||
|
||||
| Task | Models | Source |
|
||||
|---|---|---|
|
||||
| **Embeddings** (`/v1/embeddings`) | EmbeddingGemma 2 (text/image/video/audio), Qwen3-Embedding (0.6B/4B/8B), Nemotron-3.5-Embed (1B/8B), nomic-embed-text-v2-moe | Serve HF checkpoints directly or `rad-convert` |
|
||||
| **Rerankers** (`/v1/rerank`) | Qwen3-Reranker (0.6B/4B/8B), Nemotron-3.5-Rerank 8B | Serve HF checkpoints directly |
|
||||
| **ASR** (`/v1/audio/transcriptions`, `/v1/realtime`) | Qwen3-ASR 1.7B (30 languages, live WebSocket) | [Qwen/Qwen3-ASR-1.7B-hf](https://huggingface.co/Qwen/Qwen3-ASR-1.7B-hf) |
|
||||
|
||||
> **Format note:** Legacy block-FP8, MXFP4 trunk, M2XFP4 and ParoQuant containers from 1.x are refused at startup; use BF16, IQ8R, IQR-V4, EXL3-V3 or GGUF containers instead.
|
||||
|
||||
---
|
||||
|
||||
## Convert a Checkpoint
|
||||
|
||||
`rad-convert` packs a Hugging Face or GGUF checkpoint into a `.rad` container using recipes from `data/recipes/` (use `scripts/hfget.sh <org/repo> <dir>` to download):
|
||||
|
||||
```sh
|
||||
# Pack as-is (BF16)
|
||||
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
|
||||
build/bin/rad-convert /srv/models/hf/google/gemma-4-31B-it -o gemma4-31b-w4a8.rad \
|
||||
--recipe data/recipes/gemma4-31b-dense-bf16-w4a8.recipe \
|
||||
--set quantization_config.quant_method=compressed-tensors \
|
||||
--draft-model /srv/models/hf/google/gemma-4-31B-it-assistant
|
||||
build/bin/rad-convert /srv/models/hf/google/gemma-4-31B-it -o gemma4-31b-dense-w4a8-df.rad \
|
||||
--recipe data/recipes/gemma4-31b-dense-bf16-w4a8-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/google/gemma-4-31B-it -o gemma4-31b-dense-q8-df.rad \
|
||||
--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
|
||||
# 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
|
||||
# CLIP's tokenizer.json from openai/clip-vit-large-patch14
|
||||
build/bin/rad-convert /srv/models/hf/OnomaAIResearch/Illustrious-XL-v2.0/Illustrious-XL-v2.0.safetensors \
|
||||
-o illustrious-xl-v2.0-bf16.rad --recipe data/recipes/sdxl-bf16.recipe \
|
||||
--tokenizer /srv/models/hf/openai/clip-vit-large-patch14/tokenizer.json
|
||||
|
||||
# Quantise with a recipe and bundle a drafter
|
||||
build/bin/rad-convert /srv/models/hf/google/gemma-4-31B-it -o gemma4-31b-q8-df.rad \
|
||||
--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
|
||||
|
||||
# Inside Docker (recipes live in /opt/radiance/share/radiance/recipes/)
|
||||
docker run --rm -v /srv/models:/models --entrypoint rad-convert stilldeadcode/radiance ...
|
||||
```
|
||||
|
||||
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: 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.
|
||||
See [`docs/TOOLS.md`](docs/TOOLS.md) for all `rad-convert`, `rad-sidecar`, `rad-info`, `rad-kbench` and `rad-tune` options.
|
||||
|
||||
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
|
||||
ctest --test-dir build -L fast -j8 # the inner loop, under 15 s; build.sh runs it
|
||||
ctest --test-dir build -LE 'gpu|oot' -j8 # everything that runs without a card (about 5 minutes)
|
||||
ctest --test-dir build -L gpu # the card tests; they need the cards to themselves
|
||||
ctest --test-dir build -L oot # rebuilds every bundled plugin out of tree against an install
|
||||
ctest --preset fast # inner loop (<15 s); build.sh runs this
|
||||
ctest --preset host # all CPU/host tests (~5 min)
|
||||
ctest --preset gpu # GPU tests (require exclusive access to cards)
|
||||
ctest --preset full # host + gpu + out-of-tree plugin rebuild (oot)
|
||||
```
|
||||
|
||||
`CMakePresets.json` names the same runs (`ctest --preset fast`, `host`, `gpu`, `full`, `asan`), and
|
||||
[`docs/GUIDE.md`](docs/GUIDE.md) §1.3 describes the tiers and the test binaries' options.
|
||||
---
|
||||
|
||||
## Documentation
|
||||
|
||||
| | |
|
||||
| Document | Contents |
|
||||
|---|---|
|
||||
| [`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 |
|
||||
| [`docs/ARCHITECTURES.md`](docs/ARCHITECTURES.md) | the supported model families and their geometry |
|
||||
| [`docs/TP3.md`](docs/TP3.md) | any world size: the attention world and uneven delta-net heads; three ranks |
|
||||
| [`docs/OPS.md`](docs/OPS.md), [`docs/KERNELS.md`](docs/KERNELS.md) | the op vocabulary, and what `rad-kbench` last measured |
|
||||
| [`spec.md`](spec.md) | the design |
|
||||
| [`docs/GUIDE.md`](docs/GUIDE.md) | Configuration keys, memory/TP/context/speculation tuning, HTTP & WS API reference, operations |
|
||||
| [`docs/MULTIMODEL.md`](docs/MULTIMODEL.md) | Multi-model fleet serving, parking/eviction, pools, hot reload |
|
||||
| [`docs/DOCKER.md`](docs/DOCKER.md) | Docker image, compose files, `docker run` flags, custom builds |
|
||||
| [`docs/PREPARING_YOUR_RIG.md`](docs/PREPARING_YOUR_RIG.md) | Bare-metal setup guide for a multi-GPU AMD Linux host |
|
||||
| [`docs/TOOLS.md`](docs/TOOLS.md) | CLI tools (`rad-convert`, `rad-info`, `rad-kbench`, `rad-tune`, `rad-sidecar`, `rad-yaml`, etc.) and recipe syntax |
|
||||
| [`docs/ARCHITECTURES.md`](docs/ARCHITECTURES.md) | Supported model plugins, geometry and per-family notes |
|
||||
| [`docs/PLUGIN.md`](docs/PLUGIN.md) | Writing kernel, architecture and quantiser `.so` plugins (ABI 46) |
|
||||
| [`docs/IMPLEMENTATION.md`](docs/IMPLEMENTATION.md) | Contributor guide, layout and build conventions |
|
||||
| [`docs/OPS.md`](docs/OPS.md) | Machine-checked op schema contract between arch plugins and kernel libraries |
|
||||
| [`docs/KERNELS.md`](docs/KERNELS.md) | Kernel libraries and running `rad-kbench` verification/benchmarks |
|
||||
| [`docs/DIAGNOSE.md`](docs/DIAGNOSE.md) | Built-in `diagnose` self-measurement mode |
|
||||
| [`docs/IQR.md`](docs/IQR.md), [`docs/MOE-W4.md`](docs/MOE-W4.md) | Low-bit quantisation formats (IQR-V1..V4, W4/W5/W6 MoE experts) |
|
||||
| [`docs/KV-STREAMING.md`](docs/KV-STREAMING.md), [`docs/QSA.md`](docs/QSA.md), [`docs/YARN.md`](docs/YARN.md) | Long-context subsystems (host-streamed KV, QSA, YaRN) |
|
||||
| [`docs/TP3.md`](docs/TP3.md), [`docs/LORA-ROTATED.md`](docs/LORA-ROTATED.md) | Arbitrary-world-size tensor parallelism (TP3/TP4) and rotated-trunk LoRA |
|
||||
| [`spec.md`](spec.md) | Engine architecture specification |
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
|
||||
[Apache-2.0](LICENSE), copyright Deadcode and the radiance contributors. Keep [`NOTICE`](NOTICE)
|
||||
with any copy or derivative. It credits the authors and lists the MIT-licensed code the tree
|
||||
includes. The model weights are not covered: each keeps the license of the model it was converted
|
||||
from. The Docker image also holds third-party libraries under their own licenses, GPL and LGPL
|
||||
among them; `/usr/share/doc/THIRD-PARTY` in the image lists each one with its version and source.
|
||||
[Apache-2.0](LICENSE), copyright Deadcode and the radiance contributors. Keep [`NOTICE`](NOTICE) with any copy or derivative. Model weights retain their respective upstream licenses. The Docker image includes third-party libraries under their own licenses (listed in `/usr/share/doc/THIRD-PARTY` inside the image).
|
||||
+24
-1
@@ -19,7 +19,9 @@ 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 43u
|
||||
#define RAD_ABI_VERSION 46u
|
||||
/* Extra encoder feature planes carried with each request. */
|
||||
#define RAD_ENCODER_MAX_AUX 4
|
||||
|
||||
/* ================================================================== plugin identity */
|
||||
/* One value per plugin, not flags (QUANT is 3). RAD_PLUGIN_QUANT is a quantiser plugin:
|
||||
@@ -489,6 +491,17 @@ typedef struct RadKernelInfo {
|
||||
|
||||
/* This row's launch grid can depend on live seqused during prefill. */
|
||||
#define RAD_KERNEL_CAP_DYNAMIC_PREFILL_SPLIT (1ull << 0)
|
||||
/* An `hc_project` row that reads its switch as a direction offset: a row with `on` != 0 projects
|
||||
* along the n elements at `v + (on - 1)`, `v` being contiguous f32, so one launch serves rows that
|
||||
* each name a direction of a table (control-vector slots). `on` == 1 is the plain switch. The core
|
||||
* refuses --control-vector-slots over a row without this flag, which would project every such row
|
||||
* along `v` itself. */
|
||||
#define RAD_KERNEL_CAP_CVEC_ROW_OFFSET (1ull << 1)
|
||||
/* An `hc_project` row that also serves additive steering when `on` < 0: a row with `on` < 0 adds
|
||||
* `scale * d` to each stream, where `d` is the n elements at `v + (-on - 1)` (`on` == -1 is `v`
|
||||
* itself). Positive `on` keeps the projection contract above. The core refuses additive vectors
|
||||
* over a row without this flag, which would index `v` at a negative offset. */
|
||||
#define RAD_KERNEL_CAP_CVEC_ADD (1ull << 2)
|
||||
|
||||
/* ================================================================== kernel plugin exports */
|
||||
/* Every kernel plugin exports the whole set. The first plugin in hierarchy order to declare an op
|
||||
@@ -580,6 +593,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
|
||||
|
||||
@@ -108,6 +108,9 @@ 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_FIELD(RadBatch, n_mm_aux)
|
||||
ABI_FIELD(RadBatch, mm_aux)
|
||||
ABI_STRUCT(RadBufDecl)
|
||||
ABI_FIELD(RadBufDecl, dtype)
|
||||
ABI_FIELD(RadBufDecl, rank)
|
||||
@@ -150,6 +153,10 @@ 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_FIELD(RadBuildCtx, kv_host_tokens)
|
||||
ABI_STRUCT(RadAudioGenBatch)
|
||||
ABI_FIELD(RadAudioGenBatch, n_lane)
|
||||
ABI_FIELD(RadAudioGenBatch, lane)
|
||||
@@ -286,6 +293,9 @@ 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_FIELD(RadChatFormat, content_close)
|
||||
ABI_STRUCT(RadConstraint)
|
||||
ABI_FIELD(RadConstraint, key)
|
||||
ABI_FIELD(RadConstraint, op)
|
||||
@@ -332,6 +342,9 @@ ABI_FIELD(RadEncoderDecl, n_embd)
|
||||
ABI_FIELD(RadEncoderDecl, out)
|
||||
ABI_FIELD(RadEncoderDecl, one_grid)
|
||||
ABI_FIELD(RadEncoderDecl, bidirectional)
|
||||
ABI_FIELD(RadEncoderDecl, span_rows)
|
||||
ABI_FIELD(RadEncoderDecl, n_aux)
|
||||
ABI_FIELD(RadEncoderDecl, aux_out)
|
||||
ABI_STRUCT(RadEncoding)
|
||||
ABI_FIELD(RadEncoding, scheme)
|
||||
ABI_FIELD(RadEncoding, transform)
|
||||
@@ -453,6 +466,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)
|
||||
@@ -510,6 +525,7 @@ ABI_FIELD(RadGeneratorDecl, chunk_tokens)
|
||||
ABI_FIELD(RadGeneratorDecl, chunk_bos)
|
||||
ABI_FIELD(RadGeneratorDecl, chunk_eos)
|
||||
ABI_FIELD(RadGeneratorDecl, cond_opts)
|
||||
ABI_FIELD(RadGeneratorDecl, sigma_lower)
|
||||
ABI_STRUCT(RadKVGroupBatch)
|
||||
ABI_FIELD(RadKVGroupBatch, group)
|
||||
ABI_FIELD(RadKVGroupBatch, slot_mapping)
|
||||
|
||||
+182
-31
@@ -66,9 +66,22 @@ const char* rad_meta_gets(const RadModelMeta* m, const char* key, const char* df
|
||||
* [2HD + 2, 2HD + 4) V's scale (absmax / 127)
|
||||
* The plugin declares HD; the core adds the scales' bytes (rad_kv_row_elems). */
|
||||
|
||||
/* RAD_I4R, HD + 4 bytes: K and V rotated (y = H D x / sqrt(HD)) and quantised to 4-bit codes
|
||||
* with one f16 scale each per (token, head), abi/rad_kv_i4r.h:
|
||||
* [0, HD/2) K's codes, two a byte, low nibble first
|
||||
* [HD/2, HD) V's codes
|
||||
* [HD, HD + 2) K's scale
|
||||
* [HD + 2, HD + 4) V's scale
|
||||
* RAD_I6R, 3HD/2 + 4 bytes: the same rotation and scales with 6-bit codes, their low nibbles where
|
||||
* i4r's codes are, their high pairs after them (K's HD/4 bytes, V's), then the two scales.
|
||||
* An attention over either takes its query and returns its output in the model's basis. */
|
||||
|
||||
/* 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. */
|
||||
* then V, and under the int8 cache the two f16 scales after them; under the rotated int4 and int6
|
||||
* caches their head_dim + 4 and 1.5 head_dim + 4 bytes. */
|
||||
static inline int64_t rad_kv_row_elems(uint32_t dtype, int64_t head_dim) {
|
||||
if (dtype == RAD_I4R) return head_dim + 4;
|
||||
if (dtype == RAD_I6R) return head_dim * 3 / 2 + 4;
|
||||
return 2 * head_dim + (dtype == RAD_I8 ? 4 : 0);
|
||||
}
|
||||
|
||||
@@ -112,7 +125,9 @@ typedef struct RadBuildCtx {
|
||||
*
|
||||
* 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); RAD_I8; RAD_F8E4M3 */
|
||||
int kv_dtype; /* RAD_DT_INVALID = the plugin's default (bf16); RAD_I8; RAD_F8E4M3;
|
||||
* RAD_I4R / RAD_I6R, served only by a plugin that asks for them by name
|
||||
* (arch/common/rad_arch.h, rad_kv_cache_dtype_i4r) */
|
||||
int is_draft; /* this builder scope is a drafter (spec §10) */
|
||||
const char* scope; /* "", "draft", "vision", "audio" -- prefixes declared names */
|
||||
|
||||
@@ -291,6 +306,36 @@ typedef struct RadBuildCtx {
|
||||
* 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;
|
||||
|
||||
/* ---- appended in ABI 46 (a host token budget for a streamed group) */
|
||||
/* --kv-host-tokens, 0 when not set or when nothing streams: the tokens every sequence together
|
||||
* keeps in a streamed group's host mirror. The group's block-id space is then this many tokens
|
||||
* in whole blocks when that is fewer than max_seqs x max_ctx, and a plugin states that as its
|
||||
* `kv_resolve`'s `blocks` (the engine sizes the residency map and the mirror row from it; a
|
||||
* larger declaration is refused at the first resolve, or walks past the map on an overflow).
|
||||
*
|
||||
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
|
||||
int64_t kv_host_tokens;
|
||||
} RadBuildCtx;
|
||||
|
||||
/* The most instances (engine ranks) one process holds at once; every slot is below it. */
|
||||
@@ -299,6 +344,12 @@ typedef struct RadBuildCtx {
|
||||
/* 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:
|
||||
*
|
||||
@@ -315,7 +366,15 @@ static inline int rad_build_slot(const RadBuildCtx* c) { return c->slot_base + c
|
||||
* `n_layers` is the model's layer count, which may be longer than the file's (the published
|
||||
* Flash-Next vector carries 47 of 48 rows). The steered range is not a separate field: a layer is
|
||||
* steered exactly when its `scales` entry is nonzero, so a plugin asks that and cannot disagree
|
||||
* with the loader. */
|
||||
* with the loader.
|
||||
*
|
||||
* With control-vector slots (--control-vector-slots N) `dir` is [N, n_layers, n_embd] and the
|
||||
* fields describe one slot's [n_layers, n_embd] block: a row's switch carries +(1 + offset) for
|
||||
* projection (RAD_KERNEL_CAP_CVEC_ROW_OFFSET) or -(1 + offset) for additive steering
|
||||
* (RAD_KERNEL_CAP_CVEC_ADD), every layer above 0 has a positive base scale, and a row's strength
|
||||
* and layer range are folded into the slot's directions (length sqrt(|d_l| * strength / base_l)
|
||||
* for project, signed |d_l| * strength / base_l for add, zero outside the range). A plugin
|
||||
* declares the same ops either way. */
|
||||
typedef struct RadControlVector {
|
||||
const float* dir; /* device, [n_layers, n_embd] f32, unit rows */
|
||||
const float* scales; /* host, [n_layers] f32, |d_l| * user scale; 0 = not steered */
|
||||
@@ -471,7 +530,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} */
|
||||
@@ -541,12 +600,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);
|
||||
|
||||
@@ -572,6 +631,24 @@ int rad_weight_shard_span(RadBuilder* b, rad_weight w, int64_t lo, int64_t hi);
|
||||
int rad_weight_shard_span_parts(RadBuilder* b, rad_weight w, const int64_t* lo, const int64_t* hi,
|
||||
const int64_t* total, int n);
|
||||
|
||||
/* A whole weight read with its rows in another order: declared row i is the container's row
|
||||
* `order[i]` (element `order[i]` of a vector). `order` is a permutation of [0, n), n the declared
|
||||
* dim 0 (a vector's length). The loader copies the rows, so such a weight is never served from the
|
||||
* container in place (the file and mapped tiers). For a one-plane weight of whole-byte elements (a
|
||||
* bf16 router, an f32 per-expert vector) declared RAD_SHARD_NONE. A plugin that relabels its
|
||||
* routed experts (rad_expert_profile) permutes its router so: a GEMM row and a vector element are
|
||||
* computed independently, so the logits come out permuted exactly. Additive export;
|
||||
* RAD_ABI_VERSION does not move. */
|
||||
int rad_weight_row_order(RadBuilder* b, rad_weight w, const int32_t* order, int64_t n);
|
||||
|
||||
/* The decode-hot expert ranking the engine was given (--expert-profile): layer `layer`'s share of
|
||||
* the selections, per expert in the model's numbering, into share[0, n), zero for an expert the
|
||||
* profile never saw. RAD_OK, or RAD_E_NOTFOUND when there is no profile or it holds nothing for the
|
||||
* layer (share is then all zero). Every rank sees the same profile, so a plugin may derive its
|
||||
* expert-parallel split from it. A builder with no engine behind it (rad-convert, a test) has none.
|
||||
* Additive export; RAD_ABI_VERSION does not move. */
|
||||
int rad_expert_profile(RadBuilder* b, int layer, float* share, int64_t n);
|
||||
|
||||
/* This rank keeps no cache for the group. The group is still declared as on every other rank (the
|
||||
* scheduler indexes groups by position and one block table serves every rank, so it must exist
|
||||
* with the same block size and layers), but no pool is carved for it. For a rank the geometry
|
||||
@@ -616,7 +693,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 */
|
||||
@@ -677,8 +755,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);
|
||||
|
||||
@@ -781,7 +864,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.
|
||||
@@ -915,6 +998,19 @@ typedef struct RadEncoderDecl {
|
||||
* 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;
|
||||
|
||||
/* ---- appended in ABI 46 (auxiliary encoder features)
|
||||
* n_aux extra [max_patches / merge, n_embd] device BF16 outputs. Their rows
|
||||
* follow out exactly. The core retains them before the next encoder pass. */
|
||||
int64_t n_aux;
|
||||
rad_buf aux_out[RAD_ENCODER_MAX_AUX];
|
||||
} RadEncoderDecl;
|
||||
|
||||
int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d);
|
||||
@@ -1004,8 +1100,8 @@ typedef struct RadGeneratorDecl {
|
||||
|
||||
/* The sampler: flow matching, Euler steps from sigma 1 towards 0.
|
||||
* A fixed schedule: `n_sigmas` values, the terminal 0 implied; a request may not change the
|
||||
* step count. Otherwise `default_steps` sigmas from 1 to 1/steps (or off `sigma_grid`'s
|
||||
* table), shifted:
|
||||
* step count. Otherwise `default_steps` sigmas from 1 to 1/steps (or to `sigma_lower`, or
|
||||
* off `sigma_grid`'s table), shifted:
|
||||
* dyn_shift 0 sigma' = shift * s / (1 + (shift - 1) * s)
|
||||
* dyn_shift 1 mu linear in the image's token count, 256 -> base_shift .. max_seq ->
|
||||
* max_shift; shift_exp 1: exp(mu) / (exp(mu) + (1/s - 1)), 0: mu / (mu + ...)
|
||||
@@ -1094,6 +1190,13 @@ typedef struct RadGeneratorDecl {
|
||||
/* The RAD_GEN_COND_* options (rad_runtime.h) the plugin's COND pass serves, as a mask; a
|
||||
* request asking for another is refused. 0: none. */
|
||||
uint32_t cond_opts;
|
||||
|
||||
/* ---- appended in ABI 45 (MOSS-Image's schedule) */
|
||||
/* A flow-matching schedule whose unshifted linspace ends at `sigma_lower` instead of 1/steps
|
||||
* (0: diffusers' default) -- MOSSImageScheduler's table, which ends at
|
||||
* shift/(train_steps + shift - 1), so the last sigma is the same for every step count.
|
||||
* Read only by the linspace path: ignored with `n_sigmas`, `sigma_grid` and a fixed `sigmas`. */
|
||||
double sigma_lower;
|
||||
} RadGeneratorDecl;
|
||||
|
||||
/* RadGeneratorDecl::beta_schedule: betas linear in sqrt(beta) (Stable Diffusion's
|
||||
@@ -1148,6 +1251,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
|
||||
@@ -1167,8 +1278,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
|
||||
@@ -1320,10 +1432,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
|
||||
@@ -1375,6 +1488,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 */
|
||||
|
||||
@@ -1393,7 +1509,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). */
|
||||
@@ -1403,7 +1519,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;
|
||||
@@ -1429,7 +1545,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;
|
||||
@@ -1444,11 +1564,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;
|
||||
@@ -1685,7 +1807,8 @@ typedef struct RadArchProbe {
|
||||
* keeps no KV. */
|
||||
int32_t gen_video;
|
||||
/* 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. The engine refuses the flag
|
||||
* 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;
|
||||
|
||||
@@ -1739,7 +1862,7 @@ typedef struct RadArchProbe {
|
||||
* KV. */
|
||||
int32_t gen_shape;
|
||||
|
||||
/* ---- appended in ABI 43 (a checkpoint inside the step), in the tail padding behind 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
|
||||
@@ -1867,7 +1990,10 @@ typedef struct RadChatFormat {
|
||||
|
||||
/* Non-zero: a reasoning block may open again later in the reply (after its answer, between
|
||||
* calls) and is read as reasoning there too, and a reasoning_close with no block open is not
|
||||
* part of the answer. Zero: only a block the reply starts with is reasoning. */
|
||||
* part of the answer. Such a close is the model straying (Gemma 4's lone close): the reply is
|
||||
* read as having left the format, and the server logs it. A format whose answer message ends
|
||||
* with that same literal declares it as content_close, which keeps the answer's own close in
|
||||
* the format. Zero: only a block the reply starts with is reasoning. */
|
||||
uint32_t reasoning_anywhere;
|
||||
|
||||
/* Tagged arguments whose tag says the value's type: written in place of arg_value_prefix,
|
||||
@@ -1882,6 +2008,31 @@ typedef struct RadChatFormat {
|
||||
* 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;
|
||||
|
||||
/* What ends the answer message content_open began (Inkling 2's `<|end_message|>`): not part of
|
||||
* the answer, and in the format, once for each answer header the reply wrote. Without it a
|
||||
* reasoning_close in the answer, with no block open, leaves the format. Read only where it is
|
||||
* reasoning_close (the one close the answer is scanned for), with content_open and
|
||||
* reasoning_anywhere set; anything else is refused. NULL or "": the answer has no close of its
|
||||
* own. */
|
||||
const char* content_close;
|
||||
} RadChatFormat;
|
||||
|
||||
/* Return the format, or NULL for "derive it from the chat template". Called once at startup. */
|
||||
|
||||
+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,323 @@
|
||||
/* rad_kv_i4r.h -- the rotated low-bit KV caches, defined once: `kv-cache-dtype: i4r` (RAD_I4R, 4-bit
|
||||
* codes) and `i6r` (RAD_I6R, 6-bit codes). One format at two code widths.
|
||||
*
|
||||
* A token's row in one head of such a group is head_dim * bits / 4 + 4 bytes (rad_kv_row_elems,
|
||||
* rad_kvr_row_bytes): head_dim + 4 at i4r, 1.5 head_dim + 4 at i6r (260 and 388 at 256):
|
||||
*
|
||||
* [0, HD/2) K's codes' low four bits, element 2j in bits 0-3 of byte j, 2j+1 in 4-7
|
||||
* [HD/2, HD) V's, the same packing
|
||||
* i6r only:
|
||||
* [HD, HD + HD/4) K's codes' high two bits, a dword a sixteen-element chunk: byte j of
|
||||
* chunk t holds element 16t+2j in bits 0-1, 16t+2j+1 in 2-3, 16t+8+2j in
|
||||
* 4-5 and 16t+9+2j in 6-7 (rad_kvr_hi_byte / _shift)
|
||||
* [HD + HD/4, 3HD/2) V's
|
||||
* then K's scale, f16; V's scale, f16
|
||||
*
|
||||
* The low nibbles sit exactly where i4r's codes do, so a reader takes the same aligned dword for a
|
||||
* lane's eight elements at either width, and i6r adds one aligned dword a sixteen-element chunk
|
||||
* (libr4d's k6_v4 high-bit word: one mask and shift put the pairs beside the nibbles, r4d_dt16.h).
|
||||
* Four codes in three bytes would put a lane's eight elements on a 2-byte boundary across two
|
||||
* dwords, a read gfx1201 splits; the planes cost the same 0.75 bytes an element.
|
||||
*
|
||||
* What is stored is not the head's K (or V) but its rotation y = R x, R = H D / sqrt(HD): D flips
|
||||
* the sign of element i where bit i of RAD_KV_I4R_SIGNS is set, H is the Sylvester Hadamard matrix
|
||||
* of order HD (a power of two, at most 256). R is orthogonal, so a reader needs no per-token
|
||||
* inverse: q . k = (R q) . (R k) and sum_i a_i v_i = R^T sum_i a_i (R v_i). An attention over an
|
||||
* i4r or i6r group rotates its query once and un-rotates its output once a (token, head) row; its operands
|
||||
* and its output stay in the model's basis, as at every other cache dtype.
|
||||
*
|
||||
* The rotation spreads a few large channels (keys' outliers are per channel and survive RoPE as a
|
||||
* pair of channels) over the whole head, so one scale a head suffices. D matters: a component that
|
||||
* is constant over the head's channels (a shared bias) is one Walsh function, and H alone would
|
||||
* put all of it into one coefficient.
|
||||
*
|
||||
* A code c (two's complement, -8..7 at i4r, -32..31 at i6r) stands for (c + 0.5) * scale: 16 or 64
|
||||
* levels, symmetric, no zero (a midrise quantiser, ~10% less mean square error than the fifteen
|
||||
* levels of a midtread one on Gaussian data). The scale is the one of sixteen candidates, absmax
|
||||
* times rad_kvr_cand(bits, j) for j = 0..15 rounded to f16 ((32 - j) / 240 at i4r, (128 - j) / 4032
|
||||
* at i6r; clamped at 8192 and 2048 so the top level stays an f16), whose codes give the smallest
|
||||
* squared error over the head; the first such candidate on a tie. Clipping the largest values
|
||||
* trades their error for a finer step everywhere else (about 25% less error than absmax / 7.5 on
|
||||
* Gaussian rows at i4r; at i6r the best clip is a few percent). A code is floor(y * (1 / scale))
|
||||
* clamped to the width's range; a zero scale stores codes 0 (values 0).
|
||||
*
|
||||
* Every step is in f32 with one IEEE rounding an operation, in an order a GPU wave reproduces; the
|
||||
* two products that feed a sum (a level less its value, a square added to the error) are explicit
|
||||
* fused multiply-adds, so a compiler's contraction setting cannot change them: the transform's
|
||||
* stages by ascending stride with (a + b, a - b) butterflies, then the multiply by 1 / sqrt(HD) (exact at HD 4^k); a candidate's error summed per lane over its
|
||||
* HD/32 contiguous elements, then over lanes by an xor butterfly 1, 2, 4, 8, 16. A store kernel
|
||||
* that follows this writes the same bytes as rad_kvr_quant at its width.
|
||||
*
|
||||
* The rotation is switchable for an ablation, process-wide: RADIANCE_KV_I4R_ROTATE=kv (the default)
|
||||
* rotates K and V, =k K only (the query is still rotated, the output is not un-rotated), =none
|
||||
* neither (plain per-head int4 or int6, the same layout and the same scale search). Every library in the
|
||||
* process reads the one variable (rad_kv_i4r_rot_mask), so the store and every reader agree; a cache
|
||||
* written under one setting is meaningless under another, so it is a test switch, not a deployment
|
||||
* knob, and the host tier must not outlive a change (a restart drops it).
|
||||
*
|
||||
* Header-only C, no allocation: libref, libavx, the tests and the libr4d selftest share it. */
|
||||
#ifndef RAD_KV_I4R_H
|
||||
#define RAD_KV_I4R_H
|
||||
|
||||
#include <math.h>
|
||||
#include <stdint.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "rad_plugin.h" /* rad_f32_to_f16, rad_f16_to_f32 */
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define RAD_KV_I4R_MAX_HD 256
|
||||
#define RAD_KV_I4R_LANES 32
|
||||
#define RAD_KV_I4R_CANDS 16
|
||||
|
||||
/* D: bit i set flips element i. Fixed forever: a cache written under one table is read under it
|
||||
* (splitmix64 from 0x4934524b56313234, "I4RKV124"). */
|
||||
static const uint32_t RAD_KV_I4R_SIGNS[8] = {
|
||||
0xa80e5d37u, 0xa09eeca0u, 0x74da0220u, 0x1e739660u,
|
||||
0x63a4ec35u, 0x42061f18u, 0x392919a2u, 0xb850ed2eu
|
||||
};
|
||||
|
||||
/* A token's row in a head, bytes. */
|
||||
static inline int64_t rad_kv_i4r_row_bytes(int64_t head_dim) { return head_dim + 4; } /* i4r */
|
||||
/* The head widths the format is defined at: a power of two, 32 to 256. */
|
||||
static inline int rad_kv_i4r_hd_ok(int64_t head_dim) {
|
||||
return head_dim >= 32 && head_dim <= RAD_KV_I4R_MAX_HD && (head_dim & (head_dim - 1)) == 0;
|
||||
}
|
||||
static inline int rad_kv_i4r_flip(int i) { return (int)((RAD_KV_I4R_SIGNS[i >> 5] >> (i & 31)) & 1u); }
|
||||
|
||||
/* 1 / sqrt(n) as f32: exact at 4^k (64: 1/8, 256: 1/16). */
|
||||
static inline float rad_kv_i4r_norm(int n) { return 1.0f / sqrtf((float)n); }
|
||||
|
||||
/* The unnormalised Walsh-Hadamard transform in place, stages by ascending stride. */
|
||||
static inline void rad_kv_i4r_wht(float* v, int n) {
|
||||
for (int h = 1; h < n; h <<= 1)
|
||||
for (int i = 0; i < n; i += 2 * h)
|
||||
for (int j = i; j < i + h; ++j) {
|
||||
const float a = v[j], b = v[j + h];
|
||||
v[j] = a + b;
|
||||
v[j + h] = a - b;
|
||||
}
|
||||
}
|
||||
/* y = R x in place: flip, transform, normalise. */
|
||||
static inline void rad_kv_i4r_fwd(float* v, int n) {
|
||||
for (int i = 0; i < n; ++i) if (rad_kv_i4r_flip(i)) v[i] = -v[i];
|
||||
rad_kv_i4r_wht(v, n);
|
||||
const float s = rad_kv_i4r_norm(n);
|
||||
for (int i = 0; i < n; ++i) v[i] = v[i] * s;
|
||||
}
|
||||
/* x = R^T y in place: transform, normalise, flip. */
|
||||
static inline void rad_kv_i4r_inv(float* v, int n) {
|
||||
rad_kv_i4r_wht(v, n);
|
||||
const float s = rad_kv_i4r_norm(n);
|
||||
for (int i = 0; i < n; ++i) {
|
||||
v[i] = v[i] * s;
|
||||
if (rad_kv_i4r_flip(i)) v[i] = -v[i];
|
||||
}
|
||||
}
|
||||
|
||||
/* Which halves are rotated: bit 0 K, bit 1 V (RAD_KV_I4R_ROT_K / _V). From RADIANCE_KV_I4R_ROTATE,
|
||||
* read once: "kv" or unset 3, "k" 1, "none" or "0" 0, anything else 3. */
|
||||
enum { RAD_KV_I4R_ROT_K = 1, RAD_KV_I4R_ROT_V = 2 };
|
||||
static inline int rad_kv_i4r_rot_parse(const char* e) {
|
||||
if (!e || !*e) return 3;
|
||||
if (!strcmp(e, "k")) return 1;
|
||||
if (!strcmp(e, "none") || !strcmp(e, "0")) return 0;
|
||||
return 3;
|
||||
}
|
||||
static inline int rad_kv_i4r_rot_mask(void) {
|
||||
static int m = -1;
|
||||
int v = __atomic_load_n(&m, __ATOMIC_ACQUIRE);
|
||||
if (v < 0) {
|
||||
v = rad_kv_i4r_rot_parse(getenv("RADIANCE_KV_I4R_ROTATE"));
|
||||
__atomic_store_n(&m, v, __ATOMIC_RELEASE);
|
||||
}
|
||||
return v;
|
||||
}
|
||||
static inline const char* rad_kv_i4r_rot_name(int m) {
|
||||
return m == 3 ? "K and V rotated" : m == 1 ? "K rotated, V plain" : m == 0 ? "plain (unrotated)"
|
||||
: "V rotated, K plain";
|
||||
}
|
||||
|
||||
/* ---- the code width: i4r (4 bits) and i6r (6 bits) -----------------------------------------
|
||||
*
|
||||
* Every function below takes the code width `bits`, 4 or 6; the rad_kv_i4r_* names at the end are
|
||||
* the 4-bit forms. A width is the dtype's (rad_kvr_bits): one rotation, one row order, one scale
|
||||
* search, two packings of the low four bits and, at 6, a plane of the high two. */
|
||||
static inline int rad_kvr_bits(uint32_t dtype) {
|
||||
return dtype == RAD_I4R ? 4 : dtype == RAD_I6R ? 6 : 0;
|
||||
}
|
||||
/* A token's row in a head, bytes: the codes of K and V, then two f16 scales. */
|
||||
static inline int64_t rad_kvr_row_bytes(int64_t head_dim, int bits) {
|
||||
return head_dim * bits / 4 + 4;
|
||||
}
|
||||
/* Where a half's (0 K, 1 V) low nibbles, high pairs (6 bits only) and scale start in a row. */
|
||||
static inline int64_t rad_kvr_lo_off(int64_t n, int half) { return (int64_t)half * (n / 2); }
|
||||
static inline int64_t rad_kvr_hi_off(int64_t n, int half) { return n + (int64_t)half * (n / 4); }
|
||||
static inline int64_t rad_kvr_scale_off(int64_t n, int bits, int half) {
|
||||
return n * bits / 4 + 2 * half;
|
||||
}
|
||||
/* The codes, two's complement: -8..7 at 4 bits, -32..31 at 6. */
|
||||
static inline int rad_kvr_cmin(int bits) { return -(1 << (bits - 1)); }
|
||||
static inline int rad_kvr_cmax(int bits) { return (1 << (bits - 1)) - 1; }
|
||||
/* Candidate j's multiplier on the absmax, as f32: (T - j) / (T * (2^(bits-1) - 0.5)), T 32 at 4
|
||||
* bits ((32 - j) / 240: absmax down to 17/32 of it) and 128 at 6 ((128 - j) / 4032: down to
|
||||
* 113/128). Sixty-four levels want little clipping: on Gaussian and Laplace heads of 256 the best
|
||||
* candidate is within the first eight (T 64 loses 0.5% and T 32 1.8% of the error to T 128). */
|
||||
static inline float rad_kvr_cand(int bits, int j) {
|
||||
return bits == 6 ? (float)(128 - j) / 4032.0f : (float)(32 - j) / 240.0f;
|
||||
}
|
||||
/* The scale's ceiling: the top level, (2^(bits-1) - 0.5) times it, must stay an f16 (8192 * 7.5,
|
||||
* 2048 * 31.5). */
|
||||
static inline float rad_kvr_smax(int bits) { return bits == 6 ? 2048.0f : 8192.0f; }
|
||||
/* A candidate scale, rounded to f16 and clamped. */
|
||||
static inline uint16_t rad_kvr_scale_of(float amax, int bits, int j) {
|
||||
float s = amax * rad_kvr_cand(bits, j);
|
||||
if (s > rad_kvr_smax(bits)) s = rad_kvr_smax(bits);
|
||||
return rad_f32_to_f16(s);
|
||||
}
|
||||
/* y's code against a scale (as f32) and its reciprocal. */
|
||||
static inline int rad_kvr_code_of(float y, float s, float inv, int bits) {
|
||||
if (!(s > 0.0f)) return 0;
|
||||
float c = floorf(y * inv);
|
||||
if (c < (float)rad_kvr_cmin(bits)) c = (float)rad_kvr_cmin(bits);
|
||||
if (c > (float)rad_kvr_cmax(bits)) c = (float)rad_kvr_cmax(bits);
|
||||
return (int)c;
|
||||
}
|
||||
static inline float rad_kvr_level(int c, float s) { return ((float)c + 0.5f) * s; }
|
||||
|
||||
/* Element d's place in a high-pair plane: byte 4 (d / 16) + (d % 8) / 2, bit 4 ((d / 8) % 2) +
|
||||
* 2 (d % 2) -- a dword a sixteen-element chunk, libr4d's k6_v4 high-bit word, so a lane holding
|
||||
* eight contiguous elements widens them with one mask and shift (r4d_dt16.h). */
|
||||
static inline int rad_kvr_hi_byte(int d) { return 4 * (d >> 4) + ((d & 7) >> 1); }
|
||||
static inline int rad_kvr_hi_shift(int d) { return 4 * ((d >> 3) & 1) + 2 * (d & 1); }
|
||||
|
||||
/* Element d's code from a half's planes: `lo` its nibbles, `hi` its high pairs (6 bits only). */
|
||||
static inline int rad_kvr_code_at(const uint8_t* lo, const uint8_t* hi, int bits, int d) {
|
||||
int u = (lo[d >> 1] >> ((d & 1) * 4)) & 15;
|
||||
if (bits == 6) {
|
||||
u |= ((hi[rad_kvr_hi_byte(d)] >> rad_kvr_hi_shift(d)) & 3) << 4;
|
||||
return u >= 32 ? u - 64 : u;
|
||||
}
|
||||
return u >= 8 ? u - 16 : u;
|
||||
}
|
||||
|
||||
/* Quantise a rotated head y[0..n): n/2 nibble bytes at `lo`, at 6 bits n/4 high-pair bytes at `hi`
|
||||
* (unused at 4, may be null), the f16 scale returned. */
|
||||
static inline uint16_t rad_kvr_quant(const float* y, int n, int bits, uint8_t* lo, uint8_t* hi) {
|
||||
const int vpl = n / RAD_KV_I4R_LANES;
|
||||
float am = 0.0f;
|
||||
for (int i = 0; i < n; ++i) am = fmaxf(am, fabsf(y[i]));
|
||||
uint16_t best = 0;
|
||||
float berr = 0.0f;
|
||||
for (int j = 0; j < RAD_KV_I4R_CANDS; ++j) {
|
||||
const uint16_t sh = rad_kvr_scale_of(am, bits, j);
|
||||
const float s = rad_f16_to_f32(sh), inv = s > 0.0f ? 1.0f / s : 0.0f;
|
||||
float lane[RAD_KV_I4R_LANES];
|
||||
for (int l = 0; l < RAD_KV_I4R_LANES; ++l) {
|
||||
float e = 0.0f;
|
||||
for (int k = 0; k < vpl; ++k) {
|
||||
const float x = y[l * vpl + k];
|
||||
const float d = s > 0.0f
|
||||
? fmaf((float)rad_kvr_code_of(x, s, inv, bits) + 0.5f, s, -x) : -x;
|
||||
e = fmaf(d, d, e);
|
||||
}
|
||||
lane[l] = e;
|
||||
}
|
||||
for (int m = 1; m < RAD_KV_I4R_LANES; m <<= 1) {
|
||||
float nx[RAD_KV_I4R_LANES];
|
||||
for (int l = 0; l < RAD_KV_I4R_LANES; ++l) nx[l] = lane[l] + lane[l ^ m];
|
||||
memcpy(lane, nx, sizeof lane);
|
||||
}
|
||||
if (j == 0 || lane[0] < berr) { berr = lane[0]; best = sh; }
|
||||
}
|
||||
const float s = rad_f16_to_f32(best), inv = s > 0.0f ? 1.0f / s : 0.0f;
|
||||
if (bits == 6) memset(hi, 0, (size_t)n / 4);
|
||||
for (int i = 0; i < n; i += 2) {
|
||||
const int c0 = rad_kvr_code_of(y[i], s, inv, bits), c1 = rad_kvr_code_of(y[i + 1], s, inv, bits);
|
||||
lo[i >> 1] = (uint8_t)(((unsigned)c0 & 15u) | (((unsigned)c1 & 15u) << 4));
|
||||
if (bits == 6) {
|
||||
hi[rad_kvr_hi_byte(i)] |= (uint8_t)((((unsigned)c0 >> 4) & 3u) << rad_kvr_hi_shift(i));
|
||||
hi[rad_kvr_hi_byte(i + 1)] |= (uint8_t)((((unsigned)c1 >> 4) & 3u) << rad_kvr_hi_shift(i + 1));
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/* One head of K (half 0) or V (half 1) into its token's row `row` (rad_kvr_row_bytes): x is the
|
||||
* head in the model's basis, rotated first when `rot` is set. Touches only that half's bytes. */
|
||||
static inline void rad_kvr_put_rot(uint8_t* row, int n, int bits, int half, const float* x, int rot) {
|
||||
float y[RAD_KV_I4R_MAX_HD];
|
||||
memcpy(y, x, (size_t)n * sizeof(float));
|
||||
if (rot) rad_kv_i4r_fwd(y, n);
|
||||
const uint16_t sh = rad_kvr_quant(y, n, bits, row + rad_kvr_lo_off(n, half),
|
||||
bits == 6 ? row + rad_kvr_hi_off(n, half) : (uint8_t*)0);
|
||||
memcpy(row + rad_kvr_scale_off(n, bits, half), &sh, 2);
|
||||
}
|
||||
/* ... rotated as the process's setting says (rad_kv_i4r_rot_mask). */
|
||||
static inline void rad_kvr_put(uint8_t* row, int n, int bits, int half, const float* x) {
|
||||
rad_kvr_put_rot(row, n, bits, half, x, (rad_kv_i4r_rot_mask() >> half) & 1);
|
||||
}
|
||||
/* The scale of K (half 0) or V (half 1) in a row. */
|
||||
static inline float rad_kvr_scale(const uint8_t* row, int n, int bits, int half) {
|
||||
uint16_t h;
|
||||
memcpy(&h, row + rad_kvr_scale_off(n, bits, half), 2);
|
||||
return rad_f16_to_f32(h);
|
||||
}
|
||||
/* Element d's code of K (half 0) or V (half 1) in a row. */
|
||||
static inline int rad_kvr_code(const uint8_t* row, int n, int bits, int half, int d) {
|
||||
return rad_kvr_code_at(row + rad_kvr_lo_off(n, half), row + rad_kvr_hi_off(n, half), bits, d);
|
||||
}
|
||||
/* A row's K or V in the rotated basis: y[d] = (c + 0.5) * scale. */
|
||||
static inline void rad_kvr_get_rot(const uint8_t* row, int n, int bits, int half, float* y) {
|
||||
const float s = rad_kvr_scale(row, n, bits, half);
|
||||
for (int d = 0; d < n; ++d) y[d] = rad_kvr_level(rad_kvr_code(row, n, bits, half, d), s);
|
||||
}
|
||||
/* ... and in the model's basis (un-rotated where `rot` says it was stored rotated). */
|
||||
static inline void rad_kvr_get_mode(const uint8_t* row, int n, int bits, int half, float* x, int rot) {
|
||||
rad_kvr_get_rot(row, n, bits, half, x);
|
||||
if (rot) rad_kv_i4r_inv(x, n);
|
||||
}
|
||||
static inline void rad_kvr_get(const uint8_t* row, int n, int bits, int half, float* x) {
|
||||
rad_kvr_get_mode(row, n, bits, half, x, (rad_kv_i4r_rot_mask() >> half) & 1);
|
||||
}
|
||||
|
||||
/* ---- the 4-bit forms (i4r) ------------------------------------------------------------------ */
|
||||
static inline float rad_kv_i4r_cand(int j) { return rad_kvr_cand(4, j); }
|
||||
static inline uint16_t rad_kv_i4r_scale_of(float amax, int j) { return rad_kvr_scale_of(amax, 4, j); }
|
||||
static inline int rad_kv_i4r_code_of(float y, float s, float inv) { return rad_kvr_code_of(y, s, inv, 4); }
|
||||
static inline float rad_kv_i4r_level(int c, float s) { return rad_kvr_level(c, s); }
|
||||
/* Quantise a rotated head y[0..n): n/2 code bytes at `codes`, the f16 scale returned. */
|
||||
static inline uint16_t rad_kv_i4r_quant(const float* y, int n, uint8_t* codes) {
|
||||
return rad_kvr_quant(y, n, 4, codes, (uint8_t*)0);
|
||||
}
|
||||
/* Element d's code (two's complement nibble) from a code plane. */
|
||||
static inline int rad_kv_i4r_code(const uint8_t* codes, int d) {
|
||||
return rad_kvr_code_at(codes, (const uint8_t*)0, 4, d);
|
||||
}
|
||||
static inline void rad_kv_i4r_put_rot(uint8_t* row, int n, int half, const float* x, int rot) {
|
||||
rad_kvr_put_rot(row, n, 4, half, x, rot);
|
||||
}
|
||||
static inline void rad_kv_i4r_put(uint8_t* row, int n, int half, const float* x) {
|
||||
rad_kvr_put(row, n, 4, half, x);
|
||||
}
|
||||
static inline float rad_kv_i4r_scale(const uint8_t* row, int n, int half) {
|
||||
return rad_kvr_scale(row, n, 4, half);
|
||||
}
|
||||
static inline void rad_kv_i4r_get_rot(const uint8_t* row, int n, int half, float* y) {
|
||||
rad_kvr_get_rot(row, n, 4, half, y);
|
||||
}
|
||||
static inline void rad_kv_i4r_get_mode(const uint8_t* row, int n, int half, float* x, int rot) {
|
||||
rad_kvr_get_mode(row, n, 4, half, x, rot);
|
||||
}
|
||||
static inline void rad_kv_i4r_get(const uint8_t* row, int n, int half, float* x) {
|
||||
rad_kvr_get(row, n, 4, half, x);
|
||||
}
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
#endif /* RAD_KV_I4R_H */
|
||||
+17
-9
@@ -20,8 +20,8 @@
|
||||
* 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).
|
||||
* 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
|
||||
@@ -90,7 +90,9 @@ static inline RAD_BLK_HD void rad_mtp_block_scan(RadBlockRow* r, int64_t vocab)
|
||||
r->top = top;
|
||||
}
|
||||
|
||||
static inline RAD_BLK_HD bool rad_mtp_block_live(int32_t id, float v) { return id >= 0 && v != -INFINITY; }
|
||||
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. */
|
||||
@@ -208,9 +210,11 @@ static inline RAD_BLK_HD void rad_mtp_block_plan(const RadMtpCoupleState* st,
|
||||
|
||||
/* 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) {
|
||||
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;
|
||||
if (rad_spechub_uniform(seed, pos0, RAD_MTP_BLOCK_KEY_STOP + (uint64_t)i) < pl.h[i])
|
||||
return i;
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -247,7 +251,10 @@ static inline RAD_BLK_HD bool rad_mtp_block_resid_walk(const RadBlockRow& r,
|
||||
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]; }
|
||||
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;
|
||||
@@ -295,7 +302,8 @@ static inline RAD_BLK_HD bool rad_mtp_block_resid_draw(const RadBlockRow& r,
|
||||
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);
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -315,8 +323,8 @@ static inline RAD_BLK_HD bool rad_mtp_block_decide(const RadMtpCoupleState* st,
|
||||
*tau = t;
|
||||
*y = -1;
|
||||
if (t >= g) return true;
|
||||
return rad_mtp_block_resid_draw(rows[t], st[t], stat[t], pl.p[t],
|
||||
rad_spechub_uniform(seed, pos0 + (uint64_t)t, RAD_SAMPLE_KEY_RESID), y);
|
||||
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 */
|
||||
|
||||
+53
-37
@@ -17,15 +17,15 @@
|
||||
* 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 with x_i removed, renormalised.
|
||||
* 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.
|
||||
* 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).
|
||||
@@ -126,21 +126,23 @@ static inline RAD_RRS_HD int rad_mtp_rrs_prefix(const RadMtpCoupleState& s, cons
|
||||
|
||||
/* 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));
|
||||
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). */
|
||||
* 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,
|
||||
@@ -166,7 +168,10 @@ static inline RAD_RRS_HD bool rad_mtp_rrs_decide_over(const RadMtpCoupleState& s
|
||||
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; }
|
||||
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;
|
||||
@@ -245,17 +250,18 @@ static inline RAD_RRS_HD bool rad_mtp_rrs_decide(const RadMtpCoupleState& s, con
|
||||
/* ================================================================== 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, rank slots 0 .. m-1), and
|
||||
* 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).
|
||||
* 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|, which with a prefix draft order means every T token is a child):
|
||||
* 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)
|
||||
@@ -271,12 +277,14 @@ static inline RAD_RRS_HD bool rad_mtp_rrs_decide(const RadMtpCoupleState& s, con
|
||||
* m = 0 is the single-draft maximal coupling of the chain (rad_mtp_couple_decide) with the sampled
|
||||
* child in slot 0.
|
||||
*/
|
||||
#define RAD_MTP_RRS_KEY_TAIL_C 8 /* candidate index of the tail draw in the draft stream (0..7 are Gumbel's) */
|
||||
/* 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) {
|
||||
* 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];
|
||||
@@ -298,9 +306,11 @@ static inline RAD_RRS_HD void rad_mtp_rrs_slot_logq_rheo(const RadMtpCoupleState
|
||||
}
|
||||
|
||||
/* 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) {
|
||||
* 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;
|
||||
@@ -330,15 +340,19 @@ static inline RAD_RRS_HD void rad_mtp_rrs_draw_rheo_u(RadMtpCoupleState* s, doub
|
||||
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) {
|
||||
rad_mtp_rrs_draw_rheo_u(s, rad_mtp_rrs_gumbel_u(s->draw.seed, s->draw.base, node, RAD_MTP_RRS_KEY_TAIL_C),
|
||||
nkids, m);
|
||||
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) {
|
||||
/* 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;
|
||||
@@ -369,7 +383,8 @@ static inline RAD_RRS_HD bool rad_mtp_rrs_decide_rheo_u(const RadMtpCoupleState&
|
||||
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]);
|
||||
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;
|
||||
@@ -414,9 +429,10 @@ static inline RAD_RRS_HD bool rad_mtp_rrs_decide_rheo_u(const RadMtpCoupleState&
|
||||
*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) {
|
||||
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);
|
||||
|
||||
+53
-37
@@ -1,12 +1,13 @@
|
||||
/* 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:
|
||||
* 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).
|
||||
* 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
|
||||
@@ -58,10 +59,10 @@
|
||||
* 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
|
||||
* 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.
|
||||
@@ -80,9 +81,9 @@
|
||||
#ifdef __cplusplus
|
||||
|
||||
#define RAD_MTP_TRAV_MAX_DEPTH 16
|
||||
#define RAD_MTP_TRAV_MAX_ROWS 64 /* rows of one request the walk reads (its first ones) */
|
||||
#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 /* the unit of a candidate's mass: 2^-40 of the top's */
|
||||
#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. */
|
||||
@@ -226,7 +227,7 @@ static inline RAD_RRS_HD int32_t rad_mtp_trav_off_token(const int32_t* ids, cons
|
||||
/* ---------------------------------------------------------------- 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 of the butterfly ends with these bits). */
|
||||
* 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]));
|
||||
}
|
||||
@@ -237,9 +238,10 @@ static inline RAD_RRS_HD double rad_mtp_trav_sum8(const double* v) {
|
||||
* 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 the result in registers. */
|
||||
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) {
|
||||
@@ -288,19 +290,21 @@ 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 deterministic children */
|
||||
int tail[RAD_MTP_TRAV_MAX_ROWS]; /* a rheo node that carries its sampled tail child */
|
||||
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 children 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 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 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 (the final draw) */
|
||||
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];
|
||||
};
|
||||
@@ -328,7 +332,8 @@ static inline RAD_RRS_HD int rad_mtp_trav_try_slot(const RadTravTree& t, int v,
|
||||
}
|
||||
|
||||
/* 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). */
|
||||
* 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]);
|
||||
@@ -383,7 +388,10 @@ static inline RAD_RRS_HD bool rad_mtp_trav_walk_tree(RadTravTree& t, uint64_t se
|
||||
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) { t.nk[v] = j; continue; } /* a child the verify no longer carries: cut here */
|
||||
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 */
|
||||
@@ -421,7 +429,8 @@ static inline RAD_RRS_HD bool rad_mtp_trav_walk_tree(RadTravTree& t, uint64_t se
|
||||
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 a child of it */
|
||||
/* 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 {
|
||||
@@ -439,16 +448,17 @@ static inline RAD_RRS_HD bool rad_mtp_trav_walk_tree(RadTravTree& t, uint64_t se
|
||||
}
|
||||
}
|
||||
|
||||
/* 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). */
|
||||
/* 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) {
|
||||
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];
|
||||
@@ -500,12 +510,16 @@ static inline bool rad_mtp_trav_walk(const Tree& T, int root, uint64_t seed, uin
|
||||
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; }
|
||||
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;
|
||||
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;
|
||||
@@ -531,14 +545,16 @@ static inline bool rad_mtp_trav_walk(const Tree& T, int root, uint64_t seed, uin
|
||||
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 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->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;
|
||||
}
|
||||
}
|
||||
|
||||
+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);
|
||||
}
|
||||
|
||||
@@ -458,6 +458,8 @@ static inline float rad_load_f32(const void* base, uint32_t dtype, int64_t i) {
|
||||
case RAD_F8E5M2: return rad_fp8e5m2_to_f32(((const uint8_t*)base)[i]);
|
||||
case RAD_I8: return (float)((const int8_t*)base)[i];
|
||||
case RAD_U8: return (float)((const uint8_t*)base)[i];
|
||||
case RAD_I4R: return (float)((const uint8_t*)base)[i]; /* a cache row's bytes */
|
||||
case RAD_I6R: return (float)((const uint8_t*)base)[i];
|
||||
case RAD_I16: return (float)((const int16_t*)base)[i];
|
||||
case RAD_I32: return (float)((const int32_t*)base)[i];
|
||||
case RAD_U32: return (float)((const uint32_t*)base)[i];
|
||||
@@ -511,6 +513,8 @@ static inline void rad_store_f32(void* base, uint32_t dtype, int64_t i, float v)
|
||||
case RAD_F8E5M2: ((uint8_t*)base)[i] = rad_f32_to_fp8e5m2(v); break;
|
||||
case RAD_I8: ((int8_t*)base)[i] = (int8_t)rad_round_even_sat(v, -128.0, 127.0); break;
|
||||
case RAD_U8: ((uint8_t*)base)[i] = (uint8_t)rad_round_even_sat(v, 0.0, 255.0); break;
|
||||
case RAD_I4R: ((uint8_t*)base)[i] = (uint8_t)rad_round_even_sat(v, 0.0, 255.0); break;
|
||||
case RAD_I6R: ((uint8_t*)base)[i] = (uint8_t)rad_round_even_sat(v, 0.0, 255.0); break;
|
||||
case RAD_U16:
|
||||
((uint16_t*)base)[i] = (uint16_t)rad_round_even_sat(v, 0.0, 65535.0);
|
||||
break;
|
||||
|
||||
@@ -25,6 +25,14 @@ static inline int rad_prefill_splits_law(int bq, int tile, int q_len, int total_
|
||||
return std::max(1, std::min(sp, 64));
|
||||
}
|
||||
|
||||
/* Whether attn_paged_rel takes its WMMA prefill path (libr4d/r4d_attn_rel.hip, launch_rel): a
|
||||
* longest query `q_max` of 32 rows or more and at least 16 rows a sequence. That grid holds every
|
||||
* (sequence, 128-row tile) and no KV split, so it does not follow the live KV maximum, and a pass
|
||||
* key can key a prefill or mixed pass whose attention takes it (arch/inkling2). */
|
||||
static inline bool rad_rel_wmma_prefill(long long q_max, long long rows, long long n_seq) {
|
||||
return q_max >= 32 && rows >= n_seq * 16;
|
||||
}
|
||||
|
||||
/* 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,
|
||||
|
||||
+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 */
|
||||
|
||||
+50
-20
@@ -70,7 +70,7 @@ typedef struct RadKVGroupBatch {
|
||||
int64_t max_blocks;
|
||||
/* Null unless this group streams (RadKVStream). */
|
||||
const RadKVStream* stream;
|
||||
/* ABI 35: host mirror of seqused, retained through this batch for exact sliced-launch bounds. */
|
||||
/* ABI 35: host mirror of seqused, kept through this batch for exact sliced-launch bounds. */
|
||||
const int32_t* seqused_h;
|
||||
} RadKVGroupBatch;
|
||||
|
||||
@@ -177,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;
|
||||
@@ -288,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) */
|
||||
@@ -376,6 +377,18 @@ typedef struct RadBatch {
|
||||
* 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;
|
||||
/* ---- appended in ABI 46 (auxiliary encoder features) ----
|
||||
* Same rows/order/width as mm_embd, but real data on EVERY rank: a decoder
|
||||
* adds these after a completed residual reduction, not before embedding AR.
|
||||
* Count is zero without such an encoder; pointers are null without media rows. */
|
||||
int32_t n_mm_aux;
|
||||
const void* mm_aux[RAD_ENCODER_MAX_AUX];
|
||||
} RadBatch;
|
||||
|
||||
/* What a generator pass carries beside the step batch's own fields, which keep their meanings:
|
||||
@@ -420,7 +433,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. */
|
||||
@@ -515,6 +529,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). */
|
||||
@@ -533,7 +555,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,
|
||||
@@ -690,7 +712,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
|
||||
@@ -737,7 +761,8 @@ 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
|
||||
@@ -757,7 +782,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
|
||||
@@ -765,7 +791,8 @@ 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`:
|
||||
@@ -806,13 +833,14 @@ typedef struct RadShapeGenBatch {
|
||||
} 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. */
|
||||
@@ -887,7 +915,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
|
||||
@@ -1005,13 +1034,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;
|
||||
@@ -1019,7 +1048,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
|
||||
|
||||
+23
-22
@@ -37,15 +37,15 @@ 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
|
||||
/* 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. */
|
||||
* 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
|
||||
@@ -118,7 +118,8 @@ static inline RAD_SPECHUB_HD bool rad_mtp_couple_state_valid(const RadMtpCoupleS
|
||||
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))
|
||||
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;
|
||||
}
|
||||
@@ -199,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) {
|
||||
@@ -297,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
|
||||
@@ -337,11 +339,9 @@ 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;
|
||||
@@ -424,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;
|
||||
}
|
||||
}
|
||||
|
||||
+12
-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 */
|
||||
@@ -134,6 +135,12 @@ enum {
|
||||
RAD_FP6E3M2 = 36, /* OCP FP6: 1-3-2, bias 3, no inf or nan, max 28 */
|
||||
RAD_U16 = 37,
|
||||
|
||||
/* Cache rows, not element types: the rotated int4 and int6 KV caches (abi/rad_kv_i4r.h), whose
|
||||
* row in a head is head_dim + 4 and 1.5 head_dim + 4 bytes (rad_kv_row_elems). Their elements
|
||||
* are those bytes. */
|
||||
RAD_I4R = 38,
|
||||
RAD_I6R = 39,
|
||||
|
||||
RAD_DT_PLUGIN_BASE = 256
|
||||
};
|
||||
/* The dtype table, in the header for the reason given above rad_strerror.
|
||||
@@ -177,6 +184,8 @@ static const RadDtRow rad_dt_table[] = {
|
||||
{ RAD_FP6E2M3, "fp6_e2m3", 6 },
|
||||
{ RAD_FP6E3M2, "fp6_e3m2", 6 },
|
||||
{ RAD_U16, "u16", 16 },
|
||||
{ RAD_I4R, "i4r", 8 },
|
||||
{ RAD_I6R, "i6r", 8 },
|
||||
};
|
||||
enum { RAD_DT_TABLE_N = (int)(sizeof(rad_dt_table) / sizeof(rad_dt_table[0])) };
|
||||
|
||||
@@ -277,7 +286,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
|
||||
@@ -52,3 +52,7 @@ endforeach()
|
||||
install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/common/
|
||||
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/radiance/arch
|
||||
FILES_MATCHING PATTERN "*.h")
|
||||
install(FILES ${CMAKE_SOURCE_DIR}/plugin/exl3import/include/exl3i_moe_abi.h
|
||||
${CMAKE_SOURCE_DIR}/plugin/exl3import/include/exl3i_encoding.h
|
||||
${CMAKE_SOURCE_DIR}/plugin/exl3import/common/exl3i_decode.h
|
||||
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/radiance/arch)
|
||||
+16
-47
@@ -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;
|
||||
@@ -186,12 +185,6 @@ struct Model {
|
||||
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
static rad_op dense(RadBuilder* b, const char* dn, std::initializer_list<const char*> src,
|
||||
@@ -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)
|
||||
@@ -1015,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()),
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
* vLLM and SGLang serve it; HF's reference ignores it)
|
||||
*
|
||||
* The KDA core is GLM-5.3's (KdaState), the router GLM-5.3's with groups (GlmRouter), the
|
||||
* feed-forward MoeFP8. The KDA and MLA blocks around them are in this file.
|
||||
* feed-forward MoeQ. The KDA and MLA blocks around them are in this file.
|
||||
*
|
||||
* ============================== THE TRUNK'S FORM ==============================
|
||||
*
|
||||
@@ -38,7 +38,7 @@
|
||||
* and the MLA's expanded values are quantised by had_quant_act_i8g for their out projections;
|
||||
* the dense and shared gated products write gated_had_quant_i8g's codes (the shared one at
|
||||
* the group its own down weight is stored at), and the routed arm is int8 at one scale a 128
|
||||
* (MoeFP8::a8), so the rotated int8 experts read those codes at i8a8h. Where no loaded
|
||||
* (MoeQ::a8), so the rotated int8 experts read those codes at i8a8h. Where no loaded
|
||||
* library serves the rotating norm, each linear quantises the norm's bf16 output itself and
|
||||
* the routed experts read a rotated copy written once a layer. The linears the recipe keeps
|
||||
* bf16 (the KDA beta, the MLA's low-rank q and kv and its head gate) read the norm's bf16
|
||||
@@ -72,8 +72,8 @@
|
||||
#include <arch/rad_arch.h>
|
||||
#include <arch/rad_block_glm_kda.h>
|
||||
#include <arch/rad_block_glm_mtp.h>
|
||||
#include <arch/rad_block_mlp_fp8.h>
|
||||
#include <arch/rad_block_moe_fp8.h>
|
||||
#include <arch/rad_block_mlp_q.h>
|
||||
#include <arch/rad_block_moe_q.h>
|
||||
|
||||
namespace bailing_hybrid {
|
||||
|
||||
@@ -101,19 +101,19 @@ static const char* ck_name(Names& nm, const Shape& sh, int l, const char* pre, c
|
||||
* its all-reduce. */
|
||||
struct LingKda {
|
||||
struct Wire {
|
||||
ActFP8 input{};
|
||||
ActQ input{};
|
||||
rad_buf out = 0;
|
||||
ActFP8 core_out{};
|
||||
ActQ core_out{};
|
||||
KdaState::Wire core{};
|
||||
};
|
||||
Geom g{};
|
||||
Wire w{};
|
||||
KdaState core{};
|
||||
LinearFP8 qkv{}, beta{}, forget{}, gate{}, output{};
|
||||
QuantFP8 out_quant{};
|
||||
LinearQ qkv{}, beta{}, forget{}, gate{}, output{};
|
||||
QuantAct out_quant{};
|
||||
rad_op op_ar = 0;
|
||||
|
||||
/* Maps layer l's fused q|k|v and reads its stored form (LinearFP8::probe); declare() then does
|
||||
/* Maps layer l's fused q|k|v and reads its stored form (LinearQ::probe); declare() then does
|
||||
* not map it again. The model learns from it whether the trunk is rotated int8 before it
|
||||
* declares any activation buffer. */
|
||||
int probe_qkv(RadBuilder* b, Names& nm, const Geom& geom, const Shape& sh, int l,
|
||||
@@ -163,7 +163,7 @@ struct LingKda {
|
||||
RAD_ARCH_TRY(core.declare(b, nm, g, l, state, history, kc, w.core, ks));
|
||||
const char* on = nm.f("blk.%d.attn_output", l);
|
||||
RAD_ARCH_TRY(output.probe(b, nm, g, on, { ck("%s.o_proj.weight", "blk.%d.attn_output.weight") }));
|
||||
/* The out projection's input codes: on a rotated int8 trunk (ActFP8::q8_fed) an int8 out
|
||||
/* The out projection's input codes: on a rotated int8 trunk (ActQ::q8_fed) an int8 out
|
||||
* projection reads had_quant_act_i8g's, written here; otherwise a quantiser runs only for
|
||||
* a weight that does not read the bf16 plane. */
|
||||
if (w.core_out.q8_fed ? output.probed_i8 : !output.reads_x)
|
||||
@@ -190,8 +190,8 @@ struct LingKda {
|
||||
* replicated: every rank projects and stores the whole row, and splits the heads. */
|
||||
struct LingMla {
|
||||
struct Wire {
|
||||
ActFP8 input{};
|
||||
ActFP8 qa{}; /* [T, q_lora], the tiny query LoRA's normed latent (the trunk's,
|
||||
ActQ input{};
|
||||
ActQ qa{}; /* [T, q_lora], the tiny query LoRA's normed latent (the trunk's,
|
||||
projected through q_a, for the parts' GEMMs) */
|
||||
rad_buf q_rope = 0; /* [T, heads * rope] */
|
||||
rad_buf q_nope = 0; /* [T, heads * nope] */
|
||||
@@ -199,7 +199,7 @@ struct LingMla {
|
||||
rad_buf q_lat = 0; /* [T, heads, latent] */
|
||||
rad_buf gate = 0; /* [T, heads] */
|
||||
rad_buf attn = 0; /* [T, heads, latent] */
|
||||
ActFP8 value{}; /* [T, heads * v] */
|
||||
ActQ value{}; /* [T, heads * v] */
|
||||
rad_buf out = 0;
|
||||
};
|
||||
Geom g{};
|
||||
@@ -208,8 +208,8 @@ struct LingMla {
|
||||
int layer = 0;
|
||||
int64_t heads = 0, qw = 0, cw = 0;
|
||||
rad_kvgroup kv = 0;
|
||||
LinearFP8 q_a_proj{}, q_rope_proj{}, q_nope_proj{}, kv_a{}, g_proj{}, output{};
|
||||
QuantFP8 value_quant{}, qa_quant{};
|
||||
LinearQ q_a_proj{}, q_rope_proj{}, q_nope_proj{}, kv_a{}, g_proj{}, output{};
|
||||
QuantAct value_quant{}, qa_quant{};
|
||||
rad_weight kv_gain = 0, qa_gain = 0, kv_b = 0;
|
||||
rad_op op_qa_norm = 0, op_kv_norm = 0, op_q_rope = 0, op_k_rope = 0, op_store = 0,
|
||||
op_absorb = 0, op_attn = 0, op_expand = 0, op_ar = 0;
|
||||
@@ -234,7 +234,7 @@ struct LingMla {
|
||||
/* flash projects the query from the trunk; tiny runs it through a LoRA first (q_a, its
|
||||
* norm, then q_b), and the parts' rows come off q_b against the normed latent. */
|
||||
const int64_t qk = s.q_lora ? s.q_lora : g.n_embd;
|
||||
const ActFP8& qin = s.q_lora ? w.qa : w.input;
|
||||
const ActQ& qin = s.q_lora ? w.qa : w.input;
|
||||
auto ck = [&](const char* hf, const char* gg) -> const char* {
|
||||
/* The safetensors names are the layer prefix plus the projection (`pre`, `model.layers.%d`);
|
||||
* the release GGUF spells them blk./ssm. with the layer as %d. */
|
||||
@@ -288,7 +288,7 @@ struct LingMla {
|
||||
RAD_ARCH_TRY(q_nope_proj.declare(b, nm, g, nm.f("blk.%d.attn_q_nope", l), heads * s.nope,
|
||||
qk, RAD_SHARD_ROW, grp, { qsrc }, qin, w.q_nope));
|
||||
/* On a rotated int8 trunk the LoRA's latent carries an int8 pair that a part stored int8
|
||||
* quantises itself (LinearFP8's own had_quant_act_i8g) and no E4M3 pair, so no quantiser
|
||||
* quantises itself (LinearQ's own had_quant_act_i8g) and no E4M3 pair, so no quantiser
|
||||
* runs here. */
|
||||
if (s.q_lora && !q_nope_proj.reads_x && !w.qa.q8)
|
||||
RAD_ARCH_TRY(qa_quant.declare(b, g, w.qa, s.q_lora));
|
||||
@@ -378,7 +378,7 @@ struct LingMla {
|
||||
}
|
||||
const int64_t T = batch->n_tok, S = batch->n_seq;
|
||||
const RadOperand pos = praw(batch->positions, RAD_I32, T);
|
||||
const ActFP8& qin = s.q_lora ? w.qa : w.input;
|
||||
const ActQ& qin = s.q_lora ? w.qa : w.input;
|
||||
if (s.q_lora) {
|
||||
q_a_proj.step(c, w.input, w.qa.x, T);
|
||||
RAD_ISSUE_N(c, op_qa_norm, T, brows(w.qa.x, T), RAD_W(qa_gain), brows(w.qa.x, T));
|
||||
@@ -409,12 +409,12 @@ struct LingMla {
|
||||
struct Layer {
|
||||
bool mla = false, dense = false;
|
||||
rad_weight gain = 0;
|
||||
NormQuantFP8 norm{};
|
||||
NormQuant norm{};
|
||||
LingKda kda{};
|
||||
LingMla attn{};
|
||||
rad_op op_add = 0;
|
||||
MlpFP8 mlp{};
|
||||
MoeFP8 moe{};
|
||||
MlpQ mlp{};
|
||||
MoeQ moe{};
|
||||
};
|
||||
|
||||
struct Model {
|
||||
@@ -422,18 +422,18 @@ struct Model {
|
||||
Geom g{};
|
||||
Shape s{};
|
||||
/* Whether layer 0's probe found a rotated-int8 trunk, and its activation scale group: see
|
||||
* rad_fp8.h's trunk_rotation. `norm_fed`: the block norms write those codes themselves
|
||||
* rad_linear.h's trunk_rotation. `norm_fed`: the block norms write those codes themselves
|
||||
* (rmsnorm_had_quant_i8g is served). */
|
||||
bool trunk_rot = false, norm_fed = false;
|
||||
int64_t trunk_g8 = RAD_FP8_BLOCK;
|
||||
int64_t trunk_g8 = RAD_SCALE_GROUP;
|
||||
std::vector<Layer> layers;
|
||||
rad_kvgroup latent = 0, state = 0, conv = 0;
|
||||
rad_buf x = 0, y = 0, final_hidden = 0, logit_input = 0, logits = 0;
|
||||
ActFP8 act{};
|
||||
ActQ act{};
|
||||
LingKda::Wire kw{};
|
||||
LingMla::Wire aw{};
|
||||
MlpFP8::Wire dw{};
|
||||
MoeFP8::Wire mw{};
|
||||
MlpQ::Wire dw{};
|
||||
MoeQ::Wire mw{};
|
||||
rad_weight token = 0, head = 0, final_gain = 0;
|
||||
rad_op embed = 0, embed_ar = 0, norm = 0, gather = 0, head_op = 0;
|
||||
/* The draft head and its layer, declared only when the deployment speculates. */
|
||||
@@ -549,9 +549,9 @@ static void slice_of(int64_t blocks, int world, int rank, int first, int64_t* lo
|
||||
|
||||
/* The activation code pairs follow the trunk's form (the file's head comment). On a rotated int8
|
||||
* trunk every pair is int8 at the trunk's group and is declared before the wires are copied, so
|
||||
* each block sees whether its producer writes the codes (ActFP8::q8_fed): the norms where
|
||||
* each block sees whether its producer writes the codes (ActQ::q8_fed): the norms where
|
||||
* `norm_fed`, the out projections' quantisers always, the gated products where gated_had_quant_i8g
|
||||
* is served (ActFP8::declare_pair). A producer whose rotating form is not served keeps an E4M3 pair
|
||||
* is served (ActQ::declare_pair). A producer whose rotating form is not served keeps an E4M3 pair
|
||||
* that no linear reads, and each int8 linear then quantises the bf16 plane itself. */
|
||||
static int buffers(RadBuilder* b, Model& m) {
|
||||
auto& g = m.g;
|
||||
@@ -565,7 +565,7 @@ static int buffers(RadBuilder* b, Model& m) {
|
||||
};
|
||||
/* A rotated int8 trunk's pair on `a`, written by its producer (`fed`) or by each int8 linear
|
||||
* reading it. */
|
||||
auto i8_pair = [&](ActFP8& a, const char* n, int64_t width, bool fed) -> int {
|
||||
auto i8_pair = [&](ActQ& a, const char* n, int64_t width, bool fed) -> int {
|
||||
RAD_ARCH_TRY(a.declare_qs(b, nm, g, n, width, 0, true, false, g8));
|
||||
a.q8_fed = a.q8_rot = fed;
|
||||
return RAD_OK;
|
||||
@@ -636,7 +636,7 @@ static int buffers(RadBuilder* b, Model& m) {
|
||||
|
||||
/* `shared_g8`: on a rotated int8 trunk, the scale group of the shared expert's stored down weight,
|
||||
* which its input codes take. */
|
||||
static int moe_buffers(RadBuilder* b, Model& m, const MoeFP8::Config& mc, int64_t shared_g8) {
|
||||
static int moe_buffers(RadBuilder* b, Model& m, const MoeQ::Config& mc, int64_t shared_g8) {
|
||||
auto& g = m.g;
|
||||
auto& nm = m.nm;
|
||||
const int64_t T = g.max_tok, E = g.n_embd, F = mc.n_ff_exp, k = mc.top_k;
|
||||
@@ -656,9 +656,9 @@ static int moe_buffers(RadBuilder* b, Model& m, const MoeFP8::Config& mc, int64_
|
||||
mw.eff.x = bf("expert_ff", { T * k, F });
|
||||
if (m.trunk_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 (MoeFP8::a8). */
|
||||
* at one scale a 128 of K, which the grouped GEMM's int8 rows read (MoeQ::a8). */
|
||||
RAD_ARCH_TRY(mw.eff.declare_qs(b, nm, g, "expert_ff", F, T * k, true, false,
|
||||
RAD_FP8_BLOCK));
|
||||
RAD_SCALE_GROUP));
|
||||
mw.eff.q8_fed = mw.eff.q8_rot = true;
|
||||
} else {
|
||||
RAD_ARCH_TRY(mw.eff.declare_qs(b, nm, g, "expert_ff", F, T * k));
|
||||
@@ -666,15 +666,15 @@ static int moe_buffers(RadBuilder* b, Model& m, const MoeFP8::Config& mc, int64_
|
||||
mw.edn = bf("expert_down", { T * k, E });
|
||||
if (m.trunk_rot) {
|
||||
/* The routed gate_up reads the norm's own codes where it writes them, else a rotated int8
|
||||
* copy of the block input that MoeFP8 writes once a layer (Wire::hr). */
|
||||
* copy of the block input that MoeQ writes once a layer (Wire::hr). */
|
||||
if (!m.norm_fed) {
|
||||
RAD_ARCH_TRY(mw.hr.declare_qs(b, nm, g, "normed_rot", E, 0, true, false,
|
||||
RAD_FP8_BLOCK));
|
||||
RAD_SCALE_GROUP));
|
||||
mw.hr.q8_fed = mw.hr.q8_rot = true;
|
||||
}
|
||||
} else if (mc.expert_rot) {
|
||||
mw.hr.q = decl_b(b, nm.f("normed_rot.q"), RAD_F8E4M3, { T, E });
|
||||
mw.hr.s = decl_b(b, nm.f("normed_rot.s"), RAD_F32, { T, E / RAD_FP8_BLOCK });
|
||||
mw.hr.s = decl_b(b, nm.f("normed_rot.s"), RAD_F32, { T, E / RAD_SCALE_GROUP });
|
||||
if (!mw.hr.q || !mw.hr.s) return RAD_E_INVAL;
|
||||
}
|
||||
if (mc.n_ff_shared > 0) {
|
||||
@@ -713,8 +713,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
"for 1, 2 or 4 ranks\n", world);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (s.heads % world || s.ff_exp % RAD_FP8_BLOCK || s.ff_shared % RAD_FP8_BLOCK ||
|
||||
s.ff_exp / RAD_FP8_BLOCK < world) {
|
||||
if (s.heads % world || s.ff_exp % RAD_SCALE_GROUP || s.ff_shared % RAD_SCALE_GROUP ||
|
||||
s.ff_exp / RAD_SCALE_GROUP < world) {
|
||||
fprintf(stderr, "radiance: bailing_hybrid: %lld heads and experts of %lld do not split "
|
||||
"over %d ranks in whole heads and 128-column blocks\n",
|
||||
(long long)s.heads, (long long)s.ff_exp, world);
|
||||
@@ -737,7 +737,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* the six 128-column blocks of an expert split 2, 2, 1, 1 over the ranks, rotated by the
|
||||
* expert's number mod 4, so every rank carries six blocks per four experts (moe_gemm_q_mod4).
|
||||
* The shared expert splits the same way, unrotated. */
|
||||
MoeFP8::Config mc;
|
||||
MoeQ::Config mc;
|
||||
mc.n_expert = mc.n_expert_all = s.experts;
|
||||
mc.top_k = s.top_k;
|
||||
mc.sigmoid_router = 1;
|
||||
@@ -752,14 +752,14 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* whole width, so a calibration run gives every rank whole experts (below). */
|
||||
mc.calib = calib_dir() != nullptr ? 1 : 0;
|
||||
mc.probed_expert = (int64_t)g.rank * (s.experts / world);
|
||||
const int64_t eb = s.ff_exp / RAD_FP8_BLOCK, sb = s.ff_shared / RAD_FP8_BLOCK;
|
||||
const int64_t eb = s.ff_exp / RAD_SCALE_GROUP, sb = s.ff_shared / RAD_SCALE_GROUP;
|
||||
if (world == 4) {
|
||||
int64_t widest = 0;
|
||||
for (int q = 0; q < 4; ++q) {
|
||||
int64_t lo, hi;
|
||||
slice_of(eb, world, g.rank, q, &lo, &hi);
|
||||
mc.ff_lo4[q] = lo * RAD_FP8_BLOCK;
|
||||
mc.ff_hi4[q] = hi * RAD_FP8_BLOCK;
|
||||
mc.ff_lo4[q] = lo * RAD_SCALE_GROUP;
|
||||
mc.ff_hi4[q] = hi * RAD_SCALE_GROUP;
|
||||
widest = std::max(widest, mc.ff_hi4[q] - mc.ff_lo4[q]);
|
||||
}
|
||||
mc.n_ff_exp = widest;
|
||||
@@ -775,11 +775,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
} else {
|
||||
int64_t lo, hi;
|
||||
slice_of(sb, world, g.rank, 0, &lo, &hi);
|
||||
mc.shared_lo = lo * RAD_FP8_BLOCK;
|
||||
mc.shared_hi = hi * RAD_FP8_BLOCK;
|
||||
mc.shared_lo = lo * RAD_SCALE_GROUP;
|
||||
mc.shared_hi = hi * RAD_SCALE_GROUP;
|
||||
mc.n_ff_shared = mc.shared_hi - mc.shared_lo;
|
||||
}
|
||||
if (s.ff_dense % (world * RAD_FP8_BLOCK)) {
|
||||
if (s.ff_dense % (world * RAD_SCALE_GROUP)) {
|
||||
fprintf(stderr, "radiance: bailing_hybrid: the dense feed-forward's %lld columns do not "
|
||||
"split over %d ranks in 128-column blocks\n", (long long)s.ff_dense, world);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
@@ -790,10 +790,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
/* ---- each routed layer's expert format, read before any buffer is declared: rotated experts
|
||||
* need the rotated activation pair, sized here. The MTP layer follows the trunk's. */
|
||||
const bool mtp = ctx->max_spec > 0 && cfg(meta, "num_nextn_predict_layers", 0) == 1;
|
||||
std::vector<MoeFP8::Src> msrc((size_t)s.n_layer + 1);
|
||||
std::vector<MoeQ::Src> msrc((size_t)s.n_layer + 1);
|
||||
for (int l = (int)s.dense_layers; l < (int)s.n_layer + (mtp ? 1 : 0); ++l) {
|
||||
const char* pre = nm.ckpt("model.layers.%d", l);
|
||||
MoeFP8::Src& ms = msrc[(size_t)l];
|
||||
MoeQ::Src& ms = msrc[(size_t)l];
|
||||
ms.cfg = mc;
|
||||
ms.cfg.swiglu_limit = limit_at(s.lim_exp, l);
|
||||
ms.cfg.shared_swiglu_limit = limit_at(s.lim_shared, l);
|
||||
@@ -814,7 +814,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
}
|
||||
ms.shared = s.gguf ? nm.ckpt("blk.%d.mlp.shared_experts", l)
|
||||
: nm.ckpt("%s.mlp.shared_experts", pre);
|
||||
RAD_ARCH_TRY(MoeFP8::probe(b, nm, l, ms, &ms.cfg));
|
||||
RAD_ARCH_TRY(MoeQ::probe(b, nm, l, ms, &ms.cfg));
|
||||
if (ms.cfg.expert_rot) mc.expert_rot = 1;
|
||||
if (ms.cfg.expert_bf16) mc.expert_bf16 = 1;
|
||||
}
|
||||
@@ -842,7 +842,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
}
|
||||
|
||||
/* ---- the trunk's stored form, read from layer 0's fused q|k|v through that layer's own
|
||||
* LinearFP8 (layer 0 is KDA: the last of each group of `layer_group_size` > 1 is MLA). The
|
||||
* LinearQ (layer 0 is KDA: the last of each group of `layer_group_size` > 1 is MLA). The
|
||||
* activations below carry rotated int8 codes only for a rotated trunk. */
|
||||
m.layers.resize((size_t)s.n_layer);
|
||||
RAD_ARCH_TRY(m.layers[0].kda.probe_qkv(b, nm, g, s, 0,
|
||||
@@ -854,10 +854,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
}
|
||||
int64_t shared_g8 = m.trunk_g8;
|
||||
if (m.trunk_rot) {
|
||||
/* The routed experts read the trunk's rotated int8 codes (MoeFP8::a8), which only a
|
||||
* rotated expert meets. A clamped layer clamps, then quantises (GateQuantFP8). */
|
||||
/* The routed experts read the trunk's rotated int8 codes (MoeQ::a8), which only a
|
||||
* rotated expert meets. A clamped layer clamps, then quantises (GateQuant). */
|
||||
for (int l = (int)s.dense_layers; l < (int)s.n_layer + (mtp ? 1 : 0); ++l) {
|
||||
const MoeFP8::Config& c = msrc[(size_t)l].cfg;
|
||||
const MoeQ::Config& c = msrc[(size_t)l].cfg;
|
||||
if (c.expert_bf16 || !c.expert_rot) {
|
||||
fprintf(stderr, "radiance: bailing_hybrid: the trunk is rotated int8 and layer %d's "
|
||||
"routed experts are %s; a rotated trunk's experts read its int8 codes "
|
||||
@@ -869,17 +869,17 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
m.norm_fed = rad_op_declared(b, "rmsnorm_had_quant_i8g") != 0;
|
||||
/* 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 LinearFP8 (which MoeFP8 then does not map again). */
|
||||
* own LinearQ (which MoeQ then does not map again). */
|
||||
const int lm = (int)s.dense_layers;
|
||||
if (lm < (int)s.n_layer && mc.n_ff_shared > 0) {
|
||||
LinearFP8& sd = m.layers[(size_t)lm].moe.sh_down;
|
||||
LinearQ& sd = m.layers[(size_t)lm].moe.sh_down;
|
||||
RAD_ARCH_TRY(sd.probe(b, nm, g, nm.f("blk.%d.ffn_down_shexp", lm),
|
||||
{ nm.ckpt("%s.down_proj.weight", msrc[(size_t)lm].shared) }));
|
||||
if (sd.probed_i8) shared_g8 = sd.probed_g8;
|
||||
}
|
||||
} else {
|
||||
for (int l = (int)s.dense_layers; l < (int)s.n_layer + (mtp ? 1 : 0); ++l) {
|
||||
const MoeFP8::Config& c = msrc[(size_t)l].cfg;
|
||||
const MoeQ::Config& c = msrc[(size_t)l].cfg;
|
||||
if (c.expert_i8 || c.expert_iqr) {
|
||||
fprintf(stderr, "radiance: bailing_hybrid: layer %d's routed experts are rotated "
|
||||
"int8 and the trunk is not; they read the trunk's rotated int8 codes, "
|
||||
@@ -969,7 +969,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
{ m.x, m.y }, { m.x });
|
||||
if (!lay.op_add) return RAD_E_INVAL;
|
||||
if (lay.dense) {
|
||||
MlpFP8::Src ds{ s.gguf ? nm.ckpt("blk.%d.ffn_norm.weight", l)
|
||||
MlpQ::Src ds{ s.gguf ? nm.ckpt("blk.%d.ffn_norm.weight", l)
|
||||
: nm.ckpt("%s.post_attention_layernorm.weight", pre),
|
||||
s.gguf ? nm.ckpt("blk.%d.ffn_gate.weight", l)
|
||||
: nm.ckpt("%s.mlp.gate_proj.weight", pre),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/* 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. */
|
||||
/* 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"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/* 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. */
|
||||
/* 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"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/* 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. */
|
||||
/* 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"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/* 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. */
|
||||
/* 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"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/* 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. */
|
||||
/* 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"
|
||||
|
||||
+195
-93
@@ -40,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.
|
||||
@@ -52,6 +52,7 @@
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
@@ -206,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;
|
||||
@@ -232,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;
|
||||
@@ -248,7 +261,7 @@ 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] = {};
|
||||
@@ -267,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)),
|
||||
@@ -826,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",
|
||||
@@ -843,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 */
|
||||
@@ -1188,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
|
||||
@@ -1406,10 +1437,107 @@ static void step_prompt(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
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);
|
||||
@@ -1432,33 +1560,7 @@ 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,
|
||||
|
||||
+350
-28
@@ -228,7 +228,7 @@ inline bool calib_write(RadCtx* c, rad_buf b, int64_t k, long long rows, const c
|
||||
}
|
||||
|
||||
/* A selected architecture tap may use the build context's directory directly, rather than the
|
||||
* legacy process environment helper above. */
|
||||
* 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;
|
||||
@@ -380,6 +380,18 @@ private:
|
||||
} \
|
||||
} 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
|
||||
* C++; rad_builder.h points here). */
|
||||
@@ -552,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);
|
||||
@@ -569,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. */
|
||||
@@ -677,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
|
||||
@@ -711,8 +824,9 @@ inline void prefetch_beside(RadCtx* c, rad_op op, rad_weight w, int64_t T) {
|
||||
* 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, 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. */
|
||||
/* `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));
|
||||
@@ -741,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
|
||||
@@ -762,6 +876,9 @@ struct Geom {
|
||||
/* --kv-resident in tokens (RadBuildCtx::kv_resident_blocks), 0 when nothing streams: what
|
||||
* kv_resolve_declare states as the ring's depth. */
|
||||
int64_t kv_resident = 0;
|
||||
/* --kv-host-tokens (RadBuildCtx::kv_host_tokens), 0 when not set: the streamed group's id
|
||||
* space is this in whole blocks when that is under max_seqs x max_ctx (kv_resolve_declare). */
|
||||
int64_t kv_host_tokens = 0;
|
||||
int max_spec = 0;
|
||||
/* Most rows the sampler can want in one step: one per sequence, or one per draft position per
|
||||
* sequence at a speculative verify. Bounds the logits buffer (at a 248K vocab, 63 MiB rather
|
||||
@@ -805,17 +922,24 @@ 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_fp8.h's linear_is_w8h: IQ8R, or the 128-group form) with
|
||||
/* 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 (ActFP8::declare_pair). Model-wide as
|
||||
* 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;
|
||||
/* ERNIE-5.5's int8 trunk: the scale group (256) of the IQ8R linears its container stores. The
|
||||
* plugin reads it from one linear's encoding before declaring the shared activations, which
|
||||
* carry rotated int8 codes (ActQ::declare_trunk). */
|
||||
int64_t i8_group = 0;
|
||||
/* True when serving a block-FP8 trunk container (e.g. ERNIE-5.5 native FP8+MXFP4 release)
|
||||
* rather than IQ8R. */
|
||||
bool native_fp = false;
|
||||
|
||||
int64_t q_dim() const { return n_head * head_dim; }
|
||||
int64_t kv_dim() const { return n_head_kv * head_dim; }
|
||||
@@ -823,11 +947,148 @@ 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. */
|
||||
* RAD_DT_INVALID (not given). Every architecture in this tree passes RAD_BF16 as the default.
|
||||
*
|
||||
* The rotated int4 and int6 caches (RAD_I4R, RAD_I6R, abi/rad_kv_i4r.h) have attention kernels at
|
||||
* one geometry only, so they are refused here, by name, unless the plugin asks for them through
|
||||
* rad_kv_cache_dtype_i4r: a group declared i4r or i6r that no attention row reads would fail at
|
||||
* declare with no word of why. The refusal returns RAD_DT_INVALID, which rad_decl_kv_group refuses
|
||||
* in turn. */
|
||||
static inline uint32_t rad_kv_cache_dtype(const RadBuildCtx* c, uint32_t dflt) {
|
||||
if (c && (c->kv_dtype == RAD_I4R || c->kv_dtype == RAD_I6R)) {
|
||||
const int six = c->kv_dtype == RAD_I6R;
|
||||
fprintf(stderr, "radiance: --kv-cache-dtype %s: this model's attention has no rotated "
|
||||
"int%d cache (it is Qwen3.8-Flash-Next's, qwen4exp_fp8); i8 is the 8-bit cache "
|
||||
"every paged attention serves\n", six ? "i6r" : "i4r", six ? 6 : 4);
|
||||
return RAD_DT_INVALID;
|
||||
}
|
||||
return (c && c->kv_dtype != RAD_DT_INVALID) ? (uint32_t)c->kv_dtype : dflt;
|
||||
}
|
||||
/* rad_kv_cache_dtype for a plugin whose attention rows serve the rotated int4 and int6 caches. */
|
||||
static inline uint32_t rad_kv_cache_dtype_i4r(const RadBuildCtx* c, uint32_t dflt) {
|
||||
if (c && (c->kv_dtype == RAD_I4R || c->kv_dtype == RAD_I6R)) return (uint32_t)c->kv_dtype;
|
||||
return rad_kv_cache_dtype(c, dflt);
|
||||
}
|
||||
/* Divide, refusing (with a message naming `what`) rather than rounding, before any weight is
|
||||
* mapped. */
|
||||
inline int divide_or_fail(int64_t v, int world, const char* what, int64_t* out) {
|
||||
@@ -845,7 +1106,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. */
|
||||
@@ -866,6 +1127,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. */
|
||||
@@ -902,6 +1181,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.
|
||||
@@ -910,7 +1200,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;
|
||||
@@ -920,6 +1212,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;
|
||||
}
|
||||
@@ -942,8 +1249,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) {
|
||||
@@ -997,7 +1305,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
|
||||
@@ -1017,7 +1325,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,
|
||||
@@ -1042,6 +1350,7 @@ inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c,
|
||||
g.max_seqs = c->max_seqs;
|
||||
g.max_ctx = c->max_ctx;
|
||||
g.kv_resident = c->kv_resident_blocks;
|
||||
g.kv_host_tokens = c->kv_host_tokens;
|
||||
g.max_spec = c->max_spec;
|
||||
g.max_logit_rows = c->max_seqs * (c->max_spec > 0 ? c->max_spec + 1 : 1);
|
||||
if (g.max_logit_rows > c->max_tok) g.max_logit_rows = c->max_tok;
|
||||
@@ -1058,9 +1367,9 @@ inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c,
|
||||
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",
|
||||
@@ -1214,7 +1523,10 @@ inline void kv_stage_next(RadCtx* c, rad_kvgroup group, int layer) {
|
||||
|
||||
/* The `kv_resolve` a streamed group's block declares. None of its geometry is free:
|
||||
*
|
||||
* blocks the block-id space a selection can name: max_seqs sequences of the context;
|
||||
* blocks the block-id space a selection can name: max_seqs sequences of the context, or
|
||||
* --kv-host-tokens in whole blocks when that is fewer (core/kvstream/plan.h,
|
||||
* kvstream_id_blocks): the residency map and the mirror row are that long, and the
|
||||
* resolve refuses a map shorter than its declaration;
|
||||
* slots the ring --kv-resident carves, in whole blocks, raised to one decode step's
|
||||
* selection (max_seqs x (1 + n_spec) x sel_pitch) as kvstream_ring raises it, and
|
||||
* at most `blocks`; the resolve is issued with the pool's depth, so declaring the
|
||||
@@ -1232,7 +1544,9 @@ inline rad_op kv_resolve_declare(RadBuilder* b, const Geom& g, rad_kvgroup kv, r
|
||||
if (!rad_op_declared(b, "kv_resolve") || !sel || !nsel || sel_pitch <= 0) return 0;
|
||||
const int64_t bs = rad_kv_block_size(b, kv);
|
||||
const int64_t bbytes = rad_kv_layer_bytes(b, kv);
|
||||
const int64_t blocks = bs > 0 ? g.max_seqs * ((g.max_ctx + bs - 1) / bs) : 0;
|
||||
int64_t blocks = bs > 0 ? g.max_seqs * ((g.max_ctx + bs - 1) / bs) : 0;
|
||||
if (bs > 0 && g.kv_host_tokens > 0 && (g.kv_host_tokens + bs - 1) / bs < blocks)
|
||||
blocks = (g.kv_host_tokens + bs - 1) / bs;
|
||||
if (bs <= 0 || bbytes <= 0 || blocks <= 0) return 0;
|
||||
const int64_t ring = g.kv_resident > 0 ? (g.kv_resident + bs - 1) / bs : 0;
|
||||
const int64_t step = g.max_seqs * (1 + (g.max_spec > 0 ? g.max_spec : 0)) * sel_pitch;
|
||||
@@ -1436,15 +1750,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());
|
||||
@@ -1504,7 +1822,7 @@ 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 (AttnGatedFP8::qsa_use), which decides what
|
||||
/* 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,
|
||||
@@ -1598,7 +1916,10 @@ inline int drafter_geom(Geom& dg, const Geom& target, const RadModelMeta* meta,
|
||||
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);
|
||||
@@ -1618,7 +1939,8 @@ 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_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) {
|
||||
|
||||
@@ -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});
|
||||
|
||||
@@ -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,9 +1,9 @@
|
||||
/* 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.
|
||||
@@ -14,22 +14,22 @@
|
||||
*
|
||||
* 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 {
|
||||
|
||||
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] */
|
||||
@@ -37,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. */
|
||||
@@ -121,7 +121,7 @@ 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{};
|
||||
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. */
|
||||
@@ -134,7 +134,7 @@ struct AttnGatedFP8 {
|
||||
/* 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;
|
||||
NormQuantFP8 nq_h{};
|
||||
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 */
|
||||
@@ -145,6 +145,11 @@ struct AttnGatedFP8 {
|
||||
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 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;
|
||||
@@ -157,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.
|
||||
@@ -165,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,
|
||||
@@ -190,7 +195,7 @@ 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,
|
||||
@@ -258,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_) {
|
||||
@@ -296,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.
|
||||
*
|
||||
@@ -318,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));
|
||||
@@ -416,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. */
|
||||
@@ -481,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.
|
||||
@@ -507,7 +532,7 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
if (g.w_bf16) {
|
||||
RAD_ARCH_TRY(gate_pair(w.gate));
|
||||
} else {
|
||||
/* Rotated int8 codes (ActFP8::q8_rot): gate_had_quant_i8g, had_quant_act_i8g's codes. */
|
||||
/* 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,
|
||||
@@ -516,7 +541,7 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
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));
|
||||
@@ -528,10 +553,10 @@ 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. Rotated int8 codes (ActFP8::q8_rot) take attn_paged_gate_had_quant, the merge
|
||||
* 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_FP8_BLOCK &&
|
||||
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),
|
||||
@@ -542,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) {
|
||||
@@ -553,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),
|
||||
@@ -591,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,
|
||||
@@ -619,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 */
|
||||
@@ -632,7 +651,7 @@ 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,
|
||||
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;
|
||||
@@ -896,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),
|
||||
@@ -919,6 +957,7 @@ 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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -950,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,11 +1,12 @@
|
||||
/* 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
|
||||
* - Optional per-head q/k norm (Src::q_norm/k_norm), absent by default.
|
||||
* The plain path has 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.
|
||||
*
|
||||
@@ -18,27 +19,28 @@
|
||||
* (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 k = 0; /* optional contiguous keys for per-head Q/K normalization */
|
||||
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
|
||||
@@ -49,6 +51,8 @@ struct AttnFP8 {
|
||||
const char* k = nullptr;
|
||||
const char* v = nullptr;
|
||||
const char* o = nullptr;
|
||||
const char* q_norm = nullptr; /* both gains, or neither; Qwen3-style head norms */
|
||||
const char* k_norm = nullptr;
|
||||
};
|
||||
|
||||
Geom g{};
|
||||
@@ -61,12 +65,15 @@ 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;
|
||||
bool head_norms = false;
|
||||
rad_weight w_q_norm = 0, w_k_norm = 0;
|
||||
rad_op op_klift = 0, op_q_norm = 0, op_k_norm = 0, op_rope_q = 0, op_rope_k = 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,
|
||||
@@ -75,7 +82,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;
|
||||
@@ -106,7 +113,7 @@ 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,
|
||||
@@ -120,7 +127,10 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
|
||||
RAD_ARCH_TRY(qkv.span_parts(b, lo, hi, tot, 3));
|
||||
}
|
||||
|
||||
if (n_rot > 0)
|
||||
head_norms = src.q_norm && src.k_norm;
|
||||
if ((src.q_norm != nullptr) != (src.k_norm != nullptr) || (head_norms && !w.k))
|
||||
return RAD_E_INVAL;
|
||||
if (n_rot > 0 && !head_norms)
|
||||
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});
|
||||
|
||||
@@ -129,11 +139,37 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
|
||||
* 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);
|
||||
|
||||
if (head_norms) {
|
||||
/* A fused QKV row is pitched between tokens. Lift Q and K before flattening
|
||||
* tokens x heads into the contiguous rows expected by per-head rmsnorm. */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_norm.weight", l), src.q_norm));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k_norm.weight", l), src.k_norm));
|
||||
w_q_norm = decl_w(b, nm.f("blk.%d.attn_q_norm.weight", l), RAD_F32,
|
||||
{g.head_dim}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
w_k_norm = decl_w(b, nm.f("blk.%d.attn_k_norm.weight", l), RAD_F32,
|
||||
{g.head_dim}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
op_klift = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", kv_dim),
|
||||
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
|
||||
RAD_NOWEIGHTS), {w.qkv}, {w.k});
|
||||
auto norm = [&](int64_t heads, rad_weight gain, rad_buf data) {
|
||||
return rw(b, 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", 0.0), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(gain)), {data}, {data});
|
||||
};
|
||||
op_q_norm = norm(g.n_head, w_q_norm, w.q);
|
||||
op_k_norm = norm(g.n_head_kv, w_k_norm, w.k);
|
||||
if (n_rot > 0) {
|
||||
op_rope_q = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, 0, n_rot, mode),
|
||||
{w.q}, {w.q});
|
||||
op_rope_k = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head_kv, 0, n_rot, mode),
|
||||
{w.k}, {w.k});
|
||||
}
|
||||
}
|
||||
|
||||
/* Declared before kv_store, which reads back the resolved `block_size` (rad_block_attn_gated.h
|
||||
* explains declare vs issue order). */
|
||||
@@ -153,7 +189,8 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
|
||||
RAD_INT("block_size", rad_kv_block_size(b, kv)),
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.qkv}, {});
|
||||
head_norms ? std::initializer_list<rad_buf>{w.qkv, w.k}
|
||||
: std::initializer_list<rad_buf>{w.qkv}, {});
|
||||
|
||||
/* The out-projection's input quantiser; a plain `quant_act_fp8`, as there is no gate pass to
|
||||
* fold it into. Declared where the activation carries a code pair its producer writes: an int8
|
||||
@@ -163,13 +200,7 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
|
||||
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",
|
||||
@@ -180,7 +211,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;
|
||||
@@ -195,12 +226,22 @@ inline void AttnFP8::step(RadCtx* c, const RadBatch* batch) const {
|
||||
* leaves the value heads alone. */
|
||||
if (op_rope) RAD_ISSUE(c, op_rope, brows(w.qkv, T), rope_posmc(g, batch, T));
|
||||
|
||||
if (head_norms) {
|
||||
RAD_ISSUE(c, op_qlift, bcol(w.qkv, 0, q_dim, T), brows(w.q, T));
|
||||
RAD_ISSUE(c, op_klift, bcol(w.qkv, q_dim, kv_dim, T), brows(w.k, T));
|
||||
RAD_ISSUE_N(c, op_q_norm, T * g.n_head, brows(w.q, T), RAD_W(w_q_norm), brows(w.q, T));
|
||||
RAD_ISSUE_N(c, op_k_norm, T * g.n_head_kv, brows(w.k, T), RAD_W(w_k_norm), brows(w.k, T));
|
||||
if (op_rope_q) RAD_ISSUE(c, op_rope_q, brows(w.q, T), rope_posmc(g, batch, T));
|
||||
if (op_rope_k) RAD_ISSUE(c, op_rope_k, brows(w.k, T), rope_posmc(g, batch, T));
|
||||
}
|
||||
|
||||
/* k and v are column slices of the fused row, at q_dim and q_dim + kv_dim. */
|
||||
RAD_ISSUE(c, op_kv_store,
|
||||
bcol(w.qkv, q_dim, kv_dim, T), bcol(w.qkv, q_dim + kv_dim, kv_dim, T),
|
||||
head_norms ? brows(w.k, T) : bcol(w.qkv, q_dim, kv_dim, T),
|
||||
bcol(w.qkv, q_dim + kv_dim, kv_dim, T),
|
||||
praw(slot, RAD_I32, T), kv_cache(kv, layer));
|
||||
|
||||
RAD_ISSUE(c, op_qlift, bcol(w.qkv, 0, q_dim, T), brows(w.q, T));
|
||||
if (!head_norms) RAD_ISSUE(c, op_qlift, bcol(w.qkv, 0, q_dim, T), brows(w.q, T));
|
||||
|
||||
RAD_ISSUE_N(c, op_attn, batch->max_q_len,
|
||||
brows(w.q, T), kv_cache(kv, layer),
|
||||
@@ -220,4 +261,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 "
|
||||
|
||||
+151
-65
@@ -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
|
||||
@@ -58,12 +58,16 @@
|
||||
*
|
||||
* 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 ==============================
|
||||
*
|
||||
@@ -84,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
|
||||
@@ -106,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 {
|
||||
@@ -151,6 +155,15 @@ struct Dflash2 {
|
||||
* 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;
|
||||
@@ -165,13 +178,13 @@ 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 (DenseFP8::w8h: IQ8R, or a rotated int8 or
|
||||
/* 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_FP8_BLOCK;
|
||||
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. */
|
||||
@@ -226,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
|
||||
@@ -258,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;
|
||||
@@ -284,9 +297,9 @@ struct Dflash2 {
|
||||
/* 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] = {};
|
||||
|
||||
@@ -348,6 +361,37 @@ struct Dflash2 {
|
||||
/* 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;
|
||||
@@ -368,7 +412,7 @@ struct Dflash2 {
|
||||
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_FP8_BLOCK;
|
||||
*g8 = *i8 ? linear_w8h_group(fe) : (int64_t)RAD_SCALE_GROUP;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -392,7 +436,7 @@ 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);
|
||||
@@ -400,6 +444,18 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
}
|
||||
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);
|
||||
@@ -429,13 +485,13 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
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;
|
||||
@@ -458,7 +514,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
w_norm = decl_w(b, nm.f("dflash.norm.weight"), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, 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.
|
||||
@@ -485,7 +541,9 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
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 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
|
||||
@@ -638,7 +696,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- 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.
|
||||
*
|
||||
@@ -649,9 +707,9 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
* 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_FP8_BLOCK;
|
||||
const int64_t qgr = cfg.act_i8 ? cfg.act_g8 : (int64_t)RAD_SCALE_GROUP;
|
||||
{
|
||||
auto fits = [&](const DenseFP8& d) {
|
||||
auto fits = [&](const DenseQ& d) {
|
||||
return d.w8h == cfg.act_i8 && (!d.w8h || d.g8 == cfg.act_g8);
|
||||
};
|
||||
bool same = fits(w_fc);
|
||||
@@ -738,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),
|
||||
@@ -754,13 +818,8 @@ 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, qop,
|
||||
@@ -821,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 && !w_gu[i].w8h)
|
||||
* 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});
|
||||
@@ -947,13 +1006,7 @@ 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)),
|
||||
@@ -1015,32 +1068,48 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
{w.h}, {w.sel_h});
|
||||
/* LiLiCorr's head is the plugin's (rad_block_lilicorr.h), over sel_h. */
|
||||
if (cfg.lili) return RAD_OK;
|
||||
if (!head_bf16)
|
||||
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});
|
||||
op_dlogits = head_bf16
|
||||
/* 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_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_dh)),
|
||||
{w.sel_h}, {w.dlog})
|
||||
: head_i8
|
||||
? 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", "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});
|
||||
if (cfg.scap > 0.0) {
|
||||
? 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)),
|
||||
@@ -1051,18 +1120,18 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
/* 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
|
||||
@@ -1073,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),
|
||||
@@ -1210,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);
|
||||
@@ -1289,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;
|
||||
@@ -1398,7 +1475,9 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
|
||||
/* `dsum` is group-major, [n_embd/group][ceil(M/16)*16], so it has no row slice; pass it
|
||||
* whole. */
|
||||
if (head_bf16) {
|
||||
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));
|
||||
@@ -1408,13 +1487,17 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
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));
|
||||
@@ -1422,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);
|
||||
}
|
||||
|
||||
@@ -96,9 +96,9 @@
|
||||
* 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 eight bits). DenseFP8 reads block fp8 or MXFP4 against E4M3 activations, or a
|
||||
* 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.
|
||||
@@ -110,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
|
||||
@@ -120,7 +120,7 @@
|
||||
#define RAD_BLOCK_DSPARK_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
#include "rad_fp8.h"
|
||||
#include "rad_linear.h"
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
@@ -138,13 +138,13 @@ 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 (DenseFP8::w8h: IQ8R, or a rotated int8 or
|
||||
/* 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_FP8_BLOCK;
|
||||
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; }
|
||||
@@ -161,7 +161,7 @@ struct Dspark {
|
||||
rad_buf ck = 0; /* [max_tok, kv_dim] one layer's K, reused across layers */
|
||||
rad_buf cv = 0; /* [max_tok, kv_dim] one layer's V, reused across layers */
|
||||
/* The codes and scales the linears read: e4m3 | f32 [.., /128], or with Config::act_i8
|
||||
* i8 | f32 [.., /act_g8]. The same holds for the three ActFP8 pairs below, whose `q` and
|
||||
* 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;
|
||||
@@ -169,15 +169,15 @@ struct Dspark {
|
||||
/* ---- 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 */
|
||||
@@ -208,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 */
|
||||
@@ -218,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;
|
||||
@@ -230,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;
|
||||
@@ -257,7 +257,7 @@ struct Dspark {
|
||||
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_FP8_BLOCK;
|
||||
*g8 = *i8 ? linear_w8h_group(fe) : (int64_t)RAD_SCALE_GROUP;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -334,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.
|
||||
*
|
||||
@@ -412,15 +412,15 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
|
||||
/* ---------------------------------------------------------------- the context pass
|
||||
*
|
||||
* Every linear is a DenseFP8 GEMM over the pair its quantiser writes: `quant_act_fp8` codes
|
||||
* 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_FP8_BLOCK;
|
||||
const int64_t qgr = cfg.act_i8 ? cfg.act_g8 : (int64_t)RAD_SCALE_GROUP;
|
||||
{
|
||||
auto fits = [&](const DenseFP8& d) {
|
||||
auto fits = [&](const DenseQ& d) {
|
||||
return d.w8h == cfg.act_i8 && (!d.w8h || d.g8 == cfg.act_g8);
|
||||
};
|
||||
bool same = fits(w_fc);
|
||||
@@ -498,15 +498,10 @@ 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), or its rotating int8 twin `rmsnorm_had_quant_i8g` for a rotated int8
|
||||
/* 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
|
||||
@@ -567,7 +562,7 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
if (!op_fnorm[i]) return RAD_E_INVAL;
|
||||
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].m2x && !w_gu[i].w8h)
|
||||
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});
|
||||
@@ -607,13 +602,7 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
/* 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;
|
||||
|
||||
@@ -632,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. */
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
*
|
||||
* ============================== WHY A SECOND DSPARK BLOCK ==============================
|
||||
*
|
||||
* rad_block_dspark.h is the same drafter shape for a block-fp8 release: its linears are DenseFP8
|
||||
* 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
|
||||
@@ -106,17 +106,7 @@
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
/* The builder refuses a declaration it cannot serve and says why in its own words; this names which
|
||||
* handle did not come back, so that message reads against a line of this file. An op that resolves
|
||||
* to no kernel is recorded and handed back null -- it is only an error if the block issues it -- so
|
||||
* without this a missing kernel surfaces as a bare "invalid argument" at startup. */
|
||||
#define DS_REFUSED(...) ::rad::arch::drafter_refused({ __VA_ARGS__ })
|
||||
inline int drafter_refused(std::initializer_list<const char*> what) {
|
||||
std::string list;
|
||||
for (const char* w : what) { if (!list.empty()) list += ", "; list += w; }
|
||||
std::fprintf(stderr, "DSpark drafter: the builder gave no handle for %s\n", list.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
#define DS_REFUSED(...) ::rad::arch::declare_refused("DSpark drafter", { __VA_ARGS__ })
|
||||
|
||||
struct DsparkBF16 {
|
||||
enum { MAX_LAYERS = 8 };
|
||||
@@ -196,7 +186,7 @@ struct DsparkBF16 {
|
||||
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, op_widen3 = 0;
|
||||
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;
|
||||
|
||||
@@ -449,17 +439,9 @@ inline int DsparkBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, const
|
||||
RAD_INT("vocab_offset", g.vocab_off)),
|
||||
RAD_WEIGHTS(w_tok)),
|
||||
{}, {w.h});
|
||||
op_widen = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
|
||||
RAD_STR("from", "bf16"), RAD_STR("to", "f32")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h}, {w.x});
|
||||
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 = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
|
||||
RAD_STR("from", "bf16"), RAD_STR("to", "f32")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h}, {w.delta});
|
||||
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")),
|
||||
@@ -730,11 +712,7 @@ struct DsparkTaps {
|
||||
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 = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("from", "f32"), RAD_STR("to", "f32")),
|
||||
RAD_NOWEIGHTS),
|
||||
{residual}, {src});
|
||||
op = cast_op(b, rows, g.n_embd, "f32", "f32", residual, src);
|
||||
return op ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,629 @@
|
||||
/* rad_block_ernie_dsa.h -- ERNIE-5.5 D-layer token-level DSA Indexer + sparse Absorbed MLA.
|
||||
*
|
||||
* Replicated on every rank (all 64 heads), IQ8R trunk linears (rotated int8 at group 256):
|
||||
* q_a IQ8R -> q_a_layernorm -> had_quant_act_i8g (256) -> q_b IQ8R -> GPT-J plain RoPE (8e6) on [192, 256)
|
||||
* kv_a split ([0,512) IQ8R latent, [512,576) bf16 rope) -> kv_a_norm, GPT-J RoPE -> latent KV
|
||||
* indexer: wq_b IQ8R -> NeoX RoPE [0,64) -> dsa_query (WHT + pow2 E4M3)
|
||||
* wk bf16 -> LayerNorm(bias) -> NeoX RoPE [0,64) -> dsa_query -> dsa_index_store
|
||||
* weights_proj bf16 -> gemm_nt_f32 -> chunked dsa_token_score -> dsa_token_select
|
||||
* MLA: mla_project absorb (d=192, stride=448, off=0) -> mla_attn_sparse (bf16 sink)
|
||||
* -> mla_project expand (d=256, stride=448, off=192) -> vha_postmix
|
||||
* -> * sigmoid(gate_proj(c_q)) -> had_quant_act_i8g -> o_proj IQ8R
|
||||
*/
|
||||
#ifndef RAD_BLOCK_ERNIE_DSA_H
|
||||
#define RAD_BLOCK_ERNIE_DSA_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
#include "rad_linear.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct ErnieDsa {
|
||||
static constexpr int64_t kEmbd = 4096;
|
||||
static constexpr int64_t kHeads = 64;
|
||||
static constexpr int64_t kQLora = 1024;
|
||||
static constexpr int64_t kLatent = 512;
|
||||
static constexpr int64_t kNope = 192;
|
||||
static constexpr int64_t kRope = 64;
|
||||
static constexpr int64_t kQHead = kNope + kRope; /* 256 */
|
||||
static constexpr int64_t kVHead = 256;
|
||||
static constexpr int64_t kKvBStride = kNope + kVHead; /* 448 */
|
||||
static constexpr int64_t kIdxDim = 128;
|
||||
static constexpr int64_t kTopk = 2048;
|
||||
static constexpr int64_t kWin = 128;
|
||||
static constexpr int64_t kMaxSel = kTopk + kWin; /* 2176 */
|
||||
static constexpr int64_t kKvBlock = 16;
|
||||
static constexpr int64_t kIdxBytes = 132; /* 128 E4M3 + 4B f32 scale */
|
||||
static constexpr int64_t kVhaRank = 16;
|
||||
static constexpr int64_t kScoreMaxBytes = 256LL << 20;
|
||||
static constexpr double kTheta = 8000000.0;
|
||||
|
||||
struct Wire {
|
||||
ActQ in{};
|
||||
rad_buf out = 0;
|
||||
|
||||
/* Shared scratch across the 6 DSA layers. */
|
||||
rad_buf q_a_raw = 0;
|
||||
ActQ c_q{};
|
||||
rad_buf q_b = 0, q_nope = 0, q_pe = 0, q_abs = 0;
|
||||
rad_buf kv_lat_raw = 0, kv_lat = 0, kv_rope = 0, kv_mqa = 0;
|
||||
rad_buf idx_q_raw = 0, idx_q_flat = 0, idx_qq = 0, idx_qs = 0;
|
||||
rad_buf idx_k_raw = 0, idx_k = 0, idx_kq = 0, idx_ks = 0;
|
||||
rad_buf idx_gate = 0, scores = 0, slots = 0, length = 0;
|
||||
rad_buf lat_out = 0, v_out = 0, o_mix = 0, gate = 0;
|
||||
ActQ gated{};
|
||||
};
|
||||
|
||||
struct Caches {
|
||||
rad_kvgroup latent = 0, index = 0;
|
||||
};
|
||||
|
||||
Geom g{};
|
||||
Wire w{};
|
||||
Caches caches{};
|
||||
int layer = 0;
|
||||
int64_t score_cols = 0;
|
||||
int64_t score_rows = 0;
|
||||
bool attn_zero = false;
|
||||
int64_t v_dim = kHeads * kVHead;
|
||||
int64_t v_off = 0;
|
||||
|
||||
LinearQ q_a{}, q_b{}, kv_a_lat{}, kv_a_rope{}, idx_wq_b{}, idx_wk{}, gate_proj{}, o_proj{};
|
||||
QuantAct q_quant{}, gated_quant{};
|
||||
rad_weight w_qa_norm = 0, w_kva_norm = 0, w_kv_b = 0;
|
||||
rad_weight w_knorm_w = 0, w_knorm_b = 0, w_idx_gate = 0;
|
||||
rad_weight w_sink = 0, w_u = 0, w_v = 0;
|
||||
|
||||
rad_op op_qa_norm = 0, op_q_rope = 0, op_q_nope_slice = 0, op_q_pe_slice = 0;
|
||||
rad_op op_kva_norm = 0, op_k_rope = 0, op_kv_lat_pack = 0, op_kv_rope_pack = 0, op_kv_store = 0;
|
||||
rad_op op_idx_q_rope = 0, op_idx_q_pack = 0, op_idx_qq = 0;
|
||||
rad_op op_idx_knorm = 0, op_idx_k_rope = 0, op_idx_kq = 0, op_idx_store = 0;
|
||||
rad_op op_idx_gate = 0, op_score = 0, op_select = 0;
|
||||
rad_op op_absorb = 0, op_attn = 0, op_expand = 0, op_vha = 0, op_act_mul = 0;
|
||||
|
||||
static void score_bounds(const Geom& g, int64_t* cols, int64_t* rows) {
|
||||
const int64_t c = ((g.max_ctx + kKvBlock - 1) / kKvBlock) * kKvBlock;
|
||||
const int64_t per_row = c * (int64_t)sizeof(float);
|
||||
const int64_t max_r = std::max<int64_t>(1, kScoreMaxBytes / std::max<int64_t>(1, per_row));
|
||||
*cols = c;
|
||||
*rows = std::min<int64_t>(g.max_tok, max_r);
|
||||
}
|
||||
|
||||
static rad_op decl_plain_rope(RadBuilder* b, int64_t max_tok, int64_t head_dim,
|
||||
int64_t n_head, const char* mode, int64_t rotary_dim,
|
||||
int64_t rotary_offset) {
|
||||
const RadParam ps[] = {
|
||||
RAD_RANGE("M", 1, max_tok), RAD_INT("head_dim", head_dim),
|
||||
RAD_INT("n_head", n_head), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", kTheta), RAD_F64("scale", 1.0),
|
||||
RAD_STR("mode", mode), RAD_INT("rotary_dim", rotary_dim),
|
||||
RAD_INT("rotary_offset", rotary_offset),
|
||||
};
|
||||
return rad_decl_op(b, "rope", ps, rotary_offset ? 9 : 8, RAD_NOWEIGHTS);
|
||||
}
|
||||
|
||||
static int declare_wire(RadBuilder* b, Names& nm, const Geom& g, Wire* w) {
|
||||
if (!b || !w || !w->in.x || !w->out || g.n_embd != kEmbd || g.max_tok < 1 ||
|
||||
g.max_ctx < 1 || g.max_seqs < 1)
|
||||
return RAD_E_INVAL;
|
||||
const int64_t T = g.max_tok;
|
||||
int64_t sc_cols = 0, sc_rows = 0;
|
||||
score_bounds(g, &sc_cols, &sc_rows);
|
||||
|
||||
w->q_a_raw = decl_b(b, nm.f("dsa.q_a_raw"), RAD_BF16, { T, kQLora });
|
||||
w->c_q.x = decl_b(b, nm.f("dsa.c_q"), RAD_BF16, { T, kQLora });
|
||||
RAD_ARCH_TRY(w->c_q.declare_trunk(b, nm, g, "dsa.c_q", kQLora));
|
||||
w->q_b = decl_b(b, nm.f("dsa.q_b"), RAD_BF16, { T, kHeads, kQHead });
|
||||
w->q_nope = decl_b(b, nm.f("dsa.q_nope"), RAD_BF16, { T, kHeads, kNope });
|
||||
w->q_pe = decl_b(b, nm.f("dsa.q_pe"), RAD_BF16, { T, kHeads, kRope });
|
||||
w->q_abs = decl_b(b, nm.f("dsa.q_abs"), RAD_BF16, { T, kHeads * kLatent });
|
||||
|
||||
w->kv_lat_raw = decl_b(b, nm.f("dsa.kv_lat_raw"), RAD_BF16, { T, kLatent });
|
||||
w->kv_lat = decl_b(b, nm.f("dsa.kv_lat"), RAD_BF16, { T, kLatent });
|
||||
w->kv_rope = decl_b(b, nm.f("dsa.kv_rope"), RAD_BF16, { T, kRope });
|
||||
w->kv_mqa = decl_b(b, nm.f("dsa.kv_mqa"), RAD_BF16, { T, kLatent + kRope });
|
||||
|
||||
w->idx_q_raw = decl_b(b, nm.f("dsa.idx_q_raw"), RAD_BF16, { T, kHeads * kIdxDim });
|
||||
w->idx_q_flat = decl_b(b, nm.f("dsa.idx_q_flat"), RAD_BF16, { T * kHeads, kIdxDim });
|
||||
w->idx_qq = decl_b(b, nm.f("dsa.idx_qq"), RAD_F8E4M3, { T * kHeads, kIdxDim });
|
||||
w->idx_qs = decl_b(b, nm.f("dsa.idx_qs"), RAD_F32, { T * kHeads, 1 });
|
||||
w->idx_k_raw = decl_b(b, nm.f("dsa.idx_k_raw"), RAD_BF16, { T, kIdxDim });
|
||||
w->idx_k = decl_b(b, nm.f("dsa.idx_k"), RAD_BF16, { T, kIdxDim });
|
||||
w->idx_kq = decl_b(b, nm.f("dsa.idx_kq"), RAD_F8E4M3, { T, kIdxDim });
|
||||
w->idx_ks = decl_b(b, nm.f("dsa.idx_ks"), RAD_F32, { T, 1 });
|
||||
w->idx_gate = decl_b(b, nm.f("dsa.idx_gate"), RAD_F32, { T, kHeads });
|
||||
w->scores = decl_b(b, nm.f("dsa.scores"), RAD_F32, { sc_rows, sc_cols });
|
||||
w->slots = decl_b(b, nm.f("dsa.slots"), RAD_I32, { T, kMaxSel });
|
||||
w->length = decl_b(b, nm.f("dsa.length"), RAD_I32, { T });
|
||||
|
||||
const int aw = g.attn_world > 0 && g.attn_world < g.world ? g.attn_world : g.world;
|
||||
const bool out_sharded = !g.attn_zero && aw > 1 && aw < g.world;
|
||||
const int64_t w_vdim = out_sharded ? (kHeads * kVHead) / aw : (kHeads * kVHead);
|
||||
|
||||
w->lat_out = decl_b(b, nm.f("dsa.lat_out"), RAD_BF16, { T, kHeads * kLatent });
|
||||
w->v_out = decl_b(b, nm.f("dsa.v_out"), RAD_BF16, { T, kHeads * kVHead });
|
||||
w->o_mix = decl_b(b, nm.f("dsa.o_mix"), RAD_BF16, { T, kHeads * kVHead });
|
||||
w->gate = decl_b(b, nm.f("dsa.gate"), RAD_BF16, { T, w_vdim });
|
||||
w->gated.x = decl_b(b, nm.f("dsa.gated"), RAD_BF16, { T, w_vdim });
|
||||
RAD_ARCH_TRY(w->gated.declare_trunk(b, nm, g, "dsa.gated", w_vdim));
|
||||
|
||||
if (!w->q_a_raw || !w->c_q.x || !w->q_b || !w->q_nope || !w->q_pe || !w->q_abs ||
|
||||
!w->kv_lat_raw || !w->kv_lat || !w->kv_rope || !w->kv_mqa ||
|
||||
!w->idx_q_raw || !w->idx_q_flat || !w->idx_qq || !w->idx_qs ||
|
||||
!w->idx_k_raw || !w->idx_k || !w->idx_kq || !w->idx_ks || !w->idx_gate ||
|
||||
!w->scores || !w->slots || !w->length ||
|
||||
!w->lat_out || !w->v_out || !w->o_mix || !w->gate || !w->gated.x)
|
||||
return RAD_E_INVAL;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
|
||||
const char* ckpt_attn, Caches* out_caches) {
|
||||
g = geom;
|
||||
w = wire;
|
||||
layer = l;
|
||||
if (!b || !ckpt_attn || !out_caches || g.n_embd != kEmbd || g.n_head != kHeads ||
|
||||
g.max_tok < 1 || g.max_ctx < 1 || g.max_seqs < 1)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
score_bounds(g, &score_cols, &score_rows);
|
||||
const auto wg = grp_layer(l);
|
||||
const int64_t T = g.max_tok;
|
||||
const int aw = g.attn_world > 0 && g.attn_world < g.world ? g.attn_world : g.world;
|
||||
const bool rep_kv = aw == g.world;
|
||||
attn_zero = g.attn_zero;
|
||||
if (attn_zero) {
|
||||
if (!out_caches->latent) {
|
||||
RadKVGroupDecl d{};
|
||||
d.kind = RAD_KV_FULL;
|
||||
d.dtype = RAD_BF16;
|
||||
d.n_head_kv = 1;
|
||||
d.head_dim = (kLatent + kRope) / 2;
|
||||
out_caches->latent = rad_decl_kv_group(b, nm.f("kv_dsa_latent"), &d);
|
||||
if (!out_caches->latent) return RAD_E_INVAL;
|
||||
if (!rw(b, RAD_OP(b, "kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T),
|
||||
RAD_INT("head_dim", (kLatent + kRope) / 2),
|
||||
RAD_INT("n_head_kv", 1), RAD_INT("block_size", kKvBlock),
|
||||
RAD_STR("kv_dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, {}))
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, out_caches->latent));
|
||||
if (!out_caches->index) {
|
||||
RadKVGroupDecl d{};
|
||||
d.kind = RAD_KV_FULL;
|
||||
d.dtype = RAD_U8;
|
||||
d.n_head_kv = 1;
|
||||
d.head_dim = kIdxBytes / 2;
|
||||
out_caches->index = rad_decl_kv_group(b, nm.f("kv_dsa_index"), &d);
|
||||
if (!out_caches->index) return RAD_E_INVAL;
|
||||
RAD_ARCH_TRY(rad_kv_group_dense_read(b, out_caches->index));
|
||||
if (!rw(b, RAD_OP(b, "dsa_index_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", kIdxDim),
|
||||
RAD_INT("block_size", kKvBlock)),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, {}))
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, out_caches->index));
|
||||
caches = *out_caches;
|
||||
return RAD_OK;
|
||||
}
|
||||
if (!w.in.x || !w.out || !w.q_a_raw || !w.c_q.x || !w.q_b || !w.q_nope || !w.q_pe ||
|
||||
!w.q_abs || !w.kv_lat_raw || !w.kv_lat || !w.kv_rope || !w.kv_mqa || !w.idx_q_raw ||
|
||||
!w.idx_q_flat || !w.idx_qq || !w.idx_qs || !w.idx_k_raw || !w.idx_k || !w.idx_kq ||
|
||||
!w.idx_ks || !w.idx_gate || !w.scores || !w.slots || !w.length || !w.lat_out ||
|
||||
!w.v_out || !w.o_mix || !w.gate || !w.gated.x || w.v_out == w.o_mix)
|
||||
return RAD_E_INVAL;
|
||||
const bool out_sharded = aw > 1 && aw < g.world;
|
||||
if (out_sharded && ((kHeads * kVHead) % aw != 0)) return RAD_E_UNSUPPORTED;
|
||||
v_dim = out_sharded ? (kHeads * kVHead) / aw : (kHeads * kVHead);
|
||||
v_off = out_sharded ? (int64_t)g.attn_rank * v_dim : 0;
|
||||
|
||||
/* 1. Query path: q_a -> q_a_layernorm -> quant -> q_b -> GPT-J plain RoPE [192,256). */
|
||||
RAD_ARCH_TRY(q_a.declare(b, nm, g, nm.f("blk.%d.attn_q_a", l), kQLora, kEmbd,
|
||||
RAD_SHARD_NONE, wg, { nm.ckpt("%s.q_a_proj.weight", ckpt_attn) },
|
||||
w.in, w.q_a_raw));
|
||||
const char* qa_nm = nm.f("blk.%d.attn_q_norm.weight", l);
|
||||
RAD_ARCH_TRY(map_copy(b, qa_nm, nm.ckpt("%s.q_a_layernorm.weight", ckpt_attn)));
|
||||
w_qa_norm = decl_w(b, qa_nm, RAD_F32, { kQLora }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, wg);
|
||||
if (!w_qa_norm) return RAD_E_INVAL;
|
||||
op_qa_norm = rw(b,
|
||||
RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", kQLora),
|
||||
RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_qa_norm)),
|
||||
{ w.q_a_raw }, { w.c_q.x });
|
||||
RAD_ARCH_TRY(q_quant.declare(b, g, w.c_q, kQLora));
|
||||
RAD_ARCH_TRY(q_b.declare(b, nm, g, nm.f("blk.%d.attn_q_b", l), kHeads * kQHead, kQLora,
|
||||
RAD_SHARD_NONE, wg, { nm.ckpt("%s.q_b_proj.weight", ckpt_attn) },
|
||||
w.c_q, w.q_b));
|
||||
op_q_rope = rw(b, decl_plain_rope(b, T, kQHead, kHeads, "gptj", kRope, kNope),
|
||||
{ w.q_b }, { w.q_b });
|
||||
op_q_nope_slice = rw(b,
|
||||
RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", kNope),
|
||||
RAD_STR("from", "bf16"), RAD_STR("to", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.q_b }, { w.q_nope });
|
||||
op_q_pe_slice = rw(b,
|
||||
RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", kRope),
|
||||
RAD_STR("from", "bf16"), RAD_STR("to", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.q_b }, { w.q_pe });
|
||||
if (!op_qa_norm || !op_q_rope || !op_q_nope_slice || !op_q_pe_slice) return RAD_E_INVAL;
|
||||
|
||||
/* 2. KV-a split ([0,512) IQ8R latent, [512,576) BF16 rope piece). */
|
||||
const char* kva_src = nm.ckpt("%s.kv_a_proj_with_mqa.weight", ckpt_attn);
|
||||
const char* kva_lat_wn = nm.f("blk.%d.attn_kv_a_lat.weight", l);
|
||||
const char* kva_rope_wn = nm.f("blk.%d.attn_kv_a_rope.weight", l);
|
||||
RAD_ARCH_TRY(map_rows(b, kva_lat_wn, { { kva_src, 0, kLatent } }));
|
||||
RAD_ARCH_TRY(map_rows(b, kva_rope_wn, { { kva_src, kLatent, kRope } }));
|
||||
kv_a_lat.mapped = true;
|
||||
RAD_ARCH_TRY(kv_a_lat.declare(b, nm, g, nm.f("blk.%d.attn_kv_a_lat", l), kLatent, kEmbd,
|
||||
RAD_SHARD_NONE, wg, { kva_src }, w.in, w.kv_lat_raw));
|
||||
Geom bg = g;
|
||||
bg.w_bf16 = true;
|
||||
kv_a_rope.mapped = true;
|
||||
RAD_ARCH_TRY(kv_a_rope.declare(b, nm, bg, nm.f("blk.%d.attn_kv_a_rope", l), kRope, kEmbd,
|
||||
RAD_SHARD_NONE, wg, { kva_src }, w.in, w.kv_rope));
|
||||
|
||||
const char* kva_norm_nm = nm.f("blk.%d.attn_kv_a_norm.weight", l);
|
||||
RAD_ARCH_TRY(map_copy(b, kva_norm_nm, nm.ckpt("%s.kv_a_layernorm.weight", ckpt_attn)));
|
||||
w_kva_norm = decl_w(b, kva_norm_nm, RAD_F32, { kLatent }, RAD_ACCESS_PER_TOKEN,
|
||||
RAD_SHARD_NONE, wg);
|
||||
if (!w_kva_norm) return RAD_E_INVAL;
|
||||
op_kva_norm = rw(b,
|
||||
RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", kLatent),
|
||||
RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_kva_norm)),
|
||||
{ w.kv_lat_raw }, { w.kv_lat });
|
||||
op_k_rope = rw(b, decl_plain_rope(b, T, kRope, 1, "gptj", kRope, 0),
|
||||
{ w.kv_rope }, { w.kv_rope });
|
||||
op_kv_lat_pack = rw(b,
|
||||
RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", kLatent),
|
||||
RAD_STR("from", "bf16"), RAD_STR("to", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.kv_lat }, { w.kv_mqa });
|
||||
op_kv_rope_pack = rw(b,
|
||||
RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", kRope),
|
||||
RAD_STR("from", "bf16"), RAD_STR("to", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.kv_rope }, { w.kv_mqa });
|
||||
if (!op_kva_norm || !op_k_rope || !op_kv_lat_pack || !op_kv_rope_pack)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
if (!out_caches->latent) {
|
||||
RadKVGroupDecl d{};
|
||||
d.kind = RAD_KV_FULL;
|
||||
d.dtype = RAD_BF16;
|
||||
d.n_head_kv = 1;
|
||||
d.head_dim = (kLatent + kRope) / 2; /* row 576 = 2 * 288 */
|
||||
out_caches->latent = rad_decl_kv_group(b, nm.f("kv_dsa_latent"), &d);
|
||||
if (!out_caches->latent) return RAD_E_INVAL;
|
||||
if (rep_kv) RAD_ARCH_TRY(rad_kv_group_replicated(b, out_caches->latent));
|
||||
}
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, out_caches->latent));
|
||||
op_kv_store = rw(b,
|
||||
RAD_OP(b, "kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T),
|
||||
RAD_INT("head_dim", (kLatent + kRope) / 2),
|
||||
RAD_INT("n_head_kv", 1),
|
||||
RAD_INT("block_size", kKvBlock),
|
||||
RAD_STR("kv_dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.kv_mqa }, {});
|
||||
if (!op_kv_store || rad_kv_block_size(b, out_caches->latent) != kKvBlock)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
/* 3. Indexer: wq_b -> NeoX RoPE -> dsa_query; wk -> LN -> NeoX RoPE -> dsa_query -> store. */
|
||||
RAD_ARCH_TRY(idx_wq_b.declare(
|
||||
b, nm, g, nm.f("blk.%d.attn_idx_wq_b", l), kHeads * kIdxDim, kQLora, RAD_SHARD_NONE,
|
||||
wg, { nm.ckpt("%s.core_attention.indexer.wq_b.weight", ckpt_attn) },
|
||||
w.c_q, w.idx_q_raw));
|
||||
op_idx_q_rope = rw(b, decl_plain_rope(b, T, kIdxDim, kHeads, "neox", kRope, 0),
|
||||
{ w.idx_q_raw }, { w.idx_q_raw });
|
||||
op_idx_q_pack = rw(b,
|
||||
RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T * kHeads), RAD_INT("n", kIdxDim),
|
||||
RAD_STR("from", "bf16"), RAD_STR("to", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.idx_q_raw }, { w.idx_q_flat });
|
||||
op_idx_qq = rw(b,
|
||||
RAD_OP(b, "dsa_query",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T * kHeads), RAD_INT("n", kIdxDim),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.idx_q_flat }, { w.idx_qq, w.idx_qs });
|
||||
|
||||
RAD_ARCH_TRY(idx_wk.declare(
|
||||
b, nm, bg, nm.f("blk.%d.attn_idx_wk", l), kIdxDim, kEmbd, RAD_SHARD_NONE, wg,
|
||||
{ nm.ckpt("%s.core_attention.indexer.wk.weight", ckpt_attn) }, w.in, w.idx_k_raw));
|
||||
const char* knw_nm = nm.f("blk.%d.attn_idx_knorm.weight", l);
|
||||
const char* knb_nm = nm.f("blk.%d.attn_idx_knorm.bias", l);
|
||||
RAD_ARCH_TRY(map_copy(b, knw_nm, nm.ckpt("%s.core_attention.indexer.k_norm.weight", ckpt_attn)));
|
||||
RAD_ARCH_TRY(map_copy(b, knb_nm, nm.ckpt("%s.core_attention.indexer.k_norm.bias", ckpt_attn)));
|
||||
w_knorm_w = decl_w(b, knw_nm, RAD_F32, { kIdxDim }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, wg);
|
||||
w_knorm_b = decl_w(b, knb_nm, RAD_F32, { kIdxDim }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, wg);
|
||||
if (!w_knorm_w || !w_knorm_b) return RAD_E_INVAL;
|
||||
op_idx_knorm = rw(b,
|
||||
RAD_OP(b, "layernorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", kIdxDim),
|
||||
RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_knorm_w, w_knorm_b)),
|
||||
{ w.idx_k_raw }, { w.idx_k });
|
||||
op_idx_k_rope = rw(b, decl_plain_rope(b, T, kIdxDim, 1, "neox", kRope, 0),
|
||||
{ w.idx_k }, { w.idx_k });
|
||||
op_idx_kq = rw(b,
|
||||
RAD_OP(b, "dsa_query",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", kIdxDim),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.idx_k }, { w.idx_kq, w.idx_ks });
|
||||
|
||||
if (!out_caches->index) {
|
||||
RadKVGroupDecl d{};
|
||||
d.kind = RAD_KV_FULL;
|
||||
d.dtype = RAD_U8;
|
||||
d.n_head_kv = 1;
|
||||
d.head_dim = kIdxBytes / 2; /* 132 B row = 2 * 66 U8 */
|
||||
out_caches->index = rad_decl_kv_group(b, nm.f("kv_dsa_index"), &d);
|
||||
if (!out_caches->index) return RAD_E_INVAL;
|
||||
RAD_ARCH_TRY(rad_kv_group_dense_read(b, out_caches->index));
|
||||
if (rep_kv) RAD_ARCH_TRY(rad_kv_group_replicated(b, out_caches->index));
|
||||
}
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, out_caches->index));
|
||||
op_idx_store = rw(b,
|
||||
RAD_OP(b, "dsa_index_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", kIdxDim),
|
||||
RAD_INT("block_size", kKvBlock)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.idx_kq, w.idx_ks }, {});
|
||||
if (!op_idx_store || rad_kv_block_size(b, out_caches->index) != kKvBlock)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
const char* gate_nm = nm.f("blk.%d.attn_idx_weights.weight", l);
|
||||
RAD_ARCH_TRY(map_copy(
|
||||
b, gate_nm, nm.ckpt("%s.core_attention.indexer.weights_proj.weight", ckpt_attn)));
|
||||
w_idx_gate = decl_w(b, gate_nm, RAD_BF16, { kHeads, kEmbd }, RAD_ACCESS_PER_TOKEN,
|
||||
RAD_SHARD_NONE, wg);
|
||||
if (!w_idx_gate) return RAD_E_INVAL;
|
||||
op_idx_gate = rw(b,
|
||||
RAD_OP(b, "gemm_nt_f32",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("N", kHeads),
|
||||
RAD_INT("K", kEmbd), RAD_STR("dtype", "bf16"),
|
||||
RAD_STR("w_dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_idx_gate)),
|
||||
{ w.in.x }, { w.idx_gate });
|
||||
op_score = rw(b,
|
||||
RAD_OP(b, "dsa_token_score",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, score_rows), RAD_INT("n", kIdxDim),
|
||||
RAD_INT("heads", kHeads), RAD_INT("window", kWin),
|
||||
RAD_INT("block_size", kKvBlock),
|
||||
RAD_INT("seqs", g.max_seqs), RAD_STR("dtype", "fp8_e4m3")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.idx_qq, w.idx_qs, w.idx_gate }, { w.scores });
|
||||
op_select = rw(b,
|
||||
RAD_OP(b, "dsa_token_select",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, score_rows), RAD_INT("topk", kTopk),
|
||||
RAD_INT("window", kWin), RAD_INT("block_size", kKvBlock),
|
||||
RAD_INT("seqs", g.max_seqs)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.scores }, { w.slots, w.length });
|
||||
if (!op_idx_q_rope || !op_idx_q_pack || !op_idx_qq || !op_idx_knorm || !op_idx_k_rope ||
|
||||
!op_idx_kq || !op_idx_gate || !op_score || !op_select)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
/* 4. Absorbed MLA + mla_attn_sparse (bf16 softmax_offset sink) + expand + vha_postmix. */
|
||||
const char* kvb_nm = nm.f("blk.%d.attn_kv_b.weight", l);
|
||||
RAD_ARCH_TRY(map_copy(b, kvb_nm, nm.ckpt("%s.kv_b_proj.weight", ckpt_attn)));
|
||||
w_kv_b = decl_w(b, kvb_nm, RAD_BF16, { kHeads * kKvBStride, kLatent },
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, wg);
|
||||
const char* sink_nm = nm.f("blk.%d.attn_sink.weight", l);
|
||||
RAD_ARCH_TRY(map_copy(b, sink_nm, nm.ckpt("%s.core_attention.softmax_offset", ckpt_attn)));
|
||||
w_sink = decl_w(b, sink_nm, RAD_BF16, { kHeads }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, wg);
|
||||
const char* u_nm = nm.f("blk.%d.attn_vha_u.weight", l);
|
||||
const char* v_nm = nm.f("blk.%d.attn_vha_v.weight", l);
|
||||
RAD_ARCH_TRY(map_copy(b, u_nm, nm.ckpt("%s.vha_postmix_U", ckpt_attn)));
|
||||
RAD_ARCH_TRY(map_copy(b, v_nm, nm.ckpt("%s.vha_postmix_V", ckpt_attn)));
|
||||
w_u = decl_w(b, u_nm, RAD_BF16, { kHeads, kVhaRank }, RAD_ACCESS_PER_TOKEN,
|
||||
RAD_SHARD_NONE, wg);
|
||||
w_v = decl_w(b, v_nm, RAD_BF16, { kHeads, kVhaRank }, RAD_ACCESS_PER_TOKEN,
|
||||
RAD_SHARD_NONE, wg);
|
||||
if (!w_kv_b || !w_sink || !w_u || !w_v) return RAD_E_INVAL;
|
||||
|
||||
op_absorb = rw(b,
|
||||
RAD_OP(b, "mla_project",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("heads", kHeads),
|
||||
RAD_INT("head_dim", kNope), RAD_INT("latent_dim", kLatent),
|
||||
RAD_STR("mode", "absorb"), RAD_STR("dtype", "bf16"),
|
||||
RAD_INT("w_stride", kKvBStride), RAD_INT("w_offset", 0)),
|
||||
RAD_WEIGHTS(w_kv_b)),
|
||||
{ w.q_nope }, { w.q_abs });
|
||||
/* Keep score inputs live across the chunked score/select loop (T > score_rows). */
|
||||
if (op_absorb)
|
||||
RAD_ARCH_TRY(rad_op_reads(b, op_absorb, RAD_BUFS(w.idx_qq, w.idx_qs, w.idx_gate)));
|
||||
op_attn = rw(b,
|
||||
RAD_OP(b, "mla_attn_sparse",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("heads", kHeads),
|
||||
RAD_INT("latent_dim", kLatent), RAD_INT("rope_dim", kRope),
|
||||
RAD_INT("block_size", kKvBlock),
|
||||
RAD_F64("scale", 1.0 / 16.0), RAD_STR("dtype", "bf16"),
|
||||
RAD_STR("kv_dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_sink)),
|
||||
{ w.q_abs, w.q_pe, w.slots, w.length }, { w.lat_out });
|
||||
op_expand = rw(b,
|
||||
RAD_OP(b, "mla_project",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("heads", kHeads),
|
||||
RAD_INT("head_dim", kVHead), RAD_INT("latent_dim", kLatent),
|
||||
RAD_STR("mode", "expand"), RAD_STR("dtype", "bf16"),
|
||||
RAD_INT("w_stride", kKvBStride),
|
||||
RAD_INT("w_offset", kNope)),
|
||||
RAD_WEIGHTS(w_kv_b)),
|
||||
{ w.lat_out }, { w.v_out });
|
||||
op_vha = rw(b,
|
||||
RAD_OP(b, "vha_postmix",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("heads", kHeads),
|
||||
RAD_INT("head_dim", kVHead), RAD_INT("rank", kVhaRank),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_u, w_v)),
|
||||
{ w.v_out }, { w.o_mix });
|
||||
|
||||
/* 5. Output gate + act_mul sigmoid + had_quant_act_i8g + o_proj (half heads/rank when attn_world < world). */
|
||||
const int out_shard_row = out_sharded ? RAD_SHARD_ROW : RAD_SHARD_NONE;
|
||||
const int out_shard_col = out_sharded ? RAD_SHARD_COL : RAD_SHARD_NONE;
|
||||
const int64_t v_hi = out_sharded ? v_off + v_dim : 0;
|
||||
RAD_ARCH_TRY(gate_proj.declare(b, nm, g, nm.f("blk.%d.attn_gate", l), v_dim,
|
||||
kQLora, out_shard_row, wg,
|
||||
{ nm.ckpt("%s.gate_proj.weight", ckpt_attn) },
|
||||
w.c_q, w.gate, 0, {}, v_off, v_hi));
|
||||
op_act_mul = rw(b,
|
||||
RAD_OP(b, "act_mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", v_dim),
|
||||
RAD_STR("act", "sigmoid"), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.gate, w.o_mix }, { w.gated.x });
|
||||
RAD_ARCH_TRY(gated_quant.declare(b, g, w.gated, v_dim));
|
||||
RAD_ARCH_TRY(o_proj.declare(b, nm, g, nm.f("blk.%d.attn_output", l), kEmbd,
|
||||
v_dim, out_shard_col, wg,
|
||||
{ nm.ckpt("%s.o_proj.weight", ckpt_attn) }, w.gated, w.out,
|
||||
0, {}, v_off, v_hi));
|
||||
if (!op_absorb || !op_attn || !op_expand || !op_vha || !op_act_mul) return RAD_E_INVAL;
|
||||
|
||||
caches = *out_caches;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void step(RadCtx* ctx, const RadBatch* batch) const {
|
||||
if (attn_zero || !ctx || !batch || batch->n_tok < 1) return;
|
||||
const int64_t T = batch->n_tok;
|
||||
const int64_t S = batch->n_seq;
|
||||
const auto* lb = kv_batch(batch, caches.latent);
|
||||
const auto* ib = kv_batch(batch, caches.index);
|
||||
if (!lb || !ib || !lb->slot_mapping || !ib->slot_mapping || !lb->block_table ||
|
||||
!ib->block_table || ib->block_table_pitch < 1 || lb->block_table_pitch < 1 ||
|
||||
!batch->positions || !batch->cu_seqlens) {
|
||||
rad_step_fail(ctx, "ernie_dsa: missing latent/index KV batch or sequence bounds");
|
||||
return;
|
||||
}
|
||||
if (T > score_rows && S != 1) {
|
||||
rad_step_fail(ctx, "ernie_dsa: multi-sequence step exceeds score plane rows");
|
||||
return;
|
||||
}
|
||||
|
||||
/* 1. Query path + split q_b -> (q_nope, q_pe). */
|
||||
q_a.step(ctx, w.in, w.q_a_raw, T);
|
||||
RAD_ISSUE_N(ctx, op_qa_norm, T, brows(w.q_a_raw, T), RAD_W(w_qa_norm), brows(w.c_q.x, T));
|
||||
q_quant.step(ctx, T);
|
||||
q_b.step(ctx, w.c_q, w.q_b, T);
|
||||
RAD_ISSUE_N(ctx, op_q_rope, T, brows(w.q_b, T), rope_pos1(batch, T));
|
||||
/* q_b is [T, heads, 256]: one strided copy per piece covers every head. */
|
||||
RAD_ISSUE_N(ctx, op_q_nope_slice, T, bcol(w.q_b, 0, kNope, T), brows(w.q_nope, T));
|
||||
RAD_ISSUE_N(ctx, op_q_pe_slice, T, bcol(w.q_b, kNope, kRope, T), brows(w.q_pe, T));
|
||||
|
||||
/* 2. KV-a split + norm + RoPE + store into latent KV. */
|
||||
kv_a_lat.step(ctx, w.in, w.kv_lat_raw, T);
|
||||
kv_a_rope.step(ctx, w.in, w.kv_rope, T);
|
||||
RAD_ISSUE_N(ctx, op_kva_norm, T, brows(w.kv_lat_raw, T), RAD_W(w_kva_norm),
|
||||
brows(w.kv_lat, T));
|
||||
RAD_ISSUE_N(ctx, op_k_rope, T, brows(w.kv_rope, T), rope_pos1(batch, T));
|
||||
RAD_ISSUE_N(ctx, op_kv_lat_pack, T, brows(w.kv_lat, T), bcol(w.kv_mqa, 0, kLatent, T));
|
||||
RAD_ISSUE_N(ctx, op_kv_rope_pack, T, brows(w.kv_rope, T),
|
||||
bcol(w.kv_mqa, kLatent, kRope, T));
|
||||
RAD_ISSUE_N(ctx, op_kv_store, T,
|
||||
bcol(w.kv_mqa, 0, (kLatent + kRope) / 2, T),
|
||||
bcol(w.kv_mqa, (kLatent + kRope) / 2, (kLatent + kRope) / 2, T),
|
||||
praw(lb->slot_mapping, RAD_I32, T),
|
||||
kv_cache(caches.latent, layer));
|
||||
|
||||
/* 3. Indexer keys & queries (NeoX RoPE [0,64) BEFORE dsa_query), store, score, select. */
|
||||
idx_wq_b.step(ctx, w.c_q, w.idx_q_raw, T);
|
||||
RAD_ISSUE_N(ctx, op_idx_q_rope, T, brows(w.idx_q_raw, T), rope_pos1(batch, T));
|
||||
RAD_ISSUE_N(ctx, op_idx_q_pack, T * kHeads, brows(w.idx_q_raw, T),
|
||||
brows(w.idx_q_flat, T * kHeads));
|
||||
RAD_ISSUE_N(ctx, op_idx_qq, T * kHeads, brows(w.idx_q_flat, T * kHeads),
|
||||
brows(w.idx_qq, T * kHeads), brows(w.idx_qs, T * kHeads));
|
||||
|
||||
idx_wk.step(ctx, w.in, w.idx_k_raw, T);
|
||||
RAD_ISSUE_N(ctx, op_idx_knorm, T, brows(w.idx_k_raw, T), RAD_W(w_knorm_w),
|
||||
RAD_W(w_knorm_b), brows(w.idx_k, T));
|
||||
RAD_ISSUE_N(ctx, op_idx_k_rope, T, brows(w.idx_k, T), rope_pos1(batch, T));
|
||||
RAD_ISSUE_N(ctx, op_idx_kq, T, brows(w.idx_k, T), brows(w.idx_kq, T),
|
||||
brows(w.idx_ks, T));
|
||||
RAD_ISSUE_N(ctx, op_idx_store, T, brows(w.idx_kq, T), brows(w.idx_ks, T),
|
||||
praw(ib->slot_mapping, RAD_I32, T), kv_cache(caches.index, layer));
|
||||
|
||||
RAD_ISSUE_N(ctx, op_idx_gate, T, brows(w.in.x, T), RAD_W(w_idx_gate),
|
||||
brows(w.idx_gate, T));
|
||||
|
||||
const int64_t live_cols = std::min<int64_t>(score_cols, ib->block_table_pitch * kKvBlock);
|
||||
if (T <= score_rows) {
|
||||
RAD_ISSUE_N(ctx, op_score, T,
|
||||
brows(w.idx_qq, T * kHeads),
|
||||
brows(w.idx_qs, T * kHeads),
|
||||
brows(w.idx_gate, T),
|
||||
kv_cache(caches.index, layer),
|
||||
praw2(ib->block_table, RAD_I32, S, ib->block_table_pitch),
|
||||
praw(batch->positions, RAD_I32, T),
|
||||
praw(batch->cu_seqlens, RAD_I32, S + 1),
|
||||
bcol_at(w.scores, 0, score_cols, 0, live_cols, T),
|
||||
RAD_NONE);
|
||||
RAD_ISSUE_N(ctx, op_select, T,
|
||||
bcol_at(w.scores, 0, score_cols, 0, live_cols, T),
|
||||
praw2(lb->block_table, RAD_I32, S, lb->block_table_pitch),
|
||||
praw(batch->positions, RAD_I32, T),
|
||||
praw(batch->cu_seqlens, RAD_I32, S + 1),
|
||||
brows(w.slots, T),
|
||||
brows(w.length, T));
|
||||
} else {
|
||||
for (int64_t r0 = 0; r0 < T; r0 += score_rows) {
|
||||
const int64_t rn = std::min(score_rows, T - r0);
|
||||
RAD_ISSUE_N(ctx, op_score, rn,
|
||||
brow_slice(w.idx_qq, r0 * kHeads, rn * kHeads, kIdxDim),
|
||||
brow_slice(w.idx_qs, r0 * kHeads, rn * kHeads, 1),
|
||||
brow_slice(w.idx_gate, r0, rn, kHeads),
|
||||
kv_cache(caches.index, layer),
|
||||
praw2(ib->block_table, RAD_I32, 1, ib->block_table_pitch),
|
||||
praw(batch->positions + r0, RAD_I32, rn),
|
||||
praw(batch->cu_seqlens, RAD_I32, 2),
|
||||
bcol_at(w.scores, 0, score_cols, 0, live_cols, rn),
|
||||
RAD_NONE);
|
||||
RAD_ISSUE_N(ctx, op_select, rn,
|
||||
bcol_at(w.scores, 0, score_cols, 0, live_cols, rn),
|
||||
praw2(lb->block_table, RAD_I32, 1, lb->block_table_pitch),
|
||||
praw(batch->positions + r0, RAD_I32, rn),
|
||||
praw(batch->cu_seqlens, RAD_I32, 2),
|
||||
brow_slice(w.slots, r0, rn, kMaxSel),
|
||||
brow_slice(w.length, r0, rn, 1));
|
||||
}
|
||||
}
|
||||
|
||||
/* 4. Absorbed MLA + sparse attention + expand + VHA + gate + o_proj. */
|
||||
RAD_ISSUE_N(ctx, op_absorb, T, brows(w.q_nope, T), RAD_W(w_kv_b), brows(w.q_abs, T));
|
||||
RAD_ISSUE_N(ctx, op_attn, T,
|
||||
brows(w.q_abs, T), brows(w.q_pe, T), kv_cache(caches.latent, layer),
|
||||
brows(w.slots, T), brows(w.length, T), RAD_W(w_sink), brows(w.lat_out, T));
|
||||
RAD_ISSUE_N(ctx, op_expand, T, brows(w.lat_out, T), RAD_W(w_kv_b), brows(w.v_out, T));
|
||||
RAD_ISSUE_N(ctx, op_vha, T, brows(w.v_out, T), RAD_W(w_u), RAD_W(w_v), brows(w.o_mix, T));
|
||||
gate_proj.step(ctx, w.c_q, w.gate, T);
|
||||
RAD_ISSUE_N(ctx, op_act_mul, T, brows(w.gate, T),
|
||||
bcol(w.o_mix, v_off, v_dim, T), brows(w.gated.x, T));
|
||||
gated_quant.step(ctx, T);
|
||||
o_proj.step(ctx, w.gated, w.out, T);
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace arch
|
||||
} // namespace rad
|
||||
#endif
|
||||
@@ -0,0 +1,620 @@
|
||||
/* rad_block_ernie_dspark.h -- the DSpark drafter ERNIE-5.5-Flash bundles under `model.mtp.*`
|
||||
* (SPEC §8): three full ERNIE H+MoE decoder layers that denoise a block of seven rows in one pass
|
||||
* over K and V derived from three trunk taps, then the target's head and a rank-256 Markov walk.
|
||||
*
|
||||
* ============================== WHY ITS OWN BLOCK ==============================
|
||||
*
|
||||
* rad_block_dspark.h (MiniCPM / Qwen) and rad_block_dspark_inkling.h share the drive with this one
|
||||
* (RAD_DRAFT_BLOCK: a context pass per trunk step, a query pass per proposal) and nothing else:
|
||||
* ERNIE's stages are the trunk's own layers (four mHC streams, HCA attention without its
|
||||
* compressor, the latent MoE with 512 MXFP4 experts), so this block is built from ErnieHca,
|
||||
* ErnieMoe and ManifoldConn over the trunk's own wires, and its walk adds the target's multimax.
|
||||
*
|
||||
* ============================== THE FORWARD PASS ==============================
|
||||
*
|
||||
* vLLM-ERNIE `nvidia/dspark.py` and SGLang `ernie55_dspark.py` (the lead's contract, P2-DSPARK.md,
|
||||
* settles the points they disagree on):
|
||||
*
|
||||
* taps, written by the trunk step: the mean of the four streams after layers 40, 41 and 42
|
||||
* (mhc_contract of the stream row after the layer's ffn write), [T, 3 * 4096] PERSIST
|
||||
* context, one row per trunk row:
|
||||
* main_x = feature_norm(feature_projection(taps)) IQ8R [4096, 12288]
|
||||
* per stage i: k = rope(kv_layernorm_i(linear_kv_proj_i(main_x))) into stage i's window
|
||||
* query, [anchor, 1024 x 6] at positions p .. p + 6 (sample_from_anchor: every row predicts):
|
||||
* x = embed_tokens(ids) as four identical streams
|
||||
* per stage: the trunk's H+MoE layer, its attention hca_attn's anchor form (every row sees
|
||||
* the window behind the anchor and the whole block, non-causal)
|
||||
* h = norm(mhc_head(streams)) model.mtp.mhc_contract, mtp.norm
|
||||
* logits = lm_head(h) f32, the target's, vocab-sharded
|
||||
* walk, per step i = 0..6 over every sequence:
|
||||
* l = logits[i] + markov_w2 . markov_w1[prev] prev = the anchor, then step i-1's
|
||||
* l = multimax(l) the target's r, t (not monotonic)
|
||||
* proposal[i] = prev = argmax l ties to the lower id, gathered
|
||||
*
|
||||
* Every stage's K for a block row is the trunk HCA path (kv proj -> kv_layernorm -> rope), stored
|
||||
* past the context's end, where the next context pass overwrites it (rad_block_dspark.h).
|
||||
*
|
||||
* ============================== THE DRAFT ROPE ==============================
|
||||
*
|
||||
* Plain RoPE at rope_theta 8e6, GPT-J pairs over [448, 512) as the trunk's: vLLM-ERNIE's form
|
||||
* ("trained with plain RoPE at rope_theta, like SWA layers"). SGLang rotates the stages with the
|
||||
* HCA layers' YaRN rope instead (theta 160000, factor 16: "trained on the compressed YaRN rope").
|
||||
* Measured on two R9700 (TP2, the 8 golden prompts, 128 greedy tokens each, ~196 blocks a form):
|
||||
* both are lossless and accept alike, 3.79 tokens a verify step plain against 3.78 YaRN; over a
|
||||
* 128-token window the two agree in the high-frequency pairs that carry the short distances.
|
||||
* Plain did better at the two deepest positions (0.69 / 0.81 against 0.61 / 0.52, on 52 and 36
|
||||
* blocks), the only difference the run showed.
|
||||
*
|
||||
* ============================== THE WALK, COMPOSED ==============================
|
||||
*
|
||||
* Seven serial steps, each from existing ops: embed_lookup (markov_w1 transposed to [V, 256]),
|
||||
* logits_gemm at K 256 for the bias over this rank's vocabulary rows of markov_w2, add, multimax,
|
||||
* cast to bf16, row_topk, and under TP all_gather + pair_argmax. Two roundings the reference does
|
||||
* not make: the bias is f32 (the GEMM's accumulator), and the argmax reads the f32 score rounded to
|
||||
* bf16, because libr4d's row_topk is bf16 only: two ids whose scores round together resolve to the
|
||||
* lower id. Either costs acceptance only; P3 fuses the walk into one op with an f32 argmax.
|
||||
*
|
||||
* The confidence head (model.mtp.confidence_head) is not declared: it gates the verify width (P3).
|
||||
*
|
||||
* ============================== PARALLELISM ==============================
|
||||
*
|
||||
* As the trunk: the stages are replicated with expert-parallel routed experts and the 2048-wide
|
||||
* latent all-reduce; the embedding, lm_head and markov_w2 are vocabulary-sharded (markov_w1 is
|
||||
* read by id and replicated). Each rank scores its slice, its top-R pairs are gathered and
|
||||
* pair_argmax picks the same global winner everywhere.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_ERNIE_DSPARK_H
|
||||
#define RAD_BLOCK_ERNIE_DSPARK_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
#include "rad_linear.h"
|
||||
#include "rad_block_glm_mhc.h"
|
||||
#include "rad_block_ernie_hca.h"
|
||||
#include "rad_block_ernie_moe.h"
|
||||
|
||||
#include <cstdio>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct ErnieDspark {
|
||||
static constexpr int kStages = 3, kTaps = 3, kStreams = 4;
|
||||
static constexpr int64_t kEmbd = 4096, kBlock = 7, kRank = 256, kWindow = 128;
|
||||
static constexpr int32_t kNoise = 1024; /* dspark_noise_token_id */
|
||||
|
||||
struct Config {
|
||||
/* The first absolute layer index of the stages (the trunk's layer count): their weight
|
||||
* groups, name prefixes and KV bindings. */
|
||||
int base_layer = 43;
|
||||
};
|
||||
|
||||
/* The trunk's buffers, wires and weights the drafter runs over. The stages are the trunk's own
|
||||
* layers, so they share the trunk's scratch; the passes run after the trunk step. */
|
||||
struct Trunk {
|
||||
rad_buf h0 = 0, h1 = 0, x = 0, y = 0, post = 0, comb = 0;
|
||||
ActQ act{}; /* the normalised layer input, rotated int8 group 256 */
|
||||
ErnieHca::Wire hw{}; /* the HCA scratch (a ratio-0 stage reads its base part) */
|
||||
ErnieMoe::Wire mw{};
|
||||
ErnieMoe::Config moe_cfg{};
|
||||
rad_weight token = 0, head = 0, mm_r = 0, mm_t = 0;
|
||||
rad_buf taps = 0; /* [max_tok, 3 * 4096] bf16 PERSIST, written by the trunk */
|
||||
};
|
||||
|
||||
/* One draft stage: model.mtp.i, the trunk's H+MoE layer without the compressor. */
|
||||
struct Stage {
|
||||
ManifoldConn attn_hc{}, ffn_hc{};
|
||||
rad_weight attn_gain = 0, ffn_gain = 0;
|
||||
rad_op attn_norm = 0, attn_quant = 0, ffn_norm = 0, ffn_quant = 0;
|
||||
ErnieHca hca{};
|
||||
ErnieMoe moe{};
|
||||
};
|
||||
|
||||
Geom g{};
|
||||
Config cfg{};
|
||||
Trunk t{};
|
||||
int64_t smax = 0, qrows = 0, walk_r = 1;
|
||||
ErnieHca::Caches kv{}; /* .raw: the drafter's window group, layers base..base+2 */
|
||||
Stage st[kStages]{};
|
||||
|
||||
/* ---- the context pass */
|
||||
ActQ feat{}; /* the taps' rotated int8 codes (x = Trunk::taps) */
|
||||
QuantAct feat_q{}, act_q{};
|
||||
LinearQ feat_proj{};
|
||||
rad_weight w_fnorm = 0;
|
||||
rad_op op_fnorm = 0;
|
||||
|
||||
/* ---- the query pass and the head */
|
||||
rad_buf dh = 0, hs = 0, dlog = 0;
|
||||
rad_weight w_hc_fn = 0, w_hc_scale = 0, w_hc_base = 0, w_norm = 0;
|
||||
rad_op op_embed = 0, op_embed_ar = 0, op_expand = 0, op_contract = 0, op_norm = 0;
|
||||
rad_op op_gather = 0, op_logits = 0, op_attn_ar = 0, op_zero_y = 0;
|
||||
|
||||
/* ---- the walk */
|
||||
rad_buf memb = 0, e = 0, bias = 0, lg = 0, lgb = 0, tidx = 0, tval = 0, pairs = 0,
|
||||
gath = 0, prev = 0, tokens = 0;
|
||||
rad_weight w_mk1 = 0, w_mk2 = 0;
|
||||
rad_op op_mk_all = 0, op_mk_anc = 0, op_mk = 0, op_bias = 0, op_add = 0, op_mm = 0,
|
||||
op_cast = 0, op_topk = 0, op_wgather = 0, op_pick = 0, op_prev = 0;
|
||||
|
||||
/* The tap op the trunk issues after layer 40, 41 or 42: the mean of the stream row `h0`
|
||||
* (rows [T, 4 * 4096]) into a [T, 4096] column slice of the taps. */
|
||||
static rad_op decl_tap(RadBuilder* b, const Geom& g, rad_buf h0, rad_buf taps) {
|
||||
return rw(b,
|
||||
RAD_OP(b, "mhc_contract",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", kEmbd),
|
||||
RAD_INT("hc", kStreams), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ h0 }, { taps });
|
||||
}
|
||||
static void issue_tap(RadCtx* c, rad_op op, rad_buf h0, rad_buf taps, int tap, int64_t T) {
|
||||
RAD_ISSUE_N(c, op, T, brows(h0, T), bcol(taps, (int64_t)tap * kEmbd, kEmbd, T));
|
||||
}
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, const Trunk& trunk);
|
||||
/* The context pass, one row per trunk row (RadBatch::draft_pass < 0). */
|
||||
void context(RadCtx* c, const RadBatch* batch) const;
|
||||
/* The query pass, the head and the walk, `kBlock` rows a sequence (draft_pass > 0). */
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
/* The proposal, [max_seqs, kBlock] i32 (RadDrafterDecl::proposal, pitch kBlock). */
|
||||
rad_buf proposal() const { return tokens; }
|
||||
|
||||
private:
|
||||
int declare_stage(RadBuilder* b, Names& nm, int i);
|
||||
int connection(RadBuilder* b, Names& nm, ManifoldConn& hc, const char* pre, const char* kind,
|
||||
int l, const ManifoldConn::Wire& w) const;
|
||||
int norm_quant(RadBuilder* b, Names& nm, const char* declared, const char* src, int l,
|
||||
rad_weight* gain, rad_op* norm, rad_op* q) const;
|
||||
rad_op rmsnorm(RadBuilder* b, int64_t rows, rad_weight w, rad_buf x, rad_buf y) const {
|
||||
return rw(b,
|
||||
RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", kEmbd),
|
||||
RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w)),
|
||||
{ x }, { y });
|
||||
}
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------------------ a stage */
|
||||
|
||||
inline int ErnieDspark::connection(RadBuilder* b, Names& nm, ManifoldConn& hc, const char* pre,
|
||||
const char* kind, int l, const ManifoldConn::Wire& w) const {
|
||||
ManifoldConn::Config c;
|
||||
c.hc = kStreams;
|
||||
c.iterations = 20;
|
||||
c.eps = g.eps;
|
||||
c.hc_eps = 1e-6;
|
||||
c.eps_outside = true;
|
||||
c.split = false;
|
||||
ManifoldConn::Src s;
|
||||
s.fn = nm.ckpt("%s.%s_hyper_connection.mapping_proj.weight", pre, kind);
|
||||
s.fn_transposed = true;
|
||||
s.scale_parts[0] = nm.ckpt("%s.%s_hyper_connection.alpha_pre", pre, kind);
|
||||
s.scale_parts[1] = nm.ckpt("%s.%s_hyper_connection.alpha_post", pre, kind);
|
||||
s.scale_parts[2] = nm.ckpt("%s.%s_hyper_connection.alpha_res", pre, kind);
|
||||
s.base = nm.ckpt("%s.%s_hyper_connection.bias", pre, kind);
|
||||
const char* name = nm.f("blk.%d.hc_%s", l, kind[0] == 's' ? "attn" : "ffn");
|
||||
return hc.declare(b, nm, g, l, name, c, w, s, true);
|
||||
}
|
||||
|
||||
inline int ErnieDspark::norm_quant(RadBuilder* b, Names& nm, const char* declared, const char* src,
|
||||
int l, rad_weight* gain, rad_op* norm, rad_op* q) const {
|
||||
RAD_ARCH_TRY(map_copy(b, declared, src));
|
||||
*gain = decl_w(b, declared, RAD_F32, { kEmbd }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp_layer(l));
|
||||
if (!*gain) return RAD_E_INVAL;
|
||||
*norm = rmsnorm(b, g.max_tok, *gain, t.x, t.act.x);
|
||||
*q = decl_trunk_quant(b, g.max_tok, kEmbd, t.act);
|
||||
return *norm && *q ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* model.mtp.i at absolute layer base + i, in the trunk layer's order (declaration is liveness). */
|
||||
inline int ErnieDspark::declare_stage(RadBuilder* b, Names& nm, int i) {
|
||||
Stage& s = st[i];
|
||||
const int l = cfg.base_layer + i;
|
||||
const char* pre = nm.ckpt("model.mtp.%d", i);
|
||||
RAD_ARCH_TRY(connection(b, nm, s.attn_hc, pre, "self_attention", l,
|
||||
{ t.h0, t.x, t.y, t.h1, t.post, t.comb }));
|
||||
if (!g.attn_zero)
|
||||
RAD_ARCH_TRY(norm_quant(b, nm, nm.f("blk.%d.attn_norm.weight", l),
|
||||
nm.ckpt("%s.input_layernorm.weight", pre), l, &s.attn_gain,
|
||||
&s.attn_norm, &s.attn_quant));
|
||||
ErnieHca::Config hc{};
|
||||
hc.ratio = 0;
|
||||
hc.window = kWindow;
|
||||
hc.block = true;
|
||||
// Plain RoPE at rope_theta (THE DRAFT ROPE).
|
||||
hc.theta = 8000000.0;
|
||||
hc.yarn = false;
|
||||
ErnieHca::Wire hw = t.hw;
|
||||
hw.in = t.act;
|
||||
hw.out = t.y;
|
||||
RAD_ARCH_TRY(s.hca.declare(b, nm, g, l, hc, hw, nm.ckpt("%s.self_attn", pre), &kv));
|
||||
RAD_ARCH_TRY(s.attn_hc.declare_post(b));
|
||||
RAD_ARCH_TRY(connection(b, nm, s.ffn_hc, pre, "mlp", l,
|
||||
{ t.h1, t.x, t.y, t.h0, t.post, t.comb }));
|
||||
RAD_ARCH_TRY(norm_quant(b, nm, nm.f("blk.%d.ffn_norm.weight", l),
|
||||
nm.ckpt("%s.post_attention_layernorm.weight", pre), l, &s.ffn_gain,
|
||||
&s.ffn_norm, &s.ffn_quant));
|
||||
ErnieMoe::Wire mw = t.mw;
|
||||
mw.in = t.act;
|
||||
mw.out = t.y;
|
||||
RAD_ARCH_TRY(s.moe.declare(b, nm, g, l, t.moe_cfg, mw,
|
||||
nm.ckpt("%s.block_sparse_moe", pre)));
|
||||
return s.ffn_hc.declare_post(b);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------------ declare */
|
||||
|
||||
inline int ErnieDspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c,
|
||||
const Trunk& trunk) {
|
||||
g = geom; cfg = c; t = trunk;
|
||||
if (!b || !t.h0 || !t.h1 || !t.x || !t.y || !t.post || !t.comb || !t.act.x || !t.act.cq() ||
|
||||
!t.act.cs() || !t.token || !t.head || !t.mm_r || !t.mm_t ||
|
||||
(!g.attn_zero && !t.taps) || g.n_embd != kEmbd)
|
||||
return RAD_E_INVAL;
|
||||
/* A step carries at most max_tok rows, so at most max_tok / 7 sequences draft at once (the
|
||||
* scheduler's block_begin caps them the same way). */
|
||||
smax = std::min<int64_t>(g.max_seqs, g.max_tok / kBlock);
|
||||
if (smax < 1) {
|
||||
fprintf(stderr, "radiance: ernie55: the DSpark block is %lld rows a sequence and a step "
|
||||
"here carries %lld tokens; raise --max-num-batched-tokens to draft\n",
|
||||
(long long)kBlock, (long long)g.max_tok);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
qrows = smax * kBlock;
|
||||
walk_r = g.world > 1 ? 2 : 1; /* a gathered pair row is whole 16-byte words (OPS.md) */
|
||||
const int64_t T = g.max_tok, Vs = g.n_vocab, S = smax;
|
||||
const auto mg = grp_model();
|
||||
const bool rep_kv = !(g.attn_world > 0 && g.attn_world < g.world);
|
||||
|
||||
/* ---------------------------------------------------------------- the drafter's window
|
||||
* One RAD_KV_WINDOW group for the three stages, the trunk HCA window's layout (a 512-wide
|
||||
* latent as K | V halves of 256, block 16). */
|
||||
{
|
||||
RadKVGroupDecl d{};
|
||||
d.kind = RAD_KV_WINDOW;
|
||||
d.dtype = RAD_BF16;
|
||||
d.n_head_kv = 1;
|
||||
d.head_dim = ErnieHca::kHeadDim / 2;
|
||||
d.window = kWindow;
|
||||
kv.raw = rad_decl_kv_group(b, nm.f("kv_dspark"), &d);
|
||||
if (!kv.raw) return RAD_E_INVAL;
|
||||
if (rep_kv) RAD_ARCH_TRY(rad_kv_group_replicated(b, kv.raw));
|
||||
if (g.attn_zero) {
|
||||
RAD_ARCH_TRY(rad_kv_group_zero(b, kv.raw));
|
||||
if (!rw(b, RAD_OP(b, "kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T),
|
||||
RAD_INT("head_dim", ErnieHca::kHeadDim / 2),
|
||||
RAD_INT("n_head_kv", 1),
|
||||
RAD_INT("block_size", ErnieHca::kRawBlock),
|
||||
RAD_STR("kv_dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, {}))
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- model-scope weights */
|
||||
if (!g.attn_zero) {
|
||||
const char* fn_nm = nm.f("dspark.feature_norm.weight");
|
||||
RAD_ARCH_TRY(map_copy(b, fn_nm, nm.ckpt("model.mtp.feature_norm.weight")));
|
||||
w_fnorm = decl_w(b, fn_nm, RAD_F32, { kEmbd }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, mg);
|
||||
if (!w_fnorm) return RAD_E_INVAL;
|
||||
}
|
||||
RAD_ARCH_TRY(map_transpose(b, nm.f("dspark.output_hc.fn"),
|
||||
nm.ckpt("model.mtp.mhc_contract.hc_head_fn")));
|
||||
const char* hc_sc = nm.ckpt("model.mtp.mhc_contract.hc_head_scale");
|
||||
RAD_ARCH_TRY(map_concat(b, nm.f("dspark.output_hc.scale"), { hc_sc, hc_sc, hc_sc, hc_sc }));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.output_hc.base"),
|
||||
nm.ckpt("model.mtp.mhc_contract.hc_head_base")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.norm.weight"), nm.ckpt("model.mtp.norm.weight")));
|
||||
w_hc_fn = decl_w(b, nm.f("dspark.output_hc.fn"), RAD_F32, { kStreams, kStreams * kEmbd },
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, mg);
|
||||
w_hc_scale = decl_w(b, nm.f("dspark.output_hc.scale"), RAD_F32, { kStreams },
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, mg);
|
||||
w_hc_base = decl_w(b, nm.f("dspark.output_hc.base"), RAD_F32, { kStreams },
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, mg);
|
||||
w_norm = decl_w(b, nm.f("dspark.norm.weight"), RAD_F32, { kEmbd }, RAD_ACCESS_PER_TOKEN,
|
||||
RAD_SHARD_NONE, mg);
|
||||
/* markov_w1 is stored [256, V] (SPEC §11.2): transposed to [V, 256] and read by id, whole on
|
||||
* every rank. markov_w2 [V, 256] is the bias GEMM's weight, row-sharded with the vocabulary. */
|
||||
RAD_ARCH_TRY(map_transpose(b, nm.f("dspark.markov_w1"),
|
||||
nm.ckpt("model.mtp.markov_head.markov_w1.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.markov_w2"),
|
||||
nm.ckpt("model.mtp.markov_head.markov_w2.weight")));
|
||||
w_mk1 = decl_w(b, nm.f("dspark.markov_w1"), RAD_BF16, { g.n_vocab_all, kRank },
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, mg);
|
||||
w_mk2 = decl_w(b, nm.f("dspark.markov_w2"), RAD_BF16, { Vs, kRank }, RAD_ACCESS_VOCAB,
|
||||
RAD_SHARD_ROW, mg);
|
||||
if (!w_hc_fn || !w_hc_scale || !w_hc_base || !w_norm || !w_mk1 || !w_mk2)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
/* ---------------------------------------------------------------- buffers */
|
||||
if (!g.attn_zero) {
|
||||
feat.x = t.taps;
|
||||
RAD_ARCH_TRY(feat.declare_trunk(b, nm, g, "dspark.feat", kTaps * kEmbd));
|
||||
if (!feat.cq() || !feat.cs()) return RAD_E_INVAL;
|
||||
}
|
||||
dh = decl_b(b, nm.f("dspark.hidden"), RAD_BF16, { qrows, kEmbd });
|
||||
hs = decl_b(b, nm.f("dspark.head_in"), RAD_BF16, { qrows, kEmbd });
|
||||
/* The block's logits, a sequence's seven rows side by side: the head writes them as
|
||||
* [S * 7, Vs] and step i reads its column slice [S, Vs] at a pitch of seven rows. */
|
||||
dlog = decl_b(b, nm.f("dspark.logits"), RAD_F32, { S, kBlock * Vs });
|
||||
memb = decl_b(b, nm.f("dspark.markov_rows"), RAD_BF16, { qrows, kRank });
|
||||
e = decl_b(b, nm.f("dspark.markov_prev"), RAD_BF16, { S, kRank });
|
||||
bias = decl_b(b, nm.f("dspark.markov_bias"), RAD_F32, { S, Vs });
|
||||
lg = decl_b(b, nm.f("dspark.score"), RAD_F32, { S, Vs });
|
||||
lgb = decl_b(b, nm.f("dspark.score_bf16"), RAD_BF16, { S, Vs });
|
||||
tidx = decl_b(b, nm.f("dspark.top_idx"), RAD_I32, { S, walk_r });
|
||||
tval = decl_b(b, nm.f("dspark.top_val"), RAD_F32, { S, walk_r });
|
||||
pairs = decl_b(b, nm.f("dspark.top_pairs"), RAD_F32, { S, walk_r * 2 });
|
||||
if (g.world > 1) {
|
||||
gath = decl_b(b, nm.f("dspark.top_gathered"), RAD_F32, { S, g.world * walk_r * 2 });
|
||||
prev = decl_b(b, nm.f("dspark.prev"), RAD_I32, { S, 1 });
|
||||
if (!gath || !prev) return RAD_E_INVAL;
|
||||
} else {
|
||||
prev = tidx; /* R = 1: row_topk's id is the winner */
|
||||
}
|
||||
/* The proposal the engine reads (RadDrafterDecl::proposal), one row a sequence. */
|
||||
tokens = decl_b(b, nm.f("dspark.tokens"), RAD_I32, { S, kBlock });
|
||||
if (!dh || !hs || !dlog || !memb || !e || !bias || !lg || !lgb ||
|
||||
!tidx || !tval || !pairs || !tokens)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
/* ---------------------------------------------------------------- the context pass
|
||||
* taps -> IQ8R rotated int8 codes -> feature_projection -> feature_norm -> the layer input's
|
||||
* codes; each stage's raw KV path then reads them (ErnieHca::store_kv). */
|
||||
if (!g.attn_zero) {
|
||||
RAD_ARCH_TRY(feat_q.declare(b, g, feat, kTaps * kEmbd));
|
||||
RAD_ARCH_TRY(feat_proj.declare(b, nm, g, nm.f("dspark.feature_proj"), kEmbd, kTaps * kEmbd,
|
||||
RAD_SHARD_NONE, mg,
|
||||
{ nm.ckpt("model.mtp.feature_projection.weight") }, feat,
|
||||
t.x));
|
||||
op_fnorm = rmsnorm(b, T, w_fnorm, t.x, t.act.x);
|
||||
RAD_ARCH_TRY(act_q.declare(b, g, t.act, kEmbd));
|
||||
if (!op_fnorm || !feat_q.op || !act_q.op) return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- the query pass */
|
||||
op_embed = rw(b,
|
||||
RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_embd", kEmbd),
|
||||
RAD_INT("n_vocab", Vs), RAD_STR("dtype", "bf16"),
|
||||
RAD_INT("vocab_offset", g.vocab_off)),
|
||||
RAD_WEIGHTS(t.token)),
|
||||
{}, { t.x });
|
||||
op_embed_ar = GlmTp::reduce(b, g, t.x, true);
|
||||
op_expand = rw(b,
|
||||
RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", kEmbd),
|
||||
RAD_STR("from", "bf16"), RAD_STR("to", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ t.x }, { t.h0 });
|
||||
if (!op_embed || (g.world > 1 && !op_embed_ar) || !op_expand) return RAD_E_INVAL;
|
||||
if (g.attn_world > 0 && g.attn_world < g.world) {
|
||||
op_attn_ar = GlmTp::reduce(b, g, t.y, true);
|
||||
if (!op_attn_ar) return RAD_E_INVAL;
|
||||
if (g.attn_zero) {
|
||||
op_zero_y = rw(b, RAD_OP(b, "fill",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", kEmbd),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, { t.y });
|
||||
if (!op_zero_y) return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < kStages; ++i) RAD_ARCH_TRY(declare_stage(b, nm, i));
|
||||
/* The kv_stores read the window group's block size back once its first op resolved it. */
|
||||
if (!g.attn_zero && rad_kv_block_size(b, kv.raw) != ErnieHca::kRawBlock) return RAD_E_INVAL;
|
||||
|
||||
/* ---------------------------------------------------------------- the head */
|
||||
op_contract = rw(b,
|
||||
RAD_OP(b, "mhc_head",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", kEmbd),
|
||||
RAD_INT("hc", kStreams), RAD_F64("eps", g.eps),
|
||||
RAD_F64("hc_eps", 1e-6), RAD_INT("eps_outside", 1),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_hc_fn, w_hc_scale, w_hc_base)),
|
||||
{ t.h0 }, { t.x });
|
||||
op_norm = rmsnorm(b, qrows, w_norm, t.x, dh);
|
||||
op_gather = rw(b,
|
||||
RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", kEmbd),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ dh }, { hs });
|
||||
op_logits = rw(b,
|
||||
RAD_OP(b, "logits_gemm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n_vocab", Vs),
|
||||
RAD_INT("n_embd", kEmbd), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(t.head)),
|
||||
{ hs }, { dlog });
|
||||
if (!op_contract || !op_norm || !op_gather || !op_logits) return RAD_E_INVAL;
|
||||
|
||||
/* ---------------------------------------------------------------- the walk
|
||||
* Declared once and issued per step, in issue order. */
|
||||
auto embed_mk = [&](int64_t rows, rad_buf out) {
|
||||
return rw(b,
|
||||
RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n_embd", kRank),
|
||||
RAD_INT("n_vocab", g.n_vocab_all), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_mk1)),
|
||||
{}, { out });
|
||||
};
|
||||
op_mk_all = embed_mk(qrows, memb); /* step 0: every block row, the anchors gathered */
|
||||
op_mk_anc = rw(b,
|
||||
RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", kRank),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ memb }, { e });
|
||||
op_mk = rw(b,
|
||||
RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n_embd", kRank),
|
||||
RAD_INT("n_vocab", g.n_vocab_all), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_mk1)),
|
||||
{ prev }, { e });
|
||||
op_bias = rw(b,
|
||||
RAD_OP(b, "logits_gemm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n_vocab", Vs),
|
||||
RAD_INT("n_embd", kRank), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_mk2)),
|
||||
{ e }, { bias });
|
||||
op_add = rw(b,
|
||||
RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", Vs), RAD_STR("dtype", "f32")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ dlog, bias }, { lg });
|
||||
/* Before the argmax at every step: multimax is not monotonic for this checkpoint. */
|
||||
op_mm = rw(b,
|
||||
RAD_OP(b, "multimax",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", Vs), RAD_STR("dtype", "f32")),
|
||||
RAD_WEIGHTS(t.mm_r, t.mm_t)),
|
||||
{ lg }, { lg });
|
||||
op_cast = rw(b,
|
||||
RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", Vs), RAD_STR("from", "f32"),
|
||||
RAD_STR("to", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ lg }, { lgb });
|
||||
/* Sharded, row_topk reports global ids and writes the pair plane the gather moves; whole, the
|
||||
* optional `vocab_off` is left out (present at 0 is another declaration). */
|
||||
op_topk = g.world > 1
|
||||
? rw(b,
|
||||
RAD_OP(b, "row_topk",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("N", Vs), RAD_INT("R", walk_r),
|
||||
RAD_INT("vocab_off", g.vocab_off), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ lgb }, { tidx, tval, pairs })
|
||||
: rw(b,
|
||||
RAD_OP(b, "row_topk",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("N", Vs), RAD_INT("R", walk_r),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ lgb }, { tidx, tval, pairs });
|
||||
if (g.world > 1)
|
||||
op_wgather = rw(b,
|
||||
RAD_OP(b, "all_gather",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_INT("numel", S * walk_r * 2),
|
||||
RAD_STR("dtype", "f32"), RAD_INT("row", walk_r * 2)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ pairs }, { gath });
|
||||
const int64_t n_pairs = g.world * walk_r;
|
||||
op_pick = rw(b,
|
||||
RAD_OP(b, "pair_argmax",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", n_pairs),
|
||||
RAD_STR("dtype", "f32")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ g.world > 1 ? gath : pairs }, { tokens });
|
||||
if (g.world > 1)
|
||||
op_prev = rw(b,
|
||||
RAD_OP(b, "pair_argmax",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", n_pairs),
|
||||
RAD_STR("dtype", "f32")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ gath }, { prev });
|
||||
if (!op_mk_all || !op_mk_anc || !op_mk || !op_bias || !op_add || !op_mm || !op_cast ||
|
||||
!op_topk || (g.world > 1 && (!op_wgather || !op_prev)) || !op_pick)
|
||||
return RAD_E_INVAL;
|
||||
/* The walk's ops are declared once and issued seven times, so every buffer they touch is live
|
||||
* to the last of them: step i + 1 reads the block's logits, and writes every plane, after
|
||||
* step i's last op. Declared as reads of that op (liveness only; `prev`, op_prev's own
|
||||
* output under TP, is already live from op_mk to it). */
|
||||
const rad_buf live[] = { dlog, memb, e, bias, lg, lgb, tidx, tval, pairs,
|
||||
g.world > 1 ? gath : pairs };
|
||||
return rad_op_reads(b, op_prev ? op_prev : op_pick, live, (int)(sizeof live / sizeof live[0]));
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------------ the context pass */
|
||||
|
||||
inline void ErnieDspark::context(RadCtx* c, const RadBatch* batch) const {
|
||||
if (g.attn_zero) return;
|
||||
const int64_t T = batch->n_tok;
|
||||
if (T <= 0) return;
|
||||
feat_q.step(c, T);
|
||||
feat_proj.step(c, feat, t.x, T);
|
||||
RAD_ISSUE_N(c, op_fnorm, T, brows(t.x, T), RAD_W(w_fnorm), brows(t.act.x, T));
|
||||
act_q.step(c, T);
|
||||
for (int i = 0; i < kStages; ++i) st[i].hca.store_kv(c, batch);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------------ the query pass */
|
||||
|
||||
inline void ErnieDspark::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok, S = batch->n_seq;
|
||||
if (T <= 0 || S <= 0) return;
|
||||
if (T != S * kBlock || S > smax || batch->max_q_len != kBlock) {
|
||||
rad_step_fail(c, "ernie55 dspark: a query pass is 7 rows a sequence, at most "
|
||||
"max_tok / 7 sequences");
|
||||
return;
|
||||
}
|
||||
RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(t.token),
|
||||
brows(t.x, T));
|
||||
if (op_embed_ar) RAD_ISSUE_N(c, op_embed_ar, T * kEmbd, brows(t.x, T), RAD_NONE);
|
||||
for (int i = 0; i < kStreams; ++i)
|
||||
RAD_ISSUE_N(c, op_expand, T, brows(t.x, T), bcol(t.h0, i * kEmbd, kEmbd, T));
|
||||
for (int i = 0; i < kStages; ++i) {
|
||||
const Stage& s = st[i];
|
||||
s.attn_hc.read(c, T);
|
||||
if (op_zero_y) {
|
||||
RAD_ISSUE_N(c, op_zero_y, T, brows(t.y, T));
|
||||
} else {
|
||||
RAD_ISSUE_N(c, s.attn_norm, T, brows(t.x, T), RAD_W(s.attn_gain), brows(t.act.x, T));
|
||||
RAD_ISSUE_N(c, s.attn_quant, T, brows(t.act.x, T), brows(t.act.cq(), T),
|
||||
brows(t.act.cs(), T));
|
||||
s.hca.step(c, batch);
|
||||
}
|
||||
if (op_attn_ar) RAD_ISSUE_N(c, op_attn_ar, T * kEmbd, brows(t.y, T), RAD_NONE);
|
||||
s.attn_hc.write(c, T);
|
||||
s.ffn_hc.read(c, T);
|
||||
RAD_ISSUE_N(c, s.ffn_norm, T, brows(t.x, T), RAD_W(s.ffn_gain), brows(t.act.x, T));
|
||||
RAD_ISSUE_N(c, s.ffn_quant, T, brows(t.act.x, T), brows(t.act.cq(), T),
|
||||
brows(t.act.cs(), T));
|
||||
s.moe.step(c, batch);
|
||||
s.ffn_hc.write(c, T);
|
||||
}
|
||||
RAD_ISSUE_N(c, op_contract, T, brows(t.h0, T), RAD_W(w_hc_fn), RAD_W(w_hc_scale),
|
||||
RAD_W(w_hc_base), brows(t.x, T));
|
||||
RAD_ISSUE_N(c, op_norm, T, brows(t.x, T), RAD_W(w_norm), brows(dh, T));
|
||||
|
||||
/* Every row predicts (block = depth), so the scheduler names all of them, sequence-major. */
|
||||
const int64_t R = batch->n_out;
|
||||
if (R <= 0) return;
|
||||
if (R != T || !batch->out_ids) {
|
||||
rad_step_fail(c, "ernie55 dspark: the query pass samples every block row");
|
||||
return;
|
||||
}
|
||||
const int64_t Vs = g.n_vocab;
|
||||
RAD_ISSUE_N(c, op_gather, R, brows(dh, T), praw(batch->out_ids, RAD_I32, R), brows(hs, R));
|
||||
/* [S, 7 * Vs] read as the head's [S * 7, Vs] rows. */
|
||||
RAD_ISSUE_N(c, op_logits, R, brows(hs, R), RAD_W(t.head),
|
||||
RAD_P_T2(rad_buf_ptr(c, dlog), RAD_F32, R, Vs));
|
||||
|
||||
for (int64_t i = 0; i < kBlock; ++i) {
|
||||
if (i == 0) {
|
||||
/* The anchors are each sequence's first row (cu_seqlens). */
|
||||
RAD_ISSUE_N(c, op_mk_all, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w_mk1),
|
||||
brows(memb, T));
|
||||
RAD_ISSUE_N(c, op_mk_anc, S, brows(memb, T), praw(batch->cu_seqlens, RAD_I32, S),
|
||||
brows(e, S));
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_mk, S, brows(prev, S), RAD_W(w_mk1), brows(e, S));
|
||||
}
|
||||
RAD_ISSUE_N(c, op_bias, S, brows(e, S), RAD_W(w_mk2), brows(bias, S));
|
||||
RAD_ISSUE_N(c, op_add, S, bcol(dlog, i * Vs, Vs, S), brows(bias, S), brows(lg, S));
|
||||
RAD_ISSUE_N(c, op_mm, S, brows(lg, S), RAD_W(t.mm_r), RAD_W(t.mm_t), brows(lg, S));
|
||||
RAD_ISSUE_N(c, op_cast, S, brows(lg, S), brows(lgb, S));
|
||||
RAD_ISSUE_N(c, op_topk, S, brows(lgb, S), brows(tidx, S), brows(tval, S),
|
||||
brows(pairs, S));
|
||||
if (op_wgather) RAD_ISSUE(c, op_wgather, brows(pairs, S), brows(gath, S));
|
||||
const RadOperand src = op_wgather ? brows(gath, S) : brows(pairs, S);
|
||||
RAD_ISSUE_N(c, op_pick, S, src, bcol(tokens, i, 1, S), RAD_NONE);
|
||||
if (op_prev && i + 1 < kBlock) RAD_ISSUE_N(c, op_prev, S, src, brows(prev, S), RAD_NONE);
|
||||
}
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_ERNIE_DSPARK_H */
|
||||
@@ -0,0 +1,729 @@
|
||||
/* rad_block_ernie_hca.h -- ERNIE-5.5 Hierarchical Context Attention (HCA) block.
|
||||
*
|
||||
* Replicated on every rank (all 64 heads), IQ8R trunk linears (rotated int8 at group 256):
|
||||
* q_down IQ8R -> q_layernorm -> had_quant_act_i8g (256) -> q_up IQ8R -> weightless per-head RMSNorm (512)
|
||||
* -> GPT-J YaRN RoPE on [448, 512)
|
||||
* kv_proj IQ8R -> kv_layernorm -> GPT-J YaRN RoPE on [448, 512) -> raw RAD_KV_WINDOW (bf16)
|
||||
* compressor bf16 [wkv | wgate] -> qsa_work -> hca_compress -> comp RAD_KV_FULL -> qsa_tail_store
|
||||
* -> hca_attn (raw_used rebased window + sink) -> inverse GPT-J YaRN RoPE -> vha_postmix
|
||||
* -> 8-group had_quant_act_i8g + wo_a IQ8R * sigmoid(gate_proj(c_q)) -> had_quant_act_i8g -> o_proj IQ8R
|
||||
*
|
||||
* Config::block is the bundled DSpark drafter's stage attention (rad_block_ernie_dspark.h): no
|
||||
* compressor (ratio 0), and `hca_attn`'s anchor form, in which every row of a block sees the
|
||||
* window behind the block's first row and the whole block, over a RAD_KV_WINDOW group the caller
|
||||
* declares. store_kv() is the raw KV path alone, which the drafter's context pass runs over its
|
||||
* projected trunk features.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_ERNIE_HCA_H
|
||||
#define RAD_BLOCK_ERNIE_HCA_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
#include "rad_linear.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct ErnieHca {
|
||||
static constexpr int64_t kEmbd = 4096;
|
||||
static constexpr int64_t kHeads = 64;
|
||||
static constexpr int64_t kHeadDim = 512;
|
||||
static constexpr int64_t kRopeDim = 64;
|
||||
static constexpr int64_t kRopeOff = 448;
|
||||
static constexpr int64_t kQLora = 1024;
|
||||
static constexpr int64_t kQDim = kHeads * kHeadDim; /* 32768 */
|
||||
static constexpr int64_t kOGroups = 8;
|
||||
static constexpr int64_t kOGroupIn = kQDim / kOGroups; /* 4096 */
|
||||
static constexpr int64_t kOGroupOut = 1024; /* 8 * 128 */
|
||||
static constexpr int64_t kODim = kOGroups * kOGroupOut; /* 8192 */
|
||||
static constexpr int64_t kVhaRank = 16;
|
||||
static constexpr int64_t kRawBlock = 16;
|
||||
|
||||
struct Config {
|
||||
int64_t ratio = 128;
|
||||
int64_t window = 128;
|
||||
double theta = 160000.0;
|
||||
bool yarn = true;
|
||||
/* A block drafter's stage (ratio 0 only): hca_attn's `anchor` form over the window group,
|
||||
* read through its own seqused. Off, ratio 0 is the attn_paged_sink window. */
|
||||
bool block = false;
|
||||
};
|
||||
|
||||
struct Wire {
|
||||
ActQ in{};
|
||||
rad_buf out = 0;
|
||||
|
||||
/* Shared scratch across the 37 HCA layers. */
|
||||
rad_buf q_a_raw = 0;
|
||||
ActQ c_q{};
|
||||
rad_buf q_raw = 0, q = 0;
|
||||
rad_buf kv_tmp = 0, k_raw = 0;
|
||||
rad_buf comp_kg = 0, stage = 0, page = 0, bpos = 0, nc = 0;
|
||||
rad_buf attn_out = 0, o_mix = 0;
|
||||
rad_buf gate = 0;
|
||||
ActQ o_mix_act{};
|
||||
rad_buf wo_tmp = 0;
|
||||
ActQ gated{};
|
||||
};
|
||||
|
||||
struct Caches {
|
||||
rad_kvgroup raw = 0, comp = 0, state = 0;
|
||||
};
|
||||
|
||||
Geom g{};
|
||||
Config c{};
|
||||
Wire w{};
|
||||
Caches caches{};
|
||||
int layer = 0;
|
||||
int64_t max_work = 0;
|
||||
int64_t ring_cap = 0;
|
||||
bool attn_zero = false;
|
||||
int og_base = 0;
|
||||
int og_count = (int)kOGroups;
|
||||
int64_t local_qdim = kQDim;
|
||||
int64_t local_odim = kODim;
|
||||
|
||||
LinearQ q_down{}, q_up{}, kv_proj{}, comp_proj{}, gate_proj{}, o_proj{};
|
||||
LinearQ wo_a[kOGroups]{};
|
||||
QuantAct q_quant{}, gated_quant{};
|
||||
rad_weight w_q_norm = 0, w_kv_norm = 0, w_ape = 0, w_comp_norm = 0;
|
||||
rad_weight w_sink = 0, w_u = 0, w_v = 0;
|
||||
|
||||
rad_op op_q_norm = 0, op_q_norm_p = 0, op_q_rope = 0;
|
||||
rad_op op_kv_norm = 0, op_k_rope = 0, op_kv_store = 0;
|
||||
rad_op op_work = 0, op_comp = 0, op_tail = 0;
|
||||
rad_op op_attn = 0, op_o_rope = 0, op_vha = 0;
|
||||
bool wo_bf16 = false;
|
||||
rad_op op_wo_q[kOGroups]{}, op_act_mul[kOGroups]{};
|
||||
|
||||
/* YaRN find_correction_dim for rotary_dim=64, original_max_position_embeddings=65536. */
|
||||
static void yarn_bounds(double theta, double* low_out, double* high_out) {
|
||||
const double kPi = 3.14159265358979323846;
|
||||
auto corr = [&](double beta) {
|
||||
return (double)kRopeDim * std::log(65536.0 / (beta * 2.0 * kPi)) /
|
||||
(2.0 * std::log(theta));
|
||||
};
|
||||
*low_out = std::max(0.0, std::floor(corr(32.0)));
|
||||
*high_out = std::min((double)(kRopeDim - 1), std::ceil(corr(1.0)));
|
||||
}
|
||||
|
||||
static rad_op decl_hca_rope(RadBuilder* b, const Config& cfg, int64_t max_tok,
|
||||
int64_t n_head, int inverse) {
|
||||
std::vector<RadParam> ps = {
|
||||
RAD_RANGE("M", 1, max_tok), RAD_INT("head_dim", kHeadDim),
|
||||
RAD_INT("n_head", n_head), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", cfg.theta), RAD_F64("scale", 1.0),
|
||||
RAD_STR("mode", "gptj"), RAD_INT("rotary_dim", kRopeDim),
|
||||
RAD_INT("rotary_offset", kRopeOff),
|
||||
};
|
||||
if (inverse) ps.push_back(RAD_INT("inverse", 1));
|
||||
if (cfg.yarn) {
|
||||
double lo = 0.0, hi = 0.0;
|
||||
yarn_bounds(cfg.theta, &lo, &hi);
|
||||
ps.push_back(RAD_F64("yarn_factor", 16.0));
|
||||
ps.push_back(RAD_F64("yarn_low", lo));
|
||||
ps.push_back(RAD_F64("yarn_high", hi));
|
||||
ps.push_back(RAD_F64("yarn_magnitude", 1.0));
|
||||
}
|
||||
return rad_decl_op(b, "rope", ps.data(), (int)ps.size(), RAD_NOWEIGHTS);
|
||||
}
|
||||
|
||||
static int declare_wire(RadBuilder* b, Names& nm, const Geom& g, const Config& cfg, Wire* w) {
|
||||
if (!b || !w || !w->in.x || !w->out || g.n_embd != kEmbd || g.max_tok < 1 ||
|
||||
g.max_seqs < 1 || cfg.window < 1 || (cfg.ratio != 0 && cfg.ratio != 128) ||
|
||||
cfg.theta <= 0.0)
|
||||
return RAD_E_INVAL;
|
||||
const int64_t T = g.max_tok;
|
||||
w->q_a_raw = decl_b(b, nm.f("hca.q_a_raw"), RAD_BF16, { T, kQLora });
|
||||
w->c_q.x = decl_b(b, nm.f("hca.c_q"), RAD_BF16, { T, kQLora });
|
||||
RAD_ARCH_TRY(w->c_q.declare_trunk(b, nm, g, "hca.c_q", kQLora));
|
||||
w->q_raw = decl_b(b, nm.f("hca.q_raw"), RAD_BF16, { T, kQDim });
|
||||
w->q = decl_b(b, nm.f("hca.q"), RAD_BF16, { T, kQDim });
|
||||
w->kv_tmp = decl_b(b, nm.f("hca.kv_tmp"), RAD_BF16, { T, kHeadDim });
|
||||
w->k_raw = decl_b(b, nm.f("hca.k_raw"), RAD_BF16, { T, kHeadDim });
|
||||
|
||||
if (cfg.ratio > 0) {
|
||||
const int64_t mw = T / cfg.ratio + g.max_seqs;
|
||||
w->comp_kg = decl_b(b, nm.f("hca.comp_kg"), RAD_BF16, { T, 2 * kHeadDim });
|
||||
w->stage = decl_b(b, nm.f("hca.stage"), RAD_BF16, { mw * cfg.ratio, 2 * kHeadDim });
|
||||
w->page = decl_b(b, nm.f("hca.page"), RAD_I32, { mw });
|
||||
w->bpos = decl_b(b, nm.f("hca.bpos"), RAD_I32, { mw });
|
||||
w->nc = decl_b(b, nm.f("hca.nc"), RAD_I32, { g.max_seqs });
|
||||
if (!w->comp_kg || !w->stage || !w->page || !w->bpos || !w->nc) return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
const int aw = g.attn_world > 0 && g.attn_world < g.world ? g.attn_world : g.world;
|
||||
const bool out_sharded = !g.attn_zero && aw > 1 && aw < g.world;
|
||||
const int64_t w_qdim = out_sharded ? kQDim / aw : kQDim;
|
||||
const int64_t w_odim = out_sharded ? kODim / aw : kODim;
|
||||
|
||||
w->attn_out = decl_b(b, nm.f("hca.attn_out"), RAD_BF16, { T, kQDim });
|
||||
w->o_mix = decl_b(b, nm.f("hca.o_mix"), RAD_BF16, { T, kQDim });
|
||||
w->gate = decl_b(b, nm.f("hca.gate"), RAD_BF16, { T, w_odim });
|
||||
/* Each wo_a group's rotated int8 codes live in their own rows (a GEMM reads whole rows of
|
||||
* its input), group i at row i * (the step's rows). */
|
||||
w->o_mix_act.x = w->o_mix;
|
||||
RAD_ARCH_TRY(w->o_mix_act.declare_trunk(b, nm, g, "hca.o_mix", kOGroupIn,
|
||||
T * (w_qdim / kOGroupIn)));
|
||||
w->wo_tmp = decl_b(b, nm.f("hca.wo_tmp"), RAD_BF16, { T, kOGroupOut });
|
||||
w->gated.x = decl_b(b, nm.f("hca.gated"), RAD_BF16, { T, w_odim });
|
||||
RAD_ARCH_TRY(w->gated.declare_trunk(b, nm, g, "hca.gated", w_odim));
|
||||
|
||||
if (!w->q_a_raw || !w->c_q.x || !w->q_raw || !w->q || !w->kv_tmp || !w->k_raw ||
|
||||
!w->attn_out || !w->o_mix || !w->gate || !w->o_mix_act.x || !w->wo_tmp || !w->gated.x)
|
||||
return RAD_E_INVAL;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Config& cfg,
|
||||
const Wire& wire, const char* ckpt_attn, Caches* out_caches) {
|
||||
g = geom;
|
||||
c = cfg;
|
||||
w = wire;
|
||||
layer = l;
|
||||
if (!b || !ckpt_attn || !out_caches || g.n_embd != kEmbd || g.n_head != kHeads ||
|
||||
g.max_tok < 1 || g.max_seqs < 1 || c.window < 1 || c.theta <= 0.0)
|
||||
return RAD_E_INVAL;
|
||||
if (c.ratio != 128 && c.ratio != 0) return RAD_E_UNSUPPORTED;
|
||||
if (c.block && c.ratio != 0) {
|
||||
fprintf(stderr, "radiance: ernie_hca: layer %d: a drafter block stage has no "
|
||||
"compressor (ratio 0); asked for ratio %lld\n", l, (long long)c.ratio);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
const auto wg = grp_layer(l);
|
||||
const int64_t T = g.max_tok;
|
||||
const int aw = g.attn_world > 0 && g.attn_world < g.world ? g.attn_world : g.world;
|
||||
const bool rep_kv = aw == g.world;
|
||||
attn_zero = g.attn_zero;
|
||||
if (attn_zero) {
|
||||
ring_cap = c.ratio > 0 ? (c.ratio + g.max_spec) : 0;
|
||||
auto decl_bs = [&](int64_t bs, int64_t hd) {
|
||||
return rw(b, RAD_OP(b, "kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", hd),
|
||||
RAD_INT("n_head_kv", 1), RAD_INT("block_size", bs),
|
||||
RAD_STR("kv_dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, {});
|
||||
};
|
||||
if (!out_caches->raw) {
|
||||
RadKVGroupDecl d{};
|
||||
d.kind = RAD_KV_WINDOW;
|
||||
d.dtype = RAD_BF16;
|
||||
d.n_head_kv = 1;
|
||||
d.head_dim = kHeadDim / 2;
|
||||
d.window = c.window;
|
||||
out_caches->raw = rad_decl_kv_group(b, nm.f("kv_hca_raw"), &d);
|
||||
if (!out_caches->raw) return RAD_E_INVAL;
|
||||
if (!decl_bs(kRawBlock, kHeadDim / 2)) return RAD_E_INVAL;
|
||||
}
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, out_caches->raw));
|
||||
if (c.ratio > 0) {
|
||||
if (!out_caches->state) {
|
||||
RadKVGroupDecl d{};
|
||||
d.kind = RAD_KV_LINEAR;
|
||||
d.dtype = RAD_BF16;
|
||||
d.n_head_kv = 1;
|
||||
d.state_dim[0] = ring_cap;
|
||||
d.state_dim[1] = 2 * kHeadDim;
|
||||
out_caches->state = rad_decl_kv_group(b, nm.f("kv_hca_state"), &d);
|
||||
if (!out_caches->state) return RAD_E_INVAL;
|
||||
}
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, out_caches->state));
|
||||
if (!out_caches->comp) {
|
||||
RadKVGroupDecl d{};
|
||||
d.kind = RAD_KV_FULL;
|
||||
d.dtype = RAD_BF16;
|
||||
d.n_head_kv = 1;
|
||||
d.head_dim = 2;
|
||||
out_caches->comp = rad_decl_kv_group(b, nm.f("kv_hca_comp"), &d);
|
||||
if (!out_caches->comp) return RAD_E_INVAL;
|
||||
RAD_ARCH_TRY(rad_kv_group_dense_read(b, out_caches->comp));
|
||||
if (!decl_bs(c.ratio, 2)) return RAD_E_INVAL;
|
||||
}
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, out_caches->comp));
|
||||
}
|
||||
caches = *out_caches;
|
||||
return RAD_OK;
|
||||
}
|
||||
if (!w.in.x || !w.out || !w.q_a_raw || !w.c_q.x || !w.q_raw || !w.q || !w.kv_tmp ||
|
||||
!w.k_raw || !w.attn_out || !w.o_mix || !w.gate || !w.o_mix_act.x ||
|
||||
!w.o_mix_act.cq() || !w.o_mix_act.cs() || !w.wo_tmp || !w.gated.x || w.attn_out == w.o_mix ||
|
||||
(c.ratio > 0 && (!w.comp_kg || !w.stage || !w.page || !w.bpos || !w.nc)))
|
||||
return RAD_E_INVAL;
|
||||
const bool out_sharded = aw > 1 && aw < g.world;
|
||||
if (out_sharded && (kOGroups % aw != 0)) return RAD_E_UNSUPPORTED;
|
||||
og_count = out_sharded ? (int)(kOGroups / aw) : (int)kOGroups;
|
||||
og_base = out_sharded ? g.attn_rank * og_count : 0;
|
||||
local_qdim = (int64_t)og_count * kOGroupIn;
|
||||
local_odim = (int64_t)og_count * kOGroupOut;
|
||||
max_work = c.ratio > 0 ? (T / c.ratio + g.max_seqs) : 0;
|
||||
ring_cap = c.ratio > 0 ? (c.ratio + g.max_spec) : 0;
|
||||
|
||||
/* 1. Query path: q_down -> q_layernorm -> had_quant_act_i8g -> q_up -> rmsnorm_p -> YaRN RoPE */
|
||||
RAD_ARCH_TRY(q_down.declare(b, nm, g, nm.f("blk.%d.attn_q_a", l), kQLora, kEmbd,
|
||||
RAD_SHARD_NONE, wg,
|
||||
{ nm.ckpt("%s.linear_q_down_proj.weight", ckpt_attn) },
|
||||
w.in, w.q_a_raw));
|
||||
const char* q_norm_nm = nm.f("blk.%d.attn_q_norm.weight", l);
|
||||
RAD_ARCH_TRY(map_copy(b, q_norm_nm, nm.ckpt("%s.q_layernorm.weight", ckpt_attn)));
|
||||
w_q_norm = decl_w(b, q_norm_nm, RAD_F32, { kQLora }, RAD_ACCESS_PER_TOKEN,
|
||||
RAD_SHARD_NONE, wg);
|
||||
if (!w_q_norm) return RAD_E_INVAL;
|
||||
op_q_norm = rw(b,
|
||||
RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", kQLora),
|
||||
RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_q_norm)),
|
||||
{ w.q_a_raw }, { w.c_q.x });
|
||||
RAD_ARCH_TRY(q_quant.declare(b, g, w.c_q, kQLora));
|
||||
RAD_ARCH_TRY(q_up.declare(b, nm, g, nm.f("blk.%d.attn_q_up", l), kQDim, kQLora,
|
||||
RAD_SHARD_NONE, wg,
|
||||
{ nm.ckpt("%s.linear_q_up_proj.weight", ckpt_attn) },
|
||||
w.c_q, w.q_raw));
|
||||
op_q_norm_p = rw(b,
|
||||
RAD_OP(b, "rmsnorm_p",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T * kHeads), RAD_INT("n", kHeadDim),
|
||||
RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.q_raw }, { w.q });
|
||||
op_q_rope = rw(b, decl_hca_rope(b, c, T, kHeads, 0), { w.q }, { w.q });
|
||||
if (!op_q_norm || !op_q_norm_p || !op_q_rope) return RAD_E_INVAL;
|
||||
|
||||
/* 2. Raw KV path: kv_proj -> kv_layernorm -> YaRN RoPE -> raw RAD_KV_WINDOW. */
|
||||
RAD_ARCH_TRY(kv_proj.declare(b, nm, g, nm.f("blk.%d.attn_kv", l), kHeadDim, kEmbd,
|
||||
RAD_SHARD_NONE, wg,
|
||||
{ nm.ckpt("%s.linear_kv_proj.weight", ckpt_attn) },
|
||||
w.in, w.kv_tmp));
|
||||
const char* kv_norm_nm = nm.f("blk.%d.attn_kv_norm.weight", l);
|
||||
RAD_ARCH_TRY(map_copy(b, kv_norm_nm, nm.ckpt("%s.kv_layernorm.weight", ckpt_attn)));
|
||||
w_kv_norm = decl_w(b, kv_norm_nm, RAD_F32, { kHeadDim }, RAD_ACCESS_PER_TOKEN,
|
||||
RAD_SHARD_NONE, wg);
|
||||
if (!w_kv_norm) return RAD_E_INVAL;
|
||||
op_kv_norm = rw(b,
|
||||
RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", kHeadDim),
|
||||
RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_kv_norm)),
|
||||
{ w.kv_tmp }, { w.k_raw });
|
||||
op_k_rope = rw(b, decl_hca_rope(b, c, T, 1, 0), { w.k_raw }, { w.k_raw });
|
||||
if (!op_kv_norm || !op_k_rope) return RAD_E_INVAL;
|
||||
|
||||
if (!out_caches->raw) {
|
||||
RadKVGroupDecl d{};
|
||||
d.kind = RAD_KV_WINDOW;
|
||||
d.dtype = RAD_BF16;
|
||||
d.n_head_kv = 1;
|
||||
d.head_dim = kHeadDim / 2; /* row 512 = 2 * 256 */
|
||||
d.window = c.window;
|
||||
out_caches->raw = rad_decl_kv_group(b, nm.f("kv_hca_raw"), &d);
|
||||
if (!out_caches->raw) return RAD_E_INVAL;
|
||||
if (rep_kv) RAD_ARCH_TRY(rad_kv_group_replicated(b, out_caches->raw));
|
||||
}
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, out_caches->raw));
|
||||
op_kv_store = rw(b,
|
||||
RAD_OP(b, "kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", kHeadDim / 2),
|
||||
RAD_INT("n_head_kv", 1), RAD_INT("block_size", kRawBlock),
|
||||
RAD_STR("kv_dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.k_raw }, {});
|
||||
if (!op_kv_store || rad_kv_block_size(b, out_caches->raw) != kRawBlock)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
/* 3. Compressor: bf16 [wkv | wgate] -> state ring -> hca_compress -> comp KV. */
|
||||
if (c.ratio > 0) {
|
||||
Geom bg = g;
|
||||
bg.w_bf16 = true;
|
||||
const char* cproj_nm = nm.f("blk.%d.attn_comp_proj.weight", l);
|
||||
RAD_ARCH_TRY(map_concat(b, cproj_nm,
|
||||
{ nm.ckpt("%s.core_attention.compressor.linear_wkv.weight",
|
||||
ckpt_attn),
|
||||
nm.ckpt("%s.core_attention.compressor.linear_wgate.weight",
|
||||
ckpt_attn) }));
|
||||
comp_proj.mapped = true;
|
||||
RAD_ARCH_TRY(comp_proj.declare(
|
||||
b, nm, bg, nm.f("blk.%d.attn_comp_proj", l), 2 * kHeadDim, kEmbd, RAD_SHARD_NONE,
|
||||
wg,
|
||||
{ nm.ckpt("%s.core_attention.compressor.linear_wkv.weight", ckpt_attn),
|
||||
nm.ckpt("%s.core_attention.compressor.linear_wgate.weight", ckpt_attn) },
|
||||
w.in, w.comp_kg));
|
||||
|
||||
if (!out_caches->state) {
|
||||
RadKVGroupDecl d{};
|
||||
d.kind = RAD_KV_LINEAR;
|
||||
d.dtype = RAD_BF16;
|
||||
d.n_head_kv = 1;
|
||||
d.state_dim[0] = ring_cap;
|
||||
d.state_dim[1] = 2 * kHeadDim;
|
||||
out_caches->state = rad_decl_kv_group(b, nm.f("kv_hca_state"), &d);
|
||||
if (!out_caches->state) return RAD_E_INVAL;
|
||||
}
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, out_caches->state));
|
||||
|
||||
const char* ape_nm = nm.f("blk.%d.attn_comp_ape.weight", l);
|
||||
const char* cnorm_nm = nm.f("blk.%d.attn_comp_norm.weight", l);
|
||||
RAD_ARCH_TRY(map_copy(b, ape_nm,
|
||||
nm.ckpt("%s.core_attention.compressor.ape", ckpt_attn)));
|
||||
RAD_ARCH_TRY(map_copy(b, cnorm_nm,
|
||||
nm.ckpt("%s.core_attention.compressor.norm.weight", ckpt_attn)));
|
||||
w_ape = decl_w(b, ape_nm, RAD_F32, { c.ratio, kHeadDim }, RAD_ACCESS_PER_TOKEN,
|
||||
RAD_SHARD_NONE, wg);
|
||||
w_comp_norm = decl_w(b, cnorm_nm, RAD_F32, { kHeadDim }, RAD_ACCESS_PER_TOKEN,
|
||||
RAD_SHARD_NONE, wg);
|
||||
if (!w_ape || !w_comp_norm) return RAD_E_INVAL;
|
||||
|
||||
op_work = rw(b,
|
||||
RAD_OP(b, "qsa_work",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", 2 * kHeadDim),
|
||||
RAD_INT("ratio", c.ratio), RAD_INT("ring", ring_cap),
|
||||
RAD_INT("seqs", g.max_seqs), RAD_INT("work", max_work),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.comp_kg }, { w.stage, w.page, w.bpos, w.nc });
|
||||
|
||||
if (!out_caches->comp) {
|
||||
RadKVGroupDecl d{};
|
||||
d.kind = RAD_KV_FULL;
|
||||
d.dtype = RAD_BF16;
|
||||
d.n_head_kv = 1;
|
||||
d.head_dim = 2; /* row 4 * block 128 = 512 elements per page */
|
||||
out_caches->comp = rad_decl_kv_group(b, nm.f("kv_hca_comp"), &d);
|
||||
if (!out_caches->comp) return RAD_E_INVAL;
|
||||
RAD_ARCH_TRY(rad_kv_group_dense_read(b, out_caches->comp));
|
||||
if (rep_kv) RAD_ARCH_TRY(rad_kv_group_replicated(b, out_caches->comp));
|
||||
}
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, out_caches->comp));
|
||||
|
||||
std::vector<RadParam> cp = {
|
||||
RAD_RANGE("M", 1, max_work), RAD_INT("n", kHeadDim),
|
||||
RAD_INT("ratio", c.ratio), RAD_INT("rotary_dim", kRopeDim),
|
||||
RAD_INT("rotary_offset", kRopeOff), RAD_INT("block_size", c.ratio),
|
||||
RAD_F64("eps", g.eps), RAD_F64("theta", c.theta),
|
||||
RAD_F64("scale", 1.0), RAD_STR("dtype", "bf16"),
|
||||
};
|
||||
if (c.yarn) {
|
||||
double lo = 0.0, hi = 0.0;
|
||||
yarn_bounds(c.theta, &lo, &hi);
|
||||
cp.push_back(RAD_F64("yarn_factor", 16.0));
|
||||
cp.push_back(RAD_F64("yarn_low", lo));
|
||||
cp.push_back(RAD_F64("yarn_high", hi));
|
||||
cp.push_back(RAD_F64("yarn_magnitude", 1.0));
|
||||
}
|
||||
op_comp = rw(b, rad_decl_op(b, "hca_compress", cp.data(), (int)cp.size(),
|
||||
RAD_WEIGHTS(w_ape, w_comp_norm)),
|
||||
{ w.stage, w.page, w.bpos }, {});
|
||||
if (!op_comp || rad_kv_block_size(b, out_caches->comp) != c.ratio)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
op_tail = rw(b,
|
||||
RAD_OP(b, "qsa_tail_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", 2 * kHeadDim),
|
||||
RAD_INT("ratio", c.ratio), RAD_INT("ring", ring_cap),
|
||||
RAD_INT("seqs", g.max_seqs), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.comp_kg }, {});
|
||||
if (!op_work || !op_tail) return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* 4. HCA attention + inverse RoPE + VHA postmix. */
|
||||
const char* sink_nm = nm.f("blk.%d.attn_sink.weight", l);
|
||||
RAD_ARCH_TRY(map_copy(b, sink_nm, nm.ckpt("%s.core_attention.attn_sink", ckpt_attn)));
|
||||
w_sink = decl_w(b, sink_nm, RAD_F32, { kHeads }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, wg);
|
||||
const char* u_nm = nm.f("blk.%d.attn_vha_u.weight", l);
|
||||
const char* v_nm = nm.f("blk.%d.attn_vha_v.weight", l);
|
||||
RAD_ARCH_TRY(map_copy(b, u_nm, nm.ckpt("%s.vha_postmix_U", ckpt_attn)));
|
||||
RAD_ARCH_TRY(map_copy(b, v_nm, nm.ckpt("%s.vha_postmix_V", ckpt_attn)));
|
||||
w_u = decl_w(b, u_nm, RAD_BF16, { kHeads, kVhaRank }, RAD_ACCESS_PER_TOKEN,
|
||||
RAD_SHARD_NONE, wg);
|
||||
w_v = decl_w(b, v_nm, RAD_BF16, { kHeads, kVhaRank }, RAD_ACCESS_PER_TOKEN,
|
||||
RAD_SHARD_NONE, wg);
|
||||
if (!w_sink || !w_u || !w_v) return RAD_E_INVAL;
|
||||
|
||||
if (c.ratio > 0) {
|
||||
op_attn = rw(b,
|
||||
RAD_OP(b, "hca_attn",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("heads", kHeads),
|
||||
RAD_INT("latent_dim", kHeadDim),
|
||||
RAD_INT("ratio", c.ratio), RAD_INT("window", c.window),
|
||||
RAD_INT("block_size", kRawBlock),
|
||||
RAD_F64("scale", 1.0 / std::sqrt((double)kHeadDim)),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_sink)),
|
||||
{ w.q }, { w.attn_out });
|
||||
} else if (c.block) {
|
||||
/* Every row of a block sees the window behind the block's first row and the whole
|
||||
* block (`anchor`), with no compressed entries (`ratio` 0). */
|
||||
op_attn = rw(b,
|
||||
RAD_OP(b, "hca_attn",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("heads", kHeads),
|
||||
RAD_INT("latent_dim", kHeadDim), RAD_INT("ratio", 0),
|
||||
RAD_INT("window", c.window),
|
||||
RAD_INT("block_size", kRawBlock),
|
||||
RAD_F64("scale", 1.0 / std::sqrt((double)kHeadDim)),
|
||||
RAD_STR("dtype", "bf16"), RAD_INT("anchor", 1)),
|
||||
RAD_WEIGHTS(w_sink)),
|
||||
{ w.q }, { w.attn_out });
|
||||
} else {
|
||||
op_attn = rw(b,
|
||||
RAD_OP(b, "attn_paged_sink",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", kHeadDim),
|
||||
RAD_INT("gqa", kHeads), RAD_INT("causal", 1),
|
||||
RAD_STR("dtype", "bf16"),
|
||||
RAD_F64("scale", 1.0 / std::sqrt((double)kHeadDim)),
|
||||
RAD_INT("window", c.window)),
|
||||
RAD_WEIGHTS(w_sink)),
|
||||
{ w.q }, { w.attn_out });
|
||||
}
|
||||
op_o_rope = rw(b, decl_hca_rope(b, c, T, kHeads, 1), { w.attn_out }, { w.attn_out });
|
||||
op_vha = rw(b,
|
||||
RAD_OP(b, "vha_postmix",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("heads", kHeads),
|
||||
RAD_INT("head_dim", kHeadDim), RAD_INT("rank", kVhaRank),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_u, w_v)),
|
||||
{ w.attn_out }, { w.o_mix });
|
||||
if (!op_attn || !op_o_rope || !op_vha) return RAD_E_INVAL;
|
||||
|
||||
/* 5. Output gate + 8-group wo_a (IQ8R, or 4-group per rank when attn_world < world) * sigmoid + o_proj. */
|
||||
const int out_shard_row = out_sharded ? RAD_SHARD_ROW : RAD_SHARD_NONE;
|
||||
const int out_shard_col = out_sharded ? RAD_SHARD_COL : RAD_SHARD_NONE;
|
||||
const int64_t odim_lo = out_sharded ? (int64_t)g.attn_rank * local_odim : 0;
|
||||
const int64_t odim_hi = out_sharded ? odim_lo + local_odim : 0;
|
||||
RAD_ARCH_TRY(gate_proj.declare(b, nm, g, nm.f("blk.%d.attn_gate", l), local_odim, kQLora,
|
||||
out_shard_row, wg,
|
||||
{ nm.ckpt("%s.gate_proj.weight", ckpt_attn) },
|
||||
w.c_q, w.gate, 0, {}, odim_lo, odim_hi));
|
||||
|
||||
const char* wo_src = nm.ckpt("%s.linear_o_group_proj", ckpt_attn); /* no .weight */
|
||||
const bool wo_i8 = w.o_mix_act.q8_fed;
|
||||
for (int i = 0; i < og_count; ++i) {
|
||||
const int gi = og_base + i;
|
||||
op_wo_q[i] = rw(b,
|
||||
wo_i8 ? RAD_OP(b, "had_quant_act_i8g",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", kOGroupIn),
|
||||
RAD_INT("group", w.o_mix_act.g8),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS)
|
||||
: RAD_OP(b, "quant_act_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", kOGroupIn),
|
||||
RAD_INT("group", w.o_mix_act.group),
|
||||
RAD_STR("dtype", "bf16"),
|
||||
RAD_INT("ue8m0", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.o_mix }, { w.o_mix_act.cq(), w.o_mix_act.cs() });
|
||||
const char* wnm = nm.f("blk.%d.attn_wo_a.%d.weight", l, gi);
|
||||
RAD_ARCH_TRY(map_rows(b, wnm, { { wo_src, (int)(gi * kOGroupOut), (int)kOGroupOut } }));
|
||||
wo_a[i].mapped = true;
|
||||
RAD_ARCH_TRY(wo_a[i].declare(b, nm, g, nm.f("blk.%d.attn_wo_a.%d", l, gi),
|
||||
kOGroupOut, kOGroupIn, RAD_SHARD_NONE, wg, { wo_src },
|
||||
w.o_mix_act, w.wo_tmp));
|
||||
/* A bf16 wo_a is declared (rad-convert plans a conversion from bf16 weights through
|
||||
* this declare) but not served: its group slices are not a bf16 GEMM's input. */
|
||||
wo_bf16 = wo_a[i].bf16;
|
||||
if ((!wo_a[i].bf16 && wo_a[i].i8 != wo_i8) || wo_a[i].w4 || wo_a[i].iqr || wo_a[i].ggml)
|
||||
return RAD_E_DTYPE;
|
||||
op_act_mul[i] = rw(b,
|
||||
RAD_OP(b, "act_mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", kOGroupOut),
|
||||
RAD_STR("act", "sigmoid"),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.gate, w.wo_tmp }, { w.gated.x });
|
||||
if (!op_wo_q[i] || !op_act_mul[i]) return RAD_E_INVAL;
|
||||
}
|
||||
RAD_ARCH_TRY(gated_quant.declare(b, g, w.gated, local_odim));
|
||||
RAD_ARCH_TRY(o_proj.declare(b, nm, g, nm.f("blk.%d.attn_output", l), kEmbd, local_odim,
|
||||
out_shard_col, wg,
|
||||
{ nm.ckpt("%s.o_proj.weight", ckpt_attn) },
|
||||
w.gated, w.out, 0, {}, odim_lo, odim_hi));
|
||||
|
||||
caches = *out_caches;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The raw KV path alone over Wire::in's rows: kv_proj -> kv_layernorm -> RoPE at the batch's
|
||||
* positions -> the raw group's store. step() runs it between the query path and the
|
||||
* attention; a block drafter's context pass runs it over the features it projected into
|
||||
* Wire::in. */
|
||||
void store_kv(RadCtx* ctx, const RadBatch* batch) const {
|
||||
if (attn_zero || !ctx || !batch || batch->n_tok < 1) return;
|
||||
const int64_t T = batch->n_tok;
|
||||
const auto* rawb = kv_batch(batch, caches.raw);
|
||||
if (!rawb || !rawb->slot_mapping || !batch->positions) {
|
||||
rad_step_fail(ctx, "ernie_hca: missing raw KV batch or positions");
|
||||
return;
|
||||
}
|
||||
kv_proj.step(ctx, w.in, w.kv_tmp, T);
|
||||
RAD_ISSUE_N(ctx, op_kv_norm, T, brows(w.kv_tmp, T), RAD_W(w_kv_norm), brows(w.k_raw, T));
|
||||
RAD_ISSUE_N(ctx, op_k_rope, T, brows(w.k_raw, T), rope_pos1(batch, T));
|
||||
RAD_ISSUE_N(ctx, op_kv_store, T,
|
||||
bcol(w.k_raw, 0, kHeadDim / 2, T),
|
||||
bcol(w.k_raw, kHeadDim / 2, kHeadDim / 2, T),
|
||||
praw(rawb->slot_mapping, RAD_I32, T),
|
||||
kv_cache(caches.raw, layer));
|
||||
}
|
||||
|
||||
void step(RadCtx* ctx, const RadBatch* batch) const {
|
||||
if (attn_zero || !ctx || !batch || batch->n_tok < 1) return;
|
||||
const int64_t T = batch->n_tok;
|
||||
const int64_t S = batch->n_seq;
|
||||
const auto* rawb = kv_batch(batch, caches.raw);
|
||||
if (!rawb || !rawb->slot_mapping || !rawb->block_table || !batch->positions ||
|
||||
!batch->cu_seqlens) {
|
||||
rad_step_fail(ctx, "ernie_hca: missing raw KV batch or sequence bounds");
|
||||
return;
|
||||
}
|
||||
if (c.ratio > 0 && !caches.state) {
|
||||
rad_step_fail(ctx, "ernie_hca: missing compressor state cache");
|
||||
return;
|
||||
}
|
||||
|
||||
/* Query projection + norm + RoPE */
|
||||
q_down.step(ctx, w.in, w.q_a_raw, T);
|
||||
RAD_ISSUE_N(ctx, op_q_norm, T, brows(w.q_a_raw, T), RAD_W(w_q_norm), brows(w.c_q.x, T));
|
||||
q_quant.step(ctx, T);
|
||||
q_up.step(ctx, w.c_q, w.q_raw, T);
|
||||
RAD_ISSUE_N(ctx, op_q_norm_p, T * kHeads, brows(w.q_raw, T), brows(w.q, T));
|
||||
RAD_ISSUE_N(ctx, op_q_rope, T, brows(w.q, T), rope_pos1(batch, T));
|
||||
|
||||
/* Raw KV projection + norm + RoPE + raw window store */
|
||||
store_kv(ctx, batch);
|
||||
|
||||
/* Compressor + HCA attention */
|
||||
if (c.ratio > 0) {
|
||||
const auto* compb = kv_batch(batch, caches.comp);
|
||||
const auto* st = kv_batch(batch, caches.state);
|
||||
if (!compb || !st || !compb->block_table || !st->state_index) {
|
||||
rad_step_fail(ctx, "ernie_hca: missing comp or state KV batch");
|
||||
return;
|
||||
}
|
||||
const int64_t work = std::max<int64_t>(1, std::min(max_work, T / c.ratio + S));
|
||||
const int64_t s_pitch = st->state_index_pitch > 0 ? st->state_index_pitch : 1;
|
||||
|
||||
comp_proj.step(ctx, w.in, w.comp_kg, T);
|
||||
RAD_ISSUE_N(ctx, op_work, T,
|
||||
brows(w.comp_kg, T),
|
||||
praw(batch->positions, RAD_I32, T),
|
||||
praw(batch->cu_seqlens, RAD_I32, S + 1),
|
||||
kv_cache(caches.state, layer),
|
||||
praw2(st->state_index, RAD_I32, S, s_pitch),
|
||||
praw2(compb->block_table, RAD_I32, S, compb->block_table_pitch),
|
||||
RAD_NONE,
|
||||
brows(w.stage, work * c.ratio),
|
||||
brows(w.page, work),
|
||||
brows(w.bpos, work),
|
||||
brows(w.nc, S));
|
||||
RAD_ISSUE_N(ctx, op_comp, work,
|
||||
brows(w.stage, work * c.ratio),
|
||||
RAD_W(w_ape),
|
||||
RAD_W(w_comp_norm),
|
||||
brows(w.page, work),
|
||||
brows(w.bpos, work),
|
||||
kv_cache(caches.comp, layer));
|
||||
|
||||
/* Store tail AFTER hca_compress so speculative rollback preserves state. */
|
||||
if (S == 1 && batch->ckpt_cut > 0 && batch->ckpt_cut < T && batch->ckpt_cu) {
|
||||
const int64_t ck = batch->ckpt_cut;
|
||||
for (int p = 0; p < 2; ++p) {
|
||||
RAD_ISSUE_N(ctx, op_tail, p == 0 ? ck : T - ck,
|
||||
brows(w.comp_kg, T),
|
||||
praw(batch->positions, RAD_I32, T),
|
||||
praw(batch->ckpt_cu + p, RAD_I32, 2),
|
||||
kv_cache(caches.state, layer),
|
||||
praw2(st->state_index, RAD_I32, S, s_pitch));
|
||||
if (p == 0) rad_ckpt_snap(ctx, caches.state, layer);
|
||||
}
|
||||
} else {
|
||||
RAD_ISSUE_N(ctx, op_tail, T,
|
||||
brows(w.comp_kg, T),
|
||||
praw(batch->positions, RAD_I32, T),
|
||||
praw(batch->cu_seqlens, RAD_I32, S + 1),
|
||||
kv_cache(caches.state, layer),
|
||||
praw2(st->state_index, RAD_I32, S, s_pitch));
|
||||
}
|
||||
|
||||
RAD_ISSUE_N(ctx, op_attn, T,
|
||||
brows(w.q, T),
|
||||
kv_cache(caches.comp, layer),
|
||||
praw2(compb->block_table, RAD_I32, S, compb->block_table_pitch),
|
||||
kv_cache(caches.raw, layer),
|
||||
praw2(rawb->block_table, RAD_I32, S, rawb->block_table_pitch),
|
||||
rawb->seqused ? praw(rawb->seqused, RAD_I32, S) : RAD_NONE,
|
||||
praw(batch->positions, RAD_I32, T),
|
||||
praw(batch->cu_seqlens, RAD_I32, S + 1),
|
||||
RAD_W(w_sink),
|
||||
brows(w.attn_out, T));
|
||||
} else if (c.block) {
|
||||
/* The block's own K and V are stored past the context; the window group's seqused
|
||||
* rebases its table (hca_attn's raw_used). */
|
||||
if (!rawb->seqused) {
|
||||
rad_step_fail(ctx, "ernie_hca: a drafter block stage requires the window's seqused");
|
||||
return;
|
||||
}
|
||||
RAD_ISSUE_N(ctx, op_attn, T,
|
||||
brows(w.q, T),
|
||||
RAD_NONE, RAD_NONE,
|
||||
kv_cache(caches.raw, layer),
|
||||
praw2(rawb->block_table, RAD_I32, S, rawb->block_table_pitch),
|
||||
praw(rawb->seqused, RAD_I32, S),
|
||||
praw(batch->positions, RAD_I32, T),
|
||||
praw(batch->cu_seqlens, RAD_I32, S + 1),
|
||||
RAD_W(w_sink),
|
||||
brows(w.attn_out, T));
|
||||
} else {
|
||||
if (!rawb->seqused) {
|
||||
rad_step_fail(ctx, "ernie_hca: SWA mode requires raw seqused");
|
||||
return;
|
||||
}
|
||||
RAD_ISSUE_N(ctx, op_attn, T,
|
||||
brows(w.q, T),
|
||||
kv_cache(caches.raw, layer),
|
||||
praw2(rawb->block_table, RAD_I32, S, rawb->block_table_pitch),
|
||||
praw(rawb->seqused, RAD_I32, S),
|
||||
RAD_NONE, RAD_NONE,
|
||||
praw(batch->cu_seqlens, RAD_I32, S + 1),
|
||||
RAD_W(w_sink),
|
||||
brows(w.attn_out, T));
|
||||
}
|
||||
|
||||
/* Inverse RoPE -> VHA postmix -> gate -> 8x wo_a * sigmoid -> o_proj */
|
||||
RAD_ISSUE_N(ctx, op_o_rope, T, brows(w.attn_out, T), rope_pos1(batch, T));
|
||||
RAD_ISSUE_N(ctx, op_vha, T, brows(w.attn_out, T), RAD_W(w_u), RAD_W(w_v),
|
||||
brows(w.o_mix, T));
|
||||
gate_proj.step(ctx, w.c_q, w.gate, T);
|
||||
if (wo_bf16) {
|
||||
rad_step_fail(ctx, "ernie_hca: wo_a is stored bf16; this plugin serves it block fp8 or IQ8R");
|
||||
return;
|
||||
}
|
||||
const int64_t wg = w.o_mix_act.cg();
|
||||
/* Group i's rows start at i * T: the buffer holds groups * (the arena level's max_tok)
|
||||
* rows, so the offset follows this step's rows, never the declared max_tok. */
|
||||
const int64_t T0 = T;
|
||||
for (int i = 0; i < og_count; ++i) {
|
||||
RAD_ISSUE_N(ctx, op_wo_q[i], T,
|
||||
bcol(w.o_mix, (int64_t)(og_base + i) * kOGroupIn, kOGroupIn, T),
|
||||
brow_slice(w.o_mix_act.cq(), i * T0, T, kOGroupIn),
|
||||
brow_slice(w.o_mix_act.cs(), i * T0, T, kOGroupIn / wg));
|
||||
RAD_ISSUE_N(ctx, wo_a[i].op, T,
|
||||
brow_slice(w.o_mix_act.cq(), i * T0, T, kOGroupIn),
|
||||
brow_slice(w.o_mix_act.cs(), i * T0, T, kOGroupIn / wg),
|
||||
RAD_W(wo_a[i].w), RAD_W(wo_a[i].ws), brows(w.wo_tmp, T),
|
||||
RAD_NONE, RAD_NONE);
|
||||
RAD_ISSUE_N(ctx, op_act_mul[i], T,
|
||||
bcol(w.gate, (int64_t)i * kOGroupOut, kOGroupOut, T),
|
||||
brows(w.wo_tmp, T),
|
||||
bcol(w.gated.x, (int64_t)i * kOGroupOut, kOGroupOut, T));
|
||||
}
|
||||
gated_quant.step(ctx, T);
|
||||
o_proj.step(ctx, w.gated, w.out, T);
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace arch
|
||||
} // namespace rad
|
||||
#endif
|
||||
@@ -0,0 +1,481 @@
|
||||
/* rad_block_ernie_moe.h -- ERNIE-5.5-Flash's feed-forward blocks: layer 0's dense SiTU MLP and the
|
||||
* latent MoE of layers 1..42.
|
||||
*
|
||||
* ErnieDense act -> gate_up (IQ8R) -> situ_mul -> had_quant_act_i8g (256) -> down (IQ8R) -> out
|
||||
*
|
||||
* ErnieMoe act.x -> gemm_nt_f32 [gate | gate_1] -> router_ernie_topk -> ids, ew
|
||||
* act -> shared gate_up (IQ8R) -> situ_mul -> had_quant_act_i8g -> down -> sout
|
||||
* act -> fc1_latent (IQ8R) -> z -> quant 32/ue8m0 (MXFP8)
|
||||
* -> MoeQ (scatter, MXFP4 gate_up a_group 32, situ_mul, quant 32/ue8m0,
|
||||
* MXFP4 down a_group 32, gather; all_reduce when Config::reduce)
|
||||
* -> latent_norm rmsnorm -> had_quant_act_i8g (256) -> fc2_latent (IQ8R) -> out
|
||||
* out += sout
|
||||
*
|
||||
* ============================== FORMATS ==============================
|
||||
*
|
||||
* Every trunk linear is IQ8R (rotated int8 codes with a u8 scale per 256 of K under a bf16 row
|
||||
* scale, read by `gemm_nt_q` at `i8a8h`, group 256 against `had_quant_act_i8g` codes); the routed
|
||||
* experts stay byte-exact OCP MXFP4 (E2M1 codes, one E8M0 per 32 of K) read by `moe_gemm_q` at
|
||||
* `mxfp4a8` against per-32 E4M3 activations under E8M0 scales (`a_group` 32 on both GEMMs).
|
||||
*
|
||||
* ============================== PARALLELISM ==============================
|
||||
*
|
||||
* The trunk (dense MLP, shared expert, router, fc1, latent_norm, fc2) is replicated: every rank
|
||||
* holds every weight whole and computes every token. The routed experts are expert parallel, whole
|
||||
* experts [expert_base, expert_base + n_expert) a rank: the replicated router picks from all 512,
|
||||
* the scatter drops the slots outside the window, and each rank's gather is the partial latent sum
|
||||
* of its experts. With Config::reduce that 2048-wide partial is all-reduced over the world before
|
||||
* latent_norm, the layer's only collective.
|
||||
*
|
||||
* The window is in router labels. With Config::order a layer's labels are a permutation of the
|
||||
* model's experts: the router's rows, bias and scale are loaded in label order, so a rank's window
|
||||
* of labels may hold any experts (the plugin's hot-first split puts each layer's hottest on the
|
||||
* attention-free rank). The selection breaks exact ties to the lower label, which under a
|
||||
* permutation is not always the lower model expert.
|
||||
*
|
||||
* ============================== NAMES ==============================
|
||||
*
|
||||
* blk.L.ffn_gate_up / ffn_down the dense MLP (layer 0), gate rows first
|
||||
* blk.L.ernie_router.{weight,correction,scale} [gate.weight | gate.weight_1], bias, scale
|
||||
* blk.L.ffn_gate_up_shexp / ffn_down_shexp the shared expert (w1 | w3, w2)
|
||||
* blk.L.ffn_latent_in / ffn_latent_out fc1_latent_proj / fc2_latent_proj
|
||||
* blk.L.ffn_latent_norm.weight latent_norm
|
||||
* blk.L.ffn_{gate_up,down}_exps.E.{weight,scale} routed expert E (w1 | w3, w2) in model numbering
|
||||
*/
|
||||
#ifndef RAD_BLOCK_ERNIE_MOE_H
|
||||
#define RAD_BLOCK_ERNIE_MOE_H
|
||||
|
||||
#include "rad_linear.h"
|
||||
#include "rad_block_moe_q.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
/* The released geometry; the plugin refuses any other checkpoint by name. */
|
||||
struct ErnieFfnShape {
|
||||
static constexpr int64_t kEmbd = 4096, kDenseFF = 14336, kSharedFF = 2048, kLatent = 2048,
|
||||
kExpertFF = 2048, kExperts = 512, kTopK = 10;
|
||||
static constexpr double kSituBeta = 4.0, kSituLinearBeta = 25.0;
|
||||
/* The routed experts' activation group (MXFP8) and the trunk's IQ8R group. */
|
||||
static constexpr int64_t kExpertGroup = RAD_MX_GROUP, kTrunkGroup = RAD_I8_GROUP_WIDE;
|
||||
};
|
||||
|
||||
/* One SiTU-GLU over an IQ8R trunk activation: gate_up (gate rows first) into `gu`, situ_mul into
|
||||
* `ff.x`, down quantises `ff.x` with had_quant_act_i8g at g.i8_group into `ff.{q8,s8}` and writes
|
||||
* `out`. The dense MLP and the shared expert. */
|
||||
struct ErnieGlu {
|
||||
LinearQ gate_up{}, down{};
|
||||
GateQuant act{};
|
||||
ActQ in{}, ff{};
|
||||
rad_buf gu = 0, out = 0;
|
||||
int64_t n_ff = 0;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& g, int layer, const char* gate_up_base,
|
||||
const char* down_base, const char* src_gate, const char* src_up,
|
||||
const char* src_down, int64_t width, const ActQ& input, rad_buf gate_up_out,
|
||||
const ActQ& inter, rad_buf output, int shard_row = RAD_SHARD_NONE,
|
||||
int shard_col = RAD_SHARD_NONE, int64_t span_off = 0, int64_t full_width = 0) {
|
||||
in = input;
|
||||
ff = inter;
|
||||
gu = gate_up_out;
|
||||
out = output;
|
||||
n_ff = width;
|
||||
if (!in.x || !in.cq() || !in.cs() || !gu || !ff.x ||
|
||||
(g.i8_group ? !(ff.q8 && ff.s8) : !(ff.q && ff.s)) || !out || n_ff <= 0)
|
||||
return RAD_E_INVAL;
|
||||
const RadWeightGroup grp = grp_layer(layer);
|
||||
if (shard_row != RAD_SHARD_NONE) {
|
||||
RAD_ARCH_TRY(gate_up.declare(b, nm, g, gate_up_base, 2 * n_ff, g.n_embd, shard_row,
|
||||
grp, { src_gate, src_up }, in, gu, 0, { n_ff, n_ff }));
|
||||
const int64_t lo[2] = { span_off, span_off };
|
||||
const int64_t hi[2] = { span_off + n_ff, span_off + n_ff };
|
||||
const int64_t tot[2] = { full_width, full_width };
|
||||
RAD_ARCH_TRY(gate_up.span_parts(b, lo, hi, tot, 2));
|
||||
} else {
|
||||
RAD_ARCH_TRY(gate_up.declare(b, nm, g, gate_up_base, 2 * n_ff, g.n_embd, RAD_SHARD_NONE,
|
||||
grp, { src_gate, src_up }, in, gu, 0, { n_ff, n_ff }));
|
||||
}
|
||||
act.silu_only = g.i8_group != 0;
|
||||
act.situ_beta = ErnieFfnShape::kSituBeta;
|
||||
act.situ_linear_beta = ErnieFfnShape::kSituLinearBeta;
|
||||
RAD_ARCH_TRY(act.declare(b, g, gu, ff, n_ff, "situ"));
|
||||
const int64_t d_hi = shard_col != RAD_SHARD_NONE ? span_off + n_ff : 0;
|
||||
return down.declare(b, nm, g, down_base, g.n_embd, n_ff, shard_col, grp, { src_down },
|
||||
ff, out, 0, {}, span_off, d_hi);
|
||||
}
|
||||
void step(RadCtx* c, int64_t T) const {
|
||||
gate_up.step(c, in, gu, T);
|
||||
act.step(c, gu, T);
|
||||
down.step(c, ff, out, T);
|
||||
}
|
||||
};
|
||||
|
||||
/* The block input every ERNIE feed-forward reads: the post-attention norm's bf16 row and its
|
||||
* rotated int8 codes at group 256, written by the plugin. */
|
||||
inline int ernie_check_input(const Geom& g, const ActQ& in, rad_buf out, const char* what) {
|
||||
const bool iq8r_ok = g.i8_group == ErnieFfnShape::kTrunkGroup;
|
||||
const bool fp8_ok = !g.i8_group && g.native_fp;
|
||||
if (g.n_embd != ErnieFfnShape::kEmbd || g.w_bf16 || (!iq8r_ok && !fp8_ok)) {
|
||||
fprintf(stderr, "radiance: %s is ERNIE-5.5-Flash's (n_embd %lld, IQ8R group-%lld or "
|
||||
"block-FP8 linears); this geometry has n_embd %lld, i8_group %lld%s\n",
|
||||
what, (long long)ErnieFfnShape::kEmbd, (long long)ErnieFfnShape::kTrunkGroup,
|
||||
(long long)g.n_embd, (long long)g.i8_group,
|
||||
g.w_bf16 ? " and bf16 linears" : "");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const bool pair_ok = iq8r_ok
|
||||
? (in.q8 && in.s8 && in.q8_fed && in.q8_rot && in.g8 == ErnieFfnShape::kTrunkGroup)
|
||||
: (in.q && in.s && !in.q8_fed && in.group == RAD_SCALE_GROUP);
|
||||
if (!in.x || !pair_ok || !out) {
|
||||
fprintf(stderr, "radiance: %s reads the normed input's bf16 row and its %s codes (Wire::in), "
|
||||
"and writes Wire::out; the wire lacks them\n",
|
||||
what, iq8r_ok ? "rotated int8 group-256" : "ue8m0 E4M3 group-128");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ================================================================== layer 0: the dense MLP */
|
||||
struct ErnieDense {
|
||||
struct Wire {
|
||||
ActQ in{}; /* [max_tok, 4096] bf16 + rotated i8 group-256 codes, set by caller */
|
||||
rad_buf out = 0; /* [max_tok, 4096] bf16, set by caller */
|
||||
rad_buf gu = 0; /* [max_tok, 28672] bf16, gate | up */
|
||||
ActQ ff{}; /* [max_tok, 14336] bf16 SiTU product + i8 group-256 scratch for down */
|
||||
};
|
||||
|
||||
Geom g{};
|
||||
Wire w{};
|
||||
int layer = 0;
|
||||
ErnieGlu glu{};
|
||||
|
||||
/* Declares the scratch (gu, ff) once; `in` and `out` are the caller's and left as they are. */
|
||||
static int declare_wire(RadBuilder* b, Names& nm, const Geom& g, Wire* w) {
|
||||
if (!b || !w) return RAD_E_INVAL;
|
||||
const int aw = g.attn_world > 0 && g.attn_world < g.world ? g.attn_world : g.world;
|
||||
const bool sharded = !g.attn_zero && aw > 1 && aw < g.world;
|
||||
const int64_t T = g.max_tok;
|
||||
const int64_t F = sharded ? ErnieFfnShape::kDenseFF / aw : ErnieFfnShape::kDenseFF;
|
||||
w->gu = decl_b(b, nm.f("ernie_dense.gate_up"), RAD_BF16, { T, 2 * F });
|
||||
w->ff.x = decl_b(b, nm.f("ernie_dense.ff"), RAD_BF16, { T, F });
|
||||
if (!w->gu || !w->ff.x) return RAD_E_INVAL;
|
||||
return w->ff.declare_trunk_self(b, nm, g, "ernie_dense.ff", F);
|
||||
}
|
||||
|
||||
/* `ckpt_mlp`: "model.layers.0.mlp". */
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
|
||||
const char* ckpt_mlp) {
|
||||
g = geom;
|
||||
w = wire;
|
||||
layer = l;
|
||||
if (!b || !ckpt_mlp) return RAD_E_INVAL;
|
||||
if (g.attn_zero) return RAD_OK;
|
||||
RAD_ARCH_TRY(ernie_check_input(g, w.in, w.out, "the dense SiTU MLP"));
|
||||
const int aw = g.attn_world > 0 && g.attn_world < g.world ? g.attn_world : g.world;
|
||||
const bool sharded = aw > 1 && aw < g.world;
|
||||
if (sharded && ErnieFfnShape::kDenseFF % aw != 0) return RAD_E_UNSUPPORTED;
|
||||
const int64_t F = sharded ? ErnieFfnShape::kDenseFF / aw : ErnieFfnShape::kDenseFF;
|
||||
const int64_t off = sharded ? (int64_t)g.attn_rank * F : 0;
|
||||
return glu.declare(b, nm, g, l, nm.f("blk.%d.ffn_gate_up", l), nm.f("blk.%d.ffn_down", l),
|
||||
nm.ckpt("%s.gate_proj.weight", ckpt_mlp),
|
||||
nm.ckpt("%s.up_proj.weight", ckpt_mlp),
|
||||
nm.ckpt("%s.down_proj.weight", ckpt_mlp), F,
|
||||
w.in, w.gu, w.ff, w.out,
|
||||
sharded ? RAD_SHARD_ROW : RAD_SHARD_NONE,
|
||||
sharded ? RAD_SHARD_COL : RAD_SHARD_NONE,
|
||||
off, ErnieFfnShape::kDenseFF);
|
||||
}
|
||||
|
||||
/* act.in -> out, overwriting out. */
|
||||
void step(RadCtx* c, const RadBatch* batch) const {
|
||||
if (!g.attn_zero) glu.step(c, batch->n_tok);
|
||||
}
|
||||
};
|
||||
|
||||
/* ================================================================== layers 1..42: the latent MoE */
|
||||
struct ErnieMoe {
|
||||
struct Config {
|
||||
/* This rank's whole experts [expert_base, expert_base + n_expert) of the model's 512. */
|
||||
int64_t n_expert = 512, expert_base = 0;
|
||||
/* All-reduce the routed experts' latent partial sum over the world before latent_norm. */
|
||||
bool reduce = false;
|
||||
/* Tokens per routed pass (MoeQ::Config::rows); 0 is the whole step. The expert planes
|
||||
* are rows * 10 tall. */
|
||||
int64_t rows = 0;
|
||||
/* Relabelled experts, per layer: (*order)[layer][j] is the model's expert behind router
|
||||
* label j, a permutation of the 512. The router's rows (both halves), its correction
|
||||
* bias and its scale are read in that order (rad_weight_row_order), so label j scores
|
||||
* exactly as model expert order[j] does, and this rank's window
|
||||
* [expert_base, expert_base + n_expert) of labels holds the experts named there. That lets
|
||||
* an expert-parallel split give a rank any set of experts, not only an index range.
|
||||
* Null, or an empty row for a layer: labels are the model's numbering. */
|
||||
const std::vector<std::vector<int32_t>>* order = nullptr;
|
||||
};
|
||||
struct Wire {
|
||||
ActQ in{}; /* [max_tok, 4096] bf16 + rotated i8 group-256 codes, set by caller */
|
||||
rad_buf out = 0; /* [max_tok, 4096] bf16, set by caller */
|
||||
rad_buf logits = 0; /* [max_tok, 1024] f32, the two routers' logits side by side */
|
||||
rad_buf sgu = 0; /* [max_tok, 4096] bf16, the shared expert's w1 | w3 */
|
||||
ActQ sff{}; /* [max_tok, 2048] its SiTU product + i8 group-256 scratch for down */
|
||||
rad_buf sout = 0; /* [max_tok, 4096] bf16, the shared expert's output */
|
||||
/* fc1's output z with its per-32 E8M0-scaled E4M3 codes (MXFP8); then (MoeQ's gather) the
|
||||
* routed latent sum, all-reduced in place with Config::reduce. */
|
||||
ActQ lat{}; /* [max_tok, 2048] */
|
||||
ActQ ln{}; /* [max_tok, 2048] latent_norm's output, rotated i8 group-256 */
|
||||
/* The routed arm's planes (ids, f32 ew, eoff, ecnt, sorted, egu, eff at group 32, edn);
|
||||
* its `h` is `lat`, set at declare. */
|
||||
MoeQ::Wire moe{};
|
||||
};
|
||||
|
||||
Geom g{};
|
||||
Config cfg{};
|
||||
Wire w{};
|
||||
int layer = 0;
|
||||
rad_weight w_router = 0, w_bias = 0, w_scale = 0, w_lnorm = 0;
|
||||
rad_op op_router = 0, op_topk = 0, op_lnorm = 0, op_add = 0;
|
||||
ErnieGlu shared{};
|
||||
LinearQ fc1{}, fc2{};
|
||||
QuantAct lat_q{}, ln_q{};
|
||||
MoeQ moe{};
|
||||
|
||||
static int64_t pass_rows(const Geom& g, const Config& c) {
|
||||
return c.rows > 0 && c.rows < g.max_tok ? c.rows : g.max_tok;
|
||||
}
|
||||
|
||||
static int check_config(const Config& c) {
|
||||
const int64_t ne = c.n_expert;
|
||||
if (ne < 2 || ne % 2 || c.expert_base < 0 || c.expert_base + ne > ErnieFfnShape::kExperts ||
|
||||
c.rows < 0) {
|
||||
fprintf(stderr, "radiance: ERNIE's routed experts are taken as whole experts, an even "
|
||||
"count a rank inside the model's %lld; asked for [%lld, %lld)\n",
|
||||
(long long)ErnieFfnShape::kExperts, (long long)c.expert_base,
|
||||
(long long)(c.expert_base + ne));
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Declares the scratch once, for every MoE layer; `in` and `out` are the caller's and left as
|
||||
* they are. */
|
||||
static int declare_wire(RadBuilder* b, Names& nm, const Geom& g, const Config& c, Wire* w) {
|
||||
if (!b || !w) return RAD_E_INVAL;
|
||||
RAD_ARCH_TRY(check_config(c));
|
||||
using S = ErnieFfnShape;
|
||||
const int64_t T = g.max_tok, slots = pass_rows(g, c) * S::kTopK, ne = c.n_expert;
|
||||
w->logits = decl_b(b, nm.f("ernie_moe.logits"), RAD_F32, { T, 2 * S::kExperts });
|
||||
w->sgu = decl_b(b, nm.f("ernie_moe.shared_gate_up"), RAD_BF16, { T, 2 * S::kSharedFF });
|
||||
w->sff.x = decl_b(b, nm.f("ernie_moe.shared_ff"), RAD_BF16, { T, S::kSharedFF });
|
||||
w->sout = decl_b(b, nm.f("ernie_moe.shared_out"), RAD_BF16, { T, S::kEmbd });
|
||||
w->lat.x = decl_b(b, nm.f("ernie_moe.latent"), RAD_BF16, { T, S::kLatent });
|
||||
w->ln.x = decl_b(b, nm.f("ernie_moe.latent_norm"), RAD_BF16, { T, S::kLatent });
|
||||
if (!w->logits || !w->sgu || !w->sff.x || !w->sout || !w->lat.x || !w->ln.x)
|
||||
return RAD_E_INVAL;
|
||||
/* The routed arm's latent codes stay MXFP8 (per-32 ue8m0 E4M3) for the MXFP4 experts. */
|
||||
w->lat.group = S::kExpertGroup;
|
||||
w->lat.ue8m0 = true;
|
||||
RAD_ARCH_TRY(w->sff.declare_trunk_self(b, nm, g, "ernie_moe.shared_ff", S::kSharedFF));
|
||||
RAD_ARCH_TRY(w->lat.declare_qs(b, nm, g, "ernie_moe.latent", S::kLatent));
|
||||
RAD_ARCH_TRY(w->ln.declare_trunk(b, nm, g, "ernie_moe.latent_norm", S::kLatent));
|
||||
|
||||
MoeQ::Wire& m = w->moe;
|
||||
m = MoeQ::Wire{};
|
||||
m.ids = decl_b(b, nm.f("ernie_moe.ids"), RAD_I32, { T, S::kTopK });
|
||||
m.ew = decl_b(b, nm.f("ernie_moe.ew"), RAD_F32, { T, S::kTopK });
|
||||
m.eoff = decl_b(b, nm.f("ernie_moe.eoff"), RAD_I32, { ne + 1 });
|
||||
m.ecnt = decl_b(b, nm.f("ernie_moe.ecnt"), RAD_I32, { ne }, RAD_BUF_PERSIST);
|
||||
m.sorted = decl_b(b, nm.f("ernie_moe.sorted"), RAD_I32, { slots });
|
||||
m.egu = decl_b(b, nm.f("ernie_moe.egu"), RAD_BF16, { slots, 2 * S::kExpertFF });
|
||||
m.eff.x = decl_b(b, nm.f("ernie_moe.eff"), RAD_BF16, { slots, S::kExpertFF });
|
||||
m.edn = decl_b(b, nm.f("ernie_moe.edn"), RAD_BF16, { slots, S::kLatent });
|
||||
if (!m.ids || !m.ew || !m.eoff || !m.ecnt || !m.sorted || !m.egu || !m.eff.x || !m.edn)
|
||||
return RAD_E_INVAL;
|
||||
m.eff.group = S::kExpertGroup;
|
||||
m.eff.ue8m0 = true;
|
||||
return m.eff.declare_qs(b, nm, g, "ernie_moe.eff", S::kExpertFF, slots);
|
||||
}
|
||||
|
||||
/* `ckpt_moe`: "model.layers.L.block_sparse_moe". */
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Config& config,
|
||||
const Wire& wire, const char* ckpt_moe) {
|
||||
using S = ErnieFfnShape;
|
||||
g = geom;
|
||||
cfg = config;
|
||||
w = wire;
|
||||
layer = l;
|
||||
if (!b || !ckpt_moe) return RAD_E_INVAL;
|
||||
RAD_ARCH_TRY(ernie_check_input(g, w.in, w.out, "the latent MoE"));
|
||||
RAD_ARCH_TRY(check_config(cfg));
|
||||
if (!w.logits || !w.sgu || !w.sout || !w.lat.x || !w.lat.q || !w.lat.s ||
|
||||
w.lat.group != S::kExpertGroup || !w.ln.x || !w.ln.cq() || !w.ln.cs() ||
|
||||
w.ln.cg() != (g.i8_group ? S::kTrunkGroup : (int64_t)RAD_SCALE_GROUP) ||
|
||||
!w.moe.ids || !w.moe.ew) {
|
||||
fprintf(stderr, "radiance: layer %d: the latent MoE's scratch is ErnieMoe::declare_wire's; "
|
||||
"declare it before the layers\n", l);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const RadWeightGroup grp = grp_layer(l);
|
||||
const char* pre = ckpt_moe;
|
||||
const int32_t* ord = nullptr;
|
||||
if (cfg.order && l >= 0 && (size_t)l < cfg.order->size() &&
|
||||
!(*cfg.order)[(size_t)l].empty()) {
|
||||
if ((int64_t)(*cfg.order)[(size_t)l].size() != S::kExperts) return RAD_E_INVAL;
|
||||
ord = (*cfg.order)[(size_t)l].data();
|
||||
}
|
||||
|
||||
/* ---- The split-feature router: both [512, 4096] bf16 projections as one [1024, 4096]
|
||||
* weight, f32 logits (a sigmoid each, summed, inside the selection), top 10 of
|
||||
* sum + correction bias, the unbiased sums renormalised then times the per-expert scale.
|
||||
* Replicated, so every rank routes alike and only the scatter knows the window. */
|
||||
{
|
||||
const char* rn = nm.f("blk.%d.ernie_router.weight", l);
|
||||
const char* cn = nm.f("blk.%d.ernie_router.correction", l);
|
||||
const char* sn = nm.f("blk.%d.ernie_router.scale", l);
|
||||
RAD_ARCH_TRY(map_concat(b, rn, { nm.ckpt("%s.gate.weight", pre),
|
||||
nm.ckpt("%s.gate.weight_1", pre) }));
|
||||
RAD_ARCH_TRY(map_copy(b, cn, nm.ckpt("%s.e_score_correction_bias", pre)));
|
||||
RAD_ARCH_TRY(map_copy(b, sn, nm.ckpt("%s.gate.routed_scaling_factor_param", pre)));
|
||||
w_router = decl_w(b, rn, RAD_BF16, { 2 * S::kExperts, S::kEmbd }, RAD_ACCESS_PER_TOKEN,
|
||||
RAD_SHARD_NONE, grp);
|
||||
w_bias = decl_w(b, cn, RAD_F32, { S::kExperts }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp);
|
||||
w_scale = decl_w(b, sn, RAD_F32, { S::kExperts }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp);
|
||||
if (!w_router || !w_bias || !w_scale) return RAD_E_INVAL;
|
||||
if (ord) {
|
||||
/* Label j is model expert ord[j] in both halves of the split-feature router. */
|
||||
std::vector<int32_t> rows((size_t)(2 * S::kExperts));
|
||||
for (int64_t j = 0; j < S::kExperts; ++j) {
|
||||
rows[(size_t)j] = ord[j];
|
||||
rows[(size_t)(S::kExperts + j)] = (int32_t)S::kExperts + ord[j];
|
||||
}
|
||||
RAD_ARCH_TRY(rad_weight_row_order(b, w_router, rows.data(), 2 * S::kExperts));
|
||||
RAD_ARCH_TRY(rad_weight_row_order(b, w_bias, ord, S::kExperts));
|
||||
RAD_ARCH_TRY(rad_weight_row_order(b, w_scale, ord, S::kExperts));
|
||||
}
|
||||
op_router = rw(b, RAD_OP(b, "gemm_nt_f32",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
|
||||
RAD_INT("N", 2 * S::kExperts),
|
||||
RAD_INT("K", S::kEmbd), RAD_STR("dtype", "bf16"),
|
||||
RAD_STR("w_dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_router)),
|
||||
{ w.in.x }, { w.logits });
|
||||
op_topk = rw(b, RAD_OP(b, "router_ernie_topk",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
|
||||
RAD_INT("n_expert", S::kExperts),
|
||||
RAD_INT("top_k", S::kTopK), RAD_INT("norm", 1),
|
||||
RAD_STR("dtype", "f32")),
|
||||
RAD_WEIGHTS(w_bias, w_scale)),
|
||||
{ w.logits }, { w.moe.ids, w.moe.ew });
|
||||
if (!op_router || !op_topk) return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* ---- The shared expert, ungated, on the unprojected 4096-wide input. */
|
||||
RAD_ARCH_TRY(shared.declare(b, nm, g, l, nm.f("blk.%d.ffn_gate_up_shexp", l),
|
||||
nm.f("blk.%d.ffn_down_shexp", l),
|
||||
nm.ckpt("%s.shared_experts.w1.weight", pre),
|
||||
nm.ckpt("%s.shared_experts.w3.weight", pre),
|
||||
nm.ckpt("%s.shared_experts.w2.weight", pre), S::kSharedFF,
|
||||
w.in, w.sgu, w.sff, w.sout));
|
||||
|
||||
/* ---- fc1 into the latent, and its MXFP8 codes for the routed gate_up. */
|
||||
RAD_ARCH_TRY(fc1.declare(b, nm, g, nm.f("blk.%d.ffn_latent_in", l), S::kLatent, S::kEmbd,
|
||||
RAD_SHARD_NONE, grp,
|
||||
{ nm.ckpt("%s.fc1_latent_proj.weight", pre) }, w.in, w.lat.x));
|
||||
RAD_ARCH_TRY(lat_q.declare(b, g, w.lat, S::kLatent));
|
||||
|
||||
/* ---- The routed experts over the latent. */
|
||||
MoeQ::Src ms{};
|
||||
ms.experts = nm.ckpt("%s.experts", pre);
|
||||
ms.expert_gate = "w1";
|
||||
ms.expert_up = "w3";
|
||||
ms.expert_down = "w2";
|
||||
MoeQ::Config& mc = ms.cfg;
|
||||
mc.n_expert = cfg.n_expert;
|
||||
mc.n_expert_all = S::kExperts;
|
||||
mc.expert_base = cfg.expert_base;
|
||||
mc.top_k = S::kTopK;
|
||||
mc.n_ff_exp = S::kExpertFF;
|
||||
mc.ext_router = 1;
|
||||
mc.situ = 1;
|
||||
mc.allow_mxfp4 = 1;
|
||||
mc.no_reduce = cfg.reduce ? 0 : 1;
|
||||
mc.rows = pass_rows(g, cfg);
|
||||
mc.expert_ids = ord ? ord + cfg.expert_base : nullptr;
|
||||
mc.probed_expert = ord ? ord[cfg.expert_base] : cfg.expert_base;
|
||||
RAD_ARCH_TRY(MoeQ::probe(b, nm, l, ms, &mc));
|
||||
/* The release's experts are MXFP4. A builder with no model behind it (the probe reads no
|
||||
* encoding) declares them so; any other stored format is refused by name. */
|
||||
{
|
||||
RadEncoding e{};
|
||||
const char* pn = nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l,
|
||||
(long long)mc.probed_expert);
|
||||
const bool known = weight_enc(b, pn, &e);
|
||||
if (known && !linear_is_mxfp4(e)) {
|
||||
char en[256];
|
||||
rad_enc_format(&e, en, sizeof en);
|
||||
fprintf(stderr, "radiance: '%s' is %s; ERNIE-5.5's routed experts are served as the "
|
||||
"release stores them, OCP MXFP4 (fp4_e2m1*e8m0[1x32])\n", pn, en);
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
mc.expert_mx = 1;
|
||||
}
|
||||
Geom ge = g;
|
||||
ge.n_embd = S::kLatent;
|
||||
ge.n_ff_all = S::kExpertFF;
|
||||
MoeQ::Wire mw = w.moe;
|
||||
mw.h = w.lat;
|
||||
RAD_ARCH_TRY(moe.declare(b, nm, ge, l, mw, ms, false, false));
|
||||
|
||||
/* ---- latent_norm, its rotated int8 codes, fc2 back to 4096, plus the shared expert. */
|
||||
{
|
||||
const char* nn = nm.f("blk.%d.ffn_latent_norm.weight", l);
|
||||
RAD_ARCH_TRY(map_copy(b, nn, nm.ckpt("%s.latent_norm.weight", pre)));
|
||||
w_lnorm = decl_w(b, nn, RAD_F32, { S::kLatent }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp);
|
||||
if (!w_lnorm) return RAD_E_INVAL;
|
||||
op_lnorm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
|
||||
RAD_INT("n", S::kLatent), RAD_F64("eps", g.eps),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_lnorm)),
|
||||
{ w.lat.x }, { w.ln.x });
|
||||
if (!op_lnorm) return RAD_E_INVAL;
|
||||
}
|
||||
RAD_ARCH_TRY(ln_q.declare(b, g, w.ln, S::kLatent));
|
||||
RAD_ARCH_TRY(fc2.declare(b, nm, g, nm.f("blk.%d.ffn_latent_out", l), S::kEmbd, S::kLatent,
|
||||
RAD_SHARD_NONE, grp,
|
||||
{ nm.ckpt("%s.fc2_latent_proj.weight", pre) }, w.ln, w.out));
|
||||
op_add = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", S::kEmbd),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.out, w.sout }, { w.out });
|
||||
return op_add ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* act.in -> out, overwriting out. In declaration order. */
|
||||
void step(RadCtx* c, const RadBatch* batch) const {
|
||||
using S = ErnieFfnShape;
|
||||
const int64_t T = batch->n_tok;
|
||||
RAD_ISSUE_N(c, op_router, T, brows(w.in.x, T), RAD_W(w_router), brows(w.logits, T));
|
||||
RAD_ISSUE_N(c, op_topk, T, brows(w.logits, T), RAD_W(w_bias), RAD_W(w_scale),
|
||||
brows(w.moe.ids, T), brows(w.moe.ew, T));
|
||||
shared.step(c, T);
|
||||
fc1.step(c, w.in, w.lat.x, T);
|
||||
lat_q.step(c, T);
|
||||
moe.step(c, batch);
|
||||
RAD_ISSUE_N(c, op_lnorm, T, brows(w.lat.x, T), RAD_W(w_lnorm), brows(w.ln.x, T));
|
||||
ln_q.step(c, T);
|
||||
fc2.step(c, w.ln, w.out, T);
|
||||
RAD_ISSUE_N(c, op_add, T, brow_slice(w.out, 0, T, S::kEmbd),
|
||||
brow_slice(w.sout, 0, T, S::kEmbd), brow_slice(w.out, 0, T, S::kEmbd));
|
||||
}
|
||||
};
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_ERNIE_MOE_H */
|
||||
@@ -0,0 +1,154 @@
|
||||
/* rad_block_flux2_vae.h -- FLUX.2's VAE decoder as a block. arch/mossimage declares its decoder
|
||||
* through it; arch/flux3 declares the same steps inline (flux3.cpp), and could move onto it.
|
||||
*
|
||||
* `AutoencoderKLFlux2` (diffusers) is not a Wan-style VAE with a residual shortcut: its latent is
|
||||
* normalised by a BatchNorm's running statistics over the *packed* width (4 x latent_channels),
|
||||
* its decoder unpacks 2x2 to `latent_channels` and then runs ordinary GroupNorm residual blocks
|
||||
* with nearest-neighbour upsampling, and an optional 1x1 `post_quant_conv` sits in front of
|
||||
* `decoder.conv_in`. Both models in this tree that make pictures with it run the same four steps:
|
||||
*
|
||||
* 1. chan_stats `denorm` x = rd(rd(x std) + mean), std = sqrt(var + eps), over the packed rows
|
||||
* 2. fill + d2s_add the 2x2 unpack: latent channel 4*co + 2i + j -> pixel (2h+i, 2w+j)
|
||||
* 3. the block graph post_quant_conv, conv_in, the mid block (two resnets around an
|
||||
* attention), four up blocks of `layers_per_block + 1` resnets with an
|
||||
* upsampler between them, conv_norm_out + silu, conv_out
|
||||
* 4. to_rgba8 -1..1 bf16 -> 0..255 u8 rows
|
||||
*
|
||||
* The declared liveness is the caller's: it hands in its own state/preview buffers and gets the
|
||||
* ops back, so the Vae's own op list holds only what the decoder issues.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_FLUX2_VAE_H
|
||||
#define RAD_BLOCK_FLUX2_VAE_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
#include "rad_vae2d.h"
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
/* The denormalisation and the unpack, declared against the caller's latent state buffers. `NT` is
|
||||
* the largest latent token count, `C` the packed width (4 x latent_channels), `zc` the VAE's own
|
||||
* latent channel count, and `cu` a 2-row i32 that `cu_repeat` fills with {0, 4 * pixels}. */
|
||||
struct Flux2VaeIn {
|
||||
rad_weight w_mean = 0, w_std = 0;
|
||||
rad_op op_bn = 0, op_zero = 0, op_unpack = 0, op_cu4 = 0;
|
||||
};
|
||||
|
||||
inline int flux2_vae_declare_in(RadBuilder* b, Names& nm, Flux2VaeIn* in, int64_t NT, int64_t C,
|
||||
int64_t zc, double bn_eps, rad_buf state, rad_buf preview,
|
||||
rad_buf* b_dl, rad_buf* b_din, rad_buf* b_cu) {
|
||||
*b_dl = decl_b(b, nm.f("vdec.lat"), RAD_BF16, { NT, C });
|
||||
*b_din = decl_b(b, nm.f("vdec.in"), RAD_BF16, { 4 * NT, zc });
|
||||
*b_cu = decl_b(b, nm.f("vdec.cu"), RAD_I32, { 2 });
|
||||
if (map_copy(b, nm.f("vae.bn.mean"), nm.ckpt("vae.bn.running_mean")) < 0) return RAD_E_INVAL;
|
||||
in->w_mean = decl_w(b, nm.f("vae.bn.mean"), RAD_BF16, { C }, RAD_ACCESS_PER_REQUEST,
|
||||
RAD_SHARD_NONE, grp_layer(-1));
|
||||
if (map_copy(b, nm.f("vae.bn.var"), nm.ckpt("vae.bn.running_var")) < 0) return RAD_E_INVAL;
|
||||
in->w_std = decl_w(b, nm.f("vae.bn.var"), RAD_BF16, { C }, RAD_ACCESS_PER_REQUEST,
|
||||
RAD_SHARD_NONE, grp_layer(-1));
|
||||
in->op_bn = rw(b, RAD_OP(b, "chan_stats",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, NT), RAD_INT("n", C),
|
||||
RAD_STR("mode", "denorm"), RAD_INT("var", 1),
|
||||
RAD_F64("eps", bn_eps), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(in->w_mean, in->w_std)),
|
||||
{ state, preview }, { *b_dl });
|
||||
in->op_zero = rw(b, RAD_OP(b, "fill",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, 4 * NT), RAD_INT("n", zc),
|
||||
RAD_STR("dtype", "bf16"), RAD_F64("value", 0.0)),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, { *b_din });
|
||||
in->op_unpack = rw(b, RAD_OP(b, "d2s_add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, 4 * NT), RAD_INT("cin", C),
|
||||
RAD_INT("cout", zc), RAD_INT("ft", 1),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ *b_dl, *b_din }, { *b_din });
|
||||
in->op_cu4 = rw(b, RAD_OP(b, "cu_repeat", RAD_PARAMS(RAD_RANGE("M", 1, 2), RAD_INT("mult", 4)),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, { *b_cu });
|
||||
return in->op_bn && in->op_zero && in->op_unpack && in->op_cu4 ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* Steps 1-2 and `cu_repeat`; the caller issues `to_rgba8` itself. `lane_row` is the lane's
|
||||
* first latent row in `src` (the state or the preview), `h`/`w` the latent grid, `cu` the
|
||||
* batch's {0, pixels}, which the caller issues as `cu_repeat` rather than writing. */
|
||||
inline void flux2_vae_issue_in(RadCtx* c, const Flux2VaeIn& in, rad_buf dl, rad_buf din,
|
||||
rad_buf cu4, rad_buf src, int64_t lane_row, int64_t h, int64_t w,
|
||||
int64_t C, int64_t zc, const RadOperand& pixel_cu) {
|
||||
const int64_t n = h * w, H0 = 2 * h, W0 = 2 * w;
|
||||
RAD_ISSUE_N(c, in.op_bn, n, brow_slice(src, lane_row, n, C), RAD_W(in.w_mean),
|
||||
RAD_W(in.w_std), brows(dl, n));
|
||||
RAD_ISSUE_N(c, in.op_zero, H0 * W0, brows(din, H0 * W0));
|
||||
RAD_ISSUE_N(c, in.op_unpack, H0 * W0, RAD_P_T2(rad_buf_ptr(c, dl), RAD_BF16, h, w * C),
|
||||
RAD_P_T2(rad_buf_ptr(c, din), RAD_BF16, H0, W0 * zc));
|
||||
RAD_ISSUE_N(c, in.op_cu4, 2, pixel_cu, brows(cu4, 2));
|
||||
}
|
||||
|
||||
/* Declares the block graph from `vae.post_quant_conv` on, into `v`, and returns the output image
|
||||
* (3 channels at level 0). `ch` is `vae.decoder_block_out_channels` (reversed for the up blocks),
|
||||
* `nres` `vae.layers_per_block`, `groups` `vae.norm_num_groups`, `zc` `vae.latent_channels`. */
|
||||
struct Flux2VaeDec {
|
||||
VImg out{};
|
||||
rad_op op_rgb = 0;
|
||||
rad_buf b_img = 0;
|
||||
};
|
||||
|
||||
inline int flux2_vae_declare_dec(RadBuilder* b, RadModelMeta const* meta, Names& nm, Vae& v,
|
||||
Flux2VaeDec* d, int64_t px, int64_t NT, int64_t zc,
|
||||
int64_t pixel_channels, const rad_buf* din, rad_buf cu,
|
||||
int first_group) {
|
||||
v.nm = &nm;
|
||||
v.b = b;
|
||||
v.scope = "vdec";
|
||||
v.down = false;
|
||||
v.first_group = first_group;
|
||||
v.base_px = NT * 4;
|
||||
std::vector<double> ch;
|
||||
{
|
||||
const char* s = rad_meta_gets(meta, "vae.decoder_block_out_channels", nullptr);
|
||||
while (s && *s) {
|
||||
char* e = nullptr;
|
||||
const double x = std::strtod(s, &e);
|
||||
if (e == s) { ++s; continue; }
|
||||
ch.push_back(x);
|
||||
s = e;
|
||||
}
|
||||
}
|
||||
if (ch.empty()) ch = { 128, 256, 512, 512 };
|
||||
const int64_t nres = rad_meta_geti(meta, "vae.layers_per_block", 2);
|
||||
const int64_t groups = rad_meta_geti(meta, "vae.norm_num_groups", 32);
|
||||
const double eps = 1e-6;
|
||||
const std::vector<double> rch(ch.rbegin(), ch.rend());
|
||||
VImg x{ *din, zc, 0 };
|
||||
if (rad_meta_geti(meta, "vae.use_post_quant_conv", 1))
|
||||
x = v.conv(x, zc, 1, 1, 1, "same", "vae.post_quant_conv");
|
||||
x = v.conv(x, (int64_t)rch[0], 3, 1, 1, "same", "vae.decoder.conv_in");
|
||||
x = v.resblock_gn(x, (int64_t)rch[0], "vae.decoder.mid_block.resnets.0", groups, eps);
|
||||
x = v.attention_gn(x, "vae.decoder.mid_block.attentions.0", groups, eps);
|
||||
x = v.resblock_gn(x, (int64_t)rch[0], "vae.decoder.mid_block.resnets.1", groups, eps);
|
||||
for (size_t i = 0; i < rch.size(); ++i) {
|
||||
for (int64_t r = 0; r < nres + 1; ++r)
|
||||
x = v.resblock_gn(x, (int64_t)rch[i],
|
||||
nm.f("vae.decoder.up_blocks.%d.resnets.%d", (int)i, (int)r), groups,
|
||||
eps);
|
||||
if (i + 1 < rch.size())
|
||||
x = v.conv(x, x.ch, 3, 1, 2, "same",
|
||||
nm.f("vae.decoder.up_blocks.%d.upsamplers.0.conv", (int)i));
|
||||
}
|
||||
x = v.gnorm(x, true, "vae.decoder.conv_norm_out", groups, eps);
|
||||
d->out = v.conv(x, pixel_channels, 3, 1, 1, "same", "vae.decoder.conv_out");
|
||||
if (!d->out.buf) return RAD_E_INVAL;
|
||||
RAD_ARCH_TRY(v.attn_reads(cu));
|
||||
d->b_img = decl_b(b, nm.f("image_out"), RAD_U8, { px * pixel_channels }, RAD_BUF_PERSIST);
|
||||
d->op_rgb = rw(b, RAD_OP(b, "to_rgba8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, px), RAD_INT("n", pixel_channels),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ d->out.buf }, { d->b_img });
|
||||
return d->op_rgb ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_FLUX2_VAE_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 */
|
||||
@@ -129,6 +129,13 @@ struct GdnFP8 {
|
||||
/* 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 beside the decode recurrent update on steps of up to
|
||||
* pf_out_rows rows and pf_out_seqs sequences. 0 where none is declared. */
|
||||
@@ -140,13 +147,13 @@ struct GdnFP8 {
|
||||
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,
|
||||
@@ -175,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_) {
|
||||
@@ -206,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;
|
||||
@@ -239,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,
|
||||
@@ -253,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). */
|
||||
@@ -334,9 +339,9 @@ 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
|
||||
/* 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 (ActFP8::q8_rot) only the conv fold writes (gdn_conv_recurrent_update_had);
|
||||
* 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() };
|
||||
@@ -347,10 +352,10 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
{
|
||||
const int64_t hi = g.max_tok < 8 ? g.max_tok : 8;
|
||||
/* The fold's rotated epilogue writes one scale per (row, 128), or per 256 for an IQ8R
|
||||
* trunk's codes (ActFP8::g8; `group`, stated to that form alone: last, and cut off
|
||||
* 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_FP8_BLOCK || cr_wide);
|
||||
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),
|
||||
@@ -368,35 +373,53 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
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),
|
||||
@@ -406,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);
|
||||
@@ -522,7 +545,22 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
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),
|
||||
@@ -646,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 */
|
||||
@@ -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 {
|
||||
@@ -318,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;
|
||||
@@ -332,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;
|
||||
};
|
||||
@@ -360,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),
|
||||
@@ -385,7 +375,7 @@ 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;
|
||||
};
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
|
||||
@@ -13,9 +13,20 @@ struct ManifoldConn {
|
||||
struct Config {
|
||||
int64_t hc = 4, iterations = 20;
|
||||
double eps = 1e-6, hc_eps = 1e-6;
|
||||
/* ERNIE-5.5 normalises the stream row by 1 / (sqrt(mean x^2) + eps), eps outside the root
|
||||
* (GLM: rsqrt(mean + eps)). Declared only when set, so GLM's graph keeps its params. */
|
||||
bool eps_outside = false;
|
||||
/* Split a prefill's projection over the ranks (declare_split). Off for a plugin whose
|
||||
* trunk is replicated with no collective (ernie55). */
|
||||
bool split = true;
|
||||
};
|
||||
struct Src {
|
||||
const char *fn = nullptr, *scale = nullptr, *base = nullptr;
|
||||
/* ERNIE-5.5's layout: `fn` is stored [hc * n, mix] (transposed), and the three scales are
|
||||
* separate one-element tensors (alpha_pre, alpha_post, alpha_res), concatenated in that
|
||||
* order into the [3] the op reads. `scale` is then unused. */
|
||||
bool fn_transposed = false;
|
||||
const char* scale_parts[3] = { nullptr, nullptr, nullptr };
|
||||
};
|
||||
struct Wire {
|
||||
rad_buf h = 0, x = 0, y = 0, out = 0;
|
||||
@@ -40,7 +51,9 @@ struct ManifoldConn {
|
||||
g = geom;
|
||||
c = cfg;
|
||||
w = wire;
|
||||
if (!b || !name || !src.fn || !src.scale || !src.base || g.n_embd < 1 || g.max_tok < 1 ||
|
||||
const bool parts = src.scale_parts[0] && src.scale_parts[1] && src.scale_parts[2];
|
||||
if (!b || !name || !src.fn || !(src.scale || parts) || !src.base || g.n_embd < 1 ||
|
||||
g.max_tok < 1 ||
|
||||
c.hc < 2 || c.hc > 8 || c.iterations < 1 || c.iterations > 256 ||
|
||||
!std::isfinite(c.eps) || !std::isfinite(c.hc_eps) || c.eps <= 0 || c.hc_eps < 0 ||
|
||||
!w.h || !w.x || !w.y || !w.out || !w.post || !w.comb || w.h == w.out || w.h == w.x ||
|
||||
@@ -49,8 +62,10 @@ struct ManifoldConn {
|
||||
const int64_t width = c.hc * g.n_embd, mix = c.hc * (c.hc + 2);
|
||||
const char *fn = nm.f("%s.fn", name), *scale = nm.f("%s.scale", name),
|
||||
*base = nm.f("%s.base", name);
|
||||
RAD_ARCH_TRY(map_copy(b, fn, src.fn));
|
||||
RAD_ARCH_TRY(map_copy(b, scale, src.scale));
|
||||
RAD_ARCH_TRY(src.fn_transposed ? map_transpose(b, fn, src.fn) : map_copy(b, fn, src.fn));
|
||||
RAD_ARCH_TRY(parts ? map_concat(b, scale, { src.scale_parts[0], src.scale_parts[1],
|
||||
src.scale_parts[2] })
|
||||
: map_copy(b, scale, src.scale));
|
||||
RAD_ARCH_TRY(map_copy(b, base, src.base));
|
||||
// Mixing coefficients are F32 in the checkpoint; keep them replicated under TP.
|
||||
const rad_weight wf = w_fn = decl_w(b, fn, RAD_F32, { mix, width }, RAD_ACCESS_PER_TOKEN,
|
||||
@@ -60,14 +75,23 @@ struct ManifoldConn {
|
||||
const rad_weight wb = w_base = decl_w(b, base, RAD_F32, { mix }, RAD_ACCESS_PER_TOKEN,
|
||||
RAD_SHARD_NONE, grp_layer(layer));
|
||||
if (!wf || !ws || !wb) return RAD_E_INVAL;
|
||||
op_pre = rw(b,
|
||||
RAD_OP(b, "mhc_pre",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("hc", c.hc), RAD_INT("iterations", c.iterations),
|
||||
RAD_F64("eps", c.eps), RAD_F64("hc_eps", c.hc_eps),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(wf, ws, wb)),
|
||||
{ w.h }, { w.x, w.post, w.comb });
|
||||
op_pre = c.eps_outside
|
||||
? rw(b,
|
||||
RAD_OP(b, "mhc_pre",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("hc", c.hc), RAD_INT("iterations", c.iterations),
|
||||
RAD_F64("eps", c.eps), RAD_F64("hc_eps", c.hc_eps),
|
||||
RAD_INT("eps_outside", 1), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(wf, ws, wb)),
|
||||
{ w.h }, { w.x, w.post, w.comb })
|
||||
: rw(b,
|
||||
RAD_OP(b, "mhc_pre",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("hc", c.hc), RAD_INT("iterations", c.iterations),
|
||||
RAD_F64("eps", c.eps), RAD_F64("hc_eps", c.hc_eps),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(wf, ws, wb)),
|
||||
{ w.h }, { w.x, w.post, w.comb });
|
||||
if (!op_pre) return RAD_E_INVAL;
|
||||
RAD_ARCH_TRY(declare_split(b, nm, name));
|
||||
return defer_post ? RAD_OK : declare_post(b);
|
||||
@@ -75,7 +99,7 @@ struct ManifoldConn {
|
||||
int declare_split(RadBuilder* b, Names& nm, const char* name) {
|
||||
const int64_t total = c.hc * g.n_embd / kChunk;
|
||||
split_rows = GlmTp::kSplitRows;
|
||||
if (g.world < 2 || g.n_embd != 4096 || c.hc != 4 || total % g.world) {
|
||||
if (!c.split || g.world < 2 || g.n_embd != 4096 || c.hc != 4 || total % g.world) {
|
||||
split_rows = 0;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
* 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>
|
||||
@@ -29,8 +29,8 @@ struct MlaLatent {
|
||||
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, or fp8_e4m3 under --kv-cache-dtype fp8); `kv_dtype` is stated only for a cache that is
|
||||
* not bf16, so a bf16 build declares the op it always did. */
|
||||
* (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"))
|
||||
@@ -123,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{};
|
||||
@@ -140,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,
|
||||
|
||||
@@ -190,12 +190,7 @@ private:
|
||||
{ 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", width),
|
||||
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,6 @@
|
||||
/* GLM noaux_tc router. Correction bias changes selection only; mixture weights
|
||||
* come from the uncorrected sigmoid probabilities. All routing arithmetic is F32. With `groups`
|
||||
* 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
|
||||
@@ -13,9 +14,17 @@ struct GlmRouter {
|
||||
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;
|
||||
@@ -23,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,
|
||||
@@ -54,7 +63,17 @@ 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));
|
||||
if (c.groups > 1)
|
||||
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",
|
||||
@@ -73,8 +92,37 @@ struct GlmRouter {
|
||||
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,
|
||||
|
||||
+46
-30
@@ -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 {
|
||||
@@ -78,11 +78,11 @@ struct HyperConn {
|
||||
* input buffer, so this saves a launch. */
|
||||
int reduce = 0;
|
||||
/* Whether the read also emits Hadamard-rotated codes of the block input, for a consumer
|
||||
* whose weight carries the rotation (MoeFP8's rotated expert plane). Produced in the
|
||||
* 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 take the same dtype (had_quant_act_i8g's beside int8,
|
||||
* (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
|
||||
@@ -94,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 */
|
||||
@@ -116,7 +116,7 @@ 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 (ActFP8::q8_rot, a trunk stored rotated):
|
||||
/* 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;
|
||||
@@ -211,14 +211,14 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
|
||||
}
|
||||
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 (ActFP8::q8_rot), and every reader of the block input -- the trunk's
|
||||
* 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 "
|
||||
"(ActFP8::q8_rot), so there is no second rotated pair to ask for\n", name);
|
||||
"(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)) {
|
||||
@@ -278,8 +278,8 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
|
||||
if (c.inject) wr[n_wr++] = w.inj;
|
||||
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, fp8_blocks(g.n_embd) });
|
||||
if (!pq || !ps || w.x.g8 != RAD_FP8_BLOCK) return RAD_E_INVAL;
|
||||
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 {
|
||||
@@ -294,7 +294,7 @@ 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("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);
|
||||
@@ -397,11 +397,11 @@ inline void HyperConn::read(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) con
|
||||
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,
|
||||
fp8_blocks(g.n_embd)) : RAD_NONE,
|
||||
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,
|
||||
fp8_blocks(g.n_embd)) : RAD_NONE);
|
||||
scale_groups(g.n_embd)) : RAD_NONE);
|
||||
}
|
||||
|
||||
/* ================================================================== the control-vector projection
|
||||
@@ -426,14 +426,17 @@ inline void HyperConn::read(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) con
|
||||
struct HcProject {
|
||||
rad_op op = 0; /* 0: this layer is not steered (or there is no vector) */
|
||||
const float* dir = nullptr; /* this layer's row of the device direction table */
|
||||
rad_buf on = 0; /* [rows] int32: 1 = project this row */
|
||||
rad_buf on = 0; /* [2, max_tok] int32: pass 1 + optional pass 2 per-row switches */
|
||||
rad_buf h = 0; /* the model's wide stream */
|
||||
int64_t n = 0, hc = 0;
|
||||
int64_t n = 0, hc = 0, max_tok = 0;
|
||||
|
||||
bool steered() const { return op != 0; }
|
||||
|
||||
/* The per-token switch, declared once per model as a derived buffer. 0 when the deployment has
|
||||
* no vector (or one of another width), which leaves every layer unsteered. */
|
||||
* no vector (or one of another width), which leaves every layer unsteered.
|
||||
* Two rows [2, max_tok] allow stacking a second control-vector slot per request (e.g. project
|
||||
* refusal followed by additive style) without changing kernels or ABI; when no request in the
|
||||
* step stacks a second vector, only row 0 is filled and only pass 1 is issued. */
|
||||
static rad_buf declare_mask(RadBuilder* b, const char* name, const Geom& g,
|
||||
const RadControlVector* cv) {
|
||||
if (!b || g.n_embd <= 0 || g.max_tok <= 0) return 0;
|
||||
@@ -446,8 +449,9 @@ struct HcProject {
|
||||
}
|
||||
RadBufDecl d{};
|
||||
d.dtype = RAD_I32;
|
||||
d.rank = 1;
|
||||
d.shape[0] = g.max_tok;
|
||||
d.rank = 2;
|
||||
d.shape[0] = 2;
|
||||
d.shape[1] = g.max_tok;
|
||||
d.kind = RAD_BUF_DERIVED;
|
||||
d.domain = RAD_DOMAIN_DEVICE;
|
||||
d.derive = "projection_on_rows";
|
||||
@@ -455,19 +459,22 @@ struct HcProject {
|
||||
}
|
||||
|
||||
/* `layer`'s projection, when the vector steers it. Called for every layer; the unsteered ones
|
||||
* (outside the file, outside the range, or no vector at all) declare nothing. */
|
||||
* (outside the file, outside the range, or no vector at all) declare nothing. `hc_streams` 1
|
||||
* is legal: the stream may be a plain bf16 residual (inkling2's) rather than a gated one,
|
||||
* and the kernel's per-stream loop is the identity at one stream. */
|
||||
int declare(RadBuilder* b, const char* name, const Geom& g, int64_t layer,
|
||||
const RadControlVector* cv, rad_buf mask, rad_buf stream, int64_t hc_streams) {
|
||||
if (!b || !mask || !stream || !cv || !cv->dir || hc_streams <= 1) return RAD_OK;
|
||||
if (!b || !mask || !stream || !cv || !cv->dir || hc_streams < 1) return RAD_OK;
|
||||
if (layer <= 0 || layer >= cv->n_layers || layer >= g.n_layer) return RAD_OK;
|
||||
const float scale = cv->scales ? cv->scales[(size_t) layer] : 0.0f;
|
||||
if (scale == 0.0f) return RAD_OK;
|
||||
|
||||
n = g.n_embd;
|
||||
hc = hc_streams;
|
||||
on = mask;
|
||||
h = stream;
|
||||
dir = cv->dir + (size_t) layer * (size_t) n;
|
||||
n = g.n_embd;
|
||||
hc = hc_streams;
|
||||
max_tok = g.max_tok;
|
||||
on = mask;
|
||||
h = stream;
|
||||
dir = cv->dir + (size_t) layer * (size_t) n;
|
||||
|
||||
op = rw(b, RAD_OP(b, "hc_project",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", n), RAD_INT("hc", hc),
|
||||
@@ -484,14 +491,23 @@ struct HcProject {
|
||||
}
|
||||
|
||||
/* Rows [r0, r0 + rows) of the stream. The whole step is r0 = 0; the pipelined step issues one
|
||||
* call per piece, in the same place in the graph. Nothing is issued on a pass where no row
|
||||
* takes the vector (RadBatch::control_vector): every row would be skipped. */
|
||||
* call per piece, in the same place in the graph. `RadBatch::control_vector` is a 2-bit mask:
|
||||
* bit 0 issues pass 1 (row 0 of `on`), bit 1 issues pass 2 (row 1 of `on`, at `max_tok`). */
|
||||
void step(RadCtx* c_, const RadBatch* batch, int64_t r0, int64_t rows) const {
|
||||
if (!op || !batch || !batch->control_vector) return;
|
||||
RAD_ISSUE_N(c_, op, rows,
|
||||
brow_slice(h, r0, rows, hc * n),
|
||||
praw(dir, RAD_F32, n),
|
||||
praw((const int32_t*) rad_buf_ptr(c_, on) + r0, RAD_I32, rows));
|
||||
const int32_t* mask = (const int32_t*) rad_buf_ptr(c_, on);
|
||||
if (batch->control_vector & 1) {
|
||||
RAD_ISSUE_N(c_, op, rows,
|
||||
brow_slice(h, r0, rows, hc * n),
|
||||
praw(dir, RAD_F32, n),
|
||||
praw(mask + r0, RAD_I32, rows));
|
||||
}
|
||||
if (batch->control_vector & 2) {
|
||||
RAD_ISSUE_N(c_, op, rows,
|
||||
brow_slice(h, r0, rows, hc * n),
|
||||
praw(dir, RAD_F32, n),
|
||||
praw(mask + max_tok + r0, RAD_I32, rows));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -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 */
|
||||
@@ -105,15 +105,18 @@ struct LiliCorr {
|
||||
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);
|
||||
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 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)
|
||||
@@ -230,11 +233,19 @@ inline int LiliCorr::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
|
||||
const int64_t sw = 2 + 2 * rk;
|
||||
|
||||
/* The candidates: this rank's shard of the target's logits, its logprob row, the exchange. */
|
||||
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 });
|
||||
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
|
||||
@@ -272,12 +283,7 @@ inline int LiliCorr::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
|
||||
RAD_WEIGHTS(w_tok)),
|
||||
{ w.cand }, { w.emb });
|
||||
if (g.world > 1)
|
||||
op_emb_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", E, lrows * E),
|
||||
RAD_STR("dtype", "bf16"), RAD_INT("exact", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.emb }, { w.emb });
|
||||
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) {
|
||||
|
||||
+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,13 +123,11 @@ 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), 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 (M2XFP4 included), and a clamped (swiglu_limit) product, take the pair. */
|
||||
/* 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 && !gate_up.row_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
|
||||
@@ -144,39 +142,18 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
|
||||
w.ffn.x }
|
||||
: std::initializer_list<rad_buf>{ w.ffn.q8, w.ffn.s8 },
|
||||
&gated_rows);
|
||||
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);
|
||||
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),
|
||||
@@ -192,26 +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) {
|
||||
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_FP8_BLOCK), RAD_W(gate_up.w),
|
||||
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_FP8_BLOCK),
|
||||
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);
|
||||
@@ -220,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)
|
||||
@@ -229,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);
|
||||
}
|
||||
@@ -237,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,12 +144,12 @@ 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
|
||||
@@ -160,7 +160,7 @@ struct MtpHcBlock {
|
||||
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;
|
||||
@@ -243,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),
|
||||
@@ -274,7 +269,8 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
{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_FP8_BLOCK), RAD_STR("dtype", "bf16")),
|
||||
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;
|
||||
@@ -293,11 +289,7 @@ 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. */
|
||||
@@ -328,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. */
|
||||
@@ -355,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
|
||||
@@ -384,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. */
|
||||
@@ -427,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);
|
||||
@@ -593,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,11 +86,11 @@
|
||||
* 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"
|
||||
|
||||
@@ -113,10 +113,10 @@ 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; }
|
||||
|
||||
@@ -147,7 +147,7 @@ struct MtpBlockFP8 {
|
||||
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{};
|
||||
};
|
||||
|
||||
@@ -156,7 +156,7 @@ struct MtpBlockFP8 {
|
||||
const char* norm = nullptr;
|
||||
const char* pre_norm_hidden = nullptr;
|
||||
const char* pre_norm_embedding = nullptr;
|
||||
AttnGatedFP8::Src attn{};
|
||||
AttnGatedQ::Src attn{};
|
||||
typename Ffn::Src mlp{};
|
||||
};
|
||||
|
||||
@@ -168,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
|
||||
@@ -191,7 +191,7 @@ 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) {
|
||||
@@ -254,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),
|
||||
@@ -292,11 +287,7 @@ inline int MtpBlockFP8<Ffn>::declare(RadBuilder* b, Names& nm, const Geom& geom,
|
||||
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});
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -371,12 +362,8 @@ inline int MtpBlockFP8<Ffn>::declare(RadBuilder* b, Names& nm, const Geom& geom,
|
||||
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_seqs),
|
||||
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_seqs),
|
||||
@@ -417,7 +404,7 @@ 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;
|
||||
@@ -495,7 +482,7 @@ inline void MtpBlockFP8<Ffn>::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);
|
||||
RAD_ISSUE_N(c, op_dtopk, L, brows(w.dlog, L), brows(w.didx, L), brows(w.dval, L),
|
||||
@@ -511,11 +498,11 @@ inline void MtpBlockFP8<Ffn>::step(RadCtx* c, const RadBatch* batch) const {
|
||||
}
|
||||
}
|
||||
|
||||
/* 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 */
|
||||
@@ -45,7 +45,7 @@
|
||||
*
|
||||
* ============================== PRECISION ==============================
|
||||
*
|
||||
* Block fp8 or OCP-MXFP4 weights (`DenseFP8`, whichever the recipe wrote), read against an E4M3
|
||||
* Block fp8 or OCP-MXFP4 weights (`DenseQ`, whichever the recipe wrote), read against an E4M3
|
||||
* activation quantised per row and 128 of K; the residual stream stays f32, which is what the
|
||||
* reference's autocast does and what keeps five stacked layers of 6656-wide adds from drifting.
|
||||
* The per-head q/k gains and both norms stay bf16.
|
||||
@@ -70,22 +70,12 @@
|
||||
#define RAD_BLOCK_MUSE_DFLASH_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
#include "rad_fp8.h" /* DenseFP8: the block fp8 / MXFP4 linear */
|
||||
#include "rad_linear.h" /* DenseQ: the block fp8 / MXFP4 linear */
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
/* The builder refuses a declaration it cannot serve and says why in its own words; this names which
|
||||
* handle did not come back, so that message reads against a line of this file. An op that resolves
|
||||
* to no kernel is recorded and handed back null -- it is only an error if the block issues it -- so
|
||||
* without this a missing kernel surfaces as a bare "invalid argument" at startup. */
|
||||
#define MD_REFUSED(...) ::rad::arch::muse_drafter_refused({ __VA_ARGS__ })
|
||||
inline int muse_drafter_refused(std::initializer_list<const char*> what) {
|
||||
std::string list;
|
||||
for (const char* w : what) { if (!list.empty()) list += ", "; list += w; }
|
||||
std::fprintf(stderr, "Muse Glimmer drafter: the builder gave no handle for %s\n", list.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
#define MD_REFUSED(...) ::rad::arch::declare_refused("Muse Glimmer drafter", { __VA_ARGS__ })
|
||||
|
||||
struct MuseDflash {
|
||||
enum { MAX_LAYERS = 8 };
|
||||
@@ -126,8 +116,8 @@ struct MuseDflash {
|
||||
|
||||
/* ---- fp8 codes and scales of the activations the linears read (`quant_act_fp8`), one
|
||||
* pair per activation rather than per linear: q, k and v all read the same `h`. The
|
||||
* scale plane is one f32 a 128-value block (`fp8_blocks`), which is the grid a
|
||||
* block-scaled fp8 GEMM reads (`DenseFP8`). */
|
||||
* scale plane is one f32 a 128-value block (`scale_groups`), which is the grid a
|
||||
* block-scaled fp8 GEMM reads (`DenseQ`). */
|
||||
rad_buf srcq = 0, srcs = 0; /* [max_tok, n_taps * n_embd] e4m3 | [.., /128] f32 */
|
||||
rad_buf cnq = 0, cns = 0; /* [max_tok, n_embd] the normed context, k/v's input */
|
||||
rad_buf hq = 0, hs = 0; /* [qrows, n_embd] the normed stream */
|
||||
@@ -156,20 +146,13 @@ struct MuseDflash {
|
||||
* whole block is staged and verified per sequence, so at several sequences its 13 extra rows
|
||||
* cost more than the drafts they add. */
|
||||
int64_t block_lo = 0;
|
||||
int64_t long_steps() const { return cfg.steps(); }
|
||||
int64_t qrows = 0, crows = 0, srows = 0;
|
||||
rad_kvgroup kv = 0;
|
||||
|
||||
/* ---- model-scope weights */
|
||||
DenseFP8 w_fc{}; /* block fp8 or MXFP4, per the recipe */
|
||||
DenseQ w_fc{}; /* block fp8 or MXFP4, per the recipe */
|
||||
rad_weight b_fc = 0; /* the same linear in bf16, when nothing quantised it */
|
||||
bool quant = false; /* the container's linears are quantised */
|
||||
/* Test switch: declare the column-split linears (o, down) replicated instead of split plus an
|
||||
* all_reduce, to tell a wrong reduce from a wrong split. */
|
||||
static constexpr bool kRepOut = false;
|
||||
/* Test switch: at a vocab-sharded head, all-gather the draft logits and take a plain argmax
|
||||
* instead of the top-2 pair walk. Same answer by construction, so a difference is the walk's. */
|
||||
static constexpr bool kGatherLogits = true;
|
||||
rad_weight 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) */
|
||||
@@ -178,10 +161,10 @@ struct MuseDflash {
|
||||
|
||||
/* ---- per-layer weights */
|
||||
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 b_q[MAX_LAYERS] = {}, b_k[MAX_LAYERS] = {}, b_v[MAX_LAYERS] = {}, b_o[MAX_LAYERS] = {};
|
||||
rad_weight w_qn[MAX_LAYERS] = {}, w_kn[MAX_LAYERS] = {}, w_gate[MAX_LAYERS] = {};
|
||||
DenseFP8 w_gu[MAX_LAYERS]{}, w_dn[MAX_LAYERS]{};
|
||||
DenseQ w_gu[MAX_LAYERS]{}, w_dn[MAX_LAYERS]{};
|
||||
rad_weight b_gu[MAX_LAYERS] = {}, b_dn[MAX_LAYERS] = {};
|
||||
|
||||
/* ---- the context pass */
|
||||
@@ -198,7 +181,7 @@ struct MuseDflash {
|
||||
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, op_widen3 = 0;
|
||||
rad_op op_widen2 = 0;
|
||||
rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn = 0;
|
||||
/* one activation quantiser an input */
|
||||
rad_op op_qsrc = 0, op_qcn = 0, op_qh = 0, op_qat = 0, op_qff = 0;
|
||||
@@ -278,9 +261,9 @@ inline int MuseDflash::declare(RadBuilder* b, Names& nm, const Geom& geom, const
|
||||
RAD_WEIGHTS(wt)),
|
||||
{x}, {y});
|
||||
};
|
||||
/* A linear over a quantised weight: DenseFP8 picks `fp8a8` or `mxfp4a8` from the container's
|
||||
/* A linear over a quantised weight: DenseQ picks `fp8a8` or `mxfp4a8` from the container's
|
||||
* encoding of that weight, and both read the same E4M3 activation pair. */
|
||||
auto qgemm = [&](int64_t rows, int64_t n, int64_t k, DenseFP8& wt,
|
||||
auto qgemm = [&](int64_t rows, int64_t n, int64_t k, DenseQ& wt,
|
||||
rad_buf xq, rad_buf xs, rad_buf y) {
|
||||
return wt.gemm(b, rows, n, k, {xq, xs}, {y});
|
||||
};
|
||||
@@ -289,7 +272,7 @@ inline int MuseDflash::declare(RadBuilder* b, Names& nm, const Geom& geom, const
|
||||
auto qact = [&](rad_buf x, rad_buf xq, rad_buf xs, int64_t rows, int64_t n) {
|
||||
return rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_INT("group", RAD_SCALE_GROUP),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{x}, {xq, xs});
|
||||
@@ -301,13 +284,13 @@ inline int MuseDflash::declare(RadBuilder* b, Names& nm, const Geom& geom, const
|
||||
RAD_ARCH_TRY(map_linear(b, wn, { nm.ckpt("%s.encoder.fc.weight", ck) }));
|
||||
RadEncoding enc{};
|
||||
/* `weight_enc` is true for a plain bf16 plane too, so ask which encoding: block fp8
|
||||
* (e4m3 codes, bf16 scale per 128x128), OCP-MXFP4 or M2XFP4 are what `DenseFP8` reads. */
|
||||
* (e4m3 codes, bf16 scale per 128x128), OCP-MXFP4 or M2XFP4 are what `DenseQ` reads. */
|
||||
const RadEncPlane* sc = nullptr;
|
||||
const bool known = weight_enc(b, wn, &enc);
|
||||
const bool blk_fp8 = known && rad_enc_is(&enc, "affine") && enc.n_planes == 2 &&
|
||||
!enc.transform[0] && enc.plane[0].dtype == RAD_F8E4M3 &&
|
||||
(sc = rad_enc_plane(&enc, "scale")) &&
|
||||
sc->block[0] == RAD_FP8_BLOCK && sc->block[1] == RAD_FP8_BLOCK;
|
||||
sc->block[0] == RAD_SCALE_GROUP && sc->block[1] == RAD_SCALE_GROUP;
|
||||
quant = blk_fp8 || (known && (linear_is_mxfp4(enc) || linear_is_m2xfp4(enc)));
|
||||
if (quant) {
|
||||
RAD_ARCH_TRY(w_fc.declare(b, nm, nm.f("dspark.fc"), E, cfg.n_taps * E,
|
||||
@@ -388,11 +371,11 @@ inline int MuseDflash::declare(RadBuilder* b, Names& nm, const Geom& geom, const
|
||||
*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, block fp8 or MXFP4 as the recipe wrote it (`DenseFP8::declare` reads which
|
||||
/* A linear, block fp8 or MXFP4 as the recipe wrote it (`DenseQ::declare` reads which
|
||||
* from the container's encoding and maps the name itself). More than one source is a
|
||||
* concatenation, whose row parts say where each piece begins, so `act_mul` reads
|
||||
* [gate | up] as one weight. */
|
||||
auto lin_w = [&](DenseFP8* out, rad_weight* bout, const char* suffix,
|
||||
auto lin_w = [&](DenseQ* out, rad_weight* bout, const char* suffix,
|
||||
std::initializer_list<const char*> srcs,
|
||||
std::initializer_list<int64_t> shape,
|
||||
std::initializer_list<int64_t> parts = {},
|
||||
@@ -434,12 +417,12 @@ inline int MuseDflash::declare(RadBuilder* b, Names& nm, const Geom& geom, const
|
||||
RAD_ARCH_TRY(lin_w(&w_v[i], &b_v[i], "attn_v", { SRC("self_attn.v_proj.weight") }, {kvd, E}, {},
|
||||
RAD_SHARD_ROW));
|
||||
RAD_ARCH_TRY(lin_w(&w_o[i], &b_o[i], "attn_output", { SRC("self_attn.o_proj.weight") }, {E, qd}, {},
|
||||
kRepOut ? RAD_SHARD_NONE : RAD_SHARD_COL));
|
||||
RAD_SHARD_COL));
|
||||
RAD_ARCH_TRY(lin_w(&w_gu[i], &b_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_SHARD_ROW));
|
||||
RAD_ARCH_TRY(lin_w(&w_dn[i], &b_dn[i], "ffn_down", { SRC("mlp.down_proj.weight") },
|
||||
{E, g.n_ff}, {}, kRepOut ? RAD_SHARD_NONE : RAD_SHARD_COL));
|
||||
{E, g.n_ff}, {}, RAD_SHARD_COL));
|
||||
if (cfg.gate)
|
||||
RAD_ARCH_TRY(lin_b(&w_gate[i], "attn_gate", { SRC("self_attn.g_proj.weight") },
|
||||
{g.n_head, E}));
|
||||
@@ -557,23 +540,10 @@ inline int MuseDflash::declare(RadBuilder* b, Names& nm, const Geom& geom, const
|
||||
* and dspark's. Exact, because a lossy wire would move the one embedded anchor row the whole
|
||||
* block conditions on. */
|
||||
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", E, qrows * E),
|
||||
RAD_STR("dtype", "bf16"), RAD_INT("exact", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h}, {w.h});
|
||||
op_widen = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
|
||||
RAD_STR("from", "bf16"), RAD_STR("to", "f32")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h}, {w.x});
|
||||
op_embed_ar = decl_all_reduce_exact(b, g, w.h, E, qrows, "bf16");
|
||||
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 = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
|
||||
RAD_STR("from", "bf16"), RAD_STR("to", "f32")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h}, {w.delta});
|
||||
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")),
|
||||
@@ -621,7 +591,7 @@ inline int MuseDflash::declare(RadBuilder* b, Names& nm, const Geom& geom, const
|
||||
* `gemm_nt_q_gated_mx`): it writes the quantised SwiGLU output down reads, so `w.ff`
|
||||
* stays for the fallback. */
|
||||
if (quant)
|
||||
op_gug[i] = (w_gu[i].mx || w_gu[i].m2x)
|
||||
op_gug[i] = w_gu[i].mx
|
||||
? decl_gated_fold_mx(b, qrows, 2 * g.n_ff, E, w_gu[i].w, w_gu[i].s,
|
||||
w_gu[i].ref, {w.hq, w.hs}, {w.ffq, w.ffs},
|
||||
&gated_rows)
|
||||
@@ -688,13 +658,7 @@ inline int MuseDflash::declare(RadBuilder* b, Names& nm, const Geom& geom, const
|
||||
RAD_NOWEIGHTS),
|
||||
{w.gate_up}, {w.ff});
|
||||
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", "bf16"), 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, g.max_tok, "bf16");
|
||||
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),
|
||||
@@ -741,12 +705,8 @@ inline int MuseDflash::declare(RadBuilder* b, Names& nm, const Geom& geom, const
|
||||
/* No bigram bias: the draft is the argmax of the target's own head over the predicting
|
||||
* rows, exactly `main_model_output_embeddings(...).argmax(-1)` in the reference. R = 1
|
||||
* writes one id a row, which is the [sequences, steps] proposal plane. */
|
||||
op_dlogbf = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_vocab),
|
||||
RAD_STR("from", "f32"), RAD_STR("to", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.dlog}, {w.dlog_bf});
|
||||
if (sharded && kGatherLogits) {
|
||||
op_dlogbf = cast_op(b, srows, g.n_vocab, "f32", "bf16", w.dlog, w.dlog_bf);
|
||||
if (sharded) {
|
||||
op_dgath_lg = rw(b, RAD_OP(b, "all_gather",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_INT("numel", srows * g.n_vocab),
|
||||
@@ -917,7 +877,7 @@ inline void MuseDflash::step(RadCtx* c, const RadBatch* batch) const {
|
||||
RAD_ISSUE_N(c, op_op[i], T, brows(cfg.gate ? w.attng : w.attn, T), RAD_W(b_o[i]),
|
||||
brows(w.h, T));
|
||||
}
|
||||
if (op_ar && !kRepOut) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
|
||||
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_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));
|
||||
|
||||
@@ -927,7 +887,7 @@ inline void MuseDflash::step(RadCtx* c, const RadBatch* batch) const {
|
||||
if (op_gug[i] && T <= gated_rows) {
|
||||
/* The MXFP4 fold takes the reference plane as a third weight; the fp8 tile does
|
||||
* not, and its schema is one operand shorter. */
|
||||
if (w_gu[i].mx || w_gu[i].m2x)
|
||||
if (w_gu[i].mx)
|
||||
RAD_ISSUE_N(c, op_gug[i], T, brows(w.hq, T), brows(w.hs, T), RAD_W(w_gu[i].w),
|
||||
RAD_W(w_gu[i].s), RAD_W(w_gu[i].ref), brows(w.ffq, T),
|
||||
brows(w.ffs, T), RAD_NONE);
|
||||
@@ -950,7 +910,7 @@ inline void MuseDflash::step(RadCtx* c, const RadBatch* batch) const {
|
||||
RAD_W(w_dn[i].s), brows(w.h, T), RAD_NONE, w_dn[i].bref());
|
||||
else
|
||||
RAD_ISSUE_N(c, op_dn[i], T, brows(w.ff, T), RAD_W(b_dn[i]), brows(w.h, T));
|
||||
if (op_ar && !kRepOut) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
|
||||
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_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));
|
||||
}
|
||||
@@ -1213,15 +1173,15 @@ inline int declare_muse_dflash(MuseDflash* ds, MuseDflash::Wire* w, rad_kvgroup*
|
||||
/* The linears are block fp8 or MXFP4, so every activation feeding one has an E4M3 plane and
|
||||
* an f32 scale a 128 values. */
|
||||
dw.srcq = decl_b(b, nm.f("ds_srcq"), RAD_F8E4M3, {dg.max_tok, c.n_taps * dg.n_embd});
|
||||
dw.srcs = decl_b(b, nm.f("ds_srcs"), RAD_F32, {dg.max_tok, fp8_blocks(c.n_taps * dg.n_embd)});
|
||||
dw.srcs = decl_b(b, nm.f("ds_srcs"), RAD_F32, {dg.max_tok, scale_groups(c.n_taps * dg.n_embd)});
|
||||
dw.cnq = decl_b(b, nm.f("ds_cnq"), RAD_F8E4M3, {dg.max_tok, dg.n_embd});
|
||||
dw.cns = decl_b(b, nm.f("ds_cns"), RAD_F32, {dg.max_tok, fp8_blocks(dg.n_embd)});
|
||||
dw.cns = decl_b(b, nm.f("ds_cns"), RAD_F32, {dg.max_tok, scale_groups(dg.n_embd)});
|
||||
dw.hq = decl_b(b, nm.f("ds_hq"), RAD_F8E4M3, {qr, dg.n_embd});
|
||||
dw.hs = decl_b(b, nm.f("ds_hs"), RAD_F32, {qr, fp8_blocks(dg.n_embd)});
|
||||
dw.hs = decl_b(b, nm.f("ds_hs"), RAD_F32, {qr, scale_groups(dg.n_embd)});
|
||||
dw.atq = decl_b(b, nm.f("ds_atq"), RAD_F8E4M3, {qr, qd});
|
||||
dw.ats = decl_b(b, nm.f("ds_ats"), RAD_F32, {qr, fp8_blocks(qd)});
|
||||
dw.ats = decl_b(b, nm.f("ds_ats"), RAD_F32, {qr, scale_groups(qd)});
|
||||
dw.ffq = decl_b(b, nm.f("ds_ffq"), RAD_F8E4M3, {qr, dg.n_ff});
|
||||
dw.ffs = decl_b(b, nm.f("ds_ffs"), RAD_F32, {qr, fp8_blocks(dg.n_ff)});
|
||||
dw.ffs = decl_b(b, nm.f("ds_ffs"), RAD_F32, {qr, scale_groups(dg.n_ff)});
|
||||
dw.hg = decl_b(b, nm.f("ds_hg"), RAD_BF16, {sr, dg.n_embd});
|
||||
dw.dlog = decl_b(b, nm.f("ds_dlog"), RAD_F32, {sr, dg.n_vocab});
|
||||
/* Vocab-sharded, the head's rows are this rank's slice and the top-1 must be taken over every
|
||||
|
||||
@@ -55,6 +55,10 @@
|
||||
* 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
|
||||
@@ -64,6 +68,7 @@
|
||||
#define RAD_BLOCK_MUSEGLIMMER_VISION_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
#include "rad_linear.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
@@ -73,6 +78,152 @@
|
||||
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. */
|
||||
@@ -86,17 +237,17 @@ struct MuseTower {
|
||||
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, qkv_w = 0, qkv_b = 0, out_w = 0, out_b = 0;
|
||||
rad_weight n2w = 0, n2b = 0, up_w = 0, up_b = 0, down_w = 0, down_b = 0;
|
||||
rad_op ln1 = 0, qkv = 0, rope = 0, attn = 0, proj = 0, ln2 = 0, up = 0, down = 0;
|
||||
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;
|
||||
rad_weight w_a1 = 0, w_a2 = 0, w_proj = 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_m1 = 0, op_g1 = 0, op_m2 = 0, op_g2 = 0, op_proj = 0,
|
||||
op_perc = 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;
|
||||
@@ -251,6 +402,12 @@ inline int MuseTower::declare(RadBuilder* b, const RadModelMeta* m, const RadBui
|
||||
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"),
|
||||
@@ -273,28 +430,33 @@ inline int MuseTower::declare(RadBuilder* b, const RadModelMeta* m, const RadBui
|
||||
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. */
|
||||
if (map_concat(b, dn("qkv.weight"),
|
||||
{ src("attn.q_proj.weight"), src("attn.k_proj.weight"),
|
||||
src("attn.v_proj.weight") }) < 0)
|
||||
return RAD_E_INVAL;
|
||||
l.qkv_w = decl_w(b, dn("qkv.weight"), RAD_BF16, { 3 * width, width }, ACC,
|
||||
RAD_SHARD_NONE, g, 0, { width, width, width });
|
||||
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;
|
||||
l.qkv_b = decl_w(b, dn("qkv.bias"), RAD_BF16, { 3 * width }, ACC, RAD_SHARD_NONE, g, 0,
|
||||
{ width, width, width });
|
||||
l.out_w = bw(dn("proj.weight"), src("attn.proj.weight"), { width, width }, g);
|
||||
l.out_b = bw(dn("proj.bias"), src("attn.proj.bias"), { width }, g);
|
||||
{
|
||||
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);
|
||||
l.up_w = bw(dn("fc1.weight"), src("mlp.fc1.weight"), { ff, width }, g);
|
||||
l.up_b = bw(dn("fc1.bias"), src("mlp.fc1.bias"), { ff }, g);
|
||||
l.down_w= bw(dn("fc2.weight"), src("mlp.fc2.weight"), { width, ff }, g);
|
||||
l.down_b= bw(dn("fc2.bias"), src("mlp.fc2.bias"), { width }, g);
|
||||
if (!l.n1w || !l.n1b || !l.qkv_w || !l.qkv_b || !l.out_w || !l.out_b || !l.n2w || !l.n2b ||
|
||||
!l.up_w || !l.up_b || !l.down_w || !l.down_b)
|
||||
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;
|
||||
@@ -303,15 +465,13 @@ inline int MuseTower::declare(RadBuilder* b, const RadModelMeta* m, const RadBui
|
||||
grp_model());
|
||||
lb_post = bw(nm.f("v.lnpost.bias"), nm.ckpt("model.vision_tower.ln_post.bias"), { width },
|
||||
grp_model());
|
||||
w_a1 = bw(nm.f("v.mlp.fc1.weight"), nm.ckpt("model.vision_adapter.fc1.weight"),
|
||||
{ proj_ff, out_hidden }, grp_model());
|
||||
w_a2 = bw(nm.f("v.mlp.fc2.weight"), nm.ckpt("model.vision_adapter.fc2.weight"),
|
||||
{ proj_ff, proj_ff }, grp_model());
|
||||
w_proj = bw(nm.f("v.proj.weight"), nm.ckpt("model.vision_projection.weight"),
|
||||
{ n_embd, proj_ff }, grp_model());
|
||||
if (!w_patch || !w_pos || !lw_pre || !lb_pre || !lw_post || !lb_post || !w_a1 || !w_a2 ||
|
||||
!w_proj)
|
||||
return RAD_E_INVAL;
|
||||
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
|
||||
@@ -334,19 +494,17 @@ inline int MuseTower::declare(RadBuilder* b, const RadModelMeta* m, const RadBui
|
||||
!b_mh || !b_m1 || !b_m2 || !b_out)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
auto gemm_b = [&](int64_t rows, int64_t N, int64_t K, const char* a, rad_weight w,
|
||||
rad_weight bias) -> rad_op {
|
||||
return RAD_OP(b, "gemm_nt_bias",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_STR("dtype", "bf16"), RAD_STR("act", a)),
|
||||
RAD_WEIGHTS(w, bias));
|
||||
};
|
||||
auto gemm = [&](int64_t rows, int64_t N, int64_t K, rad_weight w) -> rad_op {
|
||||
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));
|
||||
};
|
||||
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),
|
||||
@@ -386,7 +544,7 @@ inline int MuseTower::declare(RadBuilder* b, const RadModelMeta* m, const RadBui
|
||||
{ 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 });
|
||||
l.qkv = rw(b, gemm_b(P, 3 * width, width, "none", l.qkv_w, l.qkv_b), { b_h }, { b_qkv });
|
||||
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),
|
||||
@@ -403,10 +561,11 @@ inline int MuseTower::declare(RadBuilder* b, const RadModelMeta* m, const RadBui
|
||||
l.full ? std::initializer_list<rad_buf>{ b_qkv }
|
||||
: std::initializer_list<rad_buf>{ b_qkv, b_cuw },
|
||||
{ b_att });
|
||||
l.proj = rw(b, gemm_b(P, width, width, "none", l.out_w, l.out_b), { b_att, b_p }, { b_p });
|
||||
/* 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 });
|
||||
l.up = rw(b, gemm_b(P, ff, width, "gelu", l.up_w, l.up_b), { b_h }, { b_ff });
|
||||
l.down = rw(b, gemm_b(P, width, ff, "none", l.down_w, l.down_b), { b_ff, b_p }, { b_p });
|
||||
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),
|
||||
@@ -423,20 +582,20 @@ inline int MuseTower::declare(RadBuilder* b, const RadModelMeta* m, const RadBui
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_x }, { b_mh });
|
||||
/* The adapter: both linears bias-less, gelu between and after (the reference's
|
||||
* act(fc2(act(fc1(x))))). */
|
||||
op_m1 = rw(b, gemm(R, proj_ff, mm * width, w_a1), { b_mh }, { b_m1 });
|
||||
* 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 });
|
||||
op_m2 = rw(b, gemm(R, proj_ff, proj_ff, w_a2), { b_m2 }, { b_m1 });
|
||||
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 });
|
||||
op_proj = rw(b, gemm(R, n_embd, proj_ff, w_proj), { b_m2 }, { b_out });
|
||||
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",
|
||||
@@ -543,20 +702,16 @@ inline void MuseTower::step(RadCtx* c, const RadBatch* batch) const {
|
||||
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));
|
||||
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));
|
||||
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));
|
||||
RAD_ISSUE_N(c, l.proj, Pn, brows(b_att, Pn), RAD_W(l.out_w), RAD_W(l.out_b),
|
||||
brows(b_p, Pn), brows(b_p, 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));
|
||||
RAD_ISSUE_N(c, l.up, Pn, brows(b_h, Pn), RAD_W(l.up_w), RAD_W(l.up_b), RAD_NONE,
|
||||
brows(b_ff, Pn));
|
||||
RAD_ISSUE_N(c, l.down, Pn, brows(b_ff, Pn), RAD_W(l.down_w), RAD_W(l.down_b),
|
||||
brows(b_p, Pn), brows(b_p, 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);
|
||||
}
|
||||
@@ -567,12 +722,12 @@ inline void MuseTower::step(RadCtx* c, const RadBatch* batch) const {
|
||||
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);
|
||||
RAD_ISSUE_N(c, op_m1, Rn, brows(b_mh, Rn), RAD_W(w_a1), brows(b_m1, Rn));
|
||||
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));
|
||||
RAD_ISSUE_N(c, op_m2, Rn, brows(b_m2, Rn), RAD_W(w_a2), brows(b_m1, Rn));
|
||||
a2.step(c, Rn);
|
||||
RAD_ISSUE_N(c, op_g2, Rn, brows(b_m1, Rn), brows(b_m2, Rn));
|
||||
RAD_ISSUE_N(c, op_proj, Rn, brows(b_m2, Rn), RAD_W(w_proj), brows(b_out, 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);
|
||||
|
||||
@@ -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 {
|
||||
@@ -104,8 +104,8 @@ struct PleLayer {
|
||||
* 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. */
|
||||
LinearFP8 key{}, value{};
|
||||
ActFP8 a_embd{}, a_fed{};
|
||||
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;
|
||||
@@ -334,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;
|
||||
@@ -398,15 +398,11 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
|
||||
op_hint_hist = op_hint_round = op_hint_gather = 0;
|
||||
}
|
||||
|
||||
op_embd = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", c.embed_dim),
|
||||
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{b_emb}, {b_embd});
|
||||
op_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 (LinearFP8 refuses the pair otherwise). */
|
||||
* 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);
|
||||
@@ -465,7 +461,7 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
|
||||
}
|
||||
|
||||
/* 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
|
||||
|
||||
+35
-31
@@ -82,20 +82,21 @@ 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",
|
||||
bool export_aux = false);
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
};
|
||||
|
||||
inline int VisionTower::declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx,
|
||||
Names& nm, int64_t model_embd, int first_group, bool deepstack,
|
||||
bool gate_weights) {
|
||||
bool gate_weights, const char* prefix, bool export_aux) {
|
||||
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 +195,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;
|
||||
}
|
||||
@@ -324,6 +324,10 @@ inline int VisionTower::declare(RadBuilder* b, const RadModelMeta* m, const RadB
|
||||
e.max_patches = P;
|
||||
e.n_embd = n_embd;
|
||||
e.out = b_out;
|
||||
if (export_aux) {
|
||||
e.n_aux = n_ds;
|
||||
for (int tap = 0; tap < n_ds; ++tap) e.aux_out[tap] = b_ds[tap];
|
||||
}
|
||||
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
|
||||
rad_note(b, "vision tower: %lld blocks of %lld (%lld heads x %lld), ff %lld, patch %lld x "
|
||||
"%lld x %lld, merge %lld; %lld patches a pass -> %lld rows of %lld",
|
||||
|
||||
@@ -9,9 +9,10 @@
|
||||
* row. An input every rank holds whole (a norm's output) is read where it is.
|
||||
*
|
||||
* One rank records each layer (layer % world), so the Gram work and the host memory split
|
||||
* evenly. Its f32 scratch receives one step's sum for one input (`gram_accum` with `upper` 1: H is
|
||||
* symmetric and only k2 >= k1 is kept), whose upper triangle is copied to a pinned square and which
|
||||
* is zeroed for the next input, all in stream order. A worker thread waits on the copy's event and adds the square to a
|
||||
* evenly. Its f32 scratch is zeroed (it is arena memory, which is not zeroed when it is allocated,
|
||||
* and `gram_accum` adds to what it finds), receives one step's sum for one input (`upper` 1: H is
|
||||
* symmetric and only k2 >= k1 is kept), and its upper triangle is copied to a pinned square, all in
|
||||
* stream order. A worker thread waits on the copy's event and adds the square to a
|
||||
* host accumulator holding the upper triangle packed row by row (k(k+1)/2 f32), while the rank goes
|
||||
* on issuing the step: two squares alternate, so the rank waits only when the adds fall two Grams
|
||||
* behind. Syncing and adding on the rank's own thread instead left the card idle for every add, 16
|
||||
@@ -58,6 +59,7 @@ 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;
|
||||
int64_t col0 = 0; /* a replicated input's first column in `local` (a slice of a wider buffer) */
|
||||
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 */
|
||||
@@ -67,6 +69,10 @@ struct CalibFull {
|
||||
const char* dir = nullptr;
|
||||
int rank = 0, world = 1;
|
||||
int64_t lo = 0, hi = 0; /* layers recorded */
|
||||
/* The ranks that record: layer l is recorded by rank l % own_world. 0 is every rank. A plugin
|
||||
* with ranks that hold no activations of a block (ERNIE-5.5's attention-zero rank) states the
|
||||
* ranks that do. */
|
||||
int own_world = 0;
|
||||
long long target = 0, seen = 0;
|
||||
bool written = false;
|
||||
rad_buf gathered = 0; /* [max_tok, widest split input] bf16 */
|
||||
@@ -93,7 +99,7 @@ struct CalibFull {
|
||||
|
||||
/* Whether this run records layer l. */
|
||||
bool records(int64_t l) const { return on && l >= lo && l < hi; }
|
||||
int owner_of(int64_t l) const { return (int)(l % world); }
|
||||
int owner_of(int64_t l) const { return (int)(l % (own_world > 0 ? own_world : world)); }
|
||||
|
||||
/* From the build context: nothing unless --calib-dir is set. `widest_split` and `widest` are
|
||||
* the largest split input and the largest input of any recorded site, which size the gather
|
||||
@@ -129,19 +135,27 @@ struct CalibFull {
|
||||
}
|
||||
|
||||
/* One input of layer `layer` (-1: the lm_head's, recorded by rank 0). `local` is the rank's
|
||||
* part, `k_local` its width; the input is split across ranks when k_local * world == K. */
|
||||
* part, `k_local` its width; the input is split across ranks when k_local * world == K.
|
||||
*
|
||||
* `part_world` (a split input only): the ranks that hold a part, when fewer than the world
|
||||
* (K == k_local * part_world). Every rank still joins the gather, the others with any buffer
|
||||
* of k_local columns, and the Gram reads the first K columns of the gathered row.
|
||||
* `col0` (a replicated input): the input is columns [col0, col0 + K) of the wider `local`. */
|
||||
int site(RadBuilder* b, const Geom& g, int64_t layer, std::string stem, std::string linears,
|
||||
rad_buf local, int64_t k_local, int64_t K) {
|
||||
rad_buf local, int64_t k_local, int64_t K, int part_world = 0, int64_t col0 = 0) {
|
||||
Site s;
|
||||
s.stem = std::move(stem);
|
||||
s.linears = std::move(linears);
|
||||
s.local = local;
|
||||
s.K = K;
|
||||
s.k_local = k_local;
|
||||
s.col0 = col0;
|
||||
s.owner = (layer < 0 ? 0 : owner_of(layer)) == rank;
|
||||
const bool split = k_local != K;
|
||||
if (split) {
|
||||
if (k_local * world != K || !gathered || K > gather_w) return RAD_E_INVAL;
|
||||
if (k_local * (part_world > 0 ? part_world : world) != K || !gathered ||
|
||||
k_local * world > gather_w)
|
||||
return RAD_E_INVAL;
|
||||
s.op_gather = rw(b, RAD_OP(b, "all_gather",
|
||||
RAD_PARAMS(RAD_INT("world_size", world),
|
||||
RAD_RANGE("numel", k_local, g.max_tok * k_local),
|
||||
@@ -190,13 +204,14 @@ struct CalibFull {
|
||||
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. */
|
||||
/* Site `i` over a step's T rows: gather (every rank), then on the owner the scratch zeroed,
|
||||
* the Gram into it, copied to a free square, and the square handed to the worker. */
|
||||
void tap(RadCtx* c, size_t i, int64_t T) {
|
||||
Site& s = sites[i];
|
||||
RadOperand a = brows(s.local, T);
|
||||
RadOperand a = s.col0 ? bcol(s.local, s.col0, s.K, T) : brows(s.local, T);
|
||||
if (s.op_gather) {
|
||||
RAD_ISSUE_N(c, s.op_gather, T * s.k_local, brows(s.local, T), bcol(gathered, 0, s.K, T));
|
||||
RAD_ISSUE_N(c, s.op_gather, T * s.k_local, brows(s.local, T),
|
||||
bcol(gathered, 0, s.k_local * world, T));
|
||||
a = bcol(gathered, 0, s.K, T);
|
||||
}
|
||||
if (!s.owner) return;
|
||||
@@ -220,6 +235,13 @@ struct CalibFull {
|
||||
}
|
||||
}
|
||||
const int64_t K = s.K;
|
||||
/* Before the Gram, not after: nothing else has zeroed the scratch when the first input
|
||||
* of a run arrives, nor the part past it when a wider one does, and a Gram summed onto
|
||||
* what the card's memory held is NaNs and 3.4e38 in a file of the right size. */
|
||||
if (rad_memset_async(dev, 0, K * K * 4, rad_stream(c)) < 0) {
|
||||
rad_step_fail(c, "calibration: zeroing the scratch failed");
|
||||
return;
|
||||
}
|
||||
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
|
||||
@@ -233,8 +255,7 @@ struct CalibFull {
|
||||
for (int64_t r = 0; r < K && ok; r += kBand)
|
||||
ok = rad_memcpy_2d_async(q.square[k] + r * K + r, K * 4, dev + r * K + r, K * 4,
|
||||
(K - r) * 4, std::min(kBand, K - r), rad_stream(c)) >= 0;
|
||||
if (!ok || rad_memset_async(dev, 0, K * K * 4, rad_stream(c)) < 0 ||
|
||||
rad_event_record(q.copied[k], rad_stream(c)) < 0) {
|
||||
if (!ok || rad_event_record(q.copied[k], rad_stream(c)) < 0) {
|
||||
rad_step_fail(c, "calibration: copying a Gram back failed");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -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,56 @@
|
||||
/* 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. The answer's own <|end_message|> is content_close: not part of the answer, and in
|
||||
* the format. A second one, with no message open, still leaves it.
|
||||
*
|
||||
* 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.content_close = "<|end_message|>";
|
||||
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,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 */
|
||||
+13
-13
@@ -16,7 +16,7 @@
|
||||
#define RAD_QSA_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
#include "rad_fp8.h"
|
||||
#include "rad_linear.h"
|
||||
|
||||
#include <atomic>
|
||||
|
||||
@@ -106,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
|
||||
@@ -120,21 +120,21 @@ 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.
|
||||
*
|
||||
* `use` is what the layer's attention reads of the selection this step (QsaUse, rad_arch.h;
|
||||
* AttnGatedFP8::qsa_use): the default issues the query, the scores and the selection as every
|
||||
* 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 ActFP8& in, const RadBatch* batch,
|
||||
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;
|
||||
* 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). */
|
||||
@@ -153,7 +153,7 @@ struct QsaIndexer {
|
||||
}
|
||||
/* 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 ActFP8& in, const RadBatch* batch) const {
|
||||
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 {
|
||||
@@ -162,7 +162,7 @@ struct QsaIndexer {
|
||||
};
|
||||
|
||||
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 */
|
||||
@@ -291,7 +291,7 @@ 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;
|
||||
}
|
||||
|
||||
@@ -362,13 +362,13 @@ inline bool QsaIndexer::store_keys(RadCtx* c_, const RadBatch* batch, int part)
|
||||
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,
|
||||
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;
|
||||
@@ -424,7 +424,7 @@ inline void QsaIndexer::step(RadCtx* c_, const ActFP8& in, const RadBatch* batch
|
||||
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 (AttnGatedFP8::qsa_use). */
|
||||
* made (AttnGatedQ::qsa_use). */
|
||||
if (use == kQsaUnread) return;
|
||||
|
||||
/* Narrow the score columns to the live history. Both kernels size their grid from the
|
||||
|
||||
+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
|
||||
@@ -266,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) ||
|
||||
@@ -279,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});
|
||||
@@ -382,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(), "",
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(ernie55 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
rad_add_plugin(ernie55 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/ernie55.cpp)
|
||||
@@ -0,0 +1,37 @@
|
||||
/* ERNIE-5.5's reply format: <ernie:think>...</ernie:think> and <ernie:tool_call><invoke>. */
|
||||
#pragma once
|
||||
#include "rad_builder.h"
|
||||
|
||||
namespace ernie55 {
|
||||
|
||||
inline const RadChatFormat* ernie55_chat_format() {
|
||||
static const char* const triggers[] = { "<ernie:tool_call>" };
|
||||
static const RadChatFormat f = [] {
|
||||
RadChatFormat x{};
|
||||
x.struct_size = sizeof(x);
|
||||
x.name = "plugin:ernie55";
|
||||
x.reasoning_open = "<ernie:think>";
|
||||
x.reasoning_close = "</ernie:think>";
|
||||
x.reasoning_breaks = triggers;
|
||||
x.n_reasoning_breaks = 1;
|
||||
x.reasoning_in_prompt = RAD_CHAT_THINK_FROM_PROMPT;
|
||||
x.section_open = "<ernie:tool_call>";
|
||||
x.section_close = "</ernie:tool_call>";
|
||||
x.name_prefix = "<invoke name=\"";
|
||||
x.name_suffix = "\">";
|
||||
x.call_end = "</invoke>";
|
||||
x.arg_prefix = "<parameter name=\"";
|
||||
x.arg_name_suffix = "\">";
|
||||
x.arg_value_suffix = "</parameter>";
|
||||
x.string_value = RAD_CHAT_VALUE_RAW;
|
||||
x.other_value = RAD_CHAT_VALUE_JSON;
|
||||
x.value_newlines = 0;
|
||||
x.triggers = triggers;
|
||||
x.n_triggers = 1;
|
||||
x.args_form = RAD_CHAT_ARGS_TAGGED;
|
||||
return x;
|
||||
}();
|
||||
return &f;
|
||||
}
|
||||
|
||||
} /* namespace ernie55 */
|
||||
@@ -0,0 +1,904 @@
|
||||
/* ernie55 -- ERNIE-5.5-Flash (`model_type: ernie5_5_moe`) served with an IQ8R trunk (rotated int8
|
||||
* codes at group 256) and byte-exact OCP MXFP4 routed experts (data/recipes/ernie55-iq8r.recipe):
|
||||
* four mHC residual streams over 37 HCA layers (heavily compressed attention: one entry per 128
|
||||
* tokens plus a 128-token window) and 6 DSA layers (absorbed MLA over a token-level indexer's top
|
||||
* 2048 plus the window), a dense SiTU layer 0 and 42 latent MoE layers (512 MXFP4 experts at top 10
|
||||
* in a 2048-wide latent, W4A8 as Baidu trained them), and a multimax logit head.
|
||||
* With --num-speculative-tokens 7 the bundled DSpark drafter (model.mtp.*) proposes a block of
|
||||
* seven: three more H+MoE layers over the outputs of trunk layers 40, 41 and 42.
|
||||
* docs/ARCHITECTURES.md describes the model, its drafter and their traps.
|
||||
*
|
||||
* The blocks live in arch/common (installed as <arch/...>), one a file:
|
||||
*
|
||||
* rad_block_glm_mhc.h ManifoldConn the four-stream residual read and write (eps outside)
|
||||
* rad_block_ernie_hca.h ErnieHca the 37 HCA layers, their window, entries and compressor
|
||||
* rad_block_ernie_dsa.h ErnieDsa the 6 DSA layers, their latent and index caches
|
||||
* rad_block_ernie_moe.h ErnieDense layer 0's SiTU feed-forward
|
||||
* ErnieMoe the latent MoE of layers 1-42
|
||||
* rad_block_ernie_dspark.h ErnieDspark the bundled drafter: taps, context, stages, walk
|
||||
*
|
||||
* Tensor parallelism: the trunk is replicated on every rank and the routed experts are expert
|
||||
* parallel, whole even-pair slices of 512 a rank (equal at TP1/2/4/8; 172+170+170 at TP3). The
|
||||
* only collective of a layer is the
|
||||
* all-reduce of the routed experts' 2048-wide latent sum, before its norm; the vocabulary is
|
||||
* row-sharded with one all-reduce after the lookup. On cards without peer access every collective
|
||||
* goes through host memory, so this layout trades replicated attention reads for no attention
|
||||
* collective (docs/ARCHITECTURES.md).
|
||||
*
|
||||
* This file declares the buffers the blocks share, places the blocks and issues the step's order.
|
||||
* Declaration order is liveness, and the issue order is the recorded pass, so both are kept as they
|
||||
* read here. This plugin uses only the public ABI and the installed common headers. */
|
||||
#include <arch/rad_block_glm_mhc.h>
|
||||
#include <arch/rad_block_ernie_hca.h>
|
||||
#include <arch/rad_block_ernie_dsa.h>
|
||||
#include <arch/rad_block_ernie_moe.h>
|
||||
#include <arch/rad_block_ernie_dspark.h>
|
||||
#include <arch/rad_calib_full.h>
|
||||
#include <arch/rad_expert_split.h>
|
||||
#include "chat.h"
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
|
||||
namespace ernie55 {
|
||||
using namespace rad::arch;
|
||||
|
||||
constexpr int64_t kLayers = 43, kEmbd = 4096, kStreams = 4, kVocab = 201216, kExperts = 512;
|
||||
/* Layers 7, 14, 21, 28, 35 and 42 are DSA (`compress_ratios` -2); the rest HCA (128). */
|
||||
inline bool is_dsa(int l) { return l > 0 && l % 7 == 0; }
|
||||
|
||||
struct Layer {
|
||||
bool dsa = false;
|
||||
ManifoldConn attn_hc{}, ffn_hc{};
|
||||
rad_weight attn_gain = 0, ffn_gain = 0;
|
||||
rad_op attn_norm = 0, attn_quant = 0, ffn_norm = 0, ffn_quant = 0;
|
||||
ErnieHca hca{};
|
||||
ErnieDsa sparse{};
|
||||
ErnieDense dense{};
|
||||
ErnieMoe moe{};
|
||||
/* The layer's calibration inputs (CalibFull sites), -1 where this run records none here: the
|
||||
* attention block's input, the query latent, wo_a's eight group inputs, the gated product
|
||||
* (o_proj's input), the feed-forward's input, the shared expert's and latent_out's inputs, and
|
||||
* layer 0's dense down input. */
|
||||
int cs_in = -1, cs_cq = -1, cs_wo[8] = { -1, -1, -1, -1, -1, -1, -1, -1 }, cs_gated = -1,
|
||||
cs_ffn = -1, cs_sff = -1, cs_ln = -1, cs_dff = -1;
|
||||
};
|
||||
struct Model {
|
||||
Names nm{};
|
||||
Geom g{};
|
||||
std::vector<Layer> layers;
|
||||
/* The streams and the step's stream-wide buffers. */
|
||||
rad_buf h0 = 0, h1 = 0, x = 0, y = 0, post = 0, comb = 0, final_hidden = 0, logit_input = 0,
|
||||
logits = 0;
|
||||
/* The normalised layer input and its rotated int8 codes (group 256), read by every block. */
|
||||
ActQ act{};
|
||||
ErnieHca::Config hca_cfg{};
|
||||
ErnieHca::Wire hw{};
|
||||
ErnieHca::Caches hca_caches{};
|
||||
ErnieDsa::Wire dw{};
|
||||
ErnieDsa::Caches dsa_caches{};
|
||||
ErnieDense::Wire fw{};
|
||||
ErnieMoe::Config moe_cfg{};
|
||||
ErnieMoe::Wire mw{};
|
||||
/* The hot-first split's router labels (ErnieMoe::Config::order), [layer][label]; empty when
|
||||
* the experts keep their numbering. */
|
||||
std::vector<std::vector<int32_t>> ep_order;
|
||||
rad_weight token = 0, head = 0, final_gain = 0, hc_fn = 0, hc_scale = 0, hc_base = 0,
|
||||
mm_r = 0, mm_t = 0;
|
||||
rad_op embed = 0, embed_ar = 0, attn_ar = 0, zero_y = 0, expand = 0, contract = 0, norm = 0,
|
||||
gather = 0, head_op = 0, multimax = 0;
|
||||
/* --calib-dir: the whole Hessian of every trunk linear's input over a --calib-corpus run. The
|
||||
* routed experts' inputs (512 a layer) are not recorded. */
|
||||
CalibFull calib;
|
||||
/* The attention-zero rank's stand-ins for the split inputs it joins the gathers of, by width. */
|
||||
std::map<int64_t, rad_buf> calib_dummy;
|
||||
/* wo_a's group inputs are columns of o_mix, which gram_accum reads whole rows of: each is
|
||||
* copied into this [max_tok, 4096] stage first. */
|
||||
rad_buf calib_stage = 0;
|
||||
rad_op calib_copy = 0;
|
||||
/* The bundled DSpark drafter, declared when the serve drafts: the trunk writes the mean of
|
||||
* the streams after each tapped layer (dspark_target_layer_ids) into `taps`. */
|
||||
bool draft = false;
|
||||
int tap_at[ErnieDspark::kTaps] = {};
|
||||
rad_buf taps = 0;
|
||||
rad_op op_tap[ErnieDspark::kTaps] = {};
|
||||
ErnieDspark ds{};
|
||||
};
|
||||
static std::unique_ptr<Model> models[MAX_SLOTS];
|
||||
static thread_local std::unique_ptr<Model> probe_model;
|
||||
|
||||
static int64_t cfg(const RadModelMeta* m, const char* key, int64_t fallback) {
|
||||
return rad_meta_geti(m, key, fallback);
|
||||
}
|
||||
static rad_op copy(RadBuilder* b, const Geom& g, rad_buf x, rad_buf y) {
|
||||
return rw(b,
|
||||
RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", kEmbd),
|
||||
RAD_STR("from", "bf16"), RAD_STR("to", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ x }, { y });
|
||||
}
|
||||
static rad_op rmsnorm(RadBuilder* b, const Geom& g, rad_weight w, rad_buf x, rad_buf y) {
|
||||
return rw(b,
|
||||
RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", kEmbd),
|
||||
RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w)),
|
||||
{ x }, { y });
|
||||
}
|
||||
static rad_op quant(RadBuilder* b, const Geom& g, const ActQ& a) {
|
||||
return decl_trunk_quant(b, g.max_tok, kEmbd, a);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the shared activations */
|
||||
static int stream_buffers(RadBuilder* b, Model& m) {
|
||||
auto& g = m.g;
|
||||
auto& nm = m.nm;
|
||||
const int64_t T = g.max_tok;
|
||||
m.h0 = decl_b(b, nm.f("manifold"), RAD_BF16, { T, kStreams * kEmbd });
|
||||
m.h1 = decl_b(b, nm.f("manifold_mid"), RAD_BF16, { T, kStreams * kEmbd });
|
||||
m.x = decl_b(b, nm.f("collapsed"), RAD_BF16, { T, kEmbd });
|
||||
m.y = decl_b(b, nm.f("block_out"), RAD_BF16, { T, kEmbd });
|
||||
m.post = decl_b(b, nm.f("post"), RAD_F32, { T, kStreams });
|
||||
m.comb = decl_b(b, nm.f("mix"), RAD_F32, { T, kStreams * kStreams });
|
||||
m.act.x = decl_b(b, nm.f("normalized"), RAD_BF16, { T, kEmbd });
|
||||
RAD_ARCH_TRY(m.act.declare_trunk(b, nm, g, "normalized", kEmbd));
|
||||
m.final_hidden = decl_b(b, nm.f("final_hidden"), RAD_BF16, { T, kEmbd }, RAD_BUF_PERSIST);
|
||||
m.logit_input = decl_b(b, nm.f("logit_input"), RAD_BF16, { g.max_logit_rows, kEmbd });
|
||||
m.logits = decl_b(b, nm.f("logits"), RAD_F32, { g.max_logit_rows, g.n_vocab });
|
||||
if (!m.h0 || !m.h1 || !m.x || !m.y || !m.post || !m.comb || !m.act.x || !m.final_hidden ||
|
||||
!m.logit_input || !m.logits)
|
||||
return RAD_E_INVAL;
|
||||
/* Written by the trunk step and read by the drafter's passes after it, row for row. */
|
||||
if (m.draft && !g.attn_zero) {
|
||||
m.taps = decl_b(b, nm.f("draft_taps"), RAD_BF16, { T, ErnieDspark::kTaps * kEmbd },
|
||||
RAD_BUF_PERSIST);
|
||||
if (!m.taps) return RAD_E_INVAL;
|
||||
}
|
||||
return rad_declare_logits(b, m.logits);
|
||||
}
|
||||
static int block_wires(RadBuilder* b, Model& m) {
|
||||
auto& g = m.g;
|
||||
auto& nm = m.nm;
|
||||
m.hw.in = m.act;
|
||||
m.hw.out = m.y;
|
||||
m.dw.in = m.act;
|
||||
m.dw.out = m.y;
|
||||
m.fw.in = m.act;
|
||||
m.fw.out = m.y;
|
||||
if (!g.attn_zero) {
|
||||
RAD_ARCH_TRY(ErnieHca::declare_wire(b, nm, g, m.hca_cfg, &m.hw));
|
||||
RAD_ARCH_TRY(ErnieDsa::declare_wire(b, nm, g, &m.dw));
|
||||
RAD_ARCH_TRY(ErnieDense::declare_wire(b, nm, g, &m.fw));
|
||||
}
|
||||
m.mw.in = m.act;
|
||||
m.mw.out = m.y;
|
||||
return ErnieMoe::declare_wire(b, nm, g, m.moe_cfg, &m.mw);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ calibration (--calib-dir)
|
||||
* The Hessian of each trunk linear's input over a --calib-corpus run, from the bf16 inputs the
|
||||
* served container's own GEMMs read. Every input but two is replicated on the attention ranks
|
||||
* (0 and 1 at TP3, one of which records a layer); the gated product (o_proj's input) and layer
|
||||
* 0's dense SiTU product are split across the attention ranks, so every rank joins their gather,
|
||||
* the attention-zero rank with a dummy buffer, and the Gram takes the whole row. */
|
||||
static int calib_begin(RadBuilder* b, Model& m, const RadBuildCtx* ctx) {
|
||||
auto& g = m.g;
|
||||
if (!ctx->calib_dir || !*ctx->calib_dir) return RAD_OK;
|
||||
const int64_t lo = ctx->calib_layer_hi ? ctx->calib_layer_lo : 0;
|
||||
const int64_t hi = ctx->calib_layer_hi ? std::min<int64_t>(ctx->calib_layer_hi, kLayers) : kLayers;
|
||||
int64_t widest = 4096, split = 128;
|
||||
const bool sharded = g.attn_world < g.world;
|
||||
for (int64_t l = lo; l < hi; ++l) {
|
||||
const int64_t gated = is_dsa((int)l) ? 16384 : 8192;
|
||||
widest = std::max(widest, gated);
|
||||
if (sharded) split = std::max(split, gated / g.attn_world * g.world);
|
||||
if (l == 0) {
|
||||
widest = std::max<int64_t>(widest, 14336);
|
||||
if (sharded) split = std::max<int64_t>(split, 14336 / g.attn_world * g.world);
|
||||
}
|
||||
}
|
||||
m.calib.own_world = g.attn_world;
|
||||
RAD_ARCH_TRY(m.calib.begin(b, m.nm, g, ctx, kLayers, split, widest));
|
||||
if (m.calib.on && !g.attn_zero) {
|
||||
m.calib_stage = decl_b(b, m.nm.f("calib.stage"), RAD_BF16, { g.max_tok, kEmbd });
|
||||
if (!m.calib_stage) return RAD_E_INVAL;
|
||||
m.calib_copy = copy(b, g, m.hw.o_mix, m.calib_stage);
|
||||
if (!m.calib_copy) return RAD_E_INVAL;
|
||||
}
|
||||
if (m.calib.on && g.attn_zero && g.world > 1) {
|
||||
for (int64_t w : { (int64_t)4096, (int64_t)8192, (int64_t)7168 }) {
|
||||
rad_buf d = decl_b(b, m.nm.f("calib.dummy.%lld", (long long)w), RAD_BF16,
|
||||
{ g.max_tok, w });
|
||||
if (!d) return RAD_E_INVAL;
|
||||
m.calib_dummy[w] = d;
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
static int calib_sites(RadBuilder* b, Model& m, Layer& lay, int l) {
|
||||
auto& cf = m.calib;
|
||||
auto& g = m.g;
|
||||
if (!cf.records(l)) return RAD_OK;
|
||||
char stem[96], lins[256];
|
||||
auto add = [&](int* slot, const char* st, const char* li, rad_buf local, int64_t k_local,
|
||||
int64_t K, int part = 0, int64_t col0 = 0) {
|
||||
*slot = (int)cf.sites.size();
|
||||
return cf.site(b, g, l, st, li, local, k_local, K, part, col0);
|
||||
};
|
||||
const bool sharded = g.attn_world < g.world;
|
||||
const int part = sharded ? g.attn_world : 0;
|
||||
const int64_t gated_k = is_dsa(l) ? 16384 : 8192;
|
||||
const ActQ& gated = lay.dsa ? m.dw.gated : m.hw.gated;
|
||||
if (!g.attn_zero) {
|
||||
std::snprintf(stem, sizeof stem, "blk.%d.attn_in.input", l);
|
||||
if (lay.dsa)
|
||||
std::snprintf(lins, sizeof lins, "blk.%d.attn_q_a,blk.%d.attn_kv_a_lat", l, l);
|
||||
else
|
||||
std::snprintf(lins, sizeof lins, "blk.%d.attn_q_a,blk.%d.attn_kv", l, l);
|
||||
RAD_ARCH_TRY(add(&lay.cs_in, stem, lins, m.act.x, kEmbd, kEmbd));
|
||||
std::snprintf(stem, sizeof stem, "blk.%d.attn_cq.input", l);
|
||||
if (lay.dsa)
|
||||
std::snprintf(lins, sizeof lins, "blk.%d.attn_q_b,blk.%d.attn_idx_wq_b,blk.%d.attn_gate",
|
||||
l, l, l);
|
||||
else
|
||||
std::snprintf(lins, sizeof lins, "blk.%d.attn_q_up,blk.%d.attn_gate", l, l);
|
||||
RAD_ARCH_TRY(add(&lay.cs_cq, stem, lins, lay.dsa ? m.dw.c_q.x : m.hw.c_q.x, 1024, 1024));
|
||||
if (!lay.dsa)
|
||||
for (int gi = 0; gi < 8; ++gi) {
|
||||
std::snprintf(stem, sizeof stem, "blk.%d.attn_wo_a.%d.input", l, gi);
|
||||
std::snprintf(lins, sizeof lins, "blk.%d.attn_wo_a.%d", l, gi);
|
||||
RAD_ARCH_TRY(add(&lay.cs_wo[gi], stem, lins, m.calib_stage, 4096, 4096));
|
||||
}
|
||||
}
|
||||
std::snprintf(stem, sizeof stem, "blk.%d.attn_output.input", l);
|
||||
std::snprintf(lins, sizeof lins, "blk.%d.attn_output", l);
|
||||
if (!g.attn_zero)
|
||||
RAD_ARCH_TRY(add(&lay.cs_gated, stem, lins, gated.x,
|
||||
sharded ? gated_k / g.attn_world : gated_k, gated_k, part));
|
||||
else if (sharded)
|
||||
RAD_ARCH_TRY(add(&lay.cs_gated, stem, lins, m.calib_dummy[gated_k / g.attn_world],
|
||||
gated_k / g.attn_world, gated_k, part));
|
||||
if (l == 0) {
|
||||
std::snprintf(stem, sizeof stem, "blk.0.ffn_down.input");
|
||||
const int64_t F = sharded ? 14336 / g.attn_world : 14336;
|
||||
if (!g.attn_zero)
|
||||
RAD_ARCH_TRY(add(&lay.cs_dff, stem, "blk.0.ffn_down", m.fw.ff.x, F, 14336, part));
|
||||
else if (sharded)
|
||||
RAD_ARCH_TRY(add(&lay.cs_dff, stem, "blk.0.ffn_down", m.calib_dummy[14336 / g.attn_world],
|
||||
14336 / g.attn_world, 14336, part));
|
||||
if (!g.attn_zero)
|
||||
RAD_ARCH_TRY(add(&lay.cs_ffn, "blk.0.ffn_in.input", "blk.0.ffn_gate_up", m.act.x, kEmbd,
|
||||
kEmbd));
|
||||
return RAD_OK;
|
||||
}
|
||||
if (g.attn_zero) return RAD_OK;
|
||||
std::snprintf(stem, sizeof stem, "blk.%d.ffn_in.input", l);
|
||||
std::snprintf(lins, sizeof lins, "blk.%d.ffn_gate_up_shexp,blk.%d.ffn_latent_in", l, l);
|
||||
RAD_ARCH_TRY(add(&lay.cs_ffn, stem, lins, m.act.x, kEmbd, kEmbd));
|
||||
std::snprintf(stem, sizeof stem, "blk.%d.ffn_shexp.input", l);
|
||||
std::snprintf(lins, sizeof lins, "blk.%d.ffn_down_shexp", l);
|
||||
RAD_ARCH_TRY(add(&lay.cs_sff, stem, lins, m.mw.sff.x, 2048, 2048));
|
||||
std::snprintf(stem, sizeof stem, "blk.%d.ffn_latent_out.input", l);
|
||||
std::snprintf(lins, sizeof lins, "blk.%d.ffn_latent_out", l);
|
||||
return add(&lay.cs_ln, stem, lins, m.mw.ln.x, 2048, 2048);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ one layer */
|
||||
static int connection(RadBuilder* b, Model& m, ManifoldConn& hc, const char* pre, const char* kind,
|
||||
int l, const ManifoldConn::Wire& w) {
|
||||
ManifoldConn::Config c;
|
||||
c.hc = kStreams;
|
||||
c.iterations = 20;
|
||||
c.eps = m.g.eps;
|
||||
c.hc_eps = 1e-6;
|
||||
c.eps_outside = true;
|
||||
c.split = false;
|
||||
ManifoldConn::Src s;
|
||||
s.fn = m.nm.ckpt("%s.%s_hyper_connection.mapping_proj.weight", pre, kind);
|
||||
s.fn_transposed = true;
|
||||
s.scale_parts[0] = m.nm.ckpt("%s.%s_hyper_connection.alpha_pre", pre, kind);
|
||||
s.scale_parts[1] = m.nm.ckpt("%s.%s_hyper_connection.alpha_post", pre, kind);
|
||||
s.scale_parts[2] = m.nm.ckpt("%s.%s_hyper_connection.alpha_res", pre, kind);
|
||||
s.base = m.nm.ckpt("%s.%s_hyper_connection.bias", pre, kind);
|
||||
const char* name = m.nm.f("blk.%d.hc_%s", l, kind[0] == 's' ? "attn" : "ffn");
|
||||
return hc.declare(b, m.nm, m.g, l, name, c, w, s, true);
|
||||
}
|
||||
static int norm_quant(RadBuilder* b, Model& m, const char* declared, const char* src, int l,
|
||||
rad_weight* gain, rad_op* norm, rad_op* q) {
|
||||
RAD_ARCH_TRY(map_copy(b, declared, src));
|
||||
*gain = decl_w(b, declared, RAD_F32, { kEmbd }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp_layer(l));
|
||||
if (!*gain) return RAD_E_INVAL;
|
||||
*norm = rmsnorm(b, m.g, *gain, m.x, m.act.x);
|
||||
*q = quant(b, m.g, m.act);
|
||||
return *norm && *q ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
static int layer(RadBuilder* b, Model& m, Layer& lay, int l) {
|
||||
auto& nm = m.nm;
|
||||
const auto& g = m.g;
|
||||
lay.dsa = is_dsa(l);
|
||||
const char* pre = nm.ckpt("model.layers.%d", l);
|
||||
RAD_ARCH_TRY(connection(b, m, lay.attn_hc, pre, "self_attention", l,
|
||||
{ m.h0, m.x, m.y, m.h1, m.post, m.comb }));
|
||||
if (!g.attn_zero)
|
||||
RAD_ARCH_TRY(norm_quant(b, m, nm.f("blk.%d.attn_norm.weight", l),
|
||||
nm.ckpt("%s.input_layernorm.weight", pre), l, &lay.attn_gain,
|
||||
&lay.attn_norm, &lay.attn_quant));
|
||||
const char* ap = nm.ckpt("%s.self_attn", pre);
|
||||
if (lay.dsa)
|
||||
RAD_ARCH_TRY(lay.sparse.declare(b, nm, g, l, m.dw, ap, &m.dsa_caches));
|
||||
else
|
||||
RAD_ARCH_TRY(lay.hca.declare(b, nm, g, l, m.hca_cfg, m.hw, ap, &m.hca_caches));
|
||||
// The ffn connection is declared after the attention's post: declaration order is liveness.
|
||||
RAD_ARCH_TRY(lay.attn_hc.declare_post(b));
|
||||
RAD_ARCH_TRY(connection(b, m, lay.ffn_hc, pre, "mlp", l,
|
||||
{ m.h1, m.x, m.y, m.h0, m.post, m.comb }));
|
||||
if (!(l == 0 && g.attn_zero))
|
||||
RAD_ARCH_TRY(norm_quant(b, m, nm.f("blk.%d.ffn_norm.weight", l),
|
||||
nm.ckpt("%s.post_attention_layernorm.weight", pre), l, &lay.ffn_gain,
|
||||
&lay.ffn_norm, &lay.ffn_quant));
|
||||
if (l == 0)
|
||||
RAD_ARCH_TRY(lay.dense.declare(b, nm, g, l, m.fw, nm.ckpt("%s.mlp", pre)));
|
||||
else
|
||||
RAD_ARCH_TRY(lay.moe.declare(b, nm, g, l, m.moe_cfg, m.mw,
|
||||
nm.ckpt("%s.block_sparse_moe", pre)));
|
||||
RAD_ARCH_TRY(lay.ffn_hc.declare_post(b));
|
||||
/* A drafter tap reads the layer's output: the mean of the streams after its ffn write. */
|
||||
for (int t = 0; m.draft && !g.attn_zero && t < ErnieDspark::kTaps; ++t)
|
||||
if (m.tap_at[t] == l) {
|
||||
m.op_tap[t] = ErnieDspark::decl_tap(b, g, m.h0, m.taps);
|
||||
if (!m.op_tap[t]) return RAD_E_INVAL;
|
||||
}
|
||||
return calib_sites(b, m, lay, l);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the head */
|
||||
/* The learned contraction of the four streams (mhc_head, eps outside the root), the final norm,
|
||||
* the logits in f32 and multimax over them in place. */
|
||||
static int head(RadBuilder* b, Model& m) {
|
||||
auto& g = m.g;
|
||||
auto& nm = m.nm;
|
||||
RAD_ARCH_TRY(map_transpose(b, nm.f("output_hc.fn"), nm.ckpt("model.mhc_contract.hc_head_fn")));
|
||||
const char* hc_sc = nm.ckpt("model.mhc_contract.hc_head_scale");
|
||||
RAD_ARCH_TRY(map_concat(b, nm.f("output_hc.scale"), { hc_sc, hc_sc, hc_sc, hc_sc }));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("output_hc.base"), nm.ckpt("model.mhc_contract.hc_head_base")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("output.multimax_r"), nm.ckpt("model.lm_head.multimax_ranges")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("output.multimax_t"), nm.ckpt("model.lm_head.multimax_ts")));
|
||||
m.hc_fn = decl_w(b, nm.f("output_hc.fn"), RAD_F32, { kStreams, kStreams * kEmbd },
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
m.hc_scale = decl_w(b, nm.f("output_hc.scale"), RAD_F32, { kStreams }, RAD_ACCESS_PER_TOKEN,
|
||||
RAD_SHARD_NONE, grp_model());
|
||||
m.hc_base = decl_w(b, nm.f("output_hc.base"), RAD_F32, { kStreams }, RAD_ACCESS_PER_TOKEN,
|
||||
RAD_SHARD_NONE, grp_model());
|
||||
m.mm_r = decl_w(b, nm.f("output.multimax_r"), RAD_F32, { 4 }, RAD_ACCESS_PER_TOKEN,
|
||||
RAD_SHARD_NONE, grp_model());
|
||||
m.mm_t = decl_w(b, nm.f("output.multimax_t"), RAD_F32, { 4 }, RAD_ACCESS_PER_TOKEN,
|
||||
RAD_SHARD_NONE, grp_model());
|
||||
if (!m.hc_fn || !m.hc_scale || !m.hc_base || !m.mm_r || !m.mm_t) return RAD_E_INVAL;
|
||||
m.contract = rw(b,
|
||||
RAD_OP(b, "mhc_head",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", kEmbd),
|
||||
RAD_INT("hc", kStreams), RAD_F64("eps", g.eps),
|
||||
RAD_F64("hc_eps", 1e-6), RAD_INT("eps_outside", 1),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(m.hc_fn, m.hc_scale, m.hc_base)),
|
||||
{ m.h0 }, { m.x });
|
||||
m.norm = rmsnorm(b, g, m.final_gain, m.x, m.final_hidden);
|
||||
m.gather = rw(b,
|
||||
RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", kEmbd),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.final_hidden }, { m.logit_input });
|
||||
m.head_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", kEmbd), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(m.head)),
|
||||
{ m.logit_input }, { m.logits });
|
||||
m.multimax = rw(b,
|
||||
RAD_OP(b, "multimax",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_vocab),
|
||||
RAD_STR("dtype", "f32")),
|
||||
RAD_WEIGHTS(m.mm_r, m.mm_t)),
|
||||
{ m.logits }, { m.logits });
|
||||
return m.contract && m.norm && m.gather && m.head_op && m.multimax ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the drafter */
|
||||
/* Whether the model has the bundled drafter's planes. A container converted with --max-spec 0
|
||||
* holds the trunk's tensors and none of model.mtp.*, while its config.json still names the
|
||||
* drafter (dspark_block_size), so the metadata cannot tell; the container's own names can. Asked
|
||||
* before any name map is declared: a container answers by its logical names, while a checkpoint
|
||||
* served as it stands, or a builder with no model behind it, answers neither and is taken to have
|
||||
* the drafter (the release ships model.mtp.*, and drafter() refuses a checkpoint without it). */
|
||||
static bool drafter_planes(RadBuilder* b, const char* scope) {
|
||||
Names nm(scope);
|
||||
RadEncoding e{};
|
||||
return !weight_enc(b, nm.f("token_embd.weight"), &e) ||
|
||||
weight_enc(b, nm.f("dspark.feature_proj.weight"), &e);
|
||||
}
|
||||
|
||||
/* The bundled drafter's config.json keys, each refused by name where the graph assumes the
|
||||
* release's value; `tap_at` gets the tapped trunk layers. */
|
||||
static int draft_config(const RadModelMeta* meta, const RadBuildCtx* ctx, int* tap_at) {
|
||||
const long long block = cfg(meta, "dspark_block_size", 0);
|
||||
if (block <= 0) {
|
||||
fprintf(stderr, "radiance: ernie55: --num-speculative-tokens %d; this checkpoint's config "
|
||||
"names no bundled DSpark drafter (dspark_block_size), so it serves without "
|
||||
"speculation\n", ctx->max_spec);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (ctx->max_spec != ErnieDspark::kBlock) {
|
||||
fprintf(stderr, "radiance: ernie55: --num-speculative-tokens %d; the bundled DSpark drafter "
|
||||
"proposes a block of exactly %lld tokens (dspark_block_size); run it at "
|
||||
"%lld\n", ctx->max_spec, (long long)ErnieDspark::kBlock,
|
||||
(long long)ErnieDspark::kBlock);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (ctx->max_tok < ErnieDspark::kBlock) {
|
||||
fprintf(stderr, "radiance: ernie55: a step here carries %lld tokens and one DSpark block is "
|
||||
"%lld rows; raise --max-num-batched-tokens to draft\n",
|
||||
(long long)ctx->max_tok, (long long)ErnieDspark::kBlock);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const struct {
|
||||
const char* what;
|
||||
long long got, want;
|
||||
} keys[] = { { "dspark_block_size", block, ErnieDspark::kBlock },
|
||||
{ "dspark_markov_rank", cfg(meta, "dspark_markov_rank", 0), ErnieDspark::kRank },
|
||||
{ "dspark_noise_token_id", cfg(meta, "dspark_noise_token_id", -1),
|
||||
ErnieDspark::kNoise } };
|
||||
for (const auto& k : keys)
|
||||
if (k.got != k.want) {
|
||||
fprintf(stderr, "radiance: ernie55: the drafter's %s is %lld; this plugin's DSpark graph "
|
||||
"is the release's, where it is %lld\n", k.what, k.got, k.want);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
int ids[ErnieDspark::kTaps + 1] = {};
|
||||
const int n = parse_layer_ids(rad_meta_gets(meta, "dspark_target_layer_ids", nullptr), kLayers,
|
||||
ids, ErnieDspark::kTaps + 1);
|
||||
for (int t = 0; t < ErnieDspark::kTaps; ++t) tap_at[t] = ids[t];
|
||||
if (n != ErnieDspark::kTaps || ids[0] != 40 || ids[1] != 41 || ids[2] != 42) {
|
||||
fprintf(stderr, "radiance: ernie55: the drafter's dspark_target_layer_ids are not [40, 41, "
|
||||
"42]; its feature projection reads the outputs of those three layers\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The drafter's graph over the trunk's wires, and its declaration to the core: a block of seven
|
||||
* rows, every one predicting (block = depth), the noise id in every row after the anchor, and its
|
||||
* attention's 128-key window behind the anchor. */
|
||||
static int drafter(RadBuilder* b, Model& m) {
|
||||
auto& nm = m.nm;
|
||||
ErnieDspark::Trunk t{};
|
||||
t.h0 = m.h0; t.h1 = m.h1; t.x = m.x; t.y = m.y; t.post = m.post; t.comb = m.comb;
|
||||
t.act = m.act;
|
||||
t.hw = m.hw;
|
||||
t.mw = m.mw;
|
||||
t.moe_cfg = m.moe_cfg;
|
||||
t.token = m.token; t.head = m.head; t.mm_r = m.mm_r; t.mm_t = m.mm_t;
|
||||
t.taps = m.taps;
|
||||
ErnieDspark::Config c{};
|
||||
c.base_layer = (int)kLayers;
|
||||
RAD_ARCH_TRY(m.ds.declare(b, nm, m.g, c, t));
|
||||
/* A checkpoint without model.mtp.* (a container without it was refused in declare, before
|
||||
* anything was declared). */
|
||||
RadEncoding e{};
|
||||
const char* mtp_probe = m.g.attn_zero ? nm.f("dspark.norm.weight")
|
||||
: nm.f("dspark.feature_proj.weight");
|
||||
if (weight_enc(b, nm.f("token_embd.weight"), &e) && !weight_enc(b, mtp_probe, &e)) {
|
||||
fprintf(stderr, "radiance: ernie55: the model holds no model.mtp.feature_projection; "
|
||||
"serve it with --num-speculative-tokens 0, or convert the checkpoint with "
|
||||
"its bundled drafter to speculate\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
RadDrafterDecl d{};
|
||||
d.name = "dspark-ernie55";
|
||||
d.kind = RAD_DRAFT_BLOCK;
|
||||
d.depth = (int)ErnieDspark::kBlock;
|
||||
d.block = ErnieDspark::kBlock;
|
||||
d.proposal = m.ds.proposal();
|
||||
d.proposal_pitch = ErnieDspark::kBlock;
|
||||
d.window = ErnieDspark::kWindow;
|
||||
d.mask_token = ErnieDspark::kNoise;
|
||||
return rad_declare_drafter(b, &d);
|
||||
}
|
||||
|
||||
/* Hot-first expert parallelism (with --expert-profile, under an attention-free rank).
|
||||
*
|
||||
* The attention-free rank (rank 2 at TP3) holds its experts in VRAM, while the attention ranks keep
|
||||
* about half of theirs in the pinned host pool and read every miss across PCIe on the step's
|
||||
* critical path. An index range hands the attention-free rank arbitrary experts. Instead, each
|
||||
* layer's experts are ranked by the profile's share of selections (ties to the lower expert) and
|
||||
* the attention-free ranks take the hottest, as many as their counts; the attention ranks are
|
||||
* dealt the rest in heat order, each next expert to the rank least full for its count, so their
|
||||
* colder sets need fewer host reads and split them evenly. The extra routings on the
|
||||
* attention-free rank read VRAM, and that rank runs no attention.
|
||||
*
|
||||
* Experts are labels: label j of a layer is model expert order[j], and rank r keeps the label
|
||||
* window ep_split gives it. ErnieMoe loads the router rows, bias and scale in label order, so every
|
||||
* label scores exactly as its expert does; the routing differs from the model's numbering only in
|
||||
* an exact tie of two scores, which the selection breaks to the lower label. Each layer with no
|
||||
* profile entries keeps its numbering. Returns with `order` empty when nothing is relabelled. */
|
||||
static int ep_split(int rank, int world, const char* spec, int64_t* base, int64_t* count);
|
||||
static int ep_order(RadBuilder* b, const Model& m, int world, const char* split_spec,
|
||||
std::vector<std::vector<int32_t>>* order) {
|
||||
order->clear();
|
||||
const Geom& g = m.g;
|
||||
if (world < 2 || g.attn_world >= world) return RAD_OK;
|
||||
std::vector<int64_t> base((size_t)world), count((size_t)world);
|
||||
for (int r = 0; r < world; ++r)
|
||||
RAD_ARCH_TRY(ep_split(r, world, split_spec, &base[(size_t)r], &count[(size_t)r]));
|
||||
const int n_layer = (int)kLayers + (m.draft ? (int)ErnieDspark::kStages : 0);
|
||||
std::vector<float> share((size_t)kExperts);
|
||||
bool any = false;
|
||||
for (int l = 1; l < n_layer; ++l) {
|
||||
const int st = rad_expert_profile(b, l, share.data(), kExperts);
|
||||
if (st == RAD_E_NOTFOUND) continue;
|
||||
if (st < 0) return st;
|
||||
std::vector<int32_t> hot((size_t)kExperts);
|
||||
for (int32_t e = 0; e < (int32_t)kExperts; ++e) hot[(size_t)e] = e;
|
||||
std::stable_sort(hot.begin(), hot.end(), [&](int32_t a, int32_t c) {
|
||||
return share[(size_t)a] > share[(size_t)c];
|
||||
});
|
||||
std::vector<std::vector<int32_t>> held((size_t)world);
|
||||
size_t next = 0;
|
||||
for (int r = g.attn_world; r < world; ++r)
|
||||
while ((int64_t)held[(size_t)r].size() < count[(size_t)r])
|
||||
held[(size_t)r].push_back(hot[next++]);
|
||||
for (; next < hot.size(); ++next) {
|
||||
int pick = -1;
|
||||
for (int r = 0; r < g.attn_world; ++r) {
|
||||
const int64_t have = (int64_t)held[(size_t)r].size();
|
||||
if (have >= count[(size_t)r]) continue;
|
||||
/* least full for its count: have/count below the pick's, ties to the lower rank */
|
||||
if (pick < 0 || have * count[(size_t)pick] <
|
||||
(int64_t)held[(size_t)pick].size() * count[(size_t)r])
|
||||
pick = r;
|
||||
}
|
||||
if (pick < 0) return RAD_E_INVAL;
|
||||
held[(size_t)pick].push_back(hot[next]);
|
||||
}
|
||||
if (order->empty()) order->assign((size_t)n_layer, {});
|
||||
std::vector<int32_t>& o = (*order)[(size_t)l];
|
||||
o.assign((size_t)kExperts, -1);
|
||||
for (int r = 0; r < world; ++r)
|
||||
for (size_t i = 0; i < held[(size_t)r].size(); ++i)
|
||||
o[(size_t)(base[(size_t)r] + (int64_t)i)] = held[(size_t)r][i];
|
||||
any = true;
|
||||
}
|
||||
if (!any) order->clear();
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ declare */
|
||||
static bool world_ok(int world) {
|
||||
return world == 1 || world == 2 || world == 3 || world == 4 || world == 8;
|
||||
}
|
||||
/* Partition 512 routed experts into `world` contiguous even-sized slices (ErnieMoe requires
|
||||
* even counts per rank): `--expert-split` (`ctx->expert_split`, e.g. `204,204,104` at TP3)
|
||||
* overrides per-rank counts via `rad_expert_split`; otherwise 256 pairs split remainder-first ->
|
||||
* TP3 gives 172, 170, 170; TP1/2/4/8 stay exact 512 / 256 / 128 / 64. */
|
||||
static int ep_split(int rank, int world, const char* spec, int64_t* base, int64_t* count) {
|
||||
bool given = false;
|
||||
if (rad_expert_split(kExperts, world, rank, 2, spec, count, base, &given)) return RAD_OK;
|
||||
if (given) {
|
||||
fprintf(stderr, "radiance: ernie55: --expert-split '%s' must be %d comma-separated "
|
||||
"even counts >= 2 summing to %lld\n",
|
||||
spec ? spec : "", world, (long long)kExperts);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const int64_t pairs = kExperts / 2;
|
||||
const int64_t q = pairs / world, rem = pairs % world;
|
||||
const int64_t before = rank * q + (rank < rem ? rank : rem);
|
||||
const int64_t mine = q + (rank < rem ? 1 : 0);
|
||||
*base = 2 * before;
|
||||
*count = 2 * mine;
|
||||
return RAD_OK;
|
||||
}
|
||||
static int geometry(Geom& g, const RadModelMeta* meta, const RadBuildCtx* ctx, int world) {
|
||||
g.n_layer = kLayers;
|
||||
g.n_embd = kEmbd;
|
||||
g.head_dim = 512;
|
||||
g.n_head_all = g.n_head = 64;
|
||||
g.n_head_kv_all = g.n_head_kv = 1;
|
||||
g.n_ff_all = g.n_ff = 14336;
|
||||
g.n_vocab_all = kVocab;
|
||||
g.n_vocab = shard_extent(kVocab, world, ctx->rank);
|
||||
g.vocab_off = shard_begin(kVocab, world, ctx->rank);
|
||||
g.rank = ctx->rank;
|
||||
g.world = world;
|
||||
/* The attention world (Geom::attn_world): the largest world that divides the 8 output groups
|
||||
* (wo_a), at most `world`. At TP3 that is ranks 0 and 1, which split the output path; rank 2
|
||||
* is attention-zero (no attention weights, no KV, a zero into the reduce) and spends its card
|
||||
* on experts. A third attention rank would only replicate the heads: neither 64 heads nor 8
|
||||
* groups divide by 3. */
|
||||
g.attn_world = world;
|
||||
while (8 % g.attn_world) --g.attn_world;
|
||||
g.attn_zero = ctx->rank >= g.attn_world;
|
||||
g.attn_rank = g.attn_zero ? g.attn_world - 1 : ctx->rank;
|
||||
if (g.attn_world < world && ctx->rank == 0 && !ctx->shape_probe)
|
||||
fprintf(stderr, "radiance: ernie55: world_size = %d: attention on %d rank(s), rank(s) "
|
||||
"%d..%d carry no attention and hold experts only\n",
|
||||
world, g.attn_world, g.attn_world, world - 1);
|
||||
g.max_tok = ctx->max_tok;
|
||||
g.max_ctx = ctx->max_ctx;
|
||||
g.max_seqs = ctx->max_seqs;
|
||||
g.max_spec = ctx->max_spec;
|
||||
g.kv_resident = ctx->kv_resident_blocks;
|
||||
g.max_logit_rows = std::min<int64_t>(g.max_tok, g.max_seqs * (g.max_spec + 1));
|
||||
if (ctx->max_out_rows > g.max_logit_rows) g.max_logit_rows = ctx->max_out_rows;
|
||||
g.eps = meta->rms_eps;
|
||||
g.kv_dtype = "bf16";
|
||||
g.wire_exact = !ctx->tp_wire_lossy;
|
||||
g.wire_min_bytes = ctx->tp_wire_min_bytes;
|
||||
g.i8_group = RAD_I8_GROUP_WIDE;
|
||||
return g.max_tok < 1 || g.max_ctx < 1 || g.max_seqs < 1 || g.eps <= 0 ? RAD_E_INVAL : RAD_OK;
|
||||
}
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx || ctx->is_draft || ctx->rank < 0 || ctx->rank >= MAX_RANKS ||
|
||||
rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
const int world = ctx->world_size ? ctx->world_size : 1;
|
||||
if (!world_ok(world)) {
|
||||
fprintf(stderr, "radiance: ernie55: --tp %d; the expert split of this plugin is built for "
|
||||
"1, 2, 3, 4 or 8 ranks\n", world);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* The graph is written for the released ERNIE-5.5-Flash and reads none of these from the
|
||||
* checkpoint, so a checkpoint that differs in any of them is refused by name. */
|
||||
const struct {
|
||||
const char* what;
|
||||
int64_t got, want;
|
||||
} shape[] = { { "hidden_size", meta->n_embd, kEmbd },
|
||||
{ "num_hidden_layers", meta->n_layers, kLayers },
|
||||
{ "vocab_size", meta->n_vocab, kVocab },
|
||||
{ "hc_mult", cfg(meta, "hc_mult", 0), kStreams },
|
||||
{ "n_routed_experts", cfg(meta, "n_routed_experts", 0), kExperts },
|
||||
{ "num_experts_per_tok", cfg(meta, "num_experts_per_tok", 0), 10 },
|
||||
{ "moe_latent_size", cfg(meta, "moe_latent_size", 0), 2048 },
|
||||
{ "first_k_dense_replace", cfg(meta, "first_k_dense_replace", 0), 1 },
|
||||
{ "index_topk", cfg(meta, "index_topk", 0), 2048 },
|
||||
{ "sliding_window", cfg(meta, "sliding_window", 0), 128 } };
|
||||
for (const auto& s : shape)
|
||||
if (s.got != s.want) {
|
||||
fprintf(stderr, "radiance: ernie55: the checkpoint's %s is %lld; this plugin serves the "
|
||||
"ERNIE-5.5-Flash geometry, where it is %lld\n",
|
||||
s.what, (long long)s.got, (long long)s.want);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
int tap_at[ErnieDspark::kTaps] = {};
|
||||
/* Speculation off declares nothing of the drafter: none of its ~9.6 GiB is placed or loaded.
|
||||
* On, the container must carry it; that is checked before its depth, since a container
|
||||
* without it serves no depth but 0. */
|
||||
if (ctx->max_spec > 0 && !drafter_planes(b, ctx->scope)) {
|
||||
fprintf(stderr, "radiance: ernie55: --num-speculative-tokens %d; this container was "
|
||||
"converted without the bundled DSpark drafter (it holds no dspark.* "
|
||||
"weights: rad-convert --max-spec 0), so it serves with speculation off only "
|
||||
"-- --num-speculative-tokens 0. Convert the checkpoint with its drafter to "
|
||||
"speculate\n", ctx->max_spec);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (ctx->max_spec > 0) RAD_ARCH_TRY(draft_config(meta, ctx, tap_at));
|
||||
if (ctx->kv_dtype && ctx->kv_dtype != RAD_BF16) {
|
||||
fprintf(stderr, "radiance: ernie55: --kv-cache-dtype %s; this plugin serves its caches in "
|
||||
"bf16 only\n",
|
||||
rad_dtype_name(ctx->kv_dtype));
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
auto& slot = ctx->shape_probe ? probe_model : models[rad_build_slot(ctx)];
|
||||
slot = std::make_unique<Model>();
|
||||
auto& m = *slot;
|
||||
auto& g = m.g;
|
||||
m.nm = Names(ctx->scope);
|
||||
auto& nm = m.nm;
|
||||
m.draft = ctx->max_spec > 0;
|
||||
for (int t = 0; t < ErnieDspark::kTaps; ++t) m.tap_at[t] = tap_at[t];
|
||||
RAD_ARCH_TRY(geometry(g, meta, ctx, world));
|
||||
/* A shape probe may pass rank >= world; it then declares rank 0's window. */
|
||||
const int ep_rank = g.rank < g.world ? g.rank : 0;
|
||||
RAD_ARCH_TRY(ep_split(ep_rank, world, ctx->expert_split, &m.moe_cfg.expert_base,
|
||||
&m.moe_cfg.n_expert));
|
||||
RAD_ARCH_TRY(ep_order(b, m, world, ctx->expert_split, &m.ep_order));
|
||||
m.moe_cfg.order = m.ep_order.empty() ? nullptr : &m.ep_order;
|
||||
if (!m.ep_order.empty() && ctx->rank == 0 && !ctx->shape_probe)
|
||||
fprintf(stderr, "radiance: ernie55: experts split hot-first by --expert-profile: rank(s) "
|
||||
"%d..%d hold each layer's hottest, ranks 0..%d share the rest by heat\n",
|
||||
g.attn_world, world - 1, g.attn_world - 1);
|
||||
m.moe_cfg.rows = std::min<int64_t>(g.max_tok, 1024);
|
||||
m.moe_cfg.reduce = world > 1;
|
||||
/* Probe the trunk's encoding from layer 1's latent-in projection. Supports IQ8R (group 256)
|
||||
* and the release's block-FP8 trunk (fp8_e4m3*bf16[128x128]); other formats are refused. */
|
||||
m.layers.resize(kLayers);
|
||||
{
|
||||
const char* pn = nm.f("blk.1.ffn_latent_in.weight");
|
||||
RAD_ARCH_TRY(map_linear(
|
||||
b, pn, { nm.ckpt("model.layers.1.block_sparse_moe.fc1_latent_proj.weight") }));
|
||||
m.layers[1].moe.fc1.mapped = true;
|
||||
RadEncoding enc{};
|
||||
const bool known = weight_enc(b, pn, &enc);
|
||||
const char* retired = known ? linear_retired(enc) : nullptr;
|
||||
if (!known || linear_is_iq8r(enc)) {
|
||||
g.i8_group = RAD_I8_GROUP_WIDE;
|
||||
g.native_fp = false;
|
||||
} else if (retired && std::strcmp(retired, "block fp8") == 0) {
|
||||
g.i8_group = 0;
|
||||
g.native_fp = true;
|
||||
} else {
|
||||
char en[256];
|
||||
rad_enc_format(&enc, en, sizeof en);
|
||||
fprintf(stderr, "radiance: ernie55: '%s' is stored as %s (%s); this build serves "
|
||||
"ERNIE-5.5 with an IQ8R trunk (data/recipes/ernie55-iq8r.recipe) or a "
|
||||
"block-FP8 trunk (data/recipes/ernie55-native.recipe)\n",
|
||||
pn, retired ? retired : "an unsupported format", en);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
}
|
||||
RAD_ARCH_TRY(stream_buffers(b, m));
|
||||
RAD_ARCH_TRY(block_wires(b, m));
|
||||
RAD_ARCH_TRY(calib_begin(b, m, ctx));
|
||||
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.weight"), nm.ckpt("lm_head.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("model.norm.weight")));
|
||||
m.token = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, { g.n_vocab, kEmbd }, RAD_ACCESS_VOCAB,
|
||||
RAD_SHARD_ROW, grp_model());
|
||||
m.head = decl_w(b, nm.f("output.weight"), RAD_BF16, { g.n_vocab, kEmbd }, RAD_ACCESS_VOCAB,
|
||||
RAD_SHARD_ROW, grp_model());
|
||||
m.final_gain = decl_w(b, nm.f("output_norm.weight"), RAD_F32, { kEmbd }, RAD_ACCESS_PER_TOKEN,
|
||||
RAD_SHARD_NONE, grp_model());
|
||||
if (!m.token || !m.head || !m.final_gain) return RAD_E_INVAL;
|
||||
m.embed = rw(b,
|
||||
RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", kEmbd),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
|
||||
RAD_INT("vocab_offset", g.vocab_off)),
|
||||
RAD_WEIGHTS(m.token)),
|
||||
{}, { m.x });
|
||||
m.embed_ar = GlmTp::reduce(b, g, m.x, true);
|
||||
if (g.attn_world < g.world) {
|
||||
m.attn_ar = GlmTp::reduce(b, g, m.y, true);
|
||||
if (!m.attn_ar) return RAD_E_INVAL;
|
||||
if (g.attn_zero) {
|
||||
m.zero_y = rw(b, RAD_OP(b, "fill",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", kEmbd),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, { m.y });
|
||||
if (!m.zero_y) return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
m.expand = copy(b, g, m.x, m.h0);
|
||||
for (int l = 0; l < kLayers; ++l) RAD_ARCH_TRY(layer(b, m, m.layers[l], l));
|
||||
/* Every rank keeps every paged cache whole when all ranks run attention (the trunk is
|
||||
* replicated); under attn_world < world (expert-only rank 2) mark all 5 paged groups zero on
|
||||
* rank 2 and skip replicated so TierExec lays out per-rank windows cleanly. */
|
||||
for (rad_kvgroup k : { m.hca_caches.raw, m.hca_caches.comp,
|
||||
m.dsa_caches.latent, m.dsa_caches.index })
|
||||
if (k) {
|
||||
if (g.attn_world == g.world)
|
||||
RAD_ARCH_TRY(rad_kv_group_replicated(b, k));
|
||||
else if (g.attn_zero)
|
||||
RAD_ARCH_TRY(rad_kv_group_zero(b, k));
|
||||
}
|
||||
RAD_ARCH_TRY(head(b, m));
|
||||
if (m.draft) RAD_ARCH_TRY(drafter(b, m));
|
||||
rad_note(b, "ERNIE-5.5-Flash: TP%d, 43 mHC layers, 37 HCA + 6 DSA, MXFP4 experts (%lld a rank) "
|
||||
"under %s, %s",
|
||||
world, (long long)m.moe_cfg.n_expert,
|
||||
g.i8_group ? "an IQ8R trunk" : "a block-FP8 trunk",
|
||||
m.draft ? "the bundled DSpark drafter (block 7)" : "no drafter");
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ step */
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
auto& m = *models[rad_slot(c)];
|
||||
/* A drafter pass: negative is the context pass over the rows the trunk step just ran,
|
||||
* positive the query pass over [anchor, noise x 6]. */
|
||||
if (batch->draft_pass != 0) {
|
||||
if (!m.draft) {
|
||||
rad_step_fail(c, "ernie55: a draft pass, and this program declares no drafter");
|
||||
return;
|
||||
}
|
||||
if (batch->draft_pass < 0) m.ds.context(c, batch);
|
||||
else m.ds.step(c, batch);
|
||||
return;
|
||||
}
|
||||
const int64_t T = batch->n_tok;
|
||||
RAD_ISSUE_N(c, m.embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(m.token), brows(m.x, T));
|
||||
if (m.embed_ar) RAD_ISSUE_N(c, m.embed_ar, T * kEmbd, brows(m.x, T), RAD_NONE);
|
||||
for (int i = 0; i < kStreams; ++i)
|
||||
RAD_ISSUE_N(c, m.expand, T, brows(m.x, T), bcol(m.h0, i * kEmbd, kEmbd, T));
|
||||
for (int i = 0; i < kLayers; ++i) {
|
||||
auto& l = m.layers[i];
|
||||
l.attn_hc.read(c, T);
|
||||
if (m.zero_y) {
|
||||
RAD_ISSUE_N(c, m.zero_y, T, brows(m.y, T));
|
||||
} else {
|
||||
RAD_ISSUE_N(c, l.attn_norm, T, brows(m.x, T), RAD_W(l.attn_gain), brows(m.act.x, T));
|
||||
RAD_ISSUE_N(c, l.attn_quant, T, brows(m.act.x, T), brows(m.act.cq(), T),
|
||||
brows(m.act.cs(), T));
|
||||
if (l.dsa)
|
||||
l.sparse.step(c, batch);
|
||||
else
|
||||
l.hca.step(c, batch);
|
||||
if (l.cs_in >= 0) m.calib.tap(c, (size_t)l.cs_in, T);
|
||||
if (l.cs_cq >= 0) m.calib.tap(c, (size_t)l.cs_cq, T);
|
||||
for (int gi = 0; gi < 8; ++gi)
|
||||
if (l.cs_wo[gi] >= 0) {
|
||||
RAD_ISSUE_N(c, m.calib_copy, T, bcol(m.hw.o_mix, (int64_t)gi * 4096, 4096, T),
|
||||
brows(m.calib_stage, T));
|
||||
m.calib.tap(c, (size_t)l.cs_wo[gi], T);
|
||||
}
|
||||
}
|
||||
/* The split inputs join their gather on every rank, before the attention all_reduce. */
|
||||
if (l.cs_gated >= 0) m.calib.tap(c, (size_t)l.cs_gated, T);
|
||||
if (m.attn_ar) RAD_ISSUE_N(c, m.attn_ar, T * kEmbd, brows(m.y, T), RAD_NONE);
|
||||
l.attn_hc.write(c, T);
|
||||
l.ffn_hc.read(c, T);
|
||||
if (i == 0) {
|
||||
if (m.zero_y) {
|
||||
RAD_ISSUE_N(c, m.zero_y, T, brows(m.y, T));
|
||||
} else {
|
||||
RAD_ISSUE_N(c, l.ffn_norm, T, brows(m.x, T), RAD_W(l.ffn_gain), brows(m.act.x, T));
|
||||
RAD_ISSUE_N(c, l.ffn_quant, T, brows(m.act.x, T), brows(m.act.cq(), T),
|
||||
brows(m.act.cs(), T));
|
||||
l.dense.step(c, batch);
|
||||
if (l.cs_ffn >= 0) m.calib.tap(c, (size_t)l.cs_ffn, T);
|
||||
}
|
||||
if (l.cs_dff >= 0) m.calib.tap(c, (size_t)l.cs_dff, T);
|
||||
if (m.attn_ar) RAD_ISSUE_N(c, m.attn_ar, T * kEmbd, brows(m.y, T), RAD_NONE);
|
||||
} else {
|
||||
RAD_ISSUE_N(c, l.ffn_norm, T, brows(m.x, T), RAD_W(l.ffn_gain), brows(m.act.x, T));
|
||||
RAD_ISSUE_N(c, l.ffn_quant, T, brows(m.act.x, T), brows(m.act.cq(), T),
|
||||
brows(m.act.cs(), T));
|
||||
l.moe.step(c, batch);
|
||||
if (l.cs_ffn >= 0) m.calib.tap(c, (size_t)l.cs_ffn, T);
|
||||
if (l.cs_sff >= 0) m.calib.tap(c, (size_t)l.cs_sff, T);
|
||||
if (l.cs_ln >= 0) m.calib.tap(c, (size_t)l.cs_ln, T);
|
||||
}
|
||||
l.ffn_hc.write(c, T);
|
||||
for (int t = 0; m.draft && !m.g.attn_zero && t < ErnieDspark::kTaps; ++t)
|
||||
if (m.tap_at[t] == i) ErnieDspark::issue_tap(c, m.op_tap[t], m.h0, m.taps, t, T);
|
||||
}
|
||||
RAD_ISSUE_N(c, m.contract, T, brows(m.h0, T), RAD_W(m.hc_fn), RAD_W(m.hc_scale),
|
||||
RAD_W(m.hc_base), brows(m.x, T));
|
||||
RAD_ISSUE_N(c, m.norm, T, brows(m.x, T), RAD_W(m.final_gain), brows(m.final_hidden, T));
|
||||
if (batch->n_out > 0) {
|
||||
const int64_t R = batch->n_out;
|
||||
RAD_ISSUE_N(c, m.gather, R, brows(m.final_hidden, T), praw(batch->out_ids, RAD_I32, R),
|
||||
brows(m.logit_input, R));
|
||||
RAD_ISSUE_N(c, m.head_op, R, brows(m.logit_input, R), RAD_W(m.head), brows(m.logits, R));
|
||||
RAD_ISSUE_N(c, m.multimax, R, brows(m.logits, R), RAD_W(m.mm_r), RAD_W(m.mm_t),
|
||||
brows(m.logits, R));
|
||||
}
|
||||
m.calib.after_step(c, T);
|
||||
}
|
||||
/* The bundled drafter's depth: its block, and only that (it denoises exactly seven rows). */
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
out->shape_probe_ok = 1;
|
||||
out->draft_depth = 0;
|
||||
out->draft_depth_fixed = 0;
|
||||
const long long block = cfg(meta, "dspark_block_size", 0);
|
||||
if (block > 0) {
|
||||
out->draft_depth = (int)block;
|
||||
out->draft_depth_fixed = 1;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
inline const RadChatFormat* chat_format(const RadModelMeta*) { return ernie55_chat_format(); }
|
||||
} // namespace ernie55
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(ernie55)
|
||||
RAD_ARCH_CHAT_FORMAT(ernie55)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(ernie55, "ernie55", "", "0.1.0",
|
||||
"ERNIE-5.5-Flash IQ8R trunk + MXFP4 experts, mHC/HCA/DSA, latent MoE")
|
||||
#endif
|
||||
+68
-123
@@ -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 */
|
||||
@@ -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;
|
||||
}
|
||||
@@ -1910,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);
|
||||
@@ -1975,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) {
|
||||
@@ -2356,7 +2301,7 @@ extern "C" int64_t rad_arch_text_prepare(int field, const char* in, char* out, i
|
||||
/* 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
|
||||
+29
-47
@@ -15,7 +15,7 @@
|
||||
* 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 (MoeFP8::a8), as qwen35moe_w8a8 serves Qwen3.6-35B-A3B;
|
||||
* 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.
|
||||
@@ -24,17 +24,13 @@
|
||||
*/
|
||||
#include <arch/rad_arch.h>
|
||||
#include "flint_attention.h"
|
||||
#include <arch/rad_block_mlp_fp8.h>
|
||||
#include <arch/rad_block_moe_fp8.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 <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace flint {
|
||||
@@ -44,8 +40,8 @@ struct Layer {
|
||||
bool dense = false;
|
||||
bool sliding = false;
|
||||
FlintAttn attn{};
|
||||
MlpFP8 dense_mlp{};
|
||||
MoeFP8 moe{};
|
||||
MlpQ dense_mlp{};
|
||||
MoeQ moe{};
|
||||
};
|
||||
|
||||
struct Model {
|
||||
@@ -54,20 +50,20 @@ struct Model {
|
||||
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_fp8.h's trunk_rotation. */
|
||||
* rad_linear.h's trunk_rotation. */
|
||||
bool trunk_rot = false;
|
||||
int64_t trunk_g8 = RAD_FP8_BLOCK;
|
||||
int64_t trunk_g8 = RAD_SCALE_GROUP;
|
||||
|
||||
rad_buf x = 0, h_out = 0, logits = 0;
|
||||
ActFP8 h{};
|
||||
ActQ h{};
|
||||
/* The routed experts' rotated int8 copy of the block input, where a rotated trunk's norms do
|
||||
* not write the codes themselves (MoeFP8::Wire::hr). */
|
||||
ActFP8 hr{};
|
||||
* not write the codes themselves (MoeQ::Wire::hr). */
|
||||
ActQ hr{};
|
||||
rad_buf q = 0, k = 0, v = 0;
|
||||
ActFP8 attn{};
|
||||
ActQ attn{};
|
||||
rad_buf dense_gate_up = 0;
|
||||
ActFP8 dense_ffn{};
|
||||
MoeFP8::Wire mw{};
|
||||
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;
|
||||
@@ -123,15 +119,6 @@ static int check_model(const RadModelMeta* meta, const Geom& g, Model& m) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static void block_slice_128(int64_t width, int world, int rank, int64_t* lo, int64_t* hi) {
|
||||
const int64_t blocks = width / RAD_FP8_BLOCK;
|
||||
const int64_t base = blocks / world, rem = blocks % world;
|
||||
const int64_t first = rank * base + std::min<int64_t>(rank, rem);
|
||||
const int64_t count = base + (rank < rem ? 1 : 0);
|
||||
*lo = first * RAD_FP8_BLOCK;
|
||||
*hi = (first + count) * RAD_FP8_BLOCK;
|
||||
}
|
||||
|
||||
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)
|
||||
@@ -183,7 +170,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
|
||||
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_fp8.h's trunk_rotation
|
||||
/* 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"),
|
||||
@@ -194,7 +181,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
trunk_rotation(enc, &m.trunk_g8);
|
||||
}
|
||||
|
||||
MoeFP8::Config mc{};
|
||||
MoeQ::Config mc{};
|
||||
mc.n_expert_all = n_expert_all;
|
||||
mc.n_expert = n_expert_local;
|
||||
mc.expert_base = n_expert_local * g.rank;
|
||||
@@ -216,11 +203,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
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 (MoeFP8::declare checks each layer's own). */
|
||||
* expert; every layer is declared with it (MoeQ::declare checks each layer's own). */
|
||||
const int64_t l_moe = 2;
|
||||
MoeFP8::Src probe_src{};
|
||||
MoeQ::Src probe_src{};
|
||||
probe_src.experts = nm.ckpt("model.layers.%lld.mlp.experts", (long long)l_moe);
|
||||
RAD_ARCH_TRY(MoeFP8::probe(b, nm, (int)l_moe, probe_src, &mc));
|
||||
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 "
|
||||
@@ -249,11 +236,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
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_FP8_BLOCK));
|
||||
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_FP8_BLOCK));
|
||||
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});
|
||||
@@ -261,7 +248,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
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_FP8_BLOCK));
|
||||
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});
|
||||
@@ -288,9 +275,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
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 (MoeFP8::a8). */
|
||||
* 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_FP8_BLOCK));
|
||||
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));
|
||||
@@ -301,8 +288,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
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 LinearFP8 (which then maps it once). */
|
||||
LinearFP8& sd = m.layers[(size_t)l_moe].moe.sh_down;
|
||||
* 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) }));
|
||||
@@ -340,16 +327,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_WEIGHTS(m.token)),
|
||||
{}, {m.x});
|
||||
if (g.world > 1)
|
||||
m.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.x}, {m.x});
|
||||
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;
|
||||
MlpFP8::Wire dw{};
|
||||
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) {
|
||||
@@ -385,7 +367,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
}
|
||||
|
||||
if (lay.dense) {
|
||||
MlpFP8::Src ds{};
|
||||
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);
|
||||
@@ -399,7 +381,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
return status;
|
||||
}
|
||||
} else {
|
||||
MoeFP8::Src ms{};
|
||||
MoeQ::Src ms{};
|
||||
ms.cfg = mc;
|
||||
const char* mlp = nm.ckpt("%s.mlp", pre);
|
||||
ms.norm = nm.ckpt("%s.post_attention_layernorm.weight", pre);
|
||||
|
||||
@@ -16,11 +16,9 @@
|
||||
#ifndef FLINT_ATTENTION_H
|
||||
#define FLINT_ATTENTION_H
|
||||
|
||||
#include <arch/rad_fp8.h>
|
||||
#include <arch/rad_linear.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
namespace rad {
|
||||
@@ -29,11 +27,11 @@ namespace arch {
|
||||
struct FlintAttn {
|
||||
struct Wire {
|
||||
rad_buf x = 0; /* [max_tok, n_embd] residual stream */
|
||||
ActFP8 h{}; /* [max_tok, n_embd] normed input, then o output */
|
||||
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] */
|
||||
ActFP8 attn{}; /* [max_tok, q_dim] attention output */
|
||||
ActQ attn{}; /* [max_tok, q_dim] attention output */
|
||||
};
|
||||
|
||||
struct Src {
|
||||
@@ -56,15 +54,15 @@ struct FlintAttn {
|
||||
rad_kvgroup kv = 0;
|
||||
|
||||
rad_weight w_norm = 0, w_q_norm = 0, w_k_norm = 0, w_sink = 0;
|
||||
LinearFP8 q{}, k{}, v{}, o{};
|
||||
NormQuantFP8 nq_h{};
|
||||
QuantFP8 q_attn{};
|
||||
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 (NormQuantFP8::fuse_ar), so
|
||||
/* 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;
|
||||
@@ -196,20 +194,14 @@ inline int FlintAttn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
}
|
||||
|
||||
/* The out projection's input codes: where the model feeds them (a rotated int8 trunk,
|
||||
* ActFP8::q8_fed), q_attn writes had_quant_act_i8g's pair and the projection declares no
|
||||
* 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 (LinearFP8 refuses the E4M3-pair formats), so no quantiser runs here. */
|
||||
* 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 = 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",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
|
||||
+23
-75
@@ -37,7 +37,7 @@
|
||||
*
|
||||
* ============================== 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. That projection also says whether the
|
||||
* linears are rotated int8 (IQ8R): the activations they read then carry int8 codes in place of the
|
||||
@@ -52,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>
|
||||
@@ -102,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;
|
||||
@@ -114,12 +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). */
|
||||
QuantFP8 q_n{};
|
||||
QuantAct q_n{};
|
||||
rad_op op_n = 0, op_qkr = 0, op_attn = 0, op_sum = 0, op_ar = 0;
|
||||
};
|
||||
|
||||
@@ -144,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 */
|
||||
@@ -176,14 +175,14 @@ 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_FP8_BLOCK;
|
||||
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;
|
||||
@@ -201,63 +200,13 @@ struct Model {
|
||||
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
/* 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,
|
||||
int64_t rows, rad_buf in, rad_buf out, rad_weight* w, int access, int group) {
|
||||
*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 */
|
||||
@@ -377,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),
|
||||
@@ -395,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",
|
||||
@@ -556,7 +505,8 @@ static int declare_block(RadBuilder* b, Model& m, Block& B, const char* pre, con
|
||||
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", m.norm_i8 ? m.g8 : RAD_FP8_BLOCK),
|
||||
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)
|
||||
@@ -610,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;
|
||||
}
|
||||
|
||||
@@ -961,7 +911,7 @@ 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",
|
||||
@@ -971,7 +921,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
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 (ActFP8::declare_pair). */
|
||||
* 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);
|
||||
}
|
||||
@@ -1154,7 +1104,7 @@ 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 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) {
|
||||
@@ -1180,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);
|
||||
@@ -1265,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) {
|
||||
|
||||
+54
-729
File diff suppressed because it is too large.
Load diff
+1562
-182
File diff suppressed because it is too large.
Load diff
@@ -20,6 +20,7 @@
|
||||
#include <arch/rad_block_gemma4_audio.h>
|
||||
#include <arch/rad_block_gemma4_unified.h>
|
||||
#include <arch/rad_block_gemma4_vision.h>
|
||||
#include <arch/rad_block_hc.h>
|
||||
#include <arch/rad_gemma4_chat.h>
|
||||
#include <arch/rad_gemma4_dflash.h>
|
||||
#include <arch/rad_block_dflash2.h>
|
||||
@@ -65,15 +66,6 @@ static int g4_parse_types(const char* lt, int64_t n, std::vector<int>& is_global
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* A config boolean, flattened as "true"/"false" (`use_double_wide_mlp`). */
|
||||
static bool g4_getb(const RadModelMeta* m, const char* k, bool dflt) {
|
||||
const char* s = meta_text_gets(m, k, nullptr);
|
||||
if (!s) return dflt;
|
||||
if (!std::strcmp(s, "true") || !std::strcmp(s, "True")) return true;
|
||||
if (!std::strcmp(s, "false") || !std::strcmp(s, "False") || !std::strcmp(s, "null")) return false;
|
||||
return std::atoll(s) != 0;
|
||||
}
|
||||
|
||||
static int g4_schedule(const RadModelMeta* m, int64_t n, int64_t interval,
|
||||
std::vector<int>& is_global) {
|
||||
const char* lt = meta_text_gets(m, "layer_types", nullptr);
|
||||
@@ -146,9 +138,9 @@ struct G4Linear {
|
||||
/* reads an int8 pair a junction can write, at either grid */
|
||||
bool pair() const { return quant || grouped(); }
|
||||
/* the pair's scales a row: one, or one per 128 columns */
|
||||
int64_t scale_w() const { return grouped() ? K / RAD_FP8_BLOCK : 1; }
|
||||
int64_t scale_w() const { return grouped() ? K / RAD_SCALE_GROUP : 1; }
|
||||
rad_buf in = 0; /* the bf16 input row `a` given at declare */
|
||||
/* a4 at decode heights, as LinearFP8's w4 (rad_fp8.h): up to kA4Split rows the bf16 input is
|
||||
/* a4 at decode heights, as LinearQ's w4 (rad_linear.h): up to kA4Split rows the bf16 input is
|
||||
* cast to f16 (`a16`) for w4a16_asym's skinny kernel; w4a8i8_asym has only a prefill kernel,
|
||||
* which at one row does 16 times the matrix work and reads its weight a quarter as fast. */
|
||||
static constexpr int64_t kA4Split = 64;
|
||||
@@ -188,16 +180,6 @@ struct G4Linear {
|
||||
}
|
||||
};
|
||||
|
||||
/* A weight on the w4a8 / w8a8 grid: i4 or i8 codes with an f16 scale per [1 x 128], the encoding
|
||||
* gemm_nt_q reads against quant_act_i8's pair. */
|
||||
static bool g4_grid_w4(const RadEncoding& enc) {
|
||||
const RadEncPlane* sc = rad_enc_plane(&enc, "scale");
|
||||
const uint32_t cdt = enc.n_planes > 0 ? enc.plane[0].dtype : 0;
|
||||
return rad_enc_is(&enc, "affine") && enc.n_planes == 2 && !enc.transform[0] &&
|
||||
(cdt == RAD_I4 || cdt == RAD_I8) && enc.plane[0].block[1] == 1 &&
|
||||
sc && sc->dtype == RAD_F16 && sc->block[0] == 1 && sc->block[1] == 128;
|
||||
}
|
||||
|
||||
/* An empty `src` means the caller made the weight's name map (a probe asked it first). */
|
||||
inline int G4Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char* base,
|
||||
std::initializer_list<const char*> src,
|
||||
@@ -223,10 +205,7 @@ inline int G4Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char
|
||||
if (plain) {
|
||||
w = decl_w(b, wn, RAD_BF16, { N, K }, RAD_ACCESS_PER_TOKEN, shard, grp, 0, row_parts);
|
||||
if (!w) return RAD_E_INVAL;
|
||||
op = 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 });
|
||||
op = decl_gemm_nt(b, g, N, K, w, a, y);
|
||||
return op ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
@@ -238,20 +217,13 @@ inline int G4Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char
|
||||
* shared. A recipe uses it for linears int4 hurts (attention, down_proj). */
|
||||
const uint32_t cdt = known && enc.n_planes > 0 ? enc.plane[0].dtype : 0;
|
||||
i8g = known && linear_is_w8(enc);
|
||||
{
|
||||
const RadEncPlane* sp = rad_enc_plane(&enc, "scale");
|
||||
const RadEncPlane* zp = rad_enc_plane(&enc, "zero");
|
||||
a4 = known && rad_enc_is(&enc, "affine") && enc.n_planes == 3 && !enc.transform[0] &&
|
||||
(cdt == RAD_U4 || cdt == RAD_U5) && enc.plane[0].block[1] == 1 && sp &&
|
||||
sp->dtype == RAD_F16 && sp->block[0] == 1 && sp->block[1] == RAD_FP8_BLOCK && zp &&
|
||||
zp->dtype == RAD_U8 && zp->block[0] == 1 && zp->block[1] == RAD_FP8_BLOCK;
|
||||
w5 = a4 && cdt == RAD_U5;
|
||||
}
|
||||
a4 = known && (linear_is_asym(enc, RAD_U4) || linear_is_asym(enc, RAD_U5));
|
||||
w5 = a4 && cdt == RAD_U5;
|
||||
if (i8g || a4) {
|
||||
if (N % 16 || K % RAD_FP8_BLOCK) {
|
||||
if (N % 16 || K % RAD_SCALE_GROUP) {
|
||||
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; it takes rows in 16s and K in "
|
||||
"whole %d-column activation scale groups\n", base, (long long)N,
|
||||
(long long)K, RAD_FP8_BLOCK);
|
||||
(long long)K, RAD_SCALE_GROUP);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (a4) {
|
||||
@@ -261,7 +233,7 @@ inline int G4Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char
|
||||
RAD_ACCESS_PER_TOKEN, shard, grp, parts, np);
|
||||
} else {
|
||||
w = decl_view(b, wn, nullptr, "codes", RAD_I8, { N, K }, RAD_ACCESS_PER_TOKEN, shard, grp, parts, np);
|
||||
ws = decl_view(b, nm.f("%s.scale", base), wn, "scale", RAD_BF16, { N, K / RAD_FP8_BLOCK },
|
||||
ws = decl_view(b, nm.f("%s.scale", base), wn, "scale", RAD_BF16, { N, K / RAD_SCALE_GROUP },
|
||||
RAD_ACCESS_PER_TOKEN, shard, grp, parts, np);
|
||||
}
|
||||
if (!w || !ws) return RAD_E_INVAL;
|
||||
@@ -272,42 +244,26 @@ inline int G4Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char
|
||||
shared_in = true;
|
||||
} else {
|
||||
q8 = decl_b(b, nm.f("%s.q8", base), RAD_I8, { g.max_tok, K });
|
||||
s8 = decl_b(b, nm.f("%s.s8", base), RAD_F32, { g.max_tok, K / RAD_FP8_BLOCK });
|
||||
s8 = decl_b(b, nm.f("%s.s8", base), RAD_F32, { g.max_tok, K / RAD_SCALE_GROUP });
|
||||
if (!q8 || !s8) return RAD_E_INVAL;
|
||||
op_q = rw(b, RAD_OP(b, "quant_act_i8g",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", K),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ a }, { q8, s8 });
|
||||
op_q = decl_quant_act(b, "quant_act_i8g", g.max_tok, K, RAD_SCALE_GROUP, a, q8, s8);
|
||||
if (!op_q) return RAD_E_INVAL;
|
||||
}
|
||||
op = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", w5 ? "w5a8i8" : a4 ? "w4a8i8_asym" : "i8a8")),
|
||||
RAD_WEIGHTS(w, ws)),
|
||||
{ q8, s8 }, { y });
|
||||
op = decl_gemm_q(b, g.max_tok, N, K, RAD_SCALE_GROUP,
|
||||
w5 ? "w5a8i8" : a4 ? "w4a8i8_asym" : "i8a8", w, ws, { q8, s8 }, y);
|
||||
if (!op) return RAD_E_INVAL;
|
||||
if (a4) {
|
||||
a4_split = std::min<int64_t>(kA4Split, g.max_tok);
|
||||
a16 = decl_b(b, nm.f("%s.a16", base), RAD_F16, { a4_split, K });
|
||||
if (!a16) return RAD_E_INVAL;
|
||||
op_a16 = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, a4_split), RAD_INT("n", K),
|
||||
RAD_STR("from", g.dtype), RAD_STR("to", "f16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ a }, { a16 });
|
||||
op_dec = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, a4_split), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", w5 ? "w5a16" : "w4a16_asym")),
|
||||
RAD_WEIGHTS(w, ws)),
|
||||
{ a16 }, { y });
|
||||
op_a16 = cast_op(b, a4_split, K, g.dtype, "f16", a, a16);
|
||||
op_dec = decl_gemm_q(b, a4_split, N, K, RAD_SCALE_GROUP, w5 ? "w5a16" : "w4a16_asym", w,
|
||||
ws, { a16 }, y);
|
||||
if (!op_a16 || !op_dec) return RAD_E_INVAL;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
if (known && g4_grid_w4(enc)) {
|
||||
if (known && linear_is_grid_w4(enc)) {
|
||||
if (N % 16 || K % 128) {
|
||||
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; a w4 weight takes rows in "
|
||||
"16s and K in whole 128-column scale groups.\n", base,
|
||||
@@ -332,16 +288,9 @@ inline int G4Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char
|
||||
* with a scale per (row, group) for i8a8; paired with these GEMMs it produces NaN logits.
|
||||
* `group` only sizes the optional code sums, which this symmetric grid does not take. */
|
||||
if (!shared_in)
|
||||
op_q = rw(b, RAD_OP(b, "quant_act_i8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", K),
|
||||
RAD_INT("group", 128), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ a }, { q8, s8 });
|
||||
op = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_INT("group", 128), RAD_STR("dtype", cdt == RAD_I8 ? "w8a8" : "w4a8")),
|
||||
RAD_WEIGHTS(w, ws)),
|
||||
{ q8, s8 }, { y });
|
||||
op_q = decl_quant_act(b, "quant_act_i8", g.max_tok, K, 128, a, q8, s8);
|
||||
op = decl_gemm_q(b, g.max_tok, N, K, 128, cdt == RAD_I8 ? "w8a8" : "w4a8", w, ws,
|
||||
{ q8, s8 }, y);
|
||||
quant = true;
|
||||
return ((op_q || shared_in) && op) ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
@@ -362,7 +311,7 @@ inline void G4Linear::step(RadCtx* c, rad_buf a, rad_buf y, int64_t T) const {
|
||||
RAD_ISSUE_N(c, op_q, T, brows(a, T), brows(q8, T), brows(s8, T), RAD_NONE);
|
||||
gemm(c, y, T);
|
||||
} else if (a4 && T <= a4_split) {
|
||||
/* the decode band: f16 copy of the input, the skinny kernel; operands as LinearFP8's w4 */
|
||||
/* the decode band: f16 copy of the input, the skinny kernel; operands as LinearQ's w4 */
|
||||
RAD_ISSUE_N(c, op_a16, T, brows(a, T), brows(a16, T));
|
||||
RAD_ISSUE_N(c, op_dec, T, brows(a16, T), RAD_NONE, RAD_W(w), RAD_W(ws), brows(y, T),
|
||||
RAD_NONE, RAD_NONE);
|
||||
@@ -557,7 +506,7 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
|
||||
/* one q|k|v GEMM wherever the weight is on a quantised grid: w4a8 / w8a8, i8a8, a4 or
|
||||
* its five-bit form */
|
||||
RadEncoding e{};
|
||||
fused = weight_enc(b, qkv_wn, &e) && (g4_grid_w4(e) || linear_is_w8(e) ||
|
||||
fused = weight_enc(b, qkv_wn, &e) && (linear_is_grid_w4(e) || linear_is_w8(e) ||
|
||||
(rad_enc_is(&e, "affine") && e.n_planes == 3 &&
|
||||
(e.plane[0].dtype == RAD_U4 ||
|
||||
e.plane[0].dtype == RAD_U5)));
|
||||
@@ -706,11 +655,7 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
|
||||
/* A column slice of the fused row copied into its own rows (`cast`, bf16 to bf16, which every
|
||||
* library takes with pitched operands). */
|
||||
auto lift = [&](int64_t n, rad_buf dst) {
|
||||
return rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", n),
|
||||
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.qkv}, {dst});
|
||||
return cast_op(b, g.max_tok, n, g.dtype, g.dtype, w.qkv, dst);
|
||||
};
|
||||
|
||||
if (!fused) {
|
||||
@@ -806,12 +751,7 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
|
||||
|
||||
/* o_proj is column-sharded: the rank's partial sum is reduced first, then normed. */
|
||||
if (g.world > 1)
|
||||
op_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world), RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
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);
|
||||
|
||||
/* The second norm: the reduced attention output is normed before the residual add. */
|
||||
op_post = rw(b, RAD_OP(b, "rmsnorm",
|
||||
@@ -898,12 +838,7 @@ int Gemma4Attn::declare_shared(RadBuilder* b, Names& nm, const char* pre) {
|
||||
op_ahead = bidi("attn_paged_ahead");
|
||||
}
|
||||
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_post = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), RAD_STR("dtype", g.dtype)),
|
||||
@@ -1249,12 +1184,7 @@ int Gemma4Mlp::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
|
||||
}
|
||||
/* down_proj is column-sharded: reduce first, then the post-norm. */
|
||||
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_post = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), RAD_STR("dtype", g.dtype)),
|
||||
@@ -1624,11 +1554,7 @@ int Gemma4Head::declare(RadBuilder* b, Names& nm, const RadModelMeta* meta, cons
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n_trunk), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{src}, {b_c});
|
||||
op_hcopy = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n_trunk),
|
||||
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{b_hn}, {b_c});
|
||||
op_hcopy = cast_op(b, rows, n_trunk, g.dtype, g.dtype, b_hn, b_c);
|
||||
op_embed = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n_embd", n_trunk),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype),
|
||||
@@ -1637,17 +1563,8 @@ int Gemma4Head::declare(RadBuilder* b, Names& nm, const RadModelMeta* meta, cons
|
||||
RAD_WEIGHTS(w_tok)),
|
||||
{}, {b_e});
|
||||
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", n_trunk, rows * n_trunk),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{b_e}, {b_e});
|
||||
op_ecopy = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n_trunk),
|
||||
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{b_e}, {b_c});
|
||||
op_embed_ar = decl_all_reduce_exact(b, g, b_e, n_trunk, rows, g.dtype);
|
||||
op_ecopy = cast_op(b, rows, n_trunk, g.dtype, g.dtype, b_e, b_c);
|
||||
if (!op_hsrc || !op_hcopy || !op_embed || !op_ecopy) return RAD_E_INVAL;
|
||||
|
||||
/* pre_projection: the joined row to the head's width. Replicated, like the stream it reads
|
||||
@@ -1671,12 +1588,7 @@ int Gemma4Head::declare(RadBuilder* b, Names& nm, const RadModelMeta* meta, cons
|
||||
{b_x, b_h}, {b_x});
|
||||
};
|
||||
auto all_reduce = [&]() {
|
||||
return rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world), RAD_RANGE("numel", n, rows * n),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{b_h}, {b_h});
|
||||
return decl_all_reduce(b, g, b_h, n, rows, g.dtype);
|
||||
};
|
||||
|
||||
/* ---- the layers. */
|
||||
@@ -1909,6 +1821,8 @@ struct Layer {
|
||||
G4Junction j_am{}, j_ma{};
|
||||
/* the DFlash drafter's tap: this layer's output into its column slice of `dflash_src` */
|
||||
rad_op op_tap = 0;
|
||||
/* per-layer control vector (projection or additive steering), declared when ctx->cvec is set */
|
||||
HcProject proj{};
|
||||
/* The prefill overlap's reductions (trunk_overlap): attn.op_ar and mlp.op_ar at `overlap` 1,
|
||||
* the narrow launch that leaves the CUs to the other slice's compute; 0 where not declared. */
|
||||
rad_op op_ar_att_ov = 0, op_ar_ff_ov = 0;
|
||||
@@ -1931,7 +1845,7 @@ struct Model {
|
||||
|
||||
rad_kvgroup kv_s = 0, kv_g = 0;
|
||||
|
||||
rad_buf b_x = 0, b_h = 0, b_hout = 0, b_logits = 0;
|
||||
rad_buf b_x = 0, b_h = 0, b_hout = 0, b_logits = 0, b_proj_on = 0;
|
||||
rad_buf b_qs = 0, b_ks = 0, b_vs = 0, b_attns = 0; /* sliding rows */
|
||||
rad_buf b_qg = 0, b_kg = 0, b_vg = 0, b_atting = 0; /* global rows */
|
||||
rad_buf b_qkvs = 0, b_qkvg = 0; /* the fused projections' rows, where a layer has one */
|
||||
@@ -2164,11 +2078,11 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
|
||||
dw.ffn = decl_b(b, nm.f("df_ffn"), dg.act_dtype, {qr, dg.n_ff});
|
||||
/* The codes the drafter's linears read: int8 with one f32 scale per (row, group) for linears
|
||||
* stored rotated int8 (the -df2 recipe's), which the drafter's `fc` tells; E4M3 with a scale
|
||||
* per 128 for an MXFP4 drafter (rad_fp8.h's DenseFP8). */
|
||||
* per 128 for an MXFP4 drafter (rad_linear.h's DenseQ). */
|
||||
RAD_ARCH_TRY(Dflash2::probe_i8(b, nm, "draft", &dc.act_i8, &dc.act_g8));
|
||||
dc.fc_mapped = true;
|
||||
const uint32_t dqt = dc.act_i8 ? RAD_I8 : RAD_F8E4M3;
|
||||
const int64_t dqg = dc.act_i8 ? dc.act_g8 : (int64_t)RAD_FP8_BLOCK;
|
||||
const int64_t dqg = dc.act_i8 ? dc.act_g8 : (int64_t)RAD_SCALE_GROUP;
|
||||
if (dc.act_i8 && ((dc.n_taps * dg.n_embd) % dqg || dg.n_embd % dqg || qd % dqg ||
|
||||
dg.n_ff % dqg)) {
|
||||
fprintf(stderr, "radiance: a rotated int8 drafter takes widths in whole %lld-column scale "
|
||||
@@ -2403,7 +2317,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* 2 * intermediate_size, as transformers' Gemma4TextMLP builds them (`use_double_wide_mlp and
|
||||
* is_kv_shared_layer`). Each layer declares its own weights and op widths, and the two widths
|
||||
* keep a pair of activation buffers each (b_gu_w). */
|
||||
const bool wide_mlp = g4_getb(meta, "use_double_wide_mlp", false) && kv_shared > 0;
|
||||
const bool wide_mlp = meta_text_getb(meta, "use_double_wide_mlp", false) && kv_shared > 0;
|
||||
const int64_t n_ff_wide = 2 * g.n_ff;
|
||||
|
||||
/* The sliding class comes from geom_from (head_dim 256, 16 kv heads, full rotation, theta_s);
|
||||
@@ -2434,6 +2348,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
|
||||
/* ---- buffers. The two classes have different row widths, so they keep their own rows. */
|
||||
m.b_x = decl_b(b, nm.f("x"), g.act_dtype, {g.max_tok, g.n_embd});
|
||||
m.b_proj_on = HcProject::declare_mask(b, nm.f("projection_on"), g, ctx->cvec);
|
||||
m.b_h = decl_b(b, nm.f("h"), g.act_dtype, {g.max_tok, g.n_embd});
|
||||
m.b_qs = decl_b(b, nm.f("attn_qs"), g.act_dtype, {g.max_tok, m.cs.q_dim()});
|
||||
m.b_ks = decl_b(b, nm.f("attn_ks"), g.act_dtype, {g.max_tok, m.cs.kv_dim()});
|
||||
@@ -2500,12 +2415,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_WEIGHTS(m.w_tok)),
|
||||
{}, {m.b_x});
|
||||
if (g.world > 1)
|
||||
m.op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_x}, {m.b_x});
|
||||
m.op_embed_ar = decl_all_reduce_exact(b, g, m.b_x);
|
||||
/* Media rows (an image's or an audio clip's) overwrite their placeholders' embeddings after
|
||||
* the lookup and before its all-reduce (RadBatch::mm_embd: rank 0 holds the rows, every other
|
||||
* rank zeros). The reference scales token embeddings by sqrt(n_embd) and scatters the media
|
||||
@@ -2552,12 +2462,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
/* A rank's lookup writes zeros for ids outside its vocabulary slice; the all-reduce makes
|
||||
* every row whole. */
|
||||
if (g.world > 1) {
|
||||
m.op_ple_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", P, g.max_tok * P),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_ple_tok}, {m.b_ple_tok});
|
||||
m.op_ple_ar = decl_all_reduce_exact(b, g, m.b_ple_tok, P, g.max_tok, g.dtype);
|
||||
if (!m.op_ple_ar) return RAD_E_INVAL;
|
||||
}
|
||||
RAD_ARCH_TRY(m.ln_ple_proj.declare(b, nm, g, nm.f("ple_model_proj"),
|
||||
@@ -2691,6 +2596,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* Per-layer control vector, after the layer scalar (and PLE branch if present). */
|
||||
RAD_ARCH_TRY(lay.proj.declare(b, nm.f("blk.%lld.proj", (long long)l), g, l, ctx->cvec,
|
||||
m.b_proj_on, m.b_x, 1));
|
||||
|
||||
/* The tap: a row copy of the layer's output (after the scalar, HF's hidden_states[l + 1])
|
||||
* into the column slice the tap owns. It is declared here, in the layer it is issued
|
||||
* after, because the buffer planner's liveness is declaration order. Declared after the
|
||||
@@ -2698,11 +2607,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* writes: the drafts would fail while the reply stays fluent. */
|
||||
for (int t = 0; t < m.n_taps; ++t)
|
||||
if (m.tap_layer[t] == (int)l && !lay.op_tap)
|
||||
lay.op_tap = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_x}, {m.b_dfsrc});
|
||||
lay.op_tap = cast_op(b, g.max_tok, g.n_embd, g.dtype, g.dtype, m.b_x, m.b_dfsrc);
|
||||
}
|
||||
|
||||
/* ---- the junctions, declared once every layer exists (j_ma reads the next layer's gain).
|
||||
@@ -2711,7 +2616,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* output (an a4 linear's decode band aside), so a bf16 k or v beside an int8 q would read a
|
||||
* stale buffer. Otherwise the blocks keep their own norms, quantisers, post-norms and adds. */
|
||||
if (m.n_main > 0) {
|
||||
bool ok = true;
|
||||
bool ok = !m.b_proj_on;
|
||||
for (const Layer& lay : m.layers)
|
||||
ok = ok && lay.attn.reads_pair() && lay.mlp.ln_gu.pair();
|
||||
if (ok) {
|
||||
@@ -2874,7 +2779,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
|
||||
/* ---- the assistant head, when the container carries one (`rad-convert --draft-model`) and
|
||||
* the deployment speculates; otherwise its ~0.5 GB of weights stay off the card. */
|
||||
if (ctx->max_spec > 0 && has_assistant(meta)) {
|
||||
if (rad_ctx_draft_head(ctx) && has_assistant(meta)) {
|
||||
int last_s = -1, last_f = -1;
|
||||
/* the last layer of each class that keeps a cache (a KV-shared layer reads another's) */
|
||||
for (int64_t l = 0; l < m.n_main; ++l)
|
||||
@@ -3275,6 +3180,7 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
RAD_ISSUE(c, l.op_scale, brows(m.b_x, batch->n_tok), RAD_W(l.w_scalar),
|
||||
brows(m.b_x, batch->n_tok));
|
||||
}
|
||||
l.proj.step(c, batch, 0, T);
|
||||
/* The drafter's taps, once the layer's output is whole. Either way that is after the
|
||||
* scalar, since the junction applies it to the stream it writes. */
|
||||
for (int t = 0; t < m.n_taps && l.op_tap; ++t)
|
||||
@@ -3308,6 +3214,7 @@ const RadChatFormat* chat_format(const RadModelMeta*) { return gemma4_chat_forma
|
||||
* trained at, fixed. */
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
out->control_vector_ok = 1;
|
||||
if (has_assistant(meta)) {
|
||||
out->draft_depth = kHeadDepth;
|
||||
out->draft_depth_fixed = 0;
|
||||
|
||||
+249
-86
@@ -11,7 +11,7 @@
|
||||
* rad_block_glm_kda.h GlmKda the 34 linear layers, KdaState their recurrence
|
||||
* rad_block_glm_mla.h GlmMla the 11 sparse MLA layers, MlaLatent their core
|
||||
* rad_block_glm_indexer.h GlmIndexer the DSA indexer, DsaCache its key cache and selection
|
||||
* rad_block_glm_router.h GlmRouter the correction-bias router (through MoeFP8)
|
||||
* rad_block_glm_router.h GlmRouter the correction-bias router (through MoeQ)
|
||||
* rad_block_glm_mtp.h GlmMtp the draft head around the plugin's layer 45
|
||||
* rad_block_glm_vision.h GlmVision the tower, MediaRows its rows over the embeddings
|
||||
* rad_glm_tp.h GlmTp the shards, the row runs and the split thresholds
|
||||
@@ -26,8 +26,10 @@
|
||||
#include <arch/rad_block_glm_indexer.h>
|
||||
#include <arch/rad_block_glm_mtp.h>
|
||||
#include <arch/rad_block_glm_vision.h>
|
||||
#include <arch/rad_block_mlp_fp8.h>
|
||||
#include <arch/rad_block_moe_fp8.h>
|
||||
#include <arch/rad_block_mlp_q.h>
|
||||
#include <arch/rad_block_moe_q.h>
|
||||
#include <arch/rad_expert_split.h>
|
||||
#include <cstdio>
|
||||
#include <memory>
|
||||
|
||||
namespace glm5next {
|
||||
@@ -36,12 +38,12 @@ using namespace rad::arch;
|
||||
struct Layer {
|
||||
bool full = false, draft = false;
|
||||
ManifoldConn attn_hc{}, ffn_hc{};
|
||||
NormQuantFP8 norm{};
|
||||
NormQuant norm{};
|
||||
GlmKda kda{};
|
||||
GlmMla mla{};
|
||||
GlmIndexer index{};
|
||||
MlpFP8 dense{};
|
||||
MoeFP8 moe{};
|
||||
MlpQ dense{};
|
||||
MoeQ moe{};
|
||||
};
|
||||
struct Model {
|
||||
Names nm{};
|
||||
@@ -53,21 +55,37 @@ struct Model {
|
||||
/* Routed experts whole on their rank (288/world of them) instead of split by width across
|
||||
* every rank. Whole experts can be read from the drive, which two cards need; at four and
|
||||
* eight the width split is the shape the MXFP4 kernels are tuned for (prefill runs about three
|
||||
* times faster), so all-MXFP4 experts take it unless --weights-disk-tier asks for the drive.
|
||||
* times faster), so all-MXFP4 or all-IQR experts take it unless --weights-disk-tier asks for
|
||||
* the drive.
|
||||
* Anything else stays whole: a plain bf16 expert cannot be sliced at all. */
|
||||
bool whole_experts = false;
|
||||
/* With whole experts, this rank's run of them [ne_base, ne_base + ne_rank) of the checkpoint's
|
||||
* numbering: 288/world each, or the expert-split list (rad_expert_split.h). */
|
||||
int64_t ne_rank = 0, ne_base = 0;
|
||||
std::vector<Layer> layers;
|
||||
/* Each routed layer's source and config, probed before any buffer is sized: the expert
|
||||
* format decides the routed arm's code pair. Indexed by layer; 0..2 are dense and unused. */
|
||||
std::vector<MoeQ::Src> moe_src;
|
||||
/* An IQ8R trunk (rotated int8 linears, one scale a `trunk_g8` of K), read from layer 0's dense
|
||||
* gate_up before any buffer is sized: every activation a trunk linear reads then carries
|
||||
* rotated int8 codes, and the routed experts read rotated int8 too (IQR). KDA, the indexer,
|
||||
* the router and the MLA's kv_b stay as they are declared. `norm_fed`: the norms write those
|
||||
* codes themselves (rmsnorm_had_quant_i8g); where they cannot, each linear quantises the bf16
|
||||
* plane. */
|
||||
bool trunk_rot = false;
|
||||
int64_t trunk_g8 = RAD_SCALE_GROUP;
|
||||
bool norm_fed = false;
|
||||
rad_kvgroup latent = 0, index = 0, tail = 0, state = 0, conv = 0;
|
||||
/* The streams and the step's stream-wide buffers. */
|
||||
rad_buf h0 = 0, h1 = 0, x = 0, y = 0, post = 0, comb = 0, final_hidden = 0, logit_input = 0,
|
||||
logits = 0;
|
||||
ActFP8 act{};
|
||||
ActQ act{};
|
||||
/* The blocks' wires: one set of activations, shared by every layer of a kind. */
|
||||
GlmKda::Wire kw{};
|
||||
GlmMla::Wire aw{};
|
||||
GlmIndexer::Wire iw{};
|
||||
MlpFP8::Wire dw{};
|
||||
MoeFP8::Wire mw{};
|
||||
MlpQ::Wire dw{};
|
||||
MoeQ::Wire mw{};
|
||||
rad_weight token = 0, head = 0, final_gain = 0;
|
||||
rad_op embed = 0, embed_ar = 0, expand = 0, contract = 0, norm = 0, gather = 0, head_op = 0;
|
||||
/* The draft head and its layer, declared only when the deployment speculates. */
|
||||
@@ -87,15 +105,24 @@ static thread_local std::unique_ptr<Model> probe_model;
|
||||
* name map, so it leaves the graph as it was. One expert in another format settles it: a protected
|
||||
* bf16 expert is served only whole. No answer means no container entry, and what is not known to
|
||||
* be MXFP4 stays whole. */
|
||||
static bool experts_are_mxfp4(RadBuilder* b, Names& nm) {
|
||||
for (int l = 3; l < 45; ++l)
|
||||
/* Whether every routed expert can be split by width over the ranks: MXFP4 (format 8) or the IQR
|
||||
* computed trellis (format 11), each a scale a row and K in whole 128-wide units, so a rank's 512
|
||||
* columns of an expert's down projection are four whole units and its gate/up rows whole rows. */
|
||||
static bool experts_split_by_width(RadBuilder* b, Names& nm, Names* mtp_nm = nullptr) {
|
||||
auto check_layer = [&](Names& n, int l) {
|
||||
for (int ge = 0; ge < 288; ++ge)
|
||||
for (const char* fmt : { "blk.%d.ffn_gate_up_exps.%d.weight",
|
||||
"blk.%d.ffn_down_exps.%d.weight" }) {
|
||||
RadEncoding e{};
|
||||
if (!weight_enc(b, nm.f(fmt, l, ge), &e) || MoeFP8::format_of(e) != 8)
|
||||
return false;
|
||||
if (!weight_enc(b, n.f(fmt, l, ge), &e)) return false;
|
||||
const int f = MoeQ::format_of(e);
|
||||
if (f != 8 && f != 11) return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
for (int l = 3; l < 45; ++l)
|
||||
if (!check_layer(nm, l)) return false;
|
||||
if (mtp_nm && !check_layer(*mtp_nm, 45)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -105,12 +132,7 @@ static int64_t cfg(const RadModelMeta* m, const char* key, int64_t fallback) {
|
||||
return rad_meta_geti(m, key, rad_meta_geti(m, nested, fallback));
|
||||
}
|
||||
static rad_op copy(RadBuilder* b, const Geom& g, rad_buf x, rad_buf y) {
|
||||
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),
|
||||
{ x }, { y });
|
||||
return cast_op(b, g.max_tok, 4096, "bf16", "bf16", x, y);
|
||||
}
|
||||
static rad_op norm(RadBuilder* b, const Geom& g, rad_weight w, rad_buf x, rad_buf y) {
|
||||
return rw(b,
|
||||
@@ -122,6 +144,31 @@ static rad_op norm(RadBuilder* b, const Geom& g, rad_weight w, rad_buf x, rad_bu
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the shared activations */
|
||||
/* A norm's code pair: E4M3 for a block-fp8 or bf16 trunk; for an IQ8R one rotated int8 codes at the
|
||||
* trunk's group, written by the norm where `norm_fed`, else an E4M3 pair no linear reads beside
|
||||
* int8 codes each linear writes from the bf16 plane (ActQ::declare_pair). */
|
||||
static int norm_pair(RadBuilder* b, Model& m, ActQ& a, const char* name, int64_t n) {
|
||||
if (!m.trunk_rot) return a.declare_qs(b, m.nm, m.g, name, n);
|
||||
RAD_ARCH_TRY(a.declare_qs(b, m.nm, m.g, name, n, 0, true, !m.norm_fed, m.trunk_g8));
|
||||
a.q8_fed = a.q8_rot = m.norm_fed;
|
||||
return RAD_OK;
|
||||
}
|
||||
/* A quantiser's code pair (the MLA's expanded output, the clamped products): for an IQ8R trunk the
|
||||
* rotated int8 codes the block's own had_quant_act_i8g writes at `group`, and no E4M3 pair. */
|
||||
static int quant_pair(RadBuilder* b, Model& m, ActQ& a, const char* name, int64_t n,
|
||||
int64_t rows = 0, int64_t group = 0) {
|
||||
if (!m.trunk_rot) return a.declare_qs(b, m.nm, m.g, name, n, rows);
|
||||
const int64_t g8 = group > 0 ? group : m.trunk_g8;
|
||||
if (n % g8) {
|
||||
fprintf(stderr, "radiance: glm5next: the IQ8R trunk keeps one scale a %lld of K, which "
|
||||
"does not divide this rank's %lld-wide '%s'\n",
|
||||
(long long)g8, (long long)n, name);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
RAD_ARCH_TRY(a.declare_qs(b, m.nm, m.g, name, n, rows, true, false, g8));
|
||||
a.q8_fed = a.q8_rot = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
static int stream_buffers(RadBuilder* b, Model& m) {
|
||||
auto& g = m.g;
|
||||
auto& nm = m.nm;
|
||||
@@ -137,7 +184,7 @@ static int stream_buffers(RadBuilder* b, Model& m) {
|
||||
m.post = decl_b(b, nm.f("post"), RAD_F32, { T, 4 });
|
||||
m.comb = decl_b(b, nm.f("mix"), RAD_F32, { T, 16 });
|
||||
m.act.x = decl_b(b, nm.f("normalized"), RAD_BF16, { T, 4096 });
|
||||
RAD_ARCH_TRY(m.act.declare_qs(b, nm, g, "normalized", 4096));
|
||||
RAD_ARCH_TRY(norm_pair(b, m, m.act, "normalized", 4096));
|
||||
m.final_hidden = decl_b(b, nm.f("final_hidden"), RAD_BF16, { T, 4096 }, RAD_BUF_PERSIST);
|
||||
m.logit_input = decl_b(b, nm.f("logit_input"), RAD_BF16, { g.max_logit_rows, 4096 });
|
||||
m.logits = decl_b(b, nm.f("logits"), RAD_F32, { g.max_logit_rows, g.n_vocab });
|
||||
@@ -178,14 +225,14 @@ static int mla_buffers(RadBuilder* b, Model& m) {
|
||||
aw.q_raw = bf("q_raw", 1536);
|
||||
aw.kv_raw = bf("kv_raw", 512);
|
||||
aw.q_low.x = bf("q_low", 1536);
|
||||
RAD_ARCH_TRY(aw.q_low.declare_qs(b, nm, g, "q_low", 1536));
|
||||
RAD_ARCH_TRY(norm_pair(b, m, aw.q_low, "q_low", 1536));
|
||||
aw.latent = bf("latent", 512);
|
||||
aw.out = m.y;
|
||||
aw.core.q = bf("query", Q);
|
||||
aw.core.q_latent = decl_b(b, nm.f("q_latent"), RAD_BF16, { T, H, 512 });
|
||||
aw.core.attn_latent = decl_b(b, nm.f("attn_latent"), RAD_BF16, { T, H, 512 });
|
||||
aw.attn.x = bf("expanded", Q);
|
||||
RAD_ARCH_TRY(aw.attn.declare_qs(b, nm, g, "expanded", Q));
|
||||
RAD_ARCH_TRY(quant_pair(b, m, aw.attn, "expanded", Q));
|
||||
aw.core.out = aw.attn.x;
|
||||
const int64_t part = g.world > 1 ? DsaCache::part_rows(T, g.world) : 0;
|
||||
const int64_t TQ = g.world > 1 ? std::max(T, g.world * part) : T;
|
||||
@@ -259,7 +306,7 @@ static int ffn_buffers(RadBuilder* b, Model& m) {
|
||||
dw.h = m.act;
|
||||
dw.gate_up = bf("dense_gate_up", 2 * g.n_ff);
|
||||
dw.ffn.x = bf("dense_ff", g.n_ff);
|
||||
RAD_ARCH_TRY(dw.ffn.declare_qs(b, nm, g, "dense_ff", g.n_ff));
|
||||
RAD_ARCH_TRY(quant_pair(b, m, dw.ffn, "dense_ff", g.n_ff));
|
||||
auto& mw = m.mw;
|
||||
mw.x = m.x;
|
||||
mw.h = m.act;
|
||||
@@ -281,11 +328,20 @@ static int ffn_buffers(RadBuilder* b, Model& m) {
|
||||
const int64_t FE = m.whole_experts ? 2048 : F;
|
||||
mw.egu = decl_b(b, nm.f("expert_gate_up"), RAD_BF16, { T * 8, 2 * FE });
|
||||
mw.eff.x = decl_b(b, nm.f("expert_ff"), RAD_BF16, { T * 8, FE });
|
||||
RAD_ARCH_TRY(mw.eff.declare_qs(b, nm, g, "expert_ff", FE, T * 8));
|
||||
/* An IQ8R trunk's routed arm is rotated int8 throughout: the gated product's codes at one
|
||||
* scale a 128 of K, which the IQR grouped GEMM reads (MoeQ::a8). Its gate_up reads the
|
||||
* norm's own codes where the norm writes them, else a rotated copy of the block input that
|
||||
* MoeQ writes once a layer (Wire::hr). */
|
||||
RAD_ARCH_TRY(quant_pair(b, m, mw.eff, "expert_ff", FE, T * 8, RAD_SCALE_GROUP));
|
||||
if (m.trunk_rot && !m.norm_fed) {
|
||||
RAD_ARCH_TRY(mw.hr.declare_qs(b, nm, g, "normalized_rot", 4096, 0, true, false,
|
||||
RAD_SCALE_GROUP));
|
||||
mw.hr.q8_fed = mw.hr.q8_rot = true;
|
||||
}
|
||||
mw.edn = decl_b(b, nm.f("expert_down"), RAD_BF16, { T * 8, 4096 });
|
||||
mw.sgu = bf("shared_gate_up", 2 * F);
|
||||
mw.sff.x = bf("shared_ff", F);
|
||||
RAD_ARCH_TRY(mw.sff.declare_qs(b, nm, g, "shared_ff", F));
|
||||
RAD_ARCH_TRY(quant_pair(b, m, mw.sff, "shared_ff", F));
|
||||
mw.sout = bf("shared_out", 4096);
|
||||
mw.sgate = bf("shared_one", 1);
|
||||
return RAD_OK;
|
||||
@@ -295,7 +351,8 @@ static int kv_groups(RadBuilder* b, Model& m) {
|
||||
auto& nm = m.nm;
|
||||
RadKVGroupDecl d{};
|
||||
d.kind = RAD_KV_FULL;
|
||||
// bf16, or E4M3 under --kv-cache-dtype fp8 (geometry); the other groups keep their own.
|
||||
// bf16, E4M3 under --kv-cache-dtype fp8, or the int8 row under i8 (geometry); the other groups
|
||||
// keep their own.
|
||||
d.dtype = rad_dtype_parse(g.kv_dtype);
|
||||
d.n_head_kv = 1;
|
||||
d.head_dim = 256;
|
||||
@@ -325,8 +382,63 @@ static int kv_groups(RadBuilder* b, Model& m) {
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ one layer */
|
||||
/* A routed layer's source and config, before its probe. */
|
||||
static MoeQ::Src moe_source(const Model& m, Names& nm, int l) {
|
||||
const auto& g = m.g;
|
||||
const char* pre = nm.ckpt("model.language_model.layers.%d", l);
|
||||
MoeQ::Src s;
|
||||
s.norm = nm.ckpt("%s.post_attention_layernorm.weight", pre);
|
||||
s.router = nm.ckpt("%s.mlp.gate.weight", pre);
|
||||
s.router_bias = nm.ckpt("%s.mlp.gate.e_score_correction_bias", pre);
|
||||
s.experts = nm.ckpt("%s.mlp.experts", pre);
|
||||
s.shared = nm.ckpt("%s.mlp.shared_experts", pre);
|
||||
// EXPERT PARALLELISM AT TP: each rank owns 288/world WHOLE experts (the contiguous
|
||||
// window [expert_base, expert_base+n_expert) of the checkpoint's numbering), which the
|
||||
// helper declares RAD_SHARD_NONE -- unsharded, so an expert unit is file-direct and can
|
||||
// live in the container's mapping or the file tier
|
||||
// instead of needing VRAM+pinned-pool residency for all 151 GiB of them. The router
|
||||
// stays replicated over n_expert_all; moe_scatter/router_topk_scatter drop slots
|
||||
// outside the window (moe_scatter schema: "which is how EXPERT PARALLELISM is
|
||||
// expressed"); the shared expert stays width-sharded on its own declaration path; the
|
||||
// block's all-reduce sums the partials exactly as width TP did. At world 1 this
|
||||
// degenerates to the whole-model declaration (n_expert == n_expert_all, no spans).
|
||||
s.cfg.n_expert_all = 288;
|
||||
s.cfg.top_k = 8;
|
||||
s.cfg.n_ff_shared = GlmTp::expert_width(g.world);
|
||||
if (m.whole_experts) {
|
||||
// The window is 288/world experts a rank, or the expert-split list's count in rank order
|
||||
// (declare, rad_expert_split.h). A shape probe may pass rank >= world (arch_test's
|
||||
// parallel declares reuse i % 4); it takes rank 0's window.
|
||||
s.cfg.n_expert = m.ne_rank;
|
||||
s.cfg.expert_base = m.ne_base;
|
||||
s.cfg.probed_expert = s.cfg.expert_base; // probe this rank's first owned expert
|
||||
s.cfg.n_ff_exp = 2048; // whole: whole experts' intermediate
|
||||
} else {
|
||||
s.cfg.n_expert = 288;
|
||||
s.cfg.n_ff_exp = GlmTp::expert_width(g.world);
|
||||
}
|
||||
s.cfg.rows = g.max_tok;
|
||||
s.cfg.sigmoid_router = 1;
|
||||
s.cfg.route_scale = 2.5;
|
||||
s.cfg.swiglu_limit = 10;
|
||||
s.cfg.shared_ungated = 1;
|
||||
s.cfg.router_fuse = 1;
|
||||
s.cfg.swiglu_quant = 1;
|
||||
// At world 1 the width-slice declaration IS the whole model: keep the spans so the
|
||||
// graph stays the pinned one. Whole experts need no width spans (split && ep is refused
|
||||
// by the helper).
|
||||
if (!m.whole_experts) {
|
||||
for (int q = 0; q < 2; ++q) {
|
||||
s.cfg.ff_lo[q] = g.rank * GlmTp::expert_width(g.world);
|
||||
s.cfg.ff_hi[q] = (g.rank + 1) * GlmTp::expert_width(g.world);
|
||||
}
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool draft) {
|
||||
const auto& g = m.g;
|
||||
if (l >= 3 && (size_t)l >= m.moe_src.size()) return RAD_E_INVAL;
|
||||
lay.draft = draft;
|
||||
lay.full = draft || l % 4 == 3;
|
||||
const char* pre = nm.ckpt("model.language_model.layers.%d", l);
|
||||
@@ -376,7 +488,7 @@ static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool dra
|
||||
if (l < 3) {
|
||||
auto w = m.dw;
|
||||
w.x = input;
|
||||
MlpFP8::Src s{ nm.ckpt("%s.post_attention_layernorm.weight", pre),
|
||||
MlpQ::Src s{ nm.ckpt("%s.post_attention_layernorm.weight", pre),
|
||||
nm.ckpt("%s.mlp.gate_proj.weight", pre),
|
||||
nm.ckpt("%s.mlp.up_proj.weight", pre),
|
||||
nm.ckpt("%s.mlp.down_proj.weight", pre) };
|
||||
@@ -385,55 +497,14 @@ static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool dra
|
||||
} else {
|
||||
auto w = m.mw;
|
||||
w.x = input;
|
||||
MoeFP8::Src s;
|
||||
s.norm = nm.ckpt("%s.post_attention_layernorm.weight", pre);
|
||||
s.router = nm.ckpt("%s.mlp.gate.weight", pre);
|
||||
s.router_bias = nm.ckpt("%s.mlp.gate.e_score_correction_bias", pre);
|
||||
s.experts = nm.ckpt("%s.mlp.experts", pre);
|
||||
s.shared = nm.ckpt("%s.mlp.shared_experts", pre);
|
||||
// EXPERT PARALLELISM AT TP: each rank owns 288/world WHOLE experts (the contiguous
|
||||
// window [expert_base, expert_base+n_expert) of the checkpoint's numbering), which the
|
||||
// helper declares RAD_SHARD_NONE -- unsharded, so an expert unit is file-direct and can
|
||||
// live in the container's mapping or the file tier
|
||||
// instead of needing VRAM+pinned-pool residency for all 151 GiB of them. The router
|
||||
// stays replicated over n_expert_all; moe_scatter/router_topk_scatter drop slots
|
||||
// outside the window (moe_scatter schema: "which is how EXPERT PARALLELISM is
|
||||
// expressed"); the shared expert stays width-sharded on its own declaration path; the
|
||||
// block's all-reduce sums the partials exactly as width TP did. At world 1 this
|
||||
// degenerates to the old whole-model declaration (n_expert == n_expert_all, no spans).
|
||||
s.cfg.n_expert_all = 288;
|
||||
s.cfg.top_k = 8;
|
||||
s.cfg.n_ff_shared = GlmTp::expert_width(g.world);
|
||||
if (m.whole_experts) {
|
||||
s.cfg.n_expert = 288 / g.world;
|
||||
// A shape probe may pass rank >= world (arch_test's parallel declares reuse i % 4);
|
||||
// old code tolerated that because expert_base stayed 0, so clamp to rank 0's window.
|
||||
const int ep_rank = g.rank < g.world ? g.rank : 0;
|
||||
s.cfg.expert_base = ep_rank * (288 / g.world);
|
||||
s.cfg.probed_expert = s.cfg.expert_base; // probe this rank's first owned expert
|
||||
s.cfg.n_ff_exp = 2048; // whole: whole experts' intermediate
|
||||
} else {
|
||||
s.cfg.n_expert = 288;
|
||||
s.cfg.n_ff_exp = GlmTp::expert_width(g.world);
|
||||
}
|
||||
s.cfg.rows = g.max_tok;
|
||||
s.cfg.sigmoid_router = 1;
|
||||
s.cfg.route_scale = 2.5;
|
||||
s.cfg.swiglu_limit = 10;
|
||||
s.cfg.shared_ungated = 1;
|
||||
s.cfg.router_fuse = 1;
|
||||
s.cfg.swiglu_quant = 1;
|
||||
// At world 1 the width-slice declaration IS the whole model: keep the spans so the
|
||||
// graph stays the pinned one. Whole experts need no width spans (split && ep is refused
|
||||
// by the helper).
|
||||
if (!m.whole_experts) {
|
||||
for (int q = 0; q < 2; ++q) {
|
||||
s.cfg.ff_lo[q] = g.rank * GlmTp::expert_width(g.world);
|
||||
s.cfg.ff_hi[q] = (g.rank + 1) * GlmTp::expert_width(g.world);
|
||||
}
|
||||
}
|
||||
RAD_ARCH_TRY(MoeFP8::probe(b, nm, l, s, &s.cfg));
|
||||
RAD_ARCH_TRY(lay.moe.declare(b, nm, g, l, w, s, false, draft));
|
||||
/* Every routed layer (trunk 3..44, and draft 45 when declared) was probed before the
|
||||
* buffers in declare(); reuse its source so no name map is declared twice. */
|
||||
MoeQ::Src s = m.moe_src[(size_t)l];
|
||||
/* The MoE helper takes a protected bf16 expert's whole width from `n_ff_all`, which the
|
||||
* model sets to the dense layers' 12288; an expert is 2048 wide. */
|
||||
Geom mg = g;
|
||||
mg.n_ff_all = GlmTp::expert_width(1);
|
||||
RAD_ARCH_TRY(lay.moe.declare(b, nm, mg, l, w, s, false, draft));
|
||||
}
|
||||
if (!draft) RAD_ARCH_TRY(lay.ffn_hc.declare_post(b));
|
||||
return RAD_OK;
|
||||
@@ -462,11 +533,12 @@ static int geometry(Geom& g, const RadModelMeta* meta, const RadBuildCtx* ctx, i
|
||||
/* Filled by hand here, not by geom_from: without it kv_resolve would declare the whole context as
|
||||
* the ring. */
|
||||
g.kv_resident = ctx->kv_resident_blocks;
|
||||
g.kv_host_tokens = ctx->kv_host_tokens;
|
||||
g.max_logit_rows = std::min<int64_t>(g.max_tok, g.max_seqs * (g.max_spec + 1));
|
||||
if (ctx->max_out_rows > g.max_logit_rows) g.max_logit_rows = ctx->max_out_rows;
|
||||
g.eps = meta->rms_eps;
|
||||
/* --kv-cache-dtype names the latent cache's dtype only (kv_groups); declare refuses all but
|
||||
* bf16 and fp8. */
|
||||
* bf16, fp8 and i8. */
|
||||
g.kv_dtype = rad_dtype_name(rad_kv_cache_dtype(ctx, RAD_BF16));
|
||||
g.wire_exact = !ctx->tp_wire_lossy;
|
||||
g.wire_min_bytes = ctx->tp_wire_min_bytes;
|
||||
@@ -507,11 +579,14 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
ctx->max_spec);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* fp8 narrows the latent attention cache to E4M3 at a descale of 1 (kv_groups); the index
|
||||
* tail, the DSA index and the KDA caches keep their dtypes. */
|
||||
if (ctx->kv_dtype && ctx->kv_dtype != RAD_BF16 && ctx->kv_dtype != RAD_F8E4M3) {
|
||||
/* fp8 narrows the latent attention cache to E4M3 at a descale of 1, i8 to the ordinary int8
|
||||
* cache row at head_dim 256 (each 256-wide half of the latent its own f16 scale; its device
|
||||
* reader is the GLM kernel plugin's, plugin/glm) (kv_groups); the index tail, the DSA index and
|
||||
* the KDA caches keep their dtypes. */
|
||||
if (ctx->kv_dtype && ctx->kv_dtype != RAD_BF16 && ctx->kv_dtype != RAD_F8E4M3 &&
|
||||
ctx->kv_dtype != RAD_I8) {
|
||||
fprintf(stderr, "radiance: glm5next: --kv-cache-dtype %s; this plugin serves its latent "
|
||||
"attention cache in bf16 or fp8 only\n",
|
||||
"attention cache in bf16, fp8 or i8 only\n",
|
||||
rad_dtype_name(ctx->kv_dtype));
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
@@ -523,8 +598,91 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
auto& nm = m.nm;
|
||||
m.form = ctx->tp_attn_rows ? GlmMla::Form::rows : GlmMla::Form::heads;
|
||||
RAD_ARCH_TRY(geometry(g, meta, ctx, world));
|
||||
const bool want_mtp = rad_ctx_draft_head(ctx) != 0;
|
||||
m.whole_experts = world == 2 || (world > 2 && (ctx->expert_file_tier ||
|
||||
!experts_are_mxfp4(b, nm)));
|
||||
!experts_split_by_width(
|
||||
b, nm, want_mtp ? &m.mtp.nm : nullptr)));
|
||||
if (m.whole_experts) {
|
||||
/* Even counts, as the quantised GEMM's two parity tables need. A rank given few enough
|
||||
* experts to hold them all in VRAM streams none over its link. */
|
||||
bool given = false;
|
||||
if (!rad_expert_split(288, world, g.rank, 2, ctx->expert_split, &m.ne_rank, &m.ne_base, &given)) {
|
||||
if (given)
|
||||
fprintf(stderr, "radiance: glm5next: expert-split %s does not split 288 experts over %d "
|
||||
"ranks (one even count a rank, comma-separated, summing to 288)\n",
|
||||
ctx->expert_split, world);
|
||||
else
|
||||
fprintf(stderr, "radiance: glm5next: 288 experts do not split over %d ranks (an even "
|
||||
"count of whole experts each)\n", world);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (given)
|
||||
rad_note(b, "routed experts split unevenly (expert-split): rank %d holds %lld of 288 a layer, "
|
||||
"from %lld", g.rank, (long long)m.ne_rank, (long long)m.ne_base);
|
||||
} else if (ctx->expert_split && *ctx->expert_split && world > 1) {
|
||||
fprintf(stderr, "radiance: glm5next: expert-split names whole experts a rank, and at %d ranks this "
|
||||
"container's experts are split by width\n", world);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* ---- each routed layer's expert format, read before any buffer is declared: the format
|
||||
* decides the routed arm's code pair (ffn_buffers). The probe declares the layer's first
|
||||
* experts' name maps, which the layer's declare skips. */
|
||||
const int n_routed_end = want_mtp ? 46 : 45;
|
||||
m.moe_src.assign((size_t)n_routed_end, MoeQ::Src{});
|
||||
for (int l = 3; l < 45; ++l) {
|
||||
m.moe_src[(size_t)l] = moe_source(m, nm, l);
|
||||
RAD_ARCH_TRY(MoeQ::probe(b, nm, l, m.moe_src[(size_t)l], &m.moe_src[(size_t)l].cfg));
|
||||
}
|
||||
if (want_mtp) {
|
||||
m.moe_src[45] = moe_source(m, m.mtp.nm, 45);
|
||||
RAD_ARCH_TRY(MoeQ::probe(b, m.mtp.nm, 45, m.moe_src[45], &m.moe_src[45].cfg));
|
||||
}
|
||||
/* ---- the trunk's stored form, read from layer 0's dense gate_up through that layer's own
|
||||
* LinearQ (MlpQ then does not map it again). */
|
||||
m.layers.resize(45);
|
||||
{
|
||||
const char* pre = nm.ckpt("model.language_model.layers.%d", 0);
|
||||
RAD_ARCH_TRY(m.layers[0].dense.gate_up.probe(
|
||||
b, nm, g, nm.f("blk.0.ffn_gate_up"),
|
||||
{ nm.ckpt("%s.mlp.gate_proj.weight", pre), nm.ckpt("%s.mlp.up_proj.weight", pre) }));
|
||||
RadEncoding enc{};
|
||||
m.trunk_rot = weight_enc(b, nm.f("blk.0.ffn_gate_up.weight"), &enc) &&
|
||||
linear_is_w8h(enc) && !linear_is_wnh(enc);
|
||||
m.trunk_g8 = m.trunk_rot ? linear_w8h_group(enc) : (int64_t)RAD_SCALE_GROUP;
|
||||
}
|
||||
if (m.trunk_rot && want_mtp) {
|
||||
RadEncoding e45{};
|
||||
const char* p45 = m.mtp.nm.f("blk.45.ffn_gate_up_exps.%lld.weight",
|
||||
(long long)m.moe_src[45].cfg.probed_expert);
|
||||
if (!weight_enc(b, p45, &e45)) {
|
||||
fprintf(stderr, "radiance: glm5next: container has no MTP draft layer "
|
||||
"(converted with --max-spec 0); serve with "
|
||||
"num-speculative-tokens: 0 or re-convert with --max-spec > 0\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
}
|
||||
for (int l = 3; l < n_routed_end; ++l) {
|
||||
const MoeQ::Config& c = m.moe_src[(size_t)l].cfg;
|
||||
const bool int8_experts = c.expert_iqr || c.expert_i8;
|
||||
if (m.trunk_rot && (c.expert_bf16 || !int8_experts)) {
|
||||
fprintf(stderr, "radiance: glm5next: the trunk is IQ8R and layer %d's routed experts are "
|
||||
"%s; an IQ8R trunk's experts read its rotated int8 codes, so they are "
|
||||
"IQR or rotated int8\n",
|
||||
l, c.expert_bf16 ? "plain bf16" : "in another format");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (!m.trunk_rot && int8_experts) {
|
||||
fprintf(stderr, "radiance: glm5next: layer %d's routed experts are rotated int8 and the "
|
||||
"trunk is not IQ8R; they read the trunk's rotated int8 codes\n", l);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
}
|
||||
if (m.trunk_rot && m.form == GlmMla::Form::rows) {
|
||||
fprintf(stderr, "radiance: glm5next: the MLA row form (tp-attn-rows) views its head-form "
|
||||
"weights, which an IQ8R trunk's int8 linears cannot; serve the head form\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
m.norm_fed = m.trunk_rot && rad_op_declared(b, "rmsnorm_had_quant_i8g") != 0;
|
||||
RAD_ARCH_TRY(stream_buffers(b, m));
|
||||
RAD_ARCH_TRY(kda_buffers(b, m));
|
||||
RAD_ARCH_TRY(mla_buffers(b, m));
|
||||
@@ -580,7 +738,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_INT("n_embd", 4096), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(m.head)),
|
||||
{ m.logit_input }, { m.logits });
|
||||
if (g.max_spec > 0) {
|
||||
if (rad_ctx_draft_head(ctx)) {
|
||||
GlmMtp::Wire tw{ m.final_hidden, m.logits, m.token, m.head };
|
||||
RAD_ARCH_TRY(m.mtp.declare_inputs(b, g, tw, m.media));
|
||||
RAD_ARCH_TRY(layer(b, m, m.draft, m.mtp.nm, 45, true));
|
||||
@@ -591,9 +749,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
// with every buffer above. Its weight groups follow the 45 layers and the MTP layer's.
|
||||
if (m.media) RAD_ARCH_TRY(m.vit.declare(b, meta, ctx, nm, 4096, 46));
|
||||
rad_note(b,
|
||||
"GLM-5.3: TP%d, 45 mHC layers, 34 KDA + 11 sparse MLA, mixed MXFP4/FP8, native MTP "
|
||||
"GLM-5.3: TP%d, 45 mHC layers, 34 KDA + 11 sparse MLA, %s trunk, native MTP "
|
||||
"%s, vision %s",
|
||||
world, m.have_mtp ? "enabled" : "disabled", m.media ? "enabled" : "disabled");
|
||||
world, m.trunk_rot ? "IQ8R" : "bf16", m.have_mtp ? "enabled" : "disabled",
|
||||
m.media ? "enabled" : "disabled");
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -678,6 +837,10 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
out->tp_attn_rows_ok = 1;
|
||||
/* --kv-cache-dtype fp8: the latent attention cache as E4M3 (declare, kv_groups). */
|
||||
out->kv_fp8_ok = 1;
|
||||
/* Nearly every launch of a decode pass depends on the one before it. Chained, at TP4 on four
|
||||
* R9700 with a 64k context, the step went from 23.82 to 23.37 ms over four sequences and from
|
||||
* 16.15 to 15.90 ms at one, with the same tokens out. */
|
||||
out->chain_pays = RAD_CHAIN_ALWAYS;
|
||||
return RAD_OK;
|
||||
}
|
||||
} // namespace glm5next
|
||||
|
||||
@@ -184,12 +184,6 @@ struct Model {
|
||||
static Model g_model[RAD_MAX_SLOTS];
|
||||
|
||||
/* ================================================================== declare helpers */
|
||||
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));
|
||||
}
|
||||
|
||||
/* A biased linear [N, K] (bias absent with `bias` false), read whole, over at most `rows` rows,
|
||||
* its activation and residual in the epilogue. The weight is mapped by the caller (`mapped`) or
|
||||
* copied from `src`.weight. `adt` is the activation's dtype ("bf16", or "f32" with an f32
|
||||
@@ -579,11 +573,7 @@ static int declare_dit(RadBuilder* b, Model& m) {
|
||||
RAD_ARCH_TRY(linear(b, nm, m.latent_in, "dit.latent_in", "model.latent_in", D, m.C, L2,
|
||||
m.b_lx, m.b_x, acc, gx));
|
||||
/* The conditioning rows from the lane's store. */
|
||||
m.op_ccopy = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, kCond), RAD_INT("n", D),
|
||||
RAD_STR("from", "bf16"), RAD_STR("to", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.b_cstore }, { m.b_x });
|
||||
m.op_ccopy = cast_op(b, kCond, D, "bf16", "bf16", m.b_cstore, m.b_x);
|
||||
/* ---- the timestep: the sinusoid of 1000 sigma, time_in, silu. The reference passes its
|
||||
* time_factor (1000) where timestep_embedding takes max_period, so the model was trained on
|
||||
* a period of 1000, and the time is scaled by the default factor, also 1000. */
|
||||
@@ -880,11 +870,7 @@ static int declare_query(RadBuilder* b, Model& m) {
|
||||
m.op_qpost = affine_norm(b, Q, D, 1e-5, m.q_pw, m.q_pb, m.b_qx, m.b_qh);
|
||||
RAD_ARCH_TRY(linear(b, nm, m.q_head, "geo.output_proj", "vae.geo_decoder.output_proj", 1, D, Q,
|
||||
m.b_qh, m.b_qlogit, acc, g));
|
||||
m.op_qcast = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, Q), RAD_INT("n", 1),
|
||||
RAD_STR("from", "bf16"), RAD_STR("to", "f32")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.b_qlogit }, { m.b_field });
|
||||
m.op_qcast = cast_op(b, Q, 1, "bf16", "f32", m.b_qlogit, m.b_field);
|
||||
return m.op_four && m.op_qn1 && m.op_qqn && m.op_qattn && m.op_qn3 && m.op_qpost &&
|
||||
m.op_qcast
|
||||
? RAD_OK : RAD_E_INVAL;
|
||||
|
||||
@@ -4,30 +4,29 @@
|
||||
* rmsnorm -> q/k/v gemm_nt_q -> per-head q/k RMSNorm -> rope -> kv_store -> attn_paged
|
||||
* -> quant_act_fp8 -> o gemm_nt_q -> [all_reduce] -> residual add
|
||||
*
|
||||
* Unlike AttnFP8, the projections stay separate so Q and K can be normalized independently before
|
||||
* Unlike AttnQ, the projections stay separate so Q and K can be normalized independently before
|
||||
* rotation. The weights and all non-attention activations use the same contracts as the other FP8
|
||||
* blocks in rad_fp8.h.
|
||||
* blocks in rad_linear.h.
|
||||
*/
|
||||
#ifndef HYV3_ATTENTION_H
|
||||
#define HYV3_ATTENTION_H
|
||||
|
||||
#include <arch/rad_fp8.h>
|
||||
#include <arch/rad_linear.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct AttnQKFP8 {
|
||||
struct AttnQK {
|
||||
struct Wire {
|
||||
rad_buf x = 0; /* [max_tok, n_embd] residual stream */
|
||||
ActFP8 h{}; /* [max_tok, n_embd] normed input, then o output */
|
||||
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], projected, normed and rotated */
|
||||
rad_buf v = 0; /* [max_tok, kv_dim], projected */
|
||||
ActFP8 attn{}; /* [max_tok, q_dim] attention output */
|
||||
ActQ attn{}; /* [max_tok, q_dim] attention output */
|
||||
};
|
||||
|
||||
struct Src {
|
||||
@@ -46,9 +45,9 @@ struct AttnQKFP8 {
|
||||
rad_kvgroup kv = 0;
|
||||
|
||||
rad_weight w_norm = 0, w_q_norm = 0, w_k_norm = 0;
|
||||
LinearFP8 q{}, k{}, v{}, o{};
|
||||
NormQuantFP8 nq_h{};
|
||||
QuantFP8 q_attn{};
|
||||
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 and BF16 cache store, decode band */
|
||||
@@ -60,7 +59,7 @@ struct AttnQKFP8 {
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
};
|
||||
|
||||
inline int AttnQKFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
inline int AttnQK::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
rad_kvgroup group, const Wire& wire, const Src& src,
|
||||
bool fold, bool add_out) {
|
||||
g = geom;
|
||||
@@ -112,7 +111,8 @@ inline int AttnQKFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
{w.k}, {w.k});
|
||||
|
||||
const rad_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_PARAMS(RAD_RANGE("q_len", 1, g.max_tok),
|
||||
RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", 0), RAD_INT("n_head", g.n_head),
|
||||
RAD_INT("block_size", RAD_KV_BLOCK),
|
||||
@@ -129,8 +129,8 @@ inline int AttnQKFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
{w.k, w.v}, {});
|
||||
|
||||
/* The standalone chain stays available for prefill, scaled/multicomponent rotary, the int8
|
||||
* cache and libraries without the fold. A 128-channel BF16 decode prologue is otherwise five tiny
|
||||
* launches; the fused kernel preserves the BF16 norm rounding before the rotary. */
|
||||
* cache and libraries without the fold. A 128-channel BF16 decode prologue is otherwise five
|
||||
* tiny launches; the fused kernel preserves the BF16 norm rounding before the rotary. */
|
||||
if (g.head_dim == 128 && !std::strcmp(g.dtype, "bf16") &&
|
||||
!std::strcmp(g.kv_dtype, "bf16") &&
|
||||
!g.rope_mc && g.yarn.factor == 0.0f &&
|
||||
@@ -142,7 +142,8 @@ inline int AttnQKFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
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("block_size", rad_kv_block_size(b, kv)),
|
||||
RAD_INT("v_norm", 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;
|
||||
@@ -154,13 +155,7 @@ inline int AttnQKFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
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",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
@@ -169,7 +164,7 @@ inline int AttnQKFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
return op_attn && op_kv_store && (!add_out || op_add) ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
inline void AttnQKFP8::step(RadCtx* c, const RadBatch* batch) const {
|
||||
inline void AttnQK::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;
|
||||
|
||||
@@ -17,14 +17,13 @@
|
||||
#include <arch/rad_arch.h>
|
||||
#include "hyv3_attention.h"
|
||||
#include "rad_abi_layout.h"
|
||||
#include <arch/rad_block_mlp_fp8.h>
|
||||
#include <arch/rad_block_moe_fp8.h>
|
||||
#include <arch/rad_block_mlp_q.h>
|
||||
#include <arch/rad_block_moe_q.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace HYV3_NS {
|
||||
@@ -32,9 +31,9 @@ using namespace rad::arch;
|
||||
|
||||
struct Layer {
|
||||
bool dense = false;
|
||||
AttnQKFP8 attn{};
|
||||
MlpFP8 dense_mlp{};
|
||||
MoeFP8 moe{};
|
||||
AttnQK attn{};
|
||||
MlpQ dense_mlp{};
|
||||
MoeQ moe{};
|
||||
};
|
||||
|
||||
struct Model {
|
||||
@@ -44,12 +43,12 @@ struct Model {
|
||||
rad_kvgroup kv_full = 0;
|
||||
|
||||
rad_buf x = 0, h_out = 0, logits = 0;
|
||||
ActFP8 h{};
|
||||
ActQ h{};
|
||||
rad_buf q = 0, k = 0, v = 0;
|
||||
ActFP8 attn{};
|
||||
ActQ attn{};
|
||||
rad_buf dense_gate_up = 0;
|
||||
ActFP8 dense_ffn{};
|
||||
MoeFP8::Wire mw{};
|
||||
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;
|
||||
@@ -105,16 +104,14 @@ static int check_model_config(const RadModelMeta* meta, const Geom& g, Model& mo
|
||||
const int64_t moe_intermediate = meta_text_geti(meta, "moe_intermediate_size", 0);
|
||||
const int64_t n_ff_shared = meta_text_geti(meta, "expert_hidden_dim", 0);
|
||||
model.n_ff_expert = meta_text_geti(meta, "expert_hidden_dim", 0);
|
||||
const int64_t route_norm = meta_text_geti(meta, "route_norm", 0);
|
||||
const double route_scale = meta_text_getf(meta, "router_scaling_factor", 1.0);
|
||||
const char* schedule = meta_text_gets(meta, "mlp_layer_types", nullptr);
|
||||
std::vector<int> kinds;
|
||||
|
||||
if (first_dense != 1 || n_expert != meta->n_expert || top_k != meta->n_expert_used ||
|
||||
n_expert != 128 || top_k != 8 || n_shared != 1 || model.n_ff_expert != 768 ||
|
||||
n_ff_shared != 768 || moe_intermediate != 1536 || route_norm != 1 ||
|
||||
!std::isfinite(route_scale) || route_scale <= 0 ||
|
||||
std::fabs(route_scale - 2.826) > 1e-6 || model.n_ff_expert % RAD_FP8_BLOCK != 0) {
|
||||
n_ff_shared != 768 || moe_intermediate != 1536 || !std::isfinite(route_scale) ||
|
||||
std::fabs(route_scale - 2.826) > 1e-6 || model.n_ff_expert % RAD_SCALE_GROUP != 0) {
|
||||
fprintf(stderr, "radiance: hyv3: unsupported MoE geometry/config; expected 128 experts, "
|
||||
"top-8, 768-wide routed and shared experts, normalized "
|
||||
"sigmoid routing scaled by 2.826, and one dense first layer\n");
|
||||
@@ -123,7 +120,8 @@ static int check_model_config(const RadModelMeta* meta, const Geom& g, Model& mo
|
||||
if (schedule && *schedule) {
|
||||
RAD_ARCH_TRY(parse_layer_kinds("hyv3", schedule, {"sparse"}, "dense", &kinds));
|
||||
if ((int64_t)kinds.size() != g.n_layer) {
|
||||
fprintf(stderr, "radiance: hyv3: mlp_layer_types names %zu layers; the model has %lld\n",
|
||||
fprintf(stderr,
|
||||
"radiance: hyv3: mlp_layer_types names %zu layers; the model has %lld\n",
|
||||
kinds.size(), (long long)g.n_layer);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
@@ -138,20 +136,11 @@ static int check_model_config(const RadModelMeta* meta, const Geom& g, Model& mo
|
||||
}
|
||||
|
||||
const int64_t shared_width = n_ff_shared * n_shared;
|
||||
if (shared_width <= 0 || shared_width % RAD_FP8_BLOCK != 0) return RAD_E_SHAPE;
|
||||
if (shared_width <= 0 || shared_width % RAD_SCALE_GROUP != 0) return RAD_E_SHAPE;
|
||||
model.n_ff_shared = shared_width;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static void block_slice_128(int64_t width, int world, int rank, int64_t* lo, int64_t* hi) {
|
||||
const int64_t blocks = width / RAD_FP8_BLOCK;
|
||||
const int64_t base = blocks / world, rem = blocks % world;
|
||||
const int64_t first = rank * base + std::min<int64_t>(rank, rem);
|
||||
const int64_t count = base + (rank < rem ? 1 : 0);
|
||||
*lo = first * RAD_FP8_BLOCK;
|
||||
*hi = (first + count) * RAD_FP8_BLOCK;
|
||||
}
|
||||
|
||||
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)
|
||||
@@ -216,8 +205,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
|
||||
/* The router is replicated, while the routed experts are expert-parallel. The shared expert
|
||||
* is split only on whole FP8 scale blocks; the final block remainder is assigned to early
|
||||
* ranks. At TP2, routed and shared BF16 outputs are all-reduced separately before FP32 combine. */
|
||||
MoeFP8::Config mc{};
|
||||
* ranks. At TP2, routed and shared BF16 outputs are all-reduced separately before FP32
|
||||
* combine. */
|
||||
MoeQ::Config mc{};
|
||||
mc.n_expert_all = n_expert_all;
|
||||
mc.n_expert = n_expert_local;
|
||||
mc.expert_base = n_expert_local * g.rank;
|
||||
@@ -296,16 +286,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_WEIGHTS(m.token)),
|
||||
{}, {m.x});
|
||||
if (g.world > 1)
|
||||
m.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.x}, {m.x});
|
||||
m.embed_ar = decl_all_reduce_exact(b, g, m.x);
|
||||
|
||||
AttnQKFP8::Wire aw{};
|
||||
AttnQK::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;
|
||||
MlpFP8::Wire dw{};
|
||||
MlpQ::Wire dw{};
|
||||
dw.x = m.x; dw.h = m.h; dw.gate_up = m.dense_gate_up; dw.ffn = m.dense_ffn;
|
||||
|
||||
m.layers.resize((size_t)g.n_layer);
|
||||
@@ -317,7 +302,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
#else
|
||||
const char* pre = nm.ckpt("model.layers.%lld", (long long)l);
|
||||
#endif
|
||||
AttnQKFP8::Src as{};
|
||||
AttnQK::Src as{};
|
||||
#if HYV3_GGUF_SOURCE
|
||||
as.norm = nm.ckpt("%s.attn_norm.weight", pre);
|
||||
as.q = nm.ckpt("%s.attn_q.weight", pre);
|
||||
@@ -347,7 +332,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
}
|
||||
|
||||
if (lay.dense) {
|
||||
MlpFP8::Src ds{};
|
||||
MlpQ::Src ds{};
|
||||
#if HYV3_GGUF_SOURCE
|
||||
ds.norm = nm.ckpt("%s.ffn_norm.weight", pre);
|
||||
ds.gate = nm.ckpt("%s.ffn_gate.weight", pre);
|
||||
@@ -367,7 +352,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
return status;
|
||||
}
|
||||
} else {
|
||||
MoeFP8::Src ms{};
|
||||
MoeQ::Src ms{};
|
||||
ms.cfg = mc;
|
||||
#if HYV3_GGUF_SOURCE
|
||||
ms.norm = nm.ckpt("%s.ffn_norm.weight", pre);
|
||||
@@ -388,7 +373,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
ms.shared = nm.ckpt("%s.shared_mlp", mlp);
|
||||
#endif
|
||||
#if !HYV3_FP8_SOURCE
|
||||
status = MoeFP8::probe(b, nm, (int)l, ms, &ms.cfg);
|
||||
status = MoeQ::probe(b, nm, (int)l, ms, &ms.cfg);
|
||||
if (status < 0) {
|
||||
fprintf(stderr, "radiance: HYV3: expert format probe failed at layer %lld (%d)\n",
|
||||
(long long)l, status);
|
||||
@@ -423,7 +408,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
{m.h_out}, {m.logits});
|
||||
|
||||
rad_note(b, "HYV3: %lld layers (dense first, then top-%lld/%lld sigmoid MoE), %lld/%lld "
|
||||
"attention/KV heads x %lld; expert width %lld, shared width %lld, router scale %.3f",
|
||||
"attention/KV heads x %lld; expert width %lld, shared width %lld, router scale "
|
||||
"%.3f",
|
||||
(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)m.n_ff_shared, mc.route_scale);
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/inkling2 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(inkling2 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(inkling2 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/inkling2.cpp)
|
||||
File diff suppressed because it is too large.
Load diff
Loaded 100 of 979 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user