Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 | ||
|
|
b16685e06b | ||
|
|
62b7f51c3b | ||
|
|
6b13b0624e | ||
|
|
74ed3ef8b4 | ||
|
|
a32d0dd71c | ||
|
|
e476d8d6d0 |
No files matched your search
+13
-6
@@ -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.3.0 LANGUAGES C CXX)
|
||||
project(radiance VERSION 2.4.0 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}
|
||||
@@ -321,10 +332,6 @@ endif()
|
||||
if(CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64|amd64)$")
|
||||
add_subdirectory(libavx)
|
||||
endif()
|
||||
# exl3: radiance-exl3, EXL3 trellis experts (exllamav3's format) -- the gfx1201 kernel library
|
||||
# exl3r4d (built when RAD_GPU_TARGETS names gfx1201), the host reference exl3ref and the `exl3`
|
||||
# quantiser. See exl3/README.md.
|
||||
add_subdirectory(exl3)
|
||||
add_subdirectory(arch)
|
||||
# spechub: the linear-MTP coupling kernels (--draft-coupling). Built by default; without the flag
|
||||
# no op resolves to its rows.
|
||||
|
||||
+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
|
||||
|
||||
|
||||
@@ -37,7 +37,9 @@ Written by Deadcode, with contributions from:
|
||||
(rotated experts and the LiLiCorr backbone reading rotated int8 codes), and the bidirectional
|
||||
media span counted from the window group's first position, and Gemma 4 dense on EXL3-V3
|
||||
(gemma4_exl3, with a quantised token table and per-layer table), and NVIDIA's 2-bit
|
||||
Nemotron-3.5-Bolt-74B-A9B on one card
|
||||
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
|
||||
@@ -95,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
|
||||
@@ -156,7 +159,7 @@ Written by Deadcode, with contributions from:
|
||||
- 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
|
||||
@@ -182,7 +185,9 @@ Written by Deadcode, with contributions from:
|
||||
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
|
||||
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,
|
||||
@@ -201,7 +206,7 @@ Written by Deadcode, with contributions from:
|
||||
trapping past its deadline, and gemm_fp8a8's narrow form with its scales staged through LDS and
|
||||
its gated three-tile form at 8 waves, and the DeepSeek-V4.1-Flash fork's v1.1 configurations and
|
||||
measurements, with its ports of mikoskinen's full-vocabulary DSpark walk and adaptive-window
|
||||
drafting
|
||||
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
|
||||
@@ -237,8 +242,9 @@ Written by Deadcode, with contributions from:
|
||||
- everplays: the paged attention at seven queries a KV head, head_dim 128 (Nanbeige4.3-33B), and
|
||||
Recursive Flint -- its plugin, the sink-aware WMMA prefill attention and the fused prologue at
|
||||
rotary_dim 0
|
||||
- Kezi: the decode tile arms of the int4 and int5 x int8 GEMM, and draft trees for Qwen3.8-27B's
|
||||
DFlash2 drafts (the tree verify rows and the gdn fold)
|
||||
- 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
|
||||
@@ -260,20 +266,27 @@ Written by Deadcode, with contributions from:
|
||||
--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
|
||||
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, and the
|
||||
dashboard's per-LoRA attribution
|
||||
- kaczy44: Gemma 4 26B-A4B's vision tower and rad-convert --add-vision
|
||||
- Itoash: a tool-call delimiter that does not end the turn, and Ling 3.0's function names ending at
|
||||
whitespace, and LTX-2's chunk ceiling raised to 40
|
||||
- jintakhan: gemma4_bf16's sliding-window attention ported to gemma4
|
||||
- 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 the token table as a Lloyd codebook (embed_tq)
|
||||
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
|
||||
@@ -284,6 +297,26 @@ Written by Deadcode, with contributions from:
|
||||
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.
|
||||
@@ -350,11 +383,13 @@ Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
||||
radiance-exl3
|
||||
-------------
|
||||
|
||||
exl3/ is radiance-exl3 (Copyright 2026 Dylan Johnston, Apache-2.0; exl3/LICENSE and exl3/NOTICE),
|
||||
imported from mikoskinen/r9700-exact-serving: the EXL3 kernel libraries exl3r4d and exl3ref, the
|
||||
exl3 quantiser and their common decode. arch/common/exl3/ carries copies of three of its headers.
|
||||
Its EXL3 decode is a transcription of exllamav3's (Copyright (c) 2025 Turboderp, MIT License), whose
|
||||
notice exl3/NOTICE reproduces.
|
||||
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
|
||||
-------------------
|
||||
|
||||
@@ -22,6 +22,7 @@ To support the development of radiance: [Patreon](https://patreon.com/StillDeadC
|
||||
|
||||
| model | container | get it | fleet file |
|
||||
|---|---|---|---|
|
||||
| Qwen3-VL 32B W4A8: writing and visual QA | `qwen3-vl-32b-instruct-abliterated-w4a8.rad` | [Convert](docs/QWEN3-VL.md) | [Fleet entry](docs/QWEN3-VL.md) |
|
||||
| Qwen3.8-Flash-Next: IQR-V4 experts, int8 trunk, MTP, vision | `qwen3.8-next-flash-iqr-v4.rad` (113 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-next-flash-iqr-v4) | `tp1.yaml`, `tp2.yaml` |
|
||||
| GLM-5.3-Flash: IQR-V4 experts, IQ8R trunk, int8 latent cache, four cards with the experts tiered to host memory | `glm53-flash-iqr-v4.rad` (159 GiB) | [download](https://huggingface.co/animusnull/glm-5.3-flash-iqr-v4) | `tp4.yaml` |
|
||||
| DeepSeek-V4.1-Flash 1017 uncensored (refusals removed): llama.cpp's blocks at 2.83 bits a weight (its DSpark drafter's MXFP4 experts are not served), exact fp8 cache, two or four cards with the experts tiered to host memory ([docs/ARCHITECTURES.md](docs/ARCHITECTURES.md#deepseek41-deepseek-v41-flash)) | `deepseek-v4.1-flash-1017-uncensored.rad` (134 GiB of experts) | [download](https://huggingface.co/bakon3/DeepSeek-V4.1-Flash-1017-uncensored-rad) | — |
|
||||
@@ -39,14 +40,9 @@ To support the development of radiance: [Patreon](https://patreon.com/StillDeadC
|
||||
| Spark X2.6 4B IQ8R: rotated int8 trunk, optional bf16 head, layers 0-11 kept bf16, optional DSpark | `spark-x2.6-4b-radiance-iq8r-diverse.rad` .. `spark-x2.6-4b-radiance-iq8r-bf16-head-dspark.rad` (4.5 to 6.6 GiB) | [download](https://huggingface.co/gostar77/spark-x2.6-4b-radiance) | — |
|
||||
| Hy-Memory-30B-A3B bf16 | `hy-memory-30b-a3b-bf16.rad` (56 GiB) | [download](https://huggingface.co/gostar77/hy-memory-30b-a3b-radiance) | — |
|
||||
| Hy-Memory-30B-A3B W4 GPTQ: attention, dense MLP and routed experts | `hy-memory-30b-a3b-w4-gptq-full-1m.rad` (15 GiB) | [download](https://huggingface.co/gostar77/hy-memory-30b-a3b-radiance) | — |
|
||||
| Gemma 4 31B: GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-w4a8) | — |
|
||||
| Gemma 4 31B w5: GPTQ int5 trunk (a scale and a zero point per 128 weights), MTP, vision | `gemma4-31b-w5.rad` (23 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-w5) | — |
|
||||
| Gemma 4 31B heretic-ara (refusals removed): GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-heretic-ara-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-heretic-ara-w4a8) | — |
|
||||
| Gemma 4 31B: int8 trunk and lm_head (no calibration), MTP, vision | `gemma4-31b-i8g.rad` (33 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-i8g) | — |
|
||||
| Gemma 4 31B heretic-ara (refusals removed): int8 trunk and lm_head (no calibration), MTP, vision | `gemma4-31b-heretic-ara-i8g.rad` (33 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-heretic-ara-i8g) | — |
|
||||
| Gemma 4 31B EXL3-V3: 3.25 to 6.0 bits a weight (`mad` codebook), int8 `lm_head`, assistant head, vision, one, two or four cards (RDNA4) | `gemma4-31b-exl3-3.25bpw.rad` .. `gemma4-31b-exl3-6.0bpw.rad` (16.8 to 26.2 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-exl3) | — |
|
||||
| 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) | — |
|
||||
| Gemma 4 12B EXL3-V3: 3.25 to 6.0 bits a weight (`mad` codebook), 4-bit embedding in host RAM, int8 `lm_head`, assistant head, vision, audio, one or two cards (RDNA4) | `gemma4-12b-exl3-3.25bpw.rad` .. `gemma4-12b-exl3-6.0bpw.rad` (6.2 to 9.7 GiB) | [download](https://huggingface.co/keptn/gemma4-12b-exl3) | — |
|
||||
| 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) | — |
|
||||
@@ -78,10 +74,13 @@ To support the development of radiance: [Patreon](https://patreon.com/StillDeadC
|
||||
| Recursive Flint (39.8B, about 2.5B active) IQ8R: rotated int8 trunk and experts, two cards | `flint-iq8r.rad` (38 GiB) | [download](https://huggingface.co/StillDeadcode/flint-iq8r) | — |
|
||||
| Ling-3.0-tiny IQ8R: rotated int8 trunk and experts, one card | `ling-3.0-tiny-iq8r.rad` (7.9 GiB) | [download](https://huggingface.co/StillDeadcode/ling-3.0-tiny-iq8r) | — |
|
||||
| NVIDIA Nemotron-3.5-Bolt-74B-A9B 2-bit: NVIDIA's IQ2_XXS experts and Q8_0 linears as stored, IQ8R Mamba projections, LiLiCorr drafter, one card | `nemotron74-2bit.rad` (26.66 GiB of weights) | [convert](data/recipes/nemotron74-nvidia-24gb-iq8r.recipe) | — |
|
||||
| NVIDIA Nemotron-3.5-Bolt-E4B EXL3-V3: 4.07 or 6.0 bits a weight (`mad` codebook), 5-bit PLE in host RAM, int8 `lm_head`, int8 DFlash drafter, vision, audio, one or two cards (RDNA4) | `nemotron-3.5-bolt-e4b-exl3-4.07bpw.rad` (7.5 GiB), `nemotron-3.5-bolt-e4b-exl3-6.0bpw.rad` (8.3 GiB) | [download](https://huggingface.co/keptn/nemotron-3.5-bolt-e4b-exl3) | — |
|
||||
| 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` |
|
||||
| Qwen3-Embedding (0.6B, 4B, 8B) bf16: text embeddings, one card | the checkpoint as it ships | [Qwen checkpoint](https://huggingface.co/collections/Qwen/qwen3-embedding) | `tp1.yaml` |
|
||||
| Qwen3-Reranker (0.6B, 4B, 8B) bf16: text document relevance, one card | the checkpoint as it ships | [Qwen checkpoint](https://huggingface.co/collections/Qwen/qwen3-reranker) | `tp1.yaml` |
|
||||
| Inkling 2 Mini IQ4R-V4 + DFlash2: the experts IQR-V4's four-bit computed trellis (GPTQ against recorded Hessians), the attention and the head rotated int8, the embedding int8, incoai's DFlash2 drafter (four-bit computed trellis, down int8), the vision tower bf16; text and images, one or two cards (`draft-window: adaptive`) ([geometry](docs/ARCHITECTURES.md#inkling2-inkling-2-mini)) | `inkling-2-mini-iq4r-v4.rad` (14.43 GiB) | [download](https://huggingface.co/StillDeadcode/inkling-2-mini-iq4r-v4) · [convert](data/recipes/inkling2-mini-iq4r-v4.recipe) | — |
|
||||
|
||||
**Not served by this version.** A container whose weights are block FP8, MXFP4, M2XFP4 or
|
||||
@@ -103,12 +102,11 @@ 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.
|
||||
The Gemma 4 and Nemotron-3.5-Bolt-E4B EXL3-V3 containers are keptn42's (codebook `mad`, RDNA4
|
||||
`exl3i` kernels; each repository has the recipes, speed and KL tables). To convert Google's bf16
|
||||
Gemma 4 31B checkpoint yourself without EXL3, `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).
|
||||
|
||||
TranslateGemma 27B is converted from Google's bf16 checkpoint with
|
||||
`data/recipes/translategemma-27b-i8a8.recipe`, an int8 trunk rounded without calibration data.
|
||||
@@ -155,8 +153,8 @@ card works best with Resizable BAR on (Above 4G Decoding and Resizable BAR in th
|
||||
without it the engine keeps kernel arguments in pinned host memory, and every dispatch reads them
|
||||
over the link. The image
|
||||
is [`stilldeadcode/radiance`](https://hub.docker.com/r/stilldeadcode/radiance), with its kernels
|
||||
built for `gfx1201` (RDNA4), `gfx11-generic` (RDNA3) and `gfx1151` (Strix Halo). Pull it, clone
|
||||
this repository for its compose files, then start one of them:
|
||||
built for `gfx1201` and `gfx12-generic` (RDNA4), `gfx11-generic` (RDNA3) and `gfx1151` (Strix
|
||||
Halo). Pull it, clone this repository for its compose files, then start one of them:
|
||||
|
||||
```sh
|
||||
docker pull stilldeadcode/radiance
|
||||
@@ -268,12 +266,10 @@ here.
|
||||
| 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 EXL3-V3 | `tp: 2, max-num-seqs: 8, max-model-len: 262144, kv-cache-dtype: i8, vision-tower-placement: ram, num-speculative-tokens: 6, draft-window: adaptive, max-num-batched-tokens: 2048, temp: 1.0, top-p: 0.95, top-k: 64`; `tp: 1` (up to 4.89 bpw) or `tp: 4` |
|
||||
| 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 |
|
||||
| Gemma 4 12B EXL3-V3 | `tp: 1, max-num-seqs: 8, max-model-len: 262144, kv-cache-dtype: i8, vision-tower-placement: ram, num-speculative-tokens: 6, draft-window: adaptive, max-num-batched-tokens: 2048, temp: 1.0, top-p: 0.95, top-k: 64`; `tp: 2` on two cards |
|
||||
| NVIDIA-Nemotron-3.5-Bolt-E4B EXL3-V3 | `tp: 1, max-num-seqs: 8, max-model-len: 65536, kv-cache-dtype: i8, num-speculative-tokens: 7, temp: 1.0, top-p: 0.95, top-k: 64`; `tp: 2` on two cards |
|
||||
| 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` |
|
||||
@@ -322,10 +318,11 @@ 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.
|
||||
memory, so its VRAM goes to the KV cache. On one card, Gemma 4 31B EXL3-V3 holds up to 202,384
|
||||
tokens of context at 4.89 bpw and 6.0 bpw does not fit; two and four cards hold full 262,144-token
|
||||
context across 8 sequences. The Bolt-E4B EXL3-V3 container ships an int8 DFlash drafter trained on
|
||||
blocks of 8 (`num-speculative-tokens: 7`); older Bolt-E4B containers with a block-FP8 drafter need
|
||||
`num-speculative-tokens: 0`.
|
||||
|
||||
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
|
||||
|
||||
+14
-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 44u
|
||||
#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
|
||||
|
||||
@@ -109,6 +109,8 @@ 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)
|
||||
@@ -154,6 +156,7 @@ 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)
|
||||
@@ -292,6 +295,7 @@ 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)
|
||||
@@ -339,6 +343,8 @@ 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)
|
||||
@@ -519,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)
|
||||
|
||||
+81
-7
@@ -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 */
|
||||
|
||||
@@ -311,6 +326,16 @@ typedef struct RadBuildCtx {
|
||||
* 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. */
|
||||
@@ -341,7 +366,15 @@ static inline int rad_ctx_draft_head(const RadBuildCtx* ctx) {
|
||||
* `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 */
|
||||
@@ -598,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
|
||||
@@ -947,7 +998,6 @@ 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
|
||||
@@ -955,6 +1005,12 @@ typedef struct RadEncoderDecl {
|
||||
* 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);
|
||||
@@ -1044,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 + ...)
|
||||
@@ -1134,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
|
||||
@@ -1927,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,
|
||||
@@ -1959,6 +2025,14 @@ typedef struct RadChatFormat {
|
||||
* 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. */
|
||||
|
||||
@@ -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 */
|
||||
@@ -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,
|
||||
|
||||
@@ -383,6 +383,12 @@ typedef struct RadBatch {
|
||||
* `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:
|
||||
|
||||
@@ -135,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.
|
||||
@@ -178,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])) };
|
||||
|
||||
|
||||
@@ -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)
|
||||
@@ -1,8 +0,0 @@
|
||||
Copied, unmodified apart from one include path, from radiance-exl3 in this tree (exl3/, Apache-2.0,
|
||||
Copyright 2026 Dylan Johnston; see exl3/LICENSE and exl3/NOTICE):
|
||||
exl3_abi.h exl3/include/exl3_abi.h (op schemas, operand positions, interface version)
|
||||
exl3_encoding.h exl3/include/exl3_encoding.h (the canonical exl3 encoding; "../common/" dropped)
|
||||
exl3_decode.h exl3/common/exl3_decode.h (declarations; the block uses the inline helpers only)
|
||||
rad_block_moe_q.h reads a layer's EXL3 encoding and issues the extension's whole-expert ops
|
||||
(moe_exl3_gate_up, moe_exl3_down) by their positions here. arch/common is installed on its own, so
|
||||
it carries copies; ctest's exl3_vendor_check fails when they drift from exl3/.
|
||||
@@ -1,909 +0,0 @@
|
||||
/* exl3_abi.h -- the interface between the EXL3 plugins: the two routed-expert GEMM ops, the routing
|
||||
* contract they read, the weight planes they read, and one parse of their geometry.
|
||||
* Header-only C. The encoding itself is include/exl3_encoding.h.
|
||||
*
|
||||
* Every library that implements `moe_exl3_gate_up` / `moe_exl3_down` exports exl3_schema_at() as its
|
||||
* schemas -- the reference (kernels/exl3ref) and the device library (kernels/exl3r4d) -- so the two
|
||||
* cannot declare different schemas (the loader refuses the second plugin if they do: docs/OPS.md
|
||||
* :139-150 at radiance 1.3.0) and `rad-schemas exl3ref.so exl3r4d.so` prints no difference.
|
||||
* docs/OPS-exl3.md is the prose form of the schemas below and is checked against them.
|
||||
*
|
||||
* Both sides check EXL3_IFACE_VERSION. Bump it on ANY change below: a schema, an operand position,
|
||||
* the routing contract, the planes' forms or the geometry rule.
|
||||
*
|
||||
* VERSION 2: ONE WEIGHT-TABLE OPERAND PER PLANE PER PARITY CLASS. Version 1 carried all of an
|
||||
* expert's planes in one table operand, and at radiance 1.3.0 that weight could be served by no host
|
||||
* row without a layout hook (core/build/rad_builder.cpp:1385, 1453-1460) and handed to the per-op
|
||||
* oracle only decoded to dense W (core/runtime/oracle.cpp:425-560), which a reference computing in
|
||||
* exllamav3's rounding order cannot read. One plane an operand is stored as it is wherever no kernel
|
||||
* re-lays it, and the oracle passes a single-plane selection through unchanged
|
||||
* (core/format/encoding.cpp:306-321). See "THE PLANES" below.
|
||||
*
|
||||
* VERSION 3: "EPI 1", gate_up's epilogue doing down's first step. Both ops take a REQUIRED flag
|
||||
* `h_rot`. With h_rot = 1, gate_up also reads down's input scales (`dn_suh`, `dn_suh_odd`) and writes
|
||||
* h ALREADY ROTATED for down -- exactly down's step 1, so the pair is bit-identical to the h_rot = 0
|
||||
* pair -- and down reads it as rotated and skips that step. Down's operands are unchanged; gate_up's
|
||||
* operands after `svh` move by one (and by two after `svh_odd`). With h_rot = 0 both ops compute what
|
||||
* version 2 computed, to the bit.
|
||||
*
|
||||
* VERSION 4: gate_up's input rotation as an op of its own, so an architecture can issue independent
|
||||
* work between the rotation and the routed GEMM. A third op, `moe_exl3_prep_gu`, writes xr -- every
|
||||
* sorted row's input rotated for gate and for up, exactly the prologue gate_up runs -- and gate_up
|
||||
* takes a REQUIRED flag `a_rot`: with a_rot = 1 its `a` IS that xr and it does not rotate (nor read
|
||||
* suh / suh.1). prep_gu -> gate_up(a_rot = 1) gives the bits gate_up(a_rot = 0) gives. With a_rot = 0
|
||||
* gate_up is version 3's, to the bit. Operand lists of gate_up and down are unchanged; prep_gu is
|
||||
* schema 2, after them.
|
||||
*
|
||||
* VERSION 5: a FOURTH op, `moe_exl3_gate_up_down`, the whole routed-expert chain of a decode pass as
|
||||
* one op -- prep_gu's rotation, gate_up with h_rot = 1, down with h_rot = 1 -- so a library can run it
|
||||
* as ONE launch (exl3r4d's fused kernel: no dispatch boundaries, down's work fills gate_up's tail). Its
|
||||
* output is exactly down's y from gate_up(a_rot = 0, h_rot = 1) -> down(h_rot = 1) on the same
|
||||
* operands, to the bit; h and xr are the op's own scratch. Operands: gate_up's planes, then down's
|
||||
* codes and svh (down's suh is gate_up's dn_suh, the same weight), per class (THE OPS below). The
|
||||
* three earlier ops are unchanged; the planes enumeration gains EXL3_P_DN_CODES and EXL3_P_DN_SVH (-1
|
||||
* for the earlier ops). Schema 3, after them.
|
||||
*
|
||||
* VERSION 6: FOUR-CLASS FORMS of gate_up, down and prep_gu -- `moe_exl3_gate_up_mod4`,
|
||||
* `moe_exl3_down_mod4`, `moe_exl3_prep_gu_mod4` -- the experts as four classes by number mod 4, radiance's
|
||||
* `moe_gemm_q_mod4` beside `moe_gemm_q` (its docs/OPS.md, "moe_gemm_q_mod4"): four ranks splitting a five-block
|
||||
* expert give the extra block four places to go instead of two. Separate ops, because the declaration divides a
|
||||
* table op's weights over its table operands by count alone, so the operand list IS the class count. Each is its
|
||||
* two-class op with three more class table sets and N_q / K_q for N_odd / K_odd (THE OPS below). The four earlier
|
||||
* ops are unchanged, to the schema; the new ones are schemas 4, 5, 6, after them. No four-class gate_up_down: its
|
||||
* fused launch's two views do not fit the engine's kernel-argument slot at four classes (docs/OPS-exl3.md).
|
||||
*
|
||||
* VERSION 7: the four-class gate_up_down, `moe_exl3_gate_up_down_mod4` -- version 5's op over
|
||||
* version 6's four classes: gate_up_down's parameters with N_q / K_q for N_odd / K_odd, its operands with classes
|
||||
* 1..3's seven tables after the routing. Its output is exactly moe_exl3_down_mod4(h_rot = 1) of
|
||||
* moe_exl3_gate_up_mod4(a_rot = 0, h_rot = 1) on the same operands, to the bit. Version 6's reason against it was the
|
||||
* slot: a fused kernel that reads no implicit argument has no hidden block, so the explicit 704 bytes fit the 768
|
||||
* (exl3r4d's exl3r4d_gd_mod4.hip). The seven earlier ops are unchanged, to the schema; it is schema 7, after them.
|
||||
*/
|
||||
#ifndef EXL3_ABI_H
|
||||
#define EXL3_ABI_H
|
||||
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "exl3_encoding.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define EXL3_IFACE_VERSION 10
|
||||
|
||||
/* THE FEWEST TOKENS a pass issues moe_exl3_gate_up_down for, and exl3r4d fuses it from -- one build-time value for
|
||||
* the architecture's issue band (QWEN4EXP_EXL3_GD) and the library's fused launch (EXL3R4D_GD_MIN_TOK's default), so
|
||||
* both move together. Not an interface fact: below it the same bits come from the other forms (3 tokens already take
|
||||
* gate_up's split-K 1, so the fused launch at 3 is the split chain's bits). Why 3: at 3 tokens the fused launch beats
|
||||
* the split chain on gfx1201 (tp2 about 76 vs 82 us a layer, tp1 about 138 vs 146), and a whole decode step at 3
|
||||
* concurrent streams is about 1-3% faster with every other concurrency unchanged. An architecture built with 3 (or 1)
|
||||
* loads and serves at tp2. At 1-2 tokens the fused launch is not taken: gate_up runs split-K 2 there and the fused
|
||||
* launch split-K 1 (EXL3R4D_GD_SK2 is a bit-identical split-K-2 arm), and at one stream the fused launch does not make
|
||||
* the engine's step faster. */
|
||||
#ifndef EXL3_GD_MIN_ROWS
|
||||
#define EXL3_GD_MIN_ROWS 3
|
||||
#endif
|
||||
|
||||
/* ===================================================================== THE ROUTING CONTRACT
|
||||
*
|
||||
* What the in-tree router hands a routed-expert GEMM, as read in radiance 1.3.0. Both ops
|
||||
* below consume it exactly as `moe_gemm_q` does, so the in-tree router, scatter and gather serve
|
||||
* them unchanged. Every claim cites the line that makes it.
|
||||
*
|
||||
* WHO WRITES IT. `router_topk` (softmax over ALL n_expert logits, top_k, optional renormalise)
|
||||
* then `moe_scatter`, or the two fused as `router_topk_scatter`, or with the router GEMM in front
|
||||
* as `router_gemm_topk_scatter` (docs/OPS.md:567-570, 601-641; libref/ref_registry.cpp:876-886).
|
||||
* The block reports the five buffers to the heat engine with rad_route_report (abi/rad_runtime.h
|
||||
* :352-369; the struct is RadRouting, :356-364); nothing is read back on the compute stream.
|
||||
*
|
||||
* expert_ids i32 [n_tok, top_k] device. The router's choice for each (token, slot);
|
||||
* RadRouting::expert_ids (rad_runtime.h:357).
|
||||
* expert_w f32 [n_tok, top_k] device. The routing weight of each (token, slot)
|
||||
* (rad_runtime.h:358). NOT READ BY EITHER OP HERE: the
|
||||
* gather (`moe_gather`, or `ar_gather_hc_write` at tp2) multiplies
|
||||
* it in as it sums a token's slots in ascending slot order
|
||||
* (docs/OPS.md:572; libref/ref_registry.cpp:907-909).
|
||||
* sorted_tok i32 [n_tok * top_k] device. The FLATTENED (token, slot) index token*top_k + slot,
|
||||
* grouped by expert by a STABLE counting sort -- not the bare
|
||||
* token id (libref/ref_moe.cpp:3-10; ref_registry.cpp:880-881).
|
||||
* Row i of every expert GEMM output belongs to pair sorted_tok[i].
|
||||
* expert_offset i32 [n_expert + 1] device. Expert e's rows are [off[e], off[e+1]);
|
||||
* off[n_expert] is the LIVE row count (rad_runtime.h:361;
|
||||
* libref/ref_moe.cpp:135-140).
|
||||
* expert_count i32 [n_expert] device. off[e+1] - off[e]; the heat engine's histogram,
|
||||
* written in place via rad_route_counts (rad_runtime.h:359,
|
||||
* 371-377). Not read by either op here.
|
||||
*
|
||||
* DROPPED SLOTS. A slot whose expert is outside the range the sort owns -- [expert_base,
|
||||
* expert_base + n_expert), which is how expert parallelism is spelt, or a negative id for a padded
|
||||
* batch row -- is not counted, and sorted_tok[off[n_expert] .. n_tok*top_k) is -1
|
||||
* (libref/ref_moe.cpp:11-13, 122-126, 144; ref_registry.cpp:364-371, 880-886).
|
||||
*
|
||||
* ROWS PAST off[n_expert] ARE ZEROED BY THE GEMM, WHATEVER sorted_tok HOLDS THERE. Two reasons
|
||||
* a row can be past the live count: a dropped slot (-1), or a PROTECTED expert's row. A layer
|
||||
* that keeps a few experts at bf16 sorts them last (`protect`, docs/OPS.md:646-651) and hands the
|
||||
* quantised GEMMs n_expert = the regular count, so off[n_expert] stops short of the protected
|
||||
* rows, which hold valid flat indices; the protected pair writes those rows AFTER the quantised
|
||||
* down GEMM zeroed them (arch/common/rad_block_moe_q.h:1611-1622). libr4d zeroes every row past
|
||||
* the live count (libr4d/r4d_moe.hip:83-86, 1834-1841, 2221-2222); libref zeroes a row only when
|
||||
* sorted_tok is negative (libref/ref_moe.cpp:285-288), which agrees on dropped slots and not on
|
||||
* protected rows. These ops follow libr4d: row i is zero when i >= off[n_expert] OR
|
||||
* sorted_tok[i] < 0 (or i < off[0], a row no expert owns), across the whole output width.
|
||||
*
|
||||
* WHICH EXPERT OWNS ROW i: the e with off[e] <= i < off[e+1] (experts with no rows have
|
||||
* off[e] == off[e+1] and own nothing). Under `protect` the offsets are in SORT order, not id
|
||||
* order -- the regular experts closed up, then the protected ones (docs/OPS.md:646-651) -- and the
|
||||
* weight tables are declared in the same order (rad_block_moe_q.h:831-834), so "expert e" below
|
||||
* always means offsets index e.
|
||||
*
|
||||
* TWO EXPERT COUNTS. The router's n_expert is the model's; the sort's (`n_local`, or the
|
||||
* scatter's n_expert) is this rank's slice and sizes expert_offset (docs/OPS.md:609-615). The
|
||||
* `n_expert` parameter of both ops below is the SORT's: the length of expert_offset minus one.
|
||||
* Under the intra-expert width split every rank holds a slice of EVERY expert, so the two are
|
||||
* equal there; under expert parallelism they are not.
|
||||
*
|
||||
* THE ROW ORDER OF THE ACTIVATION. The in-tree grouped GEMM says it with `a_order`
|
||||
* (docs/OPS.md:700-721). Here it is FIXED per op and not a parameter: gate_up reads one row per
|
||||
* TOKEN, row sorted_tok[i] / top_k (a_order "token"); down reads one row per (token, slot) in the
|
||||
* scatter's order, row i itself (a_order "sorted"). Gathering the down input a second time hands
|
||||
* every slot of a token the first slot's intermediate and stays fluent -- the failure the
|
||||
* parameter exists to prevent (docs/OPS.md:713-721) -- so the order is part of each op's name.
|
||||
*
|
||||
* `M` IS THE TOKEN COUNT OF A PASS, not the sorted row count (rad_block_moe_q.h:1052-1054): the
|
||||
* kernels read the row count T off the output and M is what the scratch hook and the operand
|
||||
* descriptions size from. T = M * top_k at every issue the in-tree block makes.
|
||||
*/
|
||||
|
||||
/* ===================================================================== THE TWO OPS
|
||||
*
|
||||
* Exact semantics, rounding points and refusals: docs/OPS-exl3.md (the checked prose form). In
|
||||
* one line each, per live row i of expert e, token t = sorted_tok[i] / top_k:
|
||||
*
|
||||
* moe_exl3_gate_up h[i] = f16( silu(had(f16(had(f16(a[t] * suh))) @ What_gate) * svh_gate)
|
||||
* * (had(f16(had(f16(a[t] * suh.1))) @ What_up) * svh_up) )
|
||||
* moe_exl3_down y[i] = bf16( had(f16(had(f16(h[i] * suh))) @ What) * svh )
|
||||
*
|
||||
* moe_exl3_prep_gu xr[i] = [ f16(had(f16(a[t] * suh_e))) | f16(had(f16(a[t] * suh.1_e))) ]
|
||||
* -- gate_up's step 1 for its two halves, side by side (below, "XR"); gate_up with
|
||||
* a_rot = 1 reads xr[i] where it would have computed it.
|
||||
*
|
||||
* moe_exl3_gate_up_down y[i] = moe_exl3_down(h_rot = 1)( moe_exl3_gate_up(a_rot = 0, h_rot = 1)(a) )[i]
|
||||
* -- the decode chain as ONE op (version 5): the same rotations, roundings and zero rules, h and
|
||||
* xr in the op's scratch, nothing but y written.
|
||||
*
|
||||
* h_rot = 1 ("EPI 1"): gate_up writes h'[i] = f16(had(f16(h[i] * dn_suh_e))) per 128-block --
|
||||
* down's own first step, with down's suh of the same expert -- and zeros past the class's width as
|
||||
* before; down then reads its input as that rotated activation, y[i] = bf16(had(h'[i] @ What) * svh),
|
||||
* and does not read its suh. Issued as a PAIR (both flags 1, or both 0) the pair's output is the same
|
||||
* bits either way; mixing the flags is a caller error nothing here can see.
|
||||
*
|
||||
* had = the normalised 128-block Hadamard (common/exl3_decode.h exl3_had128). `expert_w` is NOT
|
||||
* applied by either: the gather does it, exactly as for `moe_gemm_q`.
|
||||
*
|
||||
* THE EXPERTS ARE TWO CLASSES BY PARITY, as `moe_gemm_q`'s are (docs/OPS.md:677-688): the even
|
||||
* experts at [N, K], the odd ones at [N_odd, K_odd] (each defaulting to N, K), expert e at entry
|
||||
* e / 2 of class e % 2 -- because a rank holding 3 of an expert's five 128-column blocks for one
|
||||
* parity and 2 for the other (a rank holds whole 128-blocks) has two geometries. Each class is one
|
||||
* table operand per plane. The output is the WIDER class's width and a narrower class writes zeros
|
||||
* past its own.
|
||||
*
|
||||
* THE ODD CLASS ABSENT (every one of its tables a null RadTensor.data) means ONE class: expert e at
|
||||
* entry e of the even tables, every expert at [N, K]; N_odd / K_odd, if given, must equal N / K. A
|
||||
* partly absent odd set is refused. NOTE: at 1.3.0 an architecture cannot issue an absent table:
|
||||
* the declaration divides its weight list EVENLY over every table position, optional or not
|
||||
* (core/build/rad_builder.cpp:697-731), and an issue naming another run is refused
|
||||
* (core/runtime/issue.cpp:249-254). So the engine always passes both classes (at tp1 with
|
||||
* N_odd == N, K_odd == K, as the in-tree block does); absence is for a caller holding operands
|
||||
* directly -- a harness, a tool -- and is what a shape description without N_odd and K_odd means.
|
||||
*
|
||||
* THE _mod4 OPS (version 6) TAKE FOUR CLASSES BY NUMBER MOD 4, as `moe_gemm_q_mod4`'s are: class q at [N_q, K_q]
|
||||
* (N_0, K_0 being N, K; each N_q, K_q defaulting to N, K), expert e at entry e / 4 of class e % 4, so class q holds
|
||||
* ceil((n_expert - q) / 4) entries. Every class's tables are REQUIRED (no absent form: the architecture issues all
|
||||
* four, and a caller with one geometry has the two-class ops). Everything else -- the routing, the zero rules, the
|
||||
* output the widest class's width with a narrower class zero past its own, h_rot, a_rot, xr -- is the two-class
|
||||
* op's, word for word, with "the odd class" read as "classes 1, 2 and 3".
|
||||
*
|
||||
* PARAMETERS (both ops):
|
||||
* M the token count of the pass (the op's ranged parameter)
|
||||
* N, K class 0's weight [rows, cols] = [out features, in features] of this rank's slice.
|
||||
* gate_up: N = 2 * width (gate rows then up rows, stacked), K = hidden;
|
||||
* down: N = hidden, K = width
|
||||
* n_expert the length of expert_offset minus one (the sort's expert count)
|
||||
* top_k slots per token
|
||||
* dtype "exl3k2" .. "exl3k8": the codes' K, bits per weight (exl3_gemm_dtype); "exl3k1h" .. "exl3k3h" the
|
||||
* half-integer K 1.5 .. 3.5 (exllamav3 1.6, codebook mul1 only; codes the u(2KA+1) [1x2] pair plane)
|
||||
* codebook "mul1" | "mcg" | "3inst": the trellis codebook (the encoding's transform names it;
|
||||
* the architecture passes it so the geometry says what is decoded -- a host row has no
|
||||
* layout hook through which to see the encoding)
|
||||
* N_odd, K_odd class 1's [rows, cols]; optional, default N, K
|
||||
* h_rot 0 or 1, REQUIRED: whether h crosses between the two ops rotated (above). Required and
|
||||
* not optional because a constraint on an absent key never holds (core/util/rad_util.cpp
|
||||
* :264-265): a row that does not implement h_rot = 1 says RAD_CEQ("h_rot", 0) and is
|
||||
* refused BY NAME at selection, which it could not if callers might omit the key.
|
||||
* Any other value is RAD_E_INVAL.
|
||||
* a_rot gate_up only, 0 or 1, REQUIRED (for the reason h_rot is): 1 when gate_up's `a` is the
|
||||
* xr moe_exl3_prep_gu wrote -- sorted rows, already rotated -- rather than the token rows.
|
||||
* A row that does not implement it says RAD_CEQ("a_rot", 0). Any other value RAD_E_INVAL.
|
||||
*
|
||||
* moe_exl3_gate_up_down takes gate_up's parameters without the flags (h_rot = 1 and a_rot = 0 are what it is):
|
||||
* M, N, K, n_expert, top_k, dtype, codebook, N_odd?, K_odd?. Down's geometry follows: [K, N / 2] (and
|
||||
* [K_odd, N_odd / 2]); both matrices are the same K and codebook (an architecture whose two projections differ
|
||||
* issues the separate ops).
|
||||
*
|
||||
* moe_exl3_prep_gu takes M, K, n_expert, top_k, dtype (the routed GEMMs' "exl3kK": the family it
|
||||
* belongs to, so a library serving one K constrains all three ops alike) and K_odd?: the classes'
|
||||
* input widths are all it needs of the weight.
|
||||
*
|
||||
* The _mod4 ops take the same parameters with N_1?, K_1?, N_2?, K_2?, N_3?, K_3? in place of N_odd?, K_odd?
|
||||
* (prep_gu_mod4: K_1?, K_2?, K_3?), `moe_gemm_q_mod4`'s names.
|
||||
*
|
||||
* OPERANDS, in schema order (moe_gemm_q's pattern: the even tables, the routing, the odd tables,
|
||||
* the output):
|
||||
* gate_up a, codes, suh, suh1, svh, dn_suh?, sorted_tok, expert_offset,
|
||||
* codes_odd?, suh_odd?, suh1_odd?, svh_odd?, dn_suh_odd? -> h
|
||||
* down h, codes, suh, svh, sorted_tok, expert_offset, codes_odd?, suh_odd?, svh_odd? -> y
|
||||
* prep_gu a, suh, suh1, sorted_tok, expert_offset, suh_odd?, suh1_odd? -> xr
|
||||
* the _mod4 ops: class 0's tables, the routing, then class 1's, 2's and 3's tables (suffix _1, _2, _3; every one
|
||||
* required but dn_suh_q, as dn_suh), then the output -- `moe_gemm_q_mod4`'s pattern
|
||||
* gate_up_down a, codes, suh, suh1, svh, dn_suh, dn_codes, dn_svh, sorted_tok, expert_offset,
|
||||
* codes_odd?, suh_odd?, suh1_odd?, svh_odd?, dn_suh_odd?, dn_codes_odd?, dn_svh_odd? -> y
|
||||
* (dn_suh is down's suh; dn_codes / dn_svh are down's codes and svh, [K, N / 2] and [K, 1])
|
||||
* dn_suh / dn_suh_odd are DOWN's suh tables of the same experts (entry [1, rows/2]); read only with
|
||||
* h_rot = 1, where they are required (and dn_suh_odd with the odd class).
|
||||
*
|
||||
* THE DECLARATION: the weight list is divided evenly over the table positions in this order
|
||||
* (rad_builder.cpp:703-731), so an architecture lists the even class's codes run, its suh run,
|
||||
* [its suh.1 run,] its svh run, [gate_up: its dn_suh run,] then the odd class's in the same order --
|
||||
* each run the class's experts in entry order, each weight a one-plane view
|
||||
* (`RadWeightDecl::planes` = "codes", "suh", "suh.1", "svh") of the expert's one `exl3` encoding.
|
||||
* An odd expert count gives the even tables one more each, which is the rule's own remainder
|
||||
* (:711-729). EVERY TABLE POSITION TAKES ITS SHARE, OPTIONAL OR NOT, so an architecture issuing
|
||||
* gate_up binds dn_suh (and dn_suh_odd) whatever h_rot is -- the natural run is the one down's own
|
||||
* suh table already names (down's suh weights, read by two ops); with h_rot = 0 it is not read.
|
||||
* prep_gu's suh / suh1 runs are gate_up's (the same weights, read by both); gate_up binds them at
|
||||
* a_rot = 1 too and does not read them.
|
||||
*
|
||||
* XR, moe_exl3_prep_gu's output and gate_up's `a` at a_rot = 1: f16 [T, 2 * max(K, K_odd)], one row
|
||||
* per SORTED row (row i is slot sorted_tok[i], like the outputs). Row i of expert e (class c, input
|
||||
* width K_c) holds columns [0, K_c) the gate half's rotated input (suh) and [K_c, 2 * K_c) the up
|
||||
* half's (suh.1) -- a narrower class uses the first 2 * K_c of the row. It is the layout exl3r4d's
|
||||
* prep kernels write in both bands, decode and prefill (xr[row][m * K_c + k], row pitch 2 * x_cols;
|
||||
* kernels/exl3r4d/exl3r4d.hip, exl3r4d_prefill.hip).
|
||||
* WHAT IS NOT WRITTEN, and is left as it was: every row outside the experts' runs [off[0],
|
||||
* off[n_expert]) -- dropped slots, protected experts' rows -- and the columns past 2 * K_c. gate_up
|
||||
* reads none of them (its output rows there are zero whatever xr holds). A row inside a run whose
|
||||
* sorted_tok is negative (no scatter writes one) is zero. "Not written" is exact, so the per-op
|
||||
* oracle, which runs the host row on the pre-launch copy (core/runtime/oracle.cpp:405-423), compares
|
||||
* those bytes equal; a library that wrote them would be the one disagreeing.
|
||||
*
|
||||
* ONE a_rot PER DECLARED OP, A CHOICE PER PASS. a_rot is a fixed parameter like every other but M, so
|
||||
* an architecture that wants prep_gu + gate_up(a_rot = 1) at decode and gate_up(a_rot = 0) above it
|
||||
* declares gate_up twice -- a_rot = 1 with M ranged over the decode band, beside prep_gu over the same
|
||||
* band, and a_rot = 0 -- and picks at issue by the pass's row count. That is how the in-tree block
|
||||
* already chooses its router form: `router_gemm_topk_scatter` declared for M in [1,
|
||||
* router_fused_rows] and issued only when rows <= router_fused_rows, else the separate pair or the
|
||||
* split router (arch/common/rad_block_moe_q.h:1438-1447, 1527-1551). Both gate_up declarations
|
||||
* read the same weights, so their rows must ask the same stored form of `codes`.
|
||||
*/
|
||||
|
||||
/* The ops, as exl3_positions() and exl3_geom_parse() take them. 0 and 1 are what version 3's
|
||||
* `gate_up` flag passed, so a caller written for it is unchanged. A four-class form (v6, v7) is its op | EXL3_MOD4. */
|
||||
enum { EXL3_DOWN = 0, EXL3_GATE_UP = 1, EXL3_PREP_GU = 2, EXL3_GU_DN = 3, EXL3_MOD4 = 4,
|
||||
EXL3_DOWN4 = EXL3_MOD4 | EXL3_DOWN, EXL3_GATE_UP4 = EXL3_MOD4 | EXL3_GATE_UP,
|
||||
EXL3_PREP_GU4 = EXL3_MOD4 | EXL3_PREP_GU, EXL3_GU_DN4 = EXL3_MOD4 | EXL3_GU_DN };
|
||||
/* The two-class op a form is of (what it computes); EXL3_MOD4 says only how its experts are tabled. */
|
||||
static inline int exl3_op_base(int op) { return op & ~EXL3_MOD4; }
|
||||
|
||||
/* Where each operand of an op sits. `plane[c][p]` is class c's table of plane p (EXL3_P_*), -1 for a
|
||||
* plane the op does not have (down has no suh.1 and no dn_suh; prep_gu has only suh and suh.1) and for
|
||||
* every plane of a class past the op's `n_cls` (2, or 4 for a _mod4 op).
|
||||
* EXL3_P_DN_SUH is gate_up's view of DOWN's suh plane (h_rot = 1); the expert's own weight is planes
|
||||
* EXL3_P_CODES..EXL3_P_SVH. */
|
||||
enum { EXL3_P_CODES = 0, EXL3_P_SUH = 1, EXL3_P_SUH1 = 2, EXL3_P_SVH = 3, EXL3_P_DN_SUH = 4,
|
||||
EXL3_P_DN_CODES = 5, EXL3_P_DN_SVH = 6, EXL3_N_P = 7 };
|
||||
enum { EXL3_MAX_CLS = 4 };
|
||||
|
||||
typedef struct Exl3Positions {
|
||||
int x, sorted, offset, y, n_opd, n_cls;
|
||||
int plane[EXL3_MAX_CLS][EXL3_N_P];
|
||||
int ids; /* the router's top-k ids (OPTIONAL operand; prep_gu_mod4 only), -1 for every other op */
|
||||
} Exl3Positions;
|
||||
|
||||
static inline const Exl3Positions* exl3_positions(int op) {
|
||||
#define EXL3_NO_CLASS { -1, -1, -1, -1, -1, -1, -1 }
|
||||
static const Exl3Positions gu = { 0, 6, 7, 13, 14, 2, { { 1, 2, 3, 4, 5, -1, -1 }, { 8, 9, 10, 11, 12, -1, -1 },
|
||||
EXL3_NO_CLASS, EXL3_NO_CLASS }, -1 };
|
||||
static const Exl3Positions dn = { 0, 4, 5, 9, 10, 2, { { 1, 2, -1, 3, -1, -1, -1 }, { 6, 7, -1, 8, -1, -1, -1 },
|
||||
EXL3_NO_CLASS, EXL3_NO_CLASS }, -1 };
|
||||
static const Exl3Positions pg = { 0, 3, 4, 7, 8, 2, { { -1, 1, 2, -1, -1, -1, -1 }, { -1, 5, 6, -1, -1, -1, -1 },
|
||||
EXL3_NO_CLASS, EXL3_NO_CLASS }, -1 };
|
||||
static const Exl3Positions gd = { 0, 8, 9, 17, 18, 2, { { 1, 2, 3, 4, 5, 6, 7 }, { 10, 11, 12, 13, 14, 15, 16 },
|
||||
EXL3_NO_CLASS, EXL3_NO_CLASS }, -1 };
|
||||
static const Exl3Positions gu4 = { 0, 6, 7, 23, 24, 4, { { 1, 2, 3, 4, 5, -1, -1 }, { 8, 9, 10, 11, 12, -1, -1 },
|
||||
{ 13, 14, 15, 16, 17, -1, -1 },
|
||||
{ 18, 19, 20, 21, 22, -1, -1 } }, -1 };
|
||||
static const Exl3Positions dn4 = { 0, 4, 5, 15, 16, 4, { { 1, 2, -1, 3, -1, -1, -1 }, { 6, 7, -1, 8, -1, -1, -1 },
|
||||
{ 9, 10, -1, 11, -1, -1, -1 },
|
||||
{ 12, 13, -1, 14, -1, -1, -1 } }, -1 };
|
||||
static const Exl3Positions pg4 = { 0, 3, 4, 11, 13, 4, { { -1, 1, 2, -1, -1, -1, -1 }, { -1, 5, 6, -1, -1, -1, -1 },
|
||||
{ -1, 7, 8, -1, -1, -1, -1 },
|
||||
{ -1, 9, 10, -1, -1, -1, -1 } }, 12 };
|
||||
static const Exl3Positions gd4 = { 0, 8, 9, 31, 32, 4, { { 1, 2, 3, 4, 5, 6, 7 }, { 10, 11, 12, 13, 14, 15, 16 },
|
||||
{ 17, 18, 19, 20, 21, 22, 23 },
|
||||
{ 24, 25, 26, 27, 28, 29, 30 } }, -1 };
|
||||
#undef EXL3_NO_CLASS
|
||||
switch (op) {
|
||||
case EXL3_GU_DN: return &gd;
|
||||
case EXL3_PREP_GU: return &pg;
|
||||
case EXL3_GATE_UP: return &gu;
|
||||
case EXL3_DOWN4: return &dn4;
|
||||
case EXL3_GATE_UP4: return &gu4;
|
||||
case EXL3_PREP_GU4: return &pg4;
|
||||
case EXL3_GU_DN4: return &gd4;
|
||||
default: return &dn;
|
||||
}
|
||||
}
|
||||
|
||||
#define EXL3_OP_GATE_UP "moe_exl3_gate_up"
|
||||
#define EXL3_OP_DOWN "moe_exl3_down"
|
||||
#define EXL3_OP_PREP_GU "moe_exl3_prep_gu"
|
||||
#define EXL3_OP_GU_DN "moe_exl3_gate_up_down"
|
||||
#define EXL3_OP_GATE_UP4 "moe_exl3_gate_up_mod4"
|
||||
#define EXL3_OP_DOWN4 "moe_exl3_down_mod4"
|
||||
#define EXL3_OP_PREP_GU4 "moe_exl3_prep_gu_mod4"
|
||||
#define EXL3_OP_GU_DN4 "moe_exl3_gate_up_down_mod4"
|
||||
|
||||
/* An op's id (EXL3_*) from its name, or -1. */
|
||||
static inline int exl3_op_of(const char* name) {
|
||||
static const char* const names[] = { EXL3_OP_DOWN, EXL3_OP_GATE_UP, EXL3_OP_PREP_GU, EXL3_OP_GU_DN,
|
||||
EXL3_OP_DOWN4, EXL3_OP_GATE_UP4, EXL3_OP_PREP_GU4, EXL3_OP_GU_DN4 };
|
||||
for (int i = 0; name && i < (int)(sizeof names / sizeof names[0]); ++i)
|
||||
if (!strcmp(name, names[i])) return i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* The schemas, in this order: 0 gate_up, 1 down, 2 prep_gu, 3 gate_up_down, 4 gate_up_mod4, 5 down_mod4,
|
||||
* 6 prep_gu_mod4, 7 gate_up_down_mod4. A plugin's rad_kernel_schema_count / rad_kernel_schema_at answer with these. Static locals in a
|
||||
* static inline function, so a translation unit that includes this header and never asks pays nothing and warns
|
||||
* about nothing. */
|
||||
static inline int exl3_schema_count(void) { return 8; }
|
||||
|
||||
static inline const RadOpSchema* exl3_schema_at(int i) {
|
||||
#define EXL3_GEMM_PARAMS \
|
||||
{ "M", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE }, \
|
||||
{ "N", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE }, \
|
||||
{ "K", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE }, \
|
||||
{ "n_expert", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE }, \
|
||||
{ "top_k", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE }, \
|
||||
{ "dtype", RAD_P_STR, RAD_REQUIRED, RAD_PROLE_NONE }, \
|
||||
{ "codebook", RAD_P_STR, RAD_REQUIRED, RAD_PROLE_NONE }, \
|
||||
{ "N_odd", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE }, \
|
||||
{ "K_odd", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE }, \
|
||||
{ "h_rot", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE }
|
||||
static const RadParamSpec p_gu[] = {
|
||||
EXL3_GEMM_PARAMS,
|
||||
{ "a_rot", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
/* v8: the SwiGLU clamp (DeepSeek's swiglu_limit): gate = min(gate, limit), up = clamp(up, -limit, limit)
|
||||
* before silu(gate) * up; absent or 0 is none */
|
||||
{ "limit", RAD_P_F64, RAD_OPTIONAL, RAD_PROLE_NONE },
|
||||
/* v9, the token-count-invariant form: 1 = a row's bytes do not depend on the launch's token count -- a
|
||||
* library whose decode band picks a form by the token count (exl3r4d: split-K 2 at <= 2 tokens where the grid
|
||||
* fits, split-K 1 above) takes the one form at every count; absent or 0 is the library's own rule. The
|
||||
* result is defined as without it (a summation order, not a different product). */
|
||||
{ "bi", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE },
|
||||
/* v10, the in-launch copy ring: MiB of the prefill band's scratch for a copy ring -- in the map
|
||||
* form the launch may copy the routed experts whose codes sit in a host pool (rad_host_pool_ranges) onto the
|
||||
* card inside the GEMM launch, while the resident experts compute, and read the copies (the same bytes);
|
||||
* absent or 0 is no ring. A placement of the same bytes, not a different product. */
|
||||
{ "xring", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE },
|
||||
};
|
||||
static const RadParamSpec p_dn[] = { EXL3_GEMM_PARAMS };
|
||||
#undef EXL3_GEMM_PARAMS
|
||||
static const RadParamSpec p_pg[] = {
|
||||
{ "M", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "K", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "n_expert", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "top_k", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "dtype", RAD_P_STR, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "K_odd", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE },
|
||||
};
|
||||
static const RadOperandSpec gate_up[14] = {
|
||||
{ "a", RAD_OPD_IN, 0 },
|
||||
{ "codes", RAD_OPD_WTAB, 0 },
|
||||
{ "suh", RAD_OPD_WTAB, 0 },
|
||||
{ "suh1", RAD_OPD_WTAB, 0 },
|
||||
{ "svh", RAD_OPD_WTAB, 0 },
|
||||
{ "dn_suh", RAD_OPD_WTAB, 1 },
|
||||
{ "sorted_tok", RAD_OPD_IN, 0 },
|
||||
{ "expert_offset", RAD_OPD_IN, 0 },
|
||||
{ "codes_odd", RAD_OPD_WTAB, 1 },
|
||||
{ "suh_odd", RAD_OPD_WTAB, 1 },
|
||||
{ "suh1_odd", RAD_OPD_WTAB, 1 },
|
||||
{ "svh_odd", RAD_OPD_WTAB, 1 },
|
||||
{ "dn_suh_odd", RAD_OPD_WTAB, 1 },
|
||||
{ "h", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
static const RadOperandSpec down[10] = {
|
||||
{ "h", RAD_OPD_IN, 0 },
|
||||
{ "codes", RAD_OPD_WTAB, 0 },
|
||||
{ "suh", RAD_OPD_WTAB, 0 },
|
||||
{ "svh", RAD_OPD_WTAB, 0 },
|
||||
{ "sorted_tok", RAD_OPD_IN, 0 },
|
||||
{ "expert_offset", RAD_OPD_IN, 0 },
|
||||
{ "codes_odd", RAD_OPD_WTAB, 1 },
|
||||
{ "suh_odd", RAD_OPD_WTAB, 1 },
|
||||
{ "svh_odd", RAD_OPD_WTAB, 1 },
|
||||
{ "y", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
static const RadParamSpec p_gd[] = {
|
||||
{ "M", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "N", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "K", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "n_expert", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "top_k", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "dtype", RAD_P_STR, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "codebook", RAD_P_STR, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "N_odd", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE },
|
||||
{ "K_odd", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE },
|
||||
};
|
||||
static const RadOperandSpec gate_up_down[18] = {
|
||||
{ "a", RAD_OPD_IN, 0 },
|
||||
{ "codes", RAD_OPD_WTAB, 0 },
|
||||
{ "suh", RAD_OPD_WTAB, 0 },
|
||||
{ "suh1", RAD_OPD_WTAB, 0 },
|
||||
{ "svh", RAD_OPD_WTAB, 0 },
|
||||
{ "dn_suh", RAD_OPD_WTAB, 0 },
|
||||
{ "dn_codes", RAD_OPD_WTAB, 0 },
|
||||
{ "dn_svh", RAD_OPD_WTAB, 0 },
|
||||
{ "sorted_tok", RAD_OPD_IN, 0 },
|
||||
{ "expert_offset", RAD_OPD_IN, 0 },
|
||||
{ "codes_odd", RAD_OPD_WTAB, 1 },
|
||||
{ "suh_odd", RAD_OPD_WTAB, 1 },
|
||||
{ "suh1_odd", RAD_OPD_WTAB, 1 },
|
||||
{ "svh_odd", RAD_OPD_WTAB, 1 },
|
||||
{ "dn_suh_odd", RAD_OPD_WTAB, 1 },
|
||||
{ "dn_codes_odd", RAD_OPD_WTAB, 1 },
|
||||
{ "dn_svh_odd", RAD_OPD_WTAB, 1 },
|
||||
{ "y", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
static const RadOperandSpec prep_gu[8] = {
|
||||
{ "a", RAD_OPD_IN, 0 },
|
||||
{ "suh", RAD_OPD_WTAB, 0 },
|
||||
{ "suh1", RAD_OPD_WTAB, 0 },
|
||||
{ "sorted_tok", RAD_OPD_IN, 0 },
|
||||
{ "expert_offset", RAD_OPD_IN, 0 },
|
||||
{ "suh_odd", RAD_OPD_WTAB, 1 },
|
||||
{ "suh1_odd", RAD_OPD_WTAB, 1 },
|
||||
{ "xr", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
/* v6, the four-class forms: the two-class op's parameters with N_q / K_q for N_odd / K_odd, and its operands with
|
||||
* classes 1..3's tables after the routing (every one required but dn_suh_q, as dn_suh). */
|
||||
#define EXL3_MOD4_SHAPE \
|
||||
{ "M", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE }, \
|
||||
{ "N", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE }, \
|
||||
{ "K", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE }, \
|
||||
{ "n_expert", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE }, \
|
||||
{ "top_k", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE }, \
|
||||
{ "dtype", RAD_P_STR, RAD_REQUIRED, RAD_PROLE_NONE }, \
|
||||
{ "codebook", RAD_P_STR, RAD_REQUIRED, RAD_PROLE_NONE }, \
|
||||
{ "N_1", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE }, \
|
||||
{ "K_1", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE }, \
|
||||
{ "N_2", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE }, \
|
||||
{ "K_2", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE }, \
|
||||
{ "N_3", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE }, \
|
||||
{ "K_3", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE }, \
|
||||
{ "h_rot", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE }
|
||||
static const RadParamSpec p_gu4[] = {
|
||||
EXL3_MOD4_SHAPE,
|
||||
{ "a_rot", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
};
|
||||
static const RadParamSpec p_dn4[] = { EXL3_MOD4_SHAPE };
|
||||
#undef EXL3_MOD4_SHAPE
|
||||
static const RadParamSpec p_pg4[] = {
|
||||
{ "M", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "K", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "n_expert", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "top_k", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "dtype", RAD_P_STR, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "K_1", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE },
|
||||
{ "K_2", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE },
|
||||
{ "K_3", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE },
|
||||
};
|
||||
#define EXL3_GU_CLASS(q) \
|
||||
{ "codes_" #q, RAD_OPD_WTAB, 0 }, \
|
||||
{ "suh_" #q, RAD_OPD_WTAB, 0 }, \
|
||||
{ "suh1_" #q, RAD_OPD_WTAB, 0 }, \
|
||||
{ "svh_" #q, RAD_OPD_WTAB, 0 }, \
|
||||
{ "dn_suh_" #q, RAD_OPD_WTAB, 1 }
|
||||
static const RadOperandSpec gate_up4[24] = {
|
||||
{ "a", RAD_OPD_IN, 0 },
|
||||
{ "codes", RAD_OPD_WTAB, 0 },
|
||||
{ "suh", RAD_OPD_WTAB, 0 },
|
||||
{ "suh1", RAD_OPD_WTAB, 0 },
|
||||
{ "svh", RAD_OPD_WTAB, 0 },
|
||||
{ "dn_suh", RAD_OPD_WTAB, 1 },
|
||||
{ "sorted_tok", RAD_OPD_IN, 0 },
|
||||
{ "expert_offset", RAD_OPD_IN, 0 },
|
||||
EXL3_GU_CLASS(1), EXL3_GU_CLASS(2), EXL3_GU_CLASS(3),
|
||||
{ "h", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
#undef EXL3_GU_CLASS
|
||||
#define EXL3_DN_CLASS(q) \
|
||||
{ "codes_" #q, RAD_OPD_WTAB, 0 }, \
|
||||
{ "suh_" #q, RAD_OPD_WTAB, 0 }, \
|
||||
{ "svh_" #q, RAD_OPD_WTAB, 0 }
|
||||
static const RadOperandSpec down4[16] = {
|
||||
{ "h", RAD_OPD_IN, 0 },
|
||||
{ "codes", RAD_OPD_WTAB, 0 },
|
||||
{ "suh", RAD_OPD_WTAB, 0 },
|
||||
{ "svh", RAD_OPD_WTAB, 0 },
|
||||
{ "sorted_tok", RAD_OPD_IN, 0 },
|
||||
{ "expert_offset", RAD_OPD_IN, 0 },
|
||||
EXL3_DN_CLASS(1), EXL3_DN_CLASS(2), EXL3_DN_CLASS(3),
|
||||
{ "y", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
#undef EXL3_DN_CLASS
|
||||
#define EXL3_PG_CLASS(q) \
|
||||
{ "suh_" #q, RAD_OPD_WTAB, 0 }, \
|
||||
{ "suh1_" #q, RAD_OPD_WTAB, 0 }
|
||||
static const RadOperandSpec prep_gu4[13] = {
|
||||
{ "a", RAD_OPD_IN, 0 },
|
||||
{ "suh", RAD_OPD_WTAB, 0 },
|
||||
{ "suh1", RAD_OPD_WTAB, 0 },
|
||||
{ "sorted_tok", RAD_OPD_IN, 0 },
|
||||
{ "expert_offset", RAD_OPD_IN, 0 },
|
||||
EXL3_PG_CLASS(1), EXL3_PG_CLASS(2), EXL3_PG_CLASS(3),
|
||||
{ "xr", RAD_OPD_OUT, 0 },
|
||||
{ "topk_ids", RAD_OPD_IN, 1 }, /* optional: the router's [M, top_k] expert ids */
|
||||
};
|
||||
#undef EXL3_PG_CLASS
|
||||
static const RadParamSpec p_gd4[] = {
|
||||
{ "M", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "N", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "K", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "n_expert", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "top_k", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "dtype", RAD_P_STR, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "codebook", RAD_P_STR, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "N_1", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE },
|
||||
{ "K_1", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE },
|
||||
{ "N_2", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE },
|
||||
{ "K_2", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE },
|
||||
{ "N_3", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE },
|
||||
{ "K_3", RAD_P_INT, RAD_OPTIONAL, RAD_PROLE_NONE },
|
||||
};
|
||||
#define EXL3_GD_CLASS(q) \
|
||||
{ "codes_" #q, RAD_OPD_WTAB, 0 }, \
|
||||
{ "suh_" #q, RAD_OPD_WTAB, 0 }, \
|
||||
{ "suh1_" #q, RAD_OPD_WTAB, 0 }, \
|
||||
{ "svh_" #q, RAD_OPD_WTAB, 0 }, \
|
||||
{ "dn_suh_" #q, RAD_OPD_WTAB, 0 }, \
|
||||
{ "dn_codes_" #q, RAD_OPD_WTAB, 0 }, \
|
||||
{ "dn_svh_" #q, RAD_OPD_WTAB, 0 }
|
||||
static const RadOperandSpec gate_up_down4[32] = {
|
||||
{ "a", RAD_OPD_IN, 0 },
|
||||
{ "codes", RAD_OPD_WTAB, 0 },
|
||||
{ "suh", RAD_OPD_WTAB, 0 },
|
||||
{ "suh1", RAD_OPD_WTAB, 0 },
|
||||
{ "svh", RAD_OPD_WTAB, 0 },
|
||||
{ "dn_suh", RAD_OPD_WTAB, 0 },
|
||||
{ "dn_codes", RAD_OPD_WTAB, 0 },
|
||||
{ "dn_svh", RAD_OPD_WTAB, 0 },
|
||||
{ "sorted_tok", RAD_OPD_IN, 0 },
|
||||
{ "expert_offset", RAD_OPD_IN, 0 },
|
||||
EXL3_GD_CLASS(1), EXL3_GD_CLASS(2), EXL3_GD_CLASS(3),
|
||||
{ "y", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
#undef EXL3_GD_CLASS
|
||||
static const RadOpSchema s[8] = {
|
||||
{ EXL3_OP_GATE_UP, p_gu, (int)(sizeof p_gu / sizeof p_gu[0]), gate_up, 14,
|
||||
"EXL3 routed experts, gate and up: per sorted row, a[sorted_tok/top_k] scaled by suh "
|
||||
"(suh.1 for up) and rotated, times W_hat, rotated back and scaled by svh, then "
|
||||
"f16(silu(gate) * up); with h_rot = 1 that then scaled by down's suh (dn_suh) and "
|
||||
"rotated, which is down's first step; with a_rot = 1 `a` is moe_exl3_prep_gu's xr and "
|
||||
"the input rotation is not redone. One weight table a plane a parity class, expert e "
|
||||
"at entry e/2; rows past expert_offset[n_expert] are zero. expert_w is not applied. "
|
||||
"docs/OPS-exl3.md." },
|
||||
{ EXL3_OP_DOWN, p_dn, (int)(sizeof p_dn / sizeof p_dn[0]), down, 10,
|
||||
"EXL3 routed experts, down: per sorted row, h[i] scaled by suh and rotated (with h_rot = "
|
||||
"1: h[i] as gate_up already rotated it), times W_hat, rotated back and scaled by svh, "
|
||||
"bf16. One weight table a plane a parity class, expert e at entry e/2; rows past "
|
||||
"expert_offset[n_expert] are zero. expert_w is not applied. docs/OPS-exl3.md." },
|
||||
{ EXL3_OP_PREP_GU, p_pg, (int)(sizeof p_pg / sizeof p_pg[0]), prep_gu, 8,
|
||||
"EXL3 routed experts, gate_up's input rotation as an op: per sorted row, "
|
||||
"a[sorted_tok/top_k] scaled by suh and rotated, then by suh.1 and rotated, side by side "
|
||||
"(xr, f16 [T, 2*max(K, K_odd)]) -- what moe_exl3_gate_up with a_rot = 1 reads. Rows "
|
||||
"past expert_offset[n_expert] are zero. docs/OPS-exl3.md." },
|
||||
{ EXL3_OP_GU_DN, p_gd, (int)(sizeof p_gd / sizeof p_gd[0]), gate_up_down, 18,
|
||||
"EXL3 routed experts, the decode chain as one op: y = moe_exl3_down(h_rot = 1) of "
|
||||
"moe_exl3_gate_up(a_rot = 0, h_rot = 1) of a, on the same routing; dn_suh / dn_codes / dn_svh "
|
||||
"are down's planes ([K, N/2]); h and the rotated input are scratch. Rows past "
|
||||
"expert_offset[n_expert] are zero. docs/OPS-exl3.md." },
|
||||
{ EXL3_OP_GATE_UP4, p_gu4, (int)(sizeof p_gu4 / sizeof p_gu4[0]), gate_up4, 24,
|
||||
"moe_exl3_gate_up over FOUR classes of experts by number mod 4 (moe_gemm_q_mod4's): class q at "
|
||||
"[N_q, K_q], expert e at entry e/4 of class e%4; otherwise moe_exl3_gate_up. docs/OPS-exl3.md." },
|
||||
{ EXL3_OP_DOWN4, p_dn4, (int)(sizeof p_dn4 / sizeof p_dn4[0]), down4, 16,
|
||||
"moe_exl3_down over FOUR classes of experts by number mod 4 (moe_gemm_q_mod4's): class q at "
|
||||
"[N_q, K_q], expert e at entry e/4 of class e%4; otherwise moe_exl3_down. docs/OPS-exl3.md." },
|
||||
{ EXL3_OP_PREP_GU4, p_pg4, (int)(sizeof p_pg4 / sizeof p_pg4[0]), prep_gu4, 13,
|
||||
"moe_exl3_prep_gu over FOUR classes of experts by number mod 4: class q's input width K_q, "
|
||||
"expert e at entry e/4 of class e%4; xr f16 [T, 2*max(K_q)]; otherwise moe_exl3_prep_gu. "
|
||||
"topk_ids (optional, i32 [M, top_k]): the router's expert of each (token, slot), the sort's input -- "
|
||||
"a speed hint only, the output does not depend on it. docs/OPS-exl3.md." },
|
||||
{ EXL3_OP_GU_DN4, p_gd4, (int)(sizeof p_gd4 / sizeof p_gd4[0]), gate_up_down4, 32,
|
||||
"moe_exl3_gate_up_down over FOUR classes of experts by number mod 4: y = moe_exl3_down_mod4(h_rot = 1) of "
|
||||
"moe_exl3_gate_up_mod4(a_rot = 0, h_rot = 1) of a; class q at [N_q, K_q], expert e at entry e/4 of class "
|
||||
"e%4; otherwise moe_exl3_gate_up_down. docs/OPS-exl3.md." },
|
||||
};
|
||||
return i >= 0 && i < 8 ? &s[i] : 0;
|
||||
}
|
||||
|
||||
/* THE DECODE BAND'S ARITHMETIC ABOVE THE DECODE BAND (the "dk" ops). Two more op names,
|
||||
* moe_exl3_gate_up_dk / moe_exl3_down_dk, with moe_exl3_gate_up's / moe_exl3_down's parameters, operands and result
|
||||
* definition to the letter -- what they add is a PROMISE about the bytes: a library's row for them writes, for every
|
||||
* (token, slot), exactly the bytes its DECODE-BAND row of moe_exl3_gate_up / moe_exl3_down writes for that token in a
|
||||
* pass of at most 16 tokens, whatever the pass's other tokens (the decode band is M-invariant per row, and a run longer
|
||||
* than a pass's 16 rows is taken 16 at a time). An architecture that must give a decode row the same bytes at any
|
||||
* step height (batch invariance), and would otherwise have to cut a decode segment into passes of <= 16 tokens,
|
||||
* declares them over the heights above 16 it wants as ONE pass and issues them for decode rows only; a prefill segment of the same height keeps
|
||||
* moe_exl3_gate_up / moe_exl3_down (whose M > 16 rows are free to round differently: exl3r4d's MTX form does). Names of
|
||||
* their own, not a parameter of the old ops, so the eight schemas above stay what every other library exports (a
|
||||
* loader refuses a library whose schema for a shared name differs). Two-class form only. exl3_dk_schema_at(0 / 1). */
|
||||
#define EXL3_OP_GATE_UP_DK "moe_exl3_gate_up_dk"
|
||||
#define EXL3_OP_DOWN_DK "moe_exl3_down_dk"
|
||||
static inline int exl3_dk_schema_count(void) { return 2; }
|
||||
static inline const RadOpSchema* exl3_dk_schema_at(int i) {
|
||||
static RadOpSchema s[2];
|
||||
static int made = 0;
|
||||
if (!made) {
|
||||
s[0] = *exl3_schema_at(0);
|
||||
s[0].op = EXL3_OP_GATE_UP_DK;
|
||||
s[0].doc = "moe_exl3_gate_up at more than 16 tokens with the decode band's bytes: every (token, slot) row is "
|
||||
"what the library's decode-band moe_exl3_gate_up writes for that token in a pass of <= 16 tokens "
|
||||
"(lever P; a_rot 0, h_rot 1). docs/OPS-exl3.md.";
|
||||
s[1] = *exl3_schema_at(1);
|
||||
s[1].op = EXL3_OP_DOWN_DK;
|
||||
s[1].doc = "moe_exl3_down at more than 16 tokens with the decode band's bytes: every (token, slot) row is "
|
||||
"what the library's decode-band moe_exl3_down writes for that token in a pass of <= 16 tokens "
|
||||
"(lever P; h_rot 1). docs/OPS-exl3.md.";
|
||||
made = 1;
|
||||
}
|
||||
return i >= 0 && i < 2 ? &s[i] : 0;
|
||||
}
|
||||
|
||||
/* ===================================================================== THE PLANES
|
||||
*
|
||||
* A table's entry e is one plane of one expert, exactly as the container holds it (the canonical
|
||||
* `exl3` encoding, include/exl3_encoding.h) -- this rank's slice of it, [rows, cols] in the plane's
|
||||
* own elements, the extents the core gives a plane (rad_enc_plane_dims, abi/rad_encoding.h:236-245):
|
||||
*
|
||||
* codes uK [R, C] element (i, j) = the K-bit trellis symbol of W_hat[i][j], LSB-first rows
|
||||
* suh f16 [1, C] input scales (the gate's, for gate_up) TILED [0x1]
|
||||
* suh1 f16 [1, C] gate_up only: the up half's input scales (plane suh.1) TILED [0x1]
|
||||
* svh f16 [R, 1] output scales (gate rows then up rows, for gate_up) TILED [1x0]
|
||||
* dn_suh f16 [1, R/2] gate_up only: DOWN's suh of the same expert (down's [hidden, R/2] weight)
|
||||
*
|
||||
* with [R, C] the class's [rows, cols]. A reader takes the scales by element count (any rank whose
|
||||
* extents multiply to C or R), because the architecture's declared shape is what an issue carries.
|
||||
* A table operand is the engine's pointer table (stride[0] == 0) or the STACKED form a tool uses --
|
||||
* one rank-3 tensor [entries, rows, cols] with a real leading stride, which is also the form the
|
||||
* per-op oracle hands a host row (core/runtime/oracle.cpp:328-347, 405-418).
|
||||
*
|
||||
* What a DEVICE row stores is its own business (its layout hook; codes alone is what a trellis
|
||||
* kernel re-lays). The host reference has no layout hook and reads the planes as they are, which a
|
||||
* one-plane weight nobody re-lays is (rad_builder.cpp:1385, 1404-1411) -- so the host-only engine
|
||||
* serves it -- and which the per-op oracle restores for a plane a device row did re-lay: the device
|
||||
* row's unrelayout gives back the canonical plane, and a one-plane selection reaches the host row
|
||||
* as those bytes in the dtype its shape hook names (oracle.cpp:456-548, encoding.cpp:306-321). */
|
||||
|
||||
/* The extents of plane p of class c's [rows, cols] weight (dn_suh: down's suh, [1, rows / 2]; dn_codes / dn_svh,
|
||||
* moe_exl3_gate_up_down's down planes: [cols, rows / 2] and [cols, 1] -- [rows, cols] being gate_up's). */
|
||||
static inline void exl3_plane_extents(int64_t rows, int64_t cols, int p, int64_t* r, int64_t* c) {
|
||||
if (p == EXL3_P_DN_CODES || p == EXL3_P_DN_SVH) {
|
||||
*r = cols;
|
||||
*c = p == EXL3_P_DN_SVH ? 1 : rows / 2;
|
||||
return;
|
||||
}
|
||||
*r = p == EXL3_P_SUH || p == EXL3_P_SUH1 || p == EXL3_P_DN_SUH ? 1 : rows;
|
||||
*c = p == EXL3_P_SVH ? 1 : p == EXL3_P_DN_SUH ? rows / 2 : cols;
|
||||
}
|
||||
|
||||
/* ===================================================================== THE GEOMETRY, PARSED ONCE
|
||||
*
|
||||
* Every implementation reads the parameters through this, so a device row can never accept a
|
||||
* geometry its reference refuses. `two_classes` is whether the odd tables are present -- an operand
|
||||
* fact the parameters do not carry; a shape hook, which has no operands, passes
|
||||
* exl3_geom_two_classes(). A _mod4 op ignores it: its four classes are always present. */
|
||||
typedef struct Exl3Geom {
|
||||
int op; /* the two-class op: EXL3_DOWN, EXL3_GATE_UP, EXL3_PREP_GU, EXL3_GU_DN (a _mod4 op's base) */
|
||||
int gate_up; /* 1 for gate_up AND prep_gu (stacked: suh and suh.1), 0 for down */
|
||||
int64_t M; /* tokens (a shape hook reads a range's high bound) */
|
||||
int64_t n_expert, top_k;
|
||||
int bits, codebook; /* K and EXL3_CB_* */
|
||||
int n_class; /* 2 with the odd tables, 1 without; 4 for a _mod4 op */
|
||||
int h_rot; /* 1: h crosses rotated (gate_up writes, down reads, down's step 1) */
|
||||
int a_rot; /* gate_up: 1 when `a` is prep_gu's xr */
|
||||
double limit; /* v8, moe_exl3_gate_up only: the SwiGLU clamp, 0 none (gate <= limit, |up| <= limit) */
|
||||
int64_t rows[EXL3_MAX_CLS], cols[EXL3_MAX_CLS]; /* class c's weight [rows, cols], c < n_class (prep_gu: rows 0,
|
||||
* it has no N); past n_class, class 0's */
|
||||
int64_t x_cols; /* max(cols): the token input's width (gate_up a_rot = 1: xr is 2 * x_cols) */
|
||||
int64_t y_cols; /* the output's width: max(rows)/2 gate_up, max(rows) down, 2 * x_cols prep_gu */
|
||||
} Exl3Geom;
|
||||
|
||||
/* Does this geometry name an odd class? -- N_odd or K_odd given. What a shape description of the
|
||||
* odd tables follows (present, or RAD_OPD_F_ABSENT). */
|
||||
static inline int exl3_geom_two_classes(const RadParam* p, int n_p) {
|
||||
return rad_param_find(p, n_p, "N_odd") != 0 || rad_param_find(p, n_p, "K_odd") != 0;
|
||||
}
|
||||
|
||||
/* RAD_OK, or: RAD_E_SCHEMA a required parameter absent; RAD_E_DTYPE a dtype or codebook this
|
||||
* interface has no name for; RAD_E_INVAL h_rot or a_rot neither 0 nor 1; RAD_E_SHAPE extents the
|
||||
* format cannot hold -- K % 128 (the input rotation), N % 128 for down and N % 256 for gate_up
|
||||
* (each half's output rotation, and with it the h_rot rotation of N / 2), a non-positive count, or
|
||||
* N_odd/K_odd differing from N/K without the odd class. `op` is EXL3_DOWN, EXL3_GATE_UP or
|
||||
* EXL3_PREP_GU (version 3 callers passed gate_up's 0/1, which are the first two), EXL3_GU_DN, or a _mod4
|
||||
* form (EXL3_DOWN4, EXL3_GATE_UP4, EXL3_PREP_GU4, EXL3_GU_DN4: N_q / K_q, every class checked as class 0 is). */
|
||||
static inline int exl3_geom_parse(const RadParam* p, int n_p, int op_in, int two_classes, Exl3Geom* g) {
|
||||
static const char* const common[] = { "M", "K", "n_expert", "top_k", "dtype" };
|
||||
static const char* const gemm[] = { "N", "codebook", "h_rot" };
|
||||
static const char* const nq[EXL3_MAX_CLS] = { "N", "N_1", "N_2", "N_3" };
|
||||
static const char* const kq[EXL3_MAX_CLS] = { "K", "K_1", "K_2", "K_3" };
|
||||
const int mod4 = (op_in & EXL3_MOD4) != 0, op = exl3_op_base(op_in);
|
||||
const int prep = op == EXL3_PREP_GU, gd = op == EXL3_GU_DN, gate_up = op == EXL3_GATE_UP || prep || gd;
|
||||
const char* dt = rad_param_gets(p, n_p, "dtype", 0);
|
||||
const char* cb = rad_param_gets(p, n_p, "codebook", 0);
|
||||
const int64_t N = rad_param_geti(p, n_p, "N", 0), K = rad_param_geti(p, n_p, "K", 0);
|
||||
const int64_t No = rad_param_geti(p, n_p, "N_odd", N), Ko = rad_param_geti(p, n_p, "K_odd", K);
|
||||
const int64_t rows_mult = gate_up ? 256 : 128;
|
||||
int c;
|
||||
memset(g, 0, sizeof *g);
|
||||
for (c = 0; c < (int)(sizeof common / sizeof common[0]); ++c)
|
||||
if (!rad_param_find(p, n_p, common[c])) return RAD_E_SCHEMA;
|
||||
for (c = 0; !prep && c < (int)(sizeof gemm / sizeof gemm[0]) - (gd ? 1 : 0); ++c) /* gd: no h_rot (last) */
|
||||
if (!rad_param_find(p, n_p, gemm[c])) return RAD_E_SCHEMA;
|
||||
if (op == EXL3_GATE_UP && !rad_param_find(p, n_p, "a_rot")) return RAD_E_SCHEMA;
|
||||
if (!dt || (!prep && !cb)) return RAD_E_SCHEMA; /* present, but not as strings */
|
||||
g->op = op;
|
||||
g->gate_up = gate_up;
|
||||
g->M = rad_param_getdim(p, n_p, "M", 0);
|
||||
g->n_expert = rad_param_geti(p, n_p, "n_expert", 0);
|
||||
g->top_k = rad_param_geti(p, n_p, "top_k", 0);
|
||||
g->h_rot = prep ? 0 : gd ? 1 : (int)rad_param_geti(p, n_p, "h_rot", -1);
|
||||
g->a_rot = op == EXL3_GATE_UP ? (int)rad_param_geti(p, n_p, "a_rot", -1) : 0;
|
||||
g->bits = exl3_gemm_bits(dt);
|
||||
g->codebook = prep ? -1 : exl3_codebook_from_name(cb);
|
||||
if (g->bits < 0 || (!prep && g->codebook < 0)) return RAD_E_DTYPE;
|
||||
if (exl3_bits_half(g->bits) && !prep && g->codebook != EXL3_CB_MUL1) return RAD_E_DTYPE; /* exllamav3 1.6: half-integer K is mul1 only */
|
||||
if ((g->h_rot != 0 && g->h_rot != 1) || (g->a_rot != 0 && g->a_rot != 1)) return RAD_E_INVAL;
|
||||
g->limit = op == EXL3_GATE_UP ? rad_param_getf(p, n_p, "limit", 0.0) : 0.0;
|
||||
if (!(g->limit >= 0.0) || g->limit > 65504.0) return RAD_E_INVAL; /* NaN, negative or past f16 */
|
||||
if (g->M < 1 || g->n_expert < 1 || g->top_k < 1) return RAD_E_SHAPE;
|
||||
if (!mod4 && !two_classes && ((!prep && No != N) || Ko != K)) return RAD_E_SHAPE;
|
||||
g->n_class = mod4 ? 4 : two_classes ? 2 : 1;
|
||||
for (c = 0; c < EXL3_MAX_CLS; ++c) { /* two-class ops: class 1 is the odd class, 2 and 3 class 0 again */
|
||||
const int has = mod4 || c == 1;
|
||||
g->rows[c] = prep ? 0 : !has ? N : mod4 ? rad_param_geti(p, n_p, nq[c], N) : No;
|
||||
g->cols[c] = !has ? K : mod4 ? rad_param_geti(p, n_p, kq[c], K) : Ko;
|
||||
}
|
||||
g->x_cols = g->y_cols = 0;
|
||||
for (c = 0; c < EXL3_MAX_CLS; ++c) {
|
||||
if (g->cols[c] <= 0 || g->cols[c] % EXL3_HAD ||
|
||||
(!prep && (g->rows[c] <= 0 || g->rows[c] % rows_mult)))
|
||||
return RAD_E_SHAPE;
|
||||
if (g->cols[c] > g->x_cols) g->x_cols = g->cols[c];
|
||||
if (g->rows[c] > g->y_cols) g->y_cols = g->rows[c];
|
||||
}
|
||||
g->y_cols = prep ? 2 * g->x_cols : gd ? g->x_cols : g->y_cols / (gate_up ? 2 : 1);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ===================================================================== moe_exl3_gate_up_down AS ITS TWO HALVES
|
||||
*
|
||||
* The fused op read as the pair it is defined by, so every implementation reuses its gate_up and down: the
|
||||
* gate_up view (a_rot = 0, h_rot = 1, gate_up's operands, output h) and the down view (h_rot = 1, down's
|
||||
* geometry [K, N / 2], operands h, dn_codes, dn_suh, dn_svh, routing, output y). `h` is the caller's buffer (a
|
||||
* [T, max(N, N_odd) / 2] f16 tensor). The parameter arrays are the caller's: gate_up at most 11, down 10. */
|
||||
static inline void exl3_gd_params(const RadParam* p, int n_p, RadParam* pg, int* n_pg, RadParam* pd, int* n_pd) {
|
||||
static const RadParam h1 = { "h_rot", RAD_P_INT, 1, 0, 0, 0.0 }, a0 = { "a_rot", RAD_P_INT, 0, 0, 0, 0.0 };
|
||||
const int64_t N = rad_param_geti(p, n_p, "N", 0), K = rad_param_geti(p, n_p, "K", 0);
|
||||
const int two = exl3_geom_two_classes(p, n_p);
|
||||
const int64_t No = rad_param_geti(p, n_p, "N_odd", N), Ko = rad_param_geti(p, n_p, "K_odd", K);
|
||||
int ng = 0, nd = 0;
|
||||
for (int i = 0; i < n_p; ++i) {
|
||||
const char* k = p[i].key;
|
||||
if (!strcmp(k, "h_rot") || !strcmp(k, "a_rot")) continue;
|
||||
if (ng < 9) pg[ng++] = p[i];
|
||||
if (!strcmp(k, "N") || !strcmp(k, "K") || !strcmp(k, "N_odd") || !strcmp(k, "K_odd")) continue;
|
||||
if (nd < 6) pd[nd++] = p[i]; /* M, n_expert, top_k, dtype, codebook */
|
||||
}
|
||||
pg[ng++] = h1;
|
||||
pg[ng++] = a0;
|
||||
pd[nd] = p[0]; pd[nd].key = "N"; pd[nd].kind = RAD_P_INT; pd[nd].ival = K; pd[nd].ihi = 0; ++nd;
|
||||
pd[nd] = pd[nd - 1]; pd[nd].key = "K"; pd[nd].ival = N / 2; ++nd;
|
||||
if (two) {
|
||||
pd[nd] = pd[nd - 1]; pd[nd].key = "N_odd"; pd[nd].ival = Ko; ++nd;
|
||||
pd[nd] = pd[nd - 1]; pd[nd].key = "K_odd"; pd[nd].ival = No / 2; ++nd;
|
||||
}
|
||||
pd[nd++] = h1;
|
||||
*n_pg = ng;
|
||||
*n_pd = nd;
|
||||
}
|
||||
|
||||
/* The operand views over the fused op's operands `t` (18): gate_up's 14 (output h) and down's 10 (input h, output
|
||||
* t[17]). */
|
||||
static inline void exl3_gd_operands(const RadTensor* t, const RadTensor* h, RadTensor* tg, RadTensor* td) {
|
||||
const Exl3Positions* gd = exl3_positions(EXL3_GU_DN);
|
||||
const Exl3Positions* gu = exl3_positions(EXL3_GATE_UP);
|
||||
const Exl3Positions* dn = exl3_positions(EXL3_DOWN);
|
||||
for (int c = 0; c < 2; ++c) {
|
||||
for (int q = EXL3_P_CODES; q <= EXL3_P_DN_SUH; ++q) tg[gu->plane[c][q]] = t[gd->plane[c][q]];
|
||||
td[dn->plane[c][EXL3_P_CODES]] = t[gd->plane[c][EXL3_P_DN_CODES]];
|
||||
td[dn->plane[c][EXL3_P_SUH]] = t[gd->plane[c][EXL3_P_DN_SUH]];
|
||||
td[dn->plane[c][EXL3_P_SVH]] = t[gd->plane[c][EXL3_P_DN_SVH]];
|
||||
}
|
||||
tg[gu->x] = t[gd->x];
|
||||
tg[gu->sorted] = td[dn->sorted] = t[gd->sorted];
|
||||
tg[gu->offset] = td[dn->offset] = t[gd->offset];
|
||||
tg[gu->y] = td[dn->x] = *h;
|
||||
td[dn->y] = t[gd->y];
|
||||
}
|
||||
|
||||
/* ...and version 7's four-class op the same way: the gate_up_mod4 view (a_rot = 0, h_rot = 1) and the down_mod4 view
|
||||
* (class q at [K_q, N_q / 2]). Parameter arrays: gate_up at most 15, down 14. Operands `t` (32): gate_up_mod4's 24
|
||||
* (output h) and down_mod4's 16 (input h, output t[31]). */
|
||||
static inline void exl3_gd4_params(const RadParam* p, int n_p, RadParam* pg, int* n_pg, RadParam* pd, int* n_pd) {
|
||||
static const RadParam h1 = { "h_rot", RAD_P_INT, 1, 0, 0, 0.0 }, a0 = { "a_rot", RAD_P_INT, 0, 0, 0, 0.0 };
|
||||
static const char* const nq[EXL3_MAX_CLS] = { "N", "N_1", "N_2", "N_3" };
|
||||
static const char* const kq[EXL3_MAX_CLS] = { "K", "K_1", "K_2", "K_3" };
|
||||
const int64_t N = rad_param_geti(p, n_p, "N", 0), K = rad_param_geti(p, n_p, "K", 0);
|
||||
int ng = 0, nd = 0;
|
||||
for (int i = 0; i < n_p; ++i) {
|
||||
const char* k = p[i].key;
|
||||
int shape = 0;
|
||||
if (!strcmp(k, "h_rot") || !strcmp(k, "a_rot")) continue;
|
||||
if (ng < 13) pg[ng++] = p[i];
|
||||
for (int c = 0; c < EXL3_MAX_CLS; ++c) shape |= !strcmp(k, nq[c]) || !strcmp(k, kq[c]);
|
||||
if (!shape && nd < 5) pd[nd++] = p[i]; /* M, n_expert, top_k, dtype, codebook */
|
||||
}
|
||||
pg[ng++] = h1;
|
||||
pg[ng++] = a0;
|
||||
for (int c = 0; c < EXL3_MAX_CLS; ++c) {
|
||||
pd[nd] = p[0]; pd[nd].key = nq[c]; pd[nd].kind = RAD_P_INT; pd[nd].ihi = 0;
|
||||
pd[nd].ival = rad_param_geti(p, n_p, kq[c], K); ++nd;
|
||||
pd[nd] = pd[nd - 1]; pd[nd].key = kq[c]; pd[nd].ival = rad_param_geti(p, n_p, nq[c], N) / 2; ++nd;
|
||||
}
|
||||
pd[nd++] = h1;
|
||||
*n_pg = ng;
|
||||
*n_pd = nd;
|
||||
}
|
||||
static inline void exl3_gd4_operands(const RadTensor* t, const RadTensor* h, RadTensor* tg, RadTensor* td) {
|
||||
const Exl3Positions* gd = exl3_positions(EXL3_GU_DN4);
|
||||
const Exl3Positions* gu = exl3_positions(EXL3_GATE_UP4);
|
||||
const Exl3Positions* dn = exl3_positions(EXL3_DOWN4);
|
||||
for (int c = 0; c < EXL3_MAX_CLS; ++c) {
|
||||
for (int q = EXL3_P_CODES; q <= EXL3_P_DN_SUH; ++q) tg[gu->plane[c][q]] = t[gd->plane[c][q]];
|
||||
td[dn->plane[c][EXL3_P_CODES]] = t[gd->plane[c][EXL3_P_DN_CODES]];
|
||||
td[dn->plane[c][EXL3_P_SUH]] = t[gd->plane[c][EXL3_P_DN_SUH]];
|
||||
td[dn->plane[c][EXL3_P_SVH]] = t[gd->plane[c][EXL3_P_DN_SVH]];
|
||||
}
|
||||
tg[gu->x] = t[gd->x];
|
||||
tg[gu->sorted] = td[dn->sorted] = t[gd->sorted];
|
||||
tg[gu->offset] = td[dn->offset] = t[gd->offset];
|
||||
tg[gu->y] = td[dn->x] = *h;
|
||||
td[dn->y] = t[gd->y];
|
||||
}
|
||||
|
||||
/* Expert e's class and its entry in that class's tables. */
|
||||
static inline int exl3_class_of(const Exl3Geom* g, int64_t e) { return (int)(e % g->n_class); }
|
||||
static inline int64_t exl3_entry_of(const Exl3Geom* g, int64_t e) { return e / g->n_class; }
|
||||
/* How many entries class c's tables must hold: ceil((n_expert - c) / n_class). */
|
||||
static inline int64_t exl3_class_entries(const Exl3Geom* g, int c) {
|
||||
return (g->n_expert - c + g->n_class - 1) / g->n_class;
|
||||
}
|
||||
|
||||
#ifdef __cplusplus
|
||||
} /* extern "C" */
|
||||
#endif
|
||||
|
||||
#endif /* EXL3_ABI_H */
|
||||
@@ -1,208 +0,0 @@
|
||||
/* exl3_decode.h -- THE ORACLE: what an EXL3 weight's numbers are, in plain C99, no dependencies.
|
||||
*
|
||||
* Everything another library checks itself against goes through here: the host reference kernels
|
||||
* (kernels/exl3ref), the quantiser's decode hook (quantizers/exl3) and the property tests. It is a
|
||||
* transcription of exllamav3's host-side decode and is checked bit for bit against a golden decode
|
||||
* made by an independent host implementation (common/tests/data/exl3_golden.npz). Slow and readable
|
||||
* on purpose.
|
||||
*
|
||||
* ============================================================ THE FORMAT (one linear, y = x @ W)
|
||||
*
|
||||
* exllamav3 stores a weight W of shape [k, n] (k = in_features, n = out_features) as
|
||||
*
|
||||
* W = diag(suh) . Hb . W_hat . Hb . diag(svh)
|
||||
*
|
||||
* Hb the block-diagonal natural-order Sylvester Hadamard of block 128, scaled 1/sqrt(128); suh f16 [k]
|
||||
* and svh f16 [n] per-channel scales; W_hat [k, n] the trellis-coded values, cut into 16x16 tiles.
|
||||
* Tile (tk, tn) is 16*K int16 = 8*K little-endian u32 words, read as ONE MSB-first stream of 256*K
|
||||
* bits. Position p (0..255) owns stream bits [p*K, (p+1)*K) -- its K-bit SYMBOL -- and its 16-bit
|
||||
* STATE is the 16-bit window ending at bit (p+1)*K, circular within the tile. A codebook maps the
|
||||
* state to an fp16 value. Position p = 8*L + j (L 0..31, j 0..7) sits at tile row (k axis)
|
||||
* 2*(L%4) + {0,1,8,9}[j%4] and tile column (n axis) L/4 + 8*(j/4).
|
||||
*
|
||||
* ============================================================ RADIANCE'S VIEW (the canonical planes)
|
||||
*
|
||||
* radiance stores a weight as [rows, cols] = [n, k]: row i is OUTPUT feature n = i, column j is
|
||||
* INPUT feature k = j (the transpose of exllamav3's [k, n]). The canonical EXL3 encoding
|
||||
* (include/exl3_encoding.h) holds, at codes-plane element (i, j), the K-bit SYMBOL of
|
||||
* the trellis position that decodes weight element W_hat[k = j][n = i]: tile (tk = j/16, tn = i/16),
|
||||
* position exl3_tile_to_pos(j % 16, i % 16). The plane is uK, row-major, each row a bit stream
|
||||
* lowest bits first and starting on a byte (rad_encoding.h), so element (i, j) is bits
|
||||
* [j*K, (j+1)*K) of row i and its VALUE is the symbol. Every symbol sequence is a valid trellis, so
|
||||
* this is a lossless permutation of the tile streams (exl3_layout.h converts both ways), and any
|
||||
* cut on 16 rows / 16 columns keeps tiles whole.
|
||||
*
|
||||
* "Decode one expert's weight to f32" is exl3_decode_rows(view, 0, view->rows, out): out is
|
||||
* f32 [n][k] -- radiance's [rows, cols], i.e. out[n*k_total + k] = W[k][n] in exllamav3's terms.
|
||||
*
|
||||
* ============================================================ NUMERICS
|
||||
*
|
||||
* Codebook values are exact fp16 (one rounding, as exllamav3's __hfma / __hadd). The Hadamard is the
|
||||
* butterfly in f32 then one multiply by (float)(1/sqrt(128)); W is formed in exllamav3's order
|
||||
* (had over k, x suh, had over n, x svh) in f32. Bit-exact claims are made for W_hat only; W agrees
|
||||
* with an f32 transcription to rounding (the tests state the bound). Build with -ffp-contract=off.
|
||||
*
|
||||
* Thread safety: every function is reentrant (no static state; scratch is malloc'd per call).
|
||||
*/
|
||||
#ifndef EXL3_DECODE_H
|
||||
#define EXL3_DECODE_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* Bumped on any change to a declaration below; consumers check it at compile time.
|
||||
* 2: half-integer K (exllamav3 >= 1.6), carried as a TAGGED `bits` (below). */
|
||||
#define EXL3_DECODE_API_VERSION 2
|
||||
|
||||
enum {
|
||||
EXL3_TILE = 16, /* a tile is 16 x 16 weights */
|
||||
EXL3_TILE_POS = 256, /* positions a tile */
|
||||
EXL3_HAD = 128, /* rotation block; both feature counts are multiples of it */
|
||||
EXL3_BITS_MIN = 1, /* integer K, bits a weight, that the DECODER reads (exllamav3 1.4.4: 1..8) */
|
||||
EXL3_BITS_MAX = 8
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ half-integer K (exllamav3 >= 1.6)
|
||||
*
|
||||
* exllamav3 1.6 adds K = KA + 0.5 (1.5, 2.5, 3.5; mul1 codebook only): the tile's positions alternate KA and KA + 1
|
||||
* bits, the ODD positions carrying the extra bit (exl3_lib/quantize.py frac_k: mask 0xAAAA), so a tile is a ring of
|
||||
* 128 * (2 KA + 1) bits = 16 * K uint16 (40 at K = 2.5). Position p's symbol is stream bits [S(p - 1), S(p)) and its
|
||||
* state the 16-bit window ending at S(p), circular in the ring, with S(p) = floor((p + 1) * K2 / 2) and K2 = 2 K --
|
||||
* which is (p + 1) * K at integer K, so ONE formula covers both (exllamav3 frac.cu frac_s / frac_window).
|
||||
*
|
||||
* Everything here that takes `int bits` takes K TAGGED: an integer K is itself (1..8), a half-integer K is
|
||||
* EXL3_HALF(KA) = 16 + 2 KA + 1 (1.5 -> 19, 2.5 -> 21, 3.5 -> 23). exl3_k2(bits) is 2 K either way.
|
||||
*
|
||||
* The canonical codes plane keeps the same rule along a row: element j (k = j) is bits [off(j), off(j + 1)) with
|
||||
* off(j) = floor(j * K2 / 2), LSB-first. Positions 2m and 2m + 1 of a tile are adjacent k (tile rows r, r + 1, r even)
|
||||
* in one n column, so in radiance's [n, k] view the even column holds KA bits and the odd column KA + 1: a row is
|
||||
* cols / 2 PAIR symbols of 2 KA + 1 bits (value = even | odd << KA), which is exactly a TILED u(2KA+1) plane of block
|
||||
* [1 x 2] (include/exl3_encoding.h). At integer K it is the uK [1 x 1] plane, bit for bit as before. */
|
||||
enum { EXL3_HALF_TAG = 16 };
|
||||
#define EXL3_HALF(ka) (EXL3_HALF_TAG + 2 * (ka) + 1)
|
||||
|
||||
static inline int exl3_bits_half(int bits) {
|
||||
return bits == EXL3_HALF(1) || bits == EXL3_HALF(2) || bits == EXL3_HALF(3);
|
||||
}
|
||||
static inline int exl3_bits_valid(int bits) {
|
||||
return (bits >= EXL3_BITS_MIN && bits <= EXL3_BITS_MAX) || exl3_bits_half(bits);
|
||||
}
|
||||
/* 2 K: half-bit units (K = 2.5 -> 5). 0 for a `bits` that is not valid. */
|
||||
static inline int exl3_k2(int bits) {
|
||||
return exl3_bits_half(bits) ? bits - EXL3_HALF_TAG : exl3_bits_valid(bits) ? 2 * bits : 0;
|
||||
}
|
||||
/* Bit offset of symbol j along a tile stream or a canonical row, and its width (K, or KA / KA + 1 by parity). */
|
||||
static inline int64_t exl3_sym_off(int bits, int64_t j) { return j * exl3_k2(bits) / 2; }
|
||||
static inline int exl3_sym_width(int bits, int64_t j) {
|
||||
return (int)(exl3_sym_off(bits, j + 1) - exl3_sym_off(bits, j));
|
||||
}
|
||||
|
||||
/* Codebooks, numbered as exllamav3 numbers them (cb template argument, codebook.cuh). */
|
||||
enum { EXL3_CB_3INST = 0, EXL3_CB_MCG = 1, EXL3_CB_MUL1 = 2 };
|
||||
|
||||
/* The scalar a checkpoint stores beside the trellis to name its codebook: `<name>.mul1` or
|
||||
* `<name>.mcg`, I32 [] holding these bits; neither present means 3inst. */
|
||||
#define EXL3_MUL1_MARKER 0x83DCD12Du
|
||||
#define EXL3_MCG_MARKER 0xCBAC1FEDu
|
||||
|
||||
/* Return codes. Negative is failure; consumers map them to their own (RAD_E_*). */
|
||||
enum { EXL3_OK = 0, EXL3_E_ARG = -1, EXL3_E_SHAPE = -2, EXL3_E_NOMEM = -3 };
|
||||
|
||||
/* "3inst", "mcg", "mul1"; null for anything else. Inline so header-only consumers
|
||||
* (include/exl3_encoding.h) need nothing linked. */
|
||||
static inline const char* exl3_codebook_name(int codebook) {
|
||||
return codebook == EXL3_CB_3INST ? "3inst"
|
||||
: codebook == EXL3_CB_MCG ? "mcg"
|
||||
: codebook == EXL3_CB_MUL1 ? "mul1" : 0;
|
||||
}
|
||||
/* The inverse; -1 for a name that is not one of the three. */
|
||||
static inline int exl3_codebook_from_name(const char* name) {
|
||||
int cb;
|
||||
for (cb = EXL3_CB_3INST; cb <= EXL3_CB_MUL1 && name; ++cb) {
|
||||
const char* a = exl3_codebook_name(cb);
|
||||
const char* b = name;
|
||||
while (*a && *a == *b) { ++a; ++b; }
|
||||
if (!*a && !*b) return cb;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ fp16 */
|
||||
float exl3_half_to_float(uint16_t h);
|
||||
/* Round to nearest even, ONE rounding of the exact double; overflow to inf, nan to 0x7E00. */
|
||||
uint16_t exl3_half_from_double(double x);
|
||||
|
||||
/* ------------------------------------------------------------------ codebook */
|
||||
/* A 16-bit trellis state (higher bits ignored) to its fp16 value, as fp16 bits. */
|
||||
uint16_t exl3_codebook_value(uint32_t state, int codebook);
|
||||
|
||||
/* ------------------------------------------------------------------ the tile */
|
||||
/* Position p (0..255) -> tile row r (k axis, 0..15) and tile column c (n axis, 0..15). */
|
||||
void exl3_pos_to_tile(int p, int* r, int* c);
|
||||
/* Tile (r, c) -> position. */
|
||||
int exl3_tile_to_pos(int r, int c);
|
||||
|
||||
/* One tile's stream (16*K uint16, i.e. 8*K little-endian u32 words, MSB-first) -> its 256 symbols,
|
||||
* symbol p being stream bits [off(p), off(p+1)) read MSB first (p*K .. (p+1)*K at integer K). */
|
||||
void exl3_tile_symbols(const uint16_t* tile, int bits, uint8_t sym[EXL3_TILE_POS]);
|
||||
/* The inverse: 256 symbols (low K bits used) -> the tile stream. Any symbols are a valid trellis. */
|
||||
void exl3_tile_pack(const uint8_t sym[EXL3_TILE_POS], int bits, uint16_t* tile);
|
||||
/* The 16-bit state of every position: the window of the symbol stream ending at symbol p's last
|
||||
* bit, circular within the tile (tail-biting). */
|
||||
void exl3_tile_states(const uint8_t sym[EXL3_TILE_POS], int bits, uint16_t state[EXL3_TILE_POS]);
|
||||
|
||||
/* A whole trellis tensor as exllamav3 stores it -- int16 [kt][nt][16*K] (K2 = 2K: 8*K2), tile (tk, tn) at
|
||||
* (tk*nt + tn)*16*K -- to W_hat [16*kt][16*nt] as fp16 bits (exllamav3's [k, n] order: the golden's).
|
||||
* EXL3_E_ARG for bits or codebook out of range. */
|
||||
int exl3_trellis_decode(const uint16_t* trellis, int64_t kt, int64_t nt, int bits, int codebook,
|
||||
uint16_t* w_hat);
|
||||
|
||||
/* ------------------------------------------------------------------ the codes plane */
|
||||
/* Element (i, j) of a codes plane, rows `row_bytes` apart, LSB-first along the row: the K-bit symbol of column j
|
||||
* (half-integer K: bits [off(j), off(j+1)), KA or KA + 1 wide by j's parity). */
|
||||
uint32_t exl3_codes_get(const uint8_t* codes, int64_t row_bytes, int bits, int64_t i, int64_t j);
|
||||
void exl3_codes_set(uint8_t* codes, int64_t row_bytes, int bits, int64_t i, int64_t j,
|
||||
uint32_t value);
|
||||
/* Bytes of one dense row of `cols` symbols: ceil(off(cols)/8) = ceil(cols*K/8). */
|
||||
int64_t exl3_codes_row_bytes(int64_t cols, int bits);
|
||||
|
||||
/* ------------------------------------------------------------------ the rotation */
|
||||
/* The normalised natural-order Sylvester Hadamard over each block of 128 of v[0..n), in place:
|
||||
* butterfly (a+b low, a-b high) in f32, then x (float)(1/sqrt(128)). EXL3_E_SHAPE unless n % 128 == 0. */
|
||||
int exl3_had128(float* v, int64_t n);
|
||||
|
||||
/* ------------------------------------------------------------------ one weight from its planes */
|
||||
/* One weight -- a projection, or a TP slice of one -- in radiance's [rows = n, cols = k] view, as
|
||||
* the canonical planes hold it. A STACKED gate_up (gate rows then up rows) has the up
|
||||
* half's input scales in `suh1`: rows [0, rows/2) are read with `suh`, rows [rows/2, rows) with
|
||||
* `suh1`. A TP slice of a stacked weight takes the same span of each half, so the rule holds for
|
||||
* the slice. */
|
||||
typedef struct Exl3View {
|
||||
int64_t rows, cols; /* n, k */
|
||||
int bits; /* K */
|
||||
int codebook; /* EXL3_CB_* */
|
||||
const uint8_t* codes; /* uK [rows][cols], row-major, LSB-first */
|
||||
int64_t codes_row_bytes; /* the stride; 0 = dense, exl3_codes_row_bytes(cols, bits) */
|
||||
const uint16_t* suh; /* f16 [cols] */
|
||||
const uint16_t* suh1; /* f16 [cols] for the second half of a stacked weight, or null */
|
||||
const uint16_t* svh; /* f16 [rows] */
|
||||
} Exl3View;
|
||||
|
||||
/* W_hat (the rotated basis, the values a kernel multiplies by) of rows [row0, row0+n) as f32
|
||||
* [n][cols], each an exact fp16 value. Needs only codes, bits, codebook, rows, cols; rows and cols
|
||||
* multiples of 16. EXL3_E_ARG / EXL3_E_SHAPE (a range outside the view) / EXL3_E_NOMEM. */
|
||||
int exl3_decode_what_rows(const Exl3View* v, int64_t row0, int64_t n, float* out);
|
||||
|
||||
/* The weight itself, rows [row0, row0+n) as f32 [n][cols] = W[k][n] transposed (see the header).
|
||||
* rows and cols multiples of 128 (both rotations), and of 256 rows when suh1 is set. Any row range
|
||||
* inside the view; the enclosing 128-row blocks are decoded. */
|
||||
int exl3_decode_rows(const Exl3View* v, int64_t row0, int64_t n, float* out);
|
||||
|
||||
#ifdef __cplusplus
|
||||
} /* extern "C" */
|
||||
#endif
|
||||
|
||||
#endif /* EXL3_DECODE_H */
|
||||
@@ -1,159 +0,0 @@
|
||||
/* exl3_encoding.h -- THE canonical EXL3 encoding, as radiance encoding data, and the
|
||||
* GEMM dtype strings the architecture and kernels name it by. Header-only.
|
||||
*
|
||||
* include/exl3_abi.h includes this file; nothing else defines the encoding. A weight in it:
|
||||
*
|
||||
* scheme "exl3" a quantiser's own scheme: the core checks plane 0 and
|
||||
* role uniqueness only (rad_enc_valid) and decodes it
|
||||
* through the exl3 quantiser's decode hook
|
||||
* transform "<codebook>/h128" "mul1/h128", "mcg/h128" or "3inst/h128": the trellis
|
||||
* codebook, and the rotation (normalised Hadamard,
|
||||
* block 128) on BOTH sides of the weight
|
||||
* plane 0 codes uK TILED [1x1] element (i, j) = the K-bit trellis symbol of W_hat at
|
||||
* (k = j, n = i), position-major (common/exl3_decode.h)
|
||||
* half-integer K = KA + 0.5: u(2KA+1) TILED [1x2]: element (i, m) = the PAIR symbol of
|
||||
* columns 2m (KA bits, low) and 2m + 1 (KA + 1 bits, high) --
|
||||
* the same bits as reading column j at off(j) = floor(j K2 / 2)
|
||||
* plane 1 suh f16 TILED [0x1] input scales, one a column (k); cut with the columns
|
||||
* plane 2 svh f16 TILED [1x0] output scales, one a row (n); cut with the rows
|
||||
* plane 3 suh.1 f16 TILED [0x1] STACKED gate_up only: the up half's input scales;
|
||||
* rows [rows/2, rows) read suh.1, the first half suh
|
||||
*
|
||||
* so a stacked 4-bit gate_up spells `exl3:codes=u4[1x1],suh=f16[*x1],svh=f16[1x*],suh.1=f16[*x1]/mul1/h128`.
|
||||
* The plane ORDER is fixed (the indices below) so down and gate_up share planes 0..2; read by role
|
||||
* where a role is enough. Encodings are identical byte for byte (rad_enc_equal) or different:
|
||||
* exl3_encoding_read() refuses anything exl3_encoding_make() would not have written.
|
||||
*
|
||||
* K is per weight and per encoding: two weights of different K are two encodings. A recipe's bits
|
||||
* option, the trellis tensor's last dimension (16*K) and the codes dtype must all agree.
|
||||
*/
|
||||
#ifndef EXL3_ENCODING_H
|
||||
#define EXL3_ENCODING_H
|
||||
|
||||
#include "rad_encoding.h"
|
||||
#include "exl3_decode.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* Bumped on any change to the encoding or a declaration below. 2: half-integer K (the [1x2] pair plane). */
|
||||
#define EXL3_ENCODING_VERSION 2
|
||||
|
||||
#define EXL3_SCHEME "exl3"
|
||||
#define EXL3_ROTATION "h128" /* the second half of the transform string */
|
||||
|
||||
enum { EXL3_PLANE_CODES = 0, EXL3_PLANE_SUH = 1, EXL3_PLANE_SVH = 2, EXL3_PLANE_SUH1 = 3 };
|
||||
|
||||
/* The K a GEMM dtype string exists for: "exl3k2" .. "exl3k8", and the half-integer "exl3k1h" (1.5), "exl3k2h"
|
||||
* (2.5), "exl3k3h" (3.5). The DECODER reads K 1..8 and the three half-integer K (exl3_decode.h: a TAGGED `bits`);
|
||||
* K=1 has no dtype string, so no kernel can be named for it and the quantiser refuses it. The loops below walk
|
||||
* EXL3_GEMM_BITS_MIN..MAX, the integer K; the half-integer K are listed apart. */
|
||||
enum { EXL3_GEMM_BITS_MIN = 2, EXL3_GEMM_BITS_MAX = 8 };
|
||||
|
||||
/* The core dtype of a codes plane: RAD_U1..RAD_U8 for integer K (one symbol an element); for half-integer K the
|
||||
* pair symbol's 2 KA + 1 bits (RAD_U3 / RAD_U5 / RAD_U7, block [1x2]); RAD_DT_INVALID otherwise. */
|
||||
static inline uint32_t exl3_codes_dtype(int bits) {
|
||||
static const uint32_t dt[9] = { RAD_DT_INVALID, RAD_U1, RAD_U2, RAD_U3, RAD_U4,
|
||||
RAD_U5, RAD_U6, RAD_U7, RAD_U8 };
|
||||
if (exl3_bits_half(bits)) return dt[exl3_k2(bits)];
|
||||
return bits >= EXL3_BITS_MIN && bits <= EXL3_BITS_MAX ? dt[bits] : (uint32_t)RAD_DT_INVALID;
|
||||
}
|
||||
|
||||
/* Columns of the codes plane's element grid over a weight of `cols` columns: cols, or cols / 2 pairs. */
|
||||
static inline int64_t exl3_codes_plane_cols(int64_t cols, int bits) {
|
||||
return exl3_bits_half(bits) ? cols / 2 : cols;
|
||||
}
|
||||
|
||||
/* The inverse of exl3_codes_dtype for a [1x1] codes plane (integer K): K, or -1. */
|
||||
static inline int exl3_bits_of_dtype(uint32_t dtype) {
|
||||
int k;
|
||||
for (k = EXL3_BITS_MIN; k <= EXL3_BITS_MAX; ++k)
|
||||
if (exl3_codes_dtype(k) == dtype) return k;
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* The (tagged) K of a codes plane by its dtype AND block: [1x1] integer K, [1x2] half-integer K; -1 otherwise. */
|
||||
static inline int exl3_bits_of_plane(uint32_t dtype, int64_t block_cols) {
|
||||
int ka;
|
||||
if (block_cols == 1) return exl3_bits_of_dtype(dtype);
|
||||
if (block_cols != 2) return -1;
|
||||
for (ka = 1; ka <= 3; ++ka)
|
||||
if (exl3_codes_dtype(EXL3_HALF(ka)) == dtype) return EXL3_HALF(ka);
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* The GEMM dtype string an op constraint names for K-bit EXL3 weights; null when K has none. It
|
||||
* names K only: the codebook is in the encoding, and a kernel's layout hook refuses a codebook it
|
||||
* does not decode (RAD_E_DTYPE) -- the gfx1201 rows decode mul1 alone. */
|
||||
static inline const char* exl3_gemm_dtype(int bits) {
|
||||
static const char* const s[9] = { 0, 0, "exl3k2", "exl3k3", "exl3k4",
|
||||
"exl3k5", "exl3k6", "exl3k7", "exl3k8" };
|
||||
static const char* const h[4] = { 0, "exl3k1h", "exl3k2h", "exl3k3h" };
|
||||
if (exl3_bits_half(bits)) return h[exl3_k2(bits) / 2];
|
||||
return bits >= EXL3_GEMM_BITS_MIN && bits <= EXL3_GEMM_BITS_MAX ? s[bits] : 0;
|
||||
}
|
||||
|
||||
/* K of a GEMM dtype string (tagged for half-integer K), or -1. */
|
||||
static inline int exl3_gemm_bits(const char* dtype) {
|
||||
int k;
|
||||
for (k = EXL3_GEMM_BITS_MIN; k <= EXL3_GEMM_BITS_MAX && dtype; ++k)
|
||||
if (strcmp(dtype, exl3_gemm_dtype(k)) == 0) return k;
|
||||
for (k = 1; k <= 3 && dtype; ++k)
|
||||
if (strcmp(dtype, exl3_gemm_dtype(EXL3_HALF(k))) == 0) return EXL3_HALF(k);
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* The encoding of a K-bit weight in `codebook`; `stacked` nonzero for a gate_up (adds suh.1).
|
||||
* RAD_OK, or RAD_E_INVAL for K outside 1..8 and the half-integer three, an unknown codebook, or a
|
||||
* half-integer K in another codebook than mul1. */
|
||||
static inline int exl3_encoding_make(int bits, int codebook, int stacked, RadEncoding* out) {
|
||||
char t[RAD_ENC_STR];
|
||||
const char* cb = exl3_codebook_name(codebook);
|
||||
const uint32_t dt = exl3_codes_dtype(bits);
|
||||
if (!out || !cb || dt == RAD_DT_INVALID) return RAD_E_INVAL;
|
||||
if (exl3_bits_half(bits) && codebook != EXL3_CB_MUL1) return RAD_E_INVAL;
|
||||
rad_enc_clear(out);
|
||||
rad_enc_copy_str(out->scheme, EXL3_SCHEME);
|
||||
snprintf(t, sizeof t, "%s/%s", cb, EXL3_ROTATION);
|
||||
rad_enc_copy_str(out->transform, t);
|
||||
rad_enc_add_plane(out, "codes", dt, 1, exl3_bits_half(bits) ? 2 : 1);
|
||||
rad_enc_add_plane(out, "suh", RAD_F16, 0, 1);
|
||||
rad_enc_add_plane(out, "svh", RAD_F16, 1, 0);
|
||||
if (stacked) rad_enc_add_plane(out, "suh.1", RAD_F16, 0, 1);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Read an encoding back. RAD_E_UNSUPPORTED when the scheme is not "exl3" (not ours: a decoder
|
||||
* answers that and the core asks the next one); RAD_E_FORMAT when it says "exl3" but is not exactly
|
||||
* what exl3_encoding_make writes for some K, codebook and stacking; RAD_OK otherwise, with the
|
||||
* three filled in (any pointer may be null). */
|
||||
static inline int exl3_encoding_read(const RadEncoding* e, int* bits, int* codebook, int* stacked) {
|
||||
RadEncoding want;
|
||||
char cb[RAD_ENC_STR];
|
||||
const char* slash;
|
||||
size_t n;
|
||||
int k, c, s;
|
||||
if (!e || !rad_enc_is(e, EXL3_SCHEME)) return RAD_E_UNSUPPORTED;
|
||||
if (e->n_planes < 3 || e->n_planes > 4) return RAD_E_FORMAT;
|
||||
slash = (const char*)memchr(e->transform, '/', RAD_ENC_STR);
|
||||
if (!slash) return RAD_E_FORMAT;
|
||||
n = (size_t)(slash - e->transform);
|
||||
memcpy(cb, e->transform, n);
|
||||
cb[n] = 0;
|
||||
k = exl3_bits_of_plane(e->plane[EXL3_PLANE_CODES].dtype, e->plane[EXL3_PLANE_CODES].block[1]);
|
||||
c = exl3_codebook_from_name(cb);
|
||||
s = e->n_planes == 4;
|
||||
if (k < 0 || c < 0 || exl3_encoding_make(k, c, s, &want) != RAD_OK || !rad_enc_equal(e, &want))
|
||||
return RAD_E_FORMAT;
|
||||
if (bits) *bits = k;
|
||||
if (codebook) *codebook = c;
|
||||
if (stacked) *stacked = s;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
#ifdef __cplusplus
|
||||
} /* extern "C" */
|
||||
#endif
|
||||
|
||||
#endif /* EXL3_ENCODING_H */
|
||||
+37
-3
@@ -876,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
|
||||
@@ -930,6 +933,13 @@ struct Geom {
|
||||
* 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; }
|
||||
@@ -1057,10 +1067,28 @@ inline rad_op decl_all_reduce_exact(RadBuilder* b, const Geom& g, rad_buf x) {
|
||||
}
|
||||
|
||||
/* 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) {
|
||||
@@ -1322,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;
|
||||
@@ -1494,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
|
||||
@@ -1512,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;
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
@@ -37,6 +38,7 @@ struct AttnQ {
|
||||
rad_buf x = 0; /* [max_tok, n_embd] the residual stream */
|
||||
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 */
|
||||
ActQ attn{}; /* [max_tok, q_dim] attention output */
|
||||
};
|
||||
@@ -49,6 +51,8 @@ struct AttnQ {
|
||||
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{};
|
||||
@@ -67,6 +71,9 @@ struct AttnQ {
|
||||
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,
|
||||
@@ -120,7 +127,10 @@ inline int AttnQ::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad
|
||||
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});
|
||||
|
||||
@@ -131,6 +141,36 @@ inline int AttnQ::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad
|
||||
* kernels gain a q pitch. `cast` with from == to is this tree's row copy. */
|
||||
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). */
|
||||
op_attn = rw(b, rad_decl_op(b, "attn_paged",
|
||||
@@ -149,7 +189,8 @@ inline int AttnQ::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad
|
||||
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
|
||||
@@ -185,12 +226,22 @@ inline void AttnQ::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),
|
||||
|
||||
@@ -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 */
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
+34
-18
@@ -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));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -127,7 +127,7 @@ inline int MlpQ::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, cons
|
||||
* 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.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
|
||||
|
||||
+186
-139
@@ -50,7 +50,13 @@
|
||||
#include "rad_linear.h"
|
||||
#include "rad_block_glm_router.h"
|
||||
#include "rad_device.h"
|
||||
#include "exl3/exl3_abi.h" /* EXL3 experts (radiance-exl3, exl3/): the encoding, op schemas, operand positions */
|
||||
/* EXL3-V3 experts (exl3i records; plugin/exl3i's moe_exl3_gate_up / moe_exl3_down): the encoding, the op schemas and
|
||||
* operand positions. Header-only; one copy in the tree (no vendored twin to keep equal). */
|
||||
#if __has_include("exl3i_moe_abi.h")
|
||||
#include "exl3i_moe_abi.h"
|
||||
#else
|
||||
#include "../../plugin/exl3import/include/exl3i_moe_abi.h"
|
||||
#endif
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
@@ -131,6 +137,12 @@ struct MoeQ {
|
||||
/* This rank's first expert id in the model's numbering. moe_scatter subtracts it so the
|
||||
* offsets, counts and weight table are local. */
|
||||
int64_t expert_base = 0;
|
||||
/* The model's expert behind each of this rank's n_expert, when the router numbers its
|
||||
* experts otherwise than the checkpoint does (a plugin that relabels experts and permutes
|
||||
* its router to match, rad_weight_row_order): local expert e is router label
|
||||
* expert_base + e and checkpoint expert expert_ids[e]. Null: expert_base + e for both. It
|
||||
* names the weights only; the scatter, offsets and counts stay in router labels. */
|
||||
const int32_t* expert_ids = nullptr;
|
||||
int64_t top_k = 0;
|
||||
int64_t n_ff_exp = 0; /* one expert's intermediate width, per rank */
|
||||
/* This rank's slice of each routed expert when the width does not halve into whole fp8
|
||||
@@ -274,12 +286,12 @@ struct MoeQ {
|
||||
* reads it against the rotated int8 activations (dtype `i8a8h`, libr4d's moe_gemm_iqr).
|
||||
* Set with `expert_rot`. */
|
||||
int expert_iqr = 0;
|
||||
/* EXL3 trellis experts (radiance-exl3's canonical `exl3` encoding, imported from an
|
||||
* exllamav3 checkpoint): whole experts like bf16, read by moe_exl3_gate_up / moe_exl3_down
|
||||
* (exl3/exl3_abi.h), which take the bf16 activation and do the rotations and silu(gate) * up
|
||||
* (with swiglu_limit) themselves. K and the codebook are each layer's and projection's own.
|
||||
* Format 14. */
|
||||
int expert_exl3 = 0;
|
||||
/* EXL3-V3 trellis experts (the `exl3i` encoding of plugin/exl3import: gate_up stacked with suh.1, down
|
||||
* plain; what exl3quant / exl3import write for a trunk weight): whole experts like bf16, read by
|
||||
* moe_exl3_gate_up / moe_exl3_down (plugin/exl3import/include/exl3i_moe_abi.h), which take the bf16
|
||||
* activation and do the rotations and silu(gate) * up (with swiglu_limit) themselves. The rate and the
|
||||
* codebook are each layer's and projection's own. Format 15. */
|
||||
int expert_exl3i = 0;
|
||||
/* Plain bf16 experts (no quantising recipe). Both GEMMs are `moe_gemm` over one table of
|
||||
* whole experts with `silu_mul` between, and the shared arm follows the trunk
|
||||
* (Geom::w_bf16). Not sliced by parity: each expert is served whole on its rank, which
|
||||
@@ -307,6 +319,18 @@ struct MoeQ {
|
||||
* `expert_rot` that is rotated, the same basis the packer quantises in. */
|
||||
int calib = 0;
|
||||
int64_t rows = 0; /* tokens per pass; 0 means the whole step */
|
||||
/* The caller routes (ERNIE-5.5's split-feature router, rad_block_ernie_moe.h): it writes
|
||||
* Wire::ids (i32) and Wire::ew (f32) for the whole step before step(), and this block
|
||||
* declares no router, no selection and none of their fused forms; the scatter starts the
|
||||
* routed arm. Not with `sigmoid_router`. */
|
||||
int ext_router = 0;
|
||||
/* SiTU experts (ERNIE-5.5's SituAndMul, beta 4 and linear_beta 25): situ_mul then
|
||||
* quant_act_fp8 between the GEMMs (GateQuant's "situ"), for the routed arm and a shared
|
||||
* one. Unclamped and gated. */
|
||||
int situ = 0;
|
||||
/* Serve OCP MXFP4 experts as stored rather than refusing them by name (ERNIE-5.5's W4A8
|
||||
* QAT routed experts). Set by the plugin before probe(). */
|
||||
int allow_mxfp4 = 0;
|
||||
};
|
||||
|
||||
/* Only the four planes with one row per (token, slot) are a pass tall; everything else has one
|
||||
@@ -395,6 +419,11 @@ struct MoeQ {
|
||||
mutable const int32_t* vl_mask_ = nullptr;
|
||||
int layer = 0;
|
||||
|
||||
/* Local expert e's number in the checkpoint (Config::expert_ids). */
|
||||
long long gid(int64_t e) const {
|
||||
return c.expert_ids ? (long long)c.expert_ids[e] : (long long)(c.expert_base + e);
|
||||
}
|
||||
|
||||
rad_weight w_norm = 0, w_router = 0, w_sgate = 0;
|
||||
GlmRouter glm_router{};
|
||||
/* The input was normed and quantised by the caller; this block declares no norm. */
|
||||
@@ -539,37 +568,35 @@ struct MoeQ {
|
||||
* five-bit form per 64, 8 OCP MXFP4, 9 block fp8 at f32 scales, 10 rotated int8, 11 the rotated
|
||||
* computed trellis under one f32 scale a row (an IQR weight an expert), 12 the codebook's
|
||||
* six-bit form per 64, 13 llama.cpp's blocks of any GGUF type moe_gemm_ggml reads,
|
||||
* 14 EXL3 trellis codes (radiance-exl3's encoding); RAD_E_DTYPE otherwise. */
|
||||
* 15 EXL3-V3 trellis records (the exl3i encoding); RAD_E_DTYPE otherwise. */
|
||||
static int format_of(const RadEncoding& e);
|
||||
/* format_of's numbers as the grouped GEMMs' dtype strings against an E4M3 activation, and
|
||||
* against an int8 one (null: the format has no such row). Int8 experts read int8 only. 13,
|
||||
* llama.cpp's blocks, names the family: moe_gemm_ggml takes the type itself. */
|
||||
static constexpr const char* kServed[15] = { "fp8a8", "w4a8", "w4a8h", "bf16", "w4nla8h",
|
||||
"w4nl64a8h", "w4nl32a8h", "w5nl64a8h", "mxfp4a8",
|
||||
"fp8a8f32", nullptr, nullptr, "w6nl64a8h", "ggml",
|
||||
"exl3" };
|
||||
static constexpr const char* kServed8[15] = { nullptr, nullptr, "w4a8i8h", nullptr, nullptr,
|
||||
static constexpr const char* kServed[16] = { "fp8a8", "w4a8", "w4a8h", "bf16", "w4nla8h",
|
||||
"w4nl64a8h", "w4nl32a8h", "w5nl64a8h", "mxfp4a8",
|
||||
"fp8a8f32", nullptr, nullptr, "w6nl64a8h", "ggml",
|
||||
nullptr, "exl3i" };
|
||||
static constexpr const char* kServed8[16] = { nullptr, nullptr, "w4a8i8h", nullptr, nullptr,
|
||||
"w4nl64a8i8h", "w4nl32a8i8h", nullptr, nullptr,
|
||||
nullptr, "i8a8h", "i8a8h", nullptr, nullptr, nullptr };
|
||||
nullptr, "i8a8h", "i8a8h", nullptr, nullptr, nullptr,
|
||||
nullptr };
|
||||
/* Per projection (gate_up, down), the GGUF type and its block along K of this layer's experts
|
||||
* under expert_ggml. */
|
||||
const char* ggml_ty[2] = { nullptr, nullptr };
|
||||
int64_t ggml_blk[2] = { 0, 0 };
|
||||
/* Per projection (gate_up, down) under expert_exl3: the op's dtype ("exl3k2" ...), codebook
|
||||
* ("mul1"), K and the codes plane's columns per element (1, or 2 for a half-bit pair plane),
|
||||
* and the runs: one run a plane, each the even experts then the odd ones, declared in that
|
||||
* order so a (plane, parity) table is RAD_WTAB(first, ne / 2). */
|
||||
const char* x3_dtype[2] = { nullptr, nullptr };
|
||||
const char* x3_cb[2] = { nullptr, nullptr };
|
||||
int x3_bits[2] = { 0, 0 };
|
||||
int64_t x3_cpe[2] = { 1, 1 };
|
||||
uint32_t x3_cdt[2] = { 0, 0 };
|
||||
std::vector<rad_weight> x3_gu[4], x3_dn[3];
|
||||
rad_buf b_x3h = 0; /* gate_up's f16 h (rotated for down, h_rot 1), [rows * top_k, n_ff_exp] */
|
||||
int declare_exl3(RadBuilder* b, Names& nm, int l);
|
||||
void issue_exl3(RadCtx* c_, rad_op op_h, int op, int64_t rows, RadOperand in, RadOperand out) const;
|
||||
/* bf16, GGUF-block and EXL3 experts all read the bf16 activation, whole on their rank. */
|
||||
bool act_bf16() const { return c.expert_bf16 || c.expert_ggml || c.expert_exl3; }
|
||||
/* Per projection (gate_up, down) under expert_exl3i: the rate (m / 16, and its canonical text for the op) and
|
||||
* the codebook's name, and the runs: one run a plane, each the even experts then the odd ones, declared in
|
||||
* that order so a (plane, parity) table is RAD_WTAB(first, ne / 2). */
|
||||
int xi_m[2] = { 0, 0 };
|
||||
char xi_rate[2][16] = { "", "" };
|
||||
const char* xi_cb[2] = { nullptr, nullptr };
|
||||
std::vector<rad_weight> xi_gu[4], xi_dn[3];
|
||||
rad_buf b_xih = 0; /* gate_up's f16 h (rotated for down, h_rot 1), [rows * top_k, n_ff_exp] */
|
||||
int declare_exl3i(RadBuilder* b, Names& nm, int l);
|
||||
void issue_exl3i(RadCtx* c_, rad_op op_h, int op, int64_t rows, RadOperand in, RadOperand out) const;
|
||||
/* bf16, GGUF-block and EXL3-V3 experts all read the bf16 activation, whole on their rank. */
|
||||
bool act_bf16() const { return c.expert_bf16 || c.expert_ggml || c.expert_exl3i; }
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
const Wire& wire, const Src& src, bool fold = false, bool add_out = true,
|
||||
@@ -614,7 +641,7 @@ struct MoeQ {
|
||||
};
|
||||
|
||||
inline int MoeQ::format_of(const RadEncoding& e) {
|
||||
if (rad_enc_is(&e, EXL3_SCHEME)) return 14;
|
||||
if (rad_enc_is(&e, EXL3I_SCHEME)) return 15;
|
||||
if (linear_is_mxfp4(e)) return 8;
|
||||
if (ggml_type_of(e)) return 13;
|
||||
if (rad_enc_is(&e, "plain") && e.n_planes == 1 && e.plane[0].dtype == RAD_BF16) return 3;
|
||||
@@ -749,12 +776,13 @@ inline int MoeQ::probe(RadBuilder* b, Names& nm, int l, const Src& src, Config*
|
||||
"f32, or its 32-entry five-bit form at a 64, or OCP MXFP4 "
|
||||
"(fp4_e2m1*e8m0[1x32]), or rotated int8 (i8*bf16[1x128]/fwht128), or "
|
||||
"the rotated computed trellis under one f32 scale a row, or a GGUF's "
|
||||
"llama.cpp blocks, or EXL3 trellis codes. Convert it with a recipe that "
|
||||
"llama.cpp blocks, or EXL3-V3 trellis records (exl3i). "
|
||||
"Convert it with a recipe that "
|
||||
"makes one of them.\n",
|
||||
guw, en);
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
if (known && (f == 0 || f == 8 || f == 9))
|
||||
if (known && (f == 0 || f == 9 || (f == 8 && !cfg->allow_mxfp4)))
|
||||
return linear_refuse_retired(guw, f == 8 ? "MXFP4" : "block fp8");
|
||||
if (f != 3) break;
|
||||
}
|
||||
@@ -764,7 +792,7 @@ inline int MoeQ::probe(RadBuilder* b, Names& nm, int l, const Src& src, Config*
|
||||
cfg->expert_iqr = f == 11 ? 1 : 0;
|
||||
cfg->expert_nl = (f == 4 || f == 5 || f == 6 || f == 7 || f == 12) ? 1 : 0;
|
||||
cfg->expert_g64 = (f == 5 || f == 7 || f == 12) ? 2 : f == 6 ? 4 : 0;
|
||||
cfg->expert_exl3 = f == 14 ? 1 : 0;
|
||||
cfg->expert_exl3i = f == 15 ? 1 : 0;
|
||||
cfg->expert_w5 = f == 7 ? 1 : 0;
|
||||
cfg->expert_w6 = f == 12 ? 1 : 0;
|
||||
cfg->expert_bf16 = f == 3 ? 1 : 0;
|
||||
@@ -805,7 +833,16 @@ inline int MoeQ::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
/* The first GEMM's rows per intermediate column (gate and up, or up alone) and the activation
|
||||
* between the GEMMs. */
|
||||
const int64_t gu = c.ungated ? 1 : 2;
|
||||
const char* const gact = c.ungated ? "relu2" : "silu";
|
||||
const char* const gact = c.ungated ? "relu2" : c.situ ? "situ" : "silu";
|
||||
if (c.situ && (c.ungated || c.swiglu_limit > 0 || sh_limit > 0)) {
|
||||
fprintf(stderr, "radiance: SiTU experts are gated and unclamped\n");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (c.ext_router && (c.sigmoid_router || !w.ids || !w.ew)) {
|
||||
fprintf(stderr, "radiance: a routed feed-forward routed by its caller reads Wire::ids and "
|
||||
"Wire::ew and declares no router of its own\n");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (c.ungated && (shared || src.experts_gate_up || src.experts_gate ||
|
||||
c.swiglu_limit > 0)) {
|
||||
fprintf(stderr, "radiance: ungated experts are served one by one (`up_proj`), unclamped and "
|
||||
@@ -842,7 +879,7 @@ inline int MoeQ::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
* own bf16 GEMM pair, so they must be known before the sort is declared. */
|
||||
const int64_t ne = c.n_expert;
|
||||
for (int64_t e = 0; e < ne; ++e) {
|
||||
const long long ge = (long long)(c.expert_base + e); /* the checkpoint's numbering */
|
||||
const long long ge = gid(e); /* the checkpoint's numbering */
|
||||
const bool probed = c.probed_layer == l && ge >= (long long)c.probed_expert &&
|
||||
ge < (long long)(c.probed_expert + c.probed_count);
|
||||
RAD_ARCH_TRY(moe_map_expert(b, nm, src, nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l, ge),
|
||||
@@ -855,11 +892,11 @@ inline int MoeQ::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
ggml_ty[0] = ggml_ty[1] = nullptr;
|
||||
ggml_blk[0] = ggml_blk[1] = 0;
|
||||
{
|
||||
const int want = c.expert_exl3 ? 14 : c.expert_ggml ? 13 : c.expert_iqr ? 11 : c.expert_i8 ? 10 : c.expert_f32_scale ? 9 : c.expert_mx ? 8 : c.expert_bf16 ? 3 : c.expert_w6 ? 12 : c.expert_w5 ? 7 : c.expert_g64 == 4 ? 6
|
||||
const int want = c.expert_exl3i ? 15 : c.expert_ggml ? 13 : c.expert_iqr ? 11 : c.expert_i8 ? 10 : c.expert_f32_scale ? 9 : c.expert_mx ? 8 : c.expert_bf16 ? 3 : c.expert_w6 ? 12 : c.expert_w5 ? 7 : c.expert_g64 == 4 ? 6
|
||||
: c.expert_g64 ? 5 : c.expert_nl ? 4
|
||||
: c.expert_w4 ? (c.expert_rot ? 2 : 1) : 0;
|
||||
auto fmt_of = [&](int64_t e, RadEncoding (&enc)[2], int (&fe)[2], const char* (&nmv)[2]) {
|
||||
const long long ge = (long long)(c.expert_base + e);
|
||||
const long long ge = gid(e);
|
||||
nmv[0] = nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l, ge);
|
||||
nmv[1] = nm.f("blk.%d.ffn_down_exps.%lld.weight", l, ge);
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
@@ -903,33 +940,29 @@ inline int MoeQ::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
int fe[2];
|
||||
const char* names[2];
|
||||
fmt_of(e, enc, fe, names);
|
||||
if (fe[0] == 14 && fe[1] == 14 && want == 14) {
|
||||
/* One K and codebook per projection across the layer's experts (a table of experts
|
||||
if (fe[0] == 15 && fe[1] == 15 && want == 15) {
|
||||
/* One rate and codebook per projection across the layer's experts (a table of experts
|
||||
* takes one encoding); gate_up stacked (suh.1), down not. */
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
int bits = 0, cb = 0, st = 0;
|
||||
const char* dt = nullptr;
|
||||
if (exl3_encoding_read(&enc[i], &bits, &cb, &st) != RAD_OK || st != (i == 0) ||
|
||||
!(dt = exl3_gemm_dtype(bits)) || !exl3_codebook_name(cb)) {
|
||||
int m = 0, cb = 0, st = 0;
|
||||
int64_t er = 0, ec = 0;
|
||||
if (exl3i_encoding_read(&enc[i], &m, &cb, &st, &er, &ec) != RAD_OK || st != (i == 0)) {
|
||||
char en[256];
|
||||
rad_enc_format(&enc[i], en, sizeof en);
|
||||
fprintf(stderr, "radiance: '%s' is %s, which the EXL3 expert ops do not read (a %s "
|
||||
"projection, K the ops name, a known codebook)\n", names[i], en,
|
||||
i ? "plain down" : "stacked gate_up");
|
||||
fprintf(stderr, "radiance: '%s' is %s, which the EXL3-V3 expert ops do not read (a %s "
|
||||
"projection in natural row order, a rate and codebook the format has)\n",
|
||||
names[i], en, i ? "plain down" : "stacked gate_up");
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
if (!x3_dtype[i]) {
|
||||
x3_dtype[i] = dt;
|
||||
x3_cb[i] = exl3_codebook_name(cb);
|
||||
x3_bits[i] = bits;
|
||||
x3_cdt[i] = enc[i].plane[EXL3_PLANE_CODES].dtype;
|
||||
x3_cpe[i] = enc[i].plane[EXL3_PLANE_CODES].block[1] > 0
|
||||
? enc[i].plane[EXL3_PLANE_CODES].block[1] : 1;
|
||||
} else if (std::strcmp(dt, x3_dtype[i]) != 0 ||
|
||||
std::strcmp(exl3_codebook_name(cb), x3_cb[i]) != 0) {
|
||||
fprintf(stderr, "radiance: '%s' is %s/%s and the layer's first expert %s/%s; one "
|
||||
"table of experts takes one encoding\n", names[i], dt,
|
||||
exl3_codebook_name(cb), x3_dtype[i], x3_cb[i]);
|
||||
if (!xi_m[i]) {
|
||||
xi_m[i] = m;
|
||||
xi_cb[i] = exl3i_codebook_name(cb);
|
||||
exl3i_rate_str(m, xi_rate[i]);
|
||||
} else if (m != xi_m[i] || std::strcmp(exl3i_codebook_name(cb), xi_cb[i]) != 0) {
|
||||
char r[16];
|
||||
fprintf(stderr, "radiance: '%s' is %s/k%s and the layer's first expert %s/k%s; one "
|
||||
"table of experts takes one encoding\n", names[i],
|
||||
exl3i_codebook_name(cb), exl3i_rate_str(m, r), xi_cb[i], xi_rate[i]);
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
}
|
||||
@@ -959,8 +992,10 @@ inline int MoeQ::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
(fmt[1] != 11 || enc[1].plane[0].dtype == fenc[1].plane[0].dtype);
|
||||
if (same) continue;
|
||||
/* A whole expert kept bf16 is served beside quantised ones, not beside llama.cpp's
|
||||
* blocks or EXL3 experts: those are one table of whole experts already. */
|
||||
if (want != 3 && want != 13 && want != 14 && fe[0] == 3 && fe[1] == 3) { prot.push_back(e); continue; }
|
||||
* blocks or EXL3-V3 experts: those are one table of whole experts already. */
|
||||
if (want != 3 && want != 13 && want != 15 && fe[0] == 3 && fe[1] == 3) {
|
||||
prot.push_back(e); continue;
|
||||
}
|
||||
const int i = fe[0] != fmt[0] ? 0 : 1;
|
||||
char en[256];
|
||||
rad_enc_format(&enc[i], en, sizeof en);
|
||||
@@ -1000,7 +1035,7 @@ inline int MoeQ::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
/* The router is replicated (see Config::n_expert_all): every rank computes the same routing
|
||||
* from the full residual stream, so `sorted_tok` and `expert_offset` agree across ranks
|
||||
* without a collective. The sigmoid router (GlmRouter) declares its own projection. */
|
||||
if (!c.sigmoid_router) {
|
||||
if (!c.sigmoid_router && !c.ext_router) {
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ffn_gate_inp.weight", l), src.router));
|
||||
w_router = decl_w(b, nm.f("blk.%d.ffn_gate_inp.weight", l), RAD_BF16,
|
||||
{c.n_expert_all, g.n_embd},
|
||||
@@ -1030,7 +1065,7 @@ inline int MoeQ::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
w_router = glm_router.projection;
|
||||
op_router = glm_router.op_project;
|
||||
op_topk = glm_router.op_select;
|
||||
} else {
|
||||
} else if (!c.ext_router) {
|
||||
op_router = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", c.n_expert_all),
|
||||
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
@@ -1072,7 +1107,7 @@ inline int MoeQ::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
* depend on it. The sigmoid router selects in its own op and takes no fused pair. */
|
||||
topk_scatter_rows = (int64_t)c.rows * c.top_k <= kMoeSortRows ? c.rows
|
||||
: kMoeSortRows / c.top_k;
|
||||
if (c.sigmoid_router || scatter_inv) topk_scatter_rows = 0;
|
||||
if (c.sigmoid_router || c.ext_router || scatter_inv) topk_scatter_rows = 0;
|
||||
/* Asked for only where a loaded library declares it: a CPU-only engine would refuse the
|
||||
* declare, and the two separate ops serve without it. */
|
||||
if (topk_scatter_rows > 0 && rad_op_declared(b, "router_topk_scatter")) {
|
||||
@@ -1260,8 +1295,8 @@ inline int MoeQ::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
return rad_weight_shard_span(b, h, qlo[q] / unit, qhi[q] / unit);
|
||||
};
|
||||
const bool rot = c.expert_rot != 0;
|
||||
if (c.expert_exl3) {
|
||||
RAD_ARCH_TRY(declare_exl3(b, nm, l));
|
||||
if (c.expert_exl3i) {
|
||||
RAD_ARCH_TRY(declare_exl3i(b, nm, l));
|
||||
} else if (act_bf16()) {
|
||||
/* ---- Plain bf16 experts: one table per projection of whole experts in expert order
|
||||
* (`moe_gemm`, expert e at entry e), so the two loops must not be merged. Each expert is
|
||||
@@ -1296,14 +1331,14 @@ inline int MoeQ::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
for (int64_t e = 0; e < ne; ++e) {
|
||||
const int64_t parts[2] = { c.n_ff_exp, c.n_ff_exp }; /* gate, up (up alone: one) */
|
||||
w_gu[(size_t)e] = decl_w_n(b, nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l,
|
||||
(long long)(c.expert_base + e)),
|
||||
gid(e)),
|
||||
edt[0], {gu * c.n_ff_exp, g.n_embd}, RAD_ACCESS_CONDITIONAL,
|
||||
sh_row, grp_expert_slot(l, (int)e, 0), 0, parts, n_parts);
|
||||
if (!w_gu[(size_t)e]) return RAD_E_INVAL;
|
||||
}
|
||||
for (int64_t e = 0; e < ne; ++e) {
|
||||
w_dn[(size_t)e] = decl_w(b, nm.f("blk.%d.ffn_down_exps.%lld.weight", l,
|
||||
(long long)(c.expert_base + e)),
|
||||
gid(e)),
|
||||
edt[1], {g.n_embd, c.n_ff_exp}, RAD_ACCESS_CONDITIONAL,
|
||||
sh_col, grp_expert_slot(l, (int)e, 1));
|
||||
if (!w_dn[(size_t)e]) return RAD_E_INVAL;
|
||||
@@ -1344,7 +1379,7 @@ inline int MoeQ::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
const int64_t parts[2] = { wq[q], wq[q] };
|
||||
rad_weight& h = w_gu[(size_t)s];
|
||||
h = decl_view(b, nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l,
|
||||
(long long)(c.expert_base + e)),
|
||||
gid(e)),
|
||||
nullptr, ef[0].cplanes, ef[0].cdt, {gu * wq[q], g.n_embd},
|
||||
RAD_ACCESS_CONDITIONAL, sh_row, grp_expert_slot(l, (int)s, 0),
|
||||
parts, n_parts);
|
||||
@@ -1357,9 +1392,9 @@ inline int MoeQ::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
const int64_t parts[2] = { wq[q] / sdiv, wq[q] / sdiv };
|
||||
rad_weight& h = w_gus[(size_t)s];
|
||||
h = decl_view(b, nm.f("blk.%d.ffn_gate_up_exps.%lld.scale", l,
|
||||
(long long)(c.expert_base + e)),
|
||||
gid(e)),
|
||||
nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l,
|
||||
(long long)(c.expert_base + e)),
|
||||
gid(e)),
|
||||
ef[0].splanes, ef[0].sdt,
|
||||
{rowscale ? gu * wq[q] : scale_groups(gu * wq[q]),
|
||||
rowscale ? g.n_embd / ef[0].sgk : scale_groups(g.n_embd)},
|
||||
@@ -1373,7 +1408,7 @@ inline int MoeQ::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
const int64_t e = reg[(size_t)s];
|
||||
rad_weight& h = w_dn[(size_t)s];
|
||||
h = decl_view(b, nm.f("blk.%d.ffn_down_exps.%lld.weight", l,
|
||||
(long long)(c.expert_base + e)),
|
||||
gid(e)),
|
||||
nullptr, ef[1].cplanes, ef[1].cdt, {g.n_embd, wq[q]},
|
||||
RAD_ACCESS_CONDITIONAL, sh_col, grp_expert_slot(l, (int)s, 1));
|
||||
if (!h) return RAD_E_INVAL;
|
||||
@@ -1384,9 +1419,9 @@ inline int MoeQ::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
const int64_t e = reg[(size_t)s];
|
||||
rad_weight& h = w_dns[(size_t)s];
|
||||
h = decl_view(b, nm.f("blk.%d.ffn_down_exps.%lld.scale", l,
|
||||
(long long)(c.expert_base + e)),
|
||||
gid(e)),
|
||||
nm.f("blk.%d.ffn_down_exps.%lld.weight", l,
|
||||
(long long)(c.expert_base + e)),
|
||||
gid(e)),
|
||||
ef[1].splanes, ef[1].sdt,
|
||||
{rowscale ? g.n_embd : scale_groups(g.n_embd), wq[q] / ef[1].sgk},
|
||||
RAD_ACCESS_CONDITIONAL, sh_col, grp_expert_slot(l, (int)s, 1));
|
||||
@@ -1408,7 +1443,7 @@ inline int MoeQ::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
* consumer so graph and issue order agree. */
|
||||
gin_q = w.h.q;
|
||||
gin_s = w.h.s;
|
||||
gin_g = RAD_SCALE_GROUP;
|
||||
gin_g = w.h.group;
|
||||
if (a8 && w.h.q8_fed && w.h.q8_rot) {
|
||||
/* The trunk's own rotated int8 codes, at its group: no second quantiser. */
|
||||
gin_q = w.h.q8;
|
||||
@@ -1434,6 +1469,16 @@ inline int MoeQ::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
}
|
||||
}
|
||||
if (!gin_q || !gin_s || g.n_embd % gin_g) return RAD_E_INVAL;
|
||||
/* An E4M3 activation at another group than 128 (MXFP8's 32) is read by the MXFP4 GEMM alone,
|
||||
* which takes `a_group` 32 (libr4d's moe_gemm_mxfp4a8); the down projection's input likewise. */
|
||||
const int64_t dn_g = (a8 && !down_codebook_fp8) ? (int64_t)RAD_SCALE_GROUP : w.eff.group;
|
||||
if ((!a8 && gin_g != RAD_SCALE_GROUP && fmt[0] != 8) || (dn_g != RAD_SCALE_GROUP && fmt[1] != 8) ||
|
||||
(c.calib && (gin_g != RAD_SCALE_GROUP || dn_g != RAD_SCALE_GROUP))) {
|
||||
fprintf(stderr, "radiance: layer %d's routed activations are quantised at one scale a %lld "
|
||||
"(gate_up) and %lld (down) of K, which only MXFP4 experts read, outside "
|
||||
"calibration\n", l, (long long)gin_g, (long long)dn_g);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* A table op's weights in operand order: even experts' codes and scales, then odd experts'
|
||||
* (`w`, `w_scale`, `w_odd`, `w_odd_scale`), or at four classes classes 0 to 3. */
|
||||
auto tables = [&](const std::vector<rad_weight>& wc, const std::vector<rad_weight>& ws) {
|
||||
@@ -1466,7 +1511,7 @@ inline int MoeQ::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
RAD_STR("a_order", "token"), RAD_STR("dtype", edtype[0]),
|
||||
RAD_INT("N_odd", gu * wq[1]), RAD_INT("K_odd", g.n_embd),
|
||||
RAD_INT("parts", gu), RAD_INT("a_group", gin_g) };
|
||||
const int cut = a8 ? 0 : 1;
|
||||
const int cut = a8 || gin_g != RAD_SCALE_GROUP ? 0 : 1;
|
||||
rad_op h = ncls == 4
|
||||
? rad_decl_op(b, "moe_gemm_q_mod4", p4, (int)(sizeof p4 / sizeof *p4) - cut,
|
||||
tab.data(), (int)tab.size())
|
||||
@@ -1494,14 +1539,14 @@ inline int MoeQ::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
RAD_INT("N_1", g.n_embd), RAD_INT("K_1", wq[1]),
|
||||
RAD_INT("N_2", g.n_embd), RAD_INT("K_2", wq[2]),
|
||||
RAD_INT("N_3", g.n_embd), RAD_INT("K_3", wq[3]),
|
||||
RAD_INT("parts", 1), RAD_INT("a_group", RAD_SCALE_GROUP) };
|
||||
RAD_INT("parts", 1), RAD_INT("a_group", dn_g) };
|
||||
const RadParam p2[] = { RAD_RANGE("M", 1, c.rows), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", wq[0]), RAD_INT("n_expert", n_reg),
|
||||
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_SCALE_GROUP),
|
||||
RAD_STR("a_order", "sorted"), RAD_STR("dtype", edtype[1]),
|
||||
RAD_INT("N_odd", g.n_embd), RAD_INT("K_odd", wq[1]),
|
||||
RAD_INT("parts", 1), RAD_INT("a_group", RAD_SCALE_GROUP) };
|
||||
const int cut = a8 && !down_codebook_fp8 ? 0 : 1;
|
||||
RAD_INT("parts", 1), RAD_INT("a_group", dn_g) };
|
||||
const int cut = (a8 && !down_codebook_fp8) || dn_g != RAD_SCALE_GROUP ? 0 : 1;
|
||||
rad_op h = ncls == 4
|
||||
? rad_decl_op(b, "moe_gemm_q_mod4", p4, (int)(sizeof p4 / sizeof *p4) - cut,
|
||||
tab.data(), (int)tab.size())
|
||||
@@ -1559,7 +1604,7 @@ inline int MoeQ::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
for (int64_t j = 0; j < np; ++j) {
|
||||
const int64_t parts[2] = { wp, wp };
|
||||
w_pgu[(size_t)j] = decl_w_n(b, nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l,
|
||||
(long long)(c.expert_base + prot[(size_t)j])),
|
||||
gid(prot[(size_t)j])),
|
||||
RAD_BF16, {gu * wp, g.n_embd}, RAD_ACCESS_PER_TOKEN,
|
||||
psh_row, grp_layer(l), 0, parts, pparts);
|
||||
if (!w_pgu[(size_t)j]) return RAD_E_INVAL;
|
||||
@@ -1567,7 +1612,7 @@ inline int MoeQ::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
}
|
||||
for (int64_t j = 0; j < np; ++j) {
|
||||
w_pdn[(size_t)j] = decl_w(b, nm.f("blk.%d.ffn_down_exps.%lld.weight", l,
|
||||
(long long)(c.expert_base + prot[(size_t)j])),
|
||||
gid(prot[(size_t)j])),
|
||||
RAD_BF16, {g.n_embd, wp}, RAD_ACCESS_PER_TOKEN, psh_col,
|
||||
grp_layer(l));
|
||||
if (!w_pdn[(size_t)j]) return RAD_E_INVAL;
|
||||
@@ -1750,13 +1795,13 @@ inline int MoeQ::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
c.shared_lo, c.shared_hi));
|
||||
/* An int8 down projection fed the int8 pair reads no bf16 plane, so none is written. */
|
||||
gq_sh.fuse_clamped = c.swiglu_quant != 0;
|
||||
RAD_ARCH_TRY(gq_sh.declare(b, g, w.sgu, w.sff, c.n_ff_shared, "silu", c.rows,
|
||||
sh_down.reads_x && !(w.sff.q8_fed && sh_down.probed_i8), false,
|
||||
sh_limit, c.swiglu_step != 0));
|
||||
RAD_ARCH_TRY(gq_sh.declare(b, g, w.sgu, w.sff, c.n_ff_shared, c.situ ? "situ" : "silu",
|
||||
c.rows, sh_down.reads_x && !(w.sff.q8_fed && sh_down.probed_i8),
|
||||
false, sh_limit, c.swiglu_step != 0));
|
||||
/* An IQR gate_up between the rotated int8 trunk's fed pairs folds SwiGLU and the rotating
|
||||
* quantiser into its epilogue, to 16 rows: one launch a layer less than the pair, which
|
||||
* stays declared for longer steps, other encodings and a clamped product. */
|
||||
if (sh_limit <= 0 && sh_gate_up.iqr && w.h.q8_fed && w.h.q8_rot && w.sff.q8_fed &&
|
||||
if (sh_limit <= 0 && !c.situ && sh_gate_up.iqr && w.h.q8_fed && w.h.q8_rot && w.sff.q8_fed &&
|
||||
w.sff.q8_rot)
|
||||
op_sh_gated = decl_gated_fold_iqr(
|
||||
b, c.rows, sh_gate_up.N, sh_gate_up.K, sh_gate_up.w, sh_gate_up.ws,
|
||||
@@ -1913,7 +1958,7 @@ inline int MoeQ::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
{w.x, w.h.x}, {w.x});
|
||||
|
||||
/* The layer as the prefetch sees it, indexed by model expert number (what the router ranks). */
|
||||
if (!c.sigmoid_router && !act_bf16() && c.n_expert_all > 0 && n_reg > 0) {
|
||||
if (!c.sigmoid_router && !c.ext_router && !act_bf16() && c.n_expert_all > 0 && n_reg > 0) {
|
||||
const int64_t na = c.n_expert_all;
|
||||
xp_parts.assign((size_t)(na * 4), 0);
|
||||
xp_count_at.assign((size_t)na, -1);
|
||||
@@ -1937,112 +1982,112 @@ inline int MoeQ::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ---- EXL3 experts (expert_exl3): the radiance-exl3 extension's whole-expert ops over this rank's experts.
|
||||
/* ---- EXL3-V3 experts (expert_exl3i): plugin/exl3i's whole-expert ops over this rank's experts, the exl3i record
|
||||
* under the same op names AND the same schema as expert_exl3 (the rows apart by their constraints: the format's
|
||||
* rate in the dtype slot, codebook mad, a_rot = 0 -- a stock dtype value is refused by name).
|
||||
*
|
||||
* Every expert is whole on its rank (expert parallel, or one rank), so the ops run at their "tp1" geometry:
|
||||
* gate_up [2 n_ff, n_embd] and down [n_embd, n_ff] for every expert, in two parity tables (expert e at entry
|
||||
* e / 2 of class e % 2), as the extension's own architecture issues them at one rank. One run a plane --
|
||||
* gate_up's codes, suh, suh.1, svh; down's codes, suh, svh -- each declared as the even experts then the odd
|
||||
* ones, so a (plane, class) table is RAD_WTAB(run[q * ne / 2], ne / 2). gate_up reads the bf16 normed input
|
||||
* (one row per token), writes f16 h already rotated for down (h_rot 1, with down's suh run as its dn_suh
|
||||
* table), applies silu(gate) * up with the model's swiglu_limit (interface v8 `limit`); down reads h in the
|
||||
* scatter's order and writes the bf16 `edn` rows the gather sums. The prefill stager keys a layer on its first
|
||||
* declared expert op: gate_up, declared first. */
|
||||
inline int MoeQ::declare_exl3(RadBuilder* b, Names& nm, int l) {
|
||||
* Every expert is whole on its rank (expert parallel, or one rank): gate_up [2 n_ff, n_embd] and down [n_embd, n_ff]
|
||||
* for every expert, in two parity tables (expert e at entry e / 2 of class e % 2). One run a plane -- gate_up's
|
||||
* record, suh, suh.1, svh; down's record, suh, svh -- each declared as the even experts then the odd ones, so a
|
||||
* (plane, class) table is RAD_WTAB(run[q * ne / 2], ne / 2). gate_up reads the bf16 normed input (one row a token)
|
||||
* and writes f16 h already rotated for down (h_rot 1, with down's suh run as its dn_suh table); down reads h in
|
||||
* the scatter's order and writes the bf16 `edn` rows the gather sums. The silu(gate) * up and the swiglu_limit
|
||||
* clamp are the op's (the shared stock schema's `limit` slot, gate_up only). */
|
||||
inline int MoeQ::declare_exl3i(RadBuilder* b, Names& nm, int l) {
|
||||
const int64_t ne = c.n_expert;
|
||||
const bool ep = c.n_expert != c.n_expert_all;
|
||||
if (c.ff_hi[0] > 0 || c.ff_hi4[0] > 0 || (!ep && g.world > 1)) {
|
||||
fprintf(stderr, "radiance: layer %d's EXL3 experts are served whole on their rank (expert parallel, or "
|
||||
fprintf(stderr, "radiance: layer %d's EXL3-V3 experts are served whole on their rank (expert parallel, or "
|
||||
"one rank); this configuration slices every expert\n", l);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (!prot.empty() || c.calib || c.expert_rot || c.expert_w4) {
|
||||
fprintf(stderr, "radiance: layer %d: EXL3 experts take no protected bf16 experts, calibration tap or "
|
||||
fprintf(stderr, "radiance: layer %d: EXL3-V3 experts take no protected bf16 experts, calibration tap or "
|
||||
"rotated/four-bit form\n", l);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (ne < 2 || ne % 2) {
|
||||
fprintf(stderr, "radiance: layer %d holds %lld EXL3 experts on this rank; the ops take two equal "
|
||||
fprintf(stderr, "radiance: layer %d holds %lld EXL3-V3 experts on this rank; the ops take two equal "
|
||||
"parity tables\n", l, (long long)ne);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (!x3_dtype[0] || !x3_dtype[1] || std::strcmp(x3_cb[0], x3_cb[1]) != 0) {
|
||||
fprintf(stderr, "radiance: layer %d's EXL3 experts: encodings unknown (no model behind the builder) or "
|
||||
if (!xi_m[0] || !xi_m[1] || std::strcmp(xi_cb[0], xi_cb[1]) != 0) {
|
||||
fprintf(stderr, "radiance: layer %d's EXL3-V3 experts: encodings unknown (no model behind the builder) or "
|
||||
"gate_up and down in different codebooks\n", l);
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
if (g.n_embd % EXL3_HAD || c.n_ff_exp % EXL3_HAD || (2 * c.n_ff_exp) % 256) return RAD_E_SHAPE;
|
||||
if (g.n_embd % 128 || c.n_ff_exp % 128) return RAD_E_SHAPE;
|
||||
const int64_t half = ne / 2, D = g.n_embd, F = c.n_ff_exp;
|
||||
static const char* const gu_role[4] = { "codes", "suh", "suh.1", "svh" };
|
||||
static const char* const dn_role[3] = { "codes", "suh", "svh" };
|
||||
static const char* const gu_role[4] = { "record", "suh", "suh.1", "svh" };
|
||||
static const char* const dn_role[3] = { "record", "suh", "svh" };
|
||||
for (int proj = 0; proj < 2; ++proj) {
|
||||
const int np = proj == 0 ? 4 : 3;
|
||||
const char* stem = proj == 0 ? "ffn_gate_up_exps" : "ffn_down_exps";
|
||||
const int64_t R = proj == 0 ? 2 * F : D, C = proj == 0 ? D : F;
|
||||
for (int p = 0; p < np; ++p) {
|
||||
const char* role = proj == 0 ? gu_role[p] : dn_role[p];
|
||||
const bool codes = p == 0, per_row = std::strcmp(role, "svh") == 0, per_col = !codes && !per_row;
|
||||
const int64_t rows = per_col ? 1 : R;
|
||||
const int64_t cols = per_row ? 1 : codes ? C / x3_cpe[proj] : C;
|
||||
std::vector<rad_weight>& run = proj == 0 ? x3_gu[p] : x3_dn[p];
|
||||
const bool rec = p == 0, per_row = std::strcmp(role, "svh") == 0;
|
||||
const int64_t rows = rec ? R / 16 : per_row ? R : 1;
|
||||
const int64_t cols = rec ? exl3i_row_words(C, xi_m[proj]) : per_row ? 1 : C;
|
||||
std::vector<rad_weight>& run = proj == 0 ? xi_gu[p] : xi_dn[p];
|
||||
run.clear();
|
||||
run.reserve((size_t)ne);
|
||||
for (int q = 0; q < 2; ++q)
|
||||
for (int64_t e = q; e < ne; e += 2) {
|
||||
const long long ge = (long long)(c.expert_base + e);
|
||||
const char* weight = nm.f("blk.%d.%s.%lld.weight", l, stem, ge);
|
||||
/* the weight the planes are views OF answers the encoding; the view's own name carries the role */
|
||||
const std::string weight = nm.f("blk.%d.%s.%lld.weight", l, stem, ge);
|
||||
const rad_weight h =
|
||||
decl_view(b, codes ? weight : nm.f("blk.%d.%s.%lld.%s", l, stem, ge, role),
|
||||
codes ? nullptr : weight, role, codes ? x3_cdt[proj] : (uint32_t)RAD_F16,
|
||||
{rows, cols}, RAD_ACCESS_CONDITIONAL, RAD_SHARD_NONE,
|
||||
grp_expert_slot(l, (int)e, proj));
|
||||
decl_view(b, nm.f("blk.%d.%s.%lld.weight.%s", l, stem, ge, role), weight.c_str(), role,
|
||||
rec ? (uint32_t)RAD_U32 : (uint32_t)RAD_F16, {rows, cols},
|
||||
RAD_ACCESS_CONDITIONAL, RAD_SHARD_NONE, grp_expert_slot(l, (int)e, proj));
|
||||
if (!h) return RAD_E_INVAL;
|
||||
run.push_back(h);
|
||||
}
|
||||
}
|
||||
}
|
||||
b_x3h = decl_b(b, nm.f("blk.%d.moe_exl3_h", l), RAD_F16, {c.rows * c.top_k, F});
|
||||
b_xih = decl_b(b, nm.f("blk.%d.moe_exl3i_h", l), RAD_F16, {c.rows * c.top_k, F});
|
||||
/* the weights in each op's table-operand order: class 0's tables, then class 1's */
|
||||
std::vector<rad_weight> tab;
|
||||
const auto tables = [&](bool gate_up) {
|
||||
tab.clear();
|
||||
for (int q = 0; q < 2; ++q)
|
||||
for (int t = 0; t < (gate_up ? 5 : 3); ++t) {
|
||||
const std::vector<rad_weight>& run = gate_up ? (t < 4 ? x3_gu[t] : x3_dn[1]) : x3_dn[t];
|
||||
const std::vector<rad_weight>& run = gate_up ? (t < 4 ? xi_gu[t] : xi_dn[1]) : xi_dn[t];
|
||||
for (int64_t i = 0; i < half; ++i) tab.push_back(run[(size_t)(q * half + i)]);
|
||||
}
|
||||
};
|
||||
tables(true);
|
||||
std::vector<RadParam> gp = { RAD_RANGE("M", 1, c.rows), RAD_INT("N", 2 * F), RAD_INT("K", D),
|
||||
RAD_INT("n_expert", ne), RAD_INT("top_k", c.top_k),
|
||||
RAD_STR("dtype", x3_dtype[0]), RAD_STR("codebook", x3_cb[0]),
|
||||
RAD_STR("dtype", xi_rate[0]), RAD_STR("codebook", xi_cb[0]),
|
||||
RAD_INT("N_odd", 2 * F), RAD_INT("K_odd", D), RAD_INT("h_rot", 1),
|
||||
RAD_INT("a_rot", 0) };
|
||||
if (c.swiglu_limit > 0) gp.push_back(RAD_F64("limit", c.swiglu_limit));
|
||||
op_gu = rw(b, rad_decl_op(b, "moe_exl3_gate_up", gp.data(), (int)gp.size(), tab.data(), (int)tab.size()),
|
||||
{w.h.x, w.sorted, w.eoff}, {b_x3h});
|
||||
op_gu = rw(b, rad_decl_op(b, EXL3I_OP_MOE_GU, gp.data(), (int)gp.size(), tab.data(), (int)tab.size()),
|
||||
{w.h.x, w.sorted, w.eoff}, {b_xih});
|
||||
tables(false);
|
||||
std::vector<RadParam> dp = { RAD_RANGE("M", 1, c.rows), RAD_INT("N", D), RAD_INT("K", F),
|
||||
RAD_INT("n_expert", ne), RAD_INT("top_k", c.top_k),
|
||||
RAD_STR("dtype", x3_dtype[1]), RAD_STR("codebook", x3_cb[1]),
|
||||
RAD_STR("dtype", xi_rate[1]), RAD_STR("codebook", xi_cb[1]),
|
||||
RAD_INT("N_odd", D), RAD_INT("K_odd", F), RAD_INT("h_rot", 1) };
|
||||
op_dn = rw(b, rad_decl_op(b, "moe_exl3_down", dp.data(), (int)dp.size(), tab.data(), (int)tab.size()),
|
||||
{b_x3h, w.sorted, w.eoff}, {w.edn});
|
||||
op_dn = rw(b, rad_decl_op(b, EXL3I_OP_MOE_DN, dp.data(), (int)dp.size(), tab.data(), (int)tab.size()),
|
||||
{b_xih, w.sorted, w.eoff}, {w.edn});
|
||||
if (!op_gu || !op_dn) return RAD_E_INVAL;
|
||||
rad_note(b, "layer %d: EXL3 experts gate_up %s / down %s (%s), %lld a rank, swiglu limit %g", l,
|
||||
x3_dtype[0], x3_dtype[1], x3_cb[0], (long long)ne, c.swiglu_limit);
|
||||
rad_note(b, "layer %d: EXL3-V3 experts gate_up k%s / down k%s (%s), %lld a rank, swiglu limit %g", l,
|
||||
xi_rate[0], xi_rate[1], xi_cb[0], (long long)ne, c.swiglu_limit);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* One EXL3 op over this rank's tables, each operand where exl3_positions() puts it. */
|
||||
inline void MoeQ::issue_exl3(RadCtx* c_, rad_op op_h, int op, int64_t rows, RadOperand in,
|
||||
/* One EXL3-V3 op over this rank's tables, each operand where exl3i_moe_positions() puts it. */
|
||||
inline void MoeQ::issue_exl3i(RadCtx* c_, rad_op op_h, int op, int64_t rows, RadOperand in,
|
||||
RadOperand out) const {
|
||||
const Exl3Positions& at = *exl3_positions(op);
|
||||
static const int slot_gu[5] = { EXL3_P_CODES, EXL3_P_SUH, EXL3_P_SUH1, EXL3_P_SVH, EXL3_P_DN_SUH };
|
||||
static const int slot_dn[3] = { EXL3_P_CODES, EXL3_P_SUH, EXL3_P_SVH };
|
||||
const bool gate_up = op == EXL3_GATE_UP;
|
||||
const Exl3iMoePos& at = *exl3i_moe_positions(op);
|
||||
static const int slot_gu[5] = { EXL3I_MP_RECORD, EXL3I_MP_SUH, EXL3I_MP_SUH1, EXL3I_MP_SVH, EXL3I_MP_DN_SUH };
|
||||
static const int slot_dn[3] = { EXL3I_MP_RECORD, EXL3I_MP_SUH, EXL3I_MP_SVH };
|
||||
const bool gate_up = op == EXL3I_MOE_GATE_UP;
|
||||
const int64_t ne = c.n_expert, half = ne / 2, k = c.top_k;
|
||||
RadOperand opd[16];
|
||||
RadOperand opd[EXL3I_GU_N_OPD];
|
||||
for (RadOperand& o : opd) o = RAD_NONE;
|
||||
opd[at.x] = in;
|
||||
opd[at.sorted] = brows(w.sorted, rows * k);
|
||||
@@ -2050,7 +2095,7 @@ inline void MoeQ::issue_exl3(RadCtx* c_, rad_op op_h, int op, int64_t rows, RadO
|
||||
opd[at.y] = out;
|
||||
for (int q = 0; q < 2; ++q)
|
||||
for (int t = 0; t < (gate_up ? 5 : 3); ++t) {
|
||||
const std::vector<rad_weight>& run = gate_up ? (t < 4 ? x3_gu[t] : x3_dn[1]) : x3_dn[t];
|
||||
const std::vector<rad_weight>& run = gate_up ? (t < 4 ? xi_gu[t] : xi_dn[1]) : xi_dn[t];
|
||||
opd[at.plane[q][gate_up ? slot_gu[t] : slot_dn[t]]] = RAD_WTAB(run[(size_t)(q * half)], half);
|
||||
}
|
||||
rad_issue(c_, op_h, opd, at.n_opd, rows);
|
||||
@@ -2135,6 +2180,8 @@ inline void MoeQ::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool own
|
||||
glm_router.step_masked(c_, r0, rows, r0, praw(vl_mask_ + r0, RAD_I32, rows));
|
||||
else
|
||||
glm_router.step(c_, r0, rows, r0);
|
||||
} else if (c.ext_router) {
|
||||
/* the caller wrote ids and ew for the whole step */
|
||||
} else if (rfused)
|
||||
RAD_ISSUE_N(c_, op_router_fused, rows, brow_slice(w.h.x, r0, rows, g.n_embd),
|
||||
RAD_W(w_router), router_fused_gate ? RAD_W(w_sgate) : RAD_NONE,
|
||||
@@ -2153,7 +2200,7 @@ inline void MoeQ::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool own
|
||||
brow_slice(w.ids, r0, rows, k), brow_slice(w.ew, r0, rows, k),
|
||||
brows(w.sorted, rows * k), brows(w.eoff, ne + 1), ecnt);
|
||||
} else {
|
||||
if (!c.sigmoid_router)
|
||||
if (!c.sigmoid_router && !c.ext_router)
|
||||
RAD_ISSUE_N(c_, op_topk, rows, brow_slice(w.logits, r0, rows, ne_all),
|
||||
brow_slice(w.ids, r0, rows, k), brow_slice(w.ew, r0, rows, k));
|
||||
if (scatter_inv)
|
||||
@@ -2192,9 +2239,9 @@ inline void MoeQ::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool own
|
||||
/* Apply the previous layer's prefetch prediction: substitute the copied experts into the
|
||||
* tables. */
|
||||
(void)rad_expert_prefetch_step(c_, layer);
|
||||
if (c.expert_exl3)
|
||||
issue_exl3(c_, op_gu, EXL3_GATE_UP, rows, brow_slice(w.h.x, r0, rows, g.n_embd),
|
||||
brows(b_x3h, rows * k));
|
||||
if (c.expert_exl3i)
|
||||
issue_exl3i(c_, op_gu, EXL3I_MOE_GATE_UP, rows, brow_slice(w.h.x, r0, rows, g.n_embd),
|
||||
brows(b_xih, rows * k));
|
||||
else if (act_bf16())
|
||||
RAD_ISSUE_N(c_, op_gu, rows, brow_slice(w.h.x, r0, rows, g.n_embd),
|
||||
RAD_WTAB(w_gu[0], ne), brows(w.sorted, rows * k), brows(w.eoff, ne + 1),
|
||||
@@ -2226,7 +2273,7 @@ inline void MoeQ::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool own
|
||||
shared_up(c_, T, r0, rows,
|
||||
(rfused && router_fused_gate) || (sfused && sigmoid_scatter_gate));
|
||||
if (beside && beside->fn && r0 == 0) beside->fn(c_, beside->arg);
|
||||
if (!c.expert_exl3) gq_exp.step(c_, w.egu, rows * k, 0, rows * k); /* EXL3: inside gate_up */
|
||||
if (!c.expert_exl3i) gq_exp.step(c_, w.egu, rows * k, 0, rows * k); /* EXL3-V3: inside gate_up */
|
||||
if (shared && !(op_sh_gated && rows <= sh_gated_rows)) gq_sh.step(c_, w.sgu, T, r0, rows);
|
||||
/* The shared arm's down projection in front of the routed down GEMM on a step of
|
||||
* [sh_down_first_lo, sh_down_first_hi] rows. Behind it (below) the two still run together,
|
||||
@@ -2241,8 +2288,8 @@ inline void MoeQ::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool own
|
||||
* coupling, chain 1 / 2 / 3 (two / three / four rows): -0.28% / -0.21% / -0.25% a step. */
|
||||
const bool sh_dn_first = shared && T >= sh_down_first_lo && T <= sh_down_first_hi;
|
||||
if (sh_dn_first) sh_down.step(c_, w.sff, w.sout, T, r0, rows);
|
||||
if (c.expert_exl3)
|
||||
issue_exl3(c_, op_dn, EXL3_DOWN, rows, brows(b_x3h, rows * k), brows(w.edn, rows * k));
|
||||
if (c.expert_exl3i)
|
||||
issue_exl3i(c_, op_dn, EXL3I_MOE_DOWN, rows, brows(b_xih, rows * k), brows(w.edn, rows * k));
|
||||
else if (act_bf16())
|
||||
RAD_ISSUE_N(c_, op_dn, rows, brows(w.eff.x, rows * k), RAD_WTAB(w_dn[0], ne),
|
||||
brows(w.sorted, rows * k), brows(w.eoff, ne + 1), brows(w.edn, rows * k));
|
||||
@@ -2458,7 +2505,7 @@ inline void MoeQ::route_report(RadCtx* c_) const {
|
||||
* Copying w.ecnt into the row (the pointers now differ) also feeds the heat engine real
|
||||
* histograms instead of the zeros it saw before. With a routing table (Wire::ecnt_pitch) the
|
||||
* router did write the core's row, as a declared operand, and the report copies nothing. */
|
||||
moe_debug_weights(c_, layer, c.top_k, w.ids, w.ew, c.sigmoid_router != 0);
|
||||
moe_debug_weights(c_, layer, c.top_k, w.ids, w.ew, c.sigmoid_router != 0 || c.ext_router != 0);
|
||||
RadRouting r{};
|
||||
r.expert_ids = (const int32_t*)rad_buf_ptr(c_, w.ids);
|
||||
r.expert_w = nullptr;
|
||||
|
||||
@@ -82,13 +82,14 @@ 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, const char* prefix = "model.visual");
|
||||
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, const char* prefix) {
|
||||
bool gate_weights, const char* prefix, bool export_aux) {
|
||||
on = false;
|
||||
if (!present(m) || ctx->max_enc_patches <= 0) return RAD_OK;
|
||||
|
||||
@@ -323,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;
|
||||
}
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
* opener, before <|content_text|> (content_open) the answer's header, and both are dropped there;
|
||||
* before anything else it opens a call, so it is also name_prefix. The envelope is
|
||||
* object_args_key "args". With reasoning_anywhere a block the template interleaves later is
|
||||
* reasoning too, and the answer's own <|end_message|>, a close with no block open, is not part of
|
||||
* the answer.
|
||||
* 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,
|
||||
@@ -41,6 +41,7 @@ inline const RadChatFormat* inkling2_chat_format() {
|
||||
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|>";
|
||||
|
||||
+214
-13
@@ -48,7 +48,14 @@ inline int64_t scale_groups(int64_t n) { return (n + RAD_SCALE_GROUP - 1) / RAD_
|
||||
struct ActQ {
|
||||
rad_buf x = 0; /* [max_tok, n] bf16 */
|
||||
rad_buf q = 0; /* [max_tok, n] e4m3 */
|
||||
rad_buf s = 0; /* [max_tok, ceil(n/block)] f32 */
|
||||
rad_buf s = 0; /* [max_tok, ceil(n/group)] f32 */
|
||||
/* The E4M3 pair's scale group: RAD_SCALE_GROUP (128), or 32 for an MXFP8 activation
|
||||
* (ERNIE-5.5's routed experts, whose grouped MXFP4 GEMM reads `a_group` 32). Set before
|
||||
* declare_qs; every producer and consumer of the pair takes it from cg(). */
|
||||
int64_t group = RAD_SCALE_GROUP;
|
||||
/* Power-of-two scales, ceil(log2(amax / 448)) (`quant_act_fp8`'s `ue8m0`), for MXFP8
|
||||
* per-32 expert activations. */
|
||||
bool ue8m0 = false;
|
||||
/* Int8 codes of the same activation, for an int8 linear (LinearQ::i8): [max_tok, n] i8 and
|
||||
* an f32 scale per (row, block). Declared only for an int8 trunk (declare_qs's `i8`); written
|
||||
* by the linear's own quant_act_i8g from `x`, or by the producer when `q8_fed`. */
|
||||
@@ -71,7 +78,7 @@ struct ActQ {
|
||||
rad_buf cq() const { return q8_fed ? q8 : q; }
|
||||
rad_buf cs() const { return q8_fed ? s8 : s; }
|
||||
/* The scale group of cs(). */
|
||||
int64_t cg() const { return q8_fed ? g8 : (int64_t)RAD_SCALE_GROUP; }
|
||||
int64_t cg() const { return q8_fed ? g8 : group; }
|
||||
|
||||
/* Declares the codes: the E4M3 pair with `fp8_pair`, the int8 pair with `i8` (an int8 model's
|
||||
* activations need no E4M3 plane taking arena); `x` is set by the caller.
|
||||
@@ -88,8 +95,9 @@ struct ActQ {
|
||||
if (g.w_bf16) { q = s = q8 = s8 = 0; return RAD_OK; }
|
||||
const int64_t m = rows > 0 ? rows : g.max_tok;
|
||||
if (fp8_pair) {
|
||||
if (group <= 0) return RAD_E_INVAL;
|
||||
q = decl_b(b, nm.f("%s.q", name), RAD_F8E4M3, { m, n });
|
||||
s = decl_b(b, nm.f("%s.s", name), RAD_F32, { m, scale_groups(n) });
|
||||
s = decl_b(b, nm.f("%s.s", name), RAD_F32, { m, (n + group - 1) / group });
|
||||
if (!q || !s) return RAD_E_INVAL;
|
||||
}
|
||||
if (i8) {
|
||||
@@ -119,8 +127,65 @@ struct ActQ {
|
||||
return declare_qs(b, nm, g, name, n, rows, i8, !q8_fed,
|
||||
i8 ? i8_group : (int64_t)RAD_SCALE_GROUP);
|
||||
}
|
||||
|
||||
/* ERNIE-5.5 trunk inputs: rotated int8 pair for IQ8R (g.i8_group), or ue8m0 E4M3 pair for a
|
||||
* block-FP8 trunk (g.native_fp). */
|
||||
int declare_trunk(RadBuilder* b, Names& nm, const Geom& g, const char* name, int64_t n,
|
||||
int64_t rows = 0) {
|
||||
if (!g.i8_group) {
|
||||
if (!g.native_fp) {
|
||||
fprintf(stderr, "radiance: ernie55 requires an IQ8R or block-FP8 trunk "
|
||||
"(Geom::i8_group and native_fp both unset for '%s')\n", name);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
ue8m0 = true;
|
||||
return declare_qs(b, nm, g, name, n, rows);
|
||||
}
|
||||
ue8m0 = false;
|
||||
if (!rad_op_declared(b, "had_quant_act_i8g")) {
|
||||
fprintf(stderr, "radiance: this container's trunk is IQ8R, which needs the int8 "
|
||||
"activation quantiser had_quant_act_i8g, and no loaded library "
|
||||
"declares it\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
return declare_pair(b, nm, g, name, n, rows, true, g.i8_group, "had_quant_act_i8g");
|
||||
}
|
||||
/* A trunk input a linear quantises itself from its bf16 plane (the product of a SiTU gate). */
|
||||
int declare_trunk_self(RadBuilder* b, Names& nm, const Geom& g, const char* name, int64_t n,
|
||||
int64_t rows = 0) {
|
||||
if (!g.i8_group) {
|
||||
if (!g.native_fp) return RAD_E_UNSUPPORTED;
|
||||
ue8m0 = true;
|
||||
return declare_qs(b, nm, g, name, n, rows);
|
||||
}
|
||||
ue8m0 = false;
|
||||
return declare_qs(b, nm, g, name, n, rows, true, false, g.i8_group);
|
||||
}
|
||||
};
|
||||
|
||||
/* Standalone activation quantiser with optional ue8m0 power-of-two scaling (for MXFP8 per-32
|
||||
* expert inputs). */
|
||||
inline rad_op decl_quant_act_ex(RadBuilder* b, const char* op, int64_t rows, int64_t n,
|
||||
int64_t group, const char* dtype, bool ue8m0, rad_buf x,
|
||||
rad_buf q, rad_buf s) {
|
||||
if (ue8m0 && std::strcmp(op, "quant_act_fp8") != 0) {
|
||||
fprintf(stderr, "radiance: '%s' has no ue8m0 form\n", op);
|
||||
return 0;
|
||||
}
|
||||
const RadParam ps[5] = { RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_INT("group", group),
|
||||
RAD_STR("dtype", dtype), RAD_INT("ue8m0", 1) };
|
||||
return rw(b, rad_decl_op(b, op, ps, ue8m0 ? 5 : 4, RAD_NOWEIGHTS), { x }, { q, s });
|
||||
}
|
||||
|
||||
/* ERNIE-5.5 standalone trunk quantiser over `a.x` (rotated int8 or ue8m0 E4M3). */
|
||||
inline rad_op decl_trunk_quant(RadBuilder* b, int64_t rows, int64_t n, const ActQ& a) {
|
||||
return a.q8_fed
|
||||
? decl_quant_act_ex(b, "had_quant_act_i8g", rows, n, a.cg(), "bf16", false, a.x,
|
||||
a.cq(), a.cs())
|
||||
: decl_quant_act_ex(b, "quant_act_fp8", rows, n, a.cg(), "bf16", a.ue8m0, a.x,
|
||||
a.cq(), a.cs());
|
||||
}
|
||||
|
||||
/* The fused attention prologue's row band, shared by the block issuing it, the rope table fill,
|
||||
* the QSA indexer reading that table, and the step deciding whether to fill it.
|
||||
*
|
||||
@@ -158,15 +223,13 @@ inline int QuantAct::declare(RadBuilder* b, const Geom& g, const ActQ& act, int6
|
||||
/* Nothing to quantise for a bf16 model: no op, and step() issues nothing. */
|
||||
if (g.w_bf16) { op = 0; return a.x ? RAD_OK : RAD_E_INVAL; }
|
||||
if (!a.x || !a.cq() || !a.cs() || n <= 0) return RAD_E_INVAL;
|
||||
if (a.ue8m0 && a.q8_fed) return RAD_E_UNSUPPORTED;
|
||||
/* `dtype` is the input's (bf16); the op name gives the output format. An input fed at int8
|
||||
* codes is quantised by quant_act_i8g into its int8 pair, or by had_quant_act_i8g where they
|
||||
* are rotated (ActQ::q8_rot). */
|
||||
op = rw(b, RAD_OP(b, a.q8_fed ? (a.q8_rot ? "had_quant_act_i8g" : "quant_act_i8g") : "quant_act_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", n),
|
||||
RAD_INT("group", a.cg()), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ a.x }, { a.cq(), a.cs() });
|
||||
return RAD_OK;
|
||||
const char* qop = a.q8_fed ? (a.q8_rot ? "had_quant_act_i8g" : "quant_act_i8g") : "quant_act_fp8";
|
||||
op = decl_quant_act_ex(b, qop, g.max_tok, n, a.cg(), g.dtype, a.ue8m0, a.x, a.cq(), a.cs());
|
||||
return op ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
inline void QuantAct::step(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const {
|
||||
@@ -401,6 +464,7 @@ struct NormQuant {
|
||||
rad_op op_arn6 = 0;
|
||||
/* The ops write had_quant_act_i8g's rotated int8 codes into the int8 pair (ActQ::q8_rot). */
|
||||
bool hi8 = false;
|
||||
bool plain = false; /* a consumer keeps BF16 or quantizes its own rows */
|
||||
Geom gm{};
|
||||
/* The row width, for turning a row slice into element offsets. */
|
||||
int64_t n = 0;
|
||||
@@ -430,6 +494,19 @@ inline int NormQuant::declare(RadBuilder* b, const Geom& g, rad_weight gain, rad
|
||||
res = residual;
|
||||
gm = g;
|
||||
this->n = n; /* the parameter shadows the member; the member is the pitch */
|
||||
plain = !a.cq() && !a.cs();
|
||||
if (plain) {
|
||||
/* No implicit residual or collective is lost: callers using this path
|
||||
* must complete those junctions explicitly. */
|
||||
if (!src || !a.x || !w || n <= 0 || residual || fuse_ar != kArNone)
|
||||
return RAD_E_INVAL;
|
||||
op = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, max_rows > 0 ? max_rows : g.max_tok),
|
||||
RAD_INT("n", n), RAD_F64("eps", g.eps),
|
||||
RAD_F64("wadd", g.wadd), RAD_STR("dtype", g.dtype)), RAD_WEIGHTS(w)),
|
||||
{src}, {a.x});
|
||||
return op ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
/* bf16 models of this family take block inputs from hc_read and declare no block norm; a
|
||||
* pre-norm bf16 model uses the bf16 blocks. */
|
||||
if (g.w_bf16) {
|
||||
@@ -437,6 +514,10 @@ inline int NormQuant::declare(RadBuilder* b, const Geom& g, rad_weight gain, rad
|
||||
"linears are bf16; its blocks take a prepared input instead\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (a.ue8m0) {
|
||||
fprintf(stderr, "radiance: rmsnorm_quant_fp8 has no ue8m0 form\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* Rotated int8 codes (ActQ::q8_rot) come from the `_had_quant_i8g` twins, into the int8
|
||||
* pair; the model checked they are declared before feeding. Otherwise E4M3, as always. */
|
||||
hi8 = a.q8_fed && a.q8_rot;
|
||||
@@ -499,6 +580,12 @@ inline int NormQuant::declare(RadBuilder* b, const Geom& g, rad_weight gain, rad
|
||||
/* step() below with the plain op, whatever the wire. */
|
||||
inline void NormQuant::step_plain(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const {
|
||||
if (rows <= 0) rows = T - r0;
|
||||
if (plain) {
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(src, r0, rows, n), RAD_W(w),
|
||||
brow_slice(a.x, r0, rows, n));
|
||||
return;
|
||||
}
|
||||
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(src, r0, rows, n),
|
||||
res ? brow_slice(res, r0, rows, n) : RAD_NONE, RAD_W(w),
|
||||
brow_slice(a.q, r0, rows, n),
|
||||
@@ -512,6 +599,12 @@ inline void NormQuant::step_plain(RadCtx* c, int64_t T, int64_t r0, int64_t rows
|
||||
* different summation order would run. */
|
||||
inline void NormQuant::step(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const {
|
||||
if (rows <= 0) rows = T - r0;
|
||||
if (plain) {
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(src, r0, rows, n), RAD_W(w),
|
||||
brow_slice(a.x, r0, rows, n));
|
||||
return;
|
||||
}
|
||||
|
||||
RAD_ISSUE_N(c, pick(rows), rows, brow_slice(src, r0, rows, n),
|
||||
res ? brow_slice(res, r0, rows, n) : RAD_NONE, RAD_W(w),
|
||||
brow_slice(hi8 ? a.q8 : a.q, r0, rows, n),
|
||||
@@ -556,6 +649,12 @@ struct GateQuant {
|
||||
* quantises its input itself (an int8 linear's op_q). */
|
||||
bool silu_only = false;
|
||||
|
||||
/* act "situ" (ERNIE-5.5's SituAndMul): `op` is situ_mul over [gate|up] into the bf16 plane,
|
||||
* and when not bf16/silu_only, `op_q` is quant_act_fp8 over it at the pair's group (and ue8m0
|
||||
* for MXFP8 per-32 expert inputs). The constants are set before declare. */
|
||||
bool situ = false;
|
||||
double situ_beta = 4.0, situ_linear_beta = 25.0;
|
||||
|
||||
/* `step`: with `limit`, clip after the SiLU (`swiglu_step`, Ling-3.0) rather than before it
|
||||
* (`swiglu_clamped`, GLM-5.3). It has no fused quantiser, so the pair runs. */
|
||||
int declare(RadBuilder* b, const Geom& g, rad_buf gate_up, const ActQ& act, int64_t n,
|
||||
@@ -581,6 +680,30 @@ inline int GateQuant::declare(RadBuilder* b, const Geom& g, rad_buf gate_up, con
|
||||
clamped_fused = false;
|
||||
if (!std::isfinite(limit) || limit < 0) return RAD_E_INVAL;
|
||||
ungated = std::strcmp(act_name, "relu2") == 0;
|
||||
situ = std::strcmp(act_name, "situ") == 0;
|
||||
if (situ) {
|
||||
if (!gate_up || !a.x || n <= 0 || clipped || rot || a.q8_fed ||
|
||||
!(situ_beta > 0) || !(situ_linear_beta > 0) || (!bf16 && (!a.q || !a.s))) {
|
||||
fprintf(stderr, "radiance: a SiTU gate is situ_mul over [gate|up] into the bf16 plane, "
|
||||
"then quant_act_fp8 into an E4M3 pair; unclamped, unrotated, positive "
|
||||
"betas\n");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const int64_t rows = max_rows > 0 ? max_rows : g.max_tok;
|
||||
want_x = true;
|
||||
op = rw(b, RAD_OP(b, "situ_mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_F64("gate_cap", situ_beta), RAD_F64("up_cap", situ_linear_beta),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ gate_up }, { a.x });
|
||||
op_q = 0;
|
||||
if (!op) return RAD_E_INVAL;
|
||||
if (bf16) return RAD_OK;
|
||||
op_q = decl_quant_act_ex(b, "quant_act_fp8", rows, n, a.cg(), g.dtype, a.ue8m0, a.x,
|
||||
a.q, a.s);
|
||||
return op_q ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
if (ungated) {
|
||||
if (!gate_up || !a.x || n <= 0 || clipped || (!bf16 && (!a.cq() || !a.cs())) ||
|
||||
(rot && a.q8_fed))
|
||||
@@ -685,6 +808,10 @@ inline int GateQuant::declare(RadBuilder* b, const Geom& g, rad_buf gate_up, con
|
||||
{ gate_up }, { a.x });
|
||||
return op ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
if (a.ue8m0) {
|
||||
fprintf(stderr, "radiance: fused gated quantisers have no ue8m0 form\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (!gate_up || !a.x || !a.cq() || !a.cs() || n <= 0) return RAD_E_INVAL;
|
||||
/* Rotated codes feed a four-bit expert, which reads E4M3 only. */
|
||||
if (rot && a.q8_fed) return RAD_E_INVAL;
|
||||
@@ -803,6 +930,10 @@ struct LinearQ {
|
||||
* activation like `bf16`: the type's name, and the values one block covers along K. */
|
||||
const char* ggml = nullptr;
|
||||
int64_t ggml_block = 0;
|
||||
/* Symmetric INT4/INT8 with F16 group scales, like the dense Gemma W4A8 grid.
|
||||
* Its WMMA activation order and one F32 scale per row differ from i8a8h. */
|
||||
bool row_i8 = false;
|
||||
rad_buf row_q = 0, row_scale = 0;
|
||||
/* Block-fp8 weight whose scale plane is f32 rather than bf16 (GLM's checkpoints), read by
|
||||
* `gemm_nt_q` at dtype fp8a8f32. Read from the weight's encoding. */
|
||||
bool f32_scale = false;
|
||||
@@ -931,6 +1062,14 @@ inline int map_linear(RadBuilder* b, const char* wn, std::initializer_list<const
|
||||
|
||||
/* The int8 weight LinearQ serves at i8a8: i8 codes, a bf16 scale per [1 x 128], no transform or
|
||||
* other plane (libr4d's i8 block layout hook). */
|
||||
inline bool linear_is_row_i8(const RadEncoding& e) {
|
||||
const auto* scale = rad_enc_plane(&e, "scale");
|
||||
return rad_enc_is(&e, "affine") && e.n_planes == 2 && !e.transform[0] &&
|
||||
(e.plane[0].dtype == RAD_I4 || e.plane[0].dtype == RAD_I8) &&
|
||||
e.plane[0].block[1] == 1 && scale && scale->dtype == RAD_F16 &&
|
||||
scale->block[0] == 1 && scale->block[1] == RAD_SCALE_GROUP;
|
||||
}
|
||||
|
||||
inline bool linear_is_w8(const RadEncoding& e) {
|
||||
if (!rad_enc_is(&e, "affine") || e.n_planes != 2 || e.transform[0]) return false;
|
||||
const RadEncPlane* sc = rad_enc_plane(&e, "scale");
|
||||
@@ -1251,7 +1390,7 @@ inline int LinearQ::probe(RadBuilder* b, Names& nm, const Geom& g, const char* b
|
||||
/* llama.cpp's blocks are read against the bf16 plane, as a bf16 weight is. */
|
||||
const bool blocks = known && ggml_type_of(enc);
|
||||
reads_x = g.w_bf16 || plain || view || probed_i8 || blocks ||
|
||||
(known && linear_is_w4(enc));
|
||||
(known && (linear_is_w4(enc) || linear_is_row_i8(enc)));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -1326,7 +1465,9 @@ inline int LinearQ::declare(RadBuilder* b, Names& nm, const Geom& g, const char*
|
||||
}
|
||||
|
||||
if (known && !plain)
|
||||
if (const char* gone = linear_retired(enc)) return linear_refuse_retired(sw, gone);
|
||||
if (const char* gone = linear_retired(enc);
|
||||
gone && !(g.native_fp && std::strcmp(gone, "block fp8") == 0))
|
||||
return linear_refuse_retired(sw, gone);
|
||||
|
||||
/* ---- bf16 weight, `gemm_nt` over `a.x`: every linear of a bf16 model, or one a quantised
|
||||
* container keeps at checkpoint precision (e.g. the QSA indexer's projection, whose top-k is a
|
||||
@@ -1376,6 +1517,37 @@ inline int LinearQ::declare(RadBuilder* b, Names& nm, const Geom& g, const char*
|
||||
return op ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
if (known && linear_is_row_i8(enc)) {
|
||||
if (stored || !a.x || N % 16 || K % RAD_SCALE_GROUP) return RAD_E_INVAL;
|
||||
RowParts parts;
|
||||
RAD_ARCH_TRY(parts.set(row_parts, 16, 1, base, "weight rows"));
|
||||
w = decl_view(b, wn, nullptr, "codes", enc.plane[0].dtype, {N, K},
|
||||
access, shard, grp, parts.w, parts.n);
|
||||
ws = decl_view(b, nm.f("%s.scale", base), wn, "scale", RAD_F16,
|
||||
{N, K / RAD_SCALE_GROUP}, access, shard, grp, parts.w, parts.n);
|
||||
if (!w || !ws) return RAD_E_INVAL;
|
||||
if (span_hi > 0) {
|
||||
const bool col = shard == RAD_SHARD_COL;
|
||||
if (col && (span_lo % RAD_SCALE_GROUP || span_hi % RAD_SCALE_GROUP))
|
||||
return RAD_E_SHAPE;
|
||||
RAD_ARCH_TRY(rad_weight_shard_span(b, w, span_lo, span_hi));
|
||||
RAD_ARCH_TRY(rad_weight_shard_span(b, ws, col ? span_lo / RAD_SCALE_GROUP : span_lo,
|
||||
col ? span_hi / RAD_SCALE_GROUP : span_hi));
|
||||
}
|
||||
const int64_t rows = max_rows > 0 ? max_rows : g.max_tok;
|
||||
row_q = decl_b(b, nm.f("%s.row_q", base), RAD_I8, {rows, K});
|
||||
row_scale = decl_b(b, nm.f("%s.row_scale", base), RAD_F32, {rows, 1});
|
||||
op_q = rw(b, RAD_OP(b, "quant_act_i8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", K),
|
||||
RAD_INT("group", RAD_SCALE_GROUP), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS), {a.x}, {row_q, row_scale});
|
||||
op = decl_gemm_q(b, 1, rows, RAD_SCALE_GROUP,
|
||||
enc.plane[0].dtype == RAD_I4 ? "w4a8" : "w8a8",
|
||||
{w, ws}, {row_q, row_scale}, y);
|
||||
row_i8 = true;
|
||||
return row_q && row_scale && op_q && op ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* ---- int8 weight, `gemm_nt_q` at i8a8 over the input's `a.q8` / `a.s8`. The scale plane is
|
||||
* one bf16 per row per 128 of K: row parts and row slices apply as is, column slices in groups
|
||||
* of 128. The codes come from the producer (ActQ::q8_fed) or from op_q over `a.x` (probe()
|
||||
@@ -1643,6 +1815,14 @@ inline void LinearQ::step(RadCtx* c, const ActQ& a, rad_buf y, int64_t T, int64_
|
||||
int64_t rows, int64_t y0) const {
|
||||
if (rows <= 0) rows = T - r0;
|
||||
const int64_t yr = y0 < 0 ? r0 : y0;
|
||||
if (row_i8) {
|
||||
RAD_ISSUE_N(c, op_q, rows, brow_slice(a.x, r0, rows, K),
|
||||
brow_slice(row_q, 0, rows, K), brow_slice(row_scale, 0, rows, 1), RAD_NONE);
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(row_q, 0, rows, K),
|
||||
brow_slice(row_scale, 0, rows, 1), RAD_W(w), RAD_W(ws),
|
||||
brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE);
|
||||
return;
|
||||
}
|
||||
if (bf16 || ggml) {
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(a.x, r0, rows, K), RAD_W(w), brow_slice(y, yr, rows, N));
|
||||
return;
|
||||
@@ -1991,14 +2171,18 @@ inline rad_op decl_gated_fold_iqr(RadBuilder* b, int64_t rows, int64_t N, int64_
|
||||
|
||||
/* ================================================== a calibration tap */
|
||||
/* One tap of the GPTQ calibration (calib_dir): the Gram of a linear's bf16 input, summed over the
|
||||
* corpus in a PERSIST [K, K] f32 buffer that calib_write() saves. */
|
||||
* corpus in a PERSIST [K, K] f32 buffer that calib_write() saves. The buffer is arena memory, which
|
||||
* is not zeroed when it is allocated, and gram_accum adds to what it finds: the first live step
|
||||
* zeroes it. */
|
||||
struct CalibTap {
|
||||
rad_buf h = 0;
|
||||
rad_op op = 0;
|
||||
int64_t K = 0;
|
||||
mutable bool zeroed = false; /* step() is const to the plugins' step functions */
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, int64_t max_tok, const char* name, rad_buf a, int64_t k) {
|
||||
K = k;
|
||||
zeroed = false;
|
||||
h = decl_b(b, nm.f("%s.gram", name), RAD_F32, { k, k }, RAD_BUF_PERSIST);
|
||||
if (!h) return RAD_E_INVAL;
|
||||
op = rw(b, RAD_OP(b, "gram_accum",
|
||||
@@ -2009,8 +2193,25 @@ struct CalibTap {
|
||||
return op ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
/* gram_accum takes a, a_scale?, h: no scale for a bf16 input. */
|
||||
/* The zeroing goes on the rank's stream, lane 0's: a tap must be stepped on lane 0, as every
|
||||
* caller's is (the plugins that use a second lane turn it off under calibration). */
|
||||
bool ensure_zeroed(RadCtx* c) const {
|
||||
if (zeroed) return true;
|
||||
if (rad_memset_async(rad_buf_ptr(c, h), 0, K * K * 4, rad_stream(c)) < 0) {
|
||||
rad_step_fail(c, "calibration: zeroing a Gram accumulator failed");
|
||||
return false;
|
||||
}
|
||||
zeroed = true;
|
||||
return true;
|
||||
}
|
||||
void step(RadCtx* c, rad_buf a, int64_t T, bool live) const {
|
||||
if (op && live) RAD_ISSUE_N(c, op, T, brows(a, T), RAD_NONE, brows(h, K));
|
||||
if (!op || !live || !ensure_zeroed(c)) return;
|
||||
RAD_ISSUE_N(c, op, T, brows(a, T), RAD_NONE, brows(h, K));
|
||||
}
|
||||
/* The rows [first, first + n) only: the routed arm issues row chunks, not whole buffers. */
|
||||
void step_rows(RadCtx* c, rad_buf a, int64_t first, int64_t n, int64_t pitch, bool live) const {
|
||||
if (!op || !live || !ensure_zeroed(c)) return;
|
||||
RAD_ISSUE_N(c, op, n, brow_slice(a, first, n, pitch), RAD_NONE, brows(h, K));
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -466,6 +466,10 @@ struct Model {
|
||||
/* The checkpoint is DeepSeek's release (is_release): the name map reads its tensors by
|
||||
* inference/model.py's names (ckpt_name), `n_stage` DSpark stages (mtp.*) after the trunk. */
|
||||
bool release = false;
|
||||
/* Images are served (the engine found the tower's weights, mm-max-patches > 0), so the routers
|
||||
* need the image-span corrections (bias_vl / exp_probs_b_vl). A container converted without
|
||||
* the tower keeps vision_config in its metadata but carries neither, and serves text. */
|
||||
bool vl = false;
|
||||
int n_stage = 0;
|
||||
};
|
||||
static std::unique_ptr<Model> models[MAX_RANKS];
|
||||
@@ -1099,10 +1103,10 @@ static void moe_names(Model& m, int l, MoeQ::Src* s) {
|
||||
auto& nm = m.nm;
|
||||
s->router = ckpt_name(nm.f("blk.%d.ffn_gate_inp.weight", l));
|
||||
s->router_bias = ckpt_name(nm.f("blk.%d.exp_probs_b.bias", l));
|
||||
s->router_bias_vl = m.release
|
||||
? (l < m.c.n_layer ? nm.ckpt("layers.%d.ffn.gate.bias_vl", l)
|
||||
: nm.ckpt("mtp.%d.ffn.gate.bias_vl", l - (int)m.c.n_layer))
|
||||
: ckpt_name(nm.f("blk.%d.exp_probs_b_vl.bias", l));
|
||||
s->router_bias_vl = !m.vl ? nullptr
|
||||
: m.release ? (l < m.c.n_layer ? nm.ckpt("layers.%d.ffn.gate.bias_vl", l)
|
||||
: nm.ckpt("mtp.%d.ffn.gate.bias_vl", l - (int)m.c.n_layer))
|
||||
: ckpt_name(nm.f("blk.%d.exp_probs_b_vl.bias", l));
|
||||
s->shared_mlp_gate = ckpt_name(nm.f("blk.%d.ffn_gate_shexp.weight", l));
|
||||
s->shared_mlp_up = ckpt_name(nm.f("blk.%d.ffn_up_shexp.weight", l));
|
||||
s->shared_mlp_down = ckpt_name(nm.f("blk.%d.ffn_down_shexp.weight", l));
|
||||
@@ -2071,6 +2075,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
auto& nm = m.nm;
|
||||
DS_TRY(read_cfg(m.c, meta));
|
||||
m.release = is_release(meta);
|
||||
m.vl = ctx->max_enc_patches > 0;
|
||||
m.n_stage = (int)gi(meta, "nextn_predict_layers", 0);
|
||||
naming = &m;
|
||||
DS_TRY(geometry(m, ctx));
|
||||
|
||||
@@ -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
|
||||
+1528
-133
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>
|
||||
@@ -1820,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;
|
||||
@@ -1842,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 */
|
||||
@@ -2345,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()});
|
||||
@@ -2592,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
|
||||
@@ -2608,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) {
|
||||
@@ -3172,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)
|
||||
@@ -3205,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;
|
||||
|
||||
+34
-25
@@ -108,16 +108,21 @@ static thread_local std::unique_ptr<Model> probe_model;
|
||||
/* 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) {
|
||||
for (int l = 3; l < 45; ++l)
|
||||
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)) 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;
|
||||
}
|
||||
|
||||
@@ -433,7 +438,7 @@ static MoeQ::Src moe_source(const Model& m, Names& nm, int l) {
|
||||
|
||||
static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool draft) {
|
||||
const auto& g = m.g;
|
||||
if (!draft && l >= 3 && (size_t)l >= m.moe_src.size()) return RAD_E_INVAL;
|
||||
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);
|
||||
@@ -492,15 +497,9 @@ static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool dra
|
||||
} else {
|
||||
auto w = m.mw;
|
||||
w.x = input;
|
||||
/* The trunk's routed layers were probed before the buffers (declare); the draft layer is
|
||||
* probed here, through its own names. */
|
||||
MoeQ::Src s;
|
||||
if (draft) {
|
||||
s = moe_source(m, nm, l);
|
||||
RAD_ARCH_TRY(MoeQ::probe(b, nm, l, s, &s.cfg));
|
||||
} else {
|
||||
s = m.moe_src[(size_t)l];
|
||||
}
|
||||
/* 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;
|
||||
@@ -534,6 +533,7 @@ 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;
|
||||
@@ -598,8 +598,10 @@ 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_split_by_width(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. */
|
||||
@@ -625,11 +627,16 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
/* ---- 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. */
|
||||
m.moe_src.assign(45, MoeQ::Src{});
|
||||
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);
|
||||
@@ -643,7 +650,18 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
linear_is_w8h(enc) && !linear_is_wnh(enc);
|
||||
m.trunk_g8 = m.trunk_rot ? linear_w8h_group(enc) : (int64_t)RAD_SCALE_GROUP;
|
||||
}
|
||||
for (int l = 3; l < 45; ++l) {
|
||||
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)) {
|
||||
@@ -659,15 +677,6 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
}
|
||||
/* The draft layer's IQ8R and IQR wiring is not yet covered (its names are under the draft
|
||||
* scope and it reads the trunk's pairs from its own join), so an IQ8R container is served
|
||||
* without it until it is. */
|
||||
if (m.trunk_rot && ctx->max_spec > 0) {
|
||||
fprintf(stderr, "radiance: glm5next: the MTP draft layer of an IQ8R trunk is not served yet; "
|
||||
"`num-speculative-tokens: 0` serves the model without it (and rad-convert "
|
||||
"--max-spec 0 converts it without it)\n");
|
||||
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");
|
||||
|
||||
+76
-11
@@ -41,8 +41,10 @@
|
||||
* layout.
|
||||
*/
|
||||
#include <arch/rad_arch.h>
|
||||
#include <arch/rad_block_hc.h>
|
||||
#include <arch/rad_block_inkling2_tower.h>
|
||||
#include <arch/rad_inkling2_chat.h>
|
||||
#include <rad_prefill_split.h>
|
||||
|
||||
#include "inkling2_dflash2.h"
|
||||
|
||||
@@ -108,7 +110,12 @@ struct Layer {
|
||||
rad_op op_mlp_mix = 0, op_mlp_norm = 0, op_mlp_norm_ctl = 0, op_router = 0, op_topk = 0;
|
||||
rad_op op_mlp_norm_q8 = 0, op_mlp_norm_ctl_q8 = 0, op_router_scatter = 0;
|
||||
rad_op op_scatter = 0, op_egu = 0, op_situ = 0, op_edn = 0, op_gather = 0;
|
||||
bool scatter_inv = false, gather_inv = false; /* the sort writes `inv` for the gather */
|
||||
rad_op op_push = 0, op_resid = 0, op_push_copy = 0, op_resid_copy = 0, op_attn_add = 0, op_mlp_add = 0;
|
||||
/* the control vector's projection on the stream at this layer's output (HcProject; hc 1,
|
||||
* because the stream here is a plain bf16 residual and not a gated one). Unsteered layers
|
||||
* hold the default and issue nothing. */
|
||||
HcProject proj;
|
||||
/* the experts' stored form (ExpertForm), its codes and scale planes, and for an IQR expert the
|
||||
* quantiser of the routed input and of the SiTU product */
|
||||
int ex_form = 0;
|
||||
@@ -170,6 +177,7 @@ struct Model {
|
||||
rad_buf b_att = 0, b_sig = 0, b_attg = 0, b_ao = 0, b_ax = 0;
|
||||
rad_buf b_mx = 0, b_cym = 0, b_fm = 0, b_rl = 0, b_ids = 0, b_wts = 0;
|
||||
rad_buf b_sorted = 0, b_eoff = 0, b_ecnt = 0, b_gu = 0, b_act = 0, b_dn = 0, b_mo = 0, b_zc = 0;
|
||||
rad_buf b_inv = 0;
|
||||
rad_buf b_yo = 0, b_yn = 0, b_hout = 0, b_logits = 0;
|
||||
rad_buf b_q8 = 0, b_s8 = 0, b_aq = 0, b_as = 0; /* an IQR expert's int8 input and product */
|
||||
/* an int8 trunk's rotated activation codes: the three projection inputs and the gated output */
|
||||
@@ -695,6 +703,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
|
||||
/* ---- activations: [max_tok, width] unless stated */
|
||||
m.b_s = decl_b(b, nm.f("S"), RAD_BF16, {T, m.H});
|
||||
/* The control vector's per-token switch, once per model (HcProject). All zeros -- or no
|
||||
* vector at all -- leaves every layer unsteered and the model byte-identical to a deployment
|
||||
* without one. */
|
||||
const rad_buf proj_on = HcProject::declare_mask(b, nm.f("projection_on"), g, ctx->cvec);
|
||||
m.b_pre = decl_b(b, nm.f("pre"), RAD_BF16, {T, m.H});
|
||||
m.b_bank1 = decl_b(b, nm.f("bank1"), RAD_BF16, {T, m.H});
|
||||
m.b_bank0 = decl_b(b, nm.f("bank0"), RAD_BF16, {1, T, m.H});
|
||||
@@ -748,6 +760,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
m.b_sorted = decl_b(b, nm.f("sorted"), RAD_I32, {T * m.K});
|
||||
m.b_eoff = decl_b(b, nm.f("eoff"), RAD_I32, {m.E + 1});
|
||||
m.b_ecnt = decl_b(b, nm.f("ecnt"), RAD_I32, {m.E});
|
||||
/* the gather's slot table, written by the sort so the gather need not rebuild it */
|
||||
if (rad_op_declared(b, "moe_scatter_inv") && rad_op_declared(b, "moe_gather_inv"))
|
||||
m.b_inv = decl_b(b, nm.f("inv"), RAD_I32, {T * m.K});
|
||||
m.b_gu = decl_b(b, nm.f("gu"), RAD_BF16, {T * m.K, 2 * m.FW});
|
||||
m.b_act = decl_b(b, nm.f("act"), RAD_BF16, {T * m.K, m.FW});
|
||||
/* an IQR expert's routed input and SiTU product: int8 codes with an f32 scale per 128 */
|
||||
@@ -1446,9 +1461,16 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_F64("route_scale", m.route_scale),
|
||||
RAD_STR("dtype", "f32")),
|
||||
RAD_WEIGHTS(L.w_bias)), {m.b_rl}, {m.b_ids, m.b_wts});
|
||||
L.op_scatter = rw(b, RAD_OP(b, "moe_scatter", RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_expert", m.E),
|
||||
RAD_INT("top_k", m.K)), RAD_NOWEIGHTS),
|
||||
{m.b_ids}, {m.b_sorted, m.b_eoff, m.b_ecnt});
|
||||
{
|
||||
const RadParam ps[] = { RAD_RANGE("M", 1, T), RAD_INT("n_expert", m.E), RAD_INT("top_k", m.K) };
|
||||
if (m.b_inv)
|
||||
L.op_scatter = try_op("moe_scatter_inv", ps, 3, nullptr, 0, {m.b_ids},
|
||||
{m.b_sorted, m.b_eoff, m.b_ecnt, m.b_inv});
|
||||
L.scatter_inv = L.op_scatter != 0;
|
||||
if (!L.op_scatter)
|
||||
L.op_scatter = rw(b, rad_decl_op(b, "moe_scatter", ps, 3, nullptr, 0), {m.b_ids},
|
||||
{m.b_sorted, m.b_eoff, m.b_ecnt});
|
||||
}
|
||||
{
|
||||
const int64_t T_rs = std::min<int64_t>(T, 1024 / m.K);
|
||||
if (T_rs >= 1) {
|
||||
@@ -1458,6 +1480,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
const rad_weight w[] = { L.w_bias };
|
||||
L.op_router_scatter = try_op("router_sigmoid_topk_scatter", ps, 6, w, 1,
|
||||
{m.b_rl}, {m.b_ids, m.b_wts, m.b_sorted, m.b_eoff, m.b_ecnt});
|
||||
if (L.op_router_scatter && L.scatter_inv) rad_op_writes(b, L.op_router_scatter, &m.b_inv, 1);
|
||||
}
|
||||
}
|
||||
if (L.ex_form == kExpBf16) {
|
||||
@@ -1538,13 +1561,25 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
{m.b_aq, m.b_as, m.b_sorted, m.b_eoff}, {m.b_dn});
|
||||
}
|
||||
}
|
||||
L.op_gather = rw(b, RAD_OP(b, "moe_gather", RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", m.H),
|
||||
RAD_INT("top_k", m.K), RAD_STR("dtype", "bf16"),
|
||||
RAD_STR("act", "none")), RAD_NOWEIGHTS),
|
||||
{m.b_dn, m.b_wts, m.b_sorted}, {m.b_mo});
|
||||
{
|
||||
const RadParam ps[] = { RAD_RANGE("M", 1, T), RAD_INT("n", m.H), RAD_INT("top_k", m.K),
|
||||
RAD_STR("dtype", "bf16"), RAD_STR("act", "none") };
|
||||
if (L.scatter_inv)
|
||||
L.op_gather = try_op("moe_gather_inv", ps, 5, nullptr, 0, {m.b_dn, m.b_wts, m.b_inv}, {m.b_mo});
|
||||
L.gather_inv = L.op_gather != 0;
|
||||
if (!L.op_gather)
|
||||
L.op_gather = rw(b, rad_decl_op(b, "moe_gather", ps, 5, nullptr, 0), {m.b_dn, m.b_wts, m.b_sorted},
|
||||
{m.b_mo});
|
||||
}
|
||||
L.op_ar_m = all_reduce(m.b_mo);
|
||||
if (g.world > 1 && (!L.op_ar_o || !L.op_ar_m)) return RAD_E_UNSUPPORTED;
|
||||
L.op_mlp_add = ew("add", T, m.H, {m.b_s, m.b_zc}, m.b_s);
|
||||
/* The control vector's projection for this layer, if the vector steers it: the same
|
||||
* op qwen4exp declares on its gated stream, here on the plain one (hc 1). It sits
|
||||
* at the layer's output -- every reader of the stream from here on, the draft's taps
|
||||
* included, sees the projected residuals. */
|
||||
RAD_ARCH_TRY(L.proj.declare(b, nm.f("blk.%lld.proj", (long long) ip), g, ip,
|
||||
ctx->cvec, proj_on, m.b_s, 1));
|
||||
/* the controllers: (1 - tanh(F g)) x + tanh(G g) msg, g = D [rms x | rms msg] */
|
||||
if (L.core) {
|
||||
{
|
||||
@@ -2072,10 +2107,14 @@ static void run_layer(RadCtx* c, const Model& m, const RadBatch* batch, int a, b
|
||||
if (L.op_router_scatter && T * m.K <= 1024) {
|
||||
RAD_ISSUE_N(c, L.op_router_scatter, T, brows(m.b_rl, T), RAD_W(L.w_bias),
|
||||
brows(m.b_ids, T), brows(m.b_wts, T), RAD_B(m.b_sorted), RAD_B(m.b_eoff),
|
||||
RAD_B(m.b_ecnt), RAD_NONE, RAD_NONE);
|
||||
RAD_B(m.b_ecnt), RAD_NONE, L.scatter_inv ? RAD_B(m.b_inv) : RAD_NONE);
|
||||
} else {
|
||||
RAD_ISSUE_N(c, L.op_topk, T, brows(m.b_rl, T), RAD_W(L.w_bias), brows(m.b_ids, T), brows(m.b_wts, T));
|
||||
RAD_ISSUE_N(c, L.op_scatter, T, brows(m.b_ids, T), RAD_B(m.b_sorted), RAD_B(m.b_eoff), RAD_B(m.b_ecnt));
|
||||
if (L.scatter_inv)
|
||||
RAD_ISSUE_N(c, L.op_scatter, T, brows(m.b_ids, T), RAD_B(m.b_sorted), RAD_B(m.b_eoff),
|
||||
RAD_B(m.b_ecnt), RAD_B(m.b_inv));
|
||||
else
|
||||
RAD_ISSUE_N(c, L.op_scatter, T, brows(m.b_ids, T), RAD_B(m.b_sorted), RAD_B(m.b_eoff), RAD_B(m.b_ecnt));
|
||||
}
|
||||
if (L.ex_form == kExpBf16) {
|
||||
RAD_ISSUE_N(c, L.op_egu, T, brows(m.b_fm, T), RAD_WTAB(L.w_egu[0], m.E), RAD_B(m.b_sorted),
|
||||
@@ -2097,8 +2136,8 @@ static void run_layer(RadCtx* c, const Model& m, const RadBatch* batch, int a, b
|
||||
RAD_WTAB(L.w_edn[1], h), RAD_WTAB(L.w_edns[1], h), brows(m.b_dn, T * m.K));
|
||||
}
|
||||
calib_ffn(c, m, L, ip, T);
|
||||
RAD_ISSUE_N(c, L.op_gather, T, brows(m.b_dn, T * m.K), RAD_B(m.b_wts), RAD_B(m.b_sorted), RAD_NONE,
|
||||
RAD_NONE, brows(m.b_mo, T));
|
||||
RAD_ISSUE_N(c, L.op_gather, T, brows(m.b_dn, T * m.K), RAD_B(m.b_wts),
|
||||
RAD_B(L.gather_inv ? m.b_inv : m.b_sorted), RAD_NONE, RAD_NONE, brows(m.b_mo, T));
|
||||
if (L.op_ar_m) RAD_ISSUE_N(c, L.op_ar_m, T * m.H, brows(m.b_mo, T), RAD_NONE);
|
||||
if (L.op_mconv_add) {
|
||||
issue_sconv_add(c, batch, L.op_mconv_add, L.w_mconv, m.cv_m, a, m.b_mo, m.b_s, m.b_s);
|
||||
@@ -2106,6 +2145,11 @@ static void run_layer(RadCtx* c, const Model& m, const RadBatch* batch, int a, b
|
||||
issue_sconv(c, batch, L.op_mconv, L.w_mconv, m.cv_m, a, m.b_mo, 0, m.b_zc);
|
||||
RAD_ISSUE(c, L.op_mlp_add, brows(m.b_s, T), brows(m.b_zc, T), brows(m.b_s, T));
|
||||
}
|
||||
/* The control vector's projection at the layer output, on either write path (the FF delta
|
||||
* enters the stream through the message convolution when this model has one). Issues nothing
|
||||
* when the pass has no row taking the vector (HcProject::step, RadBatch::control_vector),
|
||||
* so an ordinary request's step is the stock one. */
|
||||
L.proj.step(c, batch, 0, T);
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
@@ -2197,11 +2241,29 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
* opening with <|message_model|> (arch/rad_inkling2_chat.h). */
|
||||
static const RadChatFormat* chat_format(const RadModelMeta*) { return inkling2_chat_format(); }
|
||||
|
||||
/* rad_arch_pass_key. attn_paged_rel's rows declare RAD_KERNEL_CAP_DYNAMIC_PREFILL_SPLIT: off its
|
||||
* WMMA prefill path the split count follows the live KV maximum, which the core's key does not hold,
|
||||
* so without a key here no prefill or mixed pass is recorded. A decode, verify or draft pass issues
|
||||
* every launch at the keyed context bound (rad_builder.h). A mixed pass is keyed when every attention
|
||||
* launch takes the WMMA path, whose grid has no split (rad_rel_wmma_prefill): one launch a layer over
|
||||
* all n_tok rows and n_seq sequences, and the launch's longest query is at least max_q_len. Its key
|
||||
* repeats while a decoding sequence holds the longest context. A prefill pass is not keyed: the
|
||||
* core's key holds the context bucket, which moves with nearly every chunk below 128K, so its
|
||||
* recordings would rarely play and would push the decode tapes out. */
|
||||
static uint64_t pass_key(const RadBatch* b) {
|
||||
if (!b || b->phase == RAD_PHASE_PREFILL) return 0;
|
||||
if (b->phase != RAD_PHASE_MIXED) return 1;
|
||||
return rad_rel_wmma_prefill(b->max_q_len, b->n_tok, b->n_seq);
|
||||
}
|
||||
|
||||
/* The tower's merge factor (4 patches per merged row) and the DFlash2 drafter's fixed depth (one
|
||||
* proposal per mask row). */
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
out->chain_pays = RAD_CHAIN_ALWAYS;
|
||||
if (meta && Inkling2Tower::present(meta)) out->enc_merge = 4;
|
||||
/* The plugin declares the control vector's projection on its stream (HcProject, hc 1), so
|
||||
* the engine loads a vector file for this architecture. */
|
||||
out->control_vector_ok = 1;
|
||||
out->draft_depth = 0;
|
||||
out->draft_depth_fixed = 0;
|
||||
if (meta && dflash2_present(meta)) {
|
||||
@@ -2229,4 +2291,7 @@ RAD_ARCH_PLUGIN(inkling2, "inkling2", "", "0.1.0",
|
||||
"calibration), a DFlash2 drafter; tensor parallel")
|
||||
RAD_ARCH_CHAT_FORMAT(inkling2)
|
||||
RAD_ARCH_PROBE(inkling2)
|
||||
extern "C" uint64_t rad_arch_pass_key(RadCtx*, const RadBatch* batch, const int32_t*) {
|
||||
return inkling2::pass_key(batch);
|
||||
}
|
||||
#endif
|
||||
+138
-141
@@ -376,10 +376,8 @@ enum : int {
|
||||
kGrpTower = 3300,
|
||||
kGrpVenc = 3400,
|
||||
kGrpAenc = 3500,
|
||||
/* The encoders' weights only a host kernel reads (conv_in, the k=1 convs, the snake alphas):
|
||||
* placement keeps a group with a host-only reader in host memory whole, so they are a group
|
||||
* of their own. */
|
||||
kGrpVencH = 3450,
|
||||
/* A host-only reader keeps its entire group in host memory. Keep the audio encoder's
|
||||
* host-only weights apart from the weights read by GPU kernels. */
|
||||
kGrpAencH = 3550,
|
||||
};
|
||||
|
||||
@@ -1238,6 +1236,15 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
RAD_ARCH_TRY(m.dit[0].down.probe(b, nm, g, nm.f("dit.blk.0.ffn_down"),
|
||||
{ nm.ckpt("transformer.transformer_blocks.0.ff.net.2.weight") }));
|
||||
m.dit_i8 = m.dit[0].down.probed_i8;
|
||||
// Rotated W4A8 consumes the same 128-column int8 activation groups as W8A8,
|
||||
// after applying the weight's Hadamard basis to its inputs.
|
||||
RadEncoding dit_encoding{};
|
||||
const bool dit_rotated = weight_enc(b, nm.f("dit.blk.0.ffn_down.weight"), &dit_encoding) &&
|
||||
linear_is_wnh(dit_encoding);
|
||||
if (dit_rotated && !rad_op_declared(b, "rms_mod_had_quant_i8g")) {
|
||||
fprintf(stderr, "radiance: minimaxh3: rotated W4A8 requires rms_mod_had_quant_i8g\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
m.op_text = rw(b, RAD_OP(b, "lane_gather",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, (int64_t)kMaxText), RAD_INT("n", D),
|
||||
RAD_INT("stride", (int64_t)kMaxText),
|
||||
@@ -1257,6 +1264,7 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
RAD_ARCH_TRY(m.a_hm.declare_qs(b, nm, g, "dit.hm", D, 0, m.dit_i8, !m.dit_i8));
|
||||
/* rms_mod_quant_i8 writes a_hm's int8 codes, as rms_mod_quant_fp8 writes its E4M3 ones. */
|
||||
m.a_hm.q8_fed = m.dit_i8;
|
||||
m.a_hm.q8_rot = dit_rotated;
|
||||
/* With video sparse attention a fourth projection beside q, k and v gates the pooled-tile
|
||||
* attention into each row's output. */
|
||||
const int64_t nparts = m.vsa_gated ? 4 : 3;
|
||||
@@ -1276,6 +1284,7 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "dit.attn", qd, 0, m.dit_i8, !m.dit_i8));
|
||||
/* q_attn writes the int8 codes the output projection reads. */
|
||||
m.a_attn.q8_fed = m.dit_i8;
|
||||
m.a_attn.q8_rot = dit_rotated;
|
||||
m.b_ao = decl_b(b, nm.f("dit.ao"), RAD_BF16, { T, D });
|
||||
/* More than one rank: the all-reduces of b_ao's halves run on the second lane (step_dit). */
|
||||
if (g.world > 1) RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_ao));
|
||||
@@ -1288,7 +1297,9 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
/* A block's modulated norm: the previous block's delta added to `b_h`, the norm, and `a_hm`'s
|
||||
* codes, int8 or E4M3, in one op. */
|
||||
auto mod_q = [&](rad_weight w, bool gated) {
|
||||
rad_op op = RAD_OP(b, m.dit_i8 ? "rms_mod_quant_i8" : "rms_mod_quant_fp8",
|
||||
const char* norm = dit_rotated ? "rms_mod_had_quant_i8g"
|
||||
: m.dit_i8 ? "rms_mod_quant_i8" : "rms_mod_quant_fp8";
|
||||
rad_op op = RAD_OP(b, norm,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), RAD_F64("eps", eps),
|
||||
RAD_INT("group", RAD_SCALE_GROUP),
|
||||
RAD_INT("gated", gated ? 1 : 0), RAD_STR("dtype", "bf16")),
|
||||
@@ -2224,11 +2235,26 @@ static rad_op venc_conv(RadBuilder* b, int64_t M, int64_t cin, int64_t cout, int
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, M), RAD_INT("cin", cin),
|
||||
RAD_INT("cout", cout), RAD_INT("k", k), RAD_INT("kt", k),
|
||||
RAD_INT("causal", 1), RAD_INT("reflect", 1),
|
||||
RAD_INT("stride", 1), RAD_INT("stride_t", 1),
|
||||
RAD_STR("pad", "same"), RAD_STR("tpad", "zero"),
|
||||
RAD_INT("tpre", 0),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w, bias));
|
||||
return res ? rw(b, op, { x, res }, { y }) : rw(b, op, { x }, { y });
|
||||
}
|
||||
|
||||
static rad_op venc_pointwise(RadBuilder* b, int64_t rows, int64_t cin, int64_t cout,
|
||||
rad_weight w, rad_weight bias) {
|
||||
if (!w || !bias) return 0;
|
||||
return RAD_OP(b, "conv3d_ndhwc",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("cin", cin), RAD_INT("cout", cout),
|
||||
RAD_INT("k", 1), RAD_INT("kt", 1), RAD_INT("causal", 0),
|
||||
RAD_INT("reflect", 0), RAD_INT("stride", 1), RAD_INT("stride_t", 1),
|
||||
RAD_STR("pad", "same"), RAD_STR("tpad", "zero"), RAD_INT("tpre", 0),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w, bias));
|
||||
}
|
||||
|
||||
/* GroupNorm over a level's whole clip volume, then SiLU. */
|
||||
static rad_op venc_gn(RadBuilder* b, int64_t M, int64_t n, int64_t G, double eps, rad_weight w,
|
||||
rad_weight bias, rad_buf x, rad_buf y, rad_buf st) {
|
||||
@@ -2238,7 +2264,9 @@ static rad_op venc_gn(RadBuilder* b, int64_t M, int64_t n, int64_t G, double eps
|
||||
RAD_INT("groups", G), RAD_F64("eps", eps),
|
||||
RAD_STR("act", "silu"), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w, bias));
|
||||
return rw(b, op, { x, st }, { y, st });
|
||||
/* Statistics are workspace initialized by this launch, not an input from a
|
||||
* previous op. Recording them as a read creates a false external dependency. */
|
||||
return rw(b, op, { x }, { y, st });
|
||||
}
|
||||
|
||||
/* The video VAE's encoder (AutoencoderKLMiniMaxH3), when the container carries it: pixels in
|
||||
@@ -2273,12 +2301,17 @@ static int declare_venc(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
"levels of two blocks, 17-frame clips, reflect padding)\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* venc_geom and the issued level volumes implement this released stride pattern. */
|
||||
static constexpr int kSpaceDown[] = {2, 2, 2, 2, 1, 1};
|
||||
static constexpr int kTimeDown[] = {1, 2, 2, 1, 1, 1};
|
||||
for (size_t i = 0; i < 6; ++i)
|
||||
if ((int64_t)dims[i] % G || ((int64_t)sds[i] != 1 && (int64_t)sds[i] != 2) ||
|
||||
((int64_t)tds[i] != 1 && (int64_t)tds[i] != 2))
|
||||
if ((int64_t)dims[i] % G || sds[i] != kSpaceDown[i] || tds[i] != kTimeDown[i]) {
|
||||
fprintf(stderr, "radiance: minimaxh3: video encoder channels must divide the "
|
||||
"normalization groups and downsample factors must match the release\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
m.venc = true;
|
||||
/* Read once a media, so they live in pinned host memory like the text encoder. */
|
||||
/* Read once per media; placement can serve the device or reference CPU reader. */
|
||||
const int acc = RAD_ACCESS_PER_REQUEST;
|
||||
const int gv = kGrpVenc;
|
||||
auto wt = [&](const char* dn, const char* src, std::initializer_list<int64_t> shape) {
|
||||
@@ -2288,11 +2321,6 @@ static int declare_venc(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
auto wb = [&](const char* dn, const char* src, std::initializer_list<int64_t> shape) {
|
||||
return wcopy(b, dn, src, RAD_BF16, shape, acc, gv);
|
||||
};
|
||||
/* conv_in's and the k=1 convolutions', f32, read by a host kernel (kGrpVencH). */
|
||||
auto wh = [&](const char* dn, const char* src, std::initializer_list<int64_t> shape) {
|
||||
return wcopy(b, dn, src, RAD_F32, shape, acc, kGrpVencH);
|
||||
};
|
||||
|
||||
/* Each level's frames, rows and rows a frame: a full clip at 256 x 256, or a frame of the
|
||||
* canvas, whichever is more. */
|
||||
int64_t tf[6], sd[6] = { 1, 1, 1, 1, 1, 1 }, R[6], PF[6];
|
||||
@@ -2324,9 +2352,8 @@ static int declare_venc(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
m.ve_fold_mul = join_list(fm);
|
||||
m.ve_fold_add = join_list(fa);
|
||||
m.b_epix32 = decl_b(b, nm.f("venc.pix32"), RAD_F32, { Rmax, 3 });
|
||||
/* conv_in and the k=1 projections run on the host. Their activation operands must be
|
||||
* pinned host buffers too: joining a device queue does not make its VRAM CPU-readable.
|
||||
* Device convolutions can read/write these boundary buffers over the link in place. */
|
||||
/* Boundary buffers remain pinned and GPU-addressable, so the reference CPU rows and
|
||||
* device convolutions can use the same graph without treating VRAM as CPU-readable. */
|
||||
m.b_epix = decl_b(b, nm.f("venc.pix"), RAD_BF16, { Rmax, 3 },
|
||||
RAD_BUF_TRANSIENT, RAD_DOMAIN_HOST);
|
||||
m.b_egn = decl_b(b, nm.f("venc.gn"), RAD_F32, { G * (2 + 3 * 1024) });
|
||||
@@ -2347,15 +2374,11 @@ static int declare_venc(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
RAD_BUF_TRANSIENT, RAD_DOMAIN_HOST);
|
||||
m.b_eqt = decl_b(b, nm.f("venc.qt"), RAD_BF16, { m.enc_tiles * (int64_t)kTile * kTile, 48 },
|
||||
RAD_BUF_TRANSIENT, RAD_DOMAIN_HOST);
|
||||
m.ve_qw = wh(nm.f("venc.q.weight"), nm.ckpt("vae.quant_conv.weight"), { 48, 48, 1, 1, 1 });
|
||||
m.ve_qb = wh(nm.f("venc.q.bias"), nm.ckpt("vae.quant_conv.bias"), { 48 });
|
||||
m.ve_qw = wt(nm.f("venc.q.weight"), nm.ckpt("vae.quant_conv.weight"), { 48, 48, 1, 1, 1 });
|
||||
m.ve_qb = wt(nm.f("venc.q.bias"), nm.ckpt("vae.quant_conv.bias"), { 48 });
|
||||
/* The whole-canvas pass writes b_eq2; the tiled pass writes a tile's slice of b_eqt, which
|
||||
* op_vt_join blends into b_eq2. */
|
||||
m.op_ve_q = rw(b, RAD_OP(b, "conv3d_ndhwc",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R[5]), RAD_INT("cin", 48),
|
||||
RAD_INT("cout", 48), RAD_INT("k", 1), RAD_INT("kt", 1),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(m.ve_qw, m.ve_qb)),
|
||||
m.op_ve_q = rw(b, venc_pointwise(b, R[5], 48, 48, m.ve_qw, m.ve_qb),
|
||||
{ m.b_eq48 }, { m.b_eq2, m.b_eqt });
|
||||
if (!m.op_ve_q) return RAD_E_INVAL;
|
||||
m.op_ve_pix = rw(b, RAD_OP(b, "chan_affine",
|
||||
@@ -2369,8 +2392,8 @@ static int declare_venc(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
m.op_ve_pcast = cast_op(b, Rmax, 3, "f32", "bf16", m.b_epix32, m.b_epix);
|
||||
/* Mapped by the presence check above. */
|
||||
m.ve_cinw = decl_w(b, nm.f("venc.cin.weight"), RAD_F32, { (int64_t)dims[0], 3, 3, 3, 3 },
|
||||
acc, RAD_SHARD_NONE, grp_layer(kGrpVencH));
|
||||
m.ve_cinb = wh(nm.f("venc.cin.bias"), nm.ckpt("vae.encoder.conv_in.bias"), { (int64_t)dims[0] });
|
||||
acc, RAD_SHARD_NONE, grp_layer(gv));
|
||||
m.ve_cinb = wt(nm.f("venc.cin.bias"), nm.ckpt("vae.encoder.conv_in.bias"), { (int64_t)dims[0] });
|
||||
if (!m.op_ve_pix || !m.op_ve_pcast) return RAD_E_INVAL;
|
||||
m.v_lv.reserve(6);
|
||||
for (int L = 0; L < 6; ++L) {
|
||||
@@ -2379,7 +2402,11 @@ static int declare_venc(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
const int64_t cout = (int64_t)dims[L], cin = L == 0 ? cout : (int64_t)dims[L - 1];
|
||||
const bool sc = L > 0 && cout != cin;
|
||||
E.cin = cin, E.cout = cout, E.rows = R[L], E.pf = PF[L], E.frames = tf[L];
|
||||
E.a = decl_b(b, nm.f("venc.l%d.a", L), RAD_BF16, { R[L], cout },
|
||||
const bool downsampled = L > 0 && (sds[L - 1] == 2 || tds[L - 1] == 2);
|
||||
/* Without a downsample or channel shortcut, this level continues the previous
|
||||
* residual stream directly; a fresh buffer would have no producer. */
|
||||
E.a = L > 0 && !sc && !downsampled ? m.v_lv[(size_t)L - 1].a :
|
||||
decl_b(b, nm.f("venc.l%d.a", L), RAD_BF16, { R[L], cout },
|
||||
RAD_BUF_TRANSIENT, RAD_DOMAIN_HOST);
|
||||
E.b = decl_b(b, nm.f("venc.l%d.b", L), RAD_BF16, { R[L], cout });
|
||||
E.c = decl_b(b, nm.f("venc.l%d.c", L), RAD_BF16, { R[L], cout });
|
||||
@@ -2387,20 +2414,15 @@ static int declare_venc(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
* downsampler before it writes, or which is the level before's stream where there is
|
||||
* none. */
|
||||
if (sc) {
|
||||
const bool dn_in = (int64_t)sds[L - 1] == 2 || (int64_t)tds[L - 1] == 2;
|
||||
E.in = dn_in ? decl_b(b, nm.f("venc.l%d.in", L), RAD_BF16, { R[L], cin },
|
||||
E.in = downsampled ? decl_b(b, nm.f("venc.l%d.in", L), RAD_BF16, { R[L], cin },
|
||||
RAD_BUF_TRANSIENT, RAD_DOMAIN_HOST)
|
||||
: m.v_lv[(size_t)L - 1].a;
|
||||
const char* sc_src = nm.ckpt("vae.encoder.down_blocks.%d.resnets.0.conv_shortcut", L);
|
||||
E.scw = wh(nm.f("venc.l%d.sc.weight", L), nm.ckpt("%s.weight", sc_src),
|
||||
E.scw = wt(nm.f("venc.l%d.sc.weight", L), nm.ckpt("%s.weight", sc_src),
|
||||
{ cout, cin, 1, 1, 1 });
|
||||
E.scb = wh(nm.f("venc.l%d.sc.bias", L), nm.ckpt("%s.bias", sc_src), { cout });
|
||||
E.scb = wt(nm.f("venc.l%d.sc.bias", L), nm.ckpt("%s.bias", sc_src), { cout });
|
||||
if (!E.scw || !E.scb) return RAD_E_INVAL;
|
||||
E.op_sc = rw(b, RAD_OP(b, "conv3d_ndhwc",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R[L]), RAD_INT("cin", cin),
|
||||
RAD_INT("cout", cout), RAD_INT("k", 1),
|
||||
RAD_INT("kt", 1), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(E.scw, E.scb)),
|
||||
E.op_sc = rw(b, venc_pointwise(b, R[L], cin, cout, E.scw, E.scb),
|
||||
{ E.in }, { E.a });
|
||||
if (!E.op_sc) return RAD_E_INVAL;
|
||||
}
|
||||
@@ -2545,7 +2567,7 @@ static int declare_aenc(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
/* Read once a media, as the video encoder's. */
|
||||
const int acc = RAD_ACCESS_PER_REQUEST;
|
||||
const int ga = kGrpAenc;
|
||||
/* The snake alphas: `snake` in f32 is a host kernel (kGrpVencH). */
|
||||
/* The snake alphas are read by a host kernel. */
|
||||
const int gh = kGrpAencH;
|
||||
static const int64_t kStr[5] = { 2, 4, 4, 5, 5 };
|
||||
for (int i = 0; i < 5; ++i)
|
||||
@@ -2572,7 +2594,12 @@ static int declare_aenc(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
m.ae_cinw = decl_w(b, nm.f("aenc.cin.weight"), RAD_F32, { 64, 1, 7 }, acc, RAD_SHARD_NONE,
|
||||
grp_layer(ga));
|
||||
m.ae_cinb = wcopy(b, nm.f("aenc.cin.bias"), nm.ckpt("%s.bias", bs), RAD_F32, { 64 }, acc, ga);
|
||||
m.b_ax[0] = decl_b(b, nm.f("aenc.x0"), RAD_F32, { nn[0], 64 });
|
||||
/* The f32 snakes run on the host (libr4d has only a bf16 one), so every buffer a snake
|
||||
* reads or writes must be a pinned host buffer: joining a device queue does not make its
|
||||
* VRAM CPU-readable (see declare_venc). The device convolutions read and write them over
|
||||
* the link. */
|
||||
m.b_ax[0] = decl_b(b, nm.f("aenc.x0"), RAD_F32, { nn[0], 64 },
|
||||
RAD_BUF_TRANSIENT, RAD_DOMAIN_HOST);
|
||||
if (!m.ae_cinw || !m.ae_cinb || !m.b_ax[0]) return RAD_E_INVAL;
|
||||
m.op_ae_cin = rw(b, RAD_OP(b, "conv1d",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, nn[0]), RAD_INT("cin", 1),
|
||||
@@ -2586,9 +2613,12 @@ static int declare_aenc(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
Model::AEncBlk& A = m.ae_blk[blk];
|
||||
const int64_t u = uu[blk], d = u * 2, np = nn[blk], no = nn[blk + 1];
|
||||
const int64_t s = kStr[blk];
|
||||
m.b_et1[blk] = decl_b(b, nm.f("aenc.t1_%d", blk), RAD_F32, { np, u });
|
||||
m.b_et2[blk] = decl_b(b, nm.f("aenc.t2_%d", blk), RAD_F32, { np, u });
|
||||
m.b_ax[blk + 1] = decl_b(b, nm.f("aenc.x%d", blk + 1), RAD_F32, { no, d });
|
||||
m.b_et1[blk] = decl_b(b, nm.f("aenc.t1_%d", blk), RAD_F32, { np, u },
|
||||
RAD_BUF_TRANSIENT, RAD_DOMAIN_HOST);
|
||||
m.b_et2[blk] = decl_b(b, nm.f("aenc.t2_%d", blk), RAD_F32, { np, u },
|
||||
RAD_BUF_TRANSIENT, RAD_DOMAIN_HOST);
|
||||
m.b_ax[blk + 1] = decl_b(b, nm.f("aenc.x%d", blk + 1), RAD_F32, { no, d },
|
||||
RAD_BUF_TRANSIENT, RAD_DOMAIN_HOST);
|
||||
A.bi = decl_b(b, nm.f("aenc.bf1_%d", blk), RAD_BF16, { np, u });
|
||||
A.bo = decl_b(b, nm.f("aenc.bf2_%d", blk), RAD_BF16, { no, d });
|
||||
if (!m.b_et1[blk] || !m.b_et2[blk] || !m.b_ax[blk + 1] || !A.bi || !A.bo)
|
||||
@@ -2685,7 +2715,8 @@ static int declare_aenc(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
m.ae_finw = decl_w(b, nm.f("aenc.fin.weight"), RAD_F32, { ld, ld, 3 }, acc, RAD_SHARD_NONE,
|
||||
grp_layer(ga));
|
||||
m.ae_finb = wcopy(b, nm.f("aenc.fin.bias"), nm.ckpt("%s.bias", f7), RAD_F32, { ld }, acc, ga);
|
||||
m.b_a6t = decl_b(b, nm.f("aenc.snk6"), RAD_F32, { T, ld });
|
||||
m.b_a6t = decl_b(b, nm.f("aenc.snk6"), RAD_F32, { T, ld },
|
||||
RAD_BUF_TRANSIENT, RAD_DOMAIN_HOST);
|
||||
m.b_ax6 = decl_b(b, nm.f("aenc.x6"), RAD_F32, { T, ld });
|
||||
if (!m.ae_al6 || !m.ae_finw || !m.ae_finb || !m.b_a6t || !m.b_ax6) return RAD_E_INVAL;
|
||||
m.op_ae_snk6 = rw(b, RAD_OP(b, "snake",
|
||||
@@ -3746,14 +3777,71 @@ static void step_upscale(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
brow_slice(m.b_astate, lane * m.maxA, arows, kAudioC));
|
||||
}
|
||||
|
||||
/* Encode one causal volume, with GPU-readable pinned geometry and host-side issue sizes. */
|
||||
static void step_venc_volume(RadCtx* c, const Model& m, const int32_t* geom, int64_t frames,
|
||||
int64_t height, int64_t width, RadOperand pixels, RadOperand moments) {
|
||||
const RadOperand stats = RAD_B(m.b_egn);
|
||||
const int64_t half_t = (frames + 1) / 2, quarter_t = (half_t + 1) / 2;
|
||||
const int64_t times[] = { frames, frames, half_t, quarter_t, quarter_t, quarter_t };
|
||||
RadOperand level_geom[6];
|
||||
int64_t rows[6];
|
||||
for (int level = 0; level < 6; ++level) {
|
||||
const int level_shape = std::min(level, 4);
|
||||
const int scale = 1 << level_shape;
|
||||
rows[level] = times[level] * (height / scale) * (width / scale);
|
||||
level_geom[level] = praw(geom + 3 * level_shape, RAD_I32, 3);
|
||||
}
|
||||
const int64_t input_rows = rows[0];
|
||||
RAD_ISSUE_N(c, m.op_ve_pix, input_rows, pixels, brows(m.b_epix32, input_rows));
|
||||
RAD_ISSUE_N(c, m.op_ve_pcast, input_rows, brows(m.b_epix32, input_rows),
|
||||
brows(m.b_epix, input_rows));
|
||||
RAD_ISSUE_N(c, m.op_ve_cin, input_rows, brows(m.b_epix, input_rows), RAD_W(m.ve_cinw),
|
||||
RAD_W(m.ve_cinb), level_geom[0], RAD_NONE, brows(m.v_lv[0].a, input_rows));
|
||||
for (int level = 0; level < 6; ++level) {
|
||||
const Model::VEncLevel& layer = m.v_lv[(size_t)level];
|
||||
const int64_t n = rows[level];
|
||||
const RadOperand gg = level_geom[level];
|
||||
for (int blk = 0; blk < 2; ++blk) {
|
||||
const Model::VEncBlock& block = layer.blk[blk];
|
||||
const bool shortcut = blk == 0 && layer.op_sc;
|
||||
const rad_buf input = shortcut ? layer.in : layer.a;
|
||||
const rad_buf normalized = shortcut ? layer.in : layer.b;
|
||||
/* The shortcut reads the raw input before norm1 overwrites it. */
|
||||
if (shortcut)
|
||||
RAD_ISSUE_N(c, layer.op_sc, n, brows(layer.in, n), RAD_W(layer.scw),
|
||||
RAD_W(layer.scb), gg, RAD_NONE, brows(layer.a, n));
|
||||
RAD_ISSUE_N(c, block.op_n1, n, brows(input, n), RAD_W(block.n1w), RAD_W(block.n1b),
|
||||
RAD_NONE, stats, brows(normalized, n));
|
||||
RAD_ISSUE_N(c, block.op_c1, n, brows(normalized, n), RAD_W(block.c1w), RAD_W(block.c1b),
|
||||
gg, RAD_NONE, brows(layer.c, n));
|
||||
RAD_ISSUE_N(c, block.op_n2, n, brows(layer.c, n), RAD_W(block.n2w), RAD_W(block.n2b),
|
||||
RAD_NONE, stats, brows(layer.b, n));
|
||||
RAD_ISSUE_N(c, block.op_c2, n, brows(layer.b, n), RAD_W(block.c2w), RAD_W(block.c2b),
|
||||
gg, brows(layer.a, n), brows(layer.a, n));
|
||||
}
|
||||
if (level < 4) {
|
||||
const Model::VEncLevel& next = m.v_lv[(size_t)level + 1];
|
||||
const rad_buf output = next.op_sc ? next.in : next.a;
|
||||
RAD_ISSUE_N(c, layer.op_dn, rows[level + 1], brows(layer.a, n), RAD_W(layer.dnw),
|
||||
RAD_W(layer.dnb), gg, RAD_NONE, brows(output, rows[level + 1]));
|
||||
}
|
||||
}
|
||||
const int64_t n = rows[5];
|
||||
RAD_ISSUE_N(c, m.op_ve_nout, n, brows(m.v_lv[5].a, n), RAD_W(m.ve_now), RAD_W(m.ve_nob),
|
||||
RAD_NONE, stats, brows(m.v_lv[5].b, n));
|
||||
RAD_ISSUE_N(c, m.op_ve_cout, n, brows(m.v_lv[5].b, n), RAD_W(m.ve_coutw), RAD_W(m.ve_coutb),
|
||||
level_geom[5], RAD_NONE, brows(m.b_eq48, n));
|
||||
RAD_ISSUE_N(c, m.op_ve_q, n, brows(m.b_eq48, n), RAD_W(m.ve_qw), RAD_W(m.ve_qb),
|
||||
level_geom[5], RAD_NONE, moments);
|
||||
}
|
||||
|
||||
/* A picture larger than a tile, encoded as ComfyUI's vae.py tiled_encode does: overlapping tiles,
|
||||
* each through the trunk alone (GroupNorm sees only its tile), and each tile's moments blended
|
||||
* with its unblended top and left neighbours into the canvas (vtile_join). A tile's geometries are
|
||||
* its row of b_tplan, which vtile_plan writes as vae.py splits. Returns the slot row past the
|
||||
* media's latents. */
|
||||
static int64_t step_venc_tiled(RadCtx* c, const RadVideoGenBatch* V, const Model& m,
|
||||
const int32_t* gd, int64_t H, int64_t W, int64_t ppc,
|
||||
const RadOperand st, int64_t row0) {
|
||||
const int32_t* gd, int64_t H, int64_t W, int64_t ppc, int64_t row0) {
|
||||
const int64_t lat_h = H / kVaeRatio, lat_w = W / kVaeRatio;
|
||||
const std::vector<int64_t> ty = tile_starts(lat_h), tx = tile_starts(lat_w);
|
||||
const int64_t nh = (int64_t)ty.size(), nw = (int64_t)tx.size(), nt = nh * nw;
|
||||
@@ -3784,54 +3872,9 @@ static int64_t step_venc_tiled(RadCtx* c, const RadVideoGenBatch* V, const Model
|
||||
const Tile& T = tl[t];
|
||||
const int64_t th = T.ny * kVaeRatio, tw = T.nx * kVaeRatio; /* the tile, in pixels */
|
||||
const int64_t Rpix = th * tw, R5 = T.ny * T.nx;
|
||||
int64_t R[6];
|
||||
for (int L = 0; L < 6; ++L) {
|
||||
const int64_t d = 1 << std::min(L, 4); /* the level's spatial divisor */
|
||||
R[L] = (th / d) * (tw / d);
|
||||
}
|
||||
/* The tile's plan row: its six {1, side, side} geometry entries, one frame deep. */
|
||||
const int32_t* tr = tp + 22 * (int64_t)t;
|
||||
const RadOperand gg[6] = { praw(tr + 4, RAD_I32, 3), praw(tr + 7, RAD_I32, 3),
|
||||
praw(tr + 10, RAD_I32, 3), praw(tr + 13, RAD_I32, 3),
|
||||
praw(tr + 16, RAD_I32, 3), praw(tr + 19, RAD_I32, 3) };
|
||||
RAD_ISSUE_N(c, m.op_ve_pix, Rpix, brow_slice(m.b_vtile, T.prow, Rpix, 3),
|
||||
brows(m.b_epix32, Rpix));
|
||||
RAD_ISSUE_N(c, m.op_ve_pcast, Rpix, brows(m.b_epix32, Rpix), brows(m.b_epix, Rpix));
|
||||
RAD_ISSUE_N(c, m.op_ve_cin, Rpix, brows(m.b_epix, Rpix), RAD_W(m.ve_cinw),
|
||||
RAD_W(m.ve_cinb), gg[0], RAD_NONE, brows(m.v_lv[0].a, Rpix));
|
||||
for (int L = 0; L < 6; ++L) {
|
||||
const Model::VEncLevel& E = m.v_lv[(size_t)L];
|
||||
const bool sc = E.op_sc;
|
||||
for (int blk = 0; blk < 2; ++blk) {
|
||||
const Model::VEncBlock& B = E.blk[blk];
|
||||
const bool f0 = blk == 0 && sc;
|
||||
const rad_buf xa = f0 ? E.in : E.a, nb = f0 ? E.in : E.b;
|
||||
/* The shortcut convolves the raw input, before norm1 (as in the plain loop). */
|
||||
if (f0)
|
||||
RAD_ISSUE_N(c, E.op_sc, R[L], brows(E.in, R[L]), RAD_W(E.scw), RAD_W(E.scb),
|
||||
gg[L], RAD_NONE, brows(E.a, R[L]));
|
||||
RAD_ISSUE_N(c, B.op_n1, R[L], brows(xa, R[L]), RAD_W(B.n1w), RAD_W(B.n1b),
|
||||
RAD_NONE, st, brows(nb, R[L]));
|
||||
RAD_ISSUE_N(c, B.op_c1, R[L], brows(nb, R[L]), RAD_W(B.c1w), RAD_W(B.c1b),
|
||||
gg[L], RAD_NONE, brows(E.c, R[L]));
|
||||
RAD_ISSUE_N(c, B.op_n2, R[L], brows(E.c, R[L]), RAD_W(B.n2w), RAD_W(B.n2b),
|
||||
RAD_NONE, st, brows(E.b, R[L]));
|
||||
RAD_ISSUE_N(c, B.op_c2, R[L], brows(E.b, R[L]), RAD_W(B.c2w), RAD_W(B.c2b),
|
||||
gg[L], brows(E.a, R[L]), brows(E.a, R[L]));
|
||||
}
|
||||
if (L < 4) {
|
||||
const Model::VEncLevel& X = m.v_lv[(size_t)L + 1];
|
||||
const rad_buf y = X.op_sc ? X.in : X.a;
|
||||
RAD_ISSUE_N(c, E.op_dn, R[L + 1], brows(E.a, R[L]), RAD_W(E.dnw), RAD_W(E.dnb),
|
||||
gg[L], RAD_NONE, brows(y, R[L + 1]));
|
||||
}
|
||||
}
|
||||
RAD_ISSUE_N(c, m.op_ve_nout, R5, brows(m.v_lv[5].a, R5), RAD_W(m.ve_now), RAD_W(m.ve_nob),
|
||||
RAD_NONE, st, brows(m.v_lv[5].b, R5));
|
||||
RAD_ISSUE_N(c, m.op_ve_cout, R5, brows(m.v_lv[5].b, R5), RAD_W(m.ve_coutw),
|
||||
RAD_W(m.ve_coutb), gg[5], RAD_NONE, brows(m.b_eq48, R5));
|
||||
RAD_ISSUE_N(c, m.op_ve_q, R5, brows(m.b_eq48, R5), RAD_W(m.ve_qw), RAD_W(m.ve_qb), gg[5],
|
||||
RAD_NONE, brow_slice(m.b_eqt, T.mrow, R5, 48));
|
||||
/* Skip the origin and extents in the tile plan to reach the volume geometries. */
|
||||
step_venc_volume(c, m, tp + 22 * (int64_t)t + 4, 1, th, tw,
|
||||
brow_slice(m.b_vtile, T.prow, Rpix, 3), brow_slice(m.b_eqt, T.mrow, R5, 48));
|
||||
}
|
||||
/* The blend over the canvas (gd's level-4/5 entry, in latents), then the plain path's fold:
|
||||
* the canvas has a one-clip encode's b_eq2 layout. */
|
||||
@@ -3873,65 +3916,19 @@ static void step_venc(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
rad_step_fail(c, "minimaxh3: a Vencode pass whose latents overflow the lane's slot");
|
||||
return;
|
||||
}
|
||||
const RadOperand st = RAD_B(m.b_egn);
|
||||
/* Each level's volume in the geometry; the last two levels have no downsampler between
|
||||
* them. */
|
||||
static const int kVOrg[6] = { 0, 3, 6, 9, 12, 12 };
|
||||
int64_t frow = row0;
|
||||
/* A one-frame media larger than a tile goes through the tiled path, as vae.py tiles its image
|
||||
* encodes; a clip never does, since venc_geom bounds its sides to kEncMaxSide. */
|
||||
const bool tiled = V->enc_frames == 1 && (H / kVaeRatio > kTile || W / kVaeRatio > kTile);
|
||||
if (tiled)
|
||||
frow = step_venc_tiled(c, V, m, gd, H, W, ppc, st, row0);
|
||||
frow = step_venc_tiled(c, V, m, gd, H, W, ppc, row0);
|
||||
else
|
||||
for (int64_t cc = 0; cc < n_clips; ++cc) {
|
||||
const bool last = cc == n_clips - 1;
|
||||
const int64_t R0 = (int64_t)g[0] * H * W;
|
||||
const RadOperand gg[6] = { praw(gd + kVOrg[0], RAD_I32, 3), praw(gd + kVOrg[1], RAD_I32, 3),
|
||||
praw(gd + kVOrg[2], RAD_I32, 3), praw(gd + kVOrg[3], RAD_I32, 3),
|
||||
praw(gd + kVOrg[4], RAD_I32, 3), praw(gd + kVOrg[5], RAD_I32, 3) };
|
||||
RAD_ISSUE_N(c, m.op_ve_pix, R0, praw2(V->enc_pixels + cc * R0 * 3, RAD_F32, R0, 3),
|
||||
brows(m.b_epix32, R0));
|
||||
RAD_ISSUE_N(c, m.op_ve_pcast, R0, brows(m.b_epix32, R0), brows(m.b_epix, R0));
|
||||
RAD_ISSUE_N(c, m.op_ve_cin, R0, brows(m.b_epix, R0), RAD_W(m.ve_cinw), RAD_W(m.ve_cinb),
|
||||
gg[0], RAD_NONE, brows(m.v_lv[0].a, R0));
|
||||
for (int L = 0; L < 6; ++L) {
|
||||
const Model::VEncLevel& E = m.v_lv[(size_t)L];
|
||||
const int64_t R = (int64_t)g[kVOrg[L]] * g[kVOrg[L] + 1] * g[kVOrg[L] + 2];
|
||||
const bool sc = E.op_sc;
|
||||
for (int blk = 0; blk < 2; ++blk) {
|
||||
const Model::VEncBlock& B = E.blk[blk];
|
||||
const bool f0 = blk == 0 && sc;
|
||||
const rad_buf xa = f0 ? E.in : E.a, nb = f0 ? E.in : E.b;
|
||||
/* The shortcut convolves the raw input, so it runs before norm1 normalises `in` in
|
||||
* place. */
|
||||
if (f0)
|
||||
RAD_ISSUE_N(c, E.op_sc, R, brows(E.in, R), RAD_W(E.scw), RAD_W(E.scb), gg[L],
|
||||
RAD_NONE, brows(E.a, R));
|
||||
RAD_ISSUE_N(c, B.op_n1, R, brows(xa, R), RAD_W(B.n1w), RAD_W(B.n1b), RAD_NONE, st,
|
||||
brows(nb, R));
|
||||
RAD_ISSUE_N(c, B.op_c1, R, brows(nb, R), RAD_W(B.c1w), RAD_W(B.c1b), gg[L],
|
||||
RAD_NONE, brows(E.c, R));
|
||||
RAD_ISSUE_N(c, B.op_n2, R, brows(E.c, R), RAD_W(B.n2w), RAD_W(B.n2b), RAD_NONE, st,
|
||||
brows(E.b, R));
|
||||
RAD_ISSUE_N(c, B.op_c2, R, brows(E.b, R), RAD_W(B.c2w), RAD_W(B.c2b), gg[L],
|
||||
brows(E.a, R), brows(E.a, R));
|
||||
}
|
||||
if (L < 4) {
|
||||
const Model::VEncLevel& X = m.v_lv[(size_t)L + 1];
|
||||
const int64_t RX = (int64_t)g[3 * (L + 1)] * g[3 * (L + 1) + 1] * g[3 * (L + 1) + 2];
|
||||
const rad_buf y = X.op_sc ? X.in : X.a;
|
||||
RAD_ISSUE_N(c, E.op_dn, RX, brows(E.a, R), RAD_W(E.dnw), RAD_W(E.dnb), gg[L],
|
||||
RAD_NONE, brows(y, RX));
|
||||
}
|
||||
}
|
||||
const int64_t R5 = (int64_t)g[12] * g[13] * g[14];
|
||||
RAD_ISSUE_N(c, m.op_ve_nout, R5, brows(m.v_lv[5].a, R5), RAD_W(m.ve_now), RAD_W(m.ve_nob),
|
||||
RAD_NONE, st, brows(m.v_lv[5].b, R5));
|
||||
RAD_ISSUE_N(c, m.op_ve_cout, R5, brows(m.v_lv[5].b, R5), RAD_W(m.ve_coutw),
|
||||
RAD_W(m.ve_coutb), gg[5], RAD_NONE, brows(m.b_eq48, R5));
|
||||
RAD_ISSUE_N(c, m.op_ve_q, R5, brows(m.b_eq48, R5), RAD_W(m.ve_qw), RAD_W(m.ve_qb), gg[5],
|
||||
RAD_NONE, brows(m.b_eq2, R5));
|
||||
step_venc_volume(c, m, gd, g[0], H, W,
|
||||
praw2(V->enc_pixels + cc * R0 * 3, RAD_F32, R0, 3), brows(m.b_eq2, R5));
|
||||
const int64_t flat = last ? short_last : full;
|
||||
RAD_ISSUE_N(c, m.op_ve_fold, flat * ppc,
|
||||
bcol(m.b_eq2, 0, kC, flat * (H / kVaeRatio) * (W / kVaeRatio)),
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/mossimage -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(mossimage LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(mossimage architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/mossimage.cpp)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -52,6 +52,7 @@
|
||||
#include <arch/rad_block_attn_gated.h>
|
||||
#include <arch/rad_block_dflash2.h>
|
||||
#include <arch/rad_block_gdn.h>
|
||||
#include <arch/rad_block_hc.h>
|
||||
#include <arch/rad_block_mlp.h>
|
||||
#include <arch/rad_block_vit.h>
|
||||
#include <arch/rad_calib_full.h>
|
||||
@@ -98,6 +99,7 @@ struct Layer {
|
||||
AttnGatedBF16 attn;
|
||||
GdnBF16 gdn;
|
||||
MlpBF16 mlp;
|
||||
HcProject proj;
|
||||
/* The layer's calibration inputs (rad_calib_full.h): the attention or delta net's, its output
|
||||
* projection's, the feed-forward's and down_proj's; -1 where the run does not record it. */
|
||||
int cs_in = -1, cs_o = -1, cs_mlp = -1, cs_down = -1;
|
||||
@@ -113,7 +115,7 @@ struct Model {
|
||||
rad_kvgroup kv_full = 0, kv_state = 0, kv_conv = 0;
|
||||
|
||||
/* the residual stream and the two vocabulary edges */
|
||||
rad_buf b_x = 0, b_h = 0, b_hout = 0, b_logits = 0;
|
||||
rad_buf b_x = 0, b_h = 0, b_hout = 0, b_logits = 0, b_proj_on = 0;
|
||||
/* full attention */
|
||||
rad_buf b_qg = 0, b_k = 0, b_v = 0, b_q = 0, b_gate = 0, b_attn = 0;
|
||||
/* gated delta net */
|
||||
@@ -663,7 +665,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
*
|
||||
* Not under calibration (--calib-dir): step() issues each block's input norm ahead of the
|
||||
* block for the tap, which a folded norm would turn into a second all-reduce and add. */
|
||||
const bool fold_ar = g.world == 2 && rad_op_declared(b, "ar_rmsnorm") && !m.calib.on;
|
||||
m.b_proj_on = HcProject::declare_mask(b, nm.f("projection_on"), g, ctx->cvec);
|
||||
const bool fold_ar = g.world == 2 && rad_op_declared(b, "ar_rmsnorm") && !m.calib.on &&
|
||||
!m.b_proj_on;
|
||||
|
||||
m.layers.resize((size_t)m.n_main);
|
||||
for (int64_t l = 0; l < m.n_main; ++l) {
|
||||
@@ -727,6 +731,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
ms.down = nm.ckpt("%s.%lld.mlp.down_proj.weight", pre, (long long)l);
|
||||
RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw, ms, fold_ar, !fold_ar || f.mlp_add,
|
||||
fold_ar, fold_ar && f.mlp_ar_out));
|
||||
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));
|
||||
if (m.calib.records(l)) {
|
||||
const std::string L = std::string(pre) + "." + std::to_string(l);
|
||||
lay.cs_mlp = (int)m.calib.sites.size();
|
||||
@@ -901,6 +907,7 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
}
|
||||
l.mlp.step(c, batch);
|
||||
if (l.cs_down >= 0) m.calib.tap(c, (size_t)l.cs_down, T);
|
||||
l.proj.step(c, batch, 0, T);
|
||||
|
||||
/* The tap, after the layer: the drafter conditions on this layer's output, which the next
|
||||
* layer overwrites, so the rows are copied into this tap's column slice now. */
|
||||
@@ -950,6 +957,7 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
out->chain_pays = RAD_CHAIN_ALWAYS;
|
||||
out->control_vector_ok = 1;
|
||||
const char* da = rad_meta_gets(meta, "draft.architectures", "");
|
||||
if (da && std::strstr(da, "DFlash2")) {
|
||||
const long long bs = rad_meta_geti(meta, "draft.dflash_config.block_size", 8);
|
||||
|
||||
@@ -80,6 +80,7 @@
|
||||
#include <arch/rad_arch.h>
|
||||
#include <arch/rad_block_attn_gated_q.h>
|
||||
#include <arch/rad_block_gdn_q.h>
|
||||
#include <arch/rad_block_hc.h>
|
||||
#include <arch/rad_calib_full.h>
|
||||
#include <arch/rad_block_mlp_q.h>
|
||||
#if QWEN35_MOE
|
||||
@@ -127,6 +128,7 @@ struct Layer {
|
||||
AttnGatedQ attn;
|
||||
GdnQ gdn;
|
||||
Ffn mlp;
|
||||
HcProject proj;
|
||||
/* gate_up's leading bytes beside the mixer's reduction, the next layer's first projection's
|
||||
* beside the feed-forward's; 0 where none is declared. */
|
||||
rad_op op_pf_gu = 0, op_pf_next = 0;
|
||||
@@ -152,7 +154,7 @@ struct Model {
|
||||
int64_t trunk_g8 = RAD_SCALE_GROUP;
|
||||
|
||||
/* the residual stream and the two vocabulary edges */
|
||||
rad_buf b_x = 0, b_hout = 0, b_logits = 0;
|
||||
rad_buf b_x = 0, b_hout = 0, b_logits = 0, b_proj_on = 0;
|
||||
ActQ a_h{};
|
||||
/* full attention */
|
||||
rad_buf b_qg = 0, b_k = 0, b_v = 0, b_q = 0;
|
||||
@@ -1097,6 +1099,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_ARCH_TRY(rad_lane1_window_begin(b));
|
||||
if (g.world > 1)
|
||||
m.op_embed_ar = decl_all_reduce_exact(b, g, m.b_x);
|
||||
m.b_proj_on = HcProject::declare_mask(b, nm.f("projection_on"), g, ctx->cvec);
|
||||
#if !QWEN35_MOE
|
||||
/* The pipelined prefill (step_pipelined), at two ranks wherever a step can be wide enough.
|
||||
* Its second lane needs a narrow `overlap` all-reduce beside the GEMMs; two ranks is the only
|
||||
@@ -1114,7 +1117,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
fprintf(stderr, "radiance: qwen35: the pipelined prefill stays off on this trunk: its norms "
|
||||
"write rotated int8 codes, which the pipeline's boundary norms do not\n");
|
||||
} else {
|
||||
m.pipe_on = g.world == 2 && g.max_tok >= kPipeMinRows;
|
||||
m.pipe_on = g.world == 2 && g.max_tok >= kPipeMinRows && !m.b_proj_on;
|
||||
}
|
||||
if (m.pipe_on) {
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_x));
|
||||
@@ -1196,7 +1199,15 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
lay.attn.ar_overlap = lay.gdn.ar_overlap = lay.mlp.ar_overlap = m.pipe_on ? 1 : 0;
|
||||
#endif
|
||||
|
||||
const LayerFold f = layer_fold(g, l, m.n_main, m.tap_layer, m.n_taps, m.op_embed_ar != 0);
|
||||
LayerFold f = layer_fold(g, l, m.n_main, m.tap_layer, m.n_taps, m.op_embed_ar != 0);
|
||||
if (m.b_proj_on && ctx->cvec && ctx->cvec->scales) {
|
||||
const bool steered = l > 0 && l < ctx->cvec->n_layers &&
|
||||
ctx->cvec->scales[(size_t)l] != 0.0f;
|
||||
const bool prev_steered = l > 1 && (l - 1) < ctx->cvec->n_layers &&
|
||||
ctx->cvec->scales[(size_t)(l - 1)] != 0.0f;
|
||||
if (prev_steered) { f.mix_fold = false; f.mix_ar_in = kArNone; }
|
||||
if (steered) { f.mlp_add = true; f.mlp_ar_out = false; }
|
||||
}
|
||||
lay.attn.tree = lay.gdn.tree = tree_want;
|
||||
|
||||
const char* pre = "model.language_model.layers";
|
||||
@@ -1253,6 +1264,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
#endif
|
||||
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));
|
||||
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));
|
||||
#if !QWEN35_MOE
|
||||
if (m.calib.records(l)) {
|
||||
/* The codes each int8 GEMM reads, in the domain its weight is stored in (i8_rot). */
|
||||
@@ -1850,6 +1863,7 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
if (l.cs_down >= 0) m.calib.tap(c, (size_t)l.cs_down, batch->n_tok);
|
||||
prefetch_beside(c, l.op_pf_next, l.pf_next_w, pf_h);
|
||||
dbg_resid(c, (int)li, "ffn", m.g.n_embd, m.b_x, m.a_h.x);
|
||||
l.proj.step(c, batch, 0, batch->n_tok);
|
||||
|
||||
/* The tap, after the layer: the drafter conditions on this layer's output, which the next
|
||||
* layer overwrites, so the rows are copied into this tap's column slice now. */
|
||||
@@ -1895,6 +1909,7 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
/* The delta-net state cache is declared at RadBuildCtx::state_dtype. */
|
||||
out->state_f16_ok = 1;
|
||||
out->control_vector_ok = 1;
|
||||
#if QWEN35_W8A8 && !QWEN35_MOE
|
||||
/* Chained launches pay on an int8 or a trellis trunk with and without its drafter: every
|
||||
* kernel of its decode chain has a chained form (libr4d's rad_kernel_chain), the two-rank
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(qwen3_embed LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(qwen3_embed architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/qwen3_embed.cpp)
|
||||
rad_add_plugin(qwen3_embed_ffn_iq8r architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/qwen3_embed.cpp)
|
||||
target_compile_definitions(qwen3_embed_ffn_iq8r PRIVATE RAD_QWEN3_EMBED_FFN_IQ8R)
|
||||
@@ -0,0 +1,278 @@
|
||||
/* Qwen3 retrieval: a causal backbone, last-token pooling, and an optional
|
||||
* two-row vocabulary head. Whole sequences share one prefill, without KV.
|
||||
* The endpoint normalises embeddings; rerank scores are already probabilities. */
|
||||
#include <arch/rad_linear.h>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
namespace qwen3_embed {
|
||||
using namespace rad::arch;
|
||||
#ifdef RAD_QWEN3_EMBED_FFN_IQ8R
|
||||
constexpr bool ffn_iq8r = true;
|
||||
constexpr char quant[] = "w8a8_ffn_fwht128";
|
||||
#else
|
||||
constexpr bool ffn_iq8r = false;
|
||||
constexpr char quant[] = "";
|
||||
#endif
|
||||
|
||||
struct Layer {
|
||||
rad_weight norm = 0, ff_norm = 0, qkv = 0, qnorm = 0, knorm = 0, out = 0;
|
||||
LinearQ gate_up, down;
|
||||
rad_op pre = 0, project = 0, qk_norm = 0, rotary = 0, attn = 0, output = 0, add = 0;
|
||||
rad_op pre_ff = 0, silu = 0, mul = 0, add_ff = 0;
|
||||
};
|
||||
struct Model {
|
||||
Geom g{};
|
||||
bool rerank = false;
|
||||
ActQ ff_input, ff_product;
|
||||
rad_buf x = 0, h = 0, qkv = 0, a = 0, o = 0, gu = 0, ff = 0;
|
||||
rad_buf final = 0, last = 0, logits = 0, probs = 0, pooled = 0;
|
||||
rad_weight tok = 0, norm = 0, head = 0;
|
||||
rad_op embed = 0, final_norm = 0, gather = 0, project = 0, softmax = 0, cast = 0;
|
||||
std::vector<Layer> layers;
|
||||
};
|
||||
static Model models[RAD_MAX_SLOTS];
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx || ctx->rank < 0 || rad_build_slot(ctx) >= RAD_MAX_SLOTS ||
|
||||
ctx->max_seqs <= 0 || ctx->max_ctx <= 0) return RAD_E_INVAL;
|
||||
// rad-convert declares with a nonzero speculative capacity to include optional heads.
|
||||
// A pooled graph has no sampler or draft head; that capacity does not alter its weights.
|
||||
if (ctx->world_size > 1 || ctx->rank || ctx->is_draft ||
|
||||
ctx->max_audio_frames > 0 || std::strcmp(meta->quant ? meta->quant : "", quant)) return RAD_E_UNSUPPORTED;
|
||||
if (std::strcmp(rad_meta_gets(meta, "model_type", ""), "qwen3") ||
|
||||
std::strcmp(rad_meta_gets(meta, "hidden_act", "silu"), "silu") ||
|
||||
rad_meta_geti(meta, "attention_bias", 0) || rad_meta_geti(meta, "use_sliding_window", 0))
|
||||
return RAD_E_UNSUPPORTED;
|
||||
// Do not mistake a generative Qwen3 checkpoint for a retrieval model.
|
||||
const char* role = rad_meta_gets(meta, "retrieval.type", "");
|
||||
const bool rerank = !std::strcmp(role, "rerank");
|
||||
if (!rerank && std::strcmp(role, "embedding")) {
|
||||
std::fprintf(stderr, "radiance: qwen3 retrieval requires pooling/LogitScore metadata or "
|
||||
"an explicit retrieval.type=embedding|rerank\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (!rerank) {
|
||||
if (!rad_meta_geti(meta, "pooling.pooling_mode_lasttoken", 1)) return RAD_E_UNSUPPORTED;
|
||||
for (const char* key : {"pooling.pooling_mode_cls_token", "pooling.pooling_mode_mean_tokens",
|
||||
"pooling.pooling_mode_max_tokens", "pooling.pooling_mode_mean_sqrt_len_tokens",
|
||||
"pooling.pooling_mode_weightedmean_tokens"})
|
||||
if (rad_meta_geti(meta, key, 0)) return RAD_E_UNSUPPORTED;
|
||||
if (rad_meta_geti(meta, "pooling.word_embedding_dimension", meta->n_embd) != meta->n_embd ||
|
||||
!rad_meta_geti(meta, "pooling.include_prompt", 1)) return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const char* scaling = rad_meta_gets(meta, "rope_scaling.rope_type",
|
||||
rad_meta_gets(meta, "rope_scaling.type", rad_meta_gets(meta, "rope_parameters.rope_type", "default")));
|
||||
if (std::strcmp(scaling, "default")) return RAD_E_UNSUPPORTED;
|
||||
if (meta->n_ctx_train <= 0 || ctx->max_ctx > meta->n_ctx_train) return RAD_E_INVAL;
|
||||
Model& m = models[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.rerank = rerank;
|
||||
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
|
||||
m.g.w_bf16 = !ffn_iq8r;
|
||||
const Geom& g = m.g;
|
||||
if (g.n_head_kv <= 0 || g.n_head % g.n_head_kv || g.head_dim % 2) return RAD_E_INVAL;
|
||||
Names nm(ctx->scope), src(rerank ? "model" : "");
|
||||
const int64_t T = g.max_tok, S = g.max_seqs, E = g.n_embd, Q = g.q_dim(), K = g.kv_dim(), F = g.n_ff;
|
||||
m.x = decl_b(b, nm.f("x"), RAD_BF16, {T, E});
|
||||
m.h = decl_b(b, nm.f("h"), RAD_BF16, {T, E});
|
||||
m.qkv = decl_b(b, nm.f("qkv"), RAD_BF16, {T, Q + 2 * K});
|
||||
m.a = decl_b(b, nm.f("attn"), RAD_BF16, {T, Q});
|
||||
m.o = decl_b(b, nm.f("o"), RAD_BF16, {T, E});
|
||||
m.gu = decl_b(b, nm.f("gate_up"), RAD_BF16, {T, 2 * F});
|
||||
m.ff = decl_b(b, nm.f("ff"), RAD_BF16, {T, F});
|
||||
m.ff_input.x = m.h;
|
||||
m.ff_product.x = m.ff;
|
||||
if constexpr (ffn_iq8r) {
|
||||
RAD_ARCH_TRY(m.ff_input.declare_qs(b, nm, g, "ff_input", E, T, true, false));
|
||||
RAD_ARCH_TRY(m.ff_product.declare_qs(b, nm, g, "ff_product", F, T, true, false));
|
||||
}
|
||||
// Store final states starting at row 1: cu[s+1] then directly indexes the last
|
||||
// token. Row 0 is never read. This avoids a host readback or an index kernel.
|
||||
m.final = decl_b(b, nm.f("final"), RAD_BF16, {T + 1, E});
|
||||
m.last = decl_b(b, nm.f("last"), RAD_BF16, {S, E});
|
||||
m.pooled = decl_b(b, nm.f("pooled"), RAD_F32, {S, rerank ? 1 : E}, RAD_BUF_PERSIST);
|
||||
RAD_ARCH_TRY(rad_declare_pooled(b, m.pooled));
|
||||
auto weight = [&](const char* dest, const char* source, std::initializer_list<int64_t> shape,
|
||||
RadWeightGroup group, uint32_t dtype = RAD_BF16) {
|
||||
if (map_copy(b, dest, source) < 0) return rad_weight(0);
|
||||
return decl_w(b, dest, dtype, shape, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, group);
|
||||
};
|
||||
auto rms = [&](rad_weight w) {
|
||||
return RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E),
|
||||
RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")), RAD_WEIGHTS(w));
|
||||
};
|
||||
auto gemm = [&](int64_t n, int64_t k, rad_weight w) {
|
||||
return RAD_OP(b, "gemm_nt", RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("N", n),
|
||||
RAD_INT("K", k), RAD_STR("dtype", "bf16")), RAD_WEIGHTS(w));
|
||||
};
|
||||
auto ffn_linear = [&](LinearQ& linear, const char* base, int64_t n, int64_t k,
|
||||
RadWeightGroup group, std::initializer_list<const char*> sources,
|
||||
const ActQ& input, rad_buf output) -> int {
|
||||
if constexpr (ffn_iq8r) {
|
||||
RAD_ARCH_TRY(linear.probe(b, nm, g, base, sources));
|
||||
RadEncoding enc{};
|
||||
if (k % RAD_SCALE_GROUP || !weight_enc(b, nm.f("%s.weight", base), &enc) ||
|
||||
linear_w8h_form(enc) != W8hForm::I8 || enc.n_planes != 2) {
|
||||
std::fprintf(stderr, "radiance: %s.weight requires rotated INT8 with BF16 scales "
|
||||
"per 128 columns; use the Qwen3 FFN IQ8R recipe\n", base);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
}
|
||||
return linear.declare(b, nm, g, base, n, k, RAD_SHARD_NONE, group, sources, input, output);
|
||||
};
|
||||
auto unary = [&](const char* op, int64_t n) {
|
||||
return RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", n),
|
||||
RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS);
|
||||
};
|
||||
m.tok = weight(nm.f("token_embd.weight"), src.f("embed_tokens.weight"), {g.n_vocab, E}, grp_model());
|
||||
m.norm = weight(nm.f("output_norm.weight"), src.f("norm.weight"), {E}, grp_model(), RAD_F32);
|
||||
m.embed = rw(b, RAD_OP(b, "embed_lookup", RAD_PARAMS(RAD_RANGE("M", 1, T),
|
||||
RAD_INT("n_embd", E), RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(m.tok)), {}, {m.x});
|
||||
m.layers.resize(g.n_layer);
|
||||
for (int i = 0; i < g.n_layer; ++i) {
|
||||
Layer& l = m.layers[i];
|
||||
const auto group = grp_layer(i);
|
||||
l.norm = weight(nm.f("blk.%d.attn_norm.weight", i), src.f("layers.%d.input_layernorm.weight", i), {E}, group, RAD_F32);
|
||||
l.ff_norm = weight(nm.f("blk.%d.ffn_norm.weight", i), src.f("layers.%d.post_attention_layernorm.weight", i), {E}, group, RAD_F32);
|
||||
l.qnorm = weight(nm.f("blk.%d.q_norm.weight", i), src.f("layers.%d.self_attn.q_norm.weight", i), {g.head_dim}, group, RAD_F32);
|
||||
l.knorm = weight(nm.f("blk.%d.k_norm.weight", i), src.f("layers.%d.self_attn.k_norm.weight", i), {g.head_dim}, group, RAD_F32);
|
||||
RAD_ARCH_TRY(map_concat(b, nm.f("blk.%d.qkv.weight", i),
|
||||
{src.f("layers.%d.self_attn.q_proj.weight", i), src.f("layers.%d.self_attn.k_proj.weight", i),
|
||||
src.f("layers.%d.self_attn.v_proj.weight", i)}, 0));
|
||||
l.qkv = decl_w(b, nm.f("blk.%d.qkv.weight", i), RAD_BF16, {Q + 2 * K, E}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, group);
|
||||
l.out = weight(nm.f("blk.%d.attn_o.weight", i), src.f("layers.%d.self_attn.o_proj.weight", i), {E, Q}, group);
|
||||
l.pre = rw(b, rms(l.norm), {m.x}, {m.h});
|
||||
l.project = rw(b, gemm(Q + 2 * K, E, l.qkv), {m.h}, {m.qkv});
|
||||
l.qk_norm = rw(b, RAD_OP(b, "qk_norm_rope", RAD_PARAMS(RAD_RANGE("M", 1, T),
|
||||
RAD_INT("head_dim", g.head_dim), RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", g.n_head_kv),
|
||||
RAD_F64("theta", g.theta), RAD_F64("eps", g.eps), RAD_INT("rotary_dim", 0)),
|
||||
RAD_WEIGHTS(l.qnorm, l.knorm)), {m.qkv}, {m.qkv});
|
||||
// Qwen's rotary casts cos/sin and rounds each product before adding, as Ministral does.
|
||||
l.rotary = rw(b, RAD_OP(b, "ministral_rope", RAD_PARAMS(RAD_RANGE("M", 1, T),
|
||||
RAD_INT("head_dim", g.head_dim), RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", g.n_head_kv),
|
||||
RAD_F64("theta", g.theta), RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS), {m.qkv}, {m.qkv});
|
||||
l.attn = rw(b, RAD_OP(b, "attn_dense", RAD_PARAMS(RAD_RANGE("M", 1, T),
|
||||
RAD_INT("head_dim", g.head_dim), RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("max_seqlen", std::min(T, g.max_ctx)), RAD_STR("dtype", "bf16"),
|
||||
RAD_F64("scale", 1.0 / std::sqrt(double(g.head_dim)))), RAD_NOWEIGHTS), {m.qkv}, {m.a});
|
||||
l.output = rw(b, gemm(E, Q, l.out), {m.a}, {m.o});
|
||||
l.add = rw(b, unary("add", E), {m.x, m.o}, {m.x});
|
||||
l.pre_ff = rw(b, rms(l.ff_norm), {m.x}, {m.h});
|
||||
RAD_ARCH_TRY(ffn_linear(l.gate_up, nm.f("blk.%d.gate_up", i), 2 * F, E, group,
|
||||
{src.f("layers.%d.mlp.gate_proj.weight", i), src.f("layers.%d.mlp.up_proj.weight", i)},
|
||||
m.ff_input, m.gu));
|
||||
// Transformers rounds SiLU before the product with up.
|
||||
l.silu = rw(b, unary("silu", F), {m.gu}, {m.gu});
|
||||
l.mul = rw(b, unary("mul", F), {m.gu}, {m.ff});
|
||||
RAD_ARCH_TRY(ffn_linear(l.down, nm.f("blk.%d.ffn_down", i), E, F, group,
|
||||
{src.f("layers.%d.mlp.down_proj.weight", i)}, m.ff_product, m.o));
|
||||
l.add_ff = rw(b, unary("add", E), {m.x, m.o}, {m.x});
|
||||
}
|
||||
m.final_norm = rw(b, rms(m.norm), {m.x}, {m.final});
|
||||
m.gather = rw(b, RAD_OP(b, "gather_rows", RAD_PARAMS(RAD_RANGE("M", 1, S),
|
||||
RAD_INT("n", E), RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS), {m.final}, {m.last});
|
||||
if (rerank) {
|
||||
const int64_t yes = rad_meta_geti(meta, "logit_score.true_token_id", -1);
|
||||
const int64_t no = rad_meta_geti(meta, "logit_score.false_token_id", -1);
|
||||
if (yes < 0 || no < 0 || yes >= g.n_vocab || no >= g.n_vocab || yes == no) return RAD_E_INVAL;
|
||||
const char* head = rad_meta_geti(meta, "tie_word_embeddings", 0)
|
||||
? src.f("embed_tokens.weight") : "lm_head.weight";
|
||||
RAD_ARCH_TRY(map_rows(b, nm.f("score.weight"),
|
||||
{{head, int(no), 1}, {head, int(yes), 1}}));
|
||||
m.head = decl_w(b, nm.f("score.weight"), RAD_BF16, {2, E}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
m.logits = decl_b(b, nm.f("scores"), RAD_F32, {S, 2});
|
||||
m.probs = decl_b(b, nm.f("probabilities"), RAD_F32, {S, 2});
|
||||
m.project = rw(b, RAD_OP(b, "logits_gemm", RAD_PARAMS(RAD_RANGE("M", 1, S),
|
||||
RAD_INT("n_vocab", 2), RAD_INT("n_embd", E), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(m.head)), {m.last}, {m.logits});
|
||||
m.softmax = rw(b, RAD_OP(b, "softmax", RAD_PARAMS(RAD_RANGE("M", 1, S),
|
||||
RAD_INT("n", 2), RAD_STR("dtype", "f32")), RAD_NOWEIGHTS), {m.logits}, {m.probs});
|
||||
m.cast = rw(b, RAD_OP(b, "cast", RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", 1),
|
||||
RAD_STR("from", "f32"), RAD_STR("to", "f32")), RAD_NOWEIGHTS), {m.probs}, {m.pooled});
|
||||
} else {
|
||||
m.cast = rw(b, RAD_OP(b, "cast", RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", E),
|
||||
RAD_STR("from", "bf16"), RAD_STR("to", "f32")), RAD_NOWEIGHTS), {m.last}, {m.pooled});
|
||||
}
|
||||
// Reject any recipe that quantises weights outside the supported FFN variant.
|
||||
auto plain = [&](const char* name, uint32_t dtype) -> int {
|
||||
RadEncoding enc{};
|
||||
const int rc = rad_weight_encoding(b, name, &enc, nullptr, nullptr);
|
||||
if (rc == RAD_E_NOTFOUND) return RAD_OK;
|
||||
const RadEncoding expected = rad_enc_plain(dtype);
|
||||
const RadEncoding bf16 = rad_enc_plain(RAD_BF16);
|
||||
if (rc == RAD_OK && dtype == RAD_F32 && rad_enc_equal(&enc, &bf16)) return RAD_OK;
|
||||
if (rc < 0) return rc;
|
||||
if (rad_enc_equal(&enc, &expected)) return RAD_OK;
|
||||
std::fprintf(stderr, "radiance: qwen3 retrieval cannot read the encoding of '%s'; "
|
||||
"keep this weight unquantised\n", name);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
};
|
||||
RAD_ARCH_TRY(plain(nm.f("token_embd.weight"), RAD_BF16));
|
||||
RAD_ARCH_TRY(plain(nm.f("output_norm.weight"), RAD_F32));
|
||||
if (rerank) RAD_ARCH_TRY(plain(nm.f("score.weight"), RAD_BF16));
|
||||
for (int i = 0; i < g.n_layer; ++i) {
|
||||
for (const char* s : {"qkv", "attn_o"})
|
||||
RAD_ARCH_TRY(plain(nm.f("blk.%d.%s.weight", i, s), RAD_BF16));
|
||||
if constexpr (!ffn_iq8r) {
|
||||
RAD_ARCH_TRY(plain(nm.f("blk.%d.gate_up.weight", i), RAD_BF16));
|
||||
RAD_ARCH_TRY(plain(nm.f("blk.%d.ffn_down.weight", i), RAD_BF16));
|
||||
}
|
||||
for (const char* s : {"attn_norm", "ffn_norm", "q_norm", "k_norm"})
|
||||
RAD_ARCH_TRY(plain(nm.f("blk.%d.%s.weight", i, s), RAD_F32));
|
||||
}
|
||||
rad_note(b, "Qwen3 %s %s, causal last-token pooling, TP1", ffn_iq8r ? "FFN IQ8R" : "BF16", role);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = models[rad_slot(c)];
|
||||
const Geom& g = m.g;
|
||||
const int64_t T = batch->n_tok, S = batch->n_seq, Q = g.q_dim(), K = g.kv_dim(), E = g.n_embd;
|
||||
if (batch->phase != RAD_PHASE_PREFILL || batch->enc || batch->n_mm_rows || T <= 0 || T > g.max_tok ||
|
||||
S <= 0 || S > g.max_seqs || batch->max_q_len > g.max_ctx || !batch->token_ids ||
|
||||
!batch->positions || !batch->cu_seqlens) {
|
||||
rad_step_fail(c, "qwen3 retrieval requires whole text sequences within the declared bounds");
|
||||
return;
|
||||
}
|
||||
const auto pos = praw(batch->positions, RAD_I32, T), cu = praw(batch->cu_seqlens, RAD_I32, S + 1);
|
||||
RAD_ISSUE(c, m.embed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.tok), brows(m.x, T));
|
||||
for (const Layer& l : m.layers) {
|
||||
RAD_ISSUE(c, l.pre, brows(m.x, T), RAD_W(l.norm), brows(m.h, T));
|
||||
RAD_ISSUE(c, l.project, brows(m.h, T), RAD_W(l.qkv), brows(m.qkv, T));
|
||||
RAD_ISSUE(c, l.qk_norm, brows(m.qkv, T), RAD_NONE, RAD_W(l.qnorm), RAD_W(l.knorm));
|
||||
RAD_ISSUE(c, l.rotary, brows(m.qkv, T), pos);
|
||||
RAD_ISSUE(c, l.attn, bcol(m.qkv, 0, Q, T), bcol(m.qkv, Q, K, T), bcol(m.qkv, Q + K, K, T), cu, brows(m.a, T));
|
||||
RAD_ISSUE(c, l.output, brows(m.a, T), RAD_W(l.out), brows(m.o, T));
|
||||
RAD_ISSUE(c, l.add, brows(m.x, T), brows(m.o, T), brows(m.x, T));
|
||||
RAD_ISSUE(c, l.pre_ff, brows(m.x, T), RAD_W(l.ff_norm), brows(m.h, T));
|
||||
l.gate_up.step(c, m.ff_input, m.gu, T);
|
||||
RAD_ISSUE(c, l.silu, bcol(m.gu, 0, g.n_ff, T), bcol(m.gu, 0, g.n_ff, T));
|
||||
RAD_ISSUE(c, l.mul, bcol(m.gu, 0, g.n_ff, T), bcol(m.gu, g.n_ff, g.n_ff, T), brows(m.ff, T));
|
||||
l.down.step(c, m.ff_product, m.o, T);
|
||||
RAD_ISSUE(c, l.add_ff, brows(m.x, T), brows(m.o, T), brows(m.x, T));
|
||||
}
|
||||
RAD_ISSUE_N(c, m.final_norm, T, brows(m.x, T), RAD_W(m.norm), brow_slice(m.final, 1, T, E));
|
||||
RAD_ISSUE_N(c, m.gather, S, brows(m.final, T + 1), praw(batch->cu_seqlens + 1, RAD_I32, S), brows(m.last, S));
|
||||
if (m.rerank) {
|
||||
RAD_ISSUE_N(c, m.project, S, brows(m.last, S), RAD_W(m.head), brows(m.logits, S));
|
||||
RAD_ISSUE_N(c, m.softmax, S, brows(m.logits, S), brows(m.probs, S));
|
||||
RAD_ISSUE_N(c, m.cast, S, bcol(m.probs, 1, 1, S), brows(m.pooled, S));
|
||||
} else {
|
||||
RAD_ISSUE_N(c, m.cast, S, brows(m.last, S), brows(m.pooled, S));
|
||||
}
|
||||
}
|
||||
} // namespace qwen3_embed
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
#ifdef RAD_QWEN3_EMBED_FFN_IQ8R
|
||||
namespace qwen3_embed_ffn_iq8r = qwen3_embed;
|
||||
RAD_ARCH_PLUGIN(qwen3_embed_ffn_iq8r, "qwen3", qwen3_embed::quant, "0.1.0",
|
||||
"Qwen3 FFN IQ8R text embeddings and reranking, TP1")
|
||||
#else
|
||||
RAD_ARCH_PLUGIN(qwen3_embed, "qwen3", "", "0.1.0", "Qwen3 BF16 text embeddings and reranking, TP1")
|
||||
#endif
|
||||
#endif
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/qwen3vl -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(qwen3vl LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(qwen3vl architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/qwen3vl.cpp)
|
||||
@@ -0,0 +1,297 @@
|
||||
/* Qwen3-VL dense decoder: per-head Q/K normalization, interleaved M-RoPE,
|
||||
* and request-owned vision DeepStack additions after the first decoder layers.
|
||||
* The text linears accept BF16 reference weights or the generic quantized grids;
|
||||
* the initial W4A8 recipe matches Gemma's signed INT4/F16 group-scale format. */
|
||||
#include <arch/rad_arch.h>
|
||||
#include <arch/rad_block_attn_q.h>
|
||||
#include <arch/rad_block_mlp_q.h>
|
||||
#include <arch/rad_block_vit.h>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
namespace qwen3vl {
|
||||
using namespace rad::arch;
|
||||
struct Layer { AttnQ attn; MlpQ mlp; };
|
||||
struct Model {
|
||||
Names nm{""}; Geom g{};
|
||||
int64_t n_main = 0, n_rot = 0, trunk_g8 = RAD_SCALE_GROUP;
|
||||
bool trunk_i8 = false, explicit_bf16_or_row_i8 = false, media = false;
|
||||
rad_kvgroup kv_full = 0;
|
||||
rad_buf b_x = 0, b_hout = 0, b_logits = 0, b_qkv = 0, b_q = 0, b_k = 0, b_gate_up = 0;
|
||||
ActQ a_h{}, a_attn{}, a_ffn{};
|
||||
rad_weight w_tok = 0, w_out_norm = 0, w_lm_head = 0;
|
||||
rad_op op_embed = 0, op_embed_ar = 0, op_final_norm = 0, op_gather = 0, op_logits = 0;
|
||||
rad_op op_deepstack[RAD_ENCODER_MAX_AUX] = {};
|
||||
VisionTower vit{}; MediaRows media_rows{};
|
||||
std::vector<Layer> layers;
|
||||
};
|
||||
static Model g_model[MAX_SLOTS];
|
||||
static int check_format(const RadModelMeta* meta) {
|
||||
if (meta->n_expert || (meta->quant && *meta->quant)) return RAD_E_UNSUPPORTED;
|
||||
return RAD_OK;
|
||||
}
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
/* Memory planning may redeclare at smaller token and encoder bounds. Those
|
||||
* temporary handles and dimensions must never replace the serving instance. */
|
||||
Model sizing_model;
|
||||
Model& m = ctx->shape_probe ? sizing_model : g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(check_format(meta));
|
||||
/* "bf16" is the activation dtype: everything but the two GEMM operands runs at it. */
|
||||
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
|
||||
|
||||
Geom& g = m.g;
|
||||
Names& nm = m.nm;
|
||||
m.n_main = g.n_layer;
|
||||
m.media = VisionTower::present(meta) && ctx->max_enc_patches > 0;
|
||||
/* Original Qwen3-VL checkpoints use rope_scaling, unlike newer Qwen3.5's
|
||||
* rope_parameters. Preserve the published sections and require interleaving. */
|
||||
const char* sections = rad_meta_gets(meta, "text_config.rope_scaling.mrope_section",
|
||||
rad_meta_gets(meta, "rope_scaling.mrope_section", ""));
|
||||
if (!g.rope_mc && *sections) {
|
||||
const int interleaved = rad_meta_geti(meta, "text_config.rope_scaling.mrope_interleaved",
|
||||
rad_meta_geti(meta, "rope_scaling.mrope_interleaved", 0));
|
||||
if (!interleaved || std::strlen(sections) >= sizeof g.rope_sections) return RAD_E_INVAL;
|
||||
g.rope_mc = true;
|
||||
std::snprintf(g.rope_mode, sizeof g.rope_mode, "imrope");
|
||||
std::snprintf(g.rope_sections, sizeof g.rope_sections, "%s", sections);
|
||||
}
|
||||
if (!g.rope_mc || std::strcmp(g.rope_mode, "imrope")) return RAD_E_UNSUPPORTED;
|
||||
|
||||
/* The rotary width is the whole head unless `partial_rotary_factor` says otherwise (Phi-style
|
||||
* models set it). A config that states nothing means the full head. */
|
||||
{
|
||||
double prf = rad_meta_getf(meta, "partial_rotary_factor", 0.0);
|
||||
if (!(prf > 0.0)) prf = rad_meta_getf(meta, "rope_parameters.partial_rotary_factor", 0.0);
|
||||
m.n_rot = prf > 0.0 ? (int64_t)(g.head_dim * prf) : g.head_dim;
|
||||
}
|
||||
if (m.n_rot <= 0 || m.n_rot > g.head_dim || (m.n_rot & 1)) {
|
||||
fprintf(stderr, "radiance: qwen3vl: rotary width %lld is not an even width inside head_dim "
|
||||
"%lld\n", (long long)m.n_rot, (long long)g.head_dim);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RAD_ARCH_TRY(yarn_from(g, meta, "", m.n_rot));
|
||||
|
||||
/* ---- the KV cache. One group: every layer is full attention. */
|
||||
RadKVGroupDecl fd{};
|
||||
fd.kind = RAD_KV_FULL;
|
||||
fd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16);
|
||||
fd.n_head_kv = g.n_head_kv;
|
||||
fd.head_dim = g.head_dim;
|
||||
m.kv_full = rad_decl_kv_group(b, nm.f("kv_attn"), &fd);
|
||||
g.kv_dtype = rad_dtype_name(fd.dtype);
|
||||
|
||||
/* ---- the trunk's stored format, read from the first layer's fused q|k|v before any
|
||||
* activation is declared: only an int8 trunk's activations carry an int8 code pair. The probe
|
||||
* maps the weight through the layer's own LinearQ, which then does not map it again; the
|
||||
* resize before the layer loop keeps the layers sized here. */
|
||||
const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim();
|
||||
m.layers.resize((size_t)m.n_main);
|
||||
if (m.n_main > 0) {
|
||||
const char* pre = "model.language_model.layers";
|
||||
RAD_ARCH_TRY(m.layers[0].attn.qkv.probe(
|
||||
b, nm, g, nm.f("blk.0.attn_qkv"),
|
||||
{ nm.ckpt("%s.0.self_attn.q_proj.weight", pre),
|
||||
nm.ckpt("%s.0.self_attn.k_proj.weight", pre),
|
||||
nm.ckpt("%s.0.self_attn.v_proj.weight", pre) }));
|
||||
RadEncoding enc{};
|
||||
m.explicit_bf16_or_row_i8 = weight_enc(b, nm.f("blk.0.attn_qkv.weight"), &enc) &&
|
||||
(rad_enc_is(&enc, "plain") || linear_is_row_i8(enc));
|
||||
m.trunk_i8 = weight_enc(b, nm.f("blk.0.attn_qkv.weight"), &enc) &&
|
||||
(linear_is_w8h(enc) || linear_is_wnh(enc));
|
||||
if (m.trunk_i8) m.trunk_g8 = linear_w8h_group(enc);
|
||||
}
|
||||
if (m.trunk_i8 && (g.n_embd % m.trunk_g8 || q_dim % m.trunk_g8 || g.n_ff % m.trunk_g8)) {
|
||||
fprintf(stderr, "radiance: qwen3vl: the int8 trunk keeps one scale a %lld of K, which does "
|
||||
"not divide this rank's widths (hidden %lld, attention %lld, "
|
||||
"feed-forward %lld)\n",
|
||||
(long long)m.trunk_g8, (long long)g.n_embd, (long long)q_dim, (long long)g.n_ff);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
/* ---- activations. An int8 trunk's quantisers sit in their producers where the kernels serve
|
||||
* the rotated forms: the norms write had_quant_act_i8g's codes for q|k|v and gate|up, the
|
||||
* gated product for the down projection, and the attention output's own quantiser for the
|
||||
* out-projection, so no projection declares one and the activation carries no E4M3 pair.
|
||||
* Where a form is not declared (the CPU kernels), the producer keeps its E4M3 pair and each
|
||||
* projection quantises its own input from the bf16 plane. */
|
||||
if (m.trunk_i8) {
|
||||
if (rad_op_declared(b, "rmsnorm_had_quant_i8g") &&
|
||||
(g.world != 2 || rad_op_declared(b, "ar_rmsnorm_had_quant_i8g")))
|
||||
m.a_h.q8_fed = m.a_h.q8_rot = true;
|
||||
if (rad_op_declared(b, "gated_had_quant_i8g")) m.a_ffn.q8_fed = m.a_ffn.q8_rot = true;
|
||||
if (rad_op_declared(b, "had_quant_act_i8g")) m.a_attn.q8_fed = m.a_attn.q8_rot = true;
|
||||
}
|
||||
m.b_x = decl_b(b, nm.f("x"), g.act_dtype, {g.max_tok, g.n_embd});
|
||||
m.a_h.x = decl_b(b, nm.f("h"), g.act_dtype, {g.max_tok, g.n_embd});
|
||||
if (!m.explicit_bf16_or_row_i8) RAD_ARCH_TRY(m.a_h.declare_qs(b, nm, g, "h", g.n_embd, 0, m.trunk_i8, !m.a_h.q8_fed,
|
||||
m.trunk_g8));
|
||||
m.b_qkv = decl_b(b, nm.f("attn_qkv"), g.act_dtype, {g.max_tok, q_dim + 2 * kv_dim});
|
||||
m.b_k = decl_b(b, nm.f("attn_k"), g.act_dtype, {g.max_tok, kv_dim});
|
||||
m.b_q = decl_b(b, nm.f("attn_q"), g.act_dtype, {g.max_tok, q_dim});
|
||||
m.a_attn.x = decl_b(b, nm.f("attn_out"), g.act_dtype, {g.max_tok, q_dim});
|
||||
if (!m.explicit_bf16_or_row_i8) RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", q_dim, 0, m.trunk_i8,
|
||||
!m.a_attn.q8_fed, m.trunk_g8));
|
||||
m.b_gate_up = decl_b(b, nm.f("gate_up"), g.act_dtype, {g.max_tok, 2 * g.n_ff});
|
||||
m.a_ffn.x = decl_b(b, nm.f("ffn"), g.act_dtype, {g.max_tok, g.n_ff});
|
||||
if (!m.explicit_bf16_or_row_i8) RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "ffn", g.n_ff, 0, m.trunk_i8, !m.a_ffn.q8_fed,
|
||||
m.trunk_g8));
|
||||
m.b_hout = decl_b(b, nm.f("h_out"), g.act_dtype, {g.max_logit_rows, g.n_embd});
|
||||
|
||||
m.b_logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab});
|
||||
RAD_ARCH_TRY(rad_declare_logits(b, m.b_logits));
|
||||
|
||||
/* ---- the vocabulary edges, both row-sharded with the vocabulary. A tied head is the
|
||||
* alternative source: without `lm_head.weight` the embedding table serves as both, as in small
|
||||
* LLaMA derivatives. The head is declared at its codes' dtype (bf16, or E4M3 where a recipe
|
||||
* made it block fp8), queried after its name map entry. */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("model.language_model.embed_tokens.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("model.language_model.norm.weight")));
|
||||
if (rad_meta_geti(meta, "tie_word_embeddings", 0))
|
||||
RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"),
|
||||
nm.ckpt("model.language_model.embed_tokens.weight")));
|
||||
else RAD_ARCH_TRY(map_copy(b, nm.f("output.weight"), nm.ckpt("lm_head.weight")));
|
||||
m.w_tok = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, {g.n_vocab, g.n_embd},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
|
||||
m.w_out_norm = decl_w(b, nm.f("output_norm.weight"), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
m.w_lm_head = decl_w(b, nm.f("output.weight"),
|
||||
weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16),
|
||||
{g.n_vocab, g.n_embd}, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
|
||||
|
||||
m.op_embed = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", g.n_embd),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype),
|
||||
RAD_INT("vocab_offset", g.vocab_off)),
|
||||
RAD_WEIGHTS(m.w_tok)),
|
||||
{}, {m.b_x});
|
||||
/* Always exact: each token's embedding comes from one rank and the others contribute zero, so
|
||||
* a lossy wire would only add error. */
|
||||
if (g.world > 1)
|
||||
m.op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_x}, {m.b_x});
|
||||
|
||||
/* Encoder passes run separately; the core retains all base and DeepStack rows. */
|
||||
if (m.media) {
|
||||
RAD_ARCH_TRY(m.vit.declare(b, meta, ctx, nm, g.n_embd, (int)g.n_layer + 64,
|
||||
true, false, "model.visual", true));
|
||||
if (m.vit.n_ds > g.n_layer) return RAD_E_INVAL;
|
||||
RAD_ARCH_TRY(m.media_rows.declare(b, g.max_tok, g.n_embd, m.b_x));
|
||||
}
|
||||
|
||||
AttnQ::Wire aw{};
|
||||
aw.x = m.b_x; aw.h = m.a_h; aw.qkv = m.b_qkv; aw.q = m.b_q; aw.k = m.b_k; aw.attn = m.a_attn;
|
||||
MlpQ::Wire mw{};
|
||||
mw.x = m.b_x; mw.h = m.a_h; mw.gate_up = m.b_gate_up; mw.ffn = m.a_ffn;
|
||||
|
||||
for (int64_t l = 0; l < m.n_main; ++l) {
|
||||
Layer& lay = m.layers[(size_t)l];
|
||||
/* Residual fold and collective placement: rad_linear.h, layer_fold. */
|
||||
/* DeepStack adds to a replicated, completed residual after each of the
|
||||
* first decoder layers. Keep both residual junctions explicit initially. */
|
||||
|
||||
const char* pre = "model.language_model.layers";
|
||||
AttnQ::Src as{};
|
||||
as.norm = nm.ckpt("%s.%lld.input_layernorm.weight", pre, (long long)l);
|
||||
as.q = nm.ckpt("%s.%lld.self_attn.q_proj.weight", pre, (long long)l);
|
||||
as.k = nm.ckpt("%s.%lld.self_attn.k_proj.weight", pre, (long long)l);
|
||||
as.v = nm.ckpt("%s.%lld.self_attn.v_proj.weight", pre, (long long)l);
|
||||
as.o = nm.ckpt("%s.%lld.self_attn.o_proj.weight", pre, (long long)l);
|
||||
as.q_norm = nm.ckpt("%s.%lld.self_attn.q_norm.weight", pre, (long long)l);
|
||||
as.k_norm = nm.ckpt("%s.%lld.self_attn.k_norm.weight", pre, (long long)l);
|
||||
lay.attn.mode = g.rope_mode;
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv_full));
|
||||
RAD_ARCH_TRY(lay.attn.declare(b, nm, g, (int)l, m.kv_full, m.n_rot, aw, as,
|
||||
false, true, kArNone, false));
|
||||
|
||||
MlpQ::Src ms{};
|
||||
ms.norm = nm.ckpt("%s.%lld.post_attention_layernorm.weight", pre, (long long)l);
|
||||
ms.gate = nm.ckpt("%s.%lld.mlp.gate_proj.weight", pre, (long long)l);
|
||||
ms.up = nm.ckpt("%s.%lld.mlp.up_proj.weight", pre, (long long)l);
|
||||
ms.down = nm.ckpt("%s.%lld.mlp.down_proj.weight", pre, (long long)l);
|
||||
lay.mlp.gq_ffn.silu_only = m.explicit_bf16_or_row_i8;
|
||||
RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw, ms, false, true, kArNone, false));
|
||||
if (m.media && l < m.vit.n_ds) {
|
||||
m.op_deepstack[l] = rw(b, RAD_OP(b, "scatter_add_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS), {m.b_x}, {m.b_x});
|
||||
if (!m.op_deepstack[l]) return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
|
||||
m.op_final_norm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(m.w_out_norm)),
|
||||
{m.b_x}, {m.a_h.x});
|
||||
m.op_gather = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
RAD_INT("n", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.a_h.x}, {m.b_hout});
|
||||
m.op_logits = rw(b, RAD_OP(b, "logits_gemm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
RAD_INT("n_vocab", g.n_vocab),
|
||||
RAD_INT("n_embd", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(m.w_lm_head)),
|
||||
{m.b_hout}, {m.b_logits});
|
||||
|
||||
rad_note(b, "Qwen3-VL: %lld full-attention layers, per-head Q/K norms, interleaved M-RoPE; "
|
||||
"%d request-owned DeepStack features", (long long)g.n_layer, m.vit.n_ds);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = g_model[rad_slot(c)];
|
||||
if (batch->enc) { m.vit.step(c, batch); return; }
|
||||
if (batch->draft_pass) { rad_step_fail(c, "Qwen3-VL has no paired drafter"); return; }
|
||||
if (batch->n_mm_rows && (batch->n_mm_aux != m.vit.n_ds || !m.media)) {
|
||||
rad_step_fail(c, "Qwen3-VL media rows lack their matching DeepStack planes"); return;
|
||||
}
|
||||
const int64_t rows = batch->n_tok;
|
||||
RAD_ISSUE(c, m.op_embed, praw(batch->token_ids, RAD_I32, rows), RAD_W(m.w_tok), brows(m.b_x, rows));
|
||||
if (m.media) m.media_rows.step(c, batch, m.b_x, rows);
|
||||
if (m.op_embed_ar)
|
||||
RAD_ISSUE_N(c, m.op_embed_ar, rows * m.g.n_embd, brows(m.b_x, rows), RAD_NONE);
|
||||
for (size_t layer = 0; layer < m.layers.size(); ++layer) {
|
||||
m.layers[layer].attn.step(c, batch);
|
||||
m.layers[layer].mlp.step(c, batch);
|
||||
if (batch->n_mm_rows && layer < (size_t)m.vit.n_ds) {
|
||||
/* Residual and tap are complete on every rank here, unlike the
|
||||
* rank-zero-only base embeddings before their vocabulary reduction. */
|
||||
if (!batch->mm_aux[layer]) { rad_step_fail(c, "Missing DeepStack plane"); return; }
|
||||
RAD_ISSUE_N(c, m.op_deepstack[layer], batch->n_mm_rows,
|
||||
praw2(batch->mm_aux[layer], RAD_BF16, batch->n_mm_rows, m.g.n_embd),
|
||||
praw(batch->mm_rows, RAD_I32, batch->n_mm_rows), brows(m.b_x, rows));
|
||||
}
|
||||
}
|
||||
RAD_ISSUE(c, m.op_final_norm, brows(m.b_x, rows), RAD_W(m.w_out_norm), brows(m.a_h.x, rows));
|
||||
if (batch->n_out) {
|
||||
RAD_ISSUE_N(c, m.op_gather, batch->n_out, brows(m.a_h.x, rows),
|
||||
praw(batch->out_ids, RAD_I32, batch->n_out), brows(m.b_hout, batch->n_out));
|
||||
RAD_ISSUE_N(c, m.op_logits, batch->n_out, brows(m.b_hout, batch->n_out),
|
||||
RAD_W(m.w_lm_head), brows(m.b_logits, batch->n_out));
|
||||
}
|
||||
}
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
out->draft_depth = 0;
|
||||
out->shape_probe_ok = 1;
|
||||
return RAD_OK;
|
||||
}
|
||||
} // namespace qwen3vl
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PROBE(qwen3vl)
|
||||
RAD_ARCH_PLUGIN(qwen3vl, "qwen3vl", "", "0.1.0",
|
||||
"Qwen3-VL dense text and vision, including request-owned DeepStack features")
|
||||
#endif
|
||||
@@ -727,7 +727,16 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
{
|
||||
RadKVGroupDecl fd{};
|
||||
fd.kind = RAD_KV_FULL;
|
||||
fd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16);
|
||||
/* The rotated int4 and int6 caches (abi/rad_kv_i4r.h) are served here: libr4d's head_dim
|
||||
* 256, 4-token page rows at six and twelve queries a KV head read them, and so do libref
|
||||
* and libavx. */
|
||||
fd.dtype = rad_kv_cache_dtype_i4r(ctx, RAD_BF16);
|
||||
if ((fd.dtype == RAD_I4R || fd.dtype == RAD_I6R) && g.head_dim != 256) {
|
||||
fprintf(stderr, "radiance: --kv-cache-dtype %s: the rotated cache's attention rows "
|
||||
"are at head_dim 256, this model's is %lld; i8 is the 8-bit cache\n",
|
||||
fd.dtype == RAD_I6R ? "i6r" : "i4r", (long long)g.head_dim);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
fd.n_head_kv = g.n_head_kv;
|
||||
fd.head_dim = g.head_dim;
|
||||
/* The MTP head's layer shares this group. */
|
||||
|
||||
@@ -25,7 +25,7 @@ set -e
|
||||
BUILD=
|
||||
CLEAN=0
|
||||
SAN=
|
||||
CMAKE_ARGS=""
|
||||
CMAKE_ARGS=${CMAKE_ARGS:-}
|
||||
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
|
||||
@@ -195,7 +195,8 @@ endfunction()
|
||||
# plugin should then skip itself with a message rather than fail the configure.
|
||||
function(rad_plugin_gpu_targets out)
|
||||
set(keep "")
|
||||
foreach(t ${RAD_GPU_TARGETS})
|
||||
string(REPLACE "\\;" ";" _rad_targets "${RAD_GPU_TARGETS}")
|
||||
foreach(t ${_rad_targets})
|
||||
foreach(pat ${ARGN})
|
||||
if(t MATCHES "${pat}")
|
||||
list(APPEND keep ${t})
|
||||
|
||||
@@ -152,6 +152,11 @@ public:
|
||||
int weight_shard_span(rad_weight w, int64_t lo, int64_t hi);
|
||||
int weight_shard_span_parts(rad_weight w, const int64_t* lo, const int64_t* hi,
|
||||
const int64_t* total, int n);
|
||||
int weight_row_order(rad_weight w, const int32_t* order, int64_t n);
|
||||
int expert_profile(int layer, float* share, int64_t n) const;
|
||||
/* --expert-profile's entries (layer, model-wide expert, share), which rad_expert_profile hands
|
||||
* the plugin. Set before the plugin declares; the caller keeps them alive. Null: none. */
|
||||
void set_expert_profile(const RadFileProfile* p, int64_t n) { profile_ = p; n_profile_ = n; }
|
||||
int kv_group_zero(rad_kvgroup g);
|
||||
int kv_group_dense_read(rad_kvgroup g);
|
||||
int kv_group_replicated(rad_kvgroup g);
|
||||
@@ -254,6 +259,8 @@ private:
|
||||
/* The model's answers, cached per source: a routed model declares each expert's codes and
|
||||
* scales as two weights over one source, and a checkpoint lookup walks the name map. */
|
||||
WeightSourceFn sources_;
|
||||
const RadFileProfile* profile_ = nullptr;
|
||||
int64_t n_profile_ = 0;
|
||||
std::unordered_map<std::string, std::pair<int, WeightSource>> source_cache_;
|
||||
int lookup_source(const std::string& name, WeightSource* out);
|
||||
|
||||
|
||||
@@ -335,6 +335,10 @@ rad_kvgroup Builder::decl_kv_group(const char* name, const RadKVGroupDecl* d) {
|
||||
if (!name || !*name || !d) return err(RAD_E_INVAL, "decl_kv_group: null name or declaration");
|
||||
if (d->kind < RAD_KV_FULL || d->kind > RAD_KV_RING)
|
||||
return err(RAD_E_INVAL, "kv group '%s': unknown kind %d", name, d->kind);
|
||||
/* rad_kv_cache_dtype's refusal (arch/common/rad_arch.h) arrives here as RAD_DT_INVALID. */
|
||||
if (d->dtype == RAD_DT_INVALID)
|
||||
return err(RAD_E_DTYPE, "kv group '%s': no dtype (a --kv-cache-dtype the plugin refused?)",
|
||||
name);
|
||||
|
||||
std::string n = scoped(name);
|
||||
for (size_t i = 1; i < prog_.kv_groups.size(); ++i)
|
||||
@@ -962,6 +966,53 @@ int Builder::weight_shard_span_parts(rad_weight h, const int64_t* lo, const int6
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* See rad_weight_row_order. The loader (format/share.cpp) holds the order to the entry's rows. */
|
||||
int Builder::weight_row_order(rad_weight h, const int32_t* order, int64_t n) {
|
||||
if (finished_) { err(RAD_E_STATE, "weight_row_order after declare finished"); return RAD_E_STATE; }
|
||||
if (h == 0 || h >= prog_.weights.size() || !order) return RAD_E_INVAL;
|
||||
WeightInfo& w = prog_.weights[h];
|
||||
const RadWeightDecl& d = w.decl;
|
||||
if (d.shard != RAD_SHARD_NONE || d.n_row_parts > 1 || d.source || d.planes) {
|
||||
err(RAD_E_INVAL, "weight '%s': a row order is for a whole weight of its own name "
|
||||
"(RAD_SHARD_NONE, no stacked parts, no view)", w.name.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (d.rank < 1 || n != d.shape[0] || rad_dtype_bits(d.dtype) < 8) {
|
||||
err(RAD_E_SHAPE, "weight '%s': a row order of %lld rows over a declared dim 0 of %lld (%s); "
|
||||
"it names every row once, of whole-byte elements", w.name.c_str(),
|
||||
(long long)n, d.rank >= 1 ? (long long)d.shape[0] : 0LL, rad_dtype_name(d.dtype));
|
||||
return RAD_E_SHAPE;
|
||||
}
|
||||
std::vector<uint8_t> seen((size_t)n, 0);
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
if (order[i] < 0 || order[i] >= n || seen[(size_t)order[i]]) {
|
||||
err(RAD_E_INVAL, "weight '%s': the row order is not a permutation of [0, %lld) "
|
||||
"(row %lld names %d)", w.name.c_str(), (long long)n, (long long)i,
|
||||
(int)order[i]);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
seen[(size_t)order[i]] = 1;
|
||||
}
|
||||
bool ident = true;
|
||||
for (int64_t i = 0; ident && i < n; ++i) ident = order[i] == i;
|
||||
if (ident) w.row_order.clear();
|
||||
else w.row_order.assign(order, order + n);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Builder::expert_profile(int layer, float* share, int64_t n) const {
|
||||
if (!share || n < 0) return RAD_E_INVAL;
|
||||
for (int64_t e = 0; e < n; ++e) share[e] = 0.0f;
|
||||
bool any = false;
|
||||
for (int64_t i = 0; i < n_profile_; ++i) {
|
||||
const RadFileProfile& p = profile_[i];
|
||||
if (p.layer != layer || p.expert < 0 || p.expert >= n) continue;
|
||||
share[p.expert] = p.share;
|
||||
any = true;
|
||||
}
|
||||
return any ? RAD_OK : RAD_E_NOTFOUND;
|
||||
}
|
||||
|
||||
int Builder::kv_group_zero(rad_kvgroup h) {
|
||||
if (finished_) { err(RAD_E_STATE, "kv_group_zero after declare finished"); return RAD_E_STATE; }
|
||||
if (h == 0 || h >= prog_.kv_groups.size()) return RAD_E_INVAL;
|
||||
@@ -1316,6 +1367,15 @@ int Builder::declare_encoder(const RadEncoderDecl* d) {
|
||||
(long long)want, (long long)d->merge);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (d->n_aux < 0 || d->n_aux > RAD_ENCODER_MAX_AUX ||
|
||||
d->max_patches / d->merge > INT64_MAX / d->n_embd) {
|
||||
err(RAD_E_INVAL, "declare_encoder '%s': invalid auxiliary count or output size", nm);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (d->span_rows != 0 && d->n_aux > 0) {
|
||||
err(RAD_E_UNSUPPORTED, "declare_encoder '%s': typed span_rows with auxiliary outputs is not supported", nm);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (d->out == RAD_NULL_HANDLE || (size_t)d->out >= prog_.buffers.size()) {
|
||||
err(RAD_E_INVAL, "declare_encoder '%s': out %u is not a declared buffer", nm,
|
||||
(unsigned)d->out);
|
||||
@@ -1341,6 +1401,16 @@ int Builder::declare_encoder(const RadEncoderDecl* d) {
|
||||
"encoder", nm, (int)d->bidirectional);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
for (int i = 0; i < d->n_aux; ++i) {
|
||||
const rad_buf handle = d->aux_out[i];
|
||||
if (!handle || handle >= prog_.buffers.size()) return RAD_E_INVAL;
|
||||
const auto& output = prog_.buffers[handle].decl;
|
||||
if (output.dtype != RAD_BF16 || output.domain != RAD_DOMAIN_DEVICE ||
|
||||
decl_numel(output.rank, output.shape) < d->max_patches / d->merge * d->n_embd) {
|
||||
err(RAD_E_INVAL, "declare_encoder '%s': auxiliary output %d has wrong storage", nm, i);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
slot = *d;
|
||||
slot_name = nm;
|
||||
slot.name = nullptr; /* the plugin's storage; the name is the copy */
|
||||
@@ -2667,6 +2737,15 @@ void Builder::finish_buffer_liveness() {
|
||||
* sharing; the undeclared-use guard in core/runtime/issue.cpp enforces it. The pooled
|
||||
* output likewise: the engine reads it after the last op. */
|
||||
if ((rad_buf)i == prog_.logits_buf || (rad_buf)i == prog_.pooled_buf) b.last_use = last_op;
|
||||
/* The engine reads an encoder's auxiliary outputs (DeepStack taps, written by early
|
||||
* blocks) after the complete pass, so they cannot share later encoder scratch. The main
|
||||
* output is not extended: its last declared use is the encoder's final op and it is read
|
||||
* back before any trunk pass, so it stays reusable scratch as before. */
|
||||
for (const auto* enc : {&prog_.encoder, &prog_.audio_encoder}) {
|
||||
if (!enc->modalities) continue;
|
||||
for (int tap = 0; tap < enc->n_aux; ++tap)
|
||||
if ((rad_buf)i == enc->aux_out[tap]) b.last_use = last_op;
|
||||
}
|
||||
}
|
||||
|
||||
/* Region 1 holds what an op the second lane may issue asks for (Program::scratch_bytes_lane1):
|
||||
@@ -2856,6 +2935,16 @@ int rad_weight_shard_span_parts(RadBuilder* b, rad_weight w, const int64_t* lo,
|
||||
return B(b)->weight_shard_span_parts(w, lo, hi, total, n);
|
||||
}
|
||||
|
||||
int rad_weight_row_order(RadBuilder* b, rad_weight w, const int32_t* order, int64_t n) {
|
||||
if (!b) return RAD_E_INVAL;
|
||||
return B(b)->weight_row_order(w, order, n);
|
||||
}
|
||||
|
||||
int rad_expert_profile(RadBuilder* b, int layer, float* share, int64_t n) {
|
||||
if (!b) return RAD_E_INVAL;
|
||||
return B(b)->expert_profile(layer, share, n);
|
||||
}
|
||||
|
||||
int rad_kv_group_zero(RadBuilder* b, rad_kvgroup g) {
|
||||
if (!b) return RAD_E_INVAL;
|
||||
return B(b)->kv_group_zero(g);
|
||||
|
||||
@@ -460,7 +460,7 @@ std::vector<std::string> CheckpointSources::refused() const {
|
||||
int rad_tools_declare(const LoadedPlugins& lp, const RadModelMeta& meta, const RadBuildCtx& ctx,
|
||||
Program* out, const std::function<int(RadBuilder*, int64_t)>& also,
|
||||
const Program* ref, const WeightSourceFn& sources, bool instances,
|
||||
const LoraDeclare* lora) {
|
||||
const LoraDeclare* lora, const std::vector<RadFileProfile>* profile) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
|
||||
Registry& r = lp.registry ? *lp.registry : rad_tools_registry();
|
||||
@@ -475,6 +475,7 @@ int rad_tools_declare(const LoadedPlugins& lp, const RadModelMeta& meta, const R
|
||||
if (ref) b.set_reference(ref);
|
||||
if (sources) b.set_sources(sources);
|
||||
b.set_instances(instances);
|
||||
if (profile && !profile->empty()) b.set_expert_profile(profile->data(), (int64_t)profile->size());
|
||||
const bool with_lora = lora && lora->cfg && lora->cfg->enabled();
|
||||
if (with_lora) b.set_lora_targets(&lora->targets);
|
||||
|
||||
|
||||
@@ -134,7 +134,8 @@ int rad_tools_declare(const LoadedPlugins& plugins, const RadModelMeta& meta,
|
||||
const RadBuildCtx& ctx, Program* out,
|
||||
const std::function<int(RadBuilder*, int64_t logits_width)>& also = {},
|
||||
const Program* ref = nullptr, const WeightSourceFn& sources = {},
|
||||
bool instances = true, const struct LoraDeclare* lora = nullptr);
|
||||
bool instances = true, const struct LoraDeclare* lora = nullptr,
|
||||
const std::vector<RadFileProfile>* expert_profile = nullptr);
|
||||
|
||||
/* A container's entries as the source of every declaration's encoding. `f` must outlive the
|
||||
* declare. */
|
||||
|
||||
+39
-6
@@ -6,6 +6,7 @@
|
||||
#include "rad_core.h"
|
||||
#include "sched/draft_depth.h" /* the --draft-depth-load lists */
|
||||
#include "kld.h"
|
||||
#include "cvec.h"
|
||||
#include "format/rope_override.h"
|
||||
#include "sample/host_ref.h"
|
||||
#include "server/oai.h"
|
||||
@@ -97,10 +98,12 @@ static const Flag g_flags[] = {
|
||||
"Not with --gpu-headroom-mib" },
|
||||
{ "--gpu-headroom-mib", "N", "VRAM left unclaimed on every card (default 96).\n"
|
||||
"Not with --gpu-memory-mib" },
|
||||
{ "--kv-cache-dtype", "T", "bf16 (default) | i8 | fp8 -- i8 halves what a token of\n"
|
||||
"context costs: K and V as int8 with one scale each per token\n"
|
||||
"and head. fp8 (E4M3): GLM-5.3's latent cache; DeepSeek-V4.1's\n"
|
||||
"compressed latent and index keys, exact (the bf16 cache's bits)" },
|
||||
{ "--kv-cache-dtype", "T", "bf16 (default) | i8 | i6r | i4r | fp8 -- i8 halves what a\n"
|
||||
"token of context costs: K and V as int8 with one scale each per\n"
|
||||
"token and head. i4r halves i8's: K and V rotated (Hadamard) to\n"
|
||||
"int4, one scale each; i6r the same at int6 (3/4 of i8's);\n"
|
||||
"Qwen3.8-Flash-Next only. fp8 (E4M3): GLM-5.3's latent cache;\n"
|
||||
"DeepSeek-V4.1's compressed latent and index keys, exact" },
|
||||
{ "--state-cache-dtype", "T", "f32 (default) | f16 -- the recurrent state cache (delta net):\n"
|
||||
"f16 halves the state pool, its checkpoints and its traffic,\n"
|
||||
"and is lossy; the qwen35 plugins serve it" },
|
||||
@@ -109,6 +112,11 @@ static const Flag g_flags[] = {
|
||||
" off). Raised to 32768 and to what one decode step selects;\n"
|
||||
" a ring that covers the context (sequences x\n"
|
||||
" --max-model-len) streams nothing" },
|
||||
{ "--kv-host-tokens", "N", "with --kv-resident: the tokens all sequences together keep in\n"
|
||||
" the streamed group's host mirror (0, the default, is\n"
|
||||
" --max-num-seqs x --max-model-len). At least --max-model-len\n"
|
||||
" plus one step; a full mirror evicts the prefix cache, then\n"
|
||||
" preempts" },
|
||||
{ "--host-pool-mib", "N", "pinned host tier for weights, in all: the ranks of a model\n"
|
||||
" pin equal shares of it (N / --tp each)" },
|
||||
{ "--host-headroom-mib", "N", "host RAM to leave free for the system when radiance\n"
|
||||
@@ -168,6 +176,12 @@ static const Flag g_flags[] = {
|
||||
" disabled -- the default, also with no flag at all -- loads\n"
|
||||
" nothing: no projection op is declared, and a request that\n"
|
||||
" asks for the vector is refused" },
|
||||
{ "--control-vector-slots", "N", "hold N control vectors (1..64; 0, the default: one, found\n"
|
||||
" at startup), uploaded, re-tuned and deleted while serving\n"
|
||||
" (/admin/control-vectors); a request's `control_vector` names\n"
|
||||
" one. A file found at startup fills the slot `default`.\n"
|
||||
" Implies --control-vector off. Uploads are not kept across\n"
|
||||
" a restart or an unload" },
|
||||
{ "--control-vector-variant", "NAME", "list MODEL:NAME, a name of this model whose\n"
|
||||
" requests run with the control vector on; the model's\n"
|
||||
" own name keeps --control-vector's default. Needs\n"
|
||||
@@ -812,8 +826,9 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
"8-bit cache (int8 K and V, a scale each per token and head)", v);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (std::strcmp(v, "bf16") && std::strcmp(v, "i8") && std::strcmp(v, "fp8")) {
|
||||
RAD_ERR("--kv-cache-dtype takes bf16, i8 or fp8, not '%s'", v);
|
||||
if (std::strcmp(v, "bf16") && std::strcmp(v, "i8") && std::strcmp(v, "i6r") &&
|
||||
std::strcmp(v, "i4r") && std::strcmp(v, "fp8")) {
|
||||
RAD_ERR("--kv-cache-dtype takes bf16, i8, i6r, i4r or fp8, not '%s'", v);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
c->kv_cache_dtype = v;
|
||||
@@ -827,6 +842,7 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
c->state_cache_dtype = v;
|
||||
}
|
||||
else if (S("--kv-resident")) { if (!num(0, INT64_MAX, &c->kv_resident)) return RAD_E_INVAL; }
|
||||
else if (S("--kv-host-tokens")) { if (!num(0, INT64_MAX, &c->kv_host_tokens)) return RAD_E_INVAL; }
|
||||
else if (S("--host-pool-mib")) { if (!num(0, INT64_MAX, &c->host_pool_mib)) return RAD_E_INVAL; pool_all = true; }
|
||||
else if (S("--embedding-placement") || S("--ngram-placement")) {
|
||||
const bool emb = S("--embedding-placement");
|
||||
@@ -951,7 +967,9 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
c->control_vector = v;
|
||||
c->control_vector_given = true;
|
||||
}
|
||||
else if (S("--control-vector-slots")) { if (!num(0, kCvecMaxSlots, &c->control_vector_slots)) return RAD_E_INVAL; }
|
||||
else if (S("--control-vector-variant")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
if (!fleet::valid_name(v)) {
|
||||
@@ -1588,6 +1606,15 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
RAD_ERR("--calib-corpus records into --calib-dir; give one");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (c->control_vector_slots > 0 && c->control_vector == "disabled") {
|
||||
if (c->control_vector_given) {
|
||||
RAD_ERR("--control-vector-slots %d with --control-vector disabled: disabled loads "
|
||||
"nothing, so there would be no slots; say off or on, or leave the flag out",
|
||||
c->control_vector_slots);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
c->control_vector = "off";
|
||||
}
|
||||
if (!c->control_vector_variant.empty()) {
|
||||
if (c->control_vector == "disabled") {
|
||||
RAD_ERR("--control-vector-variant needs --control-vector off or on: with no vector "
|
||||
@@ -1853,6 +1880,9 @@ const ShowRow kShow[] = {
|
||||
{ "--state-cache-dtype", [](const Config& c) { return c.state_cache_dtype; } },
|
||||
{ "--kv-resident", [](const Config& c) {
|
||||
return c.kv_resident > 0 ? num(c.kv_resident) : std::string("0 (off)"); } },
|
||||
{ "--kv-host-tokens", [](const Config& c) {
|
||||
return c.kv_host_tokens > 0 ? num(c.kv_host_tokens)
|
||||
: std::string("0 (--max-num-seqs x --max-model-len)"); } },
|
||||
{ "--host-pool-mib", [](const Config& c) { return num(c.host_pool_mib * std::max(c.tp, 1)); } },
|
||||
{ "--host-headroom-mib", [](const Config& c) { return num(c.host_headroom_mib); } },
|
||||
{ "--embedding-placement", [](const Config& c) { return std::string(table_placement_name(c.embedding_placement)); } },
|
||||
@@ -1884,6 +1914,9 @@ const ShowRow kShow[] = {
|
||||
{ "--control-vector", [](const Config& c) { return c.control_vector; } },
|
||||
{ "--control-vector-variant", [](const Config& c) {
|
||||
return or_none(c.control_vector_variant, "none: no variant listed"); } },
|
||||
{ "--control-vector-slots", [](const Config& c) {
|
||||
return c.control_vector_slots > 0 ? num(c.control_vector_slots)
|
||||
: std::string("0 (one vector, found at startup)"); } },
|
||||
{ "--deterministic", [](const Config& c) { return onoff(c.deterministic); } },
|
||||
{ "--checkpoint-interval", [](const Config& c) { return num(c.checkpoint_interval); } },
|
||||
{ "--prefill-span", [](const Config& c) { return num(c.prefill_span); } },
|
||||
|
||||
+652
-39
@@ -1,27 +1,35 @@
|
||||
/* cvec.cpp -- loading and validating a GGUF control vector (core/cvec.h). The reader is
|
||||
* core/text/gguf.cpp, which maps the file and sizes its tensors. */
|
||||
#include "cvec.h"
|
||||
#include "rad_core.h"
|
||||
|
||||
#include "text/gguf.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cerrno>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <fcntl.h>
|
||||
#include <fstream>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "util/json.h"
|
||||
|
||||
namespace rad {
|
||||
namespace {
|
||||
|
||||
/* FNV-1a, continued from `h`. */
|
||||
uint64_t fnv(const void* p, size_t n, uint64_t h = 1469598103934665603ull) {
|
||||
const uint8_t* b = (const uint8_t*) p;
|
||||
for (size_t i = 0; i < n; ++i) { h ^= b[i]; h *= 1099511628211ull; }
|
||||
return h;
|
||||
}
|
||||
|
||||
/* FNV-1a over the table, so two different vectors never share a cache partition. */
|
||||
uint64_t hash_table(const ControlVector& cv) {
|
||||
uint64_t h = 1469598103934665603ull;
|
||||
const auto mix = [&h](const void* p, size_t n) {
|
||||
const uint8_t* b = (const uint8_t*) p;
|
||||
for (size_t i = 0; i < n; ++i) { h ^= b[i]; h *= 1099511628211ull; }
|
||||
};
|
||||
mix(cv.dir.data(), cv.dir.size() * sizeof(float));
|
||||
mix(cv.scales.data(), cv.scales.size() * sizeof(float));
|
||||
uint64_t h = fnv(cv.dir.data(), cv.dir.size() * sizeof(float));
|
||||
h = fnv(cv.scales.data(), cv.scales.size() * sizeof(float), h);
|
||||
return h ? h : 1ull;
|
||||
}
|
||||
|
||||
@@ -85,15 +93,26 @@ int control_vector_discover(const std::string& model_path, const std::string& ar
|
||||
}
|
||||
|
||||
|
||||
const char* control_vector_mode_name(CvecMode m) {
|
||||
return m == CvecMode::Add ? "add" : "project";
|
||||
}
|
||||
|
||||
bool control_vector_mode_parse(const std::string& s, CvecMode* out) {
|
||||
if (s == "project") { if (out) *out = CvecMode::Project; return true; }
|
||||
if (s == "add") { if (out) *out = CvecMode::Add; return true; }
|
||||
return false;
|
||||
}
|
||||
|
||||
/* The package's own JSON beside the vector (`<stem>.json`), the only place the operation's
|
||||
* parameters are stated: `{"mode": "project", "scale": 1.0, "layer_range": [4, 44]}` for the
|
||||
* published Flash-Next vector. Absent, the defaults apply. A file that is not JSON or names a mode
|
||||
* other than `project` is refused: the directions were tuned for that operation. */
|
||||
* other than `project` or `add` is refused. */
|
||||
namespace {
|
||||
|
||||
struct PackageJson {
|
||||
int first = 0, last = -1; /* -1: not stated */
|
||||
float scale = 1.0f;
|
||||
int first = 0, last = -1; /* -1: not stated */
|
||||
float scale = 1.0f;
|
||||
CvecMode mode = CvecMode::Project;
|
||||
};
|
||||
|
||||
int read_package_json(const std::string& gguf_path, PackageJson* out, std::string* why) {
|
||||
@@ -108,11 +127,13 @@ int read_package_json(const std::string& gguf_path, PackageJson* out, std::strin
|
||||
if (!f) return RAD_OK;
|
||||
try {
|
||||
const Json j = Json::parse(f);
|
||||
if (const auto m = j.find("mode"); m != j.end() && m->is_string() &&
|
||||
m->get<std::string>() != "project") {
|
||||
*why = "control vector " + path + ": mode '" + m->get<std::string>() +
|
||||
"'; only 'project' is implemented";
|
||||
return RAD_E_UNSUPPORTED;
|
||||
if (const auto m = j.find("mode"); m != j.end()) {
|
||||
if (!m->is_string() || !control_vector_mode_parse(m->get<std::string>(), &out->mode)) {
|
||||
*why = "control vector " + path + ": mode '" +
|
||||
(m->is_string() ? m->get<std::string>() : m->dump()) +
|
||||
"'; only 'project' and 'add' are implemented";
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
}
|
||||
if (const auto r = j.find("layer_range"); r != j.end() && r->is_array() && r->size() == 2 &&
|
||||
(*r)[0].is_number_integer() &&
|
||||
@@ -131,20 +152,20 @@ int read_package_json(const std::string& gguf_path, PackageJson* out, std::strin
|
||||
|
||||
} /* namespace */
|
||||
|
||||
int control_vector_load(const std::string& path, const std::string& arch, int64_t n_embd,
|
||||
int64_t n_model_layers, ControlVector* out, std::string* err) {
|
||||
namespace {
|
||||
|
||||
/* Validate an open container and keep its directions. `path` names it in messages; `pj` is the
|
||||
* package's JSON, or its defaults, and `pj_why` why it was refused ("" when it was not). `upload`
|
||||
* adds the checks for bytes an admin request brought: plain-decimal tensor names, and lengths
|
||||
* that stay finite in f32. A file the deployment found for itself is read as it always was. */
|
||||
int read_vector(const GgufFile& f, const std::string& path, const PackageJson& pj,
|
||||
const std::string& pj_why, bool upload, const std::string& arch, int64_t n_embd,
|
||||
int64_t n_model_layers, const CvecTune& tune, ControlVector* out,
|
||||
std::string* err) {
|
||||
const auto fail = [err](const std::string& why) {
|
||||
if (err) *err = why;
|
||||
return RAD_E_INVAL;
|
||||
};
|
||||
if (!out) return RAD_E_INVAL;
|
||||
*out = ControlVector{};
|
||||
|
||||
GgufFile f;
|
||||
const int rc = f.open(path.c_str());
|
||||
if (rc != RAD_OK)
|
||||
return fail("control vector " + path + ": cannot read it as a GGUF container");
|
||||
|
||||
std::string a;
|
||||
if (!f.get_str("general.architecture", &a) || a != "controlvector")
|
||||
return fail("control vector " + path + ": general.architecture is '" + a +
|
||||
@@ -167,13 +188,23 @@ int control_vector_load(const std::string& path, const std::string& arch, int64_
|
||||
if (t.name.rfind("direction.", 0) != 0)
|
||||
return fail("control vector " + path + ": tensor '" + t.name +
|
||||
"' is not a direction.<layer> entry");
|
||||
/* An upload's names are plain decimal and nothing else: "direction.07" or "direction.7x"
|
||||
* would be counted as layer 7 here and never found by that name below. */
|
||||
const std::string num = t.name.substr(std::min<size_t>(10, t.name.size()));
|
||||
const bool plain = !num.empty() && num.size() <= 9 && !(num.size() > 1 && num[0] == '0') &&
|
||||
num.find_first_not_of("0123456789") == std::string::npos;
|
||||
int64_t layer = 0;
|
||||
try {
|
||||
layer = std::stoll(t.name.substr(10));
|
||||
} catch (...) {
|
||||
bool numbered = !upload || plain;
|
||||
if (numbered) {
|
||||
try {
|
||||
layer = std::stoll(num);
|
||||
} catch (...) {
|
||||
numbered = false;
|
||||
}
|
||||
}
|
||||
if (!numbered)
|
||||
return fail("control vector " + path + ": tensor name '" + t.name +
|
||||
"' does not end in a layer number");
|
||||
}
|
||||
/* 1 .. n_layers-1: the table is indexed by layer (row 0 is unused, the format carrying no
|
||||
* direction for it), so direction.<n_layers> would write one row past it. */
|
||||
if (layer < 1 || layer >= n_model_layers)
|
||||
@@ -194,13 +225,16 @@ int control_vector_load(const std::string& path, const std::string& arch, int64_
|
||||
if (n_dir == 0) return fail("control vector " + path + ": the file holds no directions");
|
||||
|
||||
/* The package's parameters: its JSON, else every direction the file carries at scale 1, as
|
||||
* llama.cpp applies a control vector given no layer range. */
|
||||
PackageJson pj;
|
||||
std::string pj_why;
|
||||
if (const int prc = read_package_json(path, &pj, &pj_why); prc != RAD_OK) return fail(pj_why);
|
||||
* llama.cpp applies a control vector given no layer range. The caller's own come first. */
|
||||
if (!pj_why.empty()) return fail(pj_why);
|
||||
int first = pj.first, last = pj.last;
|
||||
float scale = pj.scale;
|
||||
CvecMode mode = pj.mode;
|
||||
if (last < 0) { first = (int) dir_first; last = (int) dir_last; }
|
||||
if (tune.first) first = *tune.first;
|
||||
if (tune.last) last = *tune.last;
|
||||
if (tune.strength) scale = *tune.strength;
|
||||
if (tune.mode) mode = *tune.mode;
|
||||
if (first < 1 || last < first)
|
||||
return fail("control vector " + path + ": the layer range " + std::to_string(first) + ":" +
|
||||
std::to_string(last) + " is empty");
|
||||
@@ -208,8 +242,13 @@ int control_vector_load(const std::string& path, const std::string& arch, int64_
|
||||
return fail("control vector " + path + ": the layer range " + std::to_string(first) + ":" +
|
||||
std::to_string(last) + " runs past this model's " +
|
||||
std::to_string(n_model_layers) + " layers");
|
||||
if (!(scale > 0.0f) || !std::isfinite(scale))
|
||||
return fail("control vector " + path + ": its scale is not a positive number");
|
||||
if (mode == CvecMode::Project) {
|
||||
if (!(scale > 0.0f) || !std::isfinite(scale))
|
||||
return fail("control vector " + path + ": its scale is not a positive number");
|
||||
} else {
|
||||
if (scale == 0.0f || !std::isfinite(scale))
|
||||
return fail("control vector " + path + ": its scale must be a finite nonzero number");
|
||||
}
|
||||
|
||||
out->n_embd = n_embd;
|
||||
/* Indexed by layer: rows 0..n_layers-1. Row 0 stays zero, the format carrying no direction
|
||||
@@ -219,9 +258,11 @@ int control_vector_load(const std::string& path, const std::string& arch, int64_
|
||||
out->first = first;
|
||||
out->last = last;
|
||||
out->user_scale = scale;
|
||||
out->mode = mode;
|
||||
out->path = path;
|
||||
out->dir.assign((size_t) (out->n_layers * n_embd), 0.0f);
|
||||
out->scales.assign((size_t) out->n_layers, 0.0f);
|
||||
out->norms.assign((size_t) out->n_layers, 0.0f);
|
||||
|
||||
double worst = 0.0;
|
||||
for (int64_t l = 1; l <= n_model_layers; ++l) {
|
||||
@@ -230,15 +271,26 @@ int control_vector_load(const std::string& path, const std::string& arch, int64_
|
||||
const float* d = (const float*) f.tensor_data(*t);
|
||||
if (!d) return fail("control vector " + path + ": " + t->name + " lies outside the file");
|
||||
|
||||
std::vector<float> row((size_t) n_embd);
|
||||
std::memcpy(row.data(), d, (size_t) n_embd * sizeof(float));
|
||||
double nn = 0.0;
|
||||
for (int64_t i = 0; i < n_embd; ++i) nn += (double) d[i] * (double) d[i];
|
||||
for (int64_t i = 0; i < n_embd; ++i)
|
||||
nn += (double) row[(size_t) i] * (double) row[(size_t) i];
|
||||
const double norm = std::sqrt(nn);
|
||||
if (!(norm > 0.0) || !std::isfinite(norm))
|
||||
return fail("control vector " + path + ": " + t->name + " has no direction");
|
||||
|
||||
float* dst = &out->dir[(size_t) (l * n_embd)];
|
||||
const float inv = (float) (1.0 / norm);
|
||||
for (int64_t i = 0; i < n_embd; ++i) dst[i] = d[i] * inv;
|
||||
bool finite = std::isfinite((float) norm) && std::isfinite((float) norm * scale);
|
||||
for (int64_t i = 0; i < n_embd; ++i) {
|
||||
dst[i] = row[(size_t) i] * inv;
|
||||
finite = finite && std::isfinite(dst[i]);
|
||||
}
|
||||
if (upload && !finite)
|
||||
return fail("control vector " + path + ": " + t->name +
|
||||
" has a length this format's f32 cannot normalise");
|
||||
out->norms[(size_t) l] = (float) norm;
|
||||
/* Zero outside the range: a layer is steered exactly when its scale is nonzero
|
||||
* (abi/rad_builder.h, RadControlVector), and a file carries directions for layers the
|
||||
* package's JSON leaves out. The row is kept so a range change needs no new upload. */
|
||||
@@ -253,13 +305,123 @@ int control_vector_load(const std::string& path, const std::string& arch, int64_
|
||||
std::to_string(last) + " includes layer " + std::to_string(l) +
|
||||
", which has no direction in the file");
|
||||
|
||||
if (worst > 1e-2)
|
||||
if (mode == CvecMode::Project && worst > 1e-2)
|
||||
RAD_WARN("control vector: %s: the directions are not unit-normalised (worst |norm - 1| "
|
||||
"= %.4f); each is divided by its own norm, so the operation is unchanged",
|
||||
path.c_str(), worst);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
int control_vector_load(const std::string& path, const std::string& arch, int64_t n_embd,
|
||||
int64_t n_model_layers, ControlVector* out, std::string* err,
|
||||
const CvecTune& tune) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
*out = ControlVector{};
|
||||
GgufFile f;
|
||||
if (f.open(path.c_str()) != RAD_OK) {
|
||||
if (err) *err = "control vector " + path + ": cannot read it as a GGUF container";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
PackageJson pj;
|
||||
std::string why;
|
||||
if (read_package_json(path, &pj, &why) == RAD_OK) why.clear();
|
||||
return read_vector(f, path, pj, why, false, arch, n_embd, n_model_layers, tune, out, err);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
std::string strength_rule(CvecMode mode = CvecMode::Project) {
|
||||
const std::string cap = std::to_string((int) kCvecMaxStrength);
|
||||
return mode == CvecMode::Add
|
||||
? "an uploaded additive strength must be nonzero and between -" + cap + " and " + cap
|
||||
: "an uploaded strength must be above 0 and at most " + cap;
|
||||
}
|
||||
|
||||
int load_buffer(std::vector<uint8_t> bytes, const std::string& label, const PackageJson& pj,
|
||||
const std::string& arch, int64_t n_embd, int64_t n_model_layers,
|
||||
const CvecTune& tune, ControlVector* out, std::string* err) {
|
||||
if ((int64_t) bytes.size() > kCvecUploadMaxBytes) {
|
||||
if (err) *err = "control vector " + label + ": larger than " +
|
||||
std::to_string(kCvecUploadMaxBytes >> 20) + " MiB";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
GgufFile f;
|
||||
if (f.open_memory(std::move(bytes), label) != RAD_OK) {
|
||||
if (err) *err = "control vector " + label + ": cannot read it as a GGUF container";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RAD_TRY(read_vector(f, label, pj, std::string(), true, arch, n_embd, n_model_layers, tune, out,
|
||||
err));
|
||||
if (!(std::fabs(out->user_scale) <= kCvecMaxStrength)) {
|
||||
if (err) *err = "control vector " + label + ": " + strength_rule(out->mode);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
int control_vector_load_bytes(std::vector<uint8_t> bytes, const std::string& label,
|
||||
const std::string& arch, int64_t n_embd, int64_t n_model_layers,
|
||||
ControlVector* out, std::string* err, const CvecTune& tune) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
*out = ControlVector{};
|
||||
return load_buffer(std::move(bytes), label, PackageJson{}, arch, n_embd, n_model_layers, tune,
|
||||
out, err);
|
||||
}
|
||||
|
||||
int control_vector_load_upload(const std::string& path, const std::string& arch, int64_t n_embd,
|
||||
int64_t n_model_layers, ControlVector* out, std::string* err,
|
||||
const CvecTune& tune) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
*out = ControlVector{};
|
||||
const auto fail = [err, &path](const std::string& why) {
|
||||
if (err) *err = "control vector " + path + ": " + why;
|
||||
return RAD_E_INVAL;
|
||||
};
|
||||
/* Non-blocking, so a FIFO is refused below rather than waited on. */
|
||||
const int fd = ::open(path.c_str(), O_RDONLY | O_NONBLOCK | O_CLOEXEC);
|
||||
if (fd < 0) return fail(std::string("cannot open it: ") + std::strerror(errno));
|
||||
struct stat st{};
|
||||
if (::fstat(fd, &st) != 0 || !S_ISREG(st.st_mode)) {
|
||||
::close(fd);
|
||||
return fail("not a regular file");
|
||||
}
|
||||
if (st.st_size <= 0 || st.st_size > kCvecUploadMaxBytes) {
|
||||
::close(fd);
|
||||
return fail("its size is not between 1 byte and " +
|
||||
std::to_string(kCvecUploadMaxBytes >> 20) + " MiB");
|
||||
}
|
||||
std::vector<uint8_t> bytes((size_t) st.st_size);
|
||||
size_t at = 0;
|
||||
while (at < bytes.size()) {
|
||||
const ssize_t n = ::read(fd, bytes.data() + at, bytes.size() - at);
|
||||
if (n < 0 && errno == EINTR) continue;
|
||||
if (n <= 0) break;
|
||||
at += (size_t) n;
|
||||
}
|
||||
::close(fd);
|
||||
if (at != bytes.size()) return fail("it could not be read whole");
|
||||
/* A JSON beside it that is no regular file would block the read as well. */
|
||||
std::string stem = path;
|
||||
const size_t dot = stem.find_last_of('.'), slash = stem.find_last_of("/\\");
|
||||
if (dot != std::string::npos && (slash == std::string::npos || dot > slash))
|
||||
stem = stem.substr(0, dot);
|
||||
struct stat js{};
|
||||
if (::stat((stem + ".json").c_str(), &js) == 0 &&
|
||||
(!S_ISREG(js.st_mode) || js.st_size > kCvecUploadMaxBytes))
|
||||
return fail("the JSON beside it is not a small regular file");
|
||||
PackageJson pj;
|
||||
std::string why;
|
||||
if (read_package_json(path, &pj, &why) != RAD_OK) {
|
||||
if (err) *err = why;
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
return load_buffer(std::move(bytes), path, pj, arch, n_embd, n_model_layers, tune, out, err);
|
||||
}
|
||||
|
||||
RadControlVector control_vector_view(const ControlVector& cv, const float* dir_device) {
|
||||
RadControlVector v{};
|
||||
v.dir = dir_device;
|
||||
@@ -297,7 +459,458 @@ const float* control_vector_upload(const ControlVector& cv, int rank) {
|
||||
|
||||
uint64_t control_vector_salt(const ControlVector& cv) {
|
||||
if (!cv.loaded()) return 0;
|
||||
return hash_table(cv) | 1ull;
|
||||
uint64_t h = hash_table(cv);
|
||||
if (cv.mode == CvecMode::Add) h = fnv("add", 3, h);
|
||||
return h | 1ull;
|
||||
}
|
||||
|
||||
uint64_t control_vector_combine_salt(uint64_t first, uint64_t second) {
|
||||
if (second == 0) return first;
|
||||
uint64_t h = fnv(&first, sizeof(first));
|
||||
h = fnv(&second, sizeof(second), h);
|
||||
h = fnv("stack2", 6, h);
|
||||
return h | 1ull;
|
||||
}
|
||||
|
||||
int control_vector_check_kernels(const Program& p, std::string* why, uint64_t required) {
|
||||
for (size_t i = 1; i < p.ops.size(); ++i) {
|
||||
const OpInfo& oi = p.ops[i];
|
||||
if (oi.op != "hc_project") continue;
|
||||
for (const Band& b : oi.bands)
|
||||
for (const Resolved& r : b.dom) {
|
||||
if (!r.row || !r.row->info ||
|
||||
(r.row->info->capabilities & required) == required)
|
||||
continue;
|
||||
if (why) {
|
||||
const uint64_t miss = required & ~r.row->info->capabilities;
|
||||
*why = std::string("kernel '") + r.row->info->name + "' of '" + r.row->plugin +
|
||||
(miss & RAD_KERNEL_CAP_CVEC_ROW_OFFSET
|
||||
? "' does not take a per-row direction offset, so it would project "
|
||||
"every slot along slot 0; build the kernel libraries with this "
|
||||
"engine"
|
||||
: "' does not support additive control-vector steering; build the "
|
||||
"kernel libraries with this engine");
|
||||
}
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ slots */
|
||||
std::vector<float> control_vector_base_scales(const ControlVector& cv) {
|
||||
std::vector<float> base = cv.scales;
|
||||
for (float& b : base)
|
||||
b = b == 0.0f ? 1.0f : std::fabs(b);
|
||||
if (!base.empty()) base[0] = 0.0f;
|
||||
return base;
|
||||
}
|
||||
|
||||
int control_vector_fold(const ControlVector& cv, std::vector<float>* rows, std::string* err,
|
||||
const std::vector<float>* base) {
|
||||
const auto fail = [err](const std::string& why) {
|
||||
if (err) *err = why;
|
||||
return RAD_E_INVAL;
|
||||
};
|
||||
if (!cv.loaded() || (int64_t) cv.norms.size() != cv.n_layers ||
|
||||
(int64_t) cv.dir.size() != cv.n_layers * cv.n_embd ||
|
||||
(base && (int64_t) base->size() != cv.n_layers))
|
||||
return fail("control vector: no directions to fold");
|
||||
const float strength = cv.user_scale;
|
||||
if (cv.mode == CvecMode::Project) {
|
||||
if (!(strength > 0.0f) || !std::isfinite(strength))
|
||||
return fail("control vector: its scale is not a positive number");
|
||||
} else {
|
||||
if (strength == 0.0f || !std::isfinite(strength))
|
||||
return fail("control vector: its scale must be a finite nonzero number");
|
||||
}
|
||||
if (cv.first < 1 || cv.last < cv.first || cv.last >= cv.n_layers)
|
||||
return fail("control vector: the layer range " + std::to_string(cv.first) + ":" +
|
||||
std::to_string(cv.last) + " is empty or outside layers 1.." +
|
||||
std::to_string(cv.n_layers - 1));
|
||||
rows->assign(cv.dir.size(), 0.0f);
|
||||
for (int64_t l = cv.first; l <= cv.last; ++l) {
|
||||
const float norm = cv.norms[(size_t) l];
|
||||
if (norm == 0.0f)
|
||||
return fail("control vector: the range includes layer " + std::to_string(l) +
|
||||
", which has no direction in the file");
|
||||
const float b = base ? (*base)[(size_t) l] : 1.0f;
|
||||
/* Project appears quadratically (sqrt), add appears linearly (signed). */
|
||||
const float g = cv.mode == CvecMode::Add ? (norm * strength) / b
|
||||
: std::sqrt((norm * strength) / b);
|
||||
if (!std::isfinite(g) || (cv.mode == CvecMode::Project ? !(g > 0.0f) : g == 0.0f))
|
||||
return fail("control vector: layer " + std::to_string(l) + "'s scale is out of range");
|
||||
for (int64_t i = 0; i < cv.n_embd; ++i)
|
||||
(*rows)[(size_t) (l * cv.n_embd + i)] = cv.dir[(size_t) (l * cv.n_embd + i)] * g;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
bool control_vector_name_ok(const std::string& name) {
|
||||
if (name.empty() || name.size() > 64) return false;
|
||||
for (const char c : name)
|
||||
if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||
|
||||
c == '.' || c == '_' || c == '-'))
|
||||
return false;
|
||||
return name != "true" && name != "false" && name != "on" && name != "off";
|
||||
}
|
||||
|
||||
struct CvecSlots::State {
|
||||
struct Slot {
|
||||
std::string name; /* "": free */
|
||||
ControlVector cv; /* the directions kept for a re-tune */
|
||||
uint64_t salt = 0;
|
||||
int refs = 0;
|
||||
bool busy = false; /* being written */
|
||||
bool failed = false;
|
||||
};
|
||||
std::mutex change; /* one install, re-tune or removal at a time */
|
||||
mutable std::mutex mu; /* everything below */
|
||||
std::condition_variable cv; /* a slot stopped being busy, or the table closed */
|
||||
std::vector<Slot> slots;
|
||||
std::string arch;
|
||||
int64_t n_embd = 0, n_layers = 0;
|
||||
std::vector<float> base; /* the table's scale per layer */
|
||||
bool allow_add = true; /* kernels advertise RAD_KERNEL_CAP_CVEC_ADD */
|
||||
bool closed = false;
|
||||
|
||||
int find(const std::string& name) const {
|
||||
for (size_t i = 0; i < slots.size(); ++i)
|
||||
if (!slots[i].name.empty() && slots[i].name == name) return (int) i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* The write of a validated vector into `slot`, which the caller found free to change and holds
|
||||
* `change` for. `lk` holds `mu` on entry and exit. */
|
||||
int write_slot(std::unique_lock<std::mutex>& lk, int slot, const std::string& name,
|
||||
const ControlVector& next, const std::vector<float>& rows,
|
||||
const Writer& write, std::string* err) {
|
||||
Slot& x = slots[(size_t) slot];
|
||||
const bool fresh = x.name.empty();
|
||||
x.name = name;
|
||||
x.busy = true; /* from here a request naming it waits */
|
||||
lk.unlock();
|
||||
int rc = RAD_E_DEVICE;
|
||||
try {
|
||||
rc = write(slot, rows, err);
|
||||
} catch (const std::exception& e) {
|
||||
if (err) *err = std::string("control vector: writing the slot failed: ") + e.what();
|
||||
}
|
||||
ControlVector keep;
|
||||
uint64_t salt = 0;
|
||||
if (rc == RAD_OK) {
|
||||
keep = next;
|
||||
salt = fnv(base.data(), base.size() * sizeof(float),
|
||||
fnv(rows.data(), rows.size() * sizeof(float)));
|
||||
if (next.mode == CvecMode::Add) salt = fnv("add", 3, salt);
|
||||
salt |= 1ull;
|
||||
}
|
||||
lk.lock();
|
||||
x.busy = false;
|
||||
if (rc == RAD_OK) {
|
||||
x.cv = std::move(keep);
|
||||
x.salt = salt;
|
||||
x.failed = false;
|
||||
} else if (rc == RAD_E_STATE) {
|
||||
if (fresh) x = Slot{}; /* nothing was written: as it was */
|
||||
} else {
|
||||
x.failed = true;
|
||||
x.salt = 0;
|
||||
RAD_ERR("control vector: slot %d ('%s') could not be written and is unusable until it "
|
||||
"is uploaded again or deleted", slot, name.c_str());
|
||||
}
|
||||
cv.notify_all();
|
||||
return rc;
|
||||
}
|
||||
|
||||
/* Why slot `i` may not be changed now, as RAD_E_STATE, else RAD_OK. Under `mu`. */
|
||||
int changeable(int i, std::string* err) const {
|
||||
const Slot& x = slots[(size_t) i];
|
||||
if (closed) {
|
||||
if (err) *err = "the engine is stopping";
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (x.refs > 0) {
|
||||
if (err) *err = "control vector '" + x.name + "' is in use by " +
|
||||
std::to_string(x.refs) + " request" + (x.refs == 1 ? "" : "s") +
|
||||
" (running or queued); retry when they have finished";
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
};
|
||||
|
||||
bool CvecSlots::fits(int n, int64_t n_layers, int64_t n_embd) {
|
||||
if (n < 1 || n > kCvecMaxSlots || n_layers < 1 || n_embd < 1) return false;
|
||||
int64_t block = 0, all = 0;
|
||||
if (__builtin_mul_overflow(n_layers, n_embd, &block) ||
|
||||
__builtin_mul_overflow(block, (int64_t) n, &all))
|
||||
return false;
|
||||
return all <= (int64_t) INT32_MAX - 1;
|
||||
}
|
||||
|
||||
CvecSlots::CvecSlots(int n, const std::string& arch, int64_t n_embd, int64_t n_layers,
|
||||
std::vector<float> base_scales, bool allow_add)
|
||||
: s_(std::make_shared<State>()) {
|
||||
s_->slots.resize(fits(n, n_layers, n_embd) ? (size_t) n : 0);
|
||||
s_->arch = arch;
|
||||
s_->n_embd = n_embd;
|
||||
s_->n_layers = n_layers;
|
||||
s_->allow_add = allow_add;
|
||||
if (base_scales.empty() && !s_->slots.empty()) {
|
||||
base_scales.assign((size_t) n_layers, 1.0f);
|
||||
base_scales[0] = 0.0f;
|
||||
}
|
||||
s_->base = std::move(base_scales);
|
||||
}
|
||||
|
||||
int CvecSlots::size() const { return (int) s_->slots.size(); }
|
||||
int64_t CvecSlots::block_elems() const { return s_->n_layers * s_->n_embd; }
|
||||
int64_t CvecSlots::n_embd() const { return s_->n_embd; }
|
||||
int64_t CvecSlots::n_layers() const { return s_->n_layers; }
|
||||
const std::string& CvecSlots::arch() const { return s_->arch; }
|
||||
void CvecSlots::set_allow_add(bool ok) {
|
||||
std::lock_guard<std::mutex> lk(s_->mu);
|
||||
s_->allow_add = ok;
|
||||
}
|
||||
bool CvecSlots::allow_add() const {
|
||||
std::lock_guard<std::mutex> lk(s_->mu);
|
||||
return s_->allow_add;
|
||||
}
|
||||
|
||||
int CvecSlots::seed(const std::string& name, const ControlVector& cv, std::string* err) {
|
||||
return install(name, cv, [](int, const std::vector<float>&, std::string*) { return RAD_OK; },
|
||||
err);
|
||||
}
|
||||
|
||||
int CvecSlots::acquire(const std::string& name, Lease* out, std::string* err,
|
||||
std::chrono::milliseconds wait) {
|
||||
*out = Lease{};
|
||||
const auto until = std::chrono::steady_clock::now() + wait;
|
||||
std::shared_ptr<State> s = s_;
|
||||
int slot = -1;
|
||||
uint64_t salt = 0;
|
||||
CvecMode mode = CvecMode::Project;
|
||||
{
|
||||
std::unique_lock<std::mutex> lk(s->mu);
|
||||
for (;;) {
|
||||
if (s->closed) {
|
||||
if (err) *err = "the engine is stopping";
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
slot = s->find(name);
|
||||
if (slot < 0) {
|
||||
if (err) *err = "no control vector named '" + name + "' is loaded";
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
const State::Slot& x = s->slots[(size_t) slot];
|
||||
if (!x.busy) {
|
||||
if (x.failed) {
|
||||
if (err) *err = "control vector '" + name + "' is unusable: its last upload "
|
||||
"failed; upload it again";
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (std::chrono::steady_clock::now() >= until) {
|
||||
if (err) *err = "control vector '" + name + "' is being changed; retry";
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
s->cv.wait_until(lk, until);
|
||||
}
|
||||
State::Slot& x = s->slots[(size_t) slot];
|
||||
++x.refs;
|
||||
salt = x.salt;
|
||||
mode = x.cv.mode;
|
||||
}
|
||||
out->slot = slot;
|
||||
out->offset = (int32_t) ((int64_t) slot * block_elems());
|
||||
out->salt = salt;
|
||||
out->mode = mode;
|
||||
/* Made outside the lock: the deleter takes it, and runs at once if the allocation fails. The
|
||||
* pointer is not null, so that a held claim tests true (Scheduler::add_locked asks). */
|
||||
out->hold = std::shared_ptr<void>(s.get(), [s, slot](void*) {
|
||||
std::lock_guard<std::mutex> lk(s->mu);
|
||||
--s->slots[(size_t) slot].refs;
|
||||
});
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int CvecSlots::install(const std::string& name, const ControlVector& cv, const Writer& write,
|
||||
std::string* err) {
|
||||
if (!control_vector_name_ok(name)) {
|
||||
if (err) *err = kCvecNameRule;
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (cv.n_embd != s_->n_embd || cv.n_layers != s_->n_layers) {
|
||||
if (err) *err = "control vector: its shape is not this model's";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (cv.mode == CvecMode::Add && !allow_add()) {
|
||||
if (err) *err = "additive control-vector steering is not supported by the loaded kernel "
|
||||
"libraries; rebuild the kernel plugins with this engine";
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
std::vector<float> rows;
|
||||
if (const int rc = control_vector_fold(cv, &rows, err, &s_->base); rc != RAD_OK) return rc;
|
||||
std::lock_guard<std::mutex> one(s_->change);
|
||||
std::unique_lock<std::mutex> lk(s_->mu);
|
||||
int slot = s_->find(name);
|
||||
if (slot < 0) {
|
||||
for (size_t i = 0; i < s_->slots.size() && slot < 0; ++i)
|
||||
if (s_->slots[i].name.empty()) slot = (int) i;
|
||||
if (slot < 0) {
|
||||
if (err) *err = "all " + std::to_string(s_->slots.size()) + " control-vector slots "
|
||||
"are taken (--control-vector-slots); delete one or replace one by name";
|
||||
return RAD_E_FULL;
|
||||
}
|
||||
}
|
||||
if (const int rc = s_->changeable(slot, err); rc != RAD_OK) return rc;
|
||||
return s_->write_slot(lk, slot, name, cv, rows, write, err);
|
||||
}
|
||||
|
||||
int CvecSlots::retune(const std::string& name, const CvecTune& tune, const Writer& write,
|
||||
std::string* err) {
|
||||
std::lock_guard<std::mutex> one(s_->change);
|
||||
std::unique_lock<std::mutex> lk(s_->mu);
|
||||
const int slot = s_->find(name);
|
||||
if (slot < 0) {
|
||||
if (err) *err = "no control vector named '" + name + "' is loaded";
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
if (const int rc = s_->changeable(slot, err); rc != RAD_OK) return rc;
|
||||
if (s_->slots[(size_t) slot].failed) {
|
||||
if (err) *err = "control vector '" + name + "' is unusable: its last upload failed; "
|
||||
"upload it again";
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
ControlVector next = s_->slots[(size_t) slot].cv;
|
||||
if (tune.first) next.first = *tune.first;
|
||||
if (tune.last) next.last = *tune.last;
|
||||
if (tune.mode) next.mode = *tune.mode;
|
||||
if (tune.strength) next.user_scale = *tune.strength;
|
||||
if (next.mode == CvecMode::Add && !s_->allow_add) {
|
||||
if (err) *err = "additive control-vector steering is not supported by the loaded kernel "
|
||||
"libraries; rebuild the kernel plugins with this engine";
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (tune.strength) {
|
||||
const float s = *tune.strength;
|
||||
const bool ok = next.mode == CvecMode::Add
|
||||
? (s != 0.0f && std::isfinite(s) && std::fabs(s) <= kCvecMaxStrength)
|
||||
: (s > 0.0f && std::isfinite(s) && s <= kCvecMaxStrength);
|
||||
if (!ok) {
|
||||
if (err) *err = "control vector '" + name + "': " + strength_rule(next.mode);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
std::vector<float> rows;
|
||||
if (const int rc = control_vector_fold(next, &rows, err, &s_->base); rc != RAD_OK) return rc;
|
||||
for (int64_t l = 0; l < next.n_layers; ++l)
|
||||
next.scales[(size_t) l] = (l >= next.first && l <= next.last)
|
||||
? next.norms[(size_t) l] * next.user_scale : 0.0f;
|
||||
return s_->write_slot(lk, slot, name, next, rows, write, err);
|
||||
}
|
||||
|
||||
int CvecSlots::enable_default(std::atomic<bool>* flag, std::string* err) {
|
||||
std::lock_guard<std::mutex> lk(s_->mu);
|
||||
const int i = s_->find(kCvecDefaultSlot);
|
||||
const char* why = s_->closed ? "the engine is stopping"
|
||||
: i < 0 ? "the default control-vector slot is empty; "
|
||||
"upload a vector named 'default' first"
|
||||
: s_->slots[(size_t) i].busy ? "the default control-vector slot is being "
|
||||
"changed; retry"
|
||||
: s_->slots[(size_t) i].failed ? "the last upload of the default "
|
||||
"control-vector slot failed; upload it again"
|
||||
: nullptr;
|
||||
if (why) {
|
||||
if (err) *err = why;
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
flag->store(true);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int CvecSlots::remove(const std::string& name, std::string* err,
|
||||
const std::atomic<bool>* default_on) {
|
||||
std::lock_guard<std::mutex> one(s_->change);
|
||||
std::lock_guard<std::mutex> lk(s_->mu);
|
||||
const int slot = s_->find(name);
|
||||
if (slot < 0) {
|
||||
if (err) *err = "no control vector named '" + name + "' is loaded";
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
if (const int rc = s_->changeable(slot, err); rc != RAD_OK) return rc;
|
||||
/* Under the mutex enable_default holds, so the default is never on with its slot deleted. */
|
||||
if (name == kCvecDefaultSlot && default_on && default_on->load()) {
|
||||
if (err) *err = "control vector '" + name + "' serves the runtime default, which is on; "
|
||||
"turn it off (POST /admin/control-vector {\"enabled\": false}) before "
|
||||
"deleting it";
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
s_->slots[(size_t) slot] = State::Slot{};
|
||||
s_->cv.notify_all();
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
bool CvecSlots::has(const std::string& name) const {
|
||||
std::lock_guard<std::mutex> lk(s_->mu);
|
||||
return s_->find(name) >= 0;
|
||||
}
|
||||
|
||||
int CvecSlots::in_use(const std::string& name) const {
|
||||
std::lock_guard<std::mutex> lk(s_->mu);
|
||||
const int i = s_->find(name);
|
||||
return i < 0 ? 0 : s_->slots[(size_t) i].refs;
|
||||
}
|
||||
|
||||
bool CvecSlots::info(const std::string& name, int* first, int* last, float* strength,
|
||||
std::string* source, CvecMode* mode) const {
|
||||
std::lock_guard<std::mutex> lk(s_->mu);
|
||||
const int i = s_->find(name);
|
||||
if (i < 0 || s_->slots[(size_t) i].failed || !s_->slots[(size_t) i].cv.loaded()) return false;
|
||||
const ControlVector& cv = s_->slots[(size_t) i].cv;
|
||||
*first = cv.first;
|
||||
*last = cv.last;
|
||||
*strength = cv.user_scale;
|
||||
*source = cv.path;
|
||||
if (mode) *mode = cv.mode;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string CvecSlots::json() const {
|
||||
std::lock_guard<std::mutex> lk(s_->mu);
|
||||
Json o;
|
||||
o["slots"] = (int) s_->slots.size();
|
||||
o["default_name"] = kCvecDefaultSlot;
|
||||
Json list = Json::array();
|
||||
for (size_t i = 0; i < s_->slots.size(); ++i) {
|
||||
const State::Slot& x = s_->slots[i];
|
||||
if (x.name.empty()) continue;
|
||||
Json e;
|
||||
e["slot"] = (int) i;
|
||||
e["name"] = x.name;
|
||||
e["state"] = x.busy ? "changing" : x.failed ? "failed" : "ready";
|
||||
e["in_use"] = x.refs;
|
||||
if (x.cv.loaded() && !x.failed) {
|
||||
e["mode"] = control_vector_mode_name(x.cv.mode);
|
||||
e["first"] = x.cv.first;
|
||||
e["last"] = x.cv.last;
|
||||
e["strength"] = x.cv.user_scale;
|
||||
e["directions"] = x.cv.n_dirs;
|
||||
e["source"] = x.cv.path;
|
||||
e["salt"] = fmt("%016llx", (unsigned long long) x.salt);
|
||||
}
|
||||
list.push_back(std::move(e));
|
||||
}
|
||||
o["vectors"] = std::move(list);
|
||||
return o.dump();
|
||||
}
|
||||
|
||||
void CvecSlots::close() {
|
||||
std::lock_guard<std::mutex> lk(s_->mu);
|
||||
s_->closed = true;
|
||||
s_->cv.notify_all();
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
+180
-2
@@ -14,33 +14,78 @@
|
||||
* with it on, the model declines far fewer requests. It is loaded only with --control-vector, and
|
||||
* each request can name its own choice.
|
||||
*
|
||||
* With --control-vector-slots N the deployment holds N directions tables on each card instead of
|
||||
* one, filled and replaced while it serves (CvecSlots below), and a request names the slot it
|
||||
* wants. Without the flag nothing here but the loader runs.
|
||||
*
|
||||
* A file is refused unless
|
||||
*
|
||||
* - `general.architecture` is `controlvector`,
|
||||
* - `controlvector.model_hint`, when present, is this model's architecture id,
|
||||
* - every tensor is `direction.<l>`, F32, one dimension, exactly the model's `n_embd`, and
|
||||
* 1 <= l < the model's layer count,
|
||||
* 1 <= l < the model's layer count (an upload's `<l>` written in plain decimal),
|
||||
* - every direction has a finite, nonzero length,
|
||||
* - the layer range lies inside the model and every layer in it has a direction.
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_internal.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* The largest vector file an admin upload may be, and the largest strength an upload or a re-tune
|
||||
* may state (a file the deployment found at startup keeps its own). The published vector is under
|
||||
* half a MiB; a strength past a handful destroys the model. */
|
||||
inline constexpr int64_t kCvecUploadMaxBytes = 8ll << 20;
|
||||
inline constexpr float kCvecMaxStrength = 16.0f;
|
||||
inline constexpr int kCvecMaxSlots = 64;
|
||||
/* Maximum number of control-vector slots stacked on a single request. */
|
||||
inline constexpr int kCvecMaxStack = 2;
|
||||
/* The slot a request that says `true`, the runtime default and --control-vector-variant use. */
|
||||
inline constexpr const char* kCvecDefaultSlot = "default";
|
||||
/* How long a request waits for the slot it names to finish being written. */
|
||||
inline constexpr std::chrono::milliseconds kCvecBusyWait{2000};
|
||||
|
||||
/* How a control vector modifies each residual stream:
|
||||
* Project: h <- h - s_l (h . v_l) v_l (directional ablation; strength > 0)
|
||||
* Add: h <- h + s_l v_l (additive steering; strength != 0, sign steers toward/away) */
|
||||
enum class CvecMode : uint8_t { Project = 0, Add = 1 };
|
||||
|
||||
const char* control_vector_mode_name(CvecMode m);
|
||||
bool control_vector_mode_parse(const std::string& s, CvecMode* out);
|
||||
|
||||
/* A caller's own layer range, strength and mode, each in place of the package JSON's where given. */
|
||||
struct CvecTune {
|
||||
std::optional<int> first, last;
|
||||
std::optional<float> strength;
|
||||
std::optional<CvecMode> mode;
|
||||
bool empty() const { return !first && !last && !strength && !mode; }
|
||||
};
|
||||
|
||||
/* What a loaded vector keeps on the host, before it is uploaded per rank. `dir` is
|
||||
* [n_layers * n_embd] f32, unit rows, row 0 unused (the format has no direction for layer 0);
|
||||
* `scales[l]` is |d_l| * user scale, or 0 where the layer is outside the loaded range. */
|
||||
class Program;
|
||||
|
||||
struct ControlVector {
|
||||
std::vector<float> dir;
|
||||
std::vector<float> scales;
|
||||
std::vector<float> norms; /* |d_l| for every direction carried, 0 where none */
|
||||
int64_t n_embd = 0;
|
||||
int64_t n_layers = 0;
|
||||
int64_t n_dirs = 0; /* directions the file carried (47 for the published one) */
|
||||
int first = -1, last = -1; /* inclusive layer range */
|
||||
float user_scale = 1.0f;
|
||||
CvecMode mode = CvecMode::Project;
|
||||
std::string path;
|
||||
|
||||
bool loaded() const { return n_layers > 0 && n_embd > 0; }
|
||||
@@ -56,7 +101,23 @@ struct ControlVector {
|
||||
* `<stem>.json` supplies `layer_range` and `scale`; one that is not JSON or names a mode other than
|
||||
* `project` is refused. Without it, every layer the file carries steers at scale 1. */
|
||||
int control_vector_load(const std::string& path, const std::string& arch, int64_t n_embd,
|
||||
int64_t n_model_layers, ControlVector* out, std::string* err);
|
||||
int64_t n_model_layers, ControlVector* out, std::string* err,
|
||||
const CvecTune& tune = {});
|
||||
|
||||
/* The same checks over a file's bytes, which have no JSON beside them: `tune` states the range and
|
||||
* strength, else every direction carried at strength 1. This and the path upload below also refuse
|
||||
* a tensor name that is not plain decimal, a length f32 cannot normalise and a strength past
|
||||
* kCvecMaxStrength. */
|
||||
int control_vector_load_bytes(std::vector<uint8_t> bytes, const std::string& label,
|
||||
const std::string& arch, int64_t n_embd, int64_t n_model_layers,
|
||||
ControlVector* out, std::string* err, const CvecTune& tune = {});
|
||||
|
||||
/* The admin path upload: `path` must be a regular file no larger than kCvecUploadMaxBytes. It is
|
||||
* read into memory once, so what is validated is what is installed; its `<stem>.json` applies,
|
||||
* under `tune`. */
|
||||
int control_vector_load_upload(const std::string& path, const std::string& arch, int64_t n_embd,
|
||||
int64_t n_model_layers, ControlVector* out, std::string* err,
|
||||
const CvecTune& tune = {});
|
||||
|
||||
/* Where a vector for `model_path` is looked for:
|
||||
* the container's sidecar, then one generic name in the container's directory, then each
|
||||
@@ -84,4 +145,121 @@ const float* control_vector_upload(const ControlVector& cv, int rank);
|
||||
* exactly as it did before it existed. */
|
||||
uint64_t control_vector_salt(const ControlVector& cv);
|
||||
|
||||
/* Order-sensitive cache salt for a two-slot stack (`first` applied before `second`). */
|
||||
uint64_t control_vector_combine_salt(uint64_t first, uint64_t second);
|
||||
|
||||
/* RAD_E_UNSUPPORTED (*why names the kernel and its library) unless every kernel resolved for
|
||||
* every `hc_project` op of `p`, in every band and domain, advertises every capability bit in
|
||||
* `required` (default: RAD_KERNEL_CAP_CVEC_ROW_OFFSET). */
|
||||
int control_vector_check_kernels(const Program& p, std::string* why,
|
||||
uint64_t required = RAD_KERNEL_CAP_CVEC_ROW_OFFSET);
|
||||
|
||||
/* ------------------------------------------------------------------ slots */
|
||||
/* The scale a slot table declares for each layer (row 0: 0): that of `cv`, the vector found at
|
||||
* startup, where it steers, else 1. */
|
||||
std::vector<float> control_vector_base_scales(const ControlVector& cv);
|
||||
|
||||
/* One slot's block of the table as the card holds it, [n_layers, n_embd]: row l is
|
||||
* v_l * sqrt(|d_l| * strength / base_l) for l in the range and zero outside it, so that a kernel
|
||||
* applying the table's scale base_l (`base`, else 1) removes |d_l| * strength * (h . v_l) v_l, and
|
||||
* nothing at all on a layer outside the range. `strength` is cv.user_scale. Folded against its own
|
||||
* base scales, a vector's rows in its range are its unit directions bit for bit, so the default
|
||||
* slot computes what the single vector computes. RAD_E_INVAL (*err) for a strength that is not a
|
||||
* positive number, an empty range or a layer in it with no direction. */
|
||||
int control_vector_fold(const ControlVector& cv, std::vector<float>* rows, std::string* err,
|
||||
const std::vector<float>* base = nullptr);
|
||||
|
||||
/* A slot name: 1..64 of [A-Za-z0-9._-], and none of true, false, on, off (what a client that
|
||||
* meant the boolean would send as a string). */
|
||||
bool control_vector_name_ok(const std::string& name);
|
||||
inline constexpr const char* kCvecNameRule =
|
||||
"a control vector name is 1..64 of [A-Za-z0-9._-], and not true, false, on or off";
|
||||
|
||||
/* Which vector each of a deployment's N slots holds, who is using it, and when it may be written.
|
||||
* Host bookkeeping only: the caller's Writer copies the bytes to the cards.
|
||||
*
|
||||
* A request holds its slot from the moment it is resolved until the scheduler closes it, so a
|
||||
* waiting, running or preempted request all count, and a slot with a holder is never written,
|
||||
* re-tuned or removed (RAD_E_STATE). A slot being written is busy: a request naming it waits for
|
||||
* the write, bounded. Both rules are decided under one mutex, so no request can see two versions
|
||||
* of a slot. The salt is a hash of the block's bytes, so a prefix cached under one version is
|
||||
* never matched under another, and a version loaded again finds its own.
|
||||
*
|
||||
* A write that fails part way leaves the slot `failed`: named, unusable, until it is uploaded
|
||||
* again or removed. Thread-safe; changes are serialised among themselves. */
|
||||
class CvecSlots {
|
||||
public:
|
||||
/* Copies `rows` (n_layers * n_embd f32) into slot `slot` on every rank, at a point where no
|
||||
* step is on the card. RAD_OK; RAD_E_STATE when it declined and wrote nothing; any other
|
||||
* error means the slot's bytes are unknown. */
|
||||
using Writer = std::function<int(int slot, const std::vector<float>& rows, std::string* err)>;
|
||||
|
||||
/* A request's claim on a slot. `offset` is the block's first element in the table. */
|
||||
struct Lease {
|
||||
int slot = -1;
|
||||
int32_t offset = 0;
|
||||
uint64_t salt = 0;
|
||||
CvecMode mode = CvecMode::Project;
|
||||
std::shared_ptr<void> hold;
|
||||
};
|
||||
|
||||
/* Whether an [n, n_layers, n_embd] table can be addressed by a row's int32 switch. */
|
||||
static bool fits(int n, int64_t n_layers, int64_t n_embd);
|
||||
|
||||
/* `base_scales`: the scale per layer the table is declared with; empty means 1.
|
||||
* `allow_add`: whether the resolved `hc_project` kernels advertise RAD_KERNEL_CAP_CVEC_ADD. */
|
||||
CvecSlots(int n, const std::string& arch, int64_t n_embd, int64_t n_layers,
|
||||
std::vector<float> base_scales = {}, bool allow_add = true);
|
||||
|
||||
int size() const;
|
||||
int64_t block_elems() const;
|
||||
int64_t n_embd() const;
|
||||
int64_t n_layers() const;
|
||||
const std::string& arch() const;
|
||||
void set_allow_add(bool ok);
|
||||
bool allow_add() const;
|
||||
|
||||
/* Fill slot 0 before anything is served, the card already holding `rows`. */
|
||||
int seed(const std::string& name, const ControlVector& cv, std::string* err);
|
||||
|
||||
/* RAD_OK; RAD_E_NOTFOUND, no vector of that name; RAD_E_STATE, its last upload failed, it is
|
||||
* still being written after `wait`, or the table is closed. */
|
||||
int acquire(const std::string& name, Lease* out, std::string* err,
|
||||
std::chrono::milliseconds wait = kCvecBusyWait);
|
||||
|
||||
/* Upload `cv` as `name`, replacing that name's vector or taking a free slot. RAD_E_INVAL
|
||||
* (nothing touched), RAD_E_STATE (in use), RAD_E_FULL (no free slot), else the writer's. */
|
||||
int install(const std::string& name, const ControlVector& cv, const Writer& write,
|
||||
std::string* err);
|
||||
/* Change a loaded vector's range or strength from its kept directions. RAD_E_NOTFOUND, and
|
||||
* otherwise as install. */
|
||||
int retune(const std::string& name, const CvecTune& tune, const Writer& write,
|
||||
std::string* err);
|
||||
/* Free the slot. The card is not written: no request can name the block, and the next upload
|
||||
* overwrites it. RAD_E_NOTFOUND or RAD_E_STATE, the latter also for the default slot while
|
||||
* *default_on, the runtime default, is set. */
|
||||
int remove(const std::string& name, std::string* err,
|
||||
const std::atomic<bool>* default_on = nullptr);
|
||||
/* Set *flag, the runtime default, if the default slot is ready: neither empty, being written
|
||||
* nor failed. Otherwise RAD_E_STATE and *flag as it was. */
|
||||
int enable_default(std::atomic<bool>* flag, std::string* err);
|
||||
|
||||
/* Whether `name` names a usable or loading vector. */
|
||||
bool has(const std::string& name) const;
|
||||
int in_use(const std::string& name) const;
|
||||
/* The range, strength, source and optional mode of a ready vector; false for none of that
|
||||
* name. */
|
||||
bool info(const std::string& name, int* first, int* last, float* strength,
|
||||
std::string* source, CvecMode* mode = nullptr) const;
|
||||
/* The listing GET /admin/control-vectors returns. */
|
||||
std::string json() const;
|
||||
/* Wake and refuse every waiter, and refuse what follows: the engine is stopping. */
|
||||
void close();
|
||||
|
||||
private:
|
||||
struct State;
|
||||
/* Held by the leases too, so one that outlives the engine releases into live memory. */
|
||||
std::shared_ptr<State> s_;
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
+28
-6
@@ -690,7 +690,7 @@ uint32_t g_queue_gen[kMaxQueues];
|
||||
* created, alternating; an engine's two compute lanes on one pipe run ~50% slower in decode than on
|
||||
* two (2x R9700 under MES, read from the driver's queue table: slow if and only if lane 0 and lane 1
|
||||
* shared a pipe, 119 of 119 requests). Bring-up keeps queues in an order where the newest two share
|
||||
* a pipe and the two oldest do not, so last-in first-out paired the lanes. Measured on jarvis with
|
||||
* a pipe and the two oldest do not, so last-in first-out paired the lanes. Measured on a dual-R9700 host with
|
||||
* the stock plugins (27B with DFlash2, Gemma 4 31B with MTP, tp 2): the same step times either way,
|
||||
* the second lane being nearly idle in decode there. */
|
||||
std::mutex g_spare_mu;
|
||||
@@ -1880,6 +1880,7 @@ int a_stream_create(RadStream* out, int high_priority) {
|
||||
r->prev_chained = false;
|
||||
r->plain_inflight = false;
|
||||
r->peer_inflight = false;
|
||||
r->ride.handle = 0;
|
||||
*reinterpret_cast<volatile uint64_t*>(r->chain_ctr) = 0;
|
||||
_mm_sfence();
|
||||
{
|
||||
@@ -1977,6 +1978,10 @@ void a_stream_destroy(RadStream rs) {
|
||||
* stops naming it at once, as a destroyed queue's would. */
|
||||
if (s->ord < kMaxDevices && s->fault.load(std::memory_order_acquire) == 0 &&
|
||||
s->gates.load(std::memory_order_acquire) == 0) {
|
||||
{
|
||||
std::lock_guard<Stream> qlk(*s);
|
||||
s->ride.handle = 0;
|
||||
}
|
||||
g_queue_by_id[s->id % kMaxQueues].store(nullptr, std::memory_order_release);
|
||||
std::lock_guard<std::mutex> lk(g_spare_mu);
|
||||
g_spare[s->ord][s->high ? 1 : 0].push_back(s);
|
||||
@@ -2244,7 +2249,11 @@ int a_event_record(RadEvent re, RadStream rs) {
|
||||
if (!g) { device_set_error("rad_event_record: no signal could be made"); return RAD_E_DEVICE; }
|
||||
uint64_t idx = 0;
|
||||
const int rc = barrier(s, hsa_signal_t{0}, g->h, HSA_FENCE_SCOPE_NONE, rel, &idx);
|
||||
if (rc < 0) return rc; /* the queue faulted; the signal stays armed and unused */
|
||||
if (rc < 0) {
|
||||
hsa_signal_silent_store_relaxed(g->h, 0);
|
||||
sig_retire(g);
|
||||
return rc;
|
||||
}
|
||||
record_adopt(e, g);
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -2688,6 +2697,10 @@ int a_tape_play(RadTape rt, int from, int to) {
|
||||
PlayStamp* sp = stamp.take(ps);
|
||||
rc = run.put(r, &idx, g ? g->h : hsa_signal_t{0}, rel, sp);
|
||||
if (rc < 0) {
|
||||
if (g) {
|
||||
hsa_signal_silent_store_relaxed(g->h, 0);
|
||||
sig_retire(g);
|
||||
}
|
||||
if (sp) stamp.drop();
|
||||
break;
|
||||
}
|
||||
@@ -4232,8 +4245,15 @@ hsa_amd_memory_pool_t* host_coarse_pool() {
|
||||
auto* out = static_cast<std::pair<hsa_amd_memory_pool_t*, bool*>*>(data);
|
||||
if (!*out->second &&
|
||||
allocatable_global_pool(p, HSA_AMD_MEMORY_POOL_GLOBAL_FLAG_COARSE_GRAINED)) {
|
||||
*out->first = p;
|
||||
*out->second = true;
|
||||
/* A pool the runtime lists but cannot map virtual memory from (ROCm on an MI100)
|
||||
* would fail the first park: keep looking, and leave host-backed parking off. */
|
||||
hsa_amd_vmem_alloc_handle_t h{};
|
||||
if (hsa_amd_vmem_handle_create(p, (size_t)RAD_ALIGN_POOL, MEMORY_TYPE_NONE, 0, &h) ==
|
||||
HSA_STATUS_SUCCESS) {
|
||||
(void)hsa_amd_vmem_handle_release(h);
|
||||
*out->first = p;
|
||||
*out->second = true;
|
||||
}
|
||||
}
|
||||
return HSA_STATUS_SUCCESS;
|
||||
};
|
||||
@@ -4946,8 +4966,10 @@ const DeviceBackend* aql_backend_if_present(void) {
|
||||
g_aql.vmem_commit_units = a_vmem_commit_units;
|
||||
g_aql.vmem_decommit = a_vmem_decommit;
|
||||
g_aql.vmem_protect = a_vmem_protect;
|
||||
g_aql.vmem_commit_host = a_vmem_commit_host;
|
||||
g_aql.vmem_swap = a_vmem_swap;
|
||||
if (host_coarse_pool()) {
|
||||
g_aql.vmem_commit_host = a_vmem_commit_host;
|
||||
g_aql.vmem_swap = a_vmem_swap;
|
||||
}
|
||||
g_aql.tape_begin = a_tape_begin;
|
||||
g_aql.tape_mark = a_tape_mark;
|
||||
g_aql.tape_pause = a_tape_pause;
|
||||
|
||||
@@ -517,7 +517,9 @@ int h_event_record(RadEvent ev, RadStream st) {
|
||||
t.ev = e;
|
||||
t.seq = seq;
|
||||
event_retain(e);
|
||||
return stream_push((HostStream*)st, t);
|
||||
const int rc = stream_push((HostStream*)st, t);
|
||||
if (rc < 0) event_release(e);
|
||||
return rc;
|
||||
}
|
||||
|
||||
int h_event_wait(RadStream st, RadEvent ev) {
|
||||
@@ -539,7 +541,9 @@ int h_event_wait(RadStream st, RadEvent ev) {
|
||||
t.ev = e;
|
||||
t.seq = target;
|
||||
event_retain(e);
|
||||
return stream_push((HostStream*)st, t);
|
||||
const int rc = stream_push((HostStream*)st, t);
|
||||
if (rc < 0) event_release(e);
|
||||
return rc;
|
||||
}
|
||||
|
||||
int h_event_query(RadEvent ev) {
|
||||
|
||||
+33
-9
@@ -236,7 +236,10 @@ int map_dev(Page& pg, char* at, size_t i) {
|
||||
const int rc = d->vmem_commit(at, pg.len(i));
|
||||
if (rc < 0) return rc;
|
||||
if (d->vmem_protect)
|
||||
if (const int prc = d->vmem_protect(at, pg.len(i)); prc < 0) return prc;
|
||||
if (const int prc = d->vmem_protect(at, pg.len(i)); prc < 0) {
|
||||
(void)d->vmem_decommit(at, pg.len(i));
|
||||
return prc;
|
||||
}
|
||||
return rc;
|
||||
}
|
||||
|
||||
@@ -1014,16 +1017,35 @@ int page_in_begin(int owner, bool live, int64_t* left, std::vector<PageSpan>* re
|
||||
std::vector<Pick> disk;
|
||||
/* Host copies and disk reads write whole chunks; the owner's refill writes its tensors only. */
|
||||
std::vector<Clear> clear;
|
||||
struct Mapped { Page* pg; size_t i; char* at; };
|
||||
std::vector<Mapped> mapped;
|
||||
mapped.reserve(picks.size());
|
||||
const size_t refill0 = refill ? refill->size() : 0;
|
||||
auto undo = [&](int rc) -> int {
|
||||
(void)pend->clear_st.sync_all();
|
||||
(void)st.sync_all();
|
||||
const DeviceBackend* d = be();
|
||||
for (const Mapped& m : mapped) {
|
||||
rad_dev_set(m.pg->device);
|
||||
(void)d->vmem_decommit(m.at, m.pg->len(m.i));
|
||||
}
|
||||
if (!mapped.empty()) (void)dev_settle_maps();
|
||||
if (refill) refill->resize(refill0);
|
||||
return rc;
|
||||
};
|
||||
for (const Pick& p : picks) {
|
||||
const Chunk& c = p.pg->ch[p.i];
|
||||
rad_dev_set(p.pg->device);
|
||||
if (c.hloc == kAtBase) {
|
||||
if (const int rc = map_dev(*p.pg, p.pg->shadow + p.pg->off(p.i), p.i); rc < 0) return rc;
|
||||
char* at = p.pg->shadow + p.pg->off(p.i);
|
||||
if (const int rc = map_dev(*p.pg, at, p.i); rc < 0) return undo(rc);
|
||||
mapped.push_back({ p.pg, p.i, at });
|
||||
host.push_back(p);
|
||||
continue;
|
||||
}
|
||||
const int mrc = map_chunk(*p.pg, p.base, p.i);
|
||||
if (mrc < 0) return mrc;
|
||||
if (mrc < 0) return undo(mrc);
|
||||
mapped.push_back({ p.pg, p.i, p.base + p.pg->off(p.i) });
|
||||
if (c.refill) {
|
||||
char* at = p.base + p.pg->off(p.i);
|
||||
if (mrc == 1) clear.push_back({ at, p.pg->len(p.i), p.pg->device });
|
||||
@@ -1037,16 +1059,16 @@ int page_in_begin(int owner, bool live, int64_t* left, std::vector<PageSpan>* re
|
||||
if ((c.on_disk || c.backed) && !c.dropped) disk.push_back(p);
|
||||
}
|
||||
if (!picks.empty())
|
||||
if (const int rc = dev_settle_maps(); rc < 0) return rc;
|
||||
if (const int rc = dev_settle_maps(); rc < 0) return undo(rc);
|
||||
/* Only refill chunks are cleared, and the refill writes nothing before its first read lands, so
|
||||
* the clears run beside that read (~20-40 ms of a large restore's) instead of ahead of it. */
|
||||
if (const int rc = clear_issue(clear, pend->clear_st); rc < 0) return rc;
|
||||
if (const int rc = clear_issue(clear, pend->clear_st); rc < 0) return undo(rc);
|
||||
for (const Pick& p : host) {
|
||||
RadStream s = st.on(p.pg->device);
|
||||
if (!s) return RAD_E_DEVICE;
|
||||
if (!s) return undo(RAD_E_DEVICE);
|
||||
if (const int rc = rad_memcpy_async(p.pg->shadow + p.pg->off(p.i), p.base + p.pg->off(p.i),
|
||||
p.pg->len(p.i), s); rc < 0)
|
||||
return rc;
|
||||
return undo(rc);
|
||||
}
|
||||
/* Round-robin over the cards, so each card's link has a chunk in flight while the drive
|
||||
* reads the next. */
|
||||
@@ -1062,7 +1084,7 @@ int page_in_begin(int owner, bool live, int64_t* left, std::vector<PageSpan>* re
|
||||
}
|
||||
}
|
||||
/* With anything on disk, read_back waits for the stream, the host copies with it. */
|
||||
if (const int rc = read_back(disk, st); rc < 0) return rc;
|
||||
if (const int rc = read_back(disk, st); rc < 0) return undo(rc);
|
||||
std::vector<Gone> gone;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_mu);
|
||||
@@ -1222,8 +1244,10 @@ int64_t dev_page_promote(int owner, int64_t max_bytes, const std::function<int(c
|
||||
for (; swapped < picks.size(); ++swapped) {
|
||||
const Pick& p = picks[swapped];
|
||||
rad_dev_set(p.pg->device);
|
||||
if (const int r = d->vmem_swap(p.base + p.pg->off(p.i), p.pg->shadow + p.pg->off(p.i), p.pg->len(p.i)); r < 0)
|
||||
if (const int r = d->vmem_swap(p.base + p.pg->off(p.i), p.pg->shadow + p.pg->off(p.i), p.pg->len(p.i)); r < 0) {
|
||||
if (swapped > 0) (void)dev_settle_maps();
|
||||
return r;
|
||||
}
|
||||
}
|
||||
return dev_settle_maps();
|
||||
});
|
||||
|
||||
+189
-32
@@ -362,6 +362,11 @@ void Engine::hold_point(StallWatch* watch) {
|
||||
return;
|
||||
}
|
||||
hold_ack_.store(true, std::memory_order_release);
|
||||
/* Wake any run_quiet() caller so it does not wait for the duration of the park. */
|
||||
{
|
||||
std::lock_guard<std::mutex> qlk(quiet_mu_);
|
||||
}
|
||||
quiet_cv_.notify_all();
|
||||
/* A park lasts as long as the fleet keeps the model off its cards. The loop sleeps until the
|
||||
* hold clears or the engine stops, waking once a second besides to mark the step watch, so a
|
||||
* model parked for minutes is not reported as a step that stopped (and is not woken a thousand
|
||||
@@ -920,9 +925,12 @@ int Engine::run_quiet(const std::function<int()>& fn) {
|
||||
quiet_done_ = false;
|
||||
quiet_pending_.store(true, std::memory_order_release);
|
||||
sched_.wake();
|
||||
/* Polled for a stop: the step loop may end without passing a step boundary again. */
|
||||
/* Polled for a stop: the step loop may end without passing a step boundary again,
|
||||
* or park into hold_point() where quiet_service() does not run. */
|
||||
while (!quiet_cv_.wait_for(lk, std::chrono::milliseconds(50), [&] {
|
||||
return quiet_done_ || stopping_.load(std::memory_order_acquire);
|
||||
return quiet_done_ || stopping_.load(std::memory_order_acquire) ||
|
||||
hold_ack_.load(std::memory_order_acquire) ||
|
||||
parked_.load(std::memory_order_acquire);
|
||||
})) {}
|
||||
quiet_pending_.store(false, std::memory_order_release);
|
||||
quiet_fn_ = nullptr;
|
||||
@@ -1002,6 +1010,10 @@ Engine::~Engine() {
|
||||
if (RadStream s = r->mover.transfer_stream()) (void)rad_stream_sync(s);
|
||||
r->tierx.quiesce();
|
||||
}
|
||||
/* The step batch's staging, events and media buffers (BatchBuilder), freed BEFORE ctx.shutdown()
|
||||
* destroys the rank streams that BatchBuilder::free_media() may sync, and while the ranks' KV
|
||||
* managers the scheduler releases sequences into still exist. */
|
||||
sched_.fini();
|
||||
for (auto& r : ranks_) r->ctx.shutdown();
|
||||
if (cards_claimed_) {
|
||||
const std::vector<int> cards = rank_devices();
|
||||
@@ -1012,10 +1024,6 @@ Engine::~Engine() {
|
||||
* since a pass reads them. Safe after a failed bring-up. */
|
||||
for (auto& r : ranks_) r->kv.free_stream(rad_device_allocator());
|
||||
step_state_fini();
|
||||
/* The step batch's staging, events and media buffers (BatchBuilder), freed while the ranks'
|
||||
* KV managers the scheduler releases sequences into still exist. A process that unloads
|
||||
* models would otherwise keep every engine's. */
|
||||
sched_.fini();
|
||||
ranks_.clear();
|
||||
for (TableCopy& c : table_copies_) table_copy_free(&c);
|
||||
table_copies_.clear();
|
||||
@@ -1219,37 +1227,25 @@ void Engine::tiering_dispatch(Rank& r, int step) {
|
||||
xl.unlock();
|
||||
}
|
||||
|
||||
/* No swaps behind a pass the stager armed: that step is bound by its own copies on the same
|
||||
* transfer stream, and the turnover slots are filled for it (below). Histograms are still
|
||||
* credited; the next unstaged step swaps on them. */
|
||||
/* Swaps go behind every trunk pass, one the prefill stager armed included, so the residency
|
||||
* follows a long prompt's routing as it does when nothing is staged. They share the transfer
|
||||
* stream with the stager's copies, but each promotion is a unit the stager no longer copies
|
||||
* in later passes, so long prompts stay flat while follow-up turns on the cached context hit
|
||||
* VRAM more and run faster.
|
||||
*
|
||||
* Fill after the swaps: swaps are the policy's decisions, fills only use spare memory, and a
|
||||
* fill must not take a move record the next swap needs. The turnover slots stay free behind
|
||||
* a staged pass as behind any other, since its swaps use them. */
|
||||
std::vector<Swap> swaps;
|
||||
if (!r.stager.staged() && r.heat.step(&swaps) < 0) return;
|
||||
/* What the turnover slots follow (MoverConfig::turnover_adaptive). A staged step proposes
|
||||
* nothing and holds the turnover filled anyway (below), so it is not a quiet step. */
|
||||
if (!r.stager.staged()) r.mover.swap_demand((int64_t)swaps.size());
|
||||
if (r.heat.step(&swaps) < 0) return;
|
||||
/* What the turnover slots follow (MoverConfig::turnover_adaptive). */
|
||||
r.mover.swap_demand((int64_t)swaps.size());
|
||||
for (const Swap& s : swaps) {
|
||||
/* Contract: every proposed unit is busy until `issue` takes it or `abandon` returns it;
|
||||
* a dropped proposal stays busy forever. */
|
||||
if (r.mover.issue(s, &r.heat) < 0) r.heat.abandon(s);
|
||||
}
|
||||
|
||||
/* Fill after the swaps: swaps are the policy's decisions, fills only use spare memory, and a
|
||||
* fill must not take a move record the next swap needs.
|
||||
*
|
||||
* Behind a staged pass the turnover slots are filled too, since that step swaps nothing; left
|
||||
* free, the stager would copy those residents instead (at TP2 a 160K-token prompt staged 9.6%
|
||||
* more and ran 3-5% slower).
|
||||
*
|
||||
* They stay filled until kTurnoverAfter consecutive unstaged steps (idle ticks included).
|
||||
* Otherwise a short answer or a pause drops them and the next prompt's first chunk copies them
|
||||
* back, scattering the lent residents through the pool runs the stager coalesces on (at TP2,
|
||||
* back-to-back 26K-token prompts: 33 copies per staged layer instead of 16). Decode reaches the
|
||||
* count in a few steps. */
|
||||
constexpr int kTurnoverAfter = 4;
|
||||
r.unstaged_steps = r.stager.staged() ? 0 : r.unstaged_steps + 1;
|
||||
const bool hold = r.unstaged_steps < kTurnoverAfter;
|
||||
r.mover.hold_turnover(hold);
|
||||
(void)r.mover.balance(&r.heat, !hold);
|
||||
(void)r.mover.balance(&r.heat);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ --expert-stats
|
||||
@@ -1477,6 +1473,7 @@ int Engine::fail_loop(int st) {
|
||||
wake_hold();
|
||||
if (barrier_) barrier_->abort();
|
||||
sched_.shutdown("the engine stopped on an error and is not serving", st < 0 ? st : RAD_E_STATE);
|
||||
if (cvec_slots_) cvec_slots_->close();
|
||||
loop_status_.store(st < 0 ? st : RAD_E_STATE, std::memory_order_release);
|
||||
return st;
|
||||
}
|
||||
@@ -3187,6 +3184,7 @@ int Engine::serve(std::unique_ptr<StallWatch> watch) {
|
||||
stopping_.store(true, std::memory_order_release);
|
||||
wake_hold();
|
||||
barrier_->abort();
|
||||
if (cvec_slots_) cvec_slots_->close();
|
||||
/* A step loop that does not come back holds its cards and every model waiting for them, and
|
||||
* only a restart can free them, so past five minutes the process exits as for a GPU fault. */
|
||||
for (int t = 0; !stepped.load(std::memory_order_acquire); ++t) {
|
||||
@@ -3225,6 +3223,119 @@ bool Engine::state_slots_of(uint64_t seq, std::vector<int32_t>* out) const {
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the HTTP frontend */
|
||||
int Engine::cvec_acquire(const std::string& name, CvecSlots::Lease* out, std::string* err) {
|
||||
if (!cvec_slots_) {
|
||||
if (err) *err = "this deployment has no control-vector slots";
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
return cvec_slots_->acquire(name, out, err);
|
||||
}
|
||||
|
||||
/* One rank at a time, each on a stream of its own, as lora_copy. The host copies a park keeps of
|
||||
* the table no longer describe it once it is written, so they are dropped on both sides of the
|
||||
* write. Only RAD_OK or RAD_E_DEVICE: a failure may leave the block part written. */
|
||||
int Engine::cvec_copy(int slot, const std::vector<float>& rows, std::string* err) {
|
||||
const int64_t bytes = (int64_t)rows.size() * (int64_t)sizeof(float);
|
||||
for (const auto& r : ranks_) {
|
||||
const size_t ri = (size_t)r->index;
|
||||
const float* dir = ri < cvec_views_.size() ? cvec_views_[ri].dir : nullptr;
|
||||
if (!dir || rad_dev_set(r->device) < 0) {
|
||||
*err = fmt("rank %zu: no control-vector table to write", ri);
|
||||
return RAD_E_DEVICE;
|
||||
}
|
||||
float* dst = const_cast<float*>(dir) + (size_t)slot * rows.size();
|
||||
RadStream st{};
|
||||
if (rad_stream_create(&st, 0) < 0) {
|
||||
*err = fmt("rank %zu: no copy stream", ri);
|
||||
return RAD_E_DEVICE;
|
||||
}
|
||||
dev_page_invalidate(dst, bytes);
|
||||
int rc = rad_memcpy_async(dst, rows.data(), bytes, st);
|
||||
const int sy = rad_stream_sync(st);
|
||||
rad_stream_destroy(st);
|
||||
dev_page_invalidate(dst, bytes);
|
||||
if (rc < 0 || sy < 0) {
|
||||
*err = fmt("rank %zu: the copy into control-vector slot %d failed: %s", ri, slot,
|
||||
rad_dev_last_error());
|
||||
return RAD_E_DEVICE;
|
||||
}
|
||||
}
|
||||
std::copy(rows.begin(), rows.end(), cvec_.dir.begin() + (size_t)slot * rows.size());
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Engine::cvec_write(int slot, const std::vector<float>& rows, std::string* err) {
|
||||
/* A step loop that is parked, or resting for a park, sleeps and would never run the copy; a
|
||||
* parked model's memory is off the card too. One that is stopping may not pass another step. */
|
||||
if (parked() || hold_req_.load(std::memory_order_acquire)) {
|
||||
*err = "the model is parked or parking; retry once a request has woken it";
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (stopping() || !serving()) {
|
||||
*err = "the engine is not serving; nothing was written";
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
bool touched = false;
|
||||
const int rc = run_quiet([&]() -> int {
|
||||
touched = true;
|
||||
return cvec_copy(slot, rows, err);
|
||||
});
|
||||
if (rc < 0 && !touched) {
|
||||
*err = "the engine is stopping or its device fence failed; nothing was written";
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
return rc;
|
||||
}
|
||||
|
||||
std::string Engine::cvec_list_json() const {
|
||||
if (!cvec_slots_) return "{}";
|
||||
Json o = Json::parse(cvec_slots_->json());
|
||||
o["default"] = cvec_default_.load();
|
||||
return o.dump();
|
||||
}
|
||||
|
||||
int Engine::cvec_upload_bytes(const std::string& name, std::vector<uint8_t> bytes,
|
||||
const CvecTune& tune, std::string* err) {
|
||||
if (!cvec_slots_) { *err = "this deployment has no control-vector slots"; return RAD_E_UNSUPPORTED; }
|
||||
ControlVector cv;
|
||||
RAD_TRY(control_vector_load_bytes(std::move(bytes), "upload '" + name + "'",
|
||||
cvec_slots_->arch(), cvec_slots_->n_embd(),
|
||||
cvec_slots_->n_layers(), &cv, err, tune));
|
||||
const int rc = cvec_slots_->install(name, cv, cvec_writer(), err);
|
||||
if (rc == RAD_OK)
|
||||
RAD_INFO("control vectors: '%s' uploaded (%s): layers %d..%d, strength %.3f", name.c_str(),
|
||||
control_vector_mode_name(cv.mode), cv.first, cv.last, (double)cv.user_scale);
|
||||
return rc;
|
||||
}
|
||||
|
||||
int Engine::cvec_upload_path(const std::string& name, const std::string& path,
|
||||
const CvecTune& tune, std::string* err) {
|
||||
if (!cvec_slots_) { *err = "this deployment has no control-vector slots"; return RAD_E_UNSUPPORTED; }
|
||||
ControlVector cv;
|
||||
RAD_TRY(control_vector_load_upload(path, cvec_slots_->arch(), cvec_slots_->n_embd(),
|
||||
cvec_slots_->n_layers(), &cv, err, tune));
|
||||
const int rc = cvec_slots_->install(name, cv, cvec_writer(), err);
|
||||
if (rc == RAD_OK)
|
||||
RAD_INFO("control vectors: '%s' loaded from %s (%s): layers %d..%d, strength %.3f",
|
||||
name.c_str(), path.c_str(), control_vector_mode_name(cv.mode),
|
||||
cv.first, cv.last, (double)cv.user_scale);
|
||||
return rc;
|
||||
}
|
||||
|
||||
int Engine::cvec_retune(const std::string& name, const CvecTune& tune, std::string* err) {
|
||||
if (!cvec_slots_) { *err = "this deployment has no control-vector slots"; return RAD_E_UNSUPPORTED; }
|
||||
const int rc = cvec_slots_->retune(name, tune, cvec_writer(), err);
|
||||
if (rc == RAD_OK) RAD_INFO("control vectors: '%s' re-tuned", name.c_str());
|
||||
return rc;
|
||||
}
|
||||
|
||||
int Engine::cvec_remove(const std::string& name, std::string* err) {
|
||||
if (!cvec_slots_) { *err = "this deployment has no control-vector slots"; return RAD_E_UNSUPPORTED; }
|
||||
const int rc = cvec_slots_->remove(name, err, &cvec_default_);
|
||||
if (rc == RAD_OK) RAD_INFO("control vectors: '%s' deleted", name.c_str());
|
||||
return rc;
|
||||
}
|
||||
|
||||
/* The control vector, for /stats and /server_info. `available` is
|
||||
* what a client should test before sending the field: without a loaded vector a request that asks
|
||||
* for it is refused, so a UI can hide the control rather than offer a switch that fails. */
|
||||
@@ -3242,7 +3353,28 @@ std::string Engine::cvec_json() const {
|
||||
o["n_layers"] = cvec_.n_layers;
|
||||
o["scale"] = cvec_.user_scale;
|
||||
o["file"] = cvec_.path;
|
||||
o["mode"] = "project";
|
||||
CvecMode mode = cvec_.mode;
|
||||
if (cvec_slots_) {
|
||||
/* The range, strength and file are the default slot's; zero and "" while it holds
|
||||
* nothing, so the keys a client reads are always there. */
|
||||
o["first"] = 0;
|
||||
o["last"] = 0;
|
||||
o["scale"] = 0.0;
|
||||
o["file"] = "";
|
||||
o["slots"] = cvec_slots_->size();
|
||||
o["default_name"] = kCvecDefaultSlot;
|
||||
mode = CvecMode::Project;
|
||||
int first = 0, last = 0;
|
||||
float strength = 0.0f;
|
||||
std::string source;
|
||||
if (cvec_slots_->info(kCvecDefaultSlot, &first, &last, &strength, &source, &mode)) {
|
||||
o["first"] = first;
|
||||
o["last"] = last;
|
||||
o["scale"] = strength;
|
||||
o["file"] = source;
|
||||
}
|
||||
}
|
||||
o["mode"] = control_vector_mode_name(mode);
|
||||
}
|
||||
return o.dump();
|
||||
}
|
||||
@@ -3733,7 +3865,29 @@ int Engine::run_server() {
|
||||
d.control_vector.available = [this] { return cvec_loaded(); };
|
||||
d.control_vector.get_default = [this] { return cvec_default_on(); };
|
||||
d.control_vector.set_default = [this](bool on) { set_cvec_default(on); };
|
||||
d.control_vector.is_add = [this] { return !cvec_slotted() && cvec_.mode == CvecMode::Add; };
|
||||
d.control_vector.json = [this] { return cvec_json(); };
|
||||
if (cvec_slotted()) {
|
||||
d.control_vector.acquire = [this](const std::string& n, CvecSlots::Lease* l,
|
||||
std::string* e) { return cvec_acquire(n, l, e); };
|
||||
d.control_vector.enable_default = [this](std::string* e) {
|
||||
return cvec_slots_->enable_default(&cvec_default_, e);
|
||||
};
|
||||
d.control_vector.list = [this] { return cvec_list_json(); };
|
||||
d.control_vector.upload = [this](const std::string& n, std::vector<uint8_t> b,
|
||||
const CvecTune& t, std::string* e) {
|
||||
return cvec_upload_bytes(n, std::move(b), t, e);
|
||||
};
|
||||
d.control_vector.upload_path = [this](const std::string& n, const std::string& p,
|
||||
const CvecTune& t, std::string* e) {
|
||||
return cvec_upload_path(n, p, t, e);
|
||||
};
|
||||
d.control_vector.retune = [this](const std::string& n, const CvecTune& t,
|
||||
std::string* e) { return cvec_retune(n, t, e); };
|
||||
d.control_vector.remove = [this](const std::string& n, std::string* e) {
|
||||
return cvec_remove(n, e);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/* An embedding model serves /v1/embeddings and no chat. Its named prompts are the checkpoint's
|
||||
@@ -4667,6 +4821,9 @@ int Engine::run_server() {
|
||||
/* Startup ends here; a quiet server from now on is an idle one. */
|
||||
startup_watch_.reset();
|
||||
srv.note_ready(startup_begin_ns_);
|
||||
/* With slots the upload that woke this model runs as soon as the front opens, and writes only
|
||||
* while the engine is serving. */
|
||||
if (cvec_slots_) serving_.store(true, std::memory_order_release);
|
||||
front_->attach(cfg_.served_model_name, front_aliases_, &srv);
|
||||
serving_.store(true, std::memory_order_release);
|
||||
RAD_INFO("model %s: ready", cfg_.served_model_name.c_str());
|
||||
|
||||
+39
-2
@@ -228,6 +228,25 @@ public:
|
||||
bool cvec_loaded() const { return cvec_.loaded(); }
|
||||
bool cvec_default_on() const { return cvec_default_.load(); }
|
||||
void set_cvec_default(bool on) { cvec_default_.store(on); }
|
||||
int64_t max_seqs() const { return cfg_.max_seqs; }
|
||||
int64_t max_in_flight() const {
|
||||
const int64_t v = sched_.max_in_flight();
|
||||
return cfg_.max_seqs > 0 && v > cfg_.max_seqs ? cfg_.max_seqs : v;
|
||||
}
|
||||
int set_max_in_flight(int64_t n) { return sched_.set_max_in_flight(n); }
|
||||
/* --control-vector-slots (core/cvec.h, CvecSlots). With slots a request resolves the name it
|
||||
* wants to a claim before it is submitted; the admin calls change what a name holds, from any
|
||||
* thread but the step loop's, and return what CvecSlots returns (RAD_E_STATE also for a
|
||||
* parked or stopping engine, nothing written). */
|
||||
bool cvec_slotted() const { return cvec_slots_ != nullptr; }
|
||||
int cvec_acquire(const std::string& name, CvecSlots::Lease* out, std::string* err);
|
||||
std::string cvec_list_json() const;
|
||||
int cvec_upload_bytes(const std::string& name, std::vector<uint8_t> bytes,
|
||||
const CvecTune& tune, std::string* err);
|
||||
int cvec_upload_path(const std::string& name, const std::string& path, const CvecTune& tune,
|
||||
std::string* err);
|
||||
int cvec_retune(const std::string& name, const CvecTune& tune, std::string* err);
|
||||
int cvec_remove(const std::string& name, std::string* err);
|
||||
/* {available, default, mode, first, last, n_embd, n_layers, scale, file} for /stats, the
|
||||
* admin route and the dashboard. */
|
||||
std::string cvec_json() const;
|
||||
@@ -423,9 +442,16 @@ private:
|
||||
std::vector<TableCopy> table_files_;
|
||||
std::vector<const void*> table_file_src_; /* the container address each of table_files_ replaces */
|
||||
int table_file_map(const uint8_t* src, int64_t n, int64_t foff, void** out, std::string* why);
|
||||
/* --expert-profile: the decode ranking loaded once, before any rank plans, and handed to every
|
||||
* rank's planner in place of the container's activation profile. */
|
||||
/* --expert-profile: the decode ranking loaded once, before any rank declares, handed to the
|
||||
* plugin (rad_expert_profile) and to every rank's planner in place of the container's
|
||||
* activation profile. */
|
||||
std::vector<RadFileProfile> expert_profile_;
|
||||
int expert_profile_load();
|
||||
/* `prof` (model-wide expert ids) as rank `prog`'s own expert indices, through the container's
|
||||
* directory; entries for experts the rank does not hold are dropped. RAD_E_NOTFOUND when the
|
||||
* directory numbers no expert unit of the program (a checkpoint served directly). */
|
||||
int profile_to_local(const Program& prog, const RadFileProfile* prof, int64_t n,
|
||||
std::vector<RadFileProfile>* out) const;
|
||||
int load_weights();
|
||||
void seal_base_weights();
|
||||
/* After a page-in: every weight with a byte in `spans` (memory the page-in mapped back empty,
|
||||
@@ -1001,6 +1027,17 @@ private:
|
||||
* reused by a step that would compute different hidden states from the same tokens. */
|
||||
ControlVector cvec_;
|
||||
std::vector<RadControlVector> cvec_views_;
|
||||
/* Null without --control-vector-slots. With them `cvec_` is the whole [slots, layers, n_embd]
|
||||
* table, scale 1 at every layer above 0, and cvec_salt_ is 0: each request carries its own. */
|
||||
std::unique_ptr<CvecSlots> cvec_slots_;
|
||||
int cvec_slots_bringup(const std::string& file, const std::string& tried);
|
||||
int cvec_write(int slot, const std::vector<float>& rows, std::string* err);
|
||||
int cvec_copy(int slot, const std::vector<float>& rows, std::string* err);
|
||||
CvecSlots::Writer cvec_writer() {
|
||||
return [this](int slot, const std::vector<float>& rows, std::string* err) {
|
||||
return cvec_write(slot, rows, err);
|
||||
};
|
||||
}
|
||||
uint64_t cvec_salt_ = 0;
|
||||
/* Runtime default for requests that name no choice (flippable through
|
||||
* POST /admin/control-vector). Atomic: the server's admin thread writes it while
|
||||
|
||||
+336
-49
@@ -1103,6 +1103,8 @@ RadBuildCtx Engine::build_ctx(int rank, int64_t max_tok) const {
|
||||
/* The engine always states the KV dtype. RAD_DT_INVALID (zero) remains valid in the ABI for
|
||||
* other callers and means the plugin's default. */
|
||||
bc.kv_dtype = cfg_.kv_cache_dtype == "i8" ? RAD_I8
|
||||
: cfg_.kv_cache_dtype == "i4r" ? RAD_I4R
|
||||
: cfg_.kv_cache_dtype == "i6r" ? RAD_I6R
|
||||
: cfg_.kv_cache_dtype == "fp8" ? RAD_F8E4M3 : RAD_BF16;
|
||||
bc.tp_attn_rows = cfg_.tp_attn_rows;
|
||||
bc.weight_prefetch_off = cfg_.weight_prefetch ? 0 : 1;
|
||||
@@ -1134,6 +1136,9 @@ RadBuildCtx Engine::build_ctx(int rank, int64_t max_tok) const {
|
||||
bc.kv_resident_blocks = cfg_.kv_resident > 0 && cfg_.kv_resident < kStreamFloorTokens
|
||||
? kStreamFloorTokens
|
||||
: cfg_.kv_resident;
|
||||
/* --kv-host-tokens, only under a ring: the id space kv_resolve declares as `blocks`, which must
|
||||
* be the residency map's length (KVStreamStore::context_blocks, kvstream_id_blocks). */
|
||||
bc.kv_host_tokens = cfg_.kv_resident > 0 ? cfg_.kv_host_tokens : 0;
|
||||
/* A streamed-only op is declared only when the architecture streams and the flag asks
|
||||
* (kvstream_op_gated). */
|
||||
bc.kv_stream_ok = arch_probe_.kv_stream_ok;
|
||||
@@ -1146,6 +1151,64 @@ RadBuildCtx Engine::build_ctx(int rank, int64_t max_tok) const {
|
||||
return bc;
|
||||
}
|
||||
|
||||
int Engine::cvec_slots_bringup(const std::string& file, const std::string& tried) {
|
||||
const std::string arch = meta_.arch_id ? meta_.arch_id : "";
|
||||
const int n = cfg_.control_vector_slots;
|
||||
if (!CvecSlots::fits(n, meta_.n_layers, meta_.n_embd)) {
|
||||
RAD_ERR("--control-vector-slots %d: a table of %d x %lld x %lld elements is past what a "
|
||||
"row's int32 switch can address", n, n, (long long)meta_.n_layers,
|
||||
(long long)meta_.n_embd);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* No file is required unless the default is to start on; one that is found must load, and
|
||||
* fills slot 0. */
|
||||
if (file.empty() && cfg_.control_vector == "on") {
|
||||
RAD_ERR("--control-vector on with --control-vector-slots: no control vector found for the "
|
||||
"slot '%s' (looked at %s); provide the file, or start with --control-vector off and "
|
||||
"turn the default on after uploading '%s'", kCvecDefaultSlot, tried.c_str(),
|
||||
kCvecDefaultSlot);
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
ControlVector cv;
|
||||
std::string why;
|
||||
if (!file.empty() &&
|
||||
control_vector_load(file, arch, meta_.n_embd, meta_.n_layers, &cv, &why) != RAD_OK) {
|
||||
RAD_ERR("--control-vector-slots: %s", why.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* The whole table, each layer above 0 declared with the found file's scale where it steers and
|
||||
* 1 elsewhere: what a slot holds is folded into its rows against these
|
||||
* (control_vector_fold), and an empty slot's rows are zero. */
|
||||
std::vector<float> base = control_vector_base_scales(cv);
|
||||
if (base.empty()) {
|
||||
base.assign((size_t)meta_.n_layers, 1.0f);
|
||||
base[0] = 0.0f;
|
||||
}
|
||||
auto slots = std::make_unique<CvecSlots>(n, arch, meta_.n_embd, meta_.n_layers, base);
|
||||
ControlVector table;
|
||||
table.n_embd = meta_.n_embd;
|
||||
table.n_layers = meta_.n_layers;
|
||||
table.first = 1;
|
||||
table.last = (int)meta_.n_layers - 1;
|
||||
table.scales = base;
|
||||
table.dir.assign((size_t)n * (size_t)slots->block_elems(), 0.0f);
|
||||
if (!file.empty()) {
|
||||
std::vector<float> rows;
|
||||
int rc = control_vector_fold(cv, &rows, &why, &base);
|
||||
if (rc == RAD_OK) rc = slots->seed(kCvecDefaultSlot, cv, &why);
|
||||
if (rc != RAD_OK) {
|
||||
RAD_ERR("--control-vector-slots: %s: %s", file.c_str(), why.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
std::copy(rows.begin(), rows.end(), table.dir.begin());
|
||||
table.n_dirs = cv.n_dirs;
|
||||
table.path = file;
|
||||
}
|
||||
cvec_ = std::move(table);
|
||||
cvec_slots_ = std::move(slots);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Engine::declare() {
|
||||
/* An architecture that declares no streamed ops cannot stream, so with --kv-resident set on one
|
||||
* the flag is turned off here, with the decision named, before anything is planned for it. */
|
||||
@@ -1557,14 +1620,16 @@ int Engine::declare() {
|
||||
const std::string arch = meta_.arch_id ? meta_.arch_id : "";
|
||||
std::string proj_path, tried;
|
||||
(void) control_vector_discover(cfg_.model, arch, cfg_.radiance_home, &proj_path, &tried);
|
||||
if (proj_path.empty()) {
|
||||
std::string why;
|
||||
if (cfg_.control_vector_slots > 0) {
|
||||
/* A table of slots, uploaded to while serving. */
|
||||
RAD_TRY(cvec_slots_bringup(proj_path, tried));
|
||||
} else if (proj_path.empty()) {
|
||||
RAD_ERR("--control-vector %s: no control vector found for this model (looked at %s)",
|
||||
cfg_.control_vector.c_str(), tried.c_str());
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
std::string why;
|
||||
if (control_vector_load(proj_path, arch, meta_.n_embd, meta_.n_layers, &cvec_, &why) !=
|
||||
RAD_OK) {
|
||||
} else if (control_vector_load(proj_path, arch, meta_.n_embd, meta_.n_layers, &cvec_,
|
||||
&why) != RAD_OK) {
|
||||
RAD_ERR("--control-vector %s: %s", cfg_.control_vector.c_str(), why.c_str());
|
||||
cvec_ = ControlVector{};
|
||||
return RAD_E_INVAL;
|
||||
@@ -1572,26 +1637,43 @@ int Engine::declare() {
|
||||
}
|
||||
if (cvec_.loaded()) {
|
||||
cvec_views_.assign(ranks_.size(), RadControlVector{});
|
||||
cvec_salt_ = control_vector_salt(cvec_);
|
||||
/* With slots each request carries its slot's salt (Request::cvec_salt). */
|
||||
cvec_salt_ = cvec_slots_ ? 0 : control_vector_salt(cvec_);
|
||||
/* The request default; --kld-record / --kld-ref score documents with it, as they serve no
|
||||
* request that could carry the field. */
|
||||
const bool default_on = cfg_.control_vector == "on";
|
||||
cvec_default_.store(default_on);
|
||||
RAD_INFO("control vectors: %s: %lld directions of %lld, layers %d..%d, scale %.3f -- "
|
||||
"default %s%s",
|
||||
cvec_.path.c_str(), (long long) cvec_.n_dirs,
|
||||
(long long) cvec_.n_embd, cvec_.first, cvec_.last, (double) cvec_.user_scale,
|
||||
default_on ? "ON" : "off",
|
||||
default_on ? " (--control-vector on; a request can still say false)"
|
||||
: " until a request asks for it (the dashboard's switch, or a request's "
|
||||
"`control_vector` field)");
|
||||
decide("control vectors", cvec_.path,
|
||||
"found beside the container, in its directory, or in $RADIANCE_HOME/vectors; "
|
||||
"requests opt in");
|
||||
if (cvec_slots_) {
|
||||
const bool filled = cvec_slots_->has(kCvecDefaultSlot);
|
||||
RAD_INFO("control vectors: %d slots of %lld x %lld; slot '%s' %s%s -- default %s",
|
||||
cvec_slots_->size(), (long long) cvec_.n_layers, (long long) cvec_.n_embd,
|
||||
kCvecDefaultSlot, filled ? "holds " : "is empty",
|
||||
filled ? cvec_.path.c_str() : " (upload one: POST /admin/control-vectors)",
|
||||
default_on ? "ON" : "off");
|
||||
decide("control vectors", std::to_string(cvec_slots_->size()) + " slots",
|
||||
"--control-vector-slots; uploads last until the model is unloaded");
|
||||
} else {
|
||||
RAD_INFO("control vectors: %s: %lld directions of %lld, layers %d..%d, scale %.3f -- "
|
||||
"default %s%s",
|
||||
cvec_.path.c_str(), (long long) cvec_.n_dirs,
|
||||
(long long) cvec_.n_embd, cvec_.first, cvec_.last, (double) cvec_.user_scale,
|
||||
default_on ? "ON" : "off",
|
||||
default_on ? " (--control-vector on; a request can still say false)"
|
||||
: " until a request asks for it (the dashboard's switch, or a request's "
|
||||
"`control_vector` field)");
|
||||
decide("control vectors", cvec_.path,
|
||||
"found beside the container, in its directory, or in $RADIANCE_HOME/vectors; "
|
||||
"requests opt in");
|
||||
}
|
||||
} else {
|
||||
cvec_default_.store(false);
|
||||
}
|
||||
|
||||
/* --expert-profile, read before the declare: the planner ranks residency by it, and a plugin
|
||||
* may derive its expert-parallel split from it (rad_expert_profile), which every rank must
|
||||
* see alike. */
|
||||
RAD_TRY(expert_profile_load());
|
||||
|
||||
/* Declare once per rank (rank and world_size in RadBuildCtx; the plugin declares dimensions
|
||||
* already divided, spec §9), every rank concurrently on its own thread. Concurrency is
|
||||
* required: kernel init() runs during declare, and a collective's init is a rendezvous
|
||||
@@ -1634,7 +1716,8 @@ int Engine::declare() {
|
||||
return declare_sampler(ri, bb, lw);
|
||||
},
|
||||
nullptr, sources(), true,
|
||||
cfg_.lora.enabled() ? &ld : nullptr);
|
||||
cfg_.lora.enabled() ? &ld : nullptr,
|
||||
&expert_profile_);
|
||||
});
|
||||
}
|
||||
/* A message is a step's bf16 residual rows, so the floor is a row count: a decode step has
|
||||
@@ -1690,6 +1773,49 @@ int Engine::declare() {
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
}
|
||||
/* With control-vector slots one launch serves rows with different directions, which a kernel
|
||||
* must advertise. Additive steering (single-vector or slots) requires RAD_KERNEL_CAP_CVEC_ADD;
|
||||
* project-only setups without additive vectors remain compatible with older kernels. */
|
||||
if (cvec_slots_) {
|
||||
bool add_ok = true;
|
||||
std::string add_why;
|
||||
for (auto& r : ranks_) {
|
||||
r->program.cvec_slots = true;
|
||||
std::string why;
|
||||
if (control_vector_check_kernels(r->program, &why,
|
||||
RAD_KERNEL_CAP_CVEC_ROW_OFFSET) != RAD_OK) {
|
||||
RAD_ERR("--control-vector-slots %d: rank %d: %s", cfg_.control_vector_slots,
|
||||
r->index, why.c_str());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (add_ok &&
|
||||
control_vector_check_kernels(r->program, &add_why,
|
||||
RAD_KERNEL_CAP_CVEC_ADD) != RAD_OK) {
|
||||
add_ok = false;
|
||||
}
|
||||
}
|
||||
cvec_slots_->set_allow_add(add_ok);
|
||||
int first = 0, last = 0;
|
||||
float strength = 0.0f;
|
||||
std::string source;
|
||||
CvecMode def_mode = CvecMode::Project;
|
||||
if (!add_ok &&
|
||||
cvec_slots_->info(kCvecDefaultSlot, &first, &last, &strength, &source, &def_mode) &&
|
||||
def_mode == CvecMode::Add) {
|
||||
RAD_ERR("--control-vector-slots %d: startup additive vector: %s",
|
||||
cfg_.control_vector_slots, add_why.c_str());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
} else if (cvec_.loaded() && cvec_.mode == CvecMode::Add) {
|
||||
for (auto& r : ranks_) {
|
||||
std::string why;
|
||||
if (control_vector_check_kernels(r->program, &why, RAD_KERNEL_CAP_CVEC_ADD) != RAD_OK) {
|
||||
RAD_ERR("--control-vector %s: rank %d: %s", cfg_.control_vector.c_str(),
|
||||
r->index, why.c_str());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
}
|
||||
}
|
||||
/* Checkpoint weights that cannot be served as stored cannot be loaded; name them all with the
|
||||
* remedy. */
|
||||
if (ckpt_src_) {
|
||||
@@ -1867,7 +1993,8 @@ void Engine::probe_arena_levels() {
|
||||
true);
|
||||
},
|
||||
&r.program, sources(), true,
|
||||
cfg_.lora.enabled() ? &ld : nullptr);
|
||||
cfg_.lora.enabled() ? &ld : nullptr,
|
||||
&expert_profile_);
|
||||
if (st < 0) why[k] = fmt("the sizing declare failed: %s", rad_strerror(st));
|
||||
else if (plan_level(r.program, probe, want[l], &got[k], &why[k]) >= 0)
|
||||
ok[k] = 1;
|
||||
@@ -2084,12 +2211,16 @@ int Engine::plan() {
|
||||
}
|
||||
/* The pinned host pool is the experts' other home, less the file tier's staging, which
|
||||
* Planner::plan takes first. A host-placed embedding has its own room
|
||||
* (Config::embedding_host_mib). */
|
||||
* (Config::embedding_host_mib). With --weights-disk-tier on, routed experts past VRAM and
|
||||
* the host pool stream from the container a layer at a time, so VRAM needs at most the
|
||||
* file stager's two layer buffers (file_stage_vram), not every spilling expert. */
|
||||
for (size_t i = 0; i < facts.size(); ++i) {
|
||||
int64_t room = cfg_.host_pool_mib * ((int64_t)1 << 20);
|
||||
if (cfg_.weights_disk_tier)
|
||||
room -= file_stage_reserve(wfs[i].layer_unit_max, wfs[i].routed);
|
||||
facts[i].expert_floor = expert_vram_floor(wfs[i], std::max<int64_t>(room, 0));
|
||||
int64_t floor = expert_vram_floor(wfs[i], std::max<int64_t>(room, 0));
|
||||
if (cfg_.weights_disk_tier) floor = std::min(floor, file_stage_vram(wfs[i]));
|
||||
facts[i].expert_floor = floor;
|
||||
}
|
||||
/* Capped well below overflow, so the sums it joins stay defined: a store that large is
|
||||
* refused by name in configure_kv. Under --checkpoint-slots auto the store is sized in
|
||||
@@ -2226,8 +2357,10 @@ int Engine::plan() {
|
||||
int64_t room = cfg_.host_pool_mib * MiB;
|
||||
if (cfg_.weights_disk_tier)
|
||||
room -= file_stage_reserve(wfs[i].layer_unit_max, wfs[i].routed);
|
||||
facts[i].expert_floor = expert_vram_floor_draft_hosted(
|
||||
int64_t floor = expert_vram_floor_draft_hosted(
|
||||
wfs[i], std::max<int64_t>(room - align_up(wfs[i].draft_experts, MiB), 0));
|
||||
if (cfg_.weights_disk_tier) floor = std::min(floor, file_stage_vram(wfs[i]));
|
||||
facts[i].expert_floor = floor;
|
||||
facts[i].experts = std::max<int64_t>(wfs[i].experts - wfs[i].draft_experts, 0);
|
||||
}
|
||||
RAD_INFO("placement: --draft-expert-placement host pins %s of drafter experts a "
|
||||
@@ -2367,6 +2500,113 @@ int Engine::plan() {
|
||||
ranks_[i]->device, (long long)add);
|
||||
}
|
||||
}
|
||||
/* What each rank's host pool must hold: every weight resident, less its weights pool. */
|
||||
auto overflow_mib = [&]() {
|
||||
std::vector<int64_t> over(ranks_.size(), 0);
|
||||
for (size_t i = 0; i < ranks_.size(); ++i) {
|
||||
const int64_t cap = facts[i].statics + expert_vram_floor(wfs[i], 0);
|
||||
int64_t diff = std::max<int64_t>(0, cap - rank_cfg_[i].vram_weights_mib * kMiB);
|
||||
if (diff > 0 && cfg_.weights_disk_tier)
|
||||
diff += file_stage_reserve(wfs[i].layer_unit_max, wfs[i].routed);
|
||||
over[i] = (diff + kMiB - 1) / kMiB;
|
||||
}
|
||||
return over;
|
||||
};
|
||||
/* A rank whose activation arena is smaller than the dearest rank's (an attention-zero rank
|
||||
* plans no attention buffers) was charged the larger one by the common split. The
|
||||
* difference is program arithmetic, not a reading, and goes to its weights pool, up to all
|
||||
* of its weights resident: the same move as the KV re-split above. */
|
||||
for (size_t i = 0; i < facts.size() && cfg_.placement == "expert_tiered"; ++i) {
|
||||
const int64_t saved = std::max<int64_t>(vb.arena - facts[i].arena, 0) / kMiB;
|
||||
const int64_t cap =
|
||||
(facts[i].statics + expert_vram_floor(wfs[i], 0) + kMiB - 1) / kMiB;
|
||||
const int64_t add = std::min(saved,
|
||||
std::max<int64_t>(cap - rank_cfg_[i].vram_weights_mib, 0));
|
||||
if (add <= 0) continue;
|
||||
RAD_INFO("arena: rank %d's activation arena is %s where the dearest rank's is %s, so "
|
||||
"its weights pool grows %lld -> %lld MiB (every weight resident wants %lld "
|
||||
"MiB)", ranks_[i]->index, humanb(facts[i].arena).c_str(),
|
||||
humanb(vb.arena).c_str(), (long long)rank_cfg_[i].vram_weights_mib,
|
||||
(long long)(rank_cfg_[i].vram_weights_mib + add), (long long)cap);
|
||||
rank_cfg_[i].vram_weights_mib += add;
|
||||
}
|
||||
/* ---- uneven worlds: each rank's own prefill staging ring ------------------------------
|
||||
*
|
||||
* The common split sized none (VramBudget::stage_per_rank): its floor was the dearest
|
||||
* rank's against an even share of the host pool, which the block below re-splits by
|
||||
* overflow. Here each rank sizes its ring against its own final weights pool. A rank with
|
||||
* every expert on the card needs none; one that leaves experts off pays for its ring with
|
||||
* expert residency, whose experts join its overflow, while the model's host pool has room
|
||||
* for them after every rank's overflow (the split below then gives each rank exactly its
|
||||
* own). The ring sits at the arena's top and is lent back to the slab at decode, as in an
|
||||
* even world. */
|
||||
std::vector<int64_t> rank_stage(ranks_.size(), 0);
|
||||
if (vb.stage_per_rank) {
|
||||
const std::vector<int64_t> over = overflow_mib();
|
||||
int64_t room = cfg_.host_pool_mib * (int64_t)ranks_.size();
|
||||
for (int64_t o : over) room -= o;
|
||||
std::string rows;
|
||||
for (size_t i = 0; i < ranks_.size(); ++i) {
|
||||
const RankStage st = vram_budget_rank_stage(
|
||||
rank_cfg_[i].vram_weights_mib, facts[i].statics, facts[i].experts,
|
||||
facts[i].expert_layer_max, std::max<int64_t>(room, 0));
|
||||
if (st.stage > 0) {
|
||||
RAD_INFO("prefill ring: rank %d leaves %s of its experts off the card, so its "
|
||||
"ring is two buffers of %s, out of its experts: its weights pool "
|
||||
"%lld -> %lld MiB, and its host pool holds %lld MiB more (%lld MiB of "
|
||||
"the model's --host-pool-mib left after it)",
|
||||
ranks_[i]->index, humanb(st.off_card).c_str(),
|
||||
humanb(st.stage / 2).c_str(), (long long)rank_cfg_[i].vram_weights_mib,
|
||||
(long long)st.weights_mib, (long long)st.pool_mib,
|
||||
(long long)(room - st.pool_mib));
|
||||
rank_cfg_[i].vram_weights_mib = st.weights_mib;
|
||||
rank_stage[i] = st.stage;
|
||||
room -= st.pool_mib;
|
||||
} else if (st.no_room) {
|
||||
RAD_INFO("prefill ring: rank %d leaves %s of its experts off the card but gets "
|
||||
"no ring: the host pool has %lld MiB left after every rank's overflow, "
|
||||
"too little for the experts the ring would displace; a larger "
|
||||
"--host-pool-mib makes room", ranks_[i]->index,
|
||||
humanb(st.off_card).c_str(), (long long)std::max<int64_t>(room, 0));
|
||||
} else if (facts[i].expert_layer_max > 0) {
|
||||
RAD_INFO("prefill ring: rank %d holds every expert on the card and needs none",
|
||||
ranks_[i]->index);
|
||||
}
|
||||
rows += fmt("%srank %d %s", i ? ", " : "", ranks_[i]->index,
|
||||
st.stage > 0 ? humanb(st.stage).c_str()
|
||||
: st.no_room ? "none (no host-pool room)" : "none (all resident)");
|
||||
}
|
||||
decide("prefill staging", rows,
|
||||
"an uneven world: each rank's ring is sized against its own pools, out of its "
|
||||
"own experts, which the host pool then holds");
|
||||
}
|
||||
/* Overflow-proportional host-pool re-split: when ranks hold unequal expert counts or
|
||||
* per-card VRAM, move host-pool room from ranks whose weights fit in VRAM to peers that
|
||||
* overflow. */
|
||||
if (ranks_.size() > 1 && cfg_.host_pool_mib > 0 && cfg_.placement == "expert_tiered") {
|
||||
const std::vector<int64_t> over = overflow_mib();
|
||||
std::vector<int64_t> split;
|
||||
if (vram_budget_host_pool_split(over, cfg_.host_pool_mib * (int64_t)ranks_.size(),
|
||||
&split)) {
|
||||
std::string msg;
|
||||
for (size_t i = 0; i < ranks_.size(); ++i) {
|
||||
rank_cfg_[i].host_pool_mib = split[i];
|
||||
if (split[i] == 0 && over[i] == 0) rank_cfg_[i].weights_disk_tier = false;
|
||||
msg += fmt("%srank %zu %lld MiB", i ? ", " : "", i, (long long)split[i]);
|
||||
}
|
||||
RAD_INFO("host pool: re-split by per-rank overflow (%s)", msg.c_str());
|
||||
}
|
||||
}
|
||||
/* Each rank's own ring, above every planned buffer, as the common one is placed above. */
|
||||
for (size_t i = 0; i < ranks_.size(); ++i) {
|
||||
if (rank_stage[i] <= 0) continue;
|
||||
auto& r = ranks_[i];
|
||||
int64_t dev = 0;
|
||||
arena_plan_bytes(r->program, &dev, nullptr);
|
||||
r->program.arena_stage_off = align_up(dev, RAD_ALIGN_UNIT);
|
||||
r->program.arena_stage_bytes = rank_stage[i];
|
||||
r->program.arena_bytes = r->program.arena_stage_off + rank_stage[i];
|
||||
}
|
||||
}
|
||||
|
||||
for (size_t ri = 0; ri < ranks_.size(); ++ri) {
|
||||
@@ -2401,25 +2641,23 @@ int Engine::plan() {
|
||||
in.n_profile = (int64_t)file_->header().prof_count;
|
||||
}
|
||||
/* --expert-profile replaces the container's activation profile, which is prefill-heavy
|
||||
* while decode-hot experts differ (--expert-pin-top keeps them resident). Loaded once, at
|
||||
* the first rank's plan, so every rank ranks the same way. */
|
||||
if (!cfg_.expert_profile.empty()) {
|
||||
if (expert_profile_.empty() && ri == 0) {
|
||||
int32_t trunk = -1;
|
||||
const int pr = xs_profile_load(cfg_.expert_profile, &expert_profile_, &trunk);
|
||||
if (pr < 0) return pr;
|
||||
/* A profile from another model would rank its layers onto this one's. */
|
||||
if (trunk >= 0 && trunk != (int32_t)meta_.n_layers) {
|
||||
RAD_ERR("--expert-profile: %s counts %d trunk layers and this model has %d: "
|
||||
"it was recorded on another model", cfg_.expert_profile.c_str(),
|
||||
(int)trunk, (int)meta_.n_layers);
|
||||
expert_profile_.clear();
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
if (!expert_profile_.empty()) {
|
||||
in.profile = expert_profile_.data();
|
||||
in.n_profile = (int64_t)expert_profile_.size();
|
||||
* while decode-hot experts differ (--expert-pin-top keeps them resident). Loaded once,
|
||||
* before the declare (expert_profile_load), so every rank ranks the same way. */
|
||||
if (!expert_profile_.empty()) {
|
||||
in.profile = expert_profile_.data();
|
||||
in.n_profile = (int64_t)expert_profile_.size();
|
||||
}
|
||||
/* Both profiles number experts as the model does, and the planner keys a unit by its
|
||||
* group expert, the rank's own index: under expert parallelism rank r's expert e is the
|
||||
* model's base + e, or whatever the plugin's split made it. The container's directory
|
||||
* names each unit's expert (as for --expert-stats), so the entries are renumbered into
|
||||
* this rank's indices, and the experts it does not hold are dropped. */
|
||||
std::vector<RadFileProfile> local_profile;
|
||||
if (in.profile && in.n_profile > 0 && file_) {
|
||||
const int rc = profile_to_local(r->program, in.profile, in.n_profile, &local_profile);
|
||||
if (rc == RAD_OK) {
|
||||
in.profile = local_profile.data();
|
||||
in.n_profile = (int64_t)local_profile.size();
|
||||
}
|
||||
}
|
||||
in.container = file_ != nullptr;
|
||||
@@ -2450,11 +2688,11 @@ int Engine::plan() {
|
||||
}
|
||||
/* Every rank allocates its share of --host-pool-mib whole, so a re-split rank whose
|
||||
* weights all fit its grown pool still holds an empty host pool; log it. */
|
||||
if (rc.vram_kv_mib < cfg_.vram_kv_mib && cfg_.host_pool_mib > 0 &&
|
||||
if (rc.vram_kv_mib < cfg_.vram_kv_mib && rc.host_pool_mib > 0 &&
|
||||
r->plan.totals.bytes[(int)Tier::HostPinned] == 0)
|
||||
RAD_INFO("kv: rank %d's weights all fit its grown weights pool, so its pinned host pool "
|
||||
"holds no weights; its %lld MiB (its share of --host-pool-mib) stay allocated, as on "
|
||||
"every rank", r->index, (long long)cfg_.host_pool_mib);
|
||||
"holds no weights; its %lld MiB stay allocated, as configured", r->index,
|
||||
(long long)rc.host_pool_mib);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -4024,6 +4262,46 @@ static int fill_from_sidecar(const RadFile& side, const RadFileEntry& se, const
|
||||
* offsets depend on the rank index (rank 0 always starts at the plane's start, so it never
|
||||
* exercises the arithmetic), and an overrun would read the wrong weight. The load's walk and a
|
||||
* restore's refill (Engine::refill_weights) both plan through here. */
|
||||
int Engine::expert_profile_load() {
|
||||
if (cfg_.expert_profile.empty() || !expert_profile_.empty()) return RAD_OK;
|
||||
int32_t trunk = -1;
|
||||
const int pr = xs_profile_load(cfg_.expert_profile, &expert_profile_, &trunk);
|
||||
if (pr < 0) return pr;
|
||||
/* A profile from another model would rank its layers onto this one's. */
|
||||
if (trunk >= 0 && trunk != (int32_t)meta_.n_layers) {
|
||||
RAD_ERR("--expert-profile: %s counts %d trunk layers and this model has %d: it was "
|
||||
"recorded on another model", cfg_.expert_profile.c_str(), (int)trunk,
|
||||
(int)meta_.n_layers);
|
||||
expert_profile_.clear();
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Engine::profile_to_local(const Program& prog, const RadFileProfile* prof, int64_t n,
|
||||
std::vector<RadFileProfile>* out) const {
|
||||
out->clear();
|
||||
/* (layer, model expert) -> the rank's index: every weight of a unit names one expert. */
|
||||
std::map<std::pair<int32_t, int32_t>, int32_t> local;
|
||||
for (size_t w = 1; w < prog.weights.size(); ++w) {
|
||||
const WeightInfo& wi = prog.weights[w];
|
||||
const int32_t l = wi.decl.group.layer, e = wi.decl.group.expert;
|
||||
if (l < 0 || e < 0) continue;
|
||||
const RadFileEntry* fe = file_ ? file_->find(wi.source) : nullptr;
|
||||
if (!fe || fe->layer != l || fe->expert < 0) continue;
|
||||
local.emplace(std::make_pair(l, (int32_t)fe->expert), e);
|
||||
}
|
||||
if (local.empty()) return RAD_E_NOTFOUND;
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
auto it = local.find(std::make_pair(prof[i].layer, prof[i].expert));
|
||||
if (it == local.end()) continue;
|
||||
RadFileProfile p = prof[i];
|
||||
p.expert = it->second;
|
||||
out->push_back(p);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static int plan_container_weight(RadFile& file, const RadFileEntry& ent, const Program& prog,
|
||||
size_t wi, const PlaneShare* sh, int rank, int device,
|
||||
uint8_t* dst0, bool dev, std::vector<LoadRun>& runs,
|
||||
@@ -4507,7 +4785,7 @@ int Engine::refill_weights(const std::vector<PageSpan>& spans, const char* what,
|
||||
sw.wi = i;
|
||||
sw.device = r->device;
|
||||
sw.dst = const_cast<uint8_t*>(at);
|
||||
sw.dev = true;
|
||||
sw.dev = !host_only;
|
||||
sw.clip = &on;
|
||||
total += sw.lay_out_planes(sh, w.n_sel);
|
||||
std::vector<PlaneShare> shares(sh, sh + w.n_sel);
|
||||
@@ -5392,6 +5670,7 @@ int Engine::start() {
|
||||
RAD_TRY(load_weights());
|
||||
RAD_TRY(configure_kv());
|
||||
|
||||
bool stage_logged = false;
|
||||
for (auto& r : ranks_) {
|
||||
LogRank lr(r->index);
|
||||
RAD_TRY(rad_dev_set(r->device)); /* allocates on the current device; see plan() */
|
||||
@@ -5434,12 +5713,15 @@ int Engine::start() {
|
||||
base + r->program.arena_stage_off,
|
||||
r->arena_low_off >= 0 ? base + r->arena_low_off : nullptr,
|
||||
r->program.arena_stage_bytes, top_level + 1));
|
||||
if (r->stager.enabled() && r->index == 0)
|
||||
/* Once, from the first rank with a ring (an uneven world's ranks size their own). */
|
||||
if (r->stager.enabled() && !stage_logged) {
|
||||
stage_logged = true;
|
||||
RAD_INFO("prefill staging: a %s ring at the top of the arena; a step of more "
|
||||
"than %lld tokens copies the pooled experts of %zu routed layers onto "
|
||||
"the card up to %d layers ahead of the layers that read them",
|
||||
humanb(r->stager.ring_bytes()).c_str(), (long long)top_level,
|
||||
r->stager.n_layers(), (int)PrefillStager::lead());
|
||||
}
|
||||
}
|
||||
/* The file stager, wherever a routed expert is on the file tier (static or dynamic plan;
|
||||
* such a unit has no other address). Routing-aware reads take this
|
||||
@@ -5522,11 +5804,15 @@ int Engine::start() {
|
||||
{
|
||||
const KVManager& kv = ranks_[0]->kv;
|
||||
int64_t bytes = 0, state = 0, tokens = 0;
|
||||
/* What a token of context costs a card over every paged group (the attention cache at
|
||||
* --kv-cache-dtype plus any other paged group, such as an indexer's keys). */
|
||||
double per_tok = 0.0;
|
||||
for (const KVGroupPlan& p : kv.plans()) {
|
||||
bytes += kv.pool_bytes_carved(p.index);
|
||||
if (p.stateful()) state += kv.pool_bytes_carved(p.index);
|
||||
if (!p.paged() || (p.kind == RAD_KV_WINDOW && !p.runtime_win) || p.block_size <= 0)
|
||||
continue;
|
||||
per_tok += (double)p.bytes_per_block / (double)p.block_size;
|
||||
const int64_t t = p.n_blocks * p.block_size;
|
||||
if (tokens == 0 || t < tokens) tokens = t;
|
||||
}
|
||||
@@ -5543,10 +5829,11 @@ int Engine::start() {
|
||||
: "nothing is lent: it is all the cache's"));
|
||||
if (bytes > 0)
|
||||
RAD_INFO("kv: the cache can grow to %s a card -- %lld tokens of context, %.1f sessions at "
|
||||
"%lld -- with every block it lends the experts taken back; %s of that is "
|
||||
"per-sequence state, and %s",
|
||||
"%lld, %.2f KiB a token at kv-cache-dtype %s -- with every block it lends the "
|
||||
"experts taken back; %s of that is per-sequence state, and %s",
|
||||
humanb(bytes).c_str(), (long long)tokens,
|
||||
mlen > 0 ? (double)tokens / (double)mlen : 0.0, (long long)mlen,
|
||||
per_tok / 1024.0, cfg_.kv_cache_dtype.c_str(),
|
||||
humanb(state).c_str(),
|
||||
lent > 0 ? fmt("up to %s is lent to the experts while no request holds it",
|
||||
humanb(lent).c_str()).c_str()
|
||||
@@ -5867,7 +6154,7 @@ int Engine::load_vocab() {
|
||||
/* With tokenizer_config.json and chat_template.jinja: beside config.json in a model
|
||||
* repository, in a diffusers pipeline's processor/ or tokenizer/ folder. */
|
||||
const std::string tj = ckpt_->tok_dir() + "/tokenizer.json";
|
||||
if (parse_tokenizer_json(tj.c_str(), vb) < 0) {
|
||||
if (parse_tokenizer_json(tj.c_str(), vb, uses_qwen3_embedding_tokenizer(meta_)) < 0) {
|
||||
RAD_ERR("%s: no readable tokenizer.json in %s", cfg_.model.c_str(),
|
||||
ckpt_->tok_dir().c_str());
|
||||
return RAD_E_FORMAT;
|
||||
|
||||
@@ -142,6 +142,10 @@ void Engine::print_startup_report(int status) {
|
||||
std::vector<diag::ConfigRow> rows = diag::config_rows(cfg_);
|
||||
std::vector<diag::Decision> derived;
|
||||
diag::merge(&rows, decisions_, &derived);
|
||||
if (cfg_.max_seqs > 0)
|
||||
derived.push_back({ "max-in-flight", std::to_string(max_in_flight()),
|
||||
fmt("live concurrency cap (ceiling --max-num-seqs %lld)",
|
||||
(long long)cfg_.max_seqs) });
|
||||
const diag::Facts f = hardware_facts(false);
|
||||
const diag::RunFacts r = run_facts(status < 0);
|
||||
const std::vector<diag::Finding> found = diag::check(f, r);
|
||||
@@ -177,6 +181,10 @@ std::string Engine::diagnostics_json() const {
|
||||
std::vector<diag::ConfigRow> rows = diag::config_rows(cfg_);
|
||||
std::vector<diag::Decision> derived;
|
||||
diag::merge(&rows, decisions_, &derived);
|
||||
if (cfg_.max_seqs > 0)
|
||||
derived.push_back({ "max-in-flight", std::to_string(max_in_flight()),
|
||||
fmt("live concurrency cap (ceiling --max-num-seqs %lld)",
|
||||
(long long)cfg_.max_seqs) });
|
||||
diag::Facts f;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(diag_mu_);
|
||||
|
||||
@@ -296,7 +296,8 @@ int Engine::advance_all(int mode, int round, bool from_proposal, int rows) {
|
||||
a.src_pitch = (dd.proposal && dd.proposal_pitch > 0) ? dd.proposal_pitch : 1;
|
||||
/* A tree drafter's parents, at the proposal's pitch (rad_drafter_tree). */
|
||||
if (tree_ && mode == ADV_BTAKE) {
|
||||
a.par = static_cast<const int32_t*>(rk.ctx.buf_ptr(tree_parents_));
|
||||
const rad_buf par = rk.program.drafter_parents;
|
||||
a.par = static_cast<const int32_t*>(par ? rk.ctx.buf_ptr(par) : nullptr);
|
||||
if (!a.par) {
|
||||
RAD_ERR("drafter '%s': rank %zu has no parents buffer", drafter_.name, i);
|
||||
return RAD_E_STATE;
|
||||
|
||||
@@ -58,6 +58,11 @@ int Engine::gen_loop() {
|
||||
const RadBatch* b = gen_->next(step);
|
||||
if (!b) {
|
||||
step_batch_.store(nullptr, std::memory_order_release);
|
||||
if (const int fs = gen_->fatal_status(); fs < 0) {
|
||||
RAD_ERR("generator staging failed: %s -- the engine cannot continue",
|
||||
rad_strerror(fs));
|
||||
return stop(fs);
|
||||
}
|
||||
if (hold_req_.load(std::memory_order_acquire)) {
|
||||
hold_point();
|
||||
continue;
|
||||
|
||||
@@ -190,6 +190,16 @@ int Engine::run_kld() {
|
||||
RAD_INFO("kld: scoring through the runtime LoRA adapter '%s' (slot %d)", cfg_.kld_lora.c_str(),
|
||||
lora_slot);
|
||||
|
||||
/* With control-vector slots, a default-on run scores through the `default` slot. */
|
||||
CvecSlots::Lease cvec;
|
||||
if (cvec_slotted() && cvec_default_on()) {
|
||||
std::string why;
|
||||
if (cvec_acquire(kCvecDefaultSlot, &cvec, &why) != RAD_OK) {
|
||||
RAD_ERR("kld: --control-vector on: %s", why.c_str());
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::unique_ptr<server::Sink>> sinks(n);
|
||||
std::vector<std::unique_ptr<Request>> reqs(n);
|
||||
for (size_t d = 0; d < n; ++d) {
|
||||
@@ -203,6 +213,11 @@ int Engine::run_kld() {
|
||||
r->score = true;
|
||||
/* A loaded control vector scores at the deployment's default (--control-vector on|off). */
|
||||
r->sp.use_control_vector = cvec_default_on();
|
||||
r->cvec_offset = cvec.offset;
|
||||
r->cvec_salt = cvec.salt;
|
||||
r->cvec_add = cvec_default_on() &&
|
||||
(cvec_slotted() ? cvec.mode == CvecMode::Add : cvec_.mode == CvecMode::Add);
|
||||
r->cvec_hold = cvec.hold;
|
||||
/* --kld-lora-sources: the other documents run as the base, in the same steps. */
|
||||
const bool via = cfg_.kld_lora_sources.empty() ||
|
||||
kld_->source(d).rfind(cfg_.kld_lora_sources, 0) == 0;
|
||||
|
||||
+38
-5
@@ -88,7 +88,14 @@ int Engine::run_encodes() {
|
||||
++n_items;
|
||||
n_patches += ip->patch_at(ip->n_seg);
|
||||
const RadEncoderDecl& e = ip->kind == mm::Kind::Audio ? prog.audio_encoder : prog.encoder;
|
||||
ip->embd.assign((size_t)(ip->n_rows() * e.n_embd), 0);
|
||||
if (ip->n_rows() < 0 || e.n_embd <= 0 || e.n_aux < 0 ||
|
||||
e.n_aux > RAD_ENCODER_MAX_AUX ||
|
||||
ip->n_rows() > INT64_MAX / e.n_embd / (int64_t)sizeof(uint16_t) / (1 + e.n_aux))
|
||||
return RAD_E_INVAL;
|
||||
const size_t elements = (size_t)(ip->n_rows() * e.n_embd);
|
||||
ip->embd.assign(elements, 0);
|
||||
ip->aux_embd.resize((size_t)e.n_aux);
|
||||
for (auto& plane : ip->aux_embd) plane.assign(elements, 0);
|
||||
if (dump_dir && *dump_dir) dump(*ip, ".pix.bf16", ip->pixels.data(), ip->pixels.size());
|
||||
}
|
||||
|
||||
@@ -194,6 +201,22 @@ int Engine::run_encodes() {
|
||||
RAD_ERR("encoder pass failed: %s -- the engine cannot continue", rad_strerror(st));
|
||||
return st;
|
||||
}
|
||||
const char* aux[RAD_ENCODER_MAX_AUX]{};
|
||||
for (int tap = 0; tap < enc.n_aux; ++tap) {
|
||||
aux[tap] = static_cast<const char*>(r0.ctx.buf_ptr(enc.aux_out[tap]));
|
||||
if (!aux[tap]) return RAD_E_STATE;
|
||||
}
|
||||
auto finish_copies = [&](int first_error) {
|
||||
/* Never release a request's destinations while an earlier copy
|
||||
* from this pass can still write them, even after a later error. */
|
||||
int fence_error = RAD_OK;
|
||||
for (auto& rk : ranks_) {
|
||||
const int status = rad_stream_sync(rk->ctx.stream());
|
||||
if (status < 0 && fence_error == RAD_OK) fence_error = status;
|
||||
}
|
||||
if (fence_error < 0) fatal("encoder readback did not drain; request storage is still owned");
|
||||
return first_error;
|
||||
};
|
||||
/* The rows, in pass order: each part's segments are consecutive rows of its item. A
|
||||
* typed span (Item::types) covers every span position: its image rows are copied in
|
||||
* place from the pass's output, its other rows from the encoder's span_rows table,
|
||||
@@ -207,18 +230,26 @@ int Engine::run_encodes() {
|
||||
const int64_t rows = it.row_at(p.seg0 + p.n_seg) - first;
|
||||
const int64_t bytes = rows * n_embd * (int64_t)sizeof(uint16_t);
|
||||
if (!it.types.empty()) {
|
||||
if (enc.n_aux > 0) return finish_copies(RAD_E_UNSUPPORTED);
|
||||
typed.push_back(TypedPart{ &it, row * n_embd * (int64_t)sizeof(uint16_t), rows });
|
||||
row += rows;
|
||||
continue;
|
||||
}
|
||||
RAD_TRY(rad_memcpy_async(it.embd.data() + first * n_embd,
|
||||
const int copy_status = rad_memcpy_async(it.embd.data() + first * n_embd,
|
||||
static_cast<const char*>(out) +
|
||||
row * n_embd * (int64_t)sizeof(uint16_t),
|
||||
bytes, r0.ctx.stream()));
|
||||
bytes, r0.ctx.stream());
|
||||
if (copy_status < 0) return finish_copies(copy_status);
|
||||
for (int tap = 0; tap < enc.n_aux; ++tap) {
|
||||
const int aux_status = rad_memcpy_async(it.aux_embd[(size_t)tap].data() + first * n_embd,
|
||||
aux[tap] + row * n_embd * (int64_t)sizeof(uint16_t),
|
||||
bytes, r0.ctx.stream());
|
||||
if (aux_status < 0) return finish_copies(aux_status);
|
||||
}
|
||||
row += rows;
|
||||
}
|
||||
/* Sync every rank's stream: the next pass rewrites every rank's staging and arena. */
|
||||
for (auto& rk : ranks_) RAD_TRY(rad_stream_sync(rk->ctx.stream()));
|
||||
RAD_TRY(finish_copies(RAD_OK));
|
||||
|
||||
/* Typed spans: the image rows take the pass's output, every other position the
|
||||
* encoder's learned row for its type (0 start, 2 newline, 3 end). */
|
||||
@@ -238,8 +269,10 @@ int Engine::run_encodes() {
|
||||
void* sp = r0.ctx.buf_ptr(enc.span_rows);
|
||||
if (sp &&
|
||||
rad_memcpy_async(sr.data(), sp, (size_t)(4 * n_embd) * sizeof(uint16_t),
|
||||
r0.ctx.stream()) < 0)
|
||||
r0.ctx.stream()) < 0) {
|
||||
(void)rad_stream_sync(r0.ctx.stream());
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
}
|
||||
RAD_TRY(rad_stream_sync(r0.ctx.stream()));
|
||||
for (const TypedPart& t : typed) {
|
||||
|
||||
@@ -56,8 +56,6 @@ struct Engine::Rank {
|
||||
* because its bank holds an already-credited step (the layer did not route). Counting these
|
||||
* apart keeps a placement engine starved of evidence from looking like idle layers. */
|
||||
uint64_t heat_credited = 0, heat_idle = 0;
|
||||
/* Trunk steps in a row whose pass the prefill stager did not arm (Engine::tiering_dispatch). */
|
||||
int unstaged_steps = 0;
|
||||
KVManager kv;
|
||||
PrefixCache prefix;
|
||||
/* Idle session tiers (spec 7.3). Rank 0 owns the policy and session index, since a
|
||||
|
||||
+85
-4
@@ -61,8 +61,9 @@ const Replaced kReplaced[] = {
|
||||
/* Flags given more than once on a command line; a YAML sequence repeats them. */
|
||||
const char* const kRepeatable[] = { "lora", "allow-host", "trusted-proxy" };
|
||||
|
||||
/* The fleet's own keys on a model. `defaults:` may carry every one but aliases (read_model_keys). */
|
||||
const char* const kModelFleetKeys[] = { "aliases", "priority", "pin", "ttl", "flex", "park", "cards" };
|
||||
/* The fleet's own keys on a model. `defaults:` may carry every one but aliases, pool and cards
|
||||
* (read_model_keys). */
|
||||
const char* const kModelFleetKeys[] = { "aliases", "pool", "priority", "pin", "ttl", "flex", "park", "cards" };
|
||||
|
||||
const char* const kTopKeys[] = { "server", "cards", "memory", "scheduler", "defaults", "models", "groups" };
|
||||
|
||||
@@ -349,6 +350,9 @@ private:
|
||||
int read_groups(const Item& sec, FleetConfig* out);
|
||||
int read_model_keys(const Item& sec, bool is_defaults, std::vector<Item>* out);
|
||||
int read_fleet_key(const Item& it, ModelEntry* e);
|
||||
/* A `models:` entry that names a `pool:` (docs/MULTIMODEL.md §8.5). */
|
||||
int read_virtual(const Item& ent, const std::vector<Item>& own, FleetConfig* out,
|
||||
std::map<std::string, std::string>* taken);
|
||||
int build_model(const std::string& name, Node at, const std::vector<Item>& keys, ModelEntry* e);
|
||||
};
|
||||
|
||||
@@ -444,17 +448,21 @@ int Reader::read_scheduler(const Item& sec, FleetConfig* out) {
|
||||
int s = RAD_OK;
|
||||
if (k == "load-timeout") s = duration(it, &out->load_timeout_ms);
|
||||
else if (k == "drain-timeout") s = duration(it, &out->drain_timeout_ms);
|
||||
else if (k == "swap-hold") s = duration(it, &out->swap_hold_ms);
|
||||
else if (k == "keepalive") s = duration(it, &out->keepalive_ms);
|
||||
else if (k == "stuck-exit") s = duration(it, &out->stuck_exit_ms);
|
||||
else if (k == "warm-up") s = boolean(it, &out->warm_up);
|
||||
else if (k == "max-in-flight") s = integer(it, 1, 4096, &out->max_in_flight);
|
||||
else {
|
||||
return fail(it.node, "scheduler." + k + " is not a scheduler key" +
|
||||
suggest(k, { "load-timeout", "drain-timeout", "keepalive",
|
||||
"stuck-exit", "warm-up" }));
|
||||
suggest(k, { "load-timeout", "drain-timeout", "swap-hold", "keepalive",
|
||||
"stuck-exit", "warm-up", "max-in-flight" }));
|
||||
}
|
||||
if (s < 0) return s;
|
||||
}
|
||||
if (out->keepalive_ms <= 0) return fail(sec.node, "scheduler.keepalive must be above zero");
|
||||
if (out->swap_hold_ms > 0 && out->swap_hold_ms >= out->load_timeout_ms)
|
||||
return fail(sec.node, "scheduler.swap-hold must be below scheduler.load-timeout");
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -508,6 +516,9 @@ int Reader::read_model_keys(const Item& sec, bool is_defaults, std::vector<Item>
|
||||
const std::string& k = it.key;
|
||||
if (in(kModelFleetKeys, k)) {
|
||||
if (is_defaults && k == "aliases") return fail(it.node, "aliases name one model; they cannot be a default");
|
||||
if (is_defaults && k == "pool")
|
||||
return fail(it.node, "pool: names the models one virtual id routes among; it "
|
||||
"cannot be a default");
|
||||
if (is_defaults && k == "cards")
|
||||
return fail(it.node, "cards under defaults would pin every model; the top-level "
|
||||
"cards: names the cards the fleet uses");
|
||||
@@ -520,6 +531,49 @@ int Reader::read_model_keys(const Item& sec, bool is_defaults, std::vector<Item>
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Reader::read_virtual(const Item& ent, const std::vector<Item>& own, FleetConfig* out,
|
||||
std::map<std::string, std::string>* taken) {
|
||||
VirtualEntry v;
|
||||
v.name = ent.key;
|
||||
for (const Item& o : own) {
|
||||
if (o.key == "aliases") {
|
||||
ModelEntry tmp;
|
||||
if (int s = read_fleet_key(o, &tmp); s < 0) return s;
|
||||
for (const std::string& a : tmp.aliases)
|
||||
if (!valid_name(a))
|
||||
return fail(o.node, o.path + ": alias '" + a + "' holds ':' or whitespace");
|
||||
v.aliases = std::move(tmp.aliases);
|
||||
continue;
|
||||
}
|
||||
if (o.key == "pool") {
|
||||
if (!o.node.is_seq()) return fail(o.node, o.path + " takes a list of model ids");
|
||||
for (Node m : o.node.children()) {
|
||||
if (!scalar(m) || null_val(m)) return fail(m, o.path + " entries are model ids");
|
||||
const std::string name = str(m.val());
|
||||
if (name.empty()) return fail(m, o.path + " lists an empty id");
|
||||
if (!valid_name(name))
|
||||
return fail(m, o.path + " '" + name + "' holds ':' or whitespace");
|
||||
if (std::find(v.members.begin(), v.members.end(), name) != v.members.end())
|
||||
return fail(m, o.path + " lists " + name + " twice");
|
||||
v.members.push_back(name);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
return fail(o.node, o.path + " belongs to a model; '" + ent.key + "' names a pool, so it "
|
||||
"is a virtual id and takes only aliases: and pool:");
|
||||
}
|
||||
if (v.members.empty())
|
||||
return fail(ent.node, ent.path + ": a pooled entry names no pool to route among");
|
||||
std::vector<std::string> ids{ v.name };
|
||||
ids.insert(ids.end(), v.aliases.begin(), v.aliases.end());
|
||||
for (const std::string& n : ids) {
|
||||
auto [it, fresh] = taken->emplace(n, "'" + v.name + "' (its virtual id)");
|
||||
if (!fresh) return fail(ent.node, ent.path + ": '" + n + "' already names " + it->second);
|
||||
}
|
||||
out->virtuals.push_back(std::move(v));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Reader::read_fleet_key(const Item& it, ModelEntry* e) {
|
||||
const std::string& k = it.key;
|
||||
if (k == "aliases") {
|
||||
@@ -722,6 +776,14 @@ int Reader::run(FleetConfig* out) {
|
||||
"(reserved for base:adapter) and no whitespace");
|
||||
std::vector<Item> own;
|
||||
if (int s = read_model_keys(ent, false, &own); s < 0) return s;
|
||||
/* An entry naming a `pool:` is a virtual id: it configures no engine and routes among
|
||||
* the pooled models (docs/MULTIMODEL.md §8.5). */
|
||||
bool pooled = false;
|
||||
for (const Item& o : own) pooled |= o.key == "pool";
|
||||
if (pooled) {
|
||||
if (int s = read_virtual(ent, own, out, &taken); s < 0) return s;
|
||||
continue;
|
||||
}
|
||||
std::vector<Item> merged;
|
||||
for (const Item& d : base)
|
||||
if (std::none_of(own.begin(), own.end(), [&](const Item& o) { return o.key == d.key; }))
|
||||
@@ -741,6 +803,10 @@ int Reader::run(FleetConfig* out) {
|
||||
}
|
||||
out->models.push_back(std::move(e));
|
||||
}
|
||||
/* A file of only virtual ids has nothing to load: every other part of the fleet reads
|
||||
* models.front() at least (operator_ok does), so refuse the degenerate file at load. */
|
||||
if (out->models.empty())
|
||||
return fail(models->node, "models: configures no model; a virtual id needs a model to route to");
|
||||
|
||||
/* A model's own cards are among the fleet's and are enough for its ranks. */
|
||||
for (const ModelEntry& e : out->models) {
|
||||
@@ -770,6 +836,14 @@ int Reader::run(FleetConfig* out) {
|
||||
" are in both a together and an exclusive group");
|
||||
}
|
||||
}
|
||||
/* Pool members are real models: find() resolves aliases too, so the name compare below
|
||||
* refuses a member named by alias, and a member naming a virtual id or an unknown name
|
||||
* resolves to no model at all. */
|
||||
for (const VirtualEntry& v : out->virtuals)
|
||||
for (const std::string& m : v.members)
|
||||
if (const ModelEntry* me = out->find(m); !me || me->name != m)
|
||||
return fail(doc, "models." + v.name + ".pool names '" + m +
|
||||
"', which is not a model id");
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -905,13 +979,20 @@ void print_reference(FILE* to) {
|
||||
"\nscheduler:\n"
|
||||
" load-timeout: DURATION how long a request waits for its model (default 120s)\n"
|
||||
" drain-timeout: DURATION how long a model being evicted may finish requests (30s)\n"
|
||||
" swap-hold: DURATION a busy model is kept until idle before a swap, up to this long\n"
|
||||
" into the waiting model's wait (below load-timeout; 0: quantum alone)\n"
|
||||
" keepalive: DURATION SSE comment interval while a request waits (10s)\n"
|
||||
" stuck-exit: DURATION a device stuck this long ends the process (60s; 0 never)\n"
|
||||
" warm-up: true|false fill free VRAM, then host RAM, with models at start (true)\n"
|
||||
" max-in-flight: N live concurrency cap (<= max-num-seqs; tunable via admin API)\n"
|
||||
"\ndefaults: any model key, merged under every model\n"
|
||||
"\nmodels:\n"
|
||||
" NAME: the model id requests name\n"
|
||||
" aliases: [NAME, ...] more ids for this model\n"
|
||||
" pool: [ID, ...] no model file: a virtual id. A request naming it\n"
|
||||
" goes to whichever listed model is resident;\n"
|
||||
" when none is, the list is a preference order\n"
|
||||
" for what to load. Takes only aliases: beside it\n"
|
||||
" priority: N higher keeps VRAM and takes flex from lower\n"
|
||||
" pin: true|false never leaves VRAM\n"
|
||||
" cards: all | [N, ...] the cards this model may be placed on (all)\n"
|
||||
|
||||
+22
-1
@@ -8,7 +8,8 @@
|
||||
* memory: per-card VRAM headroom and the host budgets
|
||||
* scheduler: load and drain timeouts, the keepalive interval
|
||||
* defaults: per-model keys merged under every model
|
||||
* models: one entry per model, keyed by its id
|
||||
* models: one entry per model, keyed by its id; an entry with `pool:` and no `model:` file
|
||||
* is a virtual id that routes requests among the listed models
|
||||
* groups: together / exclusive co-residency rules
|
||||
*
|
||||
* Top-level keys that start with `x-` are ignored, so a file can keep anchors there and merge them
|
||||
@@ -89,6 +90,17 @@ struct Group {
|
||||
std::vector<std::string> members;
|
||||
};
|
||||
|
||||
/* A virtual model id (docs/MULTIMODEL.md 8.5): a `models:` entry with `pool:` and no `model:`
|
||||
* file. It configures no engine -- requests that name it route to whichever pooled model is
|
||||
* resident, in pool order, and ask the first one failure is not holding to load when none is. The
|
||||
* Front routes it (server/front.h add with members); the scheduler never loads, parks or evicts
|
||||
* it. */
|
||||
struct VirtualEntry {
|
||||
std::string name;
|
||||
std::vector<std::string> aliases;
|
||||
std::vector<std::string> members; /* the pool, in preference order: the front is preferred */
|
||||
};
|
||||
|
||||
struct FleetConfig {
|
||||
std::string path; /* the file read, for messages */
|
||||
|
||||
@@ -116,6 +128,10 @@ struct FleetConfig {
|
||||
/* scheduler: */
|
||||
int64_t load_timeout_ms = 120000;
|
||||
int64_t drain_timeout_ms = 30000;
|
||||
/* While another model waits for room, a busy resident model keeps its cards and host memory
|
||||
* until it has no open or queued requests, bounded by this duration into the waiting model's
|
||||
* wait (after which eviction drains it via drain-timeout). 0: the quantum alone (default). */
|
||||
int64_t swap_hold_ms = 0;
|
||||
int64_t keepalive_ms = 10000;
|
||||
/* A device that has advanced nothing for this long ends the process, so a restart policy can
|
||||
* bring the server back (dev_stuck_exit_ms); 0 never. */
|
||||
@@ -124,9 +140,14 @@ struct FleetConfig {
|
||||
* VRAM and park to host memory and the disk tier as later ones displace them, so a first
|
||||
* request finds its model parked rather than cold (docs/MULTIMODEL.md §8.6). */
|
||||
bool warm_up = true;
|
||||
/* Live admission ceiling across models (<= each model's max-num-seqs); 0 = unset (use each
|
||||
* model's max-num-seqs). Hot-reloaded and overridden per model via POST /admin/models/<name>/max-in-flight. */
|
||||
int64_t max_in_flight = 0;
|
||||
|
||||
std::vector<ModelEntry> models;
|
||||
std::vector<Group> groups;
|
||||
/* Virtual names (VirtualEntry); the post-pass validates each pool member against the models. */
|
||||
std::vector<VirtualEntry> virtuals;
|
||||
|
||||
/* The model a name or alias resolves to, or null. */
|
||||
const ModelEntry* find(const std::string& name_or_alias) const;
|
||||
|
||||
+196
-34
@@ -299,6 +299,17 @@ struct SetOnExit {
|
||||
~SetOnExit() { e.store(true, std::memory_order_release); }
|
||||
};
|
||||
|
||||
/* Re-entrant clock for swap-hold: the outermost wait starts it and clears it on exit. */
|
||||
struct WaitClock {
|
||||
std::atomic<uint64_t>& t;
|
||||
bool mine = false;
|
||||
explicit WaitClock(std::atomic<uint64_t>& at) : t(at) {
|
||||
uint64_t zero = 0;
|
||||
mine = t.compare_exchange_strong(zero, rad_mono_ns());
|
||||
}
|
||||
~WaitClock() { if (mine) t.store(0); }
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
std::string unsupported(const FleetConfig& fc) {
|
||||
@@ -342,6 +353,7 @@ public:
|
||||
private:
|
||||
friend struct FleetHostFillTestAccess;
|
||||
friend struct FleetMemoryTestAccess;
|
||||
friend struct FleetSwapHoldTestAccess;
|
||||
struct Model;
|
||||
|
||||
/* The broker one load hands its engine: the fleet's grant, for that model. */
|
||||
@@ -384,6 +396,8 @@ private:
|
||||
std::atomic<int> op{ kIdle };
|
||||
std::atomic<bool> waiting{ false }; /* in make_room_waiting */
|
||||
std::atomic<bool> waiting_host{ false }; /* in load_host_room's wait */
|
||||
/* When this model began waiting for room (VRAM or host), 0 while it is not waiting. */
|
||||
std::atomic<uint64_t> wait_since_ns{ 0 };
|
||||
/* Loaded by the warm-up and named by no request since (§8.6): its load takes room only
|
||||
* from free memory and other such models, and gives up quietly where there is none. */
|
||||
std::atomic<bool> warm{ false };
|
||||
@@ -409,6 +423,7 @@ private:
|
||||
bool in_place = false;
|
||||
double load_s = 0, park_s = 0, restore_s = 0;
|
||||
int64_t filled = 0; /* bytes read into host memory from the disk tier, this park */
|
||||
int64_t max_in_flight_override = 0; /* set via POST /admin/models/<name>/max-in-flight */
|
||||
uint64_t promote_ns = 0; /* when a pass last tried to move its live rest onto the cards */
|
||||
double fill_s = 0;
|
||||
/* kYield: what to free on each card, and for whose experts (Fleet::xflex_tick). */
|
||||
@@ -491,6 +506,8 @@ private:
|
||||
* instead of giving its cards back for each request of another (ping-pong). Four times what
|
||||
* coming back costs it, within [5 s, 30 s]. */
|
||||
bool in_quantum(const Model& m, const server::Front::Activity& a, uint64_t now) const;
|
||||
/* in_quantum, or swap-hold: `m` is busy and `waiter` has waited less than swap-hold. */
|
||||
bool swap_held(const Model& m, const server::Front::Activity& a, const Model* waiter, uint64_t now) const;
|
||||
bool take_from(Model& victim, const std::map<int, int64_t>& want, const std::string& why);
|
||||
bool unload(Model& m, int64_t drain_ms, const std::string& why);
|
||||
/* 1 when `want` left, 0 when less could leave (nothing more to page out), -1 when the model
|
||||
@@ -761,7 +778,7 @@ std::vector<Resident> Fleet::residents(const Model* except) {
|
||||
r.priority = m.entry.priority;
|
||||
r.pin = m.entry.pin;
|
||||
r.busy = a.leases > 0 || a.waiting > 0;
|
||||
r.keep = in_quantum(m, a, now);
|
||||
r.keep = swap_held(m, a, except, now);
|
||||
r.idle_s = a.last_used_ns && now > a.last_used_ns ? (double)(now - a.last_used_ns) * 1e-9 : 0;
|
||||
r.restore_s = m.parked ? std::max(m.restore_s, 0.1) : (m.load_s > 0 ? m.load_s : 5.0);
|
||||
v.push_back(r);
|
||||
@@ -1056,20 +1073,23 @@ void Fleet::reclaim_flex(const Model& m, const std::map<int, int64_t>& need) {
|
||||
int64_t sh = short_by();
|
||||
for (int pass = 0; pass < 2 && sh > 0; ++pass) {
|
||||
const bool experts = pass == 0;
|
||||
std::vector<Model*> c;
|
||||
struct Cand { Model* m; int priority; int leases; };
|
||||
std::vector<Cand> c;
|
||||
for (auto& mp : models_) {
|
||||
Model& o = *mp;
|
||||
if (&o == &m || !o.engine || o.parked || !o.resident || o.op.load() != kIdle) continue;
|
||||
if (experts ? o.engine->expert_flex_bytes() <= 0
|
||||
: o.entry.priority > m.entry.priority || o.engine->flex_bytes() <= 0)
|
||||
continue;
|
||||
if (touches(o.cards, need)) c.push_back(&o);
|
||||
if (touches(o.cards, need))
|
||||
c.push_back(Cand{ &o, o.entry.priority, (int)front_.activity(o.entry.name).leases });
|
||||
}
|
||||
std::sort(c.begin(), c.end(), [&](Model* a, Model* b) {
|
||||
if (a->entry.priority != b->entry.priority) return a->entry.priority < b->entry.priority;
|
||||
return front_.activity(a->entry.name).leases < front_.activity(b->entry.name).leases;
|
||||
std::sort(c.begin(), c.end(), [](const Cand& a, const Cand& b) {
|
||||
if (a.priority != b.priority) return a.priority < b.priority;
|
||||
return a.leases < b.leases;
|
||||
});
|
||||
for (Model* o : c) {
|
||||
for (const Cand& item : c) {
|
||||
Model* o = item.m;
|
||||
if (sh <= 0) break;
|
||||
const bool preempt = !experts && o->entry.priority < m.entry.priority;
|
||||
const int64_t got = o->engine->flex_release(sh, preempt, 10000, /*kv=*/!experts);
|
||||
@@ -1232,6 +1252,16 @@ bool Fleet::in_quantum(const Model& m, const server::Front::Activity& a, uint64_
|
||||
return now > m.on_ns && (double)(now - m.on_ns) * 1e-9 < q;
|
||||
}
|
||||
|
||||
bool Fleet::swap_held(const Model& m, const server::Front::Activity& a, const Model* waiter, uint64_t now) const {
|
||||
if (in_quantum(m, a, now)) return true;
|
||||
if (fc_.swap_hold_ms <= 0 || !waiter || m.parked || !m.resident || !m.engine || m.entry.pin) return false;
|
||||
if (a.leases <= 0 && a.waiting <= 0) return false;
|
||||
/* `since == 0` occurs during card selection (choose_cards) before a load wait begins;
|
||||
* `since > now` handles a clock started after `now` was captured. */
|
||||
const uint64_t since = waiter->wait_since_ns.load(std::memory_order_relaxed);
|
||||
return since == 0 || since > now || (now - since) / 1000000ull < (uint64_t)fc_.swap_hold_ms;
|
||||
}
|
||||
|
||||
int Fleet::passing_on(const Model& m, const std::map<int, int64_t>& need) {
|
||||
const uint64_t now = rad_mono_ns();
|
||||
std::vector<server::Front::Activity> act(models_.size());
|
||||
@@ -1248,7 +1278,7 @@ int Fleet::passing_on(const Model& m, const std::map<int, int64_t>& need) {
|
||||
else return 2;
|
||||
}
|
||||
for (size_t i = 0; i < models_.size(); ++i)
|
||||
if (models_[i].get() != &m && near(models_[i]->cards) && in_quantum(*models_[i], act[i], now))
|
||||
if (models_[i].get() != &m && near(models_[i]->cards) && swap_held(*models_[i], act[i], &m, now))
|
||||
return 2;
|
||||
for (const Reservation& r : reserved_)
|
||||
if (r.m != &m && r.claim > 0 && !r.m->starting.load() && near(r.cards)) return 2;
|
||||
@@ -1263,6 +1293,7 @@ int Fleet::make_room_waiting(Model& m, const std::map<int, int64_t>& need, std::
|
||||
auto still_since = t0;
|
||||
bool said = false, closed_queues = false;
|
||||
const Raised flag(m.waiting);
|
||||
const WaitClock wait_clock(m.wait_since_ns);
|
||||
/* The cards' free figures at the last look. Memory a model gave back is counted free only as
|
||||
* the driver's wipe reaches it, some GiB a second: after the tens of GiB a large model's
|
||||
* room takes (every other model unloaded for MiniMax-H3) the figure rises for longer than
|
||||
@@ -1652,6 +1683,7 @@ bool Fleet::load_host_room(Model& m, int64_t need, int64_t own, bool reserve) {
|
||||
* VRAM here, which what pins the memory may be waiting for, and the failed start lets go of it. */
|
||||
const int64_t tries = warm ? 1 : own == 0 ? std::max<int64_t>(fc_.load_timeout_ms / 200, 300) : 300;
|
||||
const Raised flag(m.waiting_host);
|
||||
const WaitClock wait_clock(m.wait_since_ns);
|
||||
for (int64_t i = 0; i < tries && !ok && !g_stop.load(); ++i) {
|
||||
/* As in load_op: without a load in flight beside this one the figure is exact, and parked
|
||||
* and idle models give their host memory at once. */
|
||||
@@ -1766,22 +1798,32 @@ bool Fleet::make_host_room(int64_t need, const Model* keep, bool force, bool unl
|
||||
* that has answered since it came on is idle. */
|
||||
if (a.last_used_ns >= m->on_ns || now - m->on_ns > 10000000000ull)
|
||||
idle.push_back(m.get());
|
||||
} else if (take_busy && !in_quantum(*m, a, now)) {
|
||||
} else if (take_busy && !swap_held(*m, a, keep, now)) {
|
||||
/* `keep` is the waiting model whose wait_since_ns bounds swap-hold. */
|
||||
busy.push_back(m.get());
|
||||
}
|
||||
}
|
||||
/* What frees the most first: unloading a small model for a load that wants tens of GiB
|
||||
* costs its next request a load and brings the room no nearer. */
|
||||
auto most_first = [&](Model* a, Model* b) {
|
||||
const int64_t x = a->engine->host_pinned_bytes(), y = b->engine->host_pinned_bytes();
|
||||
if (x != y) return x > y;
|
||||
return front_.activity(a->entry.name).last_used_ns < front_.activity(b->entry.name).last_used_ns;
|
||||
* costs its next request a load and brings the room no nearer. Snapshot keys before sort. */
|
||||
struct HostCand { Model* m; int64_t pinned; uint64_t last_used_ns; bool busy; };
|
||||
auto sort_cands = [&](const std::vector<Model*>& src, bool is_busy) {
|
||||
std::vector<HostCand> out;
|
||||
out.reserve(src.size());
|
||||
for (Model* m : src)
|
||||
out.push_back(HostCand{ m, m->engine ? m->engine->host_pinned_bytes() : 0,
|
||||
front_.activity(m->entry.name).last_used_ns, is_busy });
|
||||
std::sort(out.begin(), out.end(), [](const HostCand& a, const HostCand& b) {
|
||||
if (a.pinned != b.pinned) return a.pinned > b.pinned;
|
||||
return a.last_used_ns < b.last_used_ns;
|
||||
});
|
||||
return out;
|
||||
};
|
||||
std::sort(idle.begin(), idle.end(), most_first);
|
||||
std::sort(busy.begin(), busy.end(), most_first);
|
||||
idle.insert(idle.end(), busy.begin(), busy.end());
|
||||
for (Model* m : idle) {
|
||||
const bool at_work = std::find(busy.begin(), busy.end(), m) != busy.end();
|
||||
std::vector<HostCand> ordered = sort_cands(idle, false);
|
||||
std::vector<HostCand> ordered_busy = sort_cands(busy, true);
|
||||
ordered.insert(ordered.end(), ordered_busy.begin(), ordered_busy.end());
|
||||
for (const HostCand& hc : ordered) {
|
||||
Model* m = hc.m;
|
||||
const bool at_work = hc.busy;
|
||||
int expect = kIdle;
|
||||
if (!m->op.compare_exchange_strong(expect, kUnload)) continue;
|
||||
join_spill(*m);
|
||||
@@ -1956,6 +1998,11 @@ void Fleet::fill_op(Model& m) {
|
||||
}
|
||||
|
||||
void Fleet::restore_op(Model& m) {
|
||||
if (!m.engine) {
|
||||
load_op(m);
|
||||
return;
|
||||
}
|
||||
if (!m.parked) return;
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
front_.loading(m.entry.name);
|
||||
const InFlight in_flight(loads_in_flight_);
|
||||
@@ -1978,6 +2025,9 @@ void Fleet::restore_op(Model& m) {
|
||||
std::unique_lock<std::recursive_mutex> room(room_mu_, std::defer_lock);
|
||||
int rrc = RAD_OK;
|
||||
bool yielded = false;
|
||||
/* Held across restore_op (including any fallback into load_op) so one request's total wait
|
||||
* never gets a second swap-hold window. */
|
||||
const WaitClock wait_clock(m.wait_since_ns);
|
||||
for (;;) {
|
||||
/* Until it has given way, it waits a short while at a time, so the check below runs. */
|
||||
(void)make_room_waiting(m, need, &why, {}, yielded ? -1 : 2000);
|
||||
@@ -2109,12 +2159,16 @@ void Fleet::load_op(Model& m) {
|
||||
std::atomic<int64_t>* mine;
|
||||
~Unreserve() { r->fetch_sub(mine->exchange(0)); }
|
||||
} unreserve{ &host_reserve_, &m.pools_held };
|
||||
/* One WaitClock spans the entire load_op after choose_cards (host-pool wait, VRAM-guess wait,
|
||||
* and grant/host waits during engine bring-up) so sequential waits share one swap-hold bound. */
|
||||
std::optional<WaitClock> wait_clock;
|
||||
{
|
||||
std::unique_lock<std::recursive_mutex> room(room_mu_);
|
||||
if (!choose_cards(m, cfg, &chosen, &why)) {
|
||||
fail(m, why);
|
||||
return;
|
||||
}
|
||||
wait_clock.emplace(m.wait_since_ns);
|
||||
if (use_broker()) {
|
||||
/* The engine pins its own host pools at bring-up (an expert host pool on every rank,
|
||||
* a checkpoint store): parked copies make way first, so the host keeps its floor. A
|
||||
@@ -2232,6 +2286,15 @@ void Fleet::load_op(Model& m) {
|
||||
return;
|
||||
}
|
||||
m.room_retries = 0;
|
||||
{
|
||||
int64_t cap = 0;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
cap = m.max_in_flight_override > 0 ? m.max_in_flight_override : fc_.max_in_flight;
|
||||
}
|
||||
if (cap > 0 && e->max_seqs() > 0)
|
||||
(void)e->set_max_in_flight(std::min<int64_t>(cap, e->max_seqs()));
|
||||
}
|
||||
Engine* raw = e.get();
|
||||
m.ended = std::make_shared<std::atomic<bool>>(false);
|
||||
m.serve = std::thread([raw, done = m.ended, w = std::move(watch)]() mutable {
|
||||
@@ -2387,6 +2450,7 @@ void Fleet::fill_tick() {
|
||||
void Fleet::promote_tick() {
|
||||
const uint64_t now = rad_mono_ns();
|
||||
for (auto& mp : models_) {
|
||||
std::lock_guard<std::recursive_mutex> room(room_mu_);
|
||||
Model& m = *mp;
|
||||
if (!m.engine || !m.resident || m.parked || m.op.load() != kIdle) continue;
|
||||
if (now - m.promote_ns < 5000000000ull) continue;
|
||||
@@ -2420,6 +2484,7 @@ void Fleet::xflex_tick() {
|
||||
if (loads_in_flight_.load() > 0) return;
|
||||
for (auto& mp : models_)
|
||||
if (mp->op.load() == kYield) return;
|
||||
std::lock_guard<std::recursive_mutex> room(room_mu_);
|
||||
for (auto& mp : models_) {
|
||||
Model& m = *mp;
|
||||
if (!m.engine || m.parked || !m.resident || m.op.load() != kIdle) continue;
|
||||
@@ -2484,21 +2549,29 @@ void Fleet::yield_op(Model& m) {
|
||||
void Fleet::reap() {
|
||||
for (auto& mp : models_) {
|
||||
Model& m = *mp;
|
||||
if (m.op.load() != kIdle || !m.engine || !m.ended || !m.ended->load()) continue;
|
||||
if (m.serve.joinable()) m.serve.join();
|
||||
join_spill(m); /* the background copy thread holds the engine */
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
m.engine.reset();
|
||||
if (m.op.load() != kIdle) continue;
|
||||
std::lock_guard<std::recursive_mutex> room(room_mu_);
|
||||
if (!m.engine || !m.ended || !m.ended->load()) continue;
|
||||
int idle = kIdle;
|
||||
if (!m.op.compare_exchange_strong(idle, kUnload)) continue;
|
||||
if (m.engine && m.ended && m.ended->load()) {
|
||||
if (m.serve.joinable()) m.serve.join();
|
||||
join_spill(m); /* the background copy thread holds the engine */
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
m.engine.reset();
|
||||
}
|
||||
front_.detach(m.entry.name, 0);
|
||||
fail(m, "it stopped while serving (see the log)");
|
||||
}
|
||||
front_.detach(m.entry.name, 0);
|
||||
fail(m, "it stopped while serving (see the log)");
|
||||
m.op.store(kIdle);
|
||||
}
|
||||
}
|
||||
|
||||
void Fleet::ttl_tick() {
|
||||
const uint64_t now = rad_mono_ns();
|
||||
for (auto& mp : models_) {
|
||||
std::lock_guard<std::recursive_mutex> room(room_mu_);
|
||||
Model& m = *mp;
|
||||
if (!m.engine || m.parked || m.entry.pin || m.entry.ttl_ms <= 0 || m.op.load() != kIdle) continue;
|
||||
const server::Front::Activity a = front_.activity(m.entry.name);
|
||||
@@ -2561,7 +2634,10 @@ std::string Fleet::reload() {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
models_.push_back(std::move(nm));
|
||||
}
|
||||
front_.add(e.name, e.aliases, nf.load_timeout_ms, required);
|
||||
/* Empty members: a name a reload turned back into a model loses its routing in the
|
||||
* same lock hold that registers it -- no request can see it registered but unrouted. */
|
||||
front_.add(e.name, e.aliases, nf.load_timeout_ms, required, {},
|
||||
e.cfg.control_vector_slots > 0);
|
||||
RAD_INFO("model %s: added", e.name.c_str());
|
||||
continue;
|
||||
}
|
||||
@@ -2576,10 +2652,36 @@ std::string Fleet::reload() {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
m->entry = e;
|
||||
}
|
||||
front_.update(e.name, e.aliases, nf.load_timeout_ms, required);
|
||||
front_.update(e.name, e.aliases, nf.load_timeout_ms, required,
|
||||
e.cfg.control_vector_slots > 0);
|
||||
}
|
||||
/* Virtual ids follow the file: (re)register the ones it names, drop the ones it does not. */
|
||||
for (const VirtualEntry& v : nf.virtuals)
|
||||
front_.add(v.name, v.aliases, nf.load_timeout_ms, false, v.members);
|
||||
for (const VirtualEntry& v : fc_.virtuals)
|
||||
if (!std::any_of(nf.virtuals.begin(), nf.virtuals.end(),
|
||||
[&](const VirtualEntry& w) { return w.name == v.name; }) &&
|
||||
/* A name the new file turned back into a model keeps its entry: the model loop
|
||||
* above re-registered it and cleared its routing. Removing it here would 404 the
|
||||
* model the file just described. */
|
||||
!std::any_of(nf.models.begin(), nf.models.end(),
|
||||
[&](const ModelEntry& m) { return m.name == v.name; })) {
|
||||
front_.remove(v.name);
|
||||
RAD_INFO("virtual id %s: removed", v.name.c_str());
|
||||
}
|
||||
fc_ = std::move(nf);
|
||||
publish_view();
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
for (auto& mp : models_) {
|
||||
if (!mp->engine || mp->max_in_flight_override > 0 || mp->engine->max_seqs() <= 0)
|
||||
continue;
|
||||
const int64_t target = fc_.max_in_flight > 0
|
||||
? std::min<int64_t>(fc_.max_in_flight, mp->engine->max_seqs())
|
||||
: mp->engine->max_seqs();
|
||||
(void)mp->engine->set_max_in_flight(target);
|
||||
}
|
||||
}
|
||||
dev_stuck_exit_ms.store(fc_.stuck_exit_ms, std::memory_order_relaxed);
|
||||
dev_pinned_numa_node.store(fc_.pinned_numa_node, std::memory_order_relaxed);
|
||||
for (const ModelEntry& e : fc_.models)
|
||||
@@ -2680,7 +2782,15 @@ json Fleet::placement(const std::string& name) {
|
||||
/* What it pins beside its copies while it has an engine: its host pools, its tables in
|
||||
* host memory and its prefix cache's host tier. */
|
||||
j["host_pinned_bytes"] = m->engine->host_pinned_bytes();
|
||||
if (m->engine->max_seqs() > 0) {
|
||||
j["max_in_flight"] = m->engine->max_in_flight();
|
||||
j["max_num_seqs"] = m->engine->max_seqs();
|
||||
}
|
||||
if (m->parked) j["drive_bytes"] = dev_page_fillable(m->engine->owner());
|
||||
} else if (e.cfg.max_seqs > 0) {
|
||||
const int64_t cap = m->max_in_flight_override > 0 ? m->max_in_flight_override : fc_.max_in_flight;
|
||||
j["max_in_flight"] = cap > 0 ? std::min<int64_t>(cap, e.cfg.max_seqs) : e.cfg.max_seqs;
|
||||
j["max_num_seqs"] = e.cfg.max_seqs;
|
||||
}
|
||||
j["park"] = {
|
||||
{ "ram", e.park.ram == ParkSpec::Ram::Required ? "required"
|
||||
@@ -2769,6 +2879,9 @@ void Fleet::history_loop() {
|
||||
history_.fleet_sample(f, t, f.dump());
|
||||
}
|
||||
for (const std::string& n : front_.names()) {
|
||||
/* A virtual id owns no engine and no stats: its member is sampled under its own
|
||||
* name already, and a second copy of those numbers would only double the charts. */
|
||||
if (front_.is_virtual(n)) continue;
|
||||
const bool is_open = front_.activity(n).state == server::Front::State::Open;
|
||||
if (!is_open) {
|
||||
if (open.erase(n) || row) {
|
||||
@@ -2890,7 +3003,9 @@ json Fleet::status() {
|
||||
}
|
||||
|
||||
bool Fleet::operator_ok(const server::HttpRequest& q) const {
|
||||
return !op_.api_key.empty() || server::local_operator(q, op_.host, op_.allow_hosts);
|
||||
return op_.api_key.empty()
|
||||
? server::local_operator(q, op_.host, op_.allow_hosts)
|
||||
: (q.authenticated || q.raw_peer.empty());
|
||||
}
|
||||
|
||||
void Fleet::add_routes() {
|
||||
@@ -2945,6 +3060,14 @@ void Fleet::add_routes() {
|
||||
bool known = false;
|
||||
for (const std::string& n : front_.names()) known |= n == name;
|
||||
if (!known) return bad(q, 404, "no model '" + name + "' is configured");
|
||||
if (front_.is_virtual(name)) {
|
||||
std::string members;
|
||||
for (const std::string& m : front_.virtual_members(name))
|
||||
members += (members.empty() ? "" : ", ") + m;
|
||||
return bad(q, 409, "'" + name + "' is a virtual id: load, park, unload, pin or unpin "
|
||||
"one of its members" +
|
||||
(members.empty() ? "" : " (" + members + ")"));
|
||||
}
|
||||
if (action == "load") {
|
||||
front_.retry(name);
|
||||
demand(name);
|
||||
@@ -3001,7 +3124,35 @@ void Fleet::add_routes() {
|
||||
if (pin) demand(name);
|
||||
return ok({ { "id", name }, { "pinned", pin } });
|
||||
}
|
||||
return bad(q, 404, "no admin action '" + action + "'; load, park, unload, pin or unpin");
|
||||
if (action == "max-in-flight") {
|
||||
if (q.body.size() > 4096)
|
||||
return bad(q, 400, "request body too large");
|
||||
const json body = json::parse(q.body, nullptr, false);
|
||||
if (body.is_discarded() || !body.is_object() ||
|
||||
!body.contains("max_in_flight") || !body["max_in_flight"].is_number_integer())
|
||||
return bad(q, 400, "body must be a JSON object with an integer `max_in_flight`");
|
||||
const int64_t want = body["max_in_flight"].get<int64_t>();
|
||||
int64_t ceiling = 0;
|
||||
std::shared_ptr<Engine> eng;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
Model* m = find(name);
|
||||
if (!m) return bad(q, 404, "no model '" + name + "' is configured");
|
||||
eng = m->engine;
|
||||
ceiling = eng ? eng->max_seqs() : m->entry.cfg.max_seqs;
|
||||
if (ceiling <= 0)
|
||||
return bad(q, 409, "model '" + name + "' has no resolved max_num_seqs yet; load it first");
|
||||
if (want < 1 || want > ceiling)
|
||||
return bad(q, 400, fmt("max_in_flight must be between 1 and max_num_seqs (%lld)",
|
||||
(long long)ceiling));
|
||||
m->max_in_flight_override = want;
|
||||
}
|
||||
if (eng) (void)eng->set_max_in_flight(want);
|
||||
const server::Front::Activity act = front_.activity(name);
|
||||
return ok({ { "id", name }, { "max_in_flight", want }, { "max_num_seqs", ceiling },
|
||||
{ "waiting", act.waiting } });
|
||||
}
|
||||
return bad(q, 404, "no admin action '" + action + "'; load, park, unload, pin, unpin or max-in-flight");
|
||||
});
|
||||
front_.route("POST", "/admin/reload", [this, guard, ok, bad, run_cmd](const server::HttpRequest& q) {
|
||||
if (auto g = guard(q)) return *g;
|
||||
@@ -3036,9 +3187,15 @@ void Fleet::loop() {
|
||||
if (g_stop.load()) break;
|
||||
Model* m = find(n);
|
||||
if (!m) continue;
|
||||
if (m->engine && !m->parked) continue; /* serving already */
|
||||
bool has_engine = false, is_parked = false;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
has_engine = m->engine != nullptr;
|
||||
is_parked = m->parked;
|
||||
}
|
||||
if (has_engine && !is_parked) continue; /* serving already */
|
||||
/* Every model's work runs on its own worker: a restore never waits behind a load. */
|
||||
if (!start_op(*m, m->engine && m->parked ? kRestore : kLoad)) waiting.push_back(n);
|
||||
if (!start_op(*m, has_engine && is_parked ? kRestore : kLoad)) waiting.push_back(n);
|
||||
}
|
||||
for (auto& m : models_)
|
||||
if (m->op.load() == kIdle && m->worker.joinable()) m->worker.join();
|
||||
@@ -3160,9 +3317,14 @@ int Fleet::run() {
|
||||
std::vector<std::string> preload;
|
||||
for (const ModelEntry& e : fc_.models) {
|
||||
const bool required = e.pin || fc_.models.size() == 1;
|
||||
front_.add(e.name, e.aliases, fc_.load_timeout_ms, required);
|
||||
front_.add(e.name, e.aliases, fc_.load_timeout_ms, required, {},
|
||||
e.cfg.control_vector_slots > 0);
|
||||
if (required) preload.push_back(e.name);
|
||||
}
|
||||
/* Virtual ids (docs/MULTIMODEL.md §8.5) join after the models: their members must be entries
|
||||
* too, and a virtual name of its own loads nothing until a request routes through it. */
|
||||
for (const VirtualEntry& v : fc_.virtuals)
|
||||
front_.add(v.name, v.aliases, fc_.load_timeout_ms, false, v.members);
|
||||
front_.set_demand([this](const std::string& n) { demand(n); });
|
||||
/* The guarded routes wake models only for callers their own handlers would admit: the same
|
||||
* operator_ok predicate add_routes' guard reads, keyed deployments always. */
|
||||
|
||||
+232
-74
@@ -118,22 +118,58 @@ static void flatten_json(const Json& j, const std::string& prefix, MetaOwn* out)
|
||||
}
|
||||
}
|
||||
|
||||
/* Read a checkpoint JSON file through the container size and depth bounds so a malformed or
|
||||
* oversized file never builds an unbounded DOM. */
|
||||
static int read_checkpoint_json(const std::string& path, Json* out, std::string* why = nullptr) {
|
||||
std::error_code ec;
|
||||
if (!std::filesystem::exists(path, ec)) return RAD_E_NOTFOUND;
|
||||
std::string text;
|
||||
const int rst = read_text_file(path, text, kMaxContainerFile);
|
||||
if (rst == RAD_E_FORMAT) {
|
||||
if (why) *why = "file exceeds the 256 MiB container JSON limit";
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
if (rst != RAD_OK) {
|
||||
if (why) *why = "cannot read file";
|
||||
return RAD_E_IO;
|
||||
}
|
||||
bool over = false, deep = false;
|
||||
Json j = Json::parse_container(text, &over, &deep);
|
||||
if (over || deep) {
|
||||
if (why) *why = Json::bound_why(over, deep);
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
if (j.is_discarded()) {
|
||||
if (why) *why = "invalid JSON";
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
*out = std::move(j);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* A second config.json (a drafter's), flattened under a prefix only. No typed extraction, which
|
||||
* would size the trunk from the draft head; the plugin reads `draft.` keys from the free-form
|
||||
* table. No `text_config` aliasing either: a drafter is a text model, and aliasing would collide
|
||||
* with the target's bare keys. */
|
||||
int meta_merge_config_json(const std::string& dir, const std::string& prefix, MetaOwn* out) {
|
||||
const std::string path = dir + "/config.json";
|
||||
std::ifstream f(path);
|
||||
if (!f) {
|
||||
Json j;
|
||||
std::string why;
|
||||
const int rc = read_checkpoint_json(path, &j, &why);
|
||||
if (rc == RAD_E_NOTFOUND) {
|
||||
RAD_ERR("%s: no config.json. A draft checkpoint carries its own geometry there -- the "
|
||||
"block size it was trained for, which trunk layers it reads, the selector's rank "
|
||||
"-- and none of it is derivable from the target.", dir.c_str());
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
Json j;
|
||||
try { f >> j; }
|
||||
catch (const std::exception& e) { RAD_ERR("%s: %s", path.c_str(), e.what()); return RAD_E_FORMAT; }
|
||||
if (rc != RAD_OK) {
|
||||
RAD_ERR("%s: %s", path.c_str(), why.c_str());
|
||||
return rc;
|
||||
}
|
||||
if (!j.is_object()) {
|
||||
RAD_ERR("%s: not a JSON object", path.c_str());
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
flatten_json(j, prefix, out);
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -146,12 +182,12 @@ int meta_merge_config_json(const std::string& dir, const std::string& prefix, Me
|
||||
* `generation.` to avoid colliding with architecture keys such as `temperature` or `top_k`. */
|
||||
int meta_merge_generation_config(const std::string& dir, MetaOwn* out) {
|
||||
const std::string path = dir + "/generation_config.json";
|
||||
std::ifstream f(path);
|
||||
if (!f) return RAD_OK; /* optional */
|
||||
Json j;
|
||||
try { f >> j; }
|
||||
catch (const std::exception& e) {
|
||||
RAD_WARN("%s: %s; no sampling defaults are carried", path.c_str(), e.what());
|
||||
std::string why;
|
||||
const int rc = read_checkpoint_json(path, &j, &why);
|
||||
if (rc == RAD_E_NOTFOUND) return RAD_OK; /* optional */
|
||||
if (rc != RAD_OK) {
|
||||
RAD_WARN("%s: %s; no sampling defaults are carried", path.c_str(), why.c_str());
|
||||
return RAD_OK;
|
||||
}
|
||||
if (!j.is_object()) {
|
||||
@@ -181,12 +217,12 @@ int meta_merge_preprocessor_configs(const std::string& dir, MetaOwn* out) {
|
||||
};
|
||||
for (const auto& f : kFiles) {
|
||||
const std::string path = dir + "/" + f.file;
|
||||
std::ifstream in(path);
|
||||
if (!in) continue;
|
||||
Json j;
|
||||
try { in >> j; }
|
||||
catch (const std::exception& e) {
|
||||
RAD_WARN("%s: %s; it is not carried", path.c_str(), e.what());
|
||||
std::string why;
|
||||
const int rc = read_checkpoint_json(path, &j, &why);
|
||||
if (rc == RAD_E_NOTFOUND) continue;
|
||||
if (rc != RAD_OK) {
|
||||
RAD_WARN("%s: %s; it is not carried", path.c_str(), why.c_str());
|
||||
continue;
|
||||
}
|
||||
if (j.is_object()) flatten_json(j, f.prefix, out);
|
||||
@@ -196,16 +232,20 @@ int meta_merge_preprocessor_configs(const std::string& dir, MetaOwn* out) {
|
||||
|
||||
int meta_from_config_json(const std::string& dir, MetaOwn* out) {
|
||||
const std::string path = dir + "/config.json";
|
||||
std::ifstream f(path);
|
||||
if (!f) {
|
||||
Json j;
|
||||
std::string why;
|
||||
const int rc = read_checkpoint_json(path, &j, &why);
|
||||
if (rc == RAD_E_NOTFOUND) {
|
||||
RAD_ERR("%s: no config.json. A safetensors checkpoint carries its architecture and its "
|
||||
"dimensions there; without it nothing can be sized.", dir.c_str());
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
Json j;
|
||||
try { f >> j; }
|
||||
catch (const std::exception& e) {
|
||||
RAD_ERR("%s: %s", path.c_str(), e.what());
|
||||
if (rc != RAD_OK) {
|
||||
RAD_ERR("%s: %s", path.c_str(), why.c_str());
|
||||
return rc;
|
||||
}
|
||||
if (!j.is_object()) {
|
||||
RAD_ERR("%s: not a JSON object", path.c_str());
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
|
||||
@@ -262,6 +302,8 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) {
|
||||
/* Inkling 2's loop checkpoint (`inkling2_loop`) is the one plugin's model: its loop is
|
||||
* read from loop_config, the schedule the rest of the family runs. */
|
||||
if (out->arch == "inkling2loop") out->arch = "inkling2";
|
||||
/* ERNIE-5.5 MoE (`ernie5_5_moe`) strips underscores to `ernie55moe`, served by `ernie55`. */
|
||||
if (out->arch == "ernie55moe") out->arch = "ernie55";
|
||||
}
|
||||
if (const char* nm = gs("_name_or_path")) out->name = nm;
|
||||
|
||||
@@ -574,14 +616,19 @@ int Checkpoint::add_shard(const std::string& p, const std::string& prefix,
|
||||
const std::unordered_map<std::string, std::string>* owner) {
|
||||
shards_.push_back(std::make_unique<SafeTensorsFile>());
|
||||
RAD_TRY(shards_.back()->open(p));
|
||||
const std::string file = p.substr(p.find_last_of('/') + 1);
|
||||
for (const auto& t : shards_.back()->tensors()) {
|
||||
/* The index decides which shard a tensor is read from: a directory merging two
|
||||
* checkpoints (a finetune's shards beside links to the base model's) holds some names
|
||||
* twice. */
|
||||
* twice. Match against the relative shard path (which may include a subdirectory). */
|
||||
if (owner) {
|
||||
auto it = owner->find(t.name);
|
||||
if (it != owner->end() && it->second != file) continue;
|
||||
if (it != owner->end()) {
|
||||
const std::string& want = it->second;
|
||||
const bool match = p == want ||
|
||||
(p.size() > want.size() && p[p.size() - want.size() - 1] == '/' &&
|
||||
p.compare(p.size() - want.size(), want.size(), want) == 0);
|
||||
if (!match) continue;
|
||||
}
|
||||
}
|
||||
if (index_.count(prefix + t.name)) {
|
||||
RAD_ERR("%s: '%s' is also in %s, and no index entry says which copy to read", p.c_str(),
|
||||
@@ -660,15 +707,18 @@ int shard_list(const std::string& dir, const std::string& index, bool index_give
|
||||
/* A JSON file flattened under `prefix`; absent is not an error when `optional`. */
|
||||
static int meta_merge_json_file(const std::string& path, const std::string& prefix, bool optional,
|
||||
MetaOwn* out) {
|
||||
std::ifstream f(path);
|
||||
if (!f) {
|
||||
Json j;
|
||||
std::string why;
|
||||
const int rc = read_checkpoint_json(path, &j, &why);
|
||||
if (rc == RAD_E_NOTFOUND) {
|
||||
if (optional) return RAD_OK;
|
||||
RAD_ERR("%s: cannot read it", path.c_str());
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
Json j;
|
||||
try { f >> j; }
|
||||
catch (const std::exception& e) { RAD_ERR("%s: %s", path.c_str(), e.what()); return RAD_E_FORMAT; }
|
||||
if (rc != RAD_OK) {
|
||||
RAD_ERR("%s: %s", path.c_str(), why.c_str());
|
||||
return rc;
|
||||
}
|
||||
if (!j.is_object()) {
|
||||
RAD_ERR("%s: not a JSON object", path.c_str());
|
||||
return RAD_E_FORMAT;
|
||||
@@ -1169,6 +1219,31 @@ int Checkpoint::open_safetensors(const std::string& path) {
|
||||
RAD_TRY(meta_from_config_json(md, &meta_));
|
||||
RAD_TRY(meta_merge_generation_config(md, &meta_));
|
||||
RAD_TRY(meta_merge_preprocessor_configs(md, &meta_));
|
||||
/* Both Qwen3 retrieval releases advertise Qwen3ForCausalLM. Their sentence-transformers
|
||||
* modules distinguish the task; preserve those contracts in .rad metadata. Never infer
|
||||
* a retrieval task from the directory name or from model_type alone. */
|
||||
if (meta_.arch == "qwen3") {
|
||||
for (const auto& entry : {std::pair{"1_Pooling", "pooling"},
|
||||
std::pair{"1_LogitScore", "logit_score"}}) {
|
||||
const std::string file = md + "/" + entry.first + "/config.json";
|
||||
Json j;
|
||||
std::string why;
|
||||
const int rc = read_checkpoint_json(file, &j, &why);
|
||||
if (rc == RAD_E_NOTFOUND) continue;
|
||||
if (rc != RAD_OK) {
|
||||
RAD_ERR("%s: %s", file.c_str(), why.c_str());
|
||||
return rc;
|
||||
}
|
||||
if (!j.is_object()) return RAD_E_FORMAT;
|
||||
flatten_json(j, entry.second, &meta_);
|
||||
const char* role = !std::strcmp(entry.second, "pooling") ? "embedding" : "rerank";
|
||||
if (meta_.has("retrieval.type") && std::strcmp(meta_.get("retrieval.type"), role)) {
|
||||
RAD_ERR("%s: conflicting retrieval modules", md.c_str());
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
meta_.set("retrieval.type", role);
|
||||
}
|
||||
}
|
||||
if (!meta_dir_.empty() && !path_exists(dir_ + "/tokenizer.json")) tok_dir_ = meta_dir_;
|
||||
if (!is_file && !is_index) {
|
||||
RAD_TRY(add_companions());
|
||||
@@ -1319,11 +1394,8 @@ int Checkpoint::add_torch_files() {
|
||||
/* Which published quantisation this is, from quantization_config alone; import_piece checks the
|
||||
* tensors weight by weight, refusing a file at the first weight that disagrees. */
|
||||
bool Checkpoint::detect_per_tensor() {
|
||||
std::ifstream in(dir_ + "/hf_quant_config.json");
|
||||
if (!in) return false;
|
||||
Json j;
|
||||
try { in >> j; }
|
||||
catch (const std::exception&) { return false; }
|
||||
if (read_checkpoint_json(dir_ + "/hf_quant_config.json", &j) != RAD_OK) return false;
|
||||
if (!j.is_object() || !j.contains("model") || !j["model"].is_object() ||
|
||||
!j["model"].contains("parameter_groups") || !j["model"]["parameter_groups"].is_array())
|
||||
return false;
|
||||
@@ -1431,7 +1503,17 @@ void Checkpoint::detect_import() {
|
||||
return false;
|
||||
};
|
||||
const std::string qm = qc("quant_method");
|
||||
if (qm == "fp8") {
|
||||
if (qm == "fp8" && qc("expert_dtype") == "mxfp4") {
|
||||
/* ERNIE-5.5 mixed-precision checkpoint: MoE routed experts packed as I8 MXFP4 with
|
||||
* F8_E8M0 `_scale_inv` (group 32), trunk/MTP weights as 128x128 block F8_E4M3 with
|
||||
* F32 `_scale_inv` (exact pow2 in BF16). */
|
||||
if (qc("fmt") == "e4m3" && qc("scale_fmt") == "ue8m0" &&
|
||||
fp8_br_ == 128 && fp8_bc_ == 128)
|
||||
import_ = Import::ErnieMx;
|
||||
else
|
||||
import_why_ = "fp8+mxfp4 checkpoint is not fmt=e4m3, scale_fmt=ue8m0 with "
|
||||
"128x128 weight_block_size, which ErnieMx reads";
|
||||
} else if (qm == "fp8") {
|
||||
/* DeepSeek-V4's release: block-FP8 linears under `X.scale` e8m0 planes, and routed
|
||||
* experts packed two e2m1 codes a byte under an e8m0 scale per 32 of K. */
|
||||
if (qc("scale_fmt") == "ue8m0" && qc("expert_dtype") == "fp4" && fp8_br_ == 32 &&
|
||||
@@ -1879,6 +1961,71 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes,
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
if (im == Import::ErnieMx) {
|
||||
const SrcTensor* w = find(name);
|
||||
if (!w) return RAD_E_NOTFOUND;
|
||||
if (w->rad_dtype == RAD_I8) {
|
||||
const SrcTensor* e = find(name + "_scale_inv");
|
||||
if (!e) return RAD_E_NOTFOUND;
|
||||
if (e->rad_dtype != RAD_E8M0 || w->shape.size() != 2 || e->shape.size() != 2 ||
|
||||
w->shape[0] <= 0 || w->shape[1] <= 0 ||
|
||||
e->shape[0] != w->shape[0] || e->shape[1] * 32 != w->shape[1] * 2)
|
||||
return refuse(RAD_E_SHAPE, "'" + e->name + "' is not the [N, K/32] e8m0 scale "
|
||||
"plane of '" + w->name + "'");
|
||||
SrcTensor c = *w;
|
||||
c.rad_dtype = RAD_FP4E2M1;
|
||||
c.shape = { w->shape[0], w->shape[1] * 2 };
|
||||
sliced_.push_back(std::move(c));
|
||||
*codes = &sliced_.back();
|
||||
*scale = e;
|
||||
imported_[name] = { *codes, *scale };
|
||||
return RAD_OK;
|
||||
}
|
||||
if (w->rad_dtype == RAD_F8E4M3) {
|
||||
const SrcTensor* e = find(name + "_scale_inv");
|
||||
if (!e) return RAD_E_NOTFOUND;
|
||||
if (e->rad_dtype == RAD_BF16) return RAD_E_NOTFOUND; /* stock bf16 block scales */
|
||||
if (e->rad_dtype != RAD_F32)
|
||||
return refuse(RAD_E_FORMAT, "'" + e->name + "' is neither f32 nor bf16 block "
|
||||
"scales of '" + w->name + "'");
|
||||
if (w->shape.size() != 2 || e->shape.size() != 2 ||
|
||||
w->shape[0] <= 0 || w->shape[1] <= 0)
|
||||
return refuse(RAD_E_SHAPE, "'" + e->name + "' or '" + w->name +
|
||||
"' is not a non-empty 2D matrix");
|
||||
const int64_t want_r = (w->shape[0] + fp8_br_ - 1) / fp8_br_;
|
||||
const int64_t want_c = (w->shape[1] + fp8_bc_ - 1) / fp8_bc_;
|
||||
if (e->shape[0] != want_r || e->shape[1] != want_c)
|
||||
return refuse(RAD_E_SHAPE, "'" + e->name + "' is not the [" +
|
||||
std::to_string(want_r) + ", " + std::to_string(want_c) +
|
||||
"] block scale plane of '" + w->name + "'");
|
||||
const int64_t nsc = want_r * want_c;
|
||||
auto raw = std::make_unique<uint8_t[]>((size_t)nsc * 2);
|
||||
for (int64_t i = 0; i < nsc; ++i) {
|
||||
float v;
|
||||
std::memcpy(&v, (const uint8_t*)e->data + (size_t)i * 4, 4);
|
||||
if (!std::isfinite(v))
|
||||
return refuse(RAD_E_FORMAT, "'" + e->name + "' holds a non-finite scale at "
|
||||
"element " + std::to_string(i));
|
||||
rad_store_f32(raw.get(), RAD_BF16, i, v);
|
||||
if (rad_load_f32(raw.get(), RAD_BF16, i) != v)
|
||||
return refuse(RAD_E_FORMAT, "'" + e->name + "' holds F32 scale " +
|
||||
std::to_string(v) + " at element " +
|
||||
std::to_string(i) + ", which is not exact in bf16");
|
||||
}
|
||||
owned_.push_back(std::move(raw));
|
||||
SrcTensor sv = *e;
|
||||
sv.rad_dtype = RAD_BF16;
|
||||
sv.data = owned_.back().get();
|
||||
sv.bytes = nsc * 2;
|
||||
*codes = w;
|
||||
sliced_.push_back(std::move(sv));
|
||||
*scale = &sliced_.back();
|
||||
imported_[name] = { *codes, *scale };
|
||||
return RAD_OK;
|
||||
}
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
|
||||
if (im == Import::CtInt4) {
|
||||
/* CT-INT4: `X.weight` ships as X.weight_packed (i32 [N, K/8], eight codes per word from the
|
||||
* low bits, each the signed code plus 8) and X.weight_scale ([N, K/group]), and when
|
||||
@@ -2248,14 +2395,15 @@ int Checkpoint::add_draft(const std::string& dir, const std::string& prefix) {
|
||||
* a drafter repository would merge the target's config and shards a second time, so it is
|
||||
* refused by name. */
|
||||
if (path_exists(dir + "/mtp.safetensors")) {
|
||||
std::ifstream f(dir + "/config.json");
|
||||
Json j;
|
||||
try { if (f) f >> j; }
|
||||
catch (const std::exception& e) {
|
||||
RAD_ERR("%s/config.json: %s", dir.c_str(), e.what());
|
||||
return RAD_E_FORMAT;
|
||||
std::string why;
|
||||
const int rc = read_checkpoint_json(dir + "/config.json", &j, &why);
|
||||
if (rc != RAD_OK && rc != RAD_E_NOTFOUND) {
|
||||
RAD_ERR("%s/config.json: %s", dir.c_str(), why.c_str());
|
||||
return rc;
|
||||
}
|
||||
if (j.is_object() && j.contains("mtp_config") && j["mtp_config"].is_object()) {
|
||||
if (rc == RAD_OK && j.is_object() && j.contains("mtp_config") &&
|
||||
j["mtp_config"].is_object()) {
|
||||
RAD_ERR("%s is Inkling 2's release with its DSpark drafter (mtp.safetensors, "
|
||||
"config.json's mtp_config), which is not served; pass incoai's "
|
||||
"Inkling-2-Mini-DFlash2 directory as --draft-model "
|
||||
@@ -2333,14 +2481,16 @@ struct LoraRule {
|
||||
* pattern matches a module wins. */
|
||||
static int lora_map_read(const std::string& file, std::vector<std::string>* strip,
|
||||
std::vector<LoraRule>* rules) {
|
||||
std::ifstream f(file);
|
||||
if (!f) { RAD_ERR("lora: --lora-map %s cannot be read", file.c_str()); return RAD_E_NOTFOUND; }
|
||||
Json j;
|
||||
try {
|
||||
j = Json::parse(f);
|
||||
} catch (const std::exception& e) {
|
||||
RAD_ERR("lora: --lora-map %s: %s", file.c_str(), e.what());
|
||||
return RAD_E_FORMAT;
|
||||
std::string why;
|
||||
const int rc = read_checkpoint_json(file, &j, &why);
|
||||
if (rc == RAD_E_NOTFOUND) {
|
||||
RAD_ERR("lora: --lora-map %s cannot be read", file.c_str());
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
if (rc != RAD_OK) {
|
||||
RAD_ERR("lora: --lora-map %s: %s", file.c_str(), why.c_str());
|
||||
return rc;
|
||||
}
|
||||
if (!j.is_object()) { RAD_ERR("lora: --lora-map %s is not a JSON object", file.c_str());
|
||||
return RAD_E_FORMAT; }
|
||||
@@ -2419,41 +2569,47 @@ int Checkpoint::add_lora(const std::string& path, double strength,
|
||||
if (st.open(f) != RAD_OK) return RAD_E_FORMAT;
|
||||
std::vector<Pair> pairs;
|
||||
std::map<std::string, size_t> by_module;
|
||||
auto get_pair = [&](const std::string& mod) -> Pair& {
|
||||
auto [it, ins] = by_module.emplace(mod, pairs.size());
|
||||
if (ins) {
|
||||
Pair p;
|
||||
p.module = mod;
|
||||
pairs.push_back(std::move(p));
|
||||
}
|
||||
return pairs[it->second];
|
||||
};
|
||||
auto ends_with = [](const std::string& s, const char* suf, size_t n) {
|
||||
return s.size() > n && s.compare(s.size() - n, n, suf) == 0;
|
||||
};
|
||||
for (const StTensor& t : st.tensors()) {
|
||||
if (t.name.size() > 12 && t.name.compare(t.name.size() - 12, 12, ".dora.scalar") == 0) {
|
||||
if (ends_with(t.name, ".dora.scalar", 12)) {
|
||||
RAD_ERR("lora: '%s' is a DoRA adapter; only plain LoRA merges (a magnitude vector "
|
||||
"has no place in a weight merge)", t.name.c_str());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const char* suf = nullptr;
|
||||
if (t.name.size() > 14 && t.name.compare(t.name.size() - 14, 14, ".lora_A.weight") == 0)
|
||||
suf = ".lora_A.weight";
|
||||
else if (t.name.size() > 18 &&
|
||||
t.name.compare(t.name.size() - 18, 18, ".lora_down.weight") == 0)
|
||||
suf = ".lora_down.weight";
|
||||
if (suf) {
|
||||
Pair p;
|
||||
p.module = t.name.substr(0, t.name.size() - std::strlen(suf));
|
||||
p.a = &t;
|
||||
by_module[p.module] = pairs.size();
|
||||
pairs.push_back(std::move(p));
|
||||
} else if (t.name.size() > 14 &&
|
||||
t.name.compare(t.name.size() - 14, 14, ".lora_B.weight") == 0) {
|
||||
auto it = by_module.find(t.name.substr(0, t.name.size() - 14));
|
||||
if (it != by_module.end()) pairs[it->second].b = &t;
|
||||
} else if (t.name.size() > 6 &&
|
||||
t.name.compare(t.name.size() - 6, 6, ".alpha") == 0) {
|
||||
auto it = by_module.find(t.name.substr(0, t.name.size() - 6));
|
||||
if (it != by_module.end()) pairs[it->second].al = &t;
|
||||
}
|
||||
if (ends_with(t.name, ".lora_A.weight", 14))
|
||||
get_pair(t.name.substr(0, t.name.size() - 14)).a = &t;
|
||||
else if (ends_with(t.name, ".lora_down.weight", 17))
|
||||
get_pair(t.name.substr(0, t.name.size() - 17)).a = &t;
|
||||
else if (ends_with(t.name, ".lora_B.weight", 14))
|
||||
get_pair(t.name.substr(0, t.name.size() - 14)).b = &t;
|
||||
else if (ends_with(t.name, ".lora_up.weight", 15))
|
||||
get_pair(t.name.substr(0, t.name.size() - 15)).b = &t;
|
||||
else if (ends_with(t.name, ".alpha", 6))
|
||||
get_pair(t.name.substr(0, t.name.size() - 6)).al = &t;
|
||||
}
|
||||
/* Drop entries that only carried an orphan .alpha with neither A nor B. */
|
||||
pairs.erase(std::remove_if(pairs.begin(), pairs.end(),
|
||||
[](const Pair& p) { return !p.a && !p.b; }),
|
||||
pairs.end());
|
||||
if (pairs.empty()) {
|
||||
RAD_ERR("lora: %s holds no .lora_A.weight / .lora_down.weight tensors", f.c_str());
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
for (Pair& p : pairs) {
|
||||
if (!p.b) {
|
||||
RAD_ERR("lora: '%s' ships its A but no B", p.module.c_str());
|
||||
if (!p.a || !p.b) {
|
||||
RAD_ERR("lora: '%s' ships its %s but no %s", p.module.c_str(),
|
||||
p.a ? "A" : "B", p.a ? "B" : "A");
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
/* The targets: `<module>.weight`, else the same with a wrapper prefix stripped, else
|
||||
@@ -3142,7 +3298,8 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
|
||||
}
|
||||
/* A row piece (RAD_MAP_ROWS): rows [first, first + rows) of the codes, and of the
|
||||
* scale plane they cover. A block plane's rows are [K/br]-wide blocks, so a cut of
|
||||
* the codes must fall on a block boundary there. */
|
||||
* the codes must fall on a block boundary there (the last piece may end on a ragged
|
||||
* tail at whole_rows, e.g. ERNIE-5.5's [512, 576) DSA kv_a_rope). */
|
||||
if (st && row_pieces && !imported_rows) {
|
||||
const SrcTensor* whole = st;
|
||||
const int64_t r0 = s1.index, nrows = s1.rows;
|
||||
@@ -3156,12 +3313,13 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
|
||||
const int64_t srows = sc->shape.empty() ? 1 : sc->shape[0];
|
||||
const int64_t blocks = br > 0 ? (whole_rows + br - 1) / br : 0;
|
||||
if (srows == blocks && blocks != whole_rows) {
|
||||
if (r0 % br || nrows % br)
|
||||
if (r0 < 0 || nrows <= 0 || r0 + nrows > whole_rows ||
|
||||
r0 % br || (nrows % br && r0 + nrows != whole_rows))
|
||||
return refuse(RAD_E_SHAPE, "rows [" + std::to_string(r0) + ", " +
|
||||
std::to_string(r0 + nrows) + ") of '" +
|
||||
std::string(s1.name) + "' do not fall on "
|
||||
+ std::to_string(br) + "-row scale blocks");
|
||||
sc = ck.rows(*sc, r0 / br, nrows / br, name.c_str());
|
||||
sc = ck.rows(*sc, r0 / br, (nrows + br - 1) / br, name.c_str());
|
||||
} else if (srows == whole_rows) {
|
||||
sc = ck.rows(*sc, r0, nrows, name.c_str());
|
||||
} else {
|
||||
|
||||
@@ -30,6 +30,7 @@
|
||||
#include <deque>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
#include <utility>
|
||||
@@ -103,6 +104,12 @@ struct MetaOwn {
|
||||
void finish();
|
||||
};
|
||||
|
||||
/* Qwen3 embeddings pool over the token appended by the Hugging Face post-processor. */
|
||||
inline bool uses_qwen3_embedding_tokenizer(const RadModelMeta& meta) {
|
||||
return meta.arch_id && std::string_view(meta.arch_id) == "qwen3" &&
|
||||
std::string_view(rad_meta_gets(&meta, "retrieval.type", "")) == "embedding";
|
||||
}
|
||||
|
||||
int meta_from_config_json(const std::string& dir, MetaOwn* out);
|
||||
/* quantization_config's quant_method and fmt as the plugin descriptor ("fp8_e4m3"), "" without. */
|
||||
std::string quant_descriptor(const MetaOwn& m);
|
||||
@@ -183,8 +190,11 @@ public:
|
||||
* compressed-tensors' pack-quantized int4 (symmetric, or asymmetric with a zero point), a
|
||||
* release with an nvfp4-pack-quantized group, and one whose groups are all float-quantized FP8
|
||||
* (detect_import). ModelOpt: NVIDIA ModelOpt's NVFP4, FP8, or both per layer
|
||||
* (MIXED_PRECISION). In an Nvfp4, CtFp8 or ModelOpt release every weight without the NVFP4
|
||||
* tensors reads stock, so FP8 and bf16 linears beside the NVFP4 ones read by their own form.
|
||||
* (MIXED_PRECISION). ErnieMx: ERNIE-5.5 mixed precision (I8 MXFP4 routed experts with E8M0
|
||||
* `_scale_inv` per 32 of K; 128x128 block F8_E4M3 trunk/MTP weights with F32 `_scale_inv`
|
||||
* converted losslessly to BF16). In an Nvfp4, CtFp8, ModelOpt or ErnieMx release every weight
|
||||
* without the quantised planes reads stock, so FP8 and bf16/f32 linears beside them read by
|
||||
* their own form.
|
||||
* Gguf: a GGUF holding llama.cpp block types (K-, I- and legacy quants): every such tensor is
|
||||
* imported block for block as the affine planes libquant's `ggml` quantiser writes for the
|
||||
* same blocks (libquant/lq_ggml_planes.h); its float tensors read as they are.
|
||||
@@ -198,8 +208,8 @@ public:
|
||||
* describe the tool, not a served format. */
|
||||
/* PerTensor: hf_quant_config.json's per-tensor parameter groups (Inkling 2's release), which
|
||||
* decide each tensor's form and take precedence over config.json's quantization_config. */
|
||||
enum class Import { None, Gptq, QuarkMx, CtInt4, ParoMx, ParoM2, ParoI5, ParoI4, Nvfp4, CtFp8,
|
||||
ModelOpt, PerTensor, Gguf, Fp8Mx };
|
||||
enum class Import { None, Gptq, QuarkMx, ErnieMx, CtInt4, ParoMx, ParoM2, ParoI5, ParoI4,
|
||||
Nvfp4, CtFp8, ModelOpt, PerTensor, Gguf, Fp8Mx };
|
||||
Import imports() const { return import_; }
|
||||
/* The form `name` is read in: a drafter merged by add_draft ships its own quantisation (a
|
||||
* ModelOpt NVFP4 drafter beside a bf16 target), so names under its prefix take that one. */
|
||||
|
||||
+45
-6
@@ -215,7 +215,7 @@ int RadFile::validate() {
|
||||
hdr_->version, RAD_FORMAT_VER);
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
if ((int64_t)hdr_->file_bytes > size_) {
|
||||
if (hdr_->file_bytes > (uint64_t)size_) {
|
||||
RAD_ERR("%s: header claims %llu bytes, the file is %lld -- truncated",
|
||||
path_.c_str(), (unsigned long long)hdr_->file_bytes, (long long)size_);
|
||||
return RAD_E_FORMAT;
|
||||
@@ -370,13 +370,52 @@ int RadFile::validate() {
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
/* Every plane is exactly its encoding's size and inside its entry, so readers slice planes
|
||||
* by arithmetic and the mover treats the entry as one span. */
|
||||
int64_t rows = 0, cols = 0;
|
||||
rad_enc_view(e.rank, e.shape, &rows, &cols);
|
||||
* by arithmetic and the mover treats the entry as one span. Check shape multiplication
|
||||
* for overflow before calling rad_enc_view / rad_enc_plane_bytes. */
|
||||
int64_t rows = 1, cols = e.shape[e.rank - 1];
|
||||
for (uint32_t d = 0; d + 1 < e.rank; ++d) {
|
||||
if (__builtin_mul_overflow(rows, e.shape[d], &rows)) {
|
||||
RAD_ERR("%s: '%s' shape overflows int64", path_.c_str(), str(e.name));
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
}
|
||||
if (rows <= 0 || cols <= 0) {
|
||||
RAD_ERR("%s: '%s' has non-positive view [%lld, %lld]", path_.c_str(), str(e.name),
|
||||
(long long)rows, (long long)cols);
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
for (uint32_t k = 0; k < e.n_planes; ++k) {
|
||||
const RadFilePlane& p = planes_[e.plane_first + k];
|
||||
const int64_t want = rad_enc_plane_bytes(&enc.plane[k], rows, cols);
|
||||
if ((int64_t)p.bytes != want || p.offset % RAD_ALIGN_SUB != 0 || p.offset < e.offset ||
|
||||
const RadEncPlane& ep = enc.plane[k];
|
||||
int64_t pr = 0, pc = 0;
|
||||
if (ep.kind == RAD_PLANE_TABLE) {
|
||||
pr = ep.extent[0];
|
||||
pc = ep.extent[1];
|
||||
} else {
|
||||
const int64_t b0 = ep.block[0], b1 = ep.block[1];
|
||||
if (b0 < 0 || b1 < 0) {
|
||||
RAD_ERR("%s: '%s' plane %u has negative block size", path_.c_str(), str(e.name), k);
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
int64_t n0 = 0, n1 = 0;
|
||||
if (b0 == 0) pr = 1;
|
||||
else if (__builtin_add_overflow(rows, b0 - 1, &n0)) {
|
||||
RAD_ERR("%s: '%s' plane %u row count overflows", path_.c_str(), str(e.name), k);
|
||||
return RAD_E_FORMAT;
|
||||
} else pr = n0 / b0;
|
||||
if (b1 == 0) pc = 1;
|
||||
else if (__builtin_add_overflow(cols, b1 - 1, &n1)) {
|
||||
RAD_ERR("%s: '%s' plane %u col count overflows", path_.c_str(), str(e.name), k);
|
||||
return RAD_E_FORMAT;
|
||||
} else pc = n1 / b1;
|
||||
}
|
||||
const int64_t bits = rad_dtype_bits(ep.dtype);
|
||||
int64_t rbits = 0, rbits7 = 0, want = 0;
|
||||
if (pr < 0 || pc < 0 || bits <= 0 ||
|
||||
__builtin_mul_overflow(bits, pc, &rbits) ||
|
||||
__builtin_add_overflow(rbits, (int64_t)7, &rbits7) ||
|
||||
__builtin_mul_overflow(pr, rbits7 / 8, &want) ||
|
||||
(int64_t)p.bytes != want || p.offset % RAD_ALIGN_SUB != 0 || p.offset < e.offset ||
|
||||
p.offset - e.offset > e.bytes || p.bytes > e.bytes - (p.offset - e.offset)) {
|
||||
RAD_ERR("%s: '%s' plane %u ('%s') is %llu bytes at %llu; its encoding over "
|
||||
"[%lld, %lld] makes it %lld, %u-aligned inside [%llu, %llu)",
|
||||
|
||||
+20
-1
@@ -39,7 +39,26 @@ int weight_share(const WeightInfo& w, const RadEncoding& enc, uint32_t rank, con
|
||||
struct VRect { int64_t r0, r1, c0, c1; };
|
||||
std::vector<VRect> view;
|
||||
const bool span = w.shard_hi > 0 || w.n_part_spans > 0;
|
||||
if (whole) {
|
||||
if (whole && !w.row_order.empty()) {
|
||||
/* rad_weight_row_order: the entry's rows (a vector's elements) in the declared order, one
|
||||
* rectangle a run of consecutive rows. */
|
||||
const bool vec = rank == 1;
|
||||
const int64_t n = vec ? VC : VR;
|
||||
if (!single || (int64_t)w.row_order.size() != n || (vec && VR != 1))
|
||||
return refuse(fmt("a row order of %zu rows over an entry of %lld rows%s",
|
||||
w.row_order.size(), (long long)n,
|
||||
single ? "" : " and several planes"));
|
||||
for (size_t i = 0; i < w.row_order.size();) {
|
||||
const int64_t r0 = w.row_order[i];
|
||||
size_t j = i + 1;
|
||||
while (j < w.row_order.size() && w.row_order[j] == r0 + (int64_t)(j - i)) ++j;
|
||||
const int64_t r1 = r0 + (int64_t)(j - i);
|
||||
if (r0 < 0 || r1 > n) return refuse("a row order names a row outside the entry");
|
||||
if (vec) view.push_back({ 0, 1, r0, r1 });
|
||||
else view.push_back({ r0, r1, 0, VC });
|
||||
i = j;
|
||||
}
|
||||
} else if (whole) {
|
||||
view.push_back({ 0, VR, 0, VC });
|
||||
} else {
|
||||
/* A sharded weight must be a matrix; anything else is refused rather than guessing which
|
||||
|
||||
@@ -259,7 +259,9 @@ int TuneCache::save(const std::string& home) const {
|
||||
r->measured.empty() ? "-" : r->measured.c_str(), r->geom.c_str());
|
||||
}
|
||||
|
||||
if (::fflush(f) != 0 || ::fclose(f) != 0) {
|
||||
const int flush_rc = ::fflush(f);
|
||||
const int close_rc = ::fclose(f);
|
||||
if (flush_rc != 0 || close_rc != 0) {
|
||||
RAD_ERR("%s: %s", tmp.c_str(), std::strerror(errno));
|
||||
::unlink(tmp.c_str());
|
||||
return RAD_E_IO;
|
||||
|
||||
@@ -468,8 +468,9 @@ int AudioDriver::upload() {
|
||||
for (size_t r = 0; r < ranks_.size(); ++r)
|
||||
for (int g = 0; g < R_N; ++g) {
|
||||
if (reg_[g].used <= 0) continue;
|
||||
RAD_TRY(rad_memcpy_async((char*)dev_[r] + reg_[g].off, host_ + reg_[g].off,
|
||||
reg_[g].used, ranks_[r].stream));
|
||||
const int st = rad_memcpy_async((char*)dev_[r] + reg_[g].off, host_ + reg_[g].off,
|
||||
reg_[g].used, ranks_[r].stream);
|
||||
if (st < 0) { fatal_ = st; return st; }
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
+3
-2
@@ -501,8 +501,9 @@ int Driver::upload() {
|
||||
for (size_t r = 0; r < ranks_.size(); ++r)
|
||||
for (int g = 0; g < R_N; ++g) {
|
||||
if (reg_[g].used <= 0) continue;
|
||||
RAD_TRY(rad_memcpy_async((char*)dev_[r] + reg_[g].off, host_ + reg_[g].off,
|
||||
reg_[g].used, ranks_[r].stream));
|
||||
const int st = rad_memcpy_async((char*)dev_[r] + reg_[g].off, host_ + reg_[g].off,
|
||||
reg_[g].used, ranks_[r].stream);
|
||||
if (st < 0) { fatal_ = st; return st; }
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
+4
-2
@@ -80,8 +80,10 @@ std::vector<float> schedule(const RadGeneratorDecl& d, const std::vector<double>
|
||||
}
|
||||
} else {
|
||||
const int32_t n = steps > 0 ? steps : (int32_t)d.default_steps;
|
||||
/* np.linspace(1.0, 1 / n, n) in f64, then astype(f32). */
|
||||
const double lo = 1.0 / (double)n;
|
||||
/* np.linspace(1.0, 1 / n, n) in f64, then astype(f32) -- or, with `sigma_lower` > 0, the
|
||||
* schedule's own lower bound (MOSSImageScheduler: shift / (train_steps + shift - 1),
|
||||
* so the last sigma is the same for every step count). */
|
||||
const double lo = d.sigma_lower > 0.0 ? d.sigma_lower : 1.0 / (double)n;
|
||||
for (int32_t i = 0; i < n; ++i) {
|
||||
const double v = n == 1 ? 1.0 : 1.0 + (lo - 1.0) * (double)i / (double)(n - 1);
|
||||
s.push_back((float)v);
|
||||
|
||||
@@ -37,10 +37,16 @@ struct IPassDriver {
|
||||
virtual int done() = 0;
|
||||
/* Fail every request queued or in flight, and refuse new ones. */
|
||||
virtual void shutdown(const char* why, int status) = 0;
|
||||
/* Sticky fatal status set when staging/upload fails inside next(), so gen_loop() stops
|
||||
* instead of treating nullptr as idle and retrying forever. */
|
||||
virtual int fatal_status() const { return fatal_; }
|
||||
|
||||
/* For /health, /stats and the dashboard. */
|
||||
virtual int64_t queued() const = 0;
|
||||
virtual int64_t running() const = 0;
|
||||
|
||||
protected:
|
||||
int fatal_ = RAD_OK;
|
||||
};
|
||||
|
||||
} /* namespace gen */
|
||||
|
||||
@@ -214,8 +214,9 @@ int ShapeDriver::upload() {
|
||||
for (size_t r = 0; r < ranks_.size(); ++r)
|
||||
for (int g = 0; g < R_N; ++g) {
|
||||
if (reg_[g].used <= 0) continue;
|
||||
RAD_TRY(rad_memcpy_async((char*)dev_[r] + reg_[g].off, host_ + reg_[g].off,
|
||||
reg_[g].used, ranks_[r].stream));
|
||||
const int st = rad_memcpy_async((char*)dev_[r] + reg_[g].off, host_ + reg_[g].off,
|
||||
reg_[g].used, ranks_[r].stream);
|
||||
if (st < 0) { fatal_ = st; return st; }
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -858,8 +858,9 @@ int VideoDriver::upload() {
|
||||
for (size_t r = 0; r < ranks_.size(); ++r)
|
||||
for (int g = 0; g < R_N; ++g) {
|
||||
if (reg_[g].used <= 0) continue;
|
||||
RAD_TRY(rad_memcpy_async((char*)dev_[r] + reg_[g].off, host_ + reg_[g].off,
|
||||
reg_[g].used, ranks_[r].stream));
|
||||
const int st = rad_memcpy_async((char*)dev_[r] + reg_[g].off, host_ + reg_[g].off,
|
||||
reg_[g].used, ranks_[r].stream);
|
||||
if (st < 0) { fatal_ = st; return st; }
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
+53
-17
@@ -29,7 +29,15 @@ bool kvstream_op_gated(const RadBuildCtx& ctx, const char* op) {
|
||||
int kvstream_configure(const Config& cfg, int64_t ctx, const std::vector<KVGroupInfo>& groups,
|
||||
const Program& prog, KVStreamSetup* out) {
|
||||
*out = KVStreamSetup{};
|
||||
if (cfg.kv_resident <= 0) return RAD_OK;
|
||||
if (cfg.kv_resident <= 0) {
|
||||
/* The budget sizes a mirror, and with no ring there is none: every group stays a resident
|
||||
* pool sized by the card. */
|
||||
if (cfg.kv_host_tokens > 0)
|
||||
RAD_WARN("--kv-host-tokens %lld ignored: --kv-resident is off, so no KV group streams "
|
||||
"and there is no host mirror to size",
|
||||
(long long)cfg.kv_host_tokens);
|
||||
return RAD_OK;
|
||||
}
|
||||
/* On Flash-Next the group is `kv_attn`. The indexer's `kv_qsa_bkey` is full too, but qsa_score
|
||||
* reads it over the whole history every step, so it is dense-read and stays resident
|
||||
* (docs/KV-STREAMING.md §2). A model with only windowed groups has nothing to stream. */
|
||||
@@ -41,6 +49,7 @@ int kvstream_configure(const Config& cfg, int64_t ctx, const std::vector<KVGroup
|
||||
const KVGroupInfo& gi = groups[(size_t)g];
|
||||
const int64_t bs = gi.block_size > 0 ? gi.block_size : 1;
|
||||
/* A ring that covers the context is not a refusal: the group stays a resident pool. */
|
||||
RAD_TRY(kvstream_host_tokens_check(cfg, ctx));
|
||||
const KVStreamRing shape = kvstream_ring_shape(cfg, ctx, bs);
|
||||
out->asked_tokens = cfg.kv_resident;
|
||||
out->context_tokens = ctx * cfg.max_seqs;
|
||||
@@ -49,7 +58,17 @@ int kvstream_configure(const Config& cfg, int64_t ctx, const std::vector<KVGroup
|
||||
out->ring_tokens = shape.ring_blocks * bs;
|
||||
out->block_size = bs;
|
||||
out->ctx_blocks = shape.ctx_blocks;
|
||||
if (!shape.streams()) return RAD_OK;
|
||||
out->host_tokens = shape.ctx_blocks * bs < out->context_tokens ? shape.ctx_blocks * bs : 0;
|
||||
if (!shape.streams()) {
|
||||
/* A ring that covers the budget but not the context: the group stays a resident pool sized
|
||||
* by the card, and the budget has nothing to size. */
|
||||
if (out->host_tokens > 0)
|
||||
RAD_WARN("--kv-host-tokens %lld ignored: the ring (--kv-resident %lld) covers it, so "
|
||||
"group '%s' does not stream and stays a resident pool sized by the card; a "
|
||||
"budget above the ring streams",
|
||||
(long long)cfg.kv_host_tokens, (long long)cfg.kv_resident, gi.name.c_str());
|
||||
return RAD_OK;
|
||||
}
|
||||
/* Before anything is allocated: the group needs the ops its streamed path issues (KVStreamOps).
|
||||
* The gated attention (rad_block_attn_gated_q.h) and GLM-5.3's MLA block
|
||||
* (rad_block_glm_mla.h) declare both. Without them the flag is ignored and the configuration is
|
||||
@@ -64,11 +83,12 @@ int kvstream_configure(const Config& cfg, int64_t ctx, const std::vector<KVGroup
|
||||
*out = KVStreamSetup{};
|
||||
return RAD_OK;
|
||||
}
|
||||
/* The streamed store has int8, bf16 and E4M3 rows; this refuses a core dtype no architecture
|
||||
* ships a full group in (f32, f16). */
|
||||
if (gi.decl.dtype != RAD_I8 && gi.decl.dtype != RAD_BF16 && gi.decl.dtype != RAD_F8E4M3) {
|
||||
/* The streamed store has int8, rotated int4 / int6, bf16 and E4M3 rows; this refuses a core
|
||||
* dtype no architecture ships a full group in (f32, f16). */
|
||||
if (gi.decl.dtype != RAD_I8 && gi.decl.dtype != RAD_I4R && gi.decl.dtype != RAD_I6R &&
|
||||
gi.decl.dtype != RAD_BF16 && gi.decl.dtype != RAD_F8E4M3) {
|
||||
RAD_ERR("--kv-resident %lld: group '%s' has a %s cache, and the streamed store has int8, "
|
||||
"bf16 and E4M3 rows only; leave --kv-resident off",
|
||||
"rotated int4 / int6, bf16 and E4M3 rows only; leave --kv-resident off",
|
||||
(long long)cfg.kv_resident, out->group_name.c_str(),
|
||||
rad_dtype_name(gi.decl.dtype));
|
||||
return RAD_E_INVAL;
|
||||
@@ -96,14 +116,19 @@ int kvstream_configure(const Config& cfg, int64_t ctx, const std::vector<KVGroup
|
||||
(long long)kStreamFloorTokens, (long long)ring.raised_blocks, (long long)bs);
|
||||
}
|
||||
}
|
||||
/* The raised ring may cover the whole context, which does not stream. */
|
||||
/* The raised ring may cover the whole id space, which does not stream. */
|
||||
if (!ring.streams() && out->host_tokens > 0)
|
||||
RAD_WARN("--kv-host-tokens %lld ignored: the ring raised to %lld tokens covers it, so group "
|
||||
"'%s' does not stream and stays a resident pool sized by the card",
|
||||
(long long)cfg.kv_host_tokens, (long long)(ring.ring_blocks * bs),
|
||||
gi.name.c_str());
|
||||
out->ring_blocks = ring.ring_blocks;
|
||||
out->ring_tokens = ring.ring_blocks * bs;
|
||||
out->raised_tokens = ring.raised_blocks > 0 ? ring.ring_blocks * bs : 0;
|
||||
out->raised_by_union = ring.raised_blocks > 0 && ring.by_union;
|
||||
out->group = ring.streams() ? g : -1;
|
||||
/* Prefill takes the stage and never resolves: above `qsa_exact_to` a launch selects a chunk's
|
||||
* union, which no ring could hold. The stage is the group's context one layer deep, addressed
|
||||
* union, which no ring could hold. The stage is the group's id space one layer deep, addressed
|
||||
* by block id (kvstream/bind.h says which passes take it). */
|
||||
out->stage_blocks = ring.streams() ? ring.ctx_blocks : 0;
|
||||
return RAD_OK;
|
||||
@@ -123,8 +148,9 @@ int kvstream_host_gate(const KVStreamHostUse& use, int n_ranks, int64_t still, i
|
||||
if (lockable_room(use.sum.host_bytes, still, headroom, false, &why)) return RAD_OK;
|
||||
RAD_ERR("kv streaming: the host mirror for %lld streamed KV group(s) needs up to %s of "
|
||||
"pinned host memory a rank (%s over %d ranks), and %s. It holds one full context a "
|
||||
"sequence: lower --max-model-len or --max-num-seqs, or set --kv-resident 0 "
|
||||
"(--host-pool-mib sizes the experts' tier, not this one)",
|
||||
"sequence, or --kv-host-tokens in all: set or lower --kv-host-tokens, lower "
|
||||
"--max-model-len or --max-num-seqs, or set --kv-resident 0 (--host-pool-mib sizes "
|
||||
"the experts' tier, not this one)",
|
||||
(long long)use.sum.groups, humanb(use.max_rank_bytes).c_str(),
|
||||
humanb(use.sum.host_bytes).c_str(), n_ranks, why.c_str());
|
||||
return RAD_E_NOMEM;
|
||||
@@ -151,23 +177,33 @@ void kvstream_report(const KVStreamSetup& s, const KVStreamHostUse& host, int n_
|
||||
(long long)(s.raised_tokens / s.block_size), (long long)s.block_size,
|
||||
s.raised_by_union ? "the blocks one decode step can select"
|
||||
: "the floor below which misses cost more than the ring saves");
|
||||
if (host.sum.groups > 0)
|
||||
if (host.sum.groups > 0) {
|
||||
const std::string holds =
|
||||
s.host_tokens > 0
|
||||
? fmt("%lld tokens shared by every sequence (--kv-host-tokens) of the %lld at "
|
||||
"full length", (long long)s.host_tokens, (long long)s.context_tokens)
|
||||
: fmt("every sequence at full length (%lld tokens)", (long long)s.context_tokens);
|
||||
RAD_INFO("kv streaming: %lld group(s) stream (%s): up to %s of pinned host mirror a "
|
||||
"rank (%s over %d), %s of ring maps in the KV pools",
|
||||
"rank (%s over %d), %s of ring maps in the KV pools; the mirror holds %s",
|
||||
(long long)host.sum.groups, s.group_name.c_str(),
|
||||
humanb(host.max_rank_bytes).c_str(), humanb(host.sum.host_bytes).c_str(), n_ranks,
|
||||
humanb(host.sum.map_bytes).c_str());
|
||||
humanb(host.sum.map_bytes).c_str(), holds.c_str());
|
||||
}
|
||||
if (s.stage_blocks > 0)
|
||||
RAD_INFO("kv streaming: prefill staging, group '%s' ring %lld blocks, one-layer stage %lld "
|
||||
"blocks (one layer of its %lld-block context); decode passes use the ring",
|
||||
s.group_name.c_str(), (long long)s.ring_blocks,
|
||||
(long long)s.stage_blocks, (long long)s.ctx_blocks);
|
||||
if (s.group < 0 && s.asked_tokens > 0 && s.ctx_blocks > 0)
|
||||
if (s.group < 0 && s.asked_tokens > 0 && s.ctx_blocks > 0) {
|
||||
/* The id space the ring covers: the context, or the budget that holds it under that. */
|
||||
const int64_t space = s.host_tokens > 0 ? s.host_tokens : s.context_tokens;
|
||||
RAD_INFO("kv streaming: nothing streams: --kv-resident %lld covers group '%s''s "
|
||||
"%lld-token context (%lld blocks), so the group stays resident; below %lld "
|
||||
"%lld-token %s (%lld blocks), so the group stays resident; below %lld "
|
||||
"tokens it would stream",
|
||||
(long long)flag, s.group_name.c_str(), (long long)s.context_tokens,
|
||||
(long long)s.ctx_blocks, (long long)s.context_tokens);
|
||||
(long long)flag, s.group_name.c_str(), (long long)space,
|
||||
s.host_tokens > 0 ? "budget (--kv-host-tokens)" : "context",
|
||||
(long long)s.ctx_blocks, (long long)space);
|
||||
}
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
+10
-5
@@ -29,6 +29,8 @@ struct KVStreamSetup {
|
||||
int64_t ring_blocks = 0; /* the carved ring, in blocks */
|
||||
int64_t block_size = 0; /* the group's page, in tokens */
|
||||
int64_t ctx_blocks = 0; /* the group's id space, in blocks */
|
||||
int64_t host_tokens = 0; /* the id space in tokens when --kv-host-tokens holds it
|
||||
under context_tokens; 0 when it does not */
|
||||
int64_t stage_blocks = 0; /* the stage view's depth in blocks; 0 when none */
|
||||
};
|
||||
|
||||
@@ -55,7 +57,10 @@ bool kvstream_op_gated(const RadBuildCtx& ctx, const char* op);
|
||||
* - A core dtype other than int8, bf16 or E4M3 is refused: the streamed store has rows for
|
||||
* those only.
|
||||
* - A ring below the decode-step bound or kStreamFloorTokens is raised, with one warning.
|
||||
* --kv-resident itself is left as given; `out` holds both numbers for the report. */
|
||||
* --kv-resident itself is left as given; `out` holds both numbers for the report.
|
||||
* - --kv-host-tokens sizes the id space (kvstream_id_blocks). Below `ctx` plus one step of
|
||||
* --max-num-batched-tokens it is refused; without --kv-resident, or under a ring that covers
|
||||
* it (nothing streams), it is ignored with one warning. */
|
||||
int kvstream_configure(const Config& cfg, int64_t ctx, const std::vector<KVGroupInfo>& groups,
|
||||
const Program& prog, KVStreamSetup* out);
|
||||
|
||||
@@ -63,10 +68,10 @@ int kvstream_configure(const Config& cfg, int64_t ctx, const std::vector<KVGroup
|
||||
void kvstream_host_add(KVStreamHostUse* use, const KVManager& kv);
|
||||
|
||||
/* The host-RAM gate for the mirrors, checked once before any rank pins one. A mirror is one full
|
||||
* context of the group per sequence per rank, the largest host allocation after the experts'
|
||||
* pool, so it is checked against everything still to be pinned after it (`still`). A refusal
|
||||
* names --max-model-len and --max-num-seqs, which size it; --host-pool-mib sizes the experts' pool
|
||||
* and cannot make room here. */
|
||||
* context of the group per sequence per rank (or --kv-host-tokens of it in all), the largest host
|
||||
* allocation after the experts' pool, so it is checked against everything still to be pinned after
|
||||
* it (`still`). A refusal names --kv-host-tokens, --max-model-len and --max-num-seqs, which size
|
||||
* it; --host-pool-mib sizes the experts' pool and cannot make room here. */
|
||||
int kvstream_host_gate(const KVStreamHostUse& use, int n_ranks, int64_t still, int64_t headroom);
|
||||
|
||||
/* After the carve: fill the maps on a bring-up stream and drain it. */
|
||||
|
||||
+17
-9
@@ -25,7 +25,9 @@ int64_t kvstream_dense_charged(const std::vector<KVGroupPlan>& plans, const KVSt
|
||||
int64_t bytes = 0;
|
||||
for (const auto& p : plans) {
|
||||
if (!kvstream_dense(p, plans, st)) continue;
|
||||
bytes += align_up(kv_context_blocks(p.block_size, max_ctx, max_seqs) * p.bytes_per_block,
|
||||
/* The sibling's id space (kvstream_id_blocks): under --kv-host-tokens both run out at the
|
||||
* same token count. */
|
||||
bytes += align_up(st.context_blocks(p, max_ctx, max_seqs) * p.bytes_per_block,
|
||||
RAD_ALIGN_UNIT);
|
||||
}
|
||||
return bytes;
|
||||
@@ -42,10 +44,11 @@ void kvstream_split_windows(const std::vector<KVGroupPlan>& plans, const KVStrea
|
||||
}
|
||||
/* The maps, which the probe cannot reserve yet, or the pool it sizes falls short by them. */
|
||||
*remaining -= kvstream_maps_charged(plans, st, max_ctx, max_seqs);
|
||||
/* A dense-read group's floor is every sequence's context, fixed by the configuration. */
|
||||
/* A dense-read group's floor is the streamed sibling's id space: every sequence's context, or
|
||||
* --kv-host-tokens when that is smaller. Fixed by the configuration. */
|
||||
for (const auto& p : plans) {
|
||||
if (!kvstream_dense(p, plans, st)) continue;
|
||||
const int64_t blocks = kv_context_blocks(p.block_size, max_ctx, max_seqs);
|
||||
const int64_t blocks = st.context_blocks(p, max_ctx, max_seqs);
|
||||
*remaining -= align_up(blocks * p.bytes_per_block, RAD_ALIGN_UNIT);
|
||||
(*out)[p.index] = blocks;
|
||||
}
|
||||
@@ -73,19 +76,23 @@ int kvstream_window_fit(const std::vector<KVGroupPlan>& plans, const KVStreamSto
|
||||
int64_t dense_groups = 0;
|
||||
for (const auto& p : plans) if (kvstream_dense(p, plans, st)) ++dense_groups;
|
||||
if (fixed + window_bytes + map_bytes + dense_bytes > budget) {
|
||||
const std::string dense_at =
|
||||
st.host_tokens() > 0 && st.host_tokens() < max_seqs * max_ctx
|
||||
? fmt("--kv-host-tokens %lld", (long long)st.host_tokens())
|
||||
: fmt("%lld sequences x %lld tokens", (long long)max_seqs, (long long)max_ctx);
|
||||
RAD_ERR("the resident KV windows and dense-read groups do not fit vram_kv:\n"
|
||||
" resident windows %10s (%lld group(s) streaming)\n"
|
||||
" ring maps %10s (the streamed groups' residency maps)\n"
|
||||
" dense-read groups %10s (%lld group(s) at %lld sequences x %lld tokens)\n"
|
||||
" dense-read groups %10s (%lld group(s) at %s)\n"
|
||||
" linear/conv state %10s (%lld sequences)\n"
|
||||
" vram_kv %10s\n"
|
||||
" short by %10s\n"
|
||||
"Lower --kv-resident (the ring) or --max-model-len / --max-num-seqs (the one-layer "
|
||||
"stage and the dense-read floor), or give the cache more of the card: a smaller "
|
||||
"--gpu-headroom-mib or a larger --host-pool-mib.",
|
||||
"Lower --kv-resident (the ring) or --kv-host-tokens / --max-model-len / "
|
||||
"--max-num-seqs (the one-layer stage and the dense-read floor), or give the cache "
|
||||
"more of the card: a smaller --gpu-headroom-mib or a larger --host-pool-mib.",
|
||||
humanb(window_bytes).c_str(), (long long)window_groups,
|
||||
humanb(map_bytes).c_str(), humanb(dense_bytes).c_str(), (long long)dense_groups,
|
||||
(long long)max_seqs, (long long)max_ctx, humanb(fixed).c_str(),
|
||||
dense_at.c_str(), humanb(fixed).c_str(),
|
||||
(long long)max_seqs, humanb(budget).c_str(),
|
||||
humanb(fixed + window_bytes + map_bytes + dense_bytes - budget).c_str());
|
||||
return RAD_E_NOMEM;
|
||||
@@ -98,7 +105,8 @@ int kvstream_apply(std::vector<KVGroupPlan>& plans, const KVStreamStore& st,
|
||||
for (auto& p : plans) {
|
||||
if (!p.paged()) continue;
|
||||
if (st.windowed(p.index) && !p.zero) {
|
||||
/* The split gave a streamed group its window; its ids run over its context. */
|
||||
/* The split gave a streamed group its window; its ids run over its context, or over
|
||||
* --kv-host-tokens when that is smaller. */
|
||||
p.n_blocks = st.context_blocks(p, max_ctx, max_seqs);
|
||||
p.n_slots = st.resident_blocks(p);
|
||||
/* A ring that covers the context never reaches here (kvstream_ring), so the group has a
|
||||
|
||||
@@ -64,7 +64,7 @@ int64_t KVStreamStore::resident_blocks(const KVGroupPlan& p) const {
|
||||
|
||||
int64_t KVStreamStore::context_blocks(const KVGroupPlan& p, int64_t max_ctx,
|
||||
int64_t max_seqs) const {
|
||||
return kv_context_blocks(p.block_size, max_ctx, max_seqs);
|
||||
return kvstream_id_blocks(p.block_size, max_ctx, max_seqs, host_tokens_);
|
||||
}
|
||||
|
||||
void KVStreamStore::set_map(int32_t group, const Map& m) {
|
||||
|
||||
+11
-2
@@ -56,10 +56,18 @@ public:
|
||||
/* The window in whole blocks; at least one, since a pool that holds nothing cannot run. */
|
||||
int64_t resident_blocks(const KVGroupPlan& p) const;
|
||||
|
||||
/* Blocks the group's context addresses (kv_context_blocks). The block table is already pitched
|
||||
* for them, whether the pool backs them or not. */
|
||||
/* Blocks the group's ids run over (kvstream_id_blocks): its context, or the host token budget
|
||||
* when that is smaller. A block table is pitched for one sequence's context whatever this is;
|
||||
* the ids it names are below it. Also the dense-read floor of a streamed group's sibling
|
||||
* (kvstream/carve.h), so both run out at the same token count. */
|
||||
int64_t context_blocks(const KVGroupPlan& p, int64_t max_ctx, int64_t max_seqs) const;
|
||||
|
||||
/* --kv-host-tokens: the tokens every sequence together keeps in the streamed groups' mirrors
|
||||
* (and in the dense-read floor beside them); 0, the default, is every sequence at full length.
|
||||
* Set by KVManager::plan_groups. */
|
||||
void set_host_tokens(int64_t tokens) { host_tokens_ = tokens > 0 ? tokens : 0; }
|
||||
int64_t host_tokens() const { return host_tokens_; }
|
||||
|
||||
void set_map(int32_t group, const Map& m);
|
||||
const Map* map(int32_t group) const;
|
||||
|
||||
@@ -96,6 +104,7 @@ public:
|
||||
|
||||
private:
|
||||
std::vector<int64_t> resident_tokens_; /* by group handle: its pool's depth in tokens */
|
||||
int64_t host_tokens_ = 0; /* set_host_tokens(); 0 is no budget */
|
||||
std::vector<Map> maps_; /* set_map(), by group handle */
|
||||
std::atomic<uint64_t> misses_{0}; /* note_traffic() */
|
||||
std::atomic<uint64_t> bytes_in_{0};
|
||||
|
||||
+20
-1
@@ -124,7 +124,9 @@ KVStreamOps kvstream_ops(const Program& prog, const KVGroupInfo* group) {
|
||||
KVStreamRing kvstream_ring_shape(const Config& cfg, int64_t ctx, int64_t block_size) {
|
||||
KVStreamRing out;
|
||||
const int64_t bs = block_size > 0 ? block_size : 1;
|
||||
out.ctx_blocks = kv_context_blocks(bs, ctx, cfg.max_seqs);
|
||||
/* The id space, under --kv-host-tokens when given: the floor and the covering test below are
|
||||
* against what the mirror holds, not against every sequence at full length. */
|
||||
out.ctx_blocks = kvstream_id_blocks(bs, ctx, cfg.max_seqs, cfg.kv_host_tokens);
|
||||
out.ring_blocks = cfg.kv_resident > 0 ? (cfg.kv_resident + bs - 1) / bs : 0;
|
||||
/* The floor, at most the context: a context under it streams nothing. */
|
||||
if (out.ring_blocks > 0) {
|
||||
@@ -163,9 +165,26 @@ int64_t kvstream_prefix_host_off(Config& cfg) {
|
||||
return was;
|
||||
}
|
||||
|
||||
int kvstream_host_tokens_check(const Config& cfg, int64_t ctx) {
|
||||
if (cfg.kv_resident <= 0 || cfg.kv_host_tokens <= 0) return RAD_OK;
|
||||
const int64_t step = cfg.max_tok > 0 ? cfg.max_tok : 1;
|
||||
/* At or above every sequence's context the budget is the context (kvstream_id_blocks). */
|
||||
const int64_t seqs = cfg.max_seqs > 0 ? cfg.max_seqs : 1;
|
||||
if (cfg.kv_host_tokens >= ctx + step || cfg.kv_host_tokens >= seqs * ctx) return RAD_OK;
|
||||
RAD_ERR("--kv-host-tokens %lld is below one --max-model-len %lld conversation plus one step of "
|
||||
"--max-num-batched-tokens %lld (%lld tokens): the budget every sequence shares must "
|
||||
"hold the longest one beside a step of another. Raise it, or lower --max-model-len",
|
||||
(long long)cfg.kv_host_tokens, (long long)ctx, (long long)step,
|
||||
(long long)(ctx + step));
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
int kvstream_cap_probe(KVManager& probe, Config& cfg, const Program& prog, int64_t ctx) {
|
||||
cfg.kv_streams = false;
|
||||
if (cfg.kv_resident <= 0) return RAD_OK;
|
||||
/* Before the budget is sized from it: a refusal here names the flag, where a pool sized for
|
||||
* a budget under one conversation would be refused later for the wrong reason. */
|
||||
RAD_TRY(kvstream_host_tokens_check(cfg, ctx));
|
||||
const int32_t g = kv_stream_group(probe, &prog);
|
||||
if (g < 0) return RAD_OK;
|
||||
const KVGroupPlan* p = probe.plan(g);
|
||||
|
||||
+21
-2
@@ -33,6 +33,18 @@ inline int64_t kv_context_blocks(int64_t block_size, int64_t max_ctx, int64_t ma
|
||||
return seqs * ((ctx + block_size - 1) / block_size);
|
||||
}
|
||||
|
||||
/* The streamed group's block-id space: its context (kv_context_blocks), or `host_tokens` in whole
|
||||
* blocks when that is smaller (--kv-host-tokens). The budget is shared by every sequence, so the
|
||||
* host mirror, the residency maps, the stage and the dense-read floor beside it are sized for the
|
||||
* tokens the server keeps, not for every sequence at full length. 0 is no budget: the context. */
|
||||
inline int64_t kvstream_id_blocks(int64_t block_size, int64_t max_ctx, int64_t max_seqs,
|
||||
int64_t host_tokens) {
|
||||
const int64_t ctx = kv_context_blocks(block_size, max_ctx, max_seqs);
|
||||
if (host_tokens <= 0 || block_size <= 0) return ctx;
|
||||
const int64_t budget = (host_tokens + block_size - 1) / block_size;
|
||||
return budget < ctx ? budget : ctx;
|
||||
}
|
||||
|
||||
/* The group's one allocation: max(ring, stage) for `slots` resident blocks of `context_blocks`.
|
||||
* `slots >= context_blocks` is a group that does not stream: `slots` blocks of every layer. The
|
||||
* one-argument form is the carved plan's. A stateful group is its states. */
|
||||
@@ -58,8 +70,10 @@ struct KVStreamRing {
|
||||
int64_t raised_blocks = 0; /* the depth a floor raised the flag to; 0 when not raised */
|
||||
int64_t floor_blocks = 0; /* kStreamFloorTokens in blocks, at most the context */
|
||||
bool by_union = false; /* the raise was the decode-step bound, not kStreamFloorTokens */
|
||||
int64_t ctx_blocks = 0; /* max_seqs x ceil(ctx / block_size): the group's context */
|
||||
/* A ring that covers the context does not stream: the group keeps the resident path, with no
|
||||
/* The group's id space: max_seqs x ceil(ctx / block_size), or --kv-host-tokens in blocks when
|
||||
* that is smaller (kvstream_id_blocks). */
|
||||
int64_t ctx_blocks = 0;
|
||||
/* A ring that covers the id space does not stream: the group keeps the resident path, with no
|
||||
* mirror, maps, stage or resolve, and a null RadKVStream. */
|
||||
bool streams() const { return ring_blocks > 0 && ring_blocks < ctx_blocks; }
|
||||
};
|
||||
@@ -112,6 +126,11 @@ void kvstream_ring(const Config& cfg, int64_t ctx, int64_t block_size, int64_t s
|
||||
* kvstream_cap_probe, before anything is sized from --prefix-cache-mib. */
|
||||
int64_t kvstream_prefix_host_off(Config& cfg);
|
||||
|
||||
/* Refuse --kv-host-tokens under one `ctx`-token conversation plus one step of
|
||||
* --max-num-batched-tokens: the budget every sequence shares must hold the longest one beside a
|
||||
* step of another. RAD_OK when the budget or --kv-resident is off. */
|
||||
int kvstream_host_tokens_check(const Config& cfg, int64_t ctx);
|
||||
|
||||
/* Teach the budget probe the streamed plan (the ring from --kv-resident, the stage from the
|
||||
* context) before probe.ceiling(ctx), and set `cfg.kv_streams` when a group streams. A model with
|
||||
* no streamed path is left exactly as without the flag. */
|
||||
|
||||
@@ -234,8 +234,7 @@ bool stage_src(Ctx* ctx, int group, const RadKVGroupBatch* kvb, int layer, Stage
|
||||
|
||||
/* Whether the card has the DMA queue the pipelined path needs. */
|
||||
bool dma_stage(Ctx* c) {
|
||||
static const bool on = rad_xp_supported(c->device()) != 0;
|
||||
return on;
|
||||
return rad_xp_supported(c->device()) != 0;
|
||||
}
|
||||
|
||||
/* The one list in flight per rank thread: the layer it fills and the ride it waits on. */
|
||||
@@ -245,6 +244,10 @@ struct StagePipe {
|
||||
int group = -1;
|
||||
void* mark = nullptr;
|
||||
int64_t bytes = 0; /* what that list was told to move, for the pass's counter */
|
||||
~StagePipe() {
|
||||
if (mark) rad_ride_release(mark, nullptr, 0);
|
||||
if (done) rad_event_destroy(done);
|
||||
}
|
||||
};
|
||||
thread_local StagePipe g_pipe;
|
||||
/* The layer's ranges, rebuilt for each list: rad_xp_list writes them into its ring at once. */
|
||||
|
||||
+15
-3
@@ -106,6 +106,10 @@ int KVManager::plan_groups(const std::vector<KVGroupInfo>& groups, const Config&
|
||||
max_seqs_ = cfg.max_seqs > 0 ? cfg.max_seqs : 1;
|
||||
max_ctx_ = cfg.max_ctx > 0 ? cfg.max_ctx : 0;
|
||||
max_tok_ = cfg.max_tok > 0 ? cfg.max_tok : 0;
|
||||
/* --kv-host-tokens: the streamed groups' id space (and the dense-read floor beside them) is
|
||||
* this many tokens shared by every sequence, not max_seqs full contexts. Inert unless a group
|
||||
* is capped to a ring (cap_resident_tokens). */
|
||||
stream_.set_host_tokens(cfg.kv_host_tokens);
|
||||
|
||||
if (groups.empty()) {
|
||||
RAD_ERR("KV manager: no KV groups were declared; the architecture plugin declares at "
|
||||
@@ -335,6 +339,10 @@ int64_t KVManager::ceiling(int64_t ctx) const {
|
||||
int64_t blocks = max_seqs_ * ((ctx + p.block_size - 1) / p.block_size);
|
||||
if (p.kind == RAD_KV_WINDOW && !p.runtime_win && p.window_blocks > 0)
|
||||
blocks = std::min(blocks, window_pool_cap(p));
|
||||
/* A streamed group and the dense-read floor beside it address their id space, which
|
||||
* --kv-host-tokens may hold under every sequence's context (kvstream_id_blocks). */
|
||||
if (stream_.windowed(p.index) || kvstream_dense(p, plans_, stream_))
|
||||
blocks = std::min(blocks, stream_.context_blocks(p, ctx, max_seqs_));
|
||||
need += kv_ceiling_bytes(p, blocks, stream_.resident_blocks(p));
|
||||
}
|
||||
/* The streamed groups' maps come out of this pool too (kvstream/carve.h). */
|
||||
@@ -494,8 +502,12 @@ int64_t KVManager::paged_split(int64_t budget_bytes, std::vector<int64_t>* block
|
||||
for (int32_t i : open) out[i] = remaining > 0 ? tokens / plans_[i].block_size : 0;
|
||||
for (int32_t i : zeros) out[i] = remaining > 0 ? zero_blocks(plans_[i], tokens) : 0;
|
||||
/* A dense-read group's floor is already charged; with no other open group the pool still pages
|
||||
* one full-length sequence, which is what the report and the admission cap see. */
|
||||
if (dense && open.empty() && remaining > 0) tokens = max_ctx_;
|
||||
* one full-length sequence, which is what the report and the admission cap see, or under
|
||||
* --kv-host-tokens the budget every sequence shares, which the floor was sized for. */
|
||||
if (dense && open.empty() && remaining > 0) {
|
||||
const int64_t host = stream_.host_tokens();
|
||||
tokens = host > 0 && max_ctx_ > 0 ? std::min(host, max_seqs_ * max_ctx_) : max_ctx_;
|
||||
}
|
||||
if (blocks) *blocks = std::move(out);
|
||||
return tokens;
|
||||
}
|
||||
@@ -703,7 +715,7 @@ int KVManager::carve_into(Pool& kv_pool) {
|
||||
const int rc = pool_->commit(stage_off_, stage_bytes_);
|
||||
if (rc < 0) return rc;
|
||||
}
|
||||
if (const int rc = flex_span(flex_floor_loan_, carved + 1, true); rc < 0) {
|
||||
if (const int rc = flex_span(flex_floor_loan_, INT64_MAX, true); rc < 0) {
|
||||
RAD_ERR("KV pool: the card would not back the cache's floor of %s",
|
||||
humanb(flex_backed_).c_str());
|
||||
return rc;
|
||||
|
||||
@@ -163,6 +163,13 @@ void IdleTiers::note_used(const BlockHash& key, const std::vector<int32_t>& bloc
|
||||
if (!host_on()) return;
|
||||
std::lock_guard lk(mu_);
|
||||
Rec& r = recs_[key];
|
||||
if (r.pending && r.doomed) {
|
||||
r.reborn = true;
|
||||
r.reborn_blocks = blocks;
|
||||
r.reborn_ns = now_ns;
|
||||
r.reborn_depth = depth;
|
||||
return;
|
||||
}
|
||||
if (r.tier == KVTier::Device && !r.pending) r.blocks = blocks;
|
||||
/* Before touch, which files a host record under it. */
|
||||
r.depth = depth;
|
||||
@@ -228,6 +235,8 @@ void IdleTiers::forget(const BlockHash& key) {
|
||||
if (r.pending) {
|
||||
/* Mid-transfer: erasing now would be a use-after-free. report() cleans up. */
|
||||
r.doomed = true;
|
||||
r.reborn = false;
|
||||
r.reborn_blocks.clear();
|
||||
return;
|
||||
}
|
||||
unlist(r);
|
||||
@@ -480,6 +489,17 @@ void IdleTiers::report(const TierJob& job, bool ok, uint64_t now_ns) {
|
||||
* until it reports. Free each distinct slot once. */
|
||||
if (job.host_slot >= 0 && job.host_slot != r.host_slot) give_slot(job.host_slot);
|
||||
free_host(r);
|
||||
if (r.reborn) {
|
||||
r.doomed = false;
|
||||
r.reborn = false;
|
||||
r.tier = KVTier::Device;
|
||||
r.blocks = std::move(r.reborn_blocks);
|
||||
r.reborn_blocks.clear();
|
||||
r.depth = r.reborn_depth;
|
||||
touch(job.key, r, r.reborn_ns);
|
||||
queue_copy(job.key, r);
|
||||
return;
|
||||
}
|
||||
recs_.erase(it);
|
||||
return;
|
||||
}
|
||||
@@ -652,6 +672,12 @@ void IdleTiers::find_sessions(const std::string& label, uint64_t id,
|
||||
}
|
||||
}
|
||||
|
||||
void IdleTiers::for_each_session(
|
||||
const std::function<void(uint64_t, const std::vector<BlockHash>&)>& f) const {
|
||||
std::lock_guard lk(mu_);
|
||||
for (const auto& kv : sessions_) f(kv.first, kv.second.chain);
|
||||
}
|
||||
|
||||
int64_t IdleTiers::shared_prefix_blocks(const std::vector<BlockHash>& chain,
|
||||
const std::vector<uint64_t>& except) const {
|
||||
if (chain.empty()) return 0;
|
||||
|
||||
@@ -268,6 +268,9 @@ public:
|
||||
* served); a release by label means all of them. */
|
||||
void find_sessions(const std::string& label, uint64_t id,
|
||||
std::vector<SessionChain>* out) const;
|
||||
/* Calls `f` with every row's id and chain under the tiers' lock, copying nothing
|
||||
* (PrefixCache::sweep_dead). `f` must not call back into the tiers. */
|
||||
void for_each_session(const std::function<void(uint64_t, const std::vector<BlockHash>&)>& f) const;
|
||||
/* How many blocks at the start of `chain` another stored session walks too: the longest
|
||||
* common prefix with any row at the same root whose id is not in `except`. Those blocks
|
||||
* belong to the other conversation as much as to this one. */
|
||||
@@ -323,10 +326,14 @@ private:
|
||||
int32_t host_slot = -1;
|
||||
bool pending = false;
|
||||
bool doomed = false; /* forget() arrived while pending */
|
||||
bool reborn = false; /* note_used() arrived while pending && doomed */
|
||||
bool queued = false; /* in wb_q_: waiting for a copy */
|
||||
bool clean_q = false; /* in clean_q_: a drop the cache has not been asked about */
|
||||
bool listed = false; /* on host_lru_; `it` is valid */
|
||||
std::vector<int32_t> blocks;
|
||||
std::vector<int32_t> reborn_blocks;
|
||||
uint64_t reborn_ns = 0;
|
||||
int64_t reborn_depth = 0;
|
||||
/* ---- the linear half ----
|
||||
* Snapshot store slot and token position, for the session view. `ck_slot` is -1 for most
|
||||
* records: one block in (interval / block_size) is a checkpoint position. */
|
||||
|
||||
+129
-1
@@ -675,7 +675,118 @@ void PrefixCache::drop_offdevice(const BlockHash& key) {
|
||||
++stats_.evictions;
|
||||
/* A snapshot under the same key stays: no lookup reaches it past the missing block, and
|
||||
* retention or expiry retires it via retire_ckpt. It cannot be retired here because the tiers
|
||||
* call this holding their lock. */
|
||||
* call this holding their lock; sweep_dead retires it at the next step. */
|
||||
dead_pending_ = true;
|
||||
}
|
||||
|
||||
void PrefixCache::begin_step() {
|
||||
handed_.clear();
|
||||
reserved_.clear();
|
||||
/* At most every 100 ms: a sweep walks every session's chain. */
|
||||
if (dead_pending_) {
|
||||
const uint64_t now = rad_mono_ns();
|
||||
if (now - dead_swept_ns_ >= 100000000ull) {
|
||||
dead_swept_ns_ = now;
|
||||
(void)sweep_dead();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int64_t PrefixCache::sweep_dead() {
|
||||
dead_pending_ = false;
|
||||
if (!enabled_ || !has_linear_ || !tiers_ || block_size_ <= 0) return 0;
|
||||
/* Rows are kept until they expire (--prefix-cache-ttl) or are released, so a long-running
|
||||
* server holds many, most of them sound. A sound row ends on a block the cache holds with a
|
||||
* valid snapshot right there: nothing past its snapshot to give up, decided in constant time
|
||||
* and without copying the chain. The rest are looked at one by one below, and a row cleaned
|
||||
* is cut to what it can resume from, so the next sweep finds it sound. A row whose end is
|
||||
* held but a block inside it is not is passed over: that only leaves it uncleaned. */
|
||||
auto sound = [&](const std::vector<BlockHash>& c) {
|
||||
const BlockHash& tip = c.back();
|
||||
if (!map_.count(tip)) return false;
|
||||
auto ck = ck_by_prefix_.find(tip);
|
||||
return ck != ck_by_prefix_.end() && ck->second.valid &&
|
||||
ck->second.pos == (int64_t)c.size() * block_size_;
|
||||
};
|
||||
std::vector<uint64_t> suspects;
|
||||
tiers_->for_each_session([&](uint64_t id, const std::vector<BlockHash>& c) {
|
||||
if (!c.empty() && !sound(c)) suspects.push_back(id);
|
||||
});
|
||||
|
||||
int64_t gone = 0, ck_gone = 0;
|
||||
std::vector<IdleTiers::SessionChain> rows;
|
||||
for (uint64_t id : suspects) {
|
||||
tiers_->find_sessions(std::string(), id, &rows);
|
||||
if (rows.empty()) continue;
|
||||
const IdleTiers::SessionChain& row = rows[0];
|
||||
const int64_t n = (int64_t)row.chain.size();
|
||||
if (n == 0) continue;
|
||||
/* How far a lookup reaches: the first block the cache no longer holds in any tier. */
|
||||
int64_t reach = 0;
|
||||
while (reach < n && map_.count(row.chain[(size_t)reach])) ++reach;
|
||||
/* Snapshots past it are unreachable: retire them (their slot serves another session). */
|
||||
for (auto pit = ck_positions_.upper_bound(reach * block_size_); pit != ck_positions_.end();) {
|
||||
const int64_t pos = pit->first;
|
||||
++pit; /* retire_ckpt may erase the position */
|
||||
if (pos <= 0 || pos % block_size_ != 0 || pos / block_size_ > n) continue;
|
||||
const BlockHash& h = row.chain[(size_t)(pos / block_size_ - 1)];
|
||||
auto ck = ck_by_prefix_.find(h);
|
||||
/* Not one still being written, nor one a live sequence made: a request mid-prefill
|
||||
* snapshots past what it has published, and reaches it with its own blocks. */
|
||||
if (ck == ck_by_prefix_.end() || ck->second.pos != pos || !ck->second.valid ||
|
||||
handed(h) || reserved(h) || kv_->has_sequence(ck->second.session))
|
||||
continue;
|
||||
const uint64_t session = ck->second.session;
|
||||
retire_ckpt(ck);
|
||||
unindex_ckpt(session, h);
|
||||
++ck_gone;
|
||||
}
|
||||
/* The deepest snapshot a hit can resume from, at or below the reach. */
|
||||
int64_t resume = 0;
|
||||
for (auto pit = ck_positions_.upper_bound(reach * block_size_); pit != ck_positions_.begin();) {
|
||||
--pit;
|
||||
const int64_t pos = pit->first;
|
||||
if (pos <= 0 || pos % block_size_ != 0) continue;
|
||||
auto ck = ck_by_prefix_.find(row.chain[(size_t)(pos / block_size_ - 1)]);
|
||||
if (ck != ck_by_prefix_.end() && ck->second.pos == pos && ck->second.valid) {
|
||||
resume = pos / block_size_;
|
||||
break;
|
||||
}
|
||||
}
|
||||
/* Blocks [resume, reach) are cached and unusable, but a prefix another session walks is
|
||||
* that session's too: it may hold a snapshot of its own deeper in it. */
|
||||
int64_t kept = reach; /* blocks [0, kept) of the row are what is left of it */
|
||||
if (resume < reach) {
|
||||
const int64_t shared = tiers_->shared_prefix_blocks(row.chain, { row.id });
|
||||
for (int64_t b = reach - 1; b >= std::max(resume, shared); --b) {
|
||||
const BlockHash& h = row.chain[(size_t)b];
|
||||
auto it = map_.find(h);
|
||||
if (it == map_.end()) { kept = b; continue; }
|
||||
Entry& e = it->second;
|
||||
if (e.in_lru && (shared_with_live(e) || held_.count(h) > 0)) break;
|
||||
if (e.in_lru) {
|
||||
lru_.erase(e.lru);
|
||||
e.in_lru = false;
|
||||
release_blocks(e);
|
||||
}
|
||||
tiers_->forget(h);
|
||||
map_.erase(it);
|
||||
kept = b;
|
||||
++gone;
|
||||
}
|
||||
}
|
||||
/* Cut the row to what it can still resume from, so the next sweep finds it sound. Not
|
||||
* when something live stopped the walk above it, nor to nothing: a row with no snapshot
|
||||
* left still says, in the session view, that its conversation will restart. */
|
||||
if (kept == resume && resume > 0 && resume < n)
|
||||
tiers_->cut_session(row.id, resume, resume * block_size_);
|
||||
}
|
||||
stats_.dead += gone;
|
||||
stats_.ckpt_dead += ck_gone;
|
||||
if (gone || ck_gone)
|
||||
RAD_DEBUG("prefix cache: %lld entr%s and %lld snapshot(s) nothing could hit given up",
|
||||
(long long)gone, gone == 1 ? "y" : "ies", (long long)ck_gone);
|
||||
return gone;
|
||||
}
|
||||
|
||||
int PrefixCache::rebind(const BlockHash& key, const std::vector<int32_t>& blocks) {
|
||||
@@ -750,6 +861,7 @@ int64_t PrefixCache::evict_lru(int64_t n) {
|
||||
map_.erase(it);
|
||||
++done;
|
||||
++stats_.evictions;
|
||||
dead_pending_ = true;
|
||||
}
|
||||
return done;
|
||||
}
|
||||
@@ -790,6 +902,7 @@ int64_t PrefixCache::trim_sparing(int64_t n_entries,
|
||||
if (tiers_) tiers_->forget(h);
|
||||
map_.erase(m);
|
||||
++stats_.evictions;
|
||||
dead_pending_ = true;
|
||||
}
|
||||
++done;
|
||||
}
|
||||
@@ -876,6 +989,7 @@ int64_t PrefixCache::drop_stragglers(int64_t loan_goal, bool recheck) {
|
||||
tiers_->forget(h);
|
||||
map_.erase(m);
|
||||
++stats_.evictions;
|
||||
dead_pending_ = true;
|
||||
++n;
|
||||
}
|
||||
return n;
|
||||
@@ -898,6 +1012,20 @@ void PrefixCache::clear() {
|
||||
map_.clear();
|
||||
lru_.clear();
|
||||
drop_wait_.clear();
|
||||
|
||||
std::vector<std::pair<uint64_t, BlockHash>> ckpts;
|
||||
ckpts.reserve(ck_by_prefix_.size());
|
||||
for (const auto& kvp : ck_by_prefix_) {
|
||||
if (handed(kvp.first) || reserved(kvp.first)) continue;
|
||||
ckpts.emplace_back(kvp.second.session, kvp.first);
|
||||
}
|
||||
for (const auto& [sess, h] : ckpts) {
|
||||
auto it = ck_by_prefix_.find(h);
|
||||
if (it == ck_by_prefix_.end()) continue;
|
||||
retire_ckpt(it);
|
||||
++stats_.ckpt_evictions;
|
||||
unindex_ckpt(sess, h);
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<BlockHash> PrefixCache::lru_order() const {
|
||||
|
||||
+17
-1
@@ -390,7 +390,17 @@ public:
|
||||
* read by its forward by now, and the ones it reserved have been saved into (the engine
|
||||
* issues the save before the next step is planned); until this call they keep their slots
|
||||
* against retention, reserve_checkpoint's eviction and expiry. */
|
||||
void begin_step() { handed_.clear(); reserved_.clear(); }
|
||||
void begin_step();
|
||||
/* On a model whose hit resumes from a snapshot (has_linear_), a conversation is usable only
|
||||
* up to its deepest snapshot at or below the first block the cache lost. Eviction takes a
|
||||
* conversation's end first, and a lost end leaves the rest of it cached yet unusable: under
|
||||
* tip-only retention all of it. Two LRUs that do not know of each other (blocks, snapshot
|
||||
* slots) then hold dead data while live conversations are evicted. Once a block was lost for
|
||||
* good (evict_lru with no host copy, the host tier giving one up), this walks every session's
|
||||
* chain and gives up what nothing can hit: entries past the deepest reachable snapshot, down
|
||||
* to what another session shares, and snapshots past the first lost block. Entries a live
|
||||
* sequence or a waiting request holds stay. Returns the entries given up. */
|
||||
int64_t sweep_dead();
|
||||
|
||||
/* ---------------- expiry ----------------
|
||||
*
|
||||
@@ -461,6 +471,9 @@ public:
|
||||
int64_t expired = 0, ckpt_expired = 0;
|
||||
/* Entries and snapshots a client released (release_session). */
|
||||
int64_t released = 0, ckpt_released = 0;
|
||||
/* Entries and snapshots sweep_dead gave up: cached KV past the deepest snapshot a lookup
|
||||
* can still reach, and snapshots past a block the cache lost. Nothing could hit them. */
|
||||
int64_t dead = 0, ckpt_dead = 0;
|
||||
};
|
||||
const Stats& stats() const { return stats_; }
|
||||
|
||||
@@ -539,6 +552,9 @@ private:
|
||||
|
||||
KVManager* kv_ = nullptr;
|
||||
IdleTiers* tiers_ = nullptr;
|
||||
/* A block was lost for good since the last sweep (sweep_dead), and when the last ran. */
|
||||
bool dead_pending_ = false;
|
||||
uint64_t dead_swept_ns_ = 0;
|
||||
bool enabled_ = false;
|
||||
int64_t block_size_ = 0;
|
||||
int64_t interval_ = 0;
|
||||
|
||||
+130
-22
@@ -25,6 +25,14 @@ int64_t to_mib_up(int64_t bytes) { return bytes > 0 ? (bytes + kMiB - 1) / kMiB
|
||||
constexpr int64_t kDriverDrift = 16 * kMiB;
|
||||
} /* namespace */
|
||||
|
||||
/* One buffer of the prefill staging ring: a layer's share of the experts left off the card
|
||||
* (`off` of `experts`), the most one step can see, RAD_ALIGN_UNIT-aligned. */
|
||||
static int64_t stage_buffer(int64_t off, int64_t experts, int64_t layer_max) {
|
||||
const double f = (double)off / (double)experts;
|
||||
return ((int64_t)std::ceil(f * (double)layer_max) + RAD_ALIGN_UNIT - 1) / RAD_ALIGN_UNIT *
|
||||
RAD_ALIGN_UNIT;
|
||||
}
|
||||
|
||||
/* The fraction of the paged (context) part of the ceiling the cache backs. The ceiling also
|
||||
* includes fixed recurrent and conv state (gigabytes per card on a hybrid model), which a ratio
|
||||
* over the whole ceiling would wrongly count as context. */
|
||||
@@ -58,6 +66,24 @@ int64_t vram_budget_rank_spare_mib(const Config& cfg, const std::vector<VramFact
|
||||
return std::max<int64_t>((rank_room(cfg, per_rank[rank], rank) - least) / kMiB, 0);
|
||||
}
|
||||
|
||||
/* The full-length sessions the ceiling prices: --max-num-seqs, or under a streamed
|
||||
* --kv-host-tokens the sessions that budget holds (kvstream_id_blocks sizes the streamed group and
|
||||
* its dense-read sibling for it, so the ceiling is the budget, not every sequence). */
|
||||
static bool ceiling_budgeted(const Config& cfg) {
|
||||
return cfg.kv_streams && cfg.kv_host_tokens > 0 && cfg.max_ctx > 0 &&
|
||||
cfg.kv_host_tokens < cfg.max_seqs * cfg.max_ctx;
|
||||
}
|
||||
static std::string ceiling_case(const Config& cfg) {
|
||||
if (ceiling_budgeted(cfg))
|
||||
return fmt("--kv-host-tokens %lld shared by %lld sequences of up to %lld tokens",
|
||||
(long long)cfg.kv_host_tokens, (long long)cfg.max_seqs, (long long)cfg.max_ctx);
|
||||
return fmt("%lld sequences all at %lld tokens", (long long)cfg.max_seqs, (long long)cfg.max_ctx);
|
||||
}
|
||||
static double ceiling_sessions(const Config& cfg) {
|
||||
if (ceiling_budgeted(cfg)) return (double)cfg.kv_host_tokens / (double)cfg.max_ctx;
|
||||
return (double)cfg.max_seqs;
|
||||
}
|
||||
|
||||
/* The resolver. `log` is false for vram_budget_trial, whose split may never be used, so its
|
||||
* refusals must not print as startup failures. */
|
||||
static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudget* out, bool log) {
|
||||
@@ -92,6 +118,15 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
}
|
||||
b.lends = true;
|
||||
for (const VramFacts& f : per_rank) b.lends = b.lends && f.lends;
|
||||
/* Ranks whose program-derived terms differ: an attention-zero rank, an uneven expert split.
|
||||
* Measured terms (free VRAM, a queue's bytes) are left out, so equal ranks stay equal. */
|
||||
bool uneven = false;
|
||||
for (const VramFacts& f : per_rank) {
|
||||
const VramFacts& g = per_rank[0];
|
||||
uneven = uneven || f.experts != g.experts || f.expert_layer_max != g.expert_layer_max ||
|
||||
f.expert_floor != g.expert_floor || f.statics != g.statics ||
|
||||
f.kv_ceiling != g.kv_ceiling || f.arena != g.arena;
|
||||
}
|
||||
/* One RAM ledger on a unified-memory device: the pinned host pools come off the same
|
||||
* bytes as the device pools. Every rank must agree the device is unified for the
|
||||
* charge to apply (the ranks share the host on one node). */
|
||||
@@ -292,13 +327,19 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
* the residency.
|
||||
*
|
||||
* The share is what the slab alone leaves off, the most a step can see: KV and arena loans only
|
||||
* add residency. A layer larger than its share stages what fits and streams the rest. */
|
||||
* add residency. A layer larger than its share stages what fits and streams the rest.
|
||||
*
|
||||
* An uneven world under expert_tiered sizes it per rank instead (VramBudget::stage_per_rank):
|
||||
* the floor here is the dearest rank's against an even share of a host pool that is then
|
||||
* re-split by overflow, so it would refuse every rank the ring, and a rank whose experts are
|
||||
* all resident would be charged one it never fills. */
|
||||
bool stage_from_experts = false;
|
||||
if (layer_max > 0 && b.expert_ceiling > b.experts && cfg.placement != "all_vram" &&
|
||||
cfg.placement != "layer_offload") {
|
||||
const double f = (double)(b.expert_ceiling - b.experts) / (double)b.expert_ceiling;
|
||||
const int64_t one = ((int64_t)std::ceil(f * (double)layer_max) + RAD_ALIGN_UNIT - 1) /
|
||||
RAD_ALIGN_UNIT * RAD_ALIGN_UNIT;
|
||||
if (layer_max > 0 && b.expert_ceiling > b.experts && cfg.placement == "expert_tiered" &&
|
||||
uneven) {
|
||||
b.stage_per_rank = true;
|
||||
} else if (layer_max > 0 && b.expert_ceiling > b.experts && cfg.placement != "all_vram" &&
|
||||
cfg.placement != "layer_offload") {
|
||||
const int64_t one = stage_buffer(b.expert_ceiling - b.experts, b.expert_ceiling, layer_max);
|
||||
if (b.lends) {
|
||||
/* Expert residency above its host-pool floor pays first, so the cache keeps its
|
||||
* configured coverage; otherwise the cache pays. Either way the region is lent to the
|
||||
@@ -327,21 +368,24 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
* The real limit, that one max-length sequence fits, is checked in configure_kv
|
||||
* (core/engine_bringup.cpp). */
|
||||
if (log && b.kv_ceiling > 0 && cfg.max_ctx > 0)
|
||||
RAD_INFO("kv: the pool backs %.0f%% of the worst case (%lld sequences all at %lld tokens), "
|
||||
"%.1f full-length sessions; a larger --host-pool-mib gives the cache more",
|
||||
100.0 * paged_share(b),
|
||||
(long long)cfg.max_seqs, (long long)cfg.max_ctx,
|
||||
(double)cfg.max_seqs * paged_share(b));
|
||||
RAD_INFO("kv: the pool backs %.0f%% of the worst case (%s), %.1f full-length sessions; a "
|
||||
"larger --host-pool-mib gives the cache more",
|
||||
100.0 * paged_share(b), ceiling_case(cfg).c_str(),
|
||||
ceiling_sessions(cfg) * paged_share(b));
|
||||
/* Rounding the weights up claims up to a MiB the split did not hand out; take it back from
|
||||
* the cache so the headroom stays whole. */
|
||||
cfg.vram_weights_mib = to_mib_up(b.weights);
|
||||
const int64_t w_over = cfg.vram_weights_mib * kMiB - b.weights;
|
||||
cfg.vram_kv_mib = to_mib(std::max<int64_t>(b.kv - w_over, 0));
|
||||
/* A streamed plan's maps are charged in kv_one but reserved outside the paged split, so the MiB
|
||||
* truncation would leave the pool short of the one conversation kv_one was sized for. Under
|
||||
* streaming kv_one is a requirement, so it is rounded up. */
|
||||
if (cfg.kv_streams && kv_one > 0 &&
|
||||
b.kv >= kv_one && cfg.vram_kv_mib * kMiB < kv_one)
|
||||
/* One --max-model-len sequence is a requirement, not a share. kv_one is the least whole MiB
|
||||
* that pages it (KVManager::pool_mib_for_tokens), so the truncation above and the MiB the
|
||||
* weights' round-up takes back leave a pool that holds the floor (b.kv == kv_one: no lender,
|
||||
* or experts that want the whole card) a MiB short of it, and every paged group short of the
|
||||
* context: ERNIE-5.5 at --max-model-len 32768, two sequences and no lender got 317 of its 318
|
||||
* MiB and paged 32640 tokens in its compressed group, 32752 in its latent ones. A streamed
|
||||
* plan's maps are charged in kv_one too. Rounded up, out of the headroom, as the weights' MiB
|
||||
* is. */
|
||||
if (kv_one > 0 && b.kv >= kv_one && cfg.vram_kv_mib * kMiB < kv_one)
|
||||
cfg.vram_kv_mib = to_mib_up(kv_one);
|
||||
/* A cache given its whole ceiling is rounded up to cover it, out of the headroom as the
|
||||
* weights' MiB is: truncated, a ceiling under a MiB would be an empty pool and one just over a
|
||||
@@ -403,23 +447,22 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
? " -- the whole expert plane is resident, so more would do nothing" : "",
|
||||
humanb(b.kv).c_str(), 100.0 * (double)b.kv / ela,
|
||||
(b.kv_ceiling > 0 && b.kv >= b.kv_ceiling)
|
||||
? fmt(" -- backs %lld sequences all at %lld tokens at once, which is the worst case and\n"
|
||||
? fmt(" -- backs %s at once, which is the worst case and\n"
|
||||
" more would be unusable",
|
||||
(long long)cfg.max_seqs, (long long)cfg.max_ctx).c_str()
|
||||
ceiling_case(cfg).c_str()).c_str()
|
||||
: (b.kv_ceiling > 0
|
||||
/* Given as a session count, comparable with --max-num-seqs. Sessions, not
|
||||
* running requests: prefix caching holds a finished sequence's blocks for the
|
||||
* next turn, so multi-turn demand is live sessions. When they do not fit, the
|
||||
* cache evicts prefixes and the next turn re-prefills its whole context
|
||||
* (radiance:prefix_cache_evictions_total). */
|
||||
? fmt(" -- %.0f%% backing of the %lld x %lld worst case: %.1f full-length\n"
|
||||
? fmt(" -- %.0f%% backing of the worst case (%s): %.1f full-length\n"
|
||||
" sessions. With prefix caching a "
|
||||
"finished sequence's blocks stay held\n"
|
||||
" for reuse, so the demand is live "
|
||||
"sessions, not running requests",
|
||||
100.0 * paged_share(b),
|
||||
(long long)cfg.max_seqs, (long long)cfg.max_ctx,
|
||||
(double)cfg.max_seqs * paged_share(b)).c_str()
|
||||
100.0 * paged_share(b), ceiling_case(cfg).c_str(),
|
||||
ceiling_sessions(cfg) * paged_share(b)).c_str()
|
||||
: ""),
|
||||
b.unusable > 0
|
||||
? fmt(" unusable %10s neither side could take it: both are at their "
|
||||
@@ -431,6 +474,11 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
" at the arena's top and lent back to the "
|
||||
"slab while steps are small\n", humanb(b.stage).c_str(),
|
||||
stage_from_experts ? "experts" : "cache").c_str()
|
||||
: b.stage_per_rank
|
||||
? " prefill staging per rank the ranks differ: each sizes its own ring out of "
|
||||
"its own experts\n"
|
||||
" once its pools are final (the `prefill ring:` "
|
||||
"lines)\n"
|
||||
: "",
|
||||
humanb(cfg.vram_weights_mib * kMiB).c_str(), "static + experts",
|
||||
humanb(cfg.vram_kv_mib * kMiB).c_str(), "the cache's share",
|
||||
@@ -493,6 +541,27 @@ RankSplit vram_budget_rank_split(int64_t common_weights_mib, int64_t common_kv_m
|
||||
return s;
|
||||
}
|
||||
|
||||
RankStage vram_budget_rank_stage(int64_t weights_mib, int64_t statics, int64_t experts,
|
||||
int64_t layer_max, int64_t pool_room_mib) {
|
||||
RankStage st;
|
||||
st.weights_mib = weights_mib;
|
||||
if (experts <= 0 || layer_max <= 0) return st;
|
||||
const int64_t on_card = std::max<int64_t>(weights_mib * kMiB - statics, 0);
|
||||
st.off_card = std::max<int64_t>(experts - on_card, 0);
|
||||
if (st.off_card <= 0) return st; /* every expert resident: nothing to stage */
|
||||
const int64_t ring = 2 * stage_buffer(st.off_card, experts, layer_max);
|
||||
/* Whole MiB, rounded up, so the weights pool plus the ring stay within the pool it had. */
|
||||
const int64_t cut = (ring + kMiB - 1) / kMiB;
|
||||
if (cut > pool_room_mib || cut * kMiB >= on_card) {
|
||||
st.no_room = true;
|
||||
return st;
|
||||
}
|
||||
st.stage = ring;
|
||||
st.weights_mib = weights_mib - cut;
|
||||
st.pool_mib = cut;
|
||||
return st;
|
||||
}
|
||||
|
||||
/* What a fleet grants against (docs/MULTIMODEL.md §6.3): the same fixed terms resolve() charges,
|
||||
* plus the floor or the ceiling of the two elastic shares. */
|
||||
void vram_budget_need(const std::vector<VramFacts>& per_rank, int64_t* need, int64_t* want) {
|
||||
@@ -516,4 +585,43 @@ void vram_budget_need(const std::vector<VramFacts>& per_rank, int64_t* need, int
|
||||
*want = fixed + experts + std::max(kv_ceiling, kv_one) + 2 * kMiB;
|
||||
}
|
||||
|
||||
bool vram_budget_host_pool_split(const std::vector<int64_t>& overflow_mib, int64_t total_host_mib,
|
||||
std::vector<int64_t>* out_mib) {
|
||||
if (!out_mib || overflow_mib.size() <= 1 || total_host_mib <= 0) return false;
|
||||
const size_t n = overflow_mib.size();
|
||||
std::vector<int64_t> over(n, 0);
|
||||
int64_t sum = 0;
|
||||
bool same = true;
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
over[i] = std::max<int64_t>(0, overflow_mib[i]);
|
||||
sum += over[i];
|
||||
if (over[i] != over[0]) same = false;
|
||||
}
|
||||
if (same || sum == 0) return false;
|
||||
if (sum <= total_host_mib) {
|
||||
*out_mib = std::move(over);
|
||||
return true;
|
||||
}
|
||||
out_mib->assign(n, 0);
|
||||
int64_t used = 0;
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
const int64_t share = (int64_t)(((__int128)total_host_mib * over[i]) / sum);
|
||||
(*out_mib)[i] = std::min(over[i], share);
|
||||
used += (*out_mib)[i];
|
||||
}
|
||||
int64_t rem = total_host_mib - used;
|
||||
while (rem > 0) {
|
||||
bool progressed = false;
|
||||
for (size_t i = 0; i < n && rem > 0; ++i) {
|
||||
if ((*out_mib)[i] < over[i]) {
|
||||
++(*out_mib)[i];
|
||||
--rem;
|
||||
progressed = true;
|
||||
}
|
||||
}
|
||||
if (!progressed) break;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -123,6 +123,12 @@ struct VramBudget {
|
||||
* top of the activation arena (core/place/stager.h). Zero when every expert is resident or the
|
||||
* placement cannot move any. */
|
||||
int64_t stage = 0;
|
||||
/* An uneven world under expert_tiered (the ranks' expert planes, static weights, cache or
|
||||
* arena differ): the floor above is against an even share of the host pool, which
|
||||
* Engine::plan then re-splits by each rank's overflow, and one rank's ring is not another's
|
||||
* need. The common split sizes no ring (`stage` stays 0) and each rank sizes its own against
|
||||
* its own terms once its pools are final (vram_budget_rank_stage). */
|
||||
bool stage_per_rank = false;
|
||||
int64_t weights = 0; /* statics + experts: what vram_weights is set to */
|
||||
bool unified = false; /* a unified-memory device: one RAM ledger */
|
||||
int64_t host_pinned = 0; /* pinned host pools charged to that ledger */
|
||||
@@ -169,4 +175,30 @@ struct RankSplit {
|
||||
RankSplit vram_budget_rank_split(int64_t common_weights_mib, int64_t common_kv_mib,
|
||||
int64_t need_kv_mib, int64_t weights_cap_bytes);
|
||||
|
||||
/* An uneven world's prefill staging ring for one rank (VramBudget::stage_per_rank), against that
|
||||
* rank's own final weights pool. A rank that holds every expert on the card needs no ring. One
|
||||
* that leaves some off gets two buffers of one layer's share of them (`layer_max` scaled by the
|
||||
* part off the card, each RAD_ALIGN_UNIT-aligned, as the common split sizes it), paid from its
|
||||
* expert residency: the weights pool shrinks by the ring's whole MiB and the experts that held
|
||||
* them join the rank's host-pool overflow. That is allowed only when the host pool has room for
|
||||
* them, `pool_room_mib` being what the model's whole pool has left after every rank's overflow, so
|
||||
* no expert is left without a home. Pure arithmetic, for Engine::plan and the tests. */
|
||||
struct RankStage {
|
||||
int64_t stage = 0; /* ring bytes; 0 when the rank gets none */
|
||||
int64_t weights_mib = 0; /* the rank's weights pool after paying for it */
|
||||
int64_t pool_mib = 0; /* experts moved to the host pool for it (whole MiB) */
|
||||
int64_t off_card = 0; /* expert bytes this rank leaves off the card before the ring */
|
||||
bool no_room = false; /* experts are off the card, but the host pool cannot take more */
|
||||
};
|
||||
RankStage vram_budget_rank_stage(int64_t weights_mib, int64_t statics, int64_t experts,
|
||||
int64_t layer_max, int64_t pool_room_mib);
|
||||
|
||||
/* Split the model's total pinned host pool across ranks in proportion to each rank's VRAM weight
|
||||
* overflow (`overflow_mib`). Returns false (leaving `out_mib` untouched) when ranks have equal
|
||||
* overflow, total overflow is 0, fewer than two ranks exist, or `total_host_mib <= 0`. When total
|
||||
* overflow fits inside `total_host_mib`, each rank gets its overflow (0 for ranks that fit in
|
||||
* VRAM); otherwise `total_host_mib` is divided proportionally with exact sum. */
|
||||
bool vram_budget_host_pool_split(const std::vector<int64_t>& overflow_mib, int64_t total_host_mib,
|
||||
std::vector<int64_t>* out_mib);
|
||||
|
||||
} /* namespace rad */
|
||||
Loaded 100 of 448 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user